2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 We attach binding levels to Core bindings, in preparation for floating
9 We also let-ify many applications (notably case scrutinees), so they
10 will have a fighting chance of being floated sensible.
18 incMinorLvl, ltMajLvl, ltLvl, isTopLvl
21 #include "HsVersions.h"
25 import CoreUtils ( coreExprType, exprIsTrivial, idFreeVars, exprIsBottom
27 import FreeVars -- all of it
28 import Id ( Id, idType, mkUserLocal )
29 import Name ( varOcc )
30 import Var ( IdOrTyVar )
33 import Type ( isUnLiftedType, mkTyVarTys, mkForAllTys, Type )
36 import UniqSupply ( initUs, thenUs, returnUs, mapUs, mapAndUnzipUs, getUniqueUs,
37 mapAndUnzip3Us, UniqSM, UniqSupply )
38 import Maybes ( maybeToBool )
39 import Util ( zipWithEqual, zipEqual, panic, assertPanic )
42 isLeakFreeType x y = False -- safe option; ToDo
45 %************************************************************************
47 \subsection{Level numbers}
49 %************************************************************************
53 = Top -- Means *really* the top level; short for (Level 0 0).
54 | Level Int -- Level number of enclosing lambdas
55 Int -- Number of big-lambda and/or case expressions between
56 -- here and the nearest enclosing lambda
59 The {\em level number} on a (type-)lambda-bound variable is the
60 nesting depth of the (type-)lambda which binds it. The outermost lambda
61 has level 1, so (Level 0 0) means that the variable is bound outside any lambda.
63 On an expression, it's the maximum level number of its free
64 (type-)variables. On a let(rec)-bound variable, it's the level of its
65 RHS. On a case-bound variable, it's the number of enclosing lambdas.
67 Top-level variables: level~0. Those bound on the RHS of a top-level
68 definition but ``before'' a lambda; e.g., the \tr{x} in (levels shown
71 a_0 = let b_? = ... in
72 x_1 = ... b ... in ...
75 Level 0 0 will make something get floated to a top-level "equals",
76 @Top@ makes it go right to the top.
78 The main function @lvlExpr@ carries a ``context level'' (@ctxt_lvl@).
79 That's meant to be the level number of the enclosing binder in the
80 final (floated) program. If the level number of a sub-expression is
81 less than that of the context, then it might be worth let-binding the
82 sub-expression so that it will indeed float. This context level starts
83 at @Level 0 0@; it is never @Top@.
86 type LevelledExpr = TaggedExpr Level
87 type LevelledArg = TaggedArg Level
88 type LevelledBind = TaggedBind Level
92 incMajorLvl :: Level -> Level
93 incMajorLvl Top = Level 1 0
94 incMajorLvl (Level major minor) = Level (major+1) 0
96 incMinorLvl :: Level -> Level
97 incMinorLvl Top = Level 0 1
98 incMinorLvl (Level major minor) = Level major (minor+1)
100 maxLvl :: Level -> Level -> Level
103 maxLvl l1@(Level maj1 min1) l2@(Level maj2 min2)
104 | (maj1 > maj2) || (maj1 == maj2 && min1 > min2) = l1
107 ltLvl :: Level -> Level -> Bool
109 ltLvl Top (Level _ _) = True
110 ltLvl (Level maj1 min1) (Level maj2 min2)
111 = (maj1 < maj2) || (maj1 == maj2 && min1 < min2)
113 ltMajLvl :: Level -> Level -> Bool
114 -- Tells if one level belongs to a difft *lambda* level to another
115 ltMajLvl l1 Top = False
116 ltMajLvl Top (Level 0 _) = False
117 ltMajLvl Top (Level _ _) = True
118 ltMajLvl (Level maj1 _) (Level maj2 _) = maj1 < maj2
120 isTopLvl :: Level -> Bool
122 isTopLvl other = False
124 isTopMajLvl :: Level -> Bool -- Tells if it's the top *lambda* level
125 isTopMajLvl Top = True
126 isTopMajLvl (Level maj _) = maj == 0
128 instance Outputable Level where
129 ppr Top = ptext SLIT("<Top>")
130 ppr (Level maj min) = hcat [ char '<', int maj, char ',', int min, char '>' ]
134 type LevelEnv = VarEnv Level
136 varLevel :: LevelEnv -> IdOrTyVar -> Level
138 = case lookupVarEnv env v of
142 maxIdLvl :: LevelEnv -> IdOrTyVar -> Level -> Level
143 maxIdLvl env var lvl | isTyVar var = lvl
144 | otherwise = case lookupVarEnv env var of
145 Just lvl' -> maxLvl lvl' lvl
148 maxTyVarLvl :: LevelEnv -> IdOrTyVar -> Level -> Level
149 maxTyVarLvl env var lvl | isId var = lvl
150 | otherwise = case lookupVarEnv env var of
151 Just lvl' -> maxLvl lvl' lvl
155 %************************************************************************
157 \subsection{Main level-setting code}
159 %************************************************************************
162 setLevels :: [CoreBind]
167 = initLvl us (do_them binds)
169 -- "do_them"'s main business is to thread the monad along
170 -- It gives each top binding the same empty envt, because
171 -- things unbound in the envt have level number zero implicitly
172 do_them :: [CoreBind] -> LvlM [LevelledBind]
174 do_them [] = returnLvl []
176 = lvlTopBind b `thenLvl` \ (lvld_bind, _) ->
177 do_them bs `thenLvl` \ lvld_binds ->
178 returnLvl (lvld_bind ++ lvld_binds)
180 initialEnv = emptyVarEnv
182 lvlTopBind (NonRec binder rhs)
183 = lvlBind Top initialEnv (AnnNonRec binder (freeVars rhs))
184 -- Rhs can have no free vars!
186 lvlTopBind (Rec pairs)
187 = lvlBind Top initialEnv (AnnRec [(b,freeVars rhs) | (b,rhs) <- pairs])
190 %************************************************************************
192 \subsection{Bindings}
194 %************************************************************************
196 The binding stuff works for top level too.
202 -> LvlM ([LevelledBind], LevelEnv)
204 lvlBind ctxt_lvl env (AnnNonRec name rhs)
205 = setFloatLevel (Just name) ctxt_lvl env rhs ty `thenLvl` \ (final_lvl, rhs') ->
207 new_env = extendVarEnv env name final_lvl
209 returnLvl ([NonRec (name, final_lvl) rhs'], new_env)
214 lvlBind ctxt_lvl env (AnnRec pairs)
215 = decideRecFloatLevel ctxt_lvl env binders rhss `thenLvl` \ (final_lvl, extra_binds, rhss') ->
217 binders_w_lvls = binders `zip` repeat final_lvl
218 new_env = extendVarEnvList env binders_w_lvls
220 returnLvl (extra_binds ++ [Rec (zipEqual "lvlBind" binders_w_lvls rhss')], new_env)
222 (binders,rhss) = unzip pairs
225 %************************************************************************
227 \subsection{Setting expression levels}
229 %************************************************************************
232 lvlExpr :: Level -- ctxt_lvl: Level of enclosing expression
233 -> LevelEnv -- Level of in-scope names/tyvars
234 -> CoreExprWithFVs -- input expression
235 -> LvlM LevelledExpr -- Result expression
238 The @ctxt_lvl@ is, roughly, the level of the innermost enclosing
243 v = \x -> ...\y -> let r = case (..x..) of
247 When looking at the rhs of @r@, @ctxt_lvl@ will be 1 because that's
248 the level of @r@, even though it's inside a level-2 @\y@. It's
249 important that @ctxt_lvl@ is 1 and not 2 in @r@'s rhs, because we
250 don't want @lvlExpr@ to turn the scrutinee of the @case@ into an MFE
251 --- because it isn't a *maximal* free expression.
253 If there were another lambda in @r@'s rhs, it would get level-2 as well.
256 lvlExpr _ _ (_, AnnType ty) = returnLvl (Type ty)
257 lvlExpr _ _ (_, AnnVar v) = returnLvl (Var v)
259 lvlExpr ctxt_lvl env (_, AnnCon con args)
260 = mapLvl (lvlExpr ctxt_lvl env) args `thenLvl` \ args' ->
261 returnLvl (Con con args')
263 lvlExpr ctxt_lvl env (_, AnnApp fun arg)
264 = lvlExpr ctxt_lvl env fun `thenLvl` \ fun' ->
265 lvlMFE ctxt_lvl env arg `thenLvl` \ arg' ->
266 returnLvl (App fun' arg')
268 lvlExpr ctxt_lvl env (_, AnnNote note expr)
269 = lvlExpr ctxt_lvl env expr `thenLvl` \ expr' ->
270 returnLvl (Note note expr')
272 -- We don't split adjacent lambdas. That is, given
274 -- we don't float to give
275 -- \x -> let v = x+y in \y -> (v,y)
276 -- Why not? Because partial applications are fairly rare, and splitting
277 -- lambdas makes them more expensive.
279 lvlExpr ctxt_lvl env (_, AnnLam bndr rhs)
280 = lvlMFE incd_lvl new_env body `thenLvl` \ body' ->
281 returnLvl (mkLams lvld_bndrs body')
283 bndr_is_id = isId bndr
284 bndr_is_tyvar = isTyVar bndr
285 (bndrs, body) = go rhs
287 incd_lvl | bndr_is_id = incMajorLvl ctxt_lvl
288 | otherwise = incMinorLvl ctxt_lvl
289 lvld_bndrs = [(b,incd_lvl) | b <- (bndr:bndrs)]
290 new_env = extendVarEnvList env lvld_bndrs
292 go (_, AnnLam bndr rhs) | bndr_is_id && isId bndr
293 || bndr_is_tyvar && isTyVar bndr
294 = case go rhs of { (bndrs, body) -> (bndr:bndrs, body) }
297 lvlExpr ctxt_lvl env (_, AnnLet bind body)
298 = lvlBind ctxt_lvl env bind `thenLvl` \ (binds', new_env) ->
299 lvlExpr ctxt_lvl new_env body `thenLvl` \ body' ->
300 returnLvl (mkLets binds' body')
302 lvlExpr ctxt_lvl env (_, AnnCase expr case_bndr alts)
303 = lvlMFE ctxt_lvl env expr `thenLvl` \ expr' ->
304 mapLvl lvl_alt alts `thenLvl` \ alts' ->
305 returnLvl (Case expr' (case_bndr, incd_lvl) alts')
307 expr_type = coreExprType (deAnnotate expr)
308 incd_lvl = incMinorLvl ctxt_lvl
309 alts_env = extendVarEnv env case_bndr incd_lvl
311 lvl_alt (con, bs, rhs)
313 bs' = [ (b, incd_lvl) | b <- bs ]
314 new_env = extendVarEnvList alts_env bs'
316 lvlMFE incd_lvl new_env rhs `thenLvl` \ rhs' ->
317 returnLvl (con, bs', rhs')
320 @lvlMFE@ is just like @lvlExpr@, except that it might let-bind
321 the expression, so that it can itself be floated.
324 lvlMFE :: Level -- Level of innermost enclosing lambda/tylam
325 -> LevelEnv -- Level of in-scope names/tyvars
326 -> CoreExprWithFVs -- input expression
327 -> LvlM LevelledExpr -- Result expression
329 lvlMFE ctxt_lvl env (_, AnnType ty)
330 = returnLvl (Type ty)
332 lvlMFE ctxt_lvl env ann_expr
333 | isUnLiftedType ty -- Can't let-bind it
334 = lvlExpr ctxt_lvl env ann_expr
336 | otherwise -- Not primitive type so could be let-bound
337 = setFloatLevel Nothing {- Not already let-bound -}
338 ctxt_lvl env ann_expr ty `thenLvl` \ (final_lvl, expr') ->
341 ty = coreExprType (deAnnotate ann_expr)
345 %************************************************************************
347 \subsection{Deciding floatability}
349 %************************************************************************
351 @setFloatLevel@ is used for let-bound right-hand-sides, or for MFEs which
352 are being created as let-bindings
356 YES. -> (a) try abstracting type variables.
357 If we abstract type variables it will go further, that is, past more
358 lambdas. same as asking if the level number given by the free
359 variables is less than the level number given by free variables
360 and type variables together.
361 Abstract offending type variables, e.g.
363 to let v = /\ty' -> f ty' a b
365 so that v' is not stopped by the level number of ty
366 tag the original let with its level number
367 (from its variables and type variables)
369 YES. -> No point in let binding to float a WHNF.
370 Pin (leave) expression here.
371 NO. -> Will float past a lambda?
372 (check using free variables only, not type variables)
373 YES. -> do the same as (a) above.
374 NO. -> No point in let binding if it is not going anywhere
375 Pin (leave) expression here.
378 setFloatLevel :: Maybe Id -- Just id <=> the expression is already let-bound to id
379 -- Nothing <=> it's a possible MFE
380 -> Level -- of context
383 -> CoreExprWithFVs -- Original rhs
384 -> Type -- Type of rhs
386 -> LvlM (Level, -- Level to attribute to this let-binding
387 LevelledExpr) -- Final rhs
389 setFloatLevel maybe_let_bound ctxt_lvl env expr@(expr_fvs, _) ty
391 -- Now deal with (by not floating) trivial non-let-bound expressions
392 -- which just aren't worth let-binding in order to float. We always
393 -- choose to float even trivial let-bound things because it doesn't do
394 -- any harm, and not floating it may pin something important. For
401 -- Here, if we don't float v we won't float w, which is Bad News.
402 -- If this gives any problems we could restrict the idea to things destined
405 | not alreadyLetBound
406 && (expr_is_trivial || expr_is_bottom || not will_float_past_lambda)
407 = -- Pin trivial non-let-bound expressions,
408 -- or ones which aren't going anywhere useful
409 lvlExpr ctxt_lvl env expr `thenLvl` \ expr' ->
410 returnLvl (ctxt_lvl, expr')
413 The above case used to read (whnf_or_bottom || not will_float_past_lambda).
414 It was changed because we really do want to float out constructors if possible:
415 this can save a great deal of needless allocation inside a loop. On the other
416 hand, there's no point floating out nullary constructors and literals, hence
417 the expr_is_trivial condition.
420 | alreadyLetBound && not worth_type_abstraction
421 = -- Process the expression with a new ctxt_lvl, obtained from
422 -- the free vars of the expression itself
423 lvlExpr expr_lvl env expr `thenLvl` \ expr' ->
424 returnLvl (expr_lvl, expr')
426 | otherwise -- This will create a let anyway, even if there is no
427 -- type variable to abstract, so we try to abstract anyway
428 = abstractWrtTyVars offending_tyvars ty env lvl_after_ty_abstr expr
429 `thenLvl` \ final_expr ->
430 returnLvl (expr_lvl, final_expr)
431 -- OLD LIE: The body of the let, just a type application, isn't worth floating
432 -- so pin it with ctxt_lvl
433 -- The truth: better to give it expr_lvl in case it is pinning
434 -- something non-trivial which depends on it.
436 alreadyLetBound = maybeToBool maybe_let_bound
438 fvs = case maybe_let_bound of
440 Just id -> expr_fvs `unionVarSet` idFreeVars id
442 ids_only_lvl = foldVarSet (maxIdLvl env) tOP_LEVEL fvs
443 tyvars_only_lvl = foldVarSet (maxTyVarLvl env) tOP_LEVEL fvs
444 expr_lvl = ids_only_lvl `maxLvl` tyvars_only_lvl
445 lvl_after_ty_abstr = ids_only_lvl --`maxLvl` non_offending_tyvars_lvl
447 -- Will escape lambda if let-bound
448 will_float_past_lambda = ids_only_lvl `ltMajLvl` ctxt_lvl
450 -- Will escape (more) lambda(s)/type lambda(s) if type abstracted
451 worth_type_abstraction = (ids_only_lvl `ltLvl` tyvars_only_lvl)
452 && not expr_is_trivial -- Avoids abstracting trivial type applications
454 offending_tyvars = filter offending_tv (varSetElems fvs)
455 offending_tv var | isId var = False
456 | otherwise = ids_only_lvl `ltLvl` varLevel env var
458 expr_is_trivial = exprIsTrivial de_ann_expr
459 expr_is_bottom = exprIsBottom de_ann_expr
460 de_ann_expr = deAnnotate expr
463 Abstract wrt tyvars, by making it just as if we had seen
468 instead of simply E. The idea is that v can be freely floated, since it
469 has no free type variables. Of course, if E has no free type
470 variables, then we just return E.
473 abstractWrtTyVars offending_tyvars ty env lvl expr
474 = lvlExpr incd_lvl new_env expr `thenLvl` \ expr' ->
475 newLvlVar poly_ty `thenLvl` \ poly_var ->
477 poly_var_rhs = mkLams tyvar_lvls expr'
478 poly_var_binding = NonRec (poly_var, lvl) poly_var_rhs
479 poly_var_app = mkTyApps (Var poly_var) (mkTyVarTys offending_tyvars)
480 final_expr = Let poly_var_binding poly_var_app -- mkCoLet* requires Core
484 poly_ty = mkForAllTys offending_tyvars ty
486 -- These defns are just like those in the TyLam case of lvlExpr
487 incd_lvl = incMinorLvl lvl
488 tyvar_lvls = [(tv,incd_lvl) | tv <- offending_tyvars]
489 new_env = extendVarEnvList env tyvar_lvls
492 Recursive definitions. We want to transform
504 x1' = /\ ab -> let D' in e1
506 xn' = /\ ab -> let D' in en
510 where ab are the tyvars pinning the defn further in than it
511 need be, and D is a bunch of simple type applications:
517 The "_cl" indicates that in D, the level numbers on the xi are the context level
518 number; type applications aren't worth floating. The D' decls are
525 but differ in their level numbers; here the ab are the newly-introduced
529 decideRecFloatLevel ctxt_lvl env ids rhss
530 | ids_only_lvl `ltLvl` tyvars_only_lvl
531 = -- Abstract wrt tyvars;
532 -- offending_tyvars is definitely non-empty
533 -- (I love the ASSERT to check this... WDP 95/02)
535 incd_lvl = incMinorLvl ids_only_lvl
536 tyvars_w_lvl = [(var,incd_lvl) | var <- offending_tyvars]
537 ids_w_lvl = [(var,incd_lvl) | var <- ids]
538 new_env = extendVarEnvList env (tyvars_w_lvl ++ ids_w_lvl)
540 mapLvl (lvlExpr incd_lvl new_env) rhss `thenLvl` \ rhss' ->
541 mapLvl newLvlVar poly_tys `thenLvl` \ poly_vars ->
543 ids_w_poly_vars = zipEqual "decideRec2" ids poly_vars
545 -- The "d_rhss" are the right-hand sides of "D" and "D'"
546 -- in the documentation above
547 d_rhss = [ mkTyApps (Var poly_var) offending_tyvar_tys | poly_var <- poly_vars]
549 -- "local_binds" are "D'" in the documentation above
550 local_binds = zipWithEqual "SetLevels" NonRec ids_w_lvl d_rhss
552 poly_var_rhss = [ mkLams tyvars_w_lvl (mkLets local_binds rhs')
556 poly_binds = zipEqual "poly_binds" [(poly_var, ids_only_lvl) | poly_var <- poly_vars]
560 returnLvl (ctxt_lvl, [Rec poly_binds], d_rhss)
561 -- The new right-hand sides, just a type application, aren't worth floating
562 -- so pin it with ctxt_lvl
565 = -- Let it float freely
567 ids_w_lvls = ids `zip` repeat expr_lvl
568 new_env = extendVarEnvList env ids_w_lvls
570 mapLvl (lvlExpr expr_lvl new_env) rhss `thenLvl` \ rhss' ->
571 returnLvl (expr_lvl, [], rhss')
574 -- Finding the free vars of the binding group is annoying
575 bind_fvs = (unionVarSets (map fst rhss) `unionVarSet` unionVarSets (map idFreeVars ids))
579 ids_only_lvl = foldVarSet (maxIdLvl env) tOP_LEVEL bind_fvs
580 tyvars_only_lvl = foldVarSet (maxTyVarLvl env) tOP_LEVEL bind_fvs
581 expr_lvl = ids_only_lvl `maxLvl` tyvars_only_lvl
583 offending_tyvars = filter offending_tv (varSetElems bind_fvs)
584 offending_tv var | isId var = False
585 | otherwise = ids_only_lvl `ltLvl` varLevel env var
586 offending_tyvar_tys = mkTyVarTys offending_tyvars
589 poly_tys = map (mkForAllTys offending_tyvars) tys
592 %************************************************************************
594 \subsection{Free-To-Level Monad}
596 %************************************************************************
599 type LvlM result = UniqSM result
605 mapAndUnzipLvl = mapAndUnzipUs
606 mapAndUnzip3Lvl = mapAndUnzip3Us
609 We create a let-binding for `interesting' (non-utterly-trivial)
610 applications, to give them a fighting chance of being floated.
613 newLvlVar :: Type -> LvlM Id
614 newLvlVar ty = getUniqueUs `thenLvl` \ uniq ->
615 returnUs (mkUserLocal (varOcc SLIT("lvl")) uniq ty)