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