2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 ***************************
8 ***************************
10 1. We attach binding levels to Core bindings, in preparation for floating
11 outwards (@FloatOut@).
13 2. We also let-ify many expressions (notably case scrutinees), so they
14 will have a fighting chance of being floated sensible.
16 3. We clone the binders of any floatable let-binding, so that when it is
17 floated out it will be unique. (This used to be done by the simplifier
18 but the latter now only ensures that there's no shadowing; indeed, even
19 that may not be true.)
21 NOTE: this can't be done using the uniqAway idea, because the variable
22 must be unique in the whole program, not just its current scope,
23 because two variables in different scopes may float out to the
26 NOTE: Very tiresomely, we must apply this substitution to
27 the rules stored inside a variable too.
29 We do *not* clone top-level bindings, because some of them must not change,
30 but we *do* clone bindings that are heading for the top level
33 case x of wild { p -> ...wild... }
34 we substitute x for wild in the RHS of the case alternatives:
35 case x of wild { p -> ...x... }
36 This means that a sub-expression involving x is not "trapped" inside the RHS.
37 And it's not inconvenient because we already have a substitution.
39 Note that this is EXACTLY BACKWARDS from the what the simplifier does.
40 The simplifier tries to get rid of occurrences of x, in favour of wild,
41 in the hope that there will only be one remaining occurrence of x, namely
42 the scrutinee of the case, and we can inline it.
50 incMinorLvl, ltMajLvl, ltLvl, isTopLvl, isInlineCtxt
53 #include "HsVersions.h"
57 import CmdLineOpts ( FloatOutSwitches(..) )
58 import CoreUtils ( exprType, exprIsTrivial, exprIsCheap, mkPiTypes )
59 import CoreFVs -- all of it
61 import Id ( Id, idType, mkSysLocal, isOneShotLambda, zapDemandIdInfo,
62 idSpecialisation, idWorkerInfo, setIdInfo
64 import IdInfo ( workerExists, vanillaIdInfo, )
68 import Name ( getOccName )
69 import OccName ( occNameUserString )
70 import Type ( isUnLiftedType, Type )
71 import BasicTypes ( TopLevelFlag(..) )
73 import Util ( sortLt, isSingleton, count )
78 %************************************************************************
80 \subsection{Level numbers}
82 %************************************************************************
85 data Level = InlineCtxt -- A level that's used only for
86 -- the context parameter ctxt_lvl
87 | Level Int -- Level number of enclosing lambdas
88 Int -- Number of big-lambda and/or case expressions between
89 -- here and the nearest enclosing lambda
92 The {\em level number} on a (type-)lambda-bound variable is the
93 nesting depth of the (type-)lambda which binds it. The outermost lambda
94 has level 1, so (Level 0 0) means that the variable is bound outside any lambda.
96 On an expression, it's the maximum level number of its free
97 (type-)variables. On a let(rec)-bound variable, it's the level of its
98 RHS. On a case-bound variable, it's the number of enclosing lambdas.
100 Top-level variables: level~0. Those bound on the RHS of a top-level
101 definition but ``before'' a lambda; e.g., the \tr{x} in (levels shown
102 as ``subscripts'')...
104 a_0 = let b_? = ... in
105 x_1 = ... b ... in ...
108 The main function @lvlExpr@ carries a ``context level'' (@ctxt_lvl@).
109 That's meant to be the level number of the enclosing binder in the
110 final (floated) program. If the level number of a sub-expression is
111 less than that of the context, then it might be worth let-binding the
112 sub-expression so that it will indeed float.
114 If you can float to level @Level 0 0@ worth doing so because then your
115 allocation becomes static instead of dynamic. We always start with
121 @InlineCtxt@ very similar to @Level 0 0@, but is used for one purpose:
122 to say "don't float anything out of here". That's exactly what we
123 want for the body of an INLINE, where we don't want to float anything
124 out at all. See notes with lvlMFE below.
128 -- At one time I tried the effect of not float anything out of an InlineMe,
129 -- but it sometimes works badly. For example, consider PrelArr.done. It
130 -- has the form __inline (\d. e)
131 -- where e doesn't mention d. If we float this to
132 -- __inline (let x = e in \d. x)
133 -- things are bad. The inliner doesn't even inline it because it doesn't look
134 -- like a head-normal form. So it seems a lesser evil to let things float.
135 -- In SetLevels we do set the context to (Level 0 0) when we get to an InlineMe
136 -- which discourages floating out.
138 So the conclusion is: don't do any floating at all inside an InlineMe.
139 (In the above example, don't float the {x=e} out of the \d.)
141 One particular case is that of workers: we don't want to float the
142 call to the worker outside the wrapper, otherwise the worker might get
143 inlined into the floated expression, and an importing module won't see
147 type LevelledExpr = TaggedExpr Level
148 type LevelledBind = TaggedBind Level
150 tOP_LEVEL = Level 0 0
151 iNLINE_CTXT = InlineCtxt
153 incMajorLvl :: Level -> Level
154 -- For InlineCtxt we ignore any inc's; we don't want
155 -- to do any floating at all; see notes above
156 incMajorLvl InlineCtxt = InlineCtxt
157 incMajorLvl (Level major minor) = Level (major+1) 0
159 incMinorLvl :: Level -> Level
160 incMinorLvl InlineCtxt = InlineCtxt
161 incMinorLvl (Level major minor) = Level major (minor+1)
163 maxLvl :: Level -> Level -> Level
164 maxLvl InlineCtxt l2 = l2
165 maxLvl l1 InlineCtxt = l1
166 maxLvl l1@(Level maj1 min1) l2@(Level maj2 min2)
167 | (maj1 > maj2) || (maj1 == maj2 && min1 > min2) = l1
170 ltLvl :: Level -> Level -> Bool
171 ltLvl any_lvl InlineCtxt = False
172 ltLvl InlineCtxt (Level _ _) = True
173 ltLvl (Level maj1 min1) (Level maj2 min2)
174 = (maj1 < maj2) || (maj1 == maj2 && min1 < min2)
176 ltMajLvl :: Level -> Level -> Bool
177 -- Tells if one level belongs to a difft *lambda* level to another
178 ltMajLvl any_lvl InlineCtxt = False
179 ltMajLvl InlineCtxt (Level maj2 _) = 0 < maj2
180 ltMajLvl (Level maj1 _) (Level maj2 _) = maj1 < maj2
182 isTopLvl :: Level -> Bool
183 isTopLvl (Level 0 0) = True
184 isTopLvl other = False
186 isInlineCtxt :: Level -> Bool
187 isInlineCtxt InlineCtxt = True
188 isInlineCtxt other = False
190 instance Outputable Level where
191 ppr InlineCtxt = text "<INLINE>"
192 ppr (Level maj min) = hcat [ char '<', int maj, char ',', int min, char '>' ]
194 instance Eq Level where
195 InlineCtxt == InlineCtxt = True
196 (Level maj1 min1) == (Level maj2 min2) = maj1==maj2 && min1==min2
201 %************************************************************************
203 \subsection{Main level-setting code}
205 %************************************************************************
208 setLevels :: FloatOutSwitches
213 setLevels float_lams binds us
214 = initLvl us (do_them binds)
216 -- "do_them"'s main business is to thread the monad along
217 -- It gives each top binding the same empty envt, because
218 -- things unbound in the envt have level number zero implicitly
219 do_them :: [CoreBind] -> LvlM [LevelledBind]
221 do_them [] = returnLvl []
223 = lvlTopBind init_env b `thenLvl` \ (lvld_bind, _) ->
224 do_them bs `thenLvl` \ lvld_binds ->
225 returnLvl (lvld_bind : lvld_binds)
227 init_env = initialEnv float_lams
229 lvlTopBind env (NonRec binder rhs)
230 = lvlBind TopLevel tOP_LEVEL env (AnnNonRec binder (freeVars rhs))
231 -- Rhs can have no free vars!
233 lvlTopBind env (Rec pairs)
234 = lvlBind TopLevel tOP_LEVEL env (AnnRec [(b,freeVars rhs) | (b,rhs) <- pairs])
237 %************************************************************************
239 \subsection{Setting expression levels}
241 %************************************************************************
244 lvlExpr :: Level -- ctxt_lvl: Level of enclosing expression
245 -> LevelEnv -- Level of in-scope names/tyvars
246 -> CoreExprWithFVs -- input expression
247 -> LvlM LevelledExpr -- Result expression
250 The @ctxt_lvl@ is, roughly, the level of the innermost enclosing
251 binder. Here's an example
253 v = \x -> ...\y -> let r = case (..x..) of
257 When looking at the rhs of @r@, @ctxt_lvl@ will be 1 because that's
258 the level of @r@, even though it's inside a level-2 @\y@. It's
259 important that @ctxt_lvl@ is 1 and not 2 in @r@'s rhs, because we
260 don't want @lvlExpr@ to turn the scrutinee of the @case@ into an MFE
261 --- because it isn't a *maximal* free expression.
263 If there were another lambda in @r@'s rhs, it would get level-2 as well.
266 lvlExpr _ _ (_, AnnType ty) = returnLvl (Type ty)
267 lvlExpr _ env (_, AnnVar v) = returnLvl (lookupVar env v)
268 lvlExpr _ env (_, AnnLit lit) = returnLvl (Lit lit)
270 lvlExpr ctxt_lvl env (_, AnnApp fun arg)
271 = lvl_fun fun `thenLvl` \ fun' ->
272 lvlMFE False ctxt_lvl env arg `thenLvl` \ arg' ->
273 returnLvl (App fun' arg')
275 lvl_fun (_, AnnCase _ _ _) = lvlMFE True ctxt_lvl env fun
276 lvl_fun other = lvlExpr ctxt_lvl env fun
277 -- We don't do MFE on partial applications generally,
278 -- but we do if the function is big and hairy, like a case
280 lvlExpr ctxt_lvl env (_, AnnNote InlineMe expr)
281 -- Don't float anything out of an InlineMe; hence the iNLINE_CTXT
282 = lvlExpr iNLINE_CTXT env expr `thenLvl` \ expr' ->
283 returnLvl (Note InlineMe expr')
285 lvlExpr ctxt_lvl env (_, AnnNote note expr)
286 = lvlExpr ctxt_lvl env expr `thenLvl` \ expr' ->
287 returnLvl (Note note expr')
289 -- We don't split adjacent lambdas. That is, given
291 -- we don't float to give
292 -- \x -> let v = x+y in \y -> (v,y)
293 -- Why not? Because partial applications are fairly rare, and splitting
294 -- lambdas makes them more expensive.
296 lvlExpr ctxt_lvl env expr@(_, AnnLam bndr rhs)
297 = lvlMFE True new_lvl new_env body `thenLvl` \ new_body ->
298 returnLvl (mkLams new_bndrs new_body)
300 (bndrs, body) = collectAnnBndrs expr
301 (new_lvl, new_bndrs) = lvlLamBndrs ctxt_lvl bndrs
302 new_env = extendLvlEnv env new_bndrs
303 -- At one time we called a special verion of collectBinders,
304 -- which ignored coercions, because we don't want to split
305 -- a lambda like this (\x -> coerce t (\s -> ...))
306 -- This used to happen quite a bit in state-transformer programs,
307 -- but not nearly so much now non-recursive newtypes are transparent.
308 -- [See SetLevels rev 1.50 for a version with this approach.]
310 lvlExpr ctxt_lvl env (_, AnnLet bind body)
311 = lvlBind NotTopLevel ctxt_lvl env bind `thenLvl` \ (bind', new_env) ->
312 lvlExpr ctxt_lvl new_env body `thenLvl` \ body' ->
313 returnLvl (Let bind' body')
315 lvlExpr ctxt_lvl env (_, AnnCase expr case_bndr alts)
316 = lvlMFE True ctxt_lvl env expr `thenLvl` \ expr' ->
318 alts_env = extendCaseBndrLvlEnv env expr' case_bndr incd_lvl
320 mapLvl (lvl_alt alts_env) alts `thenLvl` \ alts' ->
321 returnLvl (Case expr' (case_bndr, incd_lvl) alts')
323 incd_lvl = incMinorLvl ctxt_lvl
325 lvl_alt alts_env (con, bs, rhs)
326 = lvlMFE True incd_lvl new_env rhs `thenLvl` \ rhs' ->
327 returnLvl (con, bs', rhs')
329 bs' = [ (b, incd_lvl) | b <- bs ]
330 new_env = extendLvlEnv alts_env bs'
333 @lvlMFE@ is just like @lvlExpr@, except that it might let-bind
334 the expression, so that it can itself be floated.
337 lvlMFE :: Bool -- True <=> strict context [body of case or let]
338 -> Level -- Level of innermost enclosing lambda/tylam
339 -> LevelEnv -- Level of in-scope names/tyvars
340 -> CoreExprWithFVs -- input expression
341 -> LvlM LevelledExpr -- Result expression
343 lvlMFE strict_ctxt ctxt_lvl env (_, AnnType ty)
344 = returnLvl (Type ty)
346 lvlMFE strict_ctxt ctxt_lvl env ann_expr@(fvs, _)
347 | isUnLiftedType ty -- Can't let-bind it
348 || isInlineCtxt ctxt_lvl -- Don't float out of an __inline__ context
349 || exprIsTrivial expr -- Never float if it's trivial
350 || not good_destination
351 = -- Don't float it out
352 lvlExpr ctxt_lvl env ann_expr
354 | otherwise -- Float it out!
355 = lvlFloatRhs abs_vars dest_lvl env ann_expr `thenLvl` \ expr' ->
356 newLvlVar "lvl" abs_vars ty `thenLvl` \ var ->
357 returnLvl (Let (NonRec (var,dest_lvl) expr')
358 (mkVarApps (Var var) abs_vars))
360 expr = deAnnotate ann_expr
362 dest_lvl = destLevel env fvs (isFunction ann_expr)
363 abs_vars = abstractVars dest_lvl env fvs
365 -- A decision to float entails let-binding this thing, and we only do
366 -- that if we'll escape a value lambda, or will go to the top level.
368 | dest_lvl `ltMajLvl` ctxt_lvl -- Escapes a value lambda
369 = not (exprIsCheap expr) || isTopLvl dest_lvl
370 -- Even if it escapes a value lambda, we only
371 -- float if it's not cheap (unless it'll get all the
372 -- way to the top). I've seen cases where we
373 -- float dozens of tiny free expressions, which cost
374 -- more to allocate than to evaluate.
375 -- NB: exprIsCheap is also true of bottom expressions, which
376 -- is good; we don't want to share them
378 -- It's only Really Bad to float a cheap expression out of a
379 -- strict context, because that builds a thunk that otherwise
380 -- would never be built. So another alternative would be to
382 -- || (strict_ctxt && not (exprIsBottom expr))
383 -- to the condition above. We should really try this out.
385 | otherwise -- Does not escape a value lambda
386 = isTopLvl dest_lvl -- Only float if we are going to the top level
387 && floatConsts env -- and the floatConsts flag is on
388 && not strict_ctxt -- Don't float from a strict context
389 -- We are keen to float something to the top level, even if it does not
390 -- escape a lambda, because then it needs no allocation. But it's controlled
391 -- by a flag, because doing this too early loses opportunities for RULES
392 -- which (needless to say) are important in some nofib programs
393 -- (gcd is an example).
396 -- concat = /\ a -> foldr ..a.. (++) []
397 -- was getting turned into
398 -- concat = /\ a -> lvl a
399 -- lvl = /\ a -> foldr ..a.. (++) []
400 -- which is pretty stupid. Hence the strict_ctxt test
404 %************************************************************************
406 \subsection{Bindings}
408 %************************************************************************
410 The binding stuff works for top level too.
413 lvlBind :: TopLevelFlag -- Used solely to decide whether to clone
414 -> Level -- Context level; might be Top even for bindings nested in the RHS
415 -- of a top level binding
418 -> LvlM (LevelledBind, LevelEnv)
420 lvlBind top_lvl ctxt_lvl env (AnnNonRec bndr rhs@(rhs_fvs,_))
421 | isInlineCtxt ctxt_lvl -- Don't do anything inside InlineMe
422 = lvlExpr ctxt_lvl env rhs `thenLvl` \ rhs' ->
423 returnLvl (NonRec (bndr, ctxt_lvl) rhs', env)
426 = -- No type abstraction; clone existing binder
427 lvlExpr dest_lvl env rhs `thenLvl` \ rhs' ->
428 cloneVar top_lvl env bndr ctxt_lvl dest_lvl `thenLvl` \ (env', bndr') ->
429 returnLvl (NonRec (bndr', dest_lvl) rhs', env')
432 = -- Yes, type abstraction; create a new binder, extend substitution, etc
433 lvlFloatRhs abs_vars dest_lvl env rhs `thenLvl` \ rhs' ->
434 newPolyBndrs dest_lvl env abs_vars [bndr] `thenLvl` \ (env', [bndr']) ->
435 returnLvl (NonRec (bndr', dest_lvl) rhs', env')
438 bind_fvs = rhs_fvs `unionVarSet` idFreeVars bndr
439 abs_vars = abstractVars dest_lvl env bind_fvs
441 dest_lvl | isUnLiftedType (idType bndr) = destLevel env bind_fvs False `maxLvl` Level 1 0
442 | otherwise = destLevel env bind_fvs (isFunction rhs)
443 -- Hack alert! We do have some unlifted bindings, for cheap primops, and
444 -- it is ok to float them out; but not to the top level. If they would otherwise
445 -- go to the top level, we pin them inside the topmost lambda
450 lvlBind top_lvl ctxt_lvl env (AnnRec pairs)
451 | isInlineCtxt ctxt_lvl -- Don't do anything inside InlineMe
452 = mapLvl (lvlExpr ctxt_lvl env) rhss `thenLvl` \ rhss' ->
453 returnLvl (Rec ((bndrs `zip` repeat ctxt_lvl) `zip` rhss'), env)
456 = cloneRecVars top_lvl env bndrs ctxt_lvl dest_lvl `thenLvl` \ (new_env, new_bndrs) ->
457 mapLvl (lvlExpr ctxt_lvl new_env) rhss `thenLvl` \ new_rhss ->
458 returnLvl (Rec ((new_bndrs `zip` repeat dest_lvl) `zip` new_rhss), new_env)
460 | isSingleton pairs && count isId abs_vars > 1
461 = -- Special case for self recursion where there are
462 -- several variables carried around: build a local loop:
463 -- poly_f = \abs_vars. \lam_vars . letrec f = \lam_vars. rhs in f lam_vars
464 -- This just makes the closures a bit smaller. If we don't do
465 -- this, allocation rises significantly on some programs
467 -- We could elaborate it for the case where there are several
468 -- mutually functions, but it's quite a bit more complicated
470 -- This all seems a bit ad hoc -- sigh
472 (bndr,rhs) = head pairs
473 (rhs_lvl, abs_vars_w_lvls) = lvlLamBndrs dest_lvl abs_vars
474 rhs_env = extendLvlEnv env abs_vars_w_lvls
476 cloneVar NotTopLevel rhs_env bndr rhs_lvl rhs_lvl `thenLvl` \ (rhs_env', new_bndr) ->
478 (lam_bndrs, rhs_body) = collectAnnBndrs rhs
479 (body_lvl, new_lam_bndrs) = lvlLamBndrs rhs_lvl lam_bndrs
480 body_env = extendLvlEnv rhs_env' new_lam_bndrs
482 lvlExpr body_lvl body_env rhs_body `thenLvl` \ new_rhs_body ->
483 newPolyBndrs dest_lvl env abs_vars [bndr] `thenLvl` \ (poly_env, [poly_bndr]) ->
484 returnLvl (Rec [((poly_bndr,dest_lvl), mkLams abs_vars_w_lvls $
485 mkLams new_lam_bndrs $
486 Let (Rec [((new_bndr,rhs_lvl), mkLams new_lam_bndrs new_rhs_body)])
487 (mkVarApps (Var new_bndr) lam_bndrs))],
490 | otherwise -- Non-null abs_vars
491 = newPolyBndrs dest_lvl env abs_vars bndrs `thenLvl` \ (new_env, new_bndrs) ->
492 mapLvl (lvlFloatRhs abs_vars dest_lvl new_env) rhss `thenLvl` \ new_rhss ->
493 returnLvl (Rec ((new_bndrs `zip` repeat dest_lvl) `zip` new_rhss), new_env)
496 (bndrs,rhss) = unzip pairs
498 -- Finding the free vars of the binding group is annoying
499 bind_fvs = (unionVarSets [ idFreeVars bndr `unionVarSet` rhs_fvs
500 | (bndr, (rhs_fvs,_)) <- pairs])
504 dest_lvl = destLevel env bind_fvs (all isFunction rhss)
505 abs_vars = abstractVars dest_lvl env bind_fvs
507 ----------------------------------------------------
508 -- Three help functons for the type-abstraction case
510 lvlFloatRhs abs_vars dest_lvl env rhs
511 = lvlExpr rhs_lvl rhs_env rhs `thenLvl` \ rhs' ->
512 returnLvl (mkLams abs_vars_w_lvls rhs')
514 (rhs_lvl, abs_vars_w_lvls) = lvlLamBndrs dest_lvl abs_vars
515 rhs_env = extendLvlEnv env abs_vars_w_lvls
519 %************************************************************************
521 \subsection{Deciding floatability}
523 %************************************************************************
526 lvlLamBndrs :: Level -> [CoreBndr] -> (Level, [(CoreBndr, Level)])
527 -- Compute the levels for the binders of a lambda group
528 -- The binders returned are exactly the same as the ones passed,
529 -- but they are now paired with a level
533 lvlLamBndrs lvl bndrs
534 = go (incMinorLvl lvl)
535 False -- Havn't bumped major level in this group
538 go old_lvl bumped_major rev_lvld_bndrs (bndr:bndrs)
539 | isId bndr && -- Go to the next major level if this is a value binder,
540 not bumped_major && -- and we havn't already gone to the next level (one jump per group)
541 not (isOneShotLambda bndr) -- and it isn't a one-shot lambda
542 = go new_lvl True ((bndr,new_lvl) : rev_lvld_bndrs) bndrs
545 = go old_lvl bumped_major ((bndr,old_lvl) : rev_lvld_bndrs) bndrs
548 new_lvl = incMajorLvl old_lvl
550 go old_lvl _ rev_lvld_bndrs []
551 = (old_lvl, reverse rev_lvld_bndrs)
552 -- a lambda like this (\x -> coerce t (\s -> ...))
553 -- This happens quite a bit in state-transformer programs
557 -- Destintion level is the max Id level of the expression
558 -- (We'll abstract the type variables, if any.)
559 destLevel :: LevelEnv -> VarSet -> Bool -> Level
560 destLevel env fvs is_function
562 && is_function = tOP_LEVEL -- Send functions to top level; see
563 -- the comments with isFunction
564 | otherwise = maxIdLevel env fvs
566 isFunction :: CoreExprWithFVs -> Bool
567 -- The idea here is that we want to float *functions* to
568 -- the top level. This saves no work, but
569 -- (a) it can make the host function body a lot smaller,
570 -- and hence inlinable.
571 -- (b) it can also save allocation when the function is recursive:
572 -- h = \x -> letrec f = \y -> ...f...y...x...
575 -- f = \x y -> ...(f x)...y...x...
577 -- No allocation for f now.
578 -- We may only want to do this if there are sufficiently few free
579 -- variables. We certainly only want to do it for values, and not for
580 -- constructors. So the simple thing is just to look for lambdas
581 isFunction (_, AnnLam b e) | isId b = True
582 | otherwise = isFunction e
583 isFunction (_, AnnNote n e) = isFunction e
584 isFunction other = False
588 %************************************************************************
590 \subsection{Free-To-Level Monad}
592 %************************************************************************
595 type LevelEnv = (FloatOutSwitches,
596 VarEnv Level, -- Domain is *post-cloned* TyVars and Ids
597 Subst, -- Domain is pre-cloned Ids; tracks the in-scope set
598 -- so that subtitution is capture-avoiding
599 IdEnv ([Var], LevelledExpr)) -- Domain is pre-cloned Ids
600 -- We clone let-bound variables so that they are still
601 -- distinct when floated out; hence the SubstEnv/IdEnv.
602 -- (see point 3 of the module overview comment).
603 -- We also use these envs when making a variable polymorphic
604 -- because we want to float it out past a big lambda.
606 -- The SubstEnv and IdEnv always implement the same mapping, but the
607 -- SubstEnv maps to CoreExpr and the IdEnv to LevelledExpr
608 -- Since the range is always a variable or type application,
609 -- there is never any difference between the two, but sadly
610 -- the types differ. The SubstEnv is used when substituting in
611 -- a variable's IdInfo; the IdEnv when we find a Var.
613 -- In addition the IdEnv records a list of tyvars free in the
614 -- type application, just so we don't have to call freeVars on
615 -- the type application repeatedly.
617 -- The domain of the both envs is *pre-cloned* Ids, though
619 -- The domain of the VarEnv Level is the *post-cloned* Ids
621 initialEnv :: FloatOutSwitches -> LevelEnv
622 initialEnv float_lams = (float_lams, emptyVarEnv, emptySubst, emptyVarEnv)
624 floatLams :: LevelEnv -> Bool
625 floatLams (FloatOutSw float_lams _, _, _, _) = float_lams
627 floatConsts :: LevelEnv -> Bool
628 floatConsts (FloatOutSw _ float_consts, _, _, _) = float_consts
630 extendLvlEnv :: LevelEnv -> [(Var,Level)] -> LevelEnv
631 -- Used when *not* cloning
632 extendLvlEnv (float_lams, lvl_env, subst, id_env) prs
634 foldl add_lvl lvl_env prs,
635 foldl del_subst subst prs,
636 foldl del_id id_env prs)
638 add_lvl env (v,l) = extendVarEnv env v l
639 del_subst env (v,_) = extendInScope env v
640 del_id env (v,_) = delVarEnv env v
641 -- We must remove any clone for this variable name in case of
642 -- shadowing. This bit me in the following case
643 -- (in nofib/real/gg/Spark.hs):
646 -- ... -> case e of wild {
647 -- ... -> ... wild ...
651 -- The inside occurrence of @wild@ was being replaced with @ds@,
652 -- incorrectly, because the SubstEnv was still lying around. Ouch!
655 -- extendCaseBndrLvlEnv adds the mapping case-bndr->scrut-var if it can
656 -- (see point 4 of the module overview comment)
657 extendCaseBndrLvlEnv (float_lams, lvl_env, subst, id_env) (Var scrut_var) case_bndr lvl
659 extendVarEnv lvl_env case_bndr lvl,
660 extendSubst subst case_bndr (DoneEx (Var scrut_var)),
661 extendVarEnv id_env case_bndr ([scrut_var], Var scrut_var))
663 extendCaseBndrLvlEnv env scrut case_bndr lvl
664 = extendLvlEnv env [(case_bndr,lvl)]
666 extendPolyLvlEnv dest_lvl (float_lams, lvl_env, subst, id_env) abs_vars bndr_pairs
668 foldl add_lvl lvl_env bndr_pairs,
669 foldl add_subst subst bndr_pairs,
670 foldl add_id id_env bndr_pairs)
672 add_lvl env (v,v') = extendVarEnv env v' dest_lvl
673 add_subst env (v,v') = extendSubst env v (DoneEx (mkVarApps (Var v') abs_vars))
674 add_id env (v,v') = extendVarEnv env v ((v':abs_vars), mkVarApps (Var v') abs_vars)
676 extendCloneLvlEnv lvl (float_lams, lvl_env, _, id_env) new_subst bndr_pairs
678 foldl add_lvl lvl_env bndr_pairs,
680 foldl add_id id_env bndr_pairs)
682 add_lvl env (v,v') = extendVarEnv env v' lvl
683 add_id env (v,v') = extendVarEnv env v ([v'], Var v')
686 maxIdLevel :: LevelEnv -> VarSet -> Level
687 maxIdLevel (_, lvl_env,_,id_env) var_set
688 = foldVarSet max_in tOP_LEVEL var_set
690 max_in in_var lvl = foldr max_out lvl (case lookupVarEnv id_env in_var of
691 Just (abs_vars, _) -> abs_vars
695 | isId out_var = case lookupVarEnv lvl_env out_var of
696 Just lvl' -> maxLvl lvl' lvl
698 | otherwise = lvl -- Ignore tyvars in *maxIdLevel*
700 lookupVar :: LevelEnv -> Id -> LevelledExpr
701 lookupVar (_, _, _, id_env) v = case lookupVarEnv id_env v of
702 Just (_, expr) -> expr
705 abstractVars :: Level -> LevelEnv -> VarSet -> [Var]
706 -- Find the variables in fvs, free vars of the target expresion,
707 -- whose level is greater than the destination level
708 -- These are the ones we are going to abstract out
709 abstractVars dest_lvl env fvs
710 = uniq (sortLt lt [var | fv <- varSetElems fvs, var <- absVarsOf dest_lvl env fv])
712 -- Sort the variables so we don't get
713 -- mixed-up tyvars and Ids; it's just messy
714 v1 `lt` v2 = case (isId v1, isId v2) of
715 (True, False) -> False
716 (False, True) -> True
717 other -> v1 < v2 -- Same family
719 uniq :: [Var] -> [Var]
720 -- Remove adjacent duplicates; the sort will have brought them together
721 uniq (v1:v2:vs) | v1 == v2 = uniq (v2:vs)
722 | otherwise = v1 : uniq (v2:vs)
725 absVarsOf :: Level -> LevelEnv -> Var -> [Var]
726 -- If f is free in the expression, and f maps to poly_f a b c in the
727 -- current substitution, then we must report a b c as candidate type
729 absVarsOf dest_lvl (_, lvl_env, _, id_env) v
731 = [zap av2 | av1 <- lookup_avs v, av2 <- add_tyvars av1, abstract_me av2]
734 = if abstract_me v then [v] else []
737 abstract_me v = case lookupVarEnv lvl_env v of
738 Just lvl -> dest_lvl `ltLvl` lvl
741 lookup_avs v = case lookupVarEnv id_env v of
742 Just (abs_vars, _) -> abs_vars
745 add_tyvars v | isId v = v : varSetElems (idFreeTyVars v)
748 -- We are going to lambda-abstract, so nuke any IdInfo,
749 -- and add the tyvars of the Id (if necessary)
750 zap v | isId v = WARN( workerExists (idWorkerInfo v) ||
751 not (isEmptyCoreRules (idSpecialisation v)),
752 text "absVarsOf: discarding info on" <+> ppr v )
753 setIdInfo v vanillaIdInfo
758 type LvlM result = UniqSM result
767 newPolyBndrs dest_lvl env abs_vars bndrs
768 = getUniquesUs `thenLvl` \ uniqs ->
770 new_bndrs = zipWith mk_poly_bndr bndrs uniqs
772 returnLvl (extendPolyLvlEnv dest_lvl env abs_vars (bndrs `zip` new_bndrs), new_bndrs)
774 mk_poly_bndr bndr uniq = mkSysLocal (mkFastString str) uniq poly_ty
776 str = "poly_" ++ occNameUserString (getOccName bndr)
777 poly_ty = mkPiTypes abs_vars (idType bndr)
781 -> [CoreBndr] -> Type -- Abstract wrt these bndrs
783 newLvlVar str vars body_ty
784 = getUniqueUs `thenLvl` \ uniq ->
785 returnUs (mkSysLocal (mkFastString str) uniq (mkPiTypes vars body_ty))
787 -- The deeply tiresome thing is that we have to apply the substitution
788 -- to the rules inside each Id. Grr. But it matters.
790 cloneVar :: TopLevelFlag -> LevelEnv -> Id -> Level -> Level -> LvlM (LevelEnv, Id)
791 cloneVar TopLevel env v ctxt_lvl dest_lvl
792 = returnUs (env, v) -- Don't clone top level things
793 cloneVar NotTopLevel env@(_,_,subst,_) v ctxt_lvl dest_lvl
795 getUs `thenLvl` \ us ->
797 (subst', v1) = substAndCloneId subst us v
798 v2 = zap_demand ctxt_lvl dest_lvl v1
799 env' = extendCloneLvlEnv dest_lvl env subst' [(v,v2)]
803 cloneRecVars :: TopLevelFlag -> LevelEnv -> [Id] -> Level -> Level -> LvlM (LevelEnv, [Id])
804 cloneRecVars TopLevel env vs ctxt_lvl dest_lvl
805 = returnUs (env, vs) -- Don't clone top level things
806 cloneRecVars NotTopLevel env@(_,_,subst,_) vs ctxt_lvl dest_lvl
807 = ASSERT( all isId vs )
808 getUs `thenLvl` \ us ->
810 (subst', vs1) = substAndCloneRecIds subst us vs
811 vs2 = map (zap_demand ctxt_lvl dest_lvl) vs1
812 env' = extendCloneLvlEnv dest_lvl env subst' (vs `zip` vs2)
816 -- VERY IMPORTANT: we must zap the demand info
817 -- if the thing is going to float out past a lambda
818 zap_demand dest_lvl ctxt_lvl id
819 | ctxt_lvl == dest_lvl = id -- Stays put
820 | otherwise = zapDemandIdInfo id -- Floats out