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).
14 -- The above warning supression flag is a temporary kludge.
15 -- While working on this module you are encouraged to remove it and fix
16 -- any warnings in the module. See
17 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
20 module DsBinds ( dsTopLHsBinds, dsLHsBinds, decomposeRuleLhs,
25 #include "HsVersions.h"
27 import {-# SOURCE #-} DsExpr( dsLExpr, dsExpr )
28 import {-# SOURCE #-} Match( matchWrapper )
34 import HsSyn -- lots of things
35 import CoreSyn -- lots of things
39 import TcHsSyn ( mkArbitraryType ) -- Mis-placed?
54 import BasicTypes hiding ( TopLevel )
56 import Util ( mapSnd )
62 %************************************************************************
64 \subsection[dsMonoBinds]{Desugaring a @MonoBinds@}
66 %************************************************************************
69 dsTopLHsBinds :: AutoScc -> LHsBinds Id -> DsM [(Id,CoreExpr)]
70 dsTopLHsBinds auto_scc binds = ds_lhs_binds auto_scc binds
72 dsLHsBinds :: LHsBinds Id -> DsM [(Id,CoreExpr)]
73 dsLHsBinds binds = ds_lhs_binds NoSccs binds
76 ------------------------
77 ds_lhs_binds :: AutoScc -> LHsBinds Id -> DsM [(Id,CoreExpr)]
78 -- scc annotation policy (see below)
79 ds_lhs_binds auto_scc binds = foldM (dsLHsBind auto_scc) [] (bagToList binds)
82 -> [(Id,CoreExpr)] -- Put this on the end (avoid quadratic append)
84 -> DsM [(Id,CoreExpr)] -- Result
85 dsLHsBind auto_scc rest (L loc bind)
86 = putSrcSpanDs loc $ dsHsBind auto_scc rest bind
89 -> [(Id,CoreExpr)] -- Put this on the end (avoid quadratic append)
91 -> DsM [(Id,CoreExpr)] -- Result
93 dsHsBind auto_scc rest (VarBind var expr)
94 = dsLExpr expr `thenDs` \ core_expr ->
96 -- Dictionary bindings are always VarMonoBinds, so
97 -- we only need do this here
98 addDictScc var core_expr `thenDs` \ core_expr' ->
99 returnDs ((var, core_expr') : rest)
101 dsHsBind auto_scc rest (FunBind { fun_id = L _ fun, fun_matches = matches,
102 fun_co_fn = co_fn, fun_tick = tick, fun_infix = inf })
103 = matchWrapper (FunRhs (idName fun) inf) matches `thenDs` \ (args, body) ->
104 mkOptTickBox tick body `thenDs` \ body' ->
105 dsCoercion co_fn (return (mkLams args body')) `thenDs` \ rhs ->
106 returnDs ((fun,rhs) : rest)
108 dsHsBind auto_scc rest (PatBind { pat_lhs = pat, pat_rhs = grhss, pat_rhs_ty = ty })
109 = dsGuarded grhss ty `thenDs` \ body_expr ->
110 mkSelectorBinds pat body_expr `thenDs` \ sel_binds ->
111 returnDs (sel_binds ++ rest)
113 -- Note [Rules and inlining]
114 -- Common special case: no type or dictionary abstraction
115 -- This is a bit less trivial than you might suppose
116 -- The naive way woudl be to desguar to something like
117 -- f_lcl = ...f_lcl... -- The "binds" from AbsBinds
118 -- M.f = f_lcl -- Generated from "exports"
119 -- But we don't want that, because if M.f isn't exported,
120 -- it'll be inlined unconditionally at every call site (its rhs is
121 -- trivial). That would be ok unless it has RULES, which would
122 -- thereby be completely lost. Bad, bad, bad.
124 -- Instead we want to generate
127 -- Now all is cool. The RULES are attached to M.f (by SimplCore),
128 -- and f_lcl is rapidly inlined away.
130 -- This does not happen in the same way to polymorphic binds,
131 -- because they desugar to
132 -- M.f = /\a. let f_lcl = ...f_lcl... in f_lcl
133 -- Although I'm a bit worried about whether full laziness might
134 -- float the f_lcl binding out and then inline M.f at its call site
136 dsHsBind auto_scc rest (AbsBinds [] [] exports binds)
137 = do { core_prs <- ds_lhs_binds NoSccs binds
138 ; let env = mkABEnv exports
139 do_one (lcl_id, rhs) | Just (gbl_id, prags) <- lookupVarEnv env lcl_id
140 = addInlinePrags prags gbl_id $
141 addAutoScc auto_scc gbl_id rhs
142 | otherwise = (lcl_id, rhs)
143 locals' = [(lcl_id, Var gbl_id) | (_, gbl_id, lcl_id, _) <- exports]
144 ; return (map do_one core_prs ++ locals' ++ rest) }
145 -- No Rec needed here (contrast the other AbsBinds cases)
146 -- because we can rely on the enclosing dsBind to wrap in Rec
148 -- Another common case: one exported variable
149 -- Non-recursive bindings come through this way
150 dsHsBind auto_scc rest
151 (AbsBinds all_tyvars dicts exports@[(tyvars, global, local, prags)] binds)
152 = ASSERT( all (`elem` tyvars) all_tyvars )
153 ds_lhs_binds NoSccs binds `thenDs` \ core_prs ->
155 -- Always treat the binds as recursive, because the typechecker
156 -- makes rather mixed-up dictionary bindings
157 core_bind = Rec core_prs
159 mappM (dsSpec all_tyvars dicts tyvars global local core_bind)
160 prags `thenDs` \ mb_specs ->
162 (spec_binds, rules) = unzip (catMaybes mb_specs)
163 global' = addIdSpecialisations global rules
164 rhs' = mkLams tyvars $ mkLams dicts $ Let core_bind (Var local)
165 bind = addInlinePrags prags global' $ addAutoScc auto_scc global' rhs'
167 returnDs (bind : spec_binds ++ rest)
169 dsHsBind auto_scc rest (AbsBinds all_tyvars dicts exports binds)
170 = do { core_prs <- ds_lhs_binds NoSccs binds
171 ; let env = mkABEnv exports
172 do_one (lcl_id,rhs) | Just (gbl_id, prags) <- lookupVarEnv env lcl_id
173 = addInlinePrags prags lcl_id $
174 addAutoScc auto_scc gbl_id rhs
175 | otherwise = (lcl_id,rhs)
177 -- Rec because of mixed-up dictionary bindings
178 core_bind = Rec (map do_one core_prs)
180 tup_expr = mkBigCoreVarTup locals
181 tup_ty = exprType tup_expr
182 poly_tup_expr = mkLams all_tyvars $ mkLams dicts $
183 Let core_bind tup_expr
184 locals = [local | (_, _, local, _) <- exports]
185 local_tys = map idType locals
187 ; poly_tup_id <- newSysLocalDs (exprType poly_tup_expr)
189 ; let dict_args = map Var dicts
191 mk_bind ((tyvars, global, local, prags), n) -- locals !! n == local
192 = -- Need to make fresh locals to bind in the selector, because
193 -- some of the tyvars will be bound to 'Any'
194 do { ty_args <- mapM mk_ty_arg all_tyvars
195 ; let substitute = substTyWith all_tyvars ty_args
196 ; locals' <- newSysLocalsDs (map substitute local_tys)
197 ; tup_id <- newSysLocalDs (substitute tup_ty)
198 ; mb_specs <- mapM (dsSpec all_tyvars dicts tyvars global local core_bind)
200 ; let (spec_binds, rules) = unzip (catMaybes mb_specs)
201 global' = addIdSpecialisations global rules
202 rhs = mkLams tyvars $ mkLams dicts $
203 mkTupleSelector locals' (locals' !! n) tup_id $
204 mkApps (mkTyApps (Var poly_tup_id) ty_args) dict_args
205 ; returnDs ((global', rhs) : spec_binds) }
208 | all_tyvar `elem` tyvars = return (mkTyVarTy all_tyvar)
209 | otherwise = dsMkArbitraryType all_tyvar
211 ; export_binds_s <- mappM mk_bind (exports `zip` [0..])
212 -- don't scc (auto-)annotate the tuple itself.
214 ; returnDs ((poly_tup_id, poly_tup_expr) :
215 (concat export_binds_s ++ rest)) }
217 mkABEnv :: [([TyVar], Id, Id, [LPrag])] -> VarEnv (Id, [LPrag])
218 -- Takes the exports of a AbsBinds, and returns a mapping
219 -- lcl_id -> (gbl_id, prags)
220 mkABEnv exports = mkVarEnv [ (lcl_id, (gbl_id, prags))
221 | (_, gbl_id, lcl_id, prags) <- exports]
224 dsSpec :: [TyVar] -> [DictId] -> [TyVar]
225 -> Id -> Id -- Global, local
227 -> DsM (Maybe ((Id,CoreExpr), -- Binding for specialised Id
228 CoreRule)) -- Rule for the Global Id
231 -- f :: (Eq a, Ix b) => a -> b -> b
232 -- {-# SPECIALISE f :: Ix b => Int -> b -> b #-}
234 -- AbsBinds [ab] [d1,d2] [([ab], f, f_mono, prags)] binds
236 -- SpecPrag (/\b.\(d:Ix b). f Int b dInt d)
237 -- (forall b. Ix b => Int -> b -> b)
239 -- Rule: forall b,(d:Ix b). f Int b dInt d = f_spec b d
241 -- Spec bind: f_spec = Let f = /\ab \(d1:Eq a)(d2:Ix b). let binds in f_mono
242 -- /\b.\(d:Ix b). in f Int b dInt d
243 -- The idea is that f occurs just once, so it'll be
244 -- inlined and specialised
246 -- Given SpecPrag (/\as.\ds. f es) t, we have
247 -- the defn f_spec as ds = let-nonrec f = /\fas\fds. let f_mono = <f-rhs> in f_mono
249 -- and the RULE forall as, ds. f es = f_spec as ds
251 -- It is *possible* that 'es' does not mention all of the dictionaries 'ds'
252 -- (a bit silly, because then the
253 dsSpec all_tvs dicts tvs poly_id mono_id mono_bind (L _ (InlinePrag {}))
256 dsSpec all_tvs dicts tvs poly_id mono_id mono_bind
257 (L loc (SpecPrag spec_expr spec_ty 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 (occurAnalyseExpr ds_spec_expr)
263 -- The occurrence-analysis does two things
264 -- (a) identifies unused binders: Note [Unused spec binders]
265 -- (b) sorts dict bindings into NonRecs
266 -- so they can be inlined by decomposeRuleLhs
267 mb_lhs = decomposeRuleLhs body
269 -- Check for dead binders: Note [Unused spec binders]
270 ; case filter isDeadBinder bndrs of {
271 bs | not (null bs) -> do { warnDs (dead_msg bs); return Nothing }
275 Nothing -> do { warnDs decomp_msg; return Nothing }
277 Just (var, args) -> do
279 { f_body <- fix_up (Let mono_bind (Var mono_id))
281 ; let local_poly = setIdNotExported poly_id
282 -- Very important to make the 'f' non-exported,
283 -- else it won't be inlined!
284 spec_id = mkLocalId spec_name spec_ty
285 spec_rhs = Let (NonRec local_poly poly_f_body) ds_spec_expr
286 poly_f_body = mkLams (tvs ++ dicts) f_body
288 extra_dict_bndrs = filter isDictId (varSetElems (exprFreeVars ds_spec_expr))
289 -- Note [Const rule dicts]
291 rule = mkLocalRule (mkFastString ("SPEC " ++ showSDoc (ppr poly_name)))
292 AlwaysActive poly_name
293 (extra_dict_bndrs ++ bndrs) args
294 (mkVarApps (Var spec_id) bndrs)
295 ; return (Just (addInlineInfo inl spec_id spec_rhs, rule))
298 -- Bind to Any any of all_ptvs that aren't
299 -- relevant for this particular function
300 fix_up body | null void_tvs = return body
301 | otherwise = do { void_tys <- mapM dsMkArbitraryType void_tvs
302 ; return (mkTyApps (mkLams void_tvs body) void_tys) }
304 void_tvs = all_tvs \\ tvs
306 dead_msg bs = vcat [ sep [ptext SLIT("Useless constraint") <> plural bs
307 <+> ptext SLIT("in specialied type:"),
308 nest 2 (pprTheta (map get_pred bs))]
309 , ptext SLIT("SPECIALISE pragma ignored")]
310 get_pred b = ASSERT( isId b ) expectJust "dsSpec" (tcSplitPredTy_maybe (idType b))
312 decomp_msg = hang (ptext SLIT("Specialisation too complicated to desugar; ignored"))
315 dsMkArbitraryType tv = mkArbitraryType warn tv
317 warn span msg = putSrcSpanDs span (warnDs msg)
320 Note [Unused spec binders]
321 ~~~~~~~~~~~~~~~~~~~~~~~~~~
324 {-# SPECIALISE f :: Eq a => a -> a #-}
325 It's true that this *is* a more specialised type, but the rule
326 we get is something like this:
329 Note that the rule is bogus, becuase it mentions a 'd' that is
330 not bound on the LHS! But it's a silly specialisation anyway, becuase
331 the constraint is unused. We could bind 'd' to (error "unused")
332 but it seems better to reject the program because it's almost certainly
333 a mistake. That's what the isDeadBinder call detects.
335 Note [Const rule dicts]
336 ~~~~~~~~~~~~~~~~~~~~~~~
337 When the LHS of a specialisation rule, (/\as\ds. f es) has a free dict,
338 which is presumably in scope at the function definition site, we can quantify
339 over it too. *Any* dict with that type will do.
341 So for example when you have
344 {-# SPECIALISE f :: Int -> Int #-}
346 Then we get the SpecPrag
347 SpecPrag (f Int dInt) Int
349 And from that we want the rule
351 RULE forall dInt. f Int dInt = f_spec
352 f_spec = let f = <rhs> in f Int dInt
356 %************************************************************************
358 \subsection{Adding inline pragmas}
360 %************************************************************************
363 decomposeRuleLhs :: CoreExpr -> Maybe (Id, [CoreExpr])
364 -- Returns Nothing if the LHS isn't of the expected shape
366 = go emptyVarEnv (occurAnalyseExpr lhs) -- Occurrence analysis sorts out the dict
367 -- bindings so we know if they are recursive
369 -- Substitute dicts in the LHS args, so that there
370 -- aren't any lets getting in the way
371 -- Note that we substitute the function too; we might have this as
372 -- a LHS: let f71 = M.f Int in f71
373 go env (Let (NonRec dict rhs) body)
374 = go (extendVarEnv env dict (simpleSubst env rhs)) body
376 = case collectArgs (simpleSubst env body) of
377 (Var fn, args) -> Just (fn, args)
380 simpleSubst :: IdEnv CoreExpr -> CoreExpr -> CoreExpr
381 -- Similar to CoreSubst.substExpr, except that
382 -- (a) takes no account of capture; dictionary bindings use new names
383 -- (b) can have a GlobalId (imported) in its domain
384 -- (c) Ids only; no types are substituted
386 -- (b) is the reason we can't use CoreSubst... and it's no longer relevant
387 -- so really we should replace simpleSubst
388 simpleSubst subst expr
391 go (Var v) = lookupVarEnv subst v `orElse` Var v
392 go (Cast e co) = Cast (go e) co
393 go (Type ty) = Type ty
394 go (Lit lit) = Lit lit
395 go (App fun arg) = App (go fun) (go arg)
396 go (Note note e) = Note note (go e)
397 go (Lam bndr body) = Lam bndr (go body)
398 go (Let (NonRec bndr rhs) body) = Let (NonRec bndr (go rhs)) (go body)
399 go (Let (Rec pairs) body) = Let (Rec (mapSnd go pairs)) (go body)
400 go (Case scrut bndr ty alts) = Case (go scrut) bndr ty
401 [(c,bs,go r) | (c,bs,r) <- alts]
403 addInlinePrags :: [LPrag] -> Id -> CoreExpr -> (Id,CoreExpr)
404 addInlinePrags prags bndr rhs
405 = case [inl | L _ (InlinePrag inl) <- prags] of
407 (inl:_) -> addInlineInfo inl bndr rhs
409 addInlineInfo :: InlineSpec -> Id -> CoreExpr -> (Id,CoreExpr)
410 addInlineInfo (Inline phase is_inline) bndr rhs
411 = (attach_phase bndr phase, wrap_inline is_inline rhs)
413 attach_phase bndr phase
414 | isAlwaysActive phase = bndr -- Default phase
415 | otherwise = bndr `setInlinePragma` phase
417 wrap_inline True body = mkInlineMe body
418 wrap_inline False body = body
422 %************************************************************************
424 \subsection[addAutoScc]{Adding automatic sccs}
426 %************************************************************************
429 data AutoScc = NoSccs
430 | AddSccs Module (Id -> Bool)
431 -- The (Id->Bool) says which Ids to add SCCs to
433 addAutoScc :: AutoScc
436 -> CoreExpr -- Scc'd Rhs
438 addAutoScc NoSccs _ rhs
440 addAutoScc (AddSccs mod add_scc) id rhs
441 | add_scc id = mkSCC (mkAutoCC id mod NotCafCC) rhs
445 If profiling and dealing with a dict binding,
446 wrap the dict in @_scc_ DICT <dict>@:
449 addDictScc var rhs = returnDs rhs
451 {- DISABLED for now (need to somehow make up a name for the scc) -- SDM
452 | not ( opt_SccProfilingOn && opt_AutoSccsOnDicts)
453 || not (isDictId var)
454 = returnDs rhs -- That's easy: do nothing
457 = getModuleAndGroupDs `thenDs` \ (mod, grp) ->
458 -- ToDo: do -dicts-all flag (mark dict things with individual CCs)
459 returnDs (Note (SCC (mkAllDictsCC mod grp False)) rhs)
464 %************************************************************************
468 %************************************************************************
472 dsCoercion :: HsWrapper -> DsM CoreExpr -> DsM CoreExpr
473 dsCoercion WpHole thing_inside = thing_inside
474 dsCoercion (WpCompose c1 c2) thing_inside = dsCoercion c1 (dsCoercion c2 thing_inside)
475 dsCoercion (WpCo co) thing_inside = do { expr <- thing_inside
476 ; return (Cast expr co) }
477 dsCoercion (WpLam id) thing_inside = do { expr <- thing_inside
478 ; return (Lam id expr) }
479 dsCoercion (WpTyLam tv) thing_inside = do { expr <- thing_inside
480 ; return (Lam tv expr) }
481 dsCoercion (WpApp id) thing_inside = do { expr <- thing_inside
482 ; return (App expr (Var id)) }
483 dsCoercion (WpTyApp ty) thing_inside = do { expr <- thing_inside
484 ; return (App expr (Type ty)) }
485 dsCoercion WpInline thing_inside = do { expr <- thing_inside
486 ; return (mkInlineMe expr) }
487 dsCoercion (WpLet bs) thing_inside = do { prs <- dsLHsBinds bs
488 ; expr <- thing_inside
489 ; return (Let (Rec prs) expr) }