2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[DsBinds]{Pattern-matching bindings (HsBinds and MonoBinds)}
6 Handles @HsBinds@; those at the top level require different handling,
7 in that the @Rec@/@NonRec@/etc structure is thrown away (whereas at
8 lower levels it is preserved with @let@/@letrec@s).
11 module DsBinds ( dsTopLHsBinds, dsLHsBinds, decomposeRuleLhs,
16 #include "HsVersions.h"
19 import {-# SOURCE #-} DsExpr( dsLExpr, dsExpr )
20 import {-# SOURCE #-} Match( matchWrapper )
23 import DsGRHSs ( dsGuarded )
26 import HsSyn -- lots of things
27 import CoreSyn -- lots of things
28 import CoreUtils ( exprType, mkInlineMe, mkSCC )
30 import StaticFlags ( opt_AutoSccsOnAllToplevs,
31 opt_AutoSccsOnExportedToplevs )
32 import OccurAnal ( occurAnalyseExpr )
33 import CostCentre ( mkAutoCC, IsCafCC(..) )
34 import Id ( Id, DictId, idType, idName, isExportedId, mkLocalId, setInlinePragma )
35 import Rules ( addIdSpecialisations, mkLocalRule )
36 import Var ( TyVar, Var, isGlobalId, setIdNotExported )
38 import Type ( mkTyVarTy, substTyWith )
39 import TysWiredIn ( voidTy )
41 import SrcLoc ( Located(..) )
42 import Maybes ( isJust, catMaybes, orElse )
43 import Bag ( bagToList )
44 import BasicTypes ( Activation(..), InlineSpec(..), isAlwaysActive )
45 import Monad ( foldM )
46 import FastString ( mkFastString )
48 import Util ( mapSnd )
51 %************************************************************************
53 \subsection[dsMonoBinds]{Desugaring a @MonoBinds@}
55 %************************************************************************
58 dsTopLHsBinds :: AutoScc -> LHsBinds Id -> DsM [(Id,CoreExpr)]
59 dsTopLHsBinds auto_scc binds = ds_lhs_binds auto_scc binds
61 dsLHsBinds :: LHsBinds Id -> DsM [(Id,CoreExpr)]
62 dsLHsBinds binds = ds_lhs_binds NoSccs binds
65 ------------------------
66 ds_lhs_binds :: AutoScc -> LHsBinds Id -> DsM [(Id,CoreExpr)]
67 -- scc annotation policy (see below)
68 ds_lhs_binds auto_scc binds = foldM (dsLHsBind auto_scc) [] (bagToList binds)
71 -> [(Id,CoreExpr)] -- Put this on the end (avoid quadratic append)
73 -> DsM [(Id,CoreExpr)] -- Result
74 dsLHsBind auto_scc rest (L loc bind)
75 = putSrcSpanDs loc $ dsHsBind auto_scc rest bind
78 -> [(Id,CoreExpr)] -- Put this on the end (avoid quadratic append)
80 -> DsM [(Id,CoreExpr)] -- Result
82 dsHsBind auto_scc rest (VarBind var expr)
83 = dsLExpr expr `thenDs` \ core_expr ->
85 -- Dictionary bindings are always VarMonoBinds, so
86 -- we only need do this here
87 addDictScc var core_expr `thenDs` \ core_expr' ->
88 returnDs ((var, core_expr') : rest)
90 dsHsBind auto_scc rest (FunBind { fun_id = L _ fun, fun_matches = matches, fun_co_fn = co_fn })
91 = matchWrapper (FunRhs (idName fun)) matches `thenDs` \ (args, body) ->
92 dsCoercion co_fn (return (mkLams args body)) `thenDs` \ rhs ->
93 addAutoScc auto_scc (fun, rhs) `thenDs` \ pair ->
94 returnDs (pair : rest)
96 dsHsBind auto_scc rest (PatBind { pat_lhs = pat, pat_rhs = grhss, pat_rhs_ty = ty })
97 = dsGuarded grhss ty `thenDs` \ body_expr ->
98 mkSelectorBinds pat body_expr `thenDs` \ sel_binds ->
99 mappM (addAutoScc auto_scc) sel_binds `thenDs` \ sel_binds ->
100 returnDs (sel_binds ++ rest)
102 -- Note [Rules and inlining]
103 -- Common special case: no type or dictionary abstraction
104 -- This is a bit less trivial than you might suppose
105 -- The naive way woudl be to desguar to something like
106 -- f_lcl = ...f_lcl... -- The "binds" from AbsBinds
107 -- M.f = f_lcl -- Generated from "exports"
108 -- But we don't want that, because if M.f isn't exported,
109 -- it'll be inlined unconditionally at every call site (its rhs is
110 -- trivial). That woudl be ok unless it has RULES, which would
111 -- thereby be completely lost. Bad, bad, bad.
113 -- Instead we want to generate
116 -- Now all is cool. The RULES are attached to M.f (by SimplCore),
117 -- and f_lcl is rapidly inlined away.
119 -- This does not happen in the same way to polymorphic binds,
120 -- because they desugar to
121 -- M.f = /\a. let f_lcl = ...f_lcl... in f_lcl
122 -- Although I'm a bit worried about whether full laziness might
123 -- float the f_lcl binding out and then inline M.f at its call site
125 dsHsBind auto_scc rest (AbsBinds [] [] exports binds)
126 = do { core_prs <- ds_lhs_binds (addSccs auto_scc exports) binds
127 ; let env = mkVarEnv [ (lcl_id, (gbl_id, prags))
128 | (_, gbl_id, lcl_id, prags) <- exports]
129 do_one (lcl_id, rhs) | Just (gbl_id, prags) <- lookupVarEnv env lcl_id
130 = addInlinePrags prags gbl_id rhs
131 | otherwise = (lcl_id, rhs)
132 locals' = [(lcl_id, Var gbl_id) | (_, gbl_id, lcl_id, _) <- exports]
133 ; return (map do_one core_prs ++ locals' ++ rest) }
134 -- No Rec needed here (contrast the other AbsBinds cases)
135 -- because we can rely on the enclosing dsBind to wrap in Rec
137 -- Another common case: one exported variable
138 -- Non-recursive bindings come through this way
139 dsHsBind auto_scc rest
140 (AbsBinds all_tyvars dicts exports@[(tyvars, global, local, prags)] binds)
141 = ASSERT( all (`elem` tyvars) all_tyvars )
142 ds_lhs_binds (addSccs auto_scc exports) binds `thenDs` \ core_prs ->
144 -- Always treat the binds as recursive, because the typechecker
145 -- makes rather mixed-up dictionary bindings
146 core_bind = Rec core_prs
148 mappM (dsSpec all_tyvars dicts tyvars global local core_bind)
149 prags `thenDs` \ mb_specs ->
151 (spec_binds, rules) = unzip (catMaybes mb_specs)
152 global' = addIdSpecialisations global rules
153 rhs' = mkLams tyvars $ mkLams dicts $ Let core_bind (Var local)
155 returnDs (addInlinePrags prags global' rhs' : spec_binds ++ rest)
157 dsHsBind auto_scc rest (AbsBinds all_tyvars dicts exports binds)
158 = ds_lhs_binds (addSccs auto_scc exports) binds `thenDs` \ core_prs ->
160 add_inline (bndr,rhs) | Just prags <- lookupVarEnv inline_env bndr
161 = addInlinePrags prags bndr rhs
162 | otherwise = (bndr,rhs)
163 inline_env = mkVarEnv [(lcl_id, prags) | (_, _, lcl_id, prags) <- exports]
165 -- Rec because of mixed-up dictionary bindings
166 core_bind = Rec (map add_inline core_prs)
168 tup_expr = mkTupleExpr locals
169 tup_ty = exprType tup_expr
170 poly_tup_expr = mkLams all_tyvars $ mkLams dicts $
171 Let core_bind tup_expr
172 locals = [local | (_, _, local, _) <- exports]
173 local_tys = map idType locals
175 newSysLocalDs (exprType poly_tup_expr) `thenDs` \ poly_tup_id ->
177 dict_args = map Var dicts
179 mk_bind ((tyvars, global, local, prags), n) -- locals !! n == local
180 = -- Need to make fresh locals to bind in the selector, because
181 -- some of the tyvars will be bound to voidTy
182 newSysLocalsDs (map substitute local_tys) `thenDs` \ locals' ->
183 newSysLocalDs (substitute tup_ty) `thenDs` \ tup_id ->
184 mapM (dsSpec all_tyvars dicts tyvars global local core_bind)
185 prags `thenDs` \ mb_specs ->
187 (spec_binds, rules) = unzip (catMaybes mb_specs)
188 global' = addIdSpecialisations global rules
189 rhs = mkLams tyvars $ mkLams dicts $
190 mkTupleSelector locals' (locals' !! n) tup_id $
191 mkApps (mkTyApps (Var poly_tup_id) ty_args) dict_args
193 returnDs ((global', rhs) : spec_binds)
195 mk_ty_arg all_tyvar | all_tyvar `elem` tyvars = mkTyVarTy all_tyvar
197 ty_args = map mk_ty_arg all_tyvars
198 substitute = substTyWith all_tyvars ty_args
200 mappM mk_bind (exports `zip` [0..]) `thenDs` \ export_binds_s ->
201 -- don't scc (auto-)annotate the tuple itself.
203 returnDs ((poly_tup_id, poly_tup_expr) : (concat export_binds_s ++ rest))
205 dsSpec :: [TyVar] -> [DictId] -> [TyVar]
206 -> Id -> Id -- Global, local
208 -> DsM (Maybe ((Id,CoreExpr), -- Binding for specialised Id
209 CoreRule)) -- Rule for the Global Id
212 -- f :: (Eq a, Ix b) => a -> b -> b
213 -- {-# SPECIALISE f :: Ix b => Int -> b -> b #-}
215 -- AbsBinds [ab] [d1,d2] [([ab], f, f_mono, prags)] binds
217 -- SpecPrag (/\b.\(d:Ix b). f Int b dInt d)
218 -- (forall b. Ix b => Int -> b -> b)
220 -- Rule: forall b,(d:Ix b). f Int b dInt d = f_spec b d
222 -- Spec bind: f_spec = Let f = /\ab \(d1:Eq a)(d2:Ix b). let binds in f_mono
223 -- /\b.\(d:Ix b). in f Int b dInt d
224 -- The idea is that f occurs just once, so it'll be
225 -- inlined and specialised
227 dsSpec all_tvs dicts tvs poly_id mono_id mono_bind (InlinePrag {})
230 dsSpec all_tvs dicts tvs poly_id mono_id mono_bind
231 (SpecPrag spec_expr spec_ty const_dicts inl)
232 = do { let poly_name = idName poly_id
233 ; spec_name <- newLocalName poly_name
234 ; ds_spec_expr <- dsExpr spec_expr
235 ; let (bndrs, body) = collectBinders ds_spec_expr
236 mb_lhs = decomposeRuleLhs (bndrs ++ const_dicts) body
239 Nothing -> do { warnDs msg; return Nothing }
241 Just (bndrs', var, args) -> return (Just (addInlineInfo inl spec_id spec_rhs, rule))
243 local_poly = setIdNotExported poly_id
244 -- Very important to make the 'f' non-exported,
245 -- else it won't be inlined!
246 spec_id = mkLocalId spec_name spec_ty
247 spec_rhs = Let (NonRec local_poly poly_f_body) ds_spec_expr
248 poly_f_body = mkLams (tvs ++ dicts) $
249 fix_up (Let mono_bind (Var mono_id))
251 -- Quantify over constant dicts on the LHS, since
252 -- their value depends only on their type
253 -- The ones we are interested in may even be imported
254 -- e.g. GHC.Base.dEqInt
256 rule = mkLocalRule (mkFastString ("SPEC " ++ showSDoc (ppr poly_name)))
257 AlwaysActive poly_name
258 bndrs' -- Includes constant dicts
260 (mkVarApps (Var spec_id) bndrs)
263 -- Bind to voidTy any of all_ptvs that aren't
264 -- relevant for this particular function
265 fix_up body | null void_tvs = body
266 | otherwise = mkTyApps (mkLams void_tvs body)
267 (map (const voidTy) void_tvs)
268 void_tvs = all_tvs \\ tvs
270 msg = hang (ptext SLIT("Specialisation too complicated to desugar; ignored"))
275 %************************************************************************
277 \subsection{Adding inline pragmas}
279 %************************************************************************
282 decomposeRuleLhs :: [Var] -> CoreExpr -> Maybe ([Var], Id, [CoreExpr])
283 -- Returns Nothing if the LHS isn't of the expected shape
284 -- The argument 'all_bndrs' includes the "constant dicts" of the LHS,
285 -- and they may be GlobalIds, which we can't forall-ify.
286 -- So we substitute them out instead
287 decomposeRuleLhs all_bndrs lhs
288 = go init_env (occurAnalyseExpr lhs) -- Occurrence analysis sorts out the dict
289 -- bindings so we know if they are recursive
292 -- all_bndrs may include top-level imported dicts,
293 -- imported things with a for-all.
294 -- So we localise them and subtitute them out
295 bndr_prs = [ (id, Var (localise id)) | id <- all_bndrs, isGlobalId id ]
296 localise d = mkLocalId (idName d) (idType d)
298 init_env = mkVarEnv bndr_prs
299 all_bndrs' = map subst_bndr all_bndrs
300 subst_bndr bndr = case lookupVarEnv init_env bndr of
301 Just (Var bndr') -> bndr'
302 Just other -> panic "decomposeRuleLhs"
305 -- Substitute dicts in the LHS args, so that there
306 -- aren't any lets getting in the way
307 -- Note that we substitute the function too; we might have this as
308 -- a LHS: let f71 = M.f Int in f71
309 go env (Let (NonRec dict rhs) body)
310 = go (extendVarEnv env dict (simpleSubst env rhs)) body
312 = case collectArgs (simpleSubst env body) of
313 (Var fn, args) -> Just (all_bndrs', fn, args)
316 simpleSubst :: IdEnv CoreExpr -> CoreExpr -> CoreExpr
317 -- Similar to CoreSubst.substExpr, except that
318 -- (a) takes no account of capture; dictionary bindings use new names
319 -- (b) can have a GlobalId (imported) in its domain
320 -- (c) Ids only; no types are substituted
322 simpleSubst subst expr
325 go (Var v) = lookupVarEnv subst v `orElse` Var v
326 go (Cast e co) = Cast (go e) co
327 go (Type ty) = Type ty
328 go (Lit lit) = Lit lit
329 go (App fun arg) = App (go fun) (go arg)
330 go (Note note e) = Note note (go e)
331 go (Lam bndr body) = Lam bndr (go body)
332 go (Let (NonRec bndr rhs) body) = Let (NonRec bndr (go rhs)) (go body)
333 go (Let (Rec pairs) body) = Let (Rec (mapSnd go pairs)) (go body)
334 go (Case scrut bndr ty alts) = Case (go scrut) bndr ty
335 [(c,bs,go r) | (c,bs,r) <- alts]
337 addInlinePrags :: [Prag] -> Id -> CoreExpr -> (Id,CoreExpr)
338 addInlinePrags prags bndr rhs
339 = case [inl | InlinePrag inl <- prags] of
341 (inl:_) -> addInlineInfo inl bndr rhs
343 addInlineInfo :: InlineSpec -> Id -> CoreExpr -> (Id,CoreExpr)
344 addInlineInfo (Inline phase is_inline) bndr rhs
345 = (attach_phase bndr phase, wrap_inline is_inline rhs)
347 attach_phase bndr phase
348 | isAlwaysActive phase = bndr -- Default phase
349 | otherwise = bndr `setInlinePragma` phase
351 wrap_inline True body = mkInlineMe body
352 wrap_inline False body = body
356 %************************************************************************
358 \subsection[addAutoScc]{Adding automatic sccs}
360 %************************************************************************
365 | TopLevelAddSccs (Id -> Maybe Id)
368 addSccs :: AutoScc -> [(a,Id,Id,[Prag])] -> AutoScc
369 addSccs auto_scc@(TopLevelAddSccs _) exports = auto_scc
370 addSccs NoSccs exports = NoSccs
371 addSccs TopLevel exports
372 = TopLevelAddSccs (\id -> case [ exp | (_,exp,loc,_) <- exports, loc == id ] of
373 (exp:_) | opt_AutoSccsOnAllToplevs ||
375 opt_AutoSccsOnExportedToplevs)
379 addAutoScc :: AutoScc -- if needs be, decorate toplevs?
381 -> DsM (Id, CoreExpr)
383 addAutoScc (TopLevelAddSccs auto_scc_fn) pair@(bndr, core_expr)
385 = getModuleDs `thenDs` \ mod ->
386 returnDs (bndr, mkSCC (mkAutoCC top_bndr mod NotCafCC) core_expr)
387 where do_auto_scc = isJust maybe_auto_scc
388 maybe_auto_scc = auto_scc_fn bndr
389 (Just top_bndr) = maybe_auto_scc
395 If profiling and dealing with a dict binding,
396 wrap the dict in @_scc_ DICT <dict>@:
399 addDictScc var rhs = returnDs rhs
401 {- DISABLED for now (need to somehow make up a name for the scc) -- SDM
402 | not ( opt_SccProfilingOn && opt_AutoSccsOnDicts)
403 || not (isDictId var)
404 = returnDs rhs -- That's easy: do nothing
407 = getModuleAndGroupDs `thenDs` \ (mod, grp) ->
408 -- ToDo: do -dicts-all flag (mark dict things with individual CCs)
409 returnDs (Note (SCC (mkAllDictsCC mod grp False)) rhs)
414 %************************************************************************
418 %************************************************************************
422 dsCoercion :: ExprCoFn -> DsM CoreExpr -> DsM CoreExpr
423 dsCoercion CoHole thing_inside = thing_inside
424 dsCoercion (CoCompose c1 c2) thing_inside = dsCoercion c1 (dsCoercion c2 thing_inside)
425 dsCoercion (ExprCoFn co) thing_inside = do { expr <- thing_inside
426 ; return (Cast expr co) }
427 dsCoercion (CoLams ids) thing_inside = do { expr <- thing_inside
428 ; return (mkLams ids expr) }
429 dsCoercion (CoTyLams tvs) thing_inside = do { expr <- thing_inside
430 ; return (mkLams tvs expr) }
431 dsCoercion (CoApps ids) thing_inside = do { expr <- thing_inside
432 ; return (mkVarApps expr ids) }
433 dsCoercion (CoTyApps tys) thing_inside = do { expr <- thing_inside
434 ; return (mkTyApps expr tys) }
435 dsCoercion (CoLet bs) thing_inside = do { prs <- dsLHsBinds bs
436 ; expr <- thing_inside
437 ; return (Let (Rec prs) expr) }