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, AutoScc(..) ) where
13 #include "HsVersions.h"
16 import {-# SOURCE #-} DsExpr( dsLExpr, dsExpr )
17 import {-# SOURCE #-} Match( matchWrapper )
20 import DsGRHSs ( dsGuarded )
23 import HsSyn -- lots of things
24 import CoreSyn -- lots of things
25 import CoreUtils ( exprType, mkInlineMe, mkSCC )
27 import StaticFlags ( opt_AutoSccsOnAllToplevs,
28 opt_AutoSccsOnExportedToplevs )
29 import OccurAnal ( occurAnalyseExpr )
30 import CostCentre ( mkAutoCC, IsCafCC(..) )
31 import Id ( Id, idType, idName, isExportedId, mkLocalId, setInlinePragma )
32 import Rules ( addIdSpecialisations, mkLocalRule )
33 import Var ( Var, isGlobalId )
35 import Type ( mkTyVarTy, substTyWith )
36 import TysWiredIn ( voidTy )
38 import SrcLoc ( Located(..) )
39 import Maybes ( isJust, catMaybes, orElse )
40 import Bag ( bagToList )
41 import BasicTypes ( Activation(..), isAlwaysActive )
42 import Monad ( foldM )
43 import FastString ( mkFastString )
45 import Util ( mapSnd )
48 %************************************************************************
50 \subsection[dsMonoBinds]{Desugaring a @MonoBinds@}
52 %************************************************************************
55 dsTopLHsBinds :: AutoScc -> LHsBinds Id -> DsM [(Id,CoreExpr)]
56 dsTopLHsBinds auto_scc binds = ds_lhs_binds auto_scc binds
58 dsLHsBinds :: LHsBinds Id -> DsM [(Id,CoreExpr)]
59 dsLHsBinds binds = ds_lhs_binds NoSccs binds
62 ------------------------
63 ds_lhs_binds :: AutoScc -> LHsBinds Id -> DsM [(Id,CoreExpr)]
64 -- scc annotation policy (see below)
65 ds_lhs_binds auto_scc binds = foldM (dsLHsBind auto_scc) [] (bagToList binds)
68 -> [(Id,CoreExpr)] -- Put this on the end (avoid quadratic append)
70 -> DsM [(Id,CoreExpr)] -- Result
71 dsLHsBind auto_scc rest (L loc bind)
72 = putSrcSpanDs loc $ dsHsBind auto_scc rest bind
75 -> [(Id,CoreExpr)] -- Put this on the end (avoid quadratic append)
77 -> DsM [(Id,CoreExpr)] -- Result
79 dsHsBind auto_scc rest (VarBind var expr)
80 = dsLExpr expr `thenDs` \ core_expr ->
82 -- Dictionary bindings are always VarMonoBinds, so
83 -- we only need do this here
84 addDictScc var core_expr `thenDs` \ core_expr' ->
85 returnDs ((var, core_expr') : rest)
87 dsHsBind auto_scc rest (FunBind (L _ fun) _ matches _)
88 = matchWrapper (FunRhs (idName fun)) matches `thenDs` \ (args, body) ->
89 addAutoScc auto_scc (fun, mkLams args body) `thenDs` \ pair ->
90 returnDs (pair : rest)
92 dsHsBind auto_scc rest (PatBind pat grhss ty _)
93 = dsGuarded grhss ty `thenDs` \ body_expr ->
94 mkSelectorBinds pat body_expr `thenDs` \ sel_binds ->
95 mappM (addAutoScc auto_scc) sel_binds `thenDs` \ sel_binds ->
96 returnDs (sel_binds ++ rest)
98 -- Common special case: no type or dictionary abstraction
99 -- For the (rare) case when there are some mixed-up
100 -- dictionary bindings (for which a Rec is convenient)
101 -- we reply on the enclosing dsBind to wrap a Rec around.
102 dsHsBind auto_scc rest (AbsBinds [] [] exports binds)
103 = ds_lhs_binds (addSccs auto_scc exports) binds `thenDs` \ core_prs ->
105 core_prs' = addLocalInlines exports core_prs
106 exports' = [(global, Var local) | (_, global, local, _) <- exports]
108 returnDs (core_prs' ++ exports' ++ rest)
110 -- Another common case: one exported variable
111 -- Non-recursive bindings come through this way
112 dsHsBind auto_scc rest
113 (AbsBinds all_tyvars dicts exports@[(tyvars, global, local, prags)] binds)
114 = ASSERT( all (`elem` tyvars) all_tyvars )
115 ds_lhs_binds (addSccs auto_scc exports) binds `thenDs` \ core_prs ->
117 -- Always treat the binds as recursive, because the typechecker
118 -- makes rather mixed-up dictionary bindings
119 core_bind = Rec core_prs
120 inline_env = mkVarEnv [(global, prag) | prag <- prags, isInlinePrag prag]
122 mappM (dsSpec all_tyvars dicts tyvars global local core_bind)
123 prags `thenDs` \ mb_specs ->
125 (spec_binds, rules) = unzip (catMaybes mb_specs)
126 global' = addIdSpecialisations global rules
127 rhs' = mkLams tyvars $ mkLams dicts $ Let core_bind (Var local)
129 returnDs (addInlineInfo inline_env (global', rhs') : spec_binds ++ rest)
131 dsHsBind auto_scc rest (AbsBinds all_tyvars dicts exports binds)
132 = ds_lhs_binds (addSccs auto_scc exports) binds `thenDs` \ core_prs ->
134 -- Rec because of mixed-up dictionary bindings
135 core_bind = Rec (addLocalInlines exports core_prs)
137 tup_expr = mkTupleExpr locals
138 tup_ty = exprType tup_expr
139 poly_tup_expr = mkLams all_tyvars $ mkLams dicts $
140 Let core_bind tup_expr
141 locals = [local | (_, _, local, _) <- exports]
142 local_tys = map idType locals
144 newSysLocalDs (exprType poly_tup_expr) `thenDs` \ poly_tup_id ->
146 dict_args = map Var dicts
148 mk_bind ((tyvars, global, local, prags), n) -- locals !! n == local
149 = -- Need to make fresh locals to bind in the selector, because
150 -- some of the tyvars will be bound to voidTy
151 newSysLocalsDs (map substitute local_tys) `thenDs` \ locals' ->
152 newSysLocalDs (substitute tup_ty) `thenDs` \ tup_id ->
153 mapM (dsSpec all_tyvars dicts tyvars global local core_bind)
154 prags `thenDs` \ mb_specs ->
156 (spec_binds, rules) = unzip (catMaybes mb_specs)
157 global' = addIdSpecialisations global rules
158 rhs = mkLams tyvars $ mkLams dicts $
159 mkTupleSelector locals' (locals' !! n) tup_id $
160 mkApps (mkTyApps (Var poly_tup_id) ty_args) dict_args
162 returnDs ((global', rhs) : spec_binds)
164 mk_ty_arg all_tyvar | all_tyvar `elem` tyvars = mkTyVarTy all_tyvar
166 ty_args = map mk_ty_arg all_tyvars
167 substitute = substTyWith all_tyvars ty_args
169 mappM mk_bind (exports `zip` [0..]) `thenDs` \ export_binds_s ->
170 -- don't scc (auto-)annotate the tuple itself.
172 returnDs ((poly_tup_id, poly_tup_expr) : (concat export_binds_s ++ rest))
175 -- f :: (Eq a, Ix b) => a -> b -> b
177 -- AbsBinds [ab] [d1,d2] [([ab], f, f_mono, prags)] binds
179 -- SpecPrag (/\b.\(d:Ix b). f Int b dInt d)
180 -- (forall b. Ix b => Int -> b -> b)
182 -- Rule: forall b,(d:Ix b). f Int b dInt d = f_spec b d
184 -- Spec bind: f_spec = Let f = /\ab \(d1:Eq a)(d2:Ix b). let binds in f_mono
185 -- /\b.\(d:Ix b). in f Int b dInt d
187 dsSpec all_tvs dicts tvs poly_id mono_id mono_bind (InlinePrag {})
190 dsSpec all_tvs dicts tvs poly_id mono_id mono_bind
191 (SpecPrag spec_expr spec_ty const_dicts)
192 = do { let poly_name = idName poly_id
193 ; spec_name <- newLocalName (idName poly_id)
194 ; ds_spec_expr <- dsExpr spec_expr
195 ; let (bndrs, body) = collectBinders ds_spec_expr
196 mb_lhs = decomposeRuleLhs (bndrs ++ const_dicts) body
199 Nothing -> do { dsWarn msg; return Nothing }
201 Just (bndrs', var, args) -> return (Just ((spec_id, spec_rhs), rule))
203 spec_id = mkLocalId spec_name spec_ty
204 spec_rhs = Let (NonRec poly_id poly_f_body) ds_spec_expr
205 poly_f_body = mkLams (tvs ++ dicts) $
206 fix_up (Let mono_bind (Var mono_id))
208 -- Quantify over constant dicts on the LHS, since
209 -- their value depends only on their type
210 -- The ones we are interested in may even be imported
211 -- e.g. GHC.Base.dEqInt
213 rule = mkLocalRule (mkFastString ("SPEC " ++ showSDoc (ppr poly_name)))
214 AlwaysActive poly_name
215 bndrs' -- Includes constant dicts
217 (mkVarApps (Var spec_id) bndrs)
220 -- Bind to voidTy any of all_ptvs that aren't
221 -- relevant for this particular function
222 fix_up body | null void_tvs = body
223 | otherwise = mkTyApps (mkLams void_tvs body)
224 (map (const voidTy) void_tvs)
225 void_tvs = all_tvs \\ tvs
227 msg = hang (ptext SLIT("Specialisation too complicated to desugar; ignored"))
232 %************************************************************************
234 \subsection{Adding inline pragmas}
236 %************************************************************************
239 decomposeRuleLhs :: [Var] -> CoreExpr -> Maybe ([Var], Id, [CoreExpr])
240 -- Returns Nothing if the LHS isn't of the expected shape
241 -- The argument 'all_bndrs' includes the "constant dicts" of the LHS,
242 -- and they may be GlobalIds, which we can't forall-ify.
243 -- So we substitute them out instead
244 decomposeRuleLhs all_bndrs lhs
245 = go init_env (occurAnalyseExpr lhs) -- Occurrence analysis sorts out the dict
246 -- bindings so we know if they are recursive
249 -- all_bndrs may include top-level imported dicts,
250 -- imported things with a for-all.
251 -- So we localise them and subtitute them out
252 bndr_prs = [ (id, Var (localise id)) | id <- all_bndrs, isGlobalId id ]
253 localise d = mkLocalId (idName d) (idType d)
255 init_env = mkVarEnv bndr_prs
256 all_bndrs' = map subst_bndr all_bndrs
257 subst_bndr bndr = case lookupVarEnv init_env bndr of
258 Just (Var bndr') -> bndr'
259 Just other -> panic "decomposeRuleLhs"
262 -- Substitute dicts in the LHS args, so that there
263 -- aren't any lets getting in the way
264 go env (Let (NonRec dict rhs) body)
265 = go (extendVarEnv env dict (simpleSubst env rhs)) body
267 = case collectArgs body of
268 (Var fn, args) -> Just (all_bndrs', fn, map (simpleSubst env) args)
271 simpleSubst :: IdEnv CoreExpr -> CoreExpr -> CoreExpr
272 -- Similar to CoreSubst.substExpr, except that
273 -- (a) takes no account of capture; dictionary bindings use new names
274 -- (b) can have a GlobalId (imported) in its domain
275 -- (c) Ids only; no types are substituted
277 simpleSubst subst expr
280 go (Var v) = lookupVarEnv subst v `orElse` Var v
281 go (Type ty) = Type ty
282 go (Lit lit) = Lit lit
283 go (App fun arg) = App (go fun) (go arg)
284 go (Note note e) = Note note (go e)
285 go (Lam bndr body) = Lam bndr (go body)
286 go (Let (NonRec bndr rhs) body) = Let (NonRec bndr (go rhs)) (go body)
287 go (Let (Rec pairs) body) = Let (Rec (mapSnd go pairs)) (go body)
288 go (Case scrut bndr ty alts) = Case (go scrut) bndr ty
289 [(c,bs,go r) | (c,bs,r) <- alts]
291 addLocalInlines exports core_prs
292 = map (addInlineInfo inline_env) core_prs
294 inline_env = mkVarEnv [(mono_id, prag)
295 | (_, _, mono_id, prags) <- exports,
296 prag <- prags, isInlinePrag prag]
298 addInlineInfo :: IdEnv Prag -> (Id,CoreExpr) -> (Id,CoreExpr)
299 addInlineInfo inline_env (bndr,rhs)
300 | Just (InlinePrag is_inline phase) <- lookupVarEnv inline_env bndr
301 = (attach_phase bndr phase, wrap_inline is_inline rhs)
305 attach_phase bndr phase
306 | isAlwaysActive phase = bndr -- Default phase
307 | otherwise = bndr `setInlinePragma` phase
309 wrap_inline True body = mkInlineMe body
310 wrap_inline False body = body
314 %************************************************************************
316 \subsection[addAutoScc]{Adding automatic sccs}
318 %************************************************************************
323 | TopLevelAddSccs (Id -> Maybe Id)
326 addSccs :: AutoScc -> [(a,Id,Id,[Prag])] -> AutoScc
327 addSccs auto_scc@(TopLevelAddSccs _) exports = auto_scc
328 addSccs NoSccs exports = NoSccs
329 addSccs TopLevel exports
330 = TopLevelAddSccs (\id -> case [ exp | (_,exp,loc,_) <- exports, loc == id ] of
331 (exp:_) | opt_AutoSccsOnAllToplevs ||
333 opt_AutoSccsOnExportedToplevs)
337 addAutoScc :: AutoScc -- if needs be, decorate toplevs?
339 -> DsM (Id, CoreExpr)
341 addAutoScc (TopLevelAddSccs auto_scc_fn) pair@(bndr, core_expr)
343 = getModuleDs `thenDs` \ mod ->
344 returnDs (bndr, mkSCC (mkAutoCC top_bndr mod NotCafCC) core_expr)
345 where do_auto_scc = isJust maybe_auto_scc
346 maybe_auto_scc = auto_scc_fn bndr
347 (Just top_bndr) = maybe_auto_scc
353 If profiling and dealing with a dict binding,
354 wrap the dict in @_scc_ DICT <dict>@:
357 addDictScc var rhs = returnDs rhs
359 {- DISABLED for now (need to somehow make up a name for the scc) -- SDM
360 | not ( opt_SccProfilingOn && opt_AutoSccsOnDicts)
361 || not (isDictId var)
362 = returnDs rhs -- That's easy: do nothing
365 = getModuleAndGroupDs `thenDs` \ (mod, grp) ->
366 -- ToDo: do -dicts-all flag (mark dict things with individual CCs)
367 returnDs (Note (SCC (mkAllDictsCC mod grp False)) rhs)