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