242cca857ab2bd252760c3f9cfff7ea43a6cee26
[ghc-hetmet.git] / compiler / deSugar / DsBinds.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5
6 Pattern-matching bindings (HsBinds and MonoBinds)
7
8 Handles @HsBinds@; those at the top level require different handling,
9 in that the @Rec@/@NonRec@/etc structure is thrown away (whereas at
10 lower levels it is preserved with @let@/@letrec@s).
11
12 \begin{code}
13 module DsBinds ( dsTopLHsBinds, dsLHsBinds, decomposeRuleLhs, 
14                  dsCoercion,
15                  AutoScc(..)
16   ) where
17
18 #include "HsVersions.h"
19
20 import {-# SOURCE #-}   DsExpr( dsLExpr, dsExpr )
21 import {-# SOURCE #-}   Match( matchWrapper )
22
23 import DsMonad
24 import DsGRHSs
25 import DsUtils
26
27 import HsSyn            -- lots of things
28 import CoreSyn          -- lots of things
29 import CoreUtils
30
31 import TcHsSyn          ( mkArbitraryType )     -- Mis-placed?
32 import TcType
33 import OccurAnal
34 import CostCentre
35 import Module
36 import Id
37 import Var      ( TyVar )
38 import Rules
39 import VarEnv
40 import Type
41 import Outputable
42 import SrcLoc
43 import Maybes
44 import Bag
45 import BasicTypes hiding ( TopLevel )
46 import FastString
47 import Util             ( mapSnd )
48
49 import Control.Monad
50 import Data.List
51 \end{code}
52
53 %************************************************************************
54 %*                                                                      *
55 \subsection[dsMonoBinds]{Desugaring a @MonoBinds@}
56 %*                                                                      *
57 %************************************************************************
58
59 \begin{code}
60 dsTopLHsBinds :: AutoScc -> LHsBinds Id -> DsM [(Id,CoreExpr)]
61 dsTopLHsBinds auto_scc binds = ds_lhs_binds auto_scc binds
62
63 dsLHsBinds :: LHsBinds Id -> DsM [(Id,CoreExpr)]
64 dsLHsBinds binds = ds_lhs_binds NoSccs binds
65
66
67 ------------------------
68 ds_lhs_binds :: AutoScc -> LHsBinds Id -> DsM [(Id,CoreExpr)]
69          -- scc annotation policy (see below)
70 ds_lhs_binds auto_scc binds =  foldM (dsLHsBind auto_scc) [] (bagToList binds)
71
72 dsLHsBind :: AutoScc
73          -> [(Id,CoreExpr)]     -- Put this on the end (avoid quadratic append)
74          -> LHsBind Id
75          -> DsM [(Id,CoreExpr)] -- Result
76 dsLHsBind auto_scc rest (L loc bind)
77   = putSrcSpanDs loc $ dsHsBind auto_scc rest bind
78
79 dsHsBind :: AutoScc
80          -> [(Id,CoreExpr)]     -- Put this on the end (avoid quadratic append)
81          -> HsBind Id
82          -> DsM [(Id,CoreExpr)] -- Result
83
84 dsHsBind auto_scc rest (VarBind var expr)
85   = dsLExpr expr                `thenDs` \ core_expr ->
86
87         -- Dictionary bindings are always VarMonoBinds, so
88         -- we only need do this here
89     addDictScc var core_expr    `thenDs` \ core_expr' ->
90     returnDs ((var, core_expr') : rest)
91
92 dsHsBind auto_scc rest (FunBind { fun_id = L _ fun, fun_matches = matches, fun_co_fn = co_fn, fun_tick = tick })
93   = matchWrapper (FunRhs (idName fun)) matches          `thenDs` \ (args, body) ->
94     mkOptTickBox tick body                              `thenDs` \ body' ->
95     dsCoercion co_fn (return (mkLams args body'))       `thenDs` \ rhs ->
96     returnDs ((fun,rhs) : rest)
97
98 dsHsBind auto_scc rest (PatBind { pat_lhs = pat, pat_rhs = grhss, pat_rhs_ty = ty })
99   = dsGuarded grhss ty                          `thenDs` \ body_expr ->
100     mkSelectorBinds pat body_expr               `thenDs` \ sel_binds ->
101     returnDs (sel_binds ++ rest)
102
103 -- Note [Rules and inlining]
104 -- Common special case: no type or dictionary abstraction
105 -- This is a bit less trivial than you might suppose
106 -- The naive way woudl be to desguar to something like
107 --      f_lcl = ...f_lcl...     -- The "binds" from AbsBinds
108 --      M.f = f_lcl             -- Generated from "exports"
109 -- But we don't want that, because if M.f isn't exported,
110 -- it'll be inlined unconditionally at every call site (its rhs is 
111 -- trivial).  That would be ok unless it has RULES, which would 
112 -- thereby be completely lost.  Bad, bad, bad.
113 --
114 -- Instead we want to generate
115 --      M.f = ...f_lcl...
116 --      f_lcl = M.f
117 -- Now all is cool. The RULES are attached to M.f (by SimplCore), 
118 -- and f_lcl is rapidly inlined away.
119 --
120 -- This does not happen in the same way to polymorphic binds,
121 -- because they desugar to
122 --      M.f = /\a. let f_lcl = ...f_lcl... in f_lcl
123 -- Although I'm a bit worried about whether full laziness might
124 -- float the f_lcl binding out and then inline M.f at its call site
125
126 dsHsBind auto_scc rest (AbsBinds [] [] exports binds)
127   = do  { core_prs <- ds_lhs_binds NoSccs binds
128         ; let env = mkABEnv exports
129               do_one (lcl_id, rhs) | Just (gbl_id, prags) <- lookupVarEnv env lcl_id
130                                    = addInlinePrags prags gbl_id $
131                                      addAutoScc auto_scc gbl_id rhs
132                                    | otherwise = (lcl_id, rhs)
133               locals'  = [(lcl_id, Var gbl_id) | (_, gbl_id, lcl_id, _) <- exports]
134         ; return (map do_one core_prs ++ locals' ++ rest) }
135                 -- No Rec needed here (contrast the other AbsBinds cases)
136                 -- because we can rely on the enclosing dsBind to wrap in Rec
137
138         -- Another common case: one exported variable
139         -- Non-recursive bindings come through this way
140 dsHsBind auto_scc rest
141      (AbsBinds all_tyvars dicts exports@[(tyvars, global, local, prags)] binds)
142   = ASSERT( all (`elem` tyvars) all_tyvars )
143     ds_lhs_binds NoSccs binds   `thenDs` \ core_prs ->
144     let 
145         -- Always treat the binds as recursive, because the typechecker
146         -- makes rather mixed-up dictionary bindings
147         core_bind = Rec core_prs
148     in
149     mappM (dsSpec all_tyvars dicts tyvars global local core_bind) 
150           prags                         `thenDs` \ mb_specs ->
151     let
152         (spec_binds, rules) = unzip (catMaybes mb_specs)
153         global' = addIdSpecialisations global rules
154         rhs'    = mkLams tyvars $ mkLams dicts $ Let core_bind (Var local)
155         bind    = addInlinePrags prags global' $ addAutoScc auto_scc global' rhs'
156     in
157     returnDs (bind  : spec_binds ++ rest)
158
159 dsHsBind auto_scc rest (AbsBinds all_tyvars dicts exports binds)
160   = do  { core_prs <- ds_lhs_binds NoSccs binds
161         ; let env = mkABEnv exports
162               do_one (lcl_id,rhs) | Just (gbl_id, prags) <- lookupVarEnv env lcl_id
163                                   = addInlinePrags prags lcl_id $
164                                     addAutoScc auto_scc gbl_id rhs
165                                   | otherwise = (lcl_id,rhs)
166                
167                 -- Rec because of mixed-up dictionary bindings
168               core_bind = Rec (map do_one core_prs)
169
170               tup_expr      = mkTupleExpr locals
171               tup_ty        = exprType tup_expr
172               poly_tup_expr = mkLams all_tyvars $ mkLams dicts $
173                               Let core_bind tup_expr
174               locals        = [local | (_, _, local, _) <- exports]
175               local_tys     = map idType locals
176
177         ; poly_tup_id <- newSysLocalDs (exprType poly_tup_expr)
178
179         ; let dict_args = map Var dicts
180
181               mk_bind ((tyvars, global, local, prags), n)       -- locals !! n == local
182                 =       -- Need to make fresh locals to bind in the selector, because
183                         -- some of the tyvars will be bound to 'Any'
184                   do { locals' <- newSysLocalsDs (map substitute local_tys)
185                      ; tup_id  <- newSysLocalDs  (substitute tup_ty)
186                      ; mb_specs <- mapM (dsSpec all_tyvars dicts tyvars global local core_bind) 
187                                          prags
188                      ; let (spec_binds, rules) = unzip (catMaybes mb_specs)
189                            global' = addIdSpecialisations global rules
190                            rhs = mkLams tyvars $ mkLams dicts $
191                                  mkTupleSelector locals' (locals' !! n) tup_id $
192                                  mkApps (mkTyApps (Var poly_tup_id) ty_args) dict_args
193                      ; returnDs ((global', rhs) : spec_binds) }
194                 where
195                   mk_ty_arg all_tyvar | all_tyvar `elem` tyvars = mkTyVarTy all_tyvar
196                                       | otherwise               = mkArbitraryType all_tyvar
197                   ty_args    = map mk_ty_arg all_tyvars
198                   substitute = substTyWith all_tyvars ty_args
199
200         ; export_binds_s <- mappM mk_bind (exports `zip` [0..])
201              -- don't scc (auto-)annotate the tuple itself.
202
203         ; returnDs ((poly_tup_id, poly_tup_expr) : 
204                     (concat export_binds_s ++ rest)) }
205
206 mkABEnv :: [([TyVar], Id, Id, [LPrag])] -> VarEnv (Id, [LPrag])
207 -- Takes the exports of a AbsBinds, and returns a mapping
208 --      lcl_id -> (gbl_id, prags)
209 mkABEnv exports = mkVarEnv [ (lcl_id, (gbl_id, prags)) 
210                            | (_, gbl_id, lcl_id, prags) <- exports]
211
212
213 dsSpec :: [TyVar] -> [DictId] -> [TyVar]
214        -> Id -> Id              -- Global, local
215        -> CoreBind -> LPrag
216        -> DsM (Maybe ((Id,CoreExpr),    -- Binding for specialised Id
217                       CoreRule))        -- Rule for the Global Id
218
219 -- Example:
220 --      f :: (Eq a, Ix b) => a -> b -> b
221 --      {-# SPECIALISE f :: Ix b => Int -> b -> b #-}
222 --
223 --      AbsBinds [ab] [d1,d2] [([ab], f, f_mono, prags)] binds
224 -- 
225 --      SpecPrag (/\b.\(d:Ix b). f Int b dInt d) 
226 --               (forall b. Ix b => Int -> b -> b)
227 --
228 -- Rule:        forall b,(d:Ix b). f Int b dInt d = f_spec b d
229 --
230 -- Spec bind:   f_spec = Let f = /\ab \(d1:Eq a)(d2:Ix b). let binds in f_mono 
231 --                       /\b.\(d:Ix b). in f Int b dInt d
232 --              The idea is that f occurs just once, so it'll be 
233 --              inlined and specialised
234 --
235 -- Given SpecPrag (/\as.\ds. f es) t, we have
236 -- the defn             f_spec as ds = f es 
237 -- and the RULE         f es = f_spec as ds
238 --
239 -- It is *possible* that 'es' does not mention all of the dictionaries 'ds'
240 -- (a bit silly, because then the 
241 dsSpec all_tvs dicts tvs poly_id mono_id mono_bind (L _ (InlinePrag {}))
242   = return Nothing
243
244 dsSpec all_tvs dicts tvs poly_id mono_id mono_bind
245        (L loc (SpecPrag spec_expr spec_ty _const_dicts inl))
246         -- See Note [Const rule dicts]
247   = putSrcSpanDs loc $ 
248     do  { let poly_name = idName poly_id
249         ; spec_name <- newLocalName poly_name
250         ; ds_spec_expr  <- dsExpr spec_expr
251         ; let (bndrs, body) = collectBinders (occurAnalyseExpr ds_spec_expr)
252                 -- The occurrence-analysis does two things
253                 -- (a) identifies unused binders: Note [Unused spec binders]
254                 -- (b) sorts dict bindings into NonRecs 
255                 --      so they can be inlined by decomposeRuleLhs
256               mb_lhs = decomposeRuleLhs body
257
258         -- Check for dead binders: Note [Unused spec binders]
259         ; case filter isDeadBinder bndrs of {
260                 bs | not (null bs) -> do { warnDs (dead_msg bs); return Nothing }
261                    | otherwise -> 
262
263           case mb_lhs of
264             Nothing -> do { warnDs decomp_msg; return Nothing }
265
266             Just (var, args) -> return (Just (addInlineInfo inl spec_id spec_rhs, rule))
267                 where
268                   local_poly  = setIdNotExported poly_id
269                         -- Very important to make the 'f' non-exported,
270                         -- else it won't be inlined!
271                   spec_id     = mkLocalId spec_name spec_ty
272                   spec_rhs    = Let (NonRec local_poly poly_f_body) ds_spec_expr
273                   poly_f_body = mkLams (tvs ++ dicts) $
274                                 fix_up (Let mono_bind (Var mono_id))
275
276                   rule =  mkLocalRule (mkFastString ("SPEC " ++ showSDoc (ppr poly_name)))
277                                 AlwaysActive poly_name
278                                 bndrs args
279                                 (mkVarApps (Var spec_id) bndrs)
280         } }
281   where
282         -- Bind to Any any of all_ptvs that aren't 
283         -- relevant for this particular function 
284     fix_up body | null void_tvs = body
285                 | otherwise     = mkTyApps (mkLams void_tvs body) 
286                                            (map mkArbitraryType void_tvs)
287     void_tvs = all_tvs \\ tvs
288
289     dead_msg bs = vcat [ sep [ptext SLIT("Useless constraint") <> plural bs
290                                  <+> ptext SLIT("in specialied type:"),
291                              nest 2 (pprTheta (map get_pred bs))]
292                        , ptext SLIT("SPECIALISE pragma ignored")]
293     get_pred b = ASSERT( isId b ) expectJust "dsSpec" (tcSplitPredTy_maybe (idType b))
294
295     decomp_msg = hang (ptext SLIT("Specialisation too complicated to desugar; ignored"))
296                     2 (ppr spec_expr)
297 \end{code}
298
299 Note [Unused spec binders]
300 ~~~~~~~~~~~~~~~~~~~~~~~~~~
301 Consider
302         f :: a -> a
303         {-# SPECIALISE f :: Eq a => a -> a #-}
304 It's true that this *is* a more specialised type, but the rule
305 we get is something like this:
306         f_spec d = f
307         RULE: f = f_spec d
308 Note that the rule is bogus, becuase it mentions a 'd' that is
309 not bound on the LHS!  But it's a silly specialisation anyway, becuase
310 the constraint is unused.  We could bind 'd' to (error "unused")
311 but it seems better to reject the program because it's almost certainly
312 a mistake.  That's what the isDeadBinder call detects.
313
314 Note [Const rule dicts]
315 ~~~~~~~~~~~~~~~~~~~~~~~
316 A SpecPrag has a field for "constant dicts" in the RULE, but I think
317 it's pretty useless.  See the place where it's generated in TcBinds.
318 TcSimplify will discharge a constraint by binding it to, say, 
319 GHC.Base.$f2 :: Eq Int, withour putting anything in the LIE, so this 
320 dict won't show up in the const-dicts field.  It probably doesn't matter,
321 because the rule will end up being something like
322         f Int GHC.Base.$f2 = ...
323 rather than
324         forall d. f Int d = ...
325 The latter is more general, but in practice I think it won't make any
326 difference.
327
328
329 %************************************************************************
330 %*                                                                      *
331 \subsection{Adding inline pragmas}
332 %*                                                                      *
333 %************************************************************************
334
335 \begin{code}
336 decomposeRuleLhs :: CoreExpr -> Maybe (Id, [CoreExpr])
337 -- Returns Nothing if the LHS isn't of the expected shape
338 decomposeRuleLhs lhs 
339   = go emptyVarEnv (occurAnalyseExpr lhs)       -- Occurrence analysis sorts out the dict
340                                                 -- bindings so we know if they are recursive
341   where
342         -- Substitute dicts in the LHS args, so that there 
343         -- aren't any lets getting in the way
344         -- Note that we substitute the function too; we might have this as
345         -- a LHS:       let f71 = M.f Int in f71
346     go env (Let (NonRec dict rhs) body) 
347         = go (extendVarEnv env dict (simpleSubst env rhs)) body
348     go env body 
349         = case collectArgs (simpleSubst env body) of
350             (Var fn, args) -> Just (fn, args)
351             other          -> Nothing
352
353 simpleSubst :: IdEnv CoreExpr -> CoreExpr -> CoreExpr
354 -- Similar to CoreSubst.substExpr, except that 
355 -- (a) takes no account of capture; dictionary bindings use new names
356 -- (b) can have a GlobalId (imported) in its domain
357 -- (c) Ids only; no types are substituted
358 --
359 -- (b) is the reason we can't use CoreSubst... and it's no longer relevant
360 --      so really we should replace simpleSubst 
361 simpleSubst subst expr
362   = go expr
363   where
364     go (Var v)         = lookupVarEnv subst v `orElse` Var v
365     go (Cast e co)     = Cast (go e) co
366     go (Type ty)       = Type ty
367     go (Lit lit)       = Lit lit
368     go (App fun arg)   = App (go fun) (go arg)
369     go (Note note e)   = Note note (go e)
370     go (Lam bndr body) = Lam bndr (go body)
371     go (Let (NonRec bndr rhs) body) = Let (NonRec bndr (go rhs)) (go body)
372     go (Let (Rec pairs) body)       = Let (Rec (mapSnd go pairs)) (go body)
373     go (Case scrut bndr ty alts)    = Case (go scrut) bndr ty 
374                                            [(c,bs,go r) | (c,bs,r) <- alts]
375
376 addInlinePrags :: [LPrag] -> Id -> CoreExpr -> (Id,CoreExpr)
377 addInlinePrags prags bndr rhs
378   = case [inl | L _ (InlinePrag inl) <- prags] of
379         []      -> (bndr, rhs)
380         (inl:_) -> addInlineInfo inl bndr rhs
381
382 addInlineInfo :: InlineSpec -> Id -> CoreExpr -> (Id,CoreExpr)
383 addInlineInfo (Inline phase is_inline) bndr rhs
384   = (attach_phase bndr phase, wrap_inline is_inline rhs)
385   where
386     attach_phase bndr phase 
387         | isAlwaysActive phase = bndr   -- Default phase
388         | otherwise            = bndr `setInlinePragma` phase
389
390     wrap_inline True  body = mkInlineMe body
391     wrap_inline False body = body
392 \end{code}
393
394
395 %************************************************************************
396 %*                                                                      *
397 \subsection[addAutoScc]{Adding automatic sccs}
398 %*                                                                      *
399 %************************************************************************
400
401 \begin{code}
402 data AutoScc = NoSccs 
403              | AddSccs Module (Id -> Bool)
404 -- The (Id->Bool) says which Ids to add SCCs to 
405
406 addAutoScc :: AutoScc   
407            -> Id        -- Binder
408            -> CoreExpr  -- Rhs
409            -> CoreExpr  -- Scc'd Rhs
410
411 addAutoScc NoSccs _ rhs
412   = rhs
413 addAutoScc (AddSccs mod add_scc) id rhs
414   | add_scc id = mkSCC (mkAutoCC id mod NotCafCC) rhs
415   | otherwise  = rhs
416 \end{code}
417
418 If profiling and dealing with a dict binding,
419 wrap the dict in @_scc_ DICT <dict>@:
420
421 \begin{code}
422 addDictScc var rhs = returnDs rhs
423
424 {- DISABLED for now (need to somehow make up a name for the scc) -- SDM
425   | not ( opt_SccProfilingOn && opt_AutoSccsOnDicts)
426     || not (isDictId var)
427   = returnDs rhs                                -- That's easy: do nothing
428
429   | otherwise
430   = getModuleAndGroupDs         `thenDs` \ (mod, grp) ->
431         -- ToDo: do -dicts-all flag (mark dict things with individual CCs)
432     returnDs (Note (SCC (mkAllDictsCC mod grp False)) rhs)
433 -}
434 \end{code}
435
436
437 %************************************************************************
438 %*                                                                      *
439                 Desugaring coercions
440 %*                                                                      *
441 %************************************************************************
442
443
444 \begin{code}
445 dsCoercion :: HsWrapper -> DsM CoreExpr -> DsM CoreExpr
446 dsCoercion WpHole            thing_inside = thing_inside
447 dsCoercion (WpCompose c1 c2) thing_inside = dsCoercion c1 (dsCoercion c2 thing_inside)
448 dsCoercion (WpCo co)     thing_inside = do { expr <- thing_inside
449                                                ; return (Cast expr co) }
450 dsCoercion (WpLam id)        thing_inside = do { expr <- thing_inside
451                                                ; return (Lam id expr) }
452 dsCoercion (WpTyLam tv)      thing_inside = do { expr <- thing_inside
453                                                ; return (Lam tv expr) }
454 dsCoercion (WpApp id)        thing_inside = do { expr <- thing_inside
455                                                ; return (App expr (Var id)) }
456 dsCoercion (WpTyApp ty)      thing_inside = do { expr <- thing_inside
457                                                ; return (App expr (Type ty)) }
458 dsCoercion (WpLet bs)        thing_inside = do { prs <- dsLHsBinds bs
459                                                ; expr <- thing_inside
460                                                ; return (Let (Rec prs) expr) }
461 \end{code}