2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 Pattern-matching bindings (HsBinds and MonoBinds)
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).
13 module DsBinds ( dsTopLHsBinds, dsLHsBinds, decomposeRuleLhs,
18 #include "HsVersions.h"
20 import {-# SOURCE #-} DsExpr( dsLExpr, dsExpr )
21 import {-# SOURCE #-} Match( matchWrapper )
28 import HsSyn -- lots of things
29 import CoreSyn -- lots of things
32 import TcHsSyn ( mkArbitraryType ) -- Mis-placed?
38 import Var ( TyVar, Var )
46 import BasicTypes hiding ( TopLevel )
48 import Util ( mapSnd )
58 %************************************************************************
60 \subsection[dsMonoBinds]{Desugaring a @MonoBinds@}
62 %************************************************************************
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
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
82 dsLHsBinds :: LHsBinds Id -> DsM [(Id,CoreExpr)]
83 dsLHsBinds binds = ds_lhs_binds NoSccs binds
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)
92 -> [(Id,CoreExpr)] -- Put this on the end (avoid quadratic append)
94 -> DsM [(Id,CoreExpr)] -- Result
95 dsLHsBind auto_scc rest (L loc bind)
96 = putSrcSpanDs loc $ dsHsBind auto_scc rest bind
99 -> [(Id,CoreExpr)] -- Put this on the end (avoid quadratic append)
101 -> DsM [(Id,CoreExpr)] -- Result
103 dsHsBind auto_scc rest (VarBind var expr)
104 = dsLExpr expr `thenDs` \ core_expr ->
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)
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)
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)
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.
133 -- Instead we want to generate
136 -- Now all is cool. The RULES are attached to M.f (by SimplCore),
137 -- and f_lcl is rapidly inlined away.
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
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
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 ->
164 -- Always treat the binds as recursive, because the typechecker
165 -- makes rather mixed-up dictionary bindings
166 core_bind = Rec core_prs
168 mappM (dsSpec all_tyvars dicts tyvars global local core_bind)
169 prags `thenDs` \ mb_specs ->
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'
176 returnDs (bind : spec_binds ++ rest)
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)
186 -- Rec because of mixed-up dictionary bindings
187 core_bind = Rec (map do_one core_prs)
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
196 ; poly_tup_id <- newSysLocalDs (exprType poly_tup_expr)
198 ; let dict_args = map Var dicts
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)
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) }
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
219 ; export_binds_s <- mappM mk_bind (exports `zip` [0..])
220 -- don't scc (auto-)annotate the tuple itself.
222 ; returnDs ((poly_tup_id, poly_tup_expr) :
223 (concat export_binds_s ++ rest)) }
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]
232 dsSpec :: [TyVar] -> [DictId] -> [TyVar]
233 -> Id -> Id -- Global, local
235 -> DsM (Maybe ((Id,CoreExpr), -- Binding for specialised Id
236 CoreRule)) -- Rule for the Global Id
239 -- f :: (Eq a, Ix b) => a -> b -> b
240 -- {-# SPECIALISE f :: Ix b => Int -> b -> b #-}
242 -- AbsBinds [ab] [d1,d2] [([ab], f, f_mono, prags)] binds
244 -- SpecPrag (/\b.\(d:Ix b). f Int b dInt d)
245 -- (forall b. Ix b => Int -> b -> b)
247 -- Rule: forall b,(d:Ix b). f Int b dInt d = f_spec b d
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
254 dsSpec all_tvs dicts tvs poly_id mono_id mono_bind (InlinePrag {})
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
266 Nothing -> do { warnDs msg; return Nothing }
268 Just (bndrs', var, args) -> return (Just (addInlineInfo inl spec_id spec_rhs, rule))
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))
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
283 rule = mkLocalRule (mkFastString ("SPEC " ++ showSDoc (ppr poly_name)))
284 AlwaysActive poly_name
285 bndrs' -- Includes constant dicts
287 (mkVarApps (Var spec_id) bndrs)
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
297 msg = hang (ptext SLIT("Specialisation too complicated to desugar; ignored"))
302 %************************************************************************
304 \subsection{Adding inline pragmas}
306 %************************************************************************
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
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)
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"
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
339 = case collectArgs (simpleSubst env body) of
340 (Var fn, args) -> Just (all_bndrs', fn, args)
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
349 simpleSubst subst expr
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]
364 addInlinePrags :: [Prag] -> Id -> CoreExpr -> (Id,CoreExpr)
365 addInlinePrags prags bndr rhs
366 = case [inl | InlinePrag inl <- prags] of
368 (inl:_) -> addInlineInfo inl bndr rhs
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)
374 attach_phase bndr phase
375 | isAlwaysActive phase = bndr -- Default phase
376 | otherwise = bndr `setInlinePragma` phase
378 wrap_inline True body = mkInlineMe body
379 wrap_inline False body = body
383 %************************************************************************
385 \subsection[addAutoScc]{Adding automatic sccs}
387 %************************************************************************
390 data AutoScc = NoSccs
391 | AddSccs Module (Id -> Bool)
392 -- The (Id->Bool) says which Ids to add SCCs to
394 addAutoScc :: AutoScc
397 -> CoreExpr -- Scc'd Rhs
399 addAutoScc NoSccs _ rhs
401 addAutoScc (AddSccs mod add_scc) id rhs
402 | add_scc id = mkSCC (mkAutoCC id mod NotCafCC) rhs
406 If profiling and dealing with a dict binding,
407 wrap the dict in @_scc_ DICT <dict>@:
410 addDictScc var rhs = returnDs rhs
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
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)
425 %************************************************************************
429 %************************************************************************
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) }