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 )
27 import HsSyn -- lots of things
28 import CoreSyn -- lots of things
36 import Var ( TyVar, Var )
44 import BasicTypes hiding ( TopLevel )
46 import Util ( mapSnd )
52 %************************************************************************
54 \subsection[dsMonoBinds]{Desugaring a @MonoBinds@}
56 %************************************************************************
59 dsTopLHsBinds :: AutoScc -> LHsBinds Id -> DsM [(Id,CoreExpr)]
60 dsTopLHsBinds auto_scc binds = ds_lhs_binds auto_scc binds
62 dsLHsBinds :: LHsBinds Id -> DsM [(Id,CoreExpr)]
63 dsLHsBinds binds = ds_lhs_binds NoSccs binds
66 ------------------------
67 ds_lhs_binds :: AutoScc -> LHsBinds Id -> DsM [(Id,CoreExpr)]
68 -- scc annotation policy (see below)
69 ds_lhs_binds auto_scc binds = foldM (dsLHsBind auto_scc) [] (bagToList binds)
72 -> [(Id,CoreExpr)] -- Put this on the end (avoid quadratic append)
74 -> DsM [(Id,CoreExpr)] -- Result
75 dsLHsBind auto_scc rest (L loc bind)
76 = putSrcSpanDs loc $ dsHsBind auto_scc rest bind
79 -> [(Id,CoreExpr)] -- Put this on the end (avoid quadratic append)
81 -> DsM [(Id,CoreExpr)] -- Result
83 dsHsBind auto_scc rest (VarBind var expr)
84 = dsLExpr expr `thenDs` \ core_expr ->
86 -- Dictionary bindings are always VarMonoBinds, so
87 -- we only need do this here
88 addDictScc var core_expr `thenDs` \ core_expr' ->
89 returnDs ((var, core_expr') : rest)
91 dsHsBind auto_scc rest (FunBind { fun_id = L _ fun, fun_matches = matches, fun_co_fn = co_fn })
92 = matchWrapper (FunRhs (idName fun)) matches `thenDs` \ (args, body) ->
93 dsCoercion co_fn (return (mkLams args body)) `thenDs` \ rhs ->
94 returnDs ((fun,rhs) : 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 returnDs (sel_binds ++ rest)
101 -- Note [Rules and inlining]
102 -- Common special case: no type or dictionary abstraction
103 -- This is a bit less trivial than you might suppose
104 -- The naive way woudl be to desguar to something like
105 -- f_lcl = ...f_lcl... -- The "binds" from AbsBinds
106 -- M.f = f_lcl -- Generated from "exports"
107 -- But we don't want that, because if M.f isn't exported,
108 -- it'll be inlined unconditionally at every call site (its rhs is
109 -- trivial). That would be ok unless it has RULES, which would
110 -- thereby be completely lost. Bad, bad, bad.
112 -- Instead we want to generate
115 -- Now all is cool. The RULES are attached to M.f (by SimplCore),
116 -- and f_lcl is rapidly inlined away.
118 -- This does not happen in the same way to polymorphic binds,
119 -- because they desugar to
120 -- M.f = /\a. let f_lcl = ...f_lcl... in f_lcl
121 -- Although I'm a bit worried about whether full laziness might
122 -- float the f_lcl binding out and then inline M.f at its call site
124 dsHsBind auto_scc rest (AbsBinds [] [] exports binds)
125 = do { core_prs <- ds_lhs_binds NoSccs binds
126 ; let env = mkABEnv exports
127 do_one (lcl_id, rhs) | Just (gbl_id, prags) <- lookupVarEnv env lcl_id
128 = addInlinePrags prags gbl_id $
129 addAutoScc auto_scc gbl_id rhs
130 | otherwise = (lcl_id, rhs)
131 locals' = [(lcl_id, Var gbl_id) | (_, gbl_id, lcl_id, _) <- exports]
132 ; return (map do_one core_prs ++ locals' ++ rest) }
133 -- No Rec needed here (contrast the other AbsBinds cases)
134 -- because we can rely on the enclosing dsBind to wrap in Rec
136 -- Another common case: one exported variable
137 -- Non-recursive bindings come through this way
138 dsHsBind auto_scc rest
139 (AbsBinds all_tyvars dicts exports@[(tyvars, global, local, prags)] binds)
140 = ASSERT( all (`elem` tyvars) all_tyvars )
141 ds_lhs_binds NoSccs binds `thenDs` \ core_prs ->
143 -- Always treat the binds as recursive, because the typechecker
144 -- makes rather mixed-up dictionary bindings
145 core_bind = Rec core_prs
147 mappM (dsSpec all_tyvars dicts tyvars global local core_bind)
148 prags `thenDs` \ mb_specs ->
150 (spec_binds, rules) = unzip (catMaybes mb_specs)
151 global' = addIdSpecialisations global rules
152 rhs' = mkLams tyvars $ mkLams dicts $ Let core_bind (Var local)
153 bind = addInlinePrags prags global' $ addAutoScc auto_scc global' rhs'
155 returnDs (bind : spec_binds ++ rest)
157 dsHsBind auto_scc rest (AbsBinds all_tyvars dicts exports binds)
158 = do { core_prs <- ds_lhs_binds NoSccs binds
159 ; let env = mkABEnv exports
160 do_one (lcl_id,rhs) | Just (gbl_id, prags) <- lookupVarEnv env lcl_id
161 = addInlinePrags prags lcl_id $
162 addAutoScc auto_scc gbl_id rhs
163 | otherwise = (lcl_id,rhs)
165 -- Rec because of mixed-up dictionary bindings
166 core_bind = Rec (map do_one 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 ; poly_tup_id <- newSysLocalDs (exprType poly_tup_expr)
177 ; let 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 do { locals' <- newSysLocalsDs (map substitute local_tys)
183 ; tup_id <- newSysLocalDs (substitute tup_ty)
184 ; mb_specs <- mapM (dsSpec all_tyvars dicts tyvars global local core_bind)
186 ; let (spec_binds, rules) = unzip (catMaybes mb_specs)
187 global' = addIdSpecialisations global rules
188 rhs = mkLams tyvars $ mkLams dicts $
189 mkTupleSelector locals' (locals' !! n) tup_id $
190 mkApps (mkTyApps (Var poly_tup_id) ty_args) dict_args
191 ; returnDs ((global', rhs) : spec_binds) }
193 mk_ty_arg all_tyvar | all_tyvar `elem` tyvars = mkTyVarTy all_tyvar
195 ty_args = map mk_ty_arg all_tyvars
196 substitute = substTyWith all_tyvars ty_args
198 ; export_binds_s <- mappM mk_bind (exports `zip` [0..])
199 -- don't scc (auto-)annotate the tuple itself.
201 ; returnDs ((poly_tup_id, poly_tup_expr) :
202 (concat export_binds_s ++ rest)) }
204 mkABEnv :: [([TyVar], Id, Id, [Prag])] -> VarEnv (Id, [Prag])
205 -- Takes the exports of a AbsBinds, and returns a mapping
206 -- lcl_id -> (gbl_id, prags)
207 mkABEnv exports = mkVarEnv [ (lcl_id, (gbl_id, prags))
208 | (_, gbl_id, lcl_id, prags) <- exports]
211 dsSpec :: [TyVar] -> [DictId] -> [TyVar]
212 -> Id -> Id -- Global, local
214 -> DsM (Maybe ((Id,CoreExpr), -- Binding for specialised Id
215 CoreRule)) -- Rule for the Global Id
218 -- f :: (Eq a, Ix b) => a -> b -> b
219 -- {-# SPECIALISE f :: Ix b => Int -> b -> b #-}
221 -- AbsBinds [ab] [d1,d2] [([ab], f, f_mono, prags)] binds
223 -- SpecPrag (/\b.\(d:Ix b). f Int b dInt d)
224 -- (forall b. Ix b => Int -> b -> b)
226 -- Rule: forall b,(d:Ix b). f Int b dInt d = f_spec b d
228 -- Spec bind: f_spec = Let f = /\ab \(d1:Eq a)(d2:Ix b). let binds in f_mono
229 -- /\b.\(d:Ix b). in f Int b dInt d
230 -- The idea is that f occurs just once, so it'll be
231 -- inlined and specialised
233 dsSpec all_tvs dicts tvs poly_id mono_id mono_bind (InlinePrag {})
236 dsSpec all_tvs dicts tvs poly_id mono_id mono_bind
237 (SpecPrag spec_expr spec_ty const_dicts inl)
238 = do { let poly_name = idName poly_id
239 ; spec_name <- newLocalName poly_name
240 ; ds_spec_expr <- dsExpr spec_expr
241 ; let (bndrs, body) = collectBinders ds_spec_expr
242 mb_lhs = decomposeRuleLhs (bndrs ++ const_dicts) body
245 Nothing -> do { warnDs msg; return Nothing }
247 Just (bndrs', var, args) -> return (Just (addInlineInfo inl spec_id spec_rhs, rule))
249 local_poly = setIdNotExported poly_id
250 -- Very important to make the 'f' non-exported,
251 -- else it won't be inlined!
252 spec_id = mkLocalId spec_name spec_ty
253 spec_rhs = Let (NonRec local_poly poly_f_body) ds_spec_expr
254 poly_f_body = mkLams (tvs ++ dicts) $
255 fix_up (Let mono_bind (Var mono_id))
257 -- Quantify over constant dicts on the LHS, since
258 -- their value depends only on their type
259 -- The ones we are interested in may even be imported
260 -- e.g. GHC.Base.dEqInt
262 rule = mkLocalRule (mkFastString ("SPEC " ++ showSDoc (ppr poly_name)))
263 AlwaysActive poly_name
264 bndrs' -- Includes constant dicts
266 (mkVarApps (Var spec_id) bndrs)
269 -- Bind to voidTy any of all_ptvs that aren't
270 -- relevant for this particular function
271 fix_up body | null void_tvs = body
272 | otherwise = mkTyApps (mkLams void_tvs body)
273 (map (const voidTy) void_tvs)
274 void_tvs = all_tvs \\ tvs
276 msg = hang (ptext SLIT("Specialisation too complicated to desugar; ignored"))
281 %************************************************************************
283 \subsection{Adding inline pragmas}
285 %************************************************************************
288 decomposeRuleLhs :: [Var] -> CoreExpr -> Maybe ([Var], Id, [CoreExpr])
289 -- Returns Nothing if the LHS isn't of the expected shape
290 -- The argument 'all_bndrs' includes the "constant dicts" of the LHS,
291 -- and they may be GlobalIds, which we can't forall-ify.
292 -- So we substitute them out instead
293 decomposeRuleLhs all_bndrs lhs
294 = go init_env (occurAnalyseExpr lhs) -- Occurrence analysis sorts out the dict
295 -- bindings so we know if they are recursive
298 -- all_bndrs may include top-level imported dicts,
299 -- imported things with a for-all.
300 -- So we localise them and subtitute them out
301 bndr_prs = [ (id, Var (localise id)) | id <- all_bndrs, isGlobalId id ]
302 localise d = mkLocalId (idName d) (idType d)
304 init_env = mkVarEnv bndr_prs
305 all_bndrs' = map subst_bndr all_bndrs
306 subst_bndr bndr = case lookupVarEnv init_env bndr of
307 Just (Var bndr') -> bndr'
308 Just other -> panic "decomposeRuleLhs"
311 -- Substitute dicts in the LHS args, so that there
312 -- aren't any lets getting in the way
313 -- Note that we substitute the function too; we might have this as
314 -- a LHS: let f71 = M.f Int in f71
315 go env (Let (NonRec dict rhs) body)
316 = go (extendVarEnv env dict (simpleSubst env rhs)) body
318 = case collectArgs (simpleSubst env body) of
319 (Var fn, args) -> Just (all_bndrs', fn, args)
322 simpleSubst :: IdEnv CoreExpr -> CoreExpr -> CoreExpr
323 -- Similar to CoreSubst.substExpr, except that
324 -- (a) takes no account of capture; dictionary bindings use new names
325 -- (b) can have a GlobalId (imported) in its domain
326 -- (c) Ids only; no types are substituted
328 simpleSubst subst expr
331 go (Var v) = lookupVarEnv subst v `orElse` Var v
332 go (Cast e co) = Cast (go e) co
333 go (Type ty) = Type ty
334 go (Lit lit) = Lit lit
335 go (App fun arg) = App (go fun) (go arg)
336 go (Note note e) = Note note (go e)
337 go (Lam bndr body) = Lam bndr (go body)
338 go (Let (NonRec bndr rhs) body) = Let (NonRec bndr (go rhs)) (go body)
339 go (Let (Rec pairs) body) = Let (Rec (mapSnd go pairs)) (go body)
340 go (Case scrut bndr ty alts) = Case (go scrut) bndr ty
341 [(c,bs,go r) | (c,bs,r) <- alts]
343 addInlinePrags :: [Prag] -> Id -> CoreExpr -> (Id,CoreExpr)
344 addInlinePrags prags bndr rhs
345 = case [inl | InlinePrag inl <- prags] of
347 (inl:_) -> addInlineInfo inl bndr rhs
349 addInlineInfo :: InlineSpec -> Id -> CoreExpr -> (Id,CoreExpr)
350 addInlineInfo (Inline phase is_inline) bndr rhs
351 = (attach_phase bndr phase, wrap_inline is_inline rhs)
353 attach_phase bndr phase
354 | isAlwaysActive phase = bndr -- Default phase
355 | otherwise = bndr `setInlinePragma` phase
357 wrap_inline True body = mkInlineMe body
358 wrap_inline False body = body
362 %************************************************************************
364 \subsection[addAutoScc]{Adding automatic sccs}
366 %************************************************************************
369 data AutoScc = NoSccs
370 | AddSccs Module (Id -> Bool)
371 -- The (Id->Bool) says which Ids to add SCCs to
373 addAutoScc :: AutoScc
376 -> CoreExpr -- Scc'd Rhs
378 addAutoScc NoSccs _ rhs
380 addAutoScc (AddSccs mod add_scc) id rhs
381 | add_scc id = mkSCC (mkAutoCC id mod NotCafCC) rhs
385 If profiling and dealing with a dict binding,
386 wrap the dict in @_scc_ DICT <dict>@:
389 addDictScc var rhs = returnDs rhs
391 {- DISABLED for now (need to somehow make up a name for the scc) -- SDM
392 | not ( opt_SccProfilingOn && opt_AutoSccsOnDicts)
393 || not (isDictId var)
394 = returnDs rhs -- That's easy: do nothing
397 = getModuleAndGroupDs `thenDs` \ (mod, grp) ->
398 -- ToDo: do -dicts-all flag (mark dict things with individual CCs)
399 returnDs (Note (SCC (mkAllDictsCC mod grp False)) rhs)
404 %************************************************************************
408 %************************************************************************
412 dsCoercion :: HsWrapper -> DsM CoreExpr -> DsM CoreExpr
413 dsCoercion WpHole thing_inside = thing_inside
414 dsCoercion (WpCompose c1 c2) thing_inside = dsCoercion c1 (dsCoercion c2 thing_inside)
415 dsCoercion (WpCo co) thing_inside = do { expr <- thing_inside
416 ; return (Cast expr co) }
417 dsCoercion (WpLam id) thing_inside = do { expr <- thing_inside
418 ; return (Lam id expr) }
419 dsCoercion (WpTyLam tv) thing_inside = do { expr <- thing_inside
420 ; return (Lam tv expr) }
421 dsCoercion (WpApp id) thing_inside = do { expr <- thing_inside
422 ; return (App expr (Var id)) }
423 dsCoercion (WpTyApp ty) thing_inside = do { expr <- thing_inside
424 ; return (App expr (Type ty)) }
425 dsCoercion (WpLet bs) thing_inside = do { prs <- dsLHsBinds bs
426 ; expr <- thing_inside
427 ; return (Let (Rec prs) expr) }