{-# LANGUAGE PatternSynonyms #-} {-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-} {- (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 \section{GHC.Core.Opt.SetLevels} *************************** Overview *************************** 1. We attach binding levels to Core bindings, in preparation for floating outwards (@FloatOut@). 2. We also let-ify many expressions (notably case scrutinees), so they will have a fighting chance of being floated sensible. 3. Note [Need for cloning during float-out] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We clone the binders of any floatable let-binding, so that when it is floated out it will be unique. Example (let x=2 in x) + (let x=3 in x) we must clone before floating so we get let x1=2 in let x2=3 in x1+x2 NOTE: this can't be done using the uniqAway idea, because the variable must be unique in the whole program, not just its current scope, because two variables in different scopes may float out to the same top level place NOTE: Very tiresomely, we must apply this substitution to the rules stored inside a variable too. We do *not* clone top-level bindings, because some of them must not change, but we *do* clone bindings that are heading for the top level 4. Note [Binder-swap during float-out] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In the expression case x of wild { p -> ...wild... } we substitute x for wild in the RHS of the case alternatives: case x of wild { p -> ...x... } This means that a sub-expression involving x is not "trapped" inside the RHS. And it's not inconvenient because we already have a substitution. Note that this is EXACTLY BACKWARDS from the what the simplifier does. The simplifier tries to get rid of occurrences of x, in favour of wild, in the hope that there will only be one remaining occurrence of x, namely the scrutinee of the case, and we can inline it. -} module GHC.Core.Opt.SetLevels ( setLevels, Level(..), LevelType(..), tOP_LEVEL, isJoinCeilLvl, asJoinCeilLvl, LevelledBind, LevelledExpr, LevelledBndr, FloatSpec(..), floatSpecLevel, incMinorLvl, ltMajLvl, ltLvl, isTopLvl ) where import GHC.Prelude import GHC.Core import GHC.Core.Opt.Monad ( FloatOutSwitches(..) ) import GHC.Core.Utils ( exprType, exprIsHNF , exprOkForSpeculation , exprIsTopLevelBindable , collectMakeStaticArgs , mkLamTypes, extendInScopeSetBndrs ) import GHC.Core.Opt.Arity ( exprBotStrictness_maybe, isOneShotBndr ) import GHC.Core.FVs -- all of it import GHC.Core.Subst import GHC.Core.Make ( sortQuantVars ) import GHC.Core.Type ( Type, tyCoVarsOfType , mightBeUnliftedType, closeOverKindsDSet , typeHasFixedRuntimeRep ) import GHC.Core.Multiplicity ( pattern ManyTy ) import GHC.Types.Id import GHC.Types.Id.Info import GHC.Types.Var import GHC.Types.Var.Set import GHC.Types.Unique.Set ( nonDetStrictFoldUniqSet ) import GHC.Types.Unique.DSet ( getUniqDSet ) import GHC.Types.Var.Env import GHC.Types.Literal ( litIsTrivial ) import GHC.Types.Demand ( DmdSig, prependArgsDmdSig ) import GHC.Types.Cpr ( CprSig, prependArgsCprSig ) import GHC.Types.Name ( getOccName, mkSystemVarName ) import GHC.Types.Name.Occurrence ( occNameFS ) import GHC.Types.Unique ( hasKey ) import GHC.Types.Tickish ( tickishIsCode ) import GHC.Types.Unique.Supply import GHC.Types.Unique.DFM import GHC.Types.Basic ( Arity, RecFlag(..), isRec ) import GHC.Builtin.Types import GHC.Builtin.Names ( runRWKey ) import GHC.Data.FastString import GHC.Utils.FV import GHC.Utils.Misc import GHC.Utils.Outputable import GHC.Utils.Panic import GHC.Utils.Panic.Plain import Data.Maybe {- ************************************************************************ * * \subsection{Level numbers} * * ************************************************************************ -} type LevelledExpr = TaggedExpr FloatSpec type LevelledBind = TaggedBind FloatSpec type LevelledBndr = TaggedBndr FloatSpec data Level = Level Int -- Level number of enclosing lambdas Int -- Number of big-lambda and/or case expressions and/or -- context boundaries between -- here and the nearest enclosing lambda LevelType -- Binder or join ceiling? data LevelType = BndrLvl | JoinCeilLvl deriving (Eq) data FloatSpec = FloatMe Level -- Float to just inside the binding -- tagged with this level | StayPut Level -- Stay where it is; binding is -- tagged with this level floatSpecLevel :: FloatSpec -> Level floatSpecLevel (FloatMe l) = l floatSpecLevel (StayPut l) = l {- The {\em level number} on a (type-)lambda-bound variable is the nesting depth of the (type-)lambda which binds it. The outermost lambda has level 1, so (Level 0 0) means that the variable is bound outside any lambda. On an expression, it's the maximum level number of its free (type-)variables. On a let(rec)-bound variable, it's the level of its RHS. On a case-bound variable, it's the number of enclosing lambdas. Top-level variables: level~0. Those bound on the RHS of a top-level definition but ``before'' a lambda; e.g., the \tr{x} in (levels shown as ``subscripts'')... \begin{verbatim} a_0 = let b_? = ... in x_1 = ... b ... in ... \end{verbatim} The main function @lvlExpr@ carries a ``context level'' (@le_ctxt_lvl@). That's meant to be the level number of the enclosing binder in the final (floated) program. If the level number of a sub-expression is less than that of the context, then it might be worth let-binding the sub-expression so that it will indeed float. If you can float to level @Level 0 0@ worth doing so because then your allocation becomes static instead of dynamic. We always start with context @Level 0 0@. Note [FloatOut inside INLINE] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @InlineCtxt@ very similar to @Level 0 0@, but is used for one purpose: to say "don't float anything out of here". That's exactly what we want for the body of an INLINE, where we don't want to float anything out at all. See notes with lvlMFE below. But, check this out: -- At one time I tried the effect of not floating anything out of an InlineMe, -- but it sometimes works badly. For example, consider PrelArr.done. It -- has the form __inline (\d. e) -- where e doesn't mention d. If we float this to -- __inline (let x = e in \d. x) -- things are bad. The inliner doesn't even inline it because it doesn't look -- like a head-normal form. So it seems a lesser evil to let things float. -- In GHC.Core.Opt.SetLevels we do set the context to (Level 0 0) when we get to an InlineMe -- which discourages floating out. So the conclusion is: don't do any floating at all inside an InlineMe. (In the above example, don't float the {x=e} out of the \d.) One particular case is that of workers: we don't want to float the call to the worker outside the wrapper, otherwise the worker might get inlined into the floated expression, and an importing module won't see the worker at all. Note [Join ceiling] ~~~~~~~~~~~~~~~~~~~ Join points can't float very far; too far, and they can't remain join points So, suppose we have: f x = (joinrec j y = ... x ... in jump j x) + 1 One may be tempted to float j out to the top of f's RHS, but then the jump would not be a tail call. Thus we keep track of a level called the *join ceiling* past which join points are not allowed to float. The troublesome thing is that, unlike most levels to which something might float, there is not necessarily an identifier to which the join ceiling is attached. Fortunately, if something is to be floated to a join ceiling, it must be dropped at the *nearest* join ceiling. Thus each level is marked as to whether it is a join ceiling, so that FloatOut can tell which binders are being floated to the nearest join ceiling and which to a particular binder (or set of binders). -} instance Outputable FloatSpec where ppr (FloatMe l) = char 'F' <> ppr l ppr (StayPut l) = ppr l tOP_LEVEL :: Level tOP_LEVEL = Level 0 0 BndrLvl incMajorLvl :: Level -> Level incMajorLvl (Level major _ _) = Level (major + 1) 0 BndrLvl incMinorLvl :: Level -> Level incMinorLvl (Level major minor _) = Level major (minor+1) BndrLvl asJoinCeilLvl :: Level -> Level asJoinCeilLvl (Level major minor _) = Level major minor JoinCeilLvl maxLvl :: Level -> Level -> Level maxLvl l1@(Level maj1 min1 _) l2@(Level maj2 min2 _) | (maj1 > maj2) || (maj1 == maj2 && min1 > min2) = l1 | otherwise = l2 ltLvl :: Level -> Level -> Bool ltLvl (Level maj1 min1 _) (Level maj2 min2 _) = (maj1 < maj2) || (maj1 == maj2 && min1 < min2) ltMajLvl :: Level -> Level -> Bool -- Tells if one level belongs to a difft *lambda* level to another ltMajLvl (Level maj1 _ _) (Level maj2 _ _) = maj1 < maj2 isTopLvl :: Level -> Bool isTopLvl (Level 0 0 _) = True isTopLvl _ = False isJoinCeilLvl :: Level -> Bool isJoinCeilLvl (Level _ _ t) = t == JoinCeilLvl instance Outputable Level where ppr (Level maj min typ) = hcat [ char '<', int maj, char ',', int min, char '>' , ppWhen (typ == JoinCeilLvl) (char 'C') ] instance Eq Level where (Level maj1 min1 _) == (Level maj2 min2 _) = maj1 == maj2 && min1 == min2 {- ************************************************************************ * * \subsection{Main level-setting code} * * ************************************************************************ -} setLevels :: FloatOutSwitches -> CoreProgram -> UniqSupply -> [LevelledBind] setLevels float_lams binds us = initLvl us (do_them binds) where env = initialEnv float_lams binds do_them :: [CoreBind] -> LvlM [LevelledBind] do_them [] = return [] do_them (b:bs) = do { lvld_bind <- lvlTopBind env b ; lvld_binds <- do_them bs ; return (lvld_bind : lvld_binds) } lvlTopBind :: LevelEnv -> Bind Id -> LvlM LevelledBind lvlTopBind env (NonRec bndr rhs) = do { (bndr', rhs') <- lvl_top env NonRecursive bndr rhs ; return (NonRec bndr' rhs') } lvlTopBind env (Rec pairs) = do { prs' <- mapM (\(b,r) -> lvl_top env Recursive b r) pairs ; return (Rec prs') } lvl_top :: LevelEnv -> RecFlag -> Id -> CoreExpr -> LvlM (LevelledBndr, LevelledExpr) -- NB: 'env' has all the top-level binders in scope, so -- there is no need call substAndLvlBndrs here lvl_top env is_rec bndr rhs = do { rhs' <- lvlRhs env is_rec (isDeadEndId bndr) Nothing -- Not a join point (freeVars rhs) ; return (stayPut tOP_LEVEL bndr, rhs') } {- ************************************************************************ * * \subsection{Setting expression levels} * * ************************************************************************ Note [Floating over-saturated applications] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If we see (f x y), and (f x) is a redex (ie f's arity is 1), we call (f x) an "over-saturated application" Should we float out an over-sat app, if can escape a value lambda? It is sometimes very beneficial (-7% runtime -4% alloc over nofib -O2). But we don't want to do it for class selectors, because the work saved is minimal, and the extra local thunks allocated cost money. Arguably we could float even class-op applications if they were going to top level -- but then they must be applied to a constant dictionary and will almost certainly be optimised away anyway. -} lvlExpr :: LevelEnv -- Context -> CoreExprWithFVs -- Input expression -> LvlM LevelledExpr -- Result expression {- The @le_ctxt_lvl@ is, roughly, the level of the innermost enclosing binder. Here's an example v = \x -> ...\y -> let r = case (..x..) of ..x.. in .. When looking at the rhs of @r@, @le_ctxt_lvl@ will be 1 because that's the level of @r@, even though it's inside a level-2 @\y@. It's important that @le_ctxt_lvl@ is 1 and not 2 in @r@'s rhs, because we don't want @lvlExpr@ to turn the scrutinee of the @case@ into an MFE --- because it isn't a *maximal* free expression. If there were another lambda in @r@'s rhs, it would get level-2 as well. -} lvlExpr env (_, AnnType ty) = return (Type (substTyUnchecked (le_subst env) ty)) lvlExpr env (_, AnnCoercion co) = return (Coercion (substCo (le_subst env) co)) lvlExpr env (_, AnnVar v) = return (lookupVar env v) lvlExpr _ (_, AnnLit lit) = return (Lit lit) lvlExpr env (_, AnnCast expr (_, co)) = do expr' <- lvlNonTailExpr env expr return (Cast expr' (substCo (le_subst env) co)) lvlExpr env (_, AnnTick tickish expr) = do expr' <- lvlNonTailExpr env expr let tickish' = substTickish (le_subst env) tickish return (Tick tickish' expr') lvlExpr env expr@(_, AnnApp _ _) = lvlApp env expr (collectAnnArgs expr) -- We don't split adjacent lambdas. That is, given -- \x y -> (x+1,y) -- we don't float to give -- \x -> let v = x+1 in \y -> (v,y) -- Why not? Because partial applications are fairly rare, and splitting -- lambdas makes them more expensive. lvlExpr env expr@(_, AnnLam {}) = do { new_body <- lvlNonTailMFE new_env True body ; return (mkLams new_bndrs new_body) } where (bndrs, body) = collectAnnBndrs expr (env1, bndrs1) = substBndrsSL NonRecursive env bndrs (new_env, new_bndrs) = lvlLamBndrs env1 (le_ctxt_lvl env) bndrs1 -- At one time we called a special version of collectBinders, -- which ignored coercions, because we don't want to split -- a lambda like this (\x -> coerce t (\s -> ...)) -- This used to happen quite a bit in state-transformer programs, -- but not nearly so much now non-recursive newtypes are transparent. -- [See GHC.Core.Opt.SetLevels rev 1.50 for a version with this approach.] lvlExpr env (_, AnnLet bind body) = do { (bind', new_env) <- lvlBind env bind ; body' <- lvlExpr new_env body -- No point in going via lvlMFE here. If the binding is alive -- (mentioned in body), and the whole let-expression doesn't -- float, then neither will the body ; return (Let bind' body') } lvlExpr env (_, AnnCase scrut case_bndr ty alts) = do { scrut' <- lvlNonTailMFE env True scrut ; lvlCase env (freeVarsOf scrut) scrut' case_bndr ty alts } lvlNonTailExpr :: LevelEnv -- Context -> CoreExprWithFVs -- Input expression -> LvlM LevelledExpr -- Result expression lvlNonTailExpr env expr = lvlExpr (placeJoinCeiling env) expr ------------------------------------------- lvlApp :: LevelEnv -> CoreExprWithFVs -> (CoreExprWithFVs, [CoreExprWithFVs]) -- Input application -> LvlM LevelledExpr -- Result expression lvlApp env orig_expr ((_,AnnVar fn), args) -- Try to ensure that runRW#'s continuation isn't floated out. -- See Note [Simplification of runRW#]. | fn `hasKey` runRWKey = do { args' <- mapM (lvlExpr env) args ; return (foldl' App (lookupVar env fn) args') } | floatOverSat env -- See Note [Floating over-saturated applications] , arity > 0 , arity < n_val_args , Nothing <- isClassOpId_maybe fn = do { rargs' <- mapM (lvlNonTailMFE env False) rargs ; lapp' <- lvlNonTailMFE env False lapp ; return (foldl' App lapp' rargs') } | otherwise = do { args' <- mapM (lvlMFE env False) args -- False: see "Arguments" in Note [Floating to the top] ; return (foldl' App (lookupVar env fn) args') } where n_val_args = count (isValArg . deAnnotate) args arity = idArity fn -- Separate out the PAP that we are floating from the extra -- arguments, by traversing the spine until we have collected -- (n_val_args - arity) value arguments. (lapp, rargs) = left (n_val_args - arity) orig_expr [] left 0 e rargs = (e, rargs) left n (_, AnnApp f a) rargs | isValArg (deAnnotate a) = left (n-1) f (a:rargs) | otherwise = left n f (a:rargs) left _ _ _ = panic "GHC.Core.Opt.SetLevels.lvlExpr.left" lvlApp env _ (fun, args) = -- No PAPs that we can float: just carry on with the -- arguments and the function. do { args' <- mapM (lvlNonTailMFE env False) args ; fun' <- lvlNonTailExpr env fun ; return (foldl' App fun' args') } ------------------------------------------- lvlCase :: LevelEnv -- Level of in-scope names/tyvars -> DVarSet -- Free vars of input scrutinee -> LevelledExpr -- Processed scrutinee -> Id -> Type -- Case binder and result type -> [CoreAltWithFVs] -- Input alternatives -> LvlM LevelledExpr -- Result expression lvlCase env scrut_fvs scrut' case_bndr ty alts -- See Note [Floating single-alternative cases] | [AnnAlt con@(DataAlt {}) bs body] <- alts , exprIsHNF (deTagExpr scrut') -- See Note [Check the output scrutinee for exprIsHNF] , not (isTopLvl dest_lvl) -- Can't have top-level cases , not (floatTopLvlOnly env) -- Can float anywhere , ManyTy <- idMult case_bndr -- See Note [Floating linear case] = -- Always float the case if possible -- Unlike lets we don't insist that it escapes a value lambda do { (env1, (case_bndr' : bs')) <- cloneCaseBndrs env dest_lvl (case_bndr : bs) ; let rhs_env = extendCaseBndrEnv env1 case_bndr scrut' ; body' <- lvlMFE rhs_env True body ; let alt' = Alt con (map (stayPut dest_lvl) bs') body' ; return (Case scrut' (TB case_bndr' (FloatMe dest_lvl)) ty' [alt']) } | otherwise -- Stays put = do { let (alts_env1, [case_bndr']) = substAndLvlBndrs NonRecursive env incd_lvl [case_bndr] alts_env = extendCaseBndrEnv alts_env1 case_bndr scrut' ; alts' <- mapM (lvl_alt alts_env) alts ; return (Case scrut' case_bndr' ty' alts') } where ty' = substTyUnchecked (le_subst env) ty incd_lvl = incMinorLvl (le_ctxt_lvl env) dest_lvl = maxFvLevel (const True) env scrut_fvs -- Don't abstract over type variables, hence const True lvl_alt alts_env (AnnAlt con bs rhs) = do { rhs' <- lvlMFE new_env True rhs ; return (Alt con bs' rhs') } where (new_env, bs') = substAndLvlBndrs NonRecursive alts_env incd_lvl bs {- Note [Floating single-alternative cases] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this: data T a = MkT !a f :: T Int -> blah f x vs = case x of { MkT y -> let f vs = ...(case y of I# w -> e)...f.. in f vs Here we can float the (case y ...) out, because y is sure to be evaluated, to give f x vs = case x of { MkT y -> case y of I# w -> let f vs = ...(e)...f.. in f vs That saves unboxing it every time round the loop. It's important in some DPH stuff where we really want to avoid that repeated unboxing in the inner loop. Things to note: * The test we perform is exprIsHNF, and /not/ exprOkForSpeculation. - exrpIsHNF catches the key case of an evaluated variable - exprOkForSpeculation is /false/ of an evaluated variable; See Note [exprOkForSpeculation and evaluated variables] in GHC.Core.Utils So we'd actually miss the key case! - Nothing is gained from the extra generality of exprOkForSpeculation since we only consider floating a case whose single alternative is a DataAlt K a b -> rhs * We can't float a case to top level * It's worth doing this float even if we don't float the case outside a value lambda. Example case x of { MkT y -> (case y of I# w2 -> ..., case y of I# w2 -> ...) If we floated the cases out we could eliminate one of them. * We only do this with a single-alternative case Note [Floating linear case] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Linear case can't be floated past case branches: case u of { p1 -> case[1] v of { C x -> ...x...}; p2 -> ... } Is well typed, but case[1] v of { C x -> case u of { p1 -> ...x...; p2 -> ... }} Will not be, because of how `x` is used in one alternative but not the other. It is not easy to float this linear cases precisely, so, instead, we elect, for the moment, to simply not float linear case. Note [Setting levels when floating single-alternative cases] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Handling level-setting when floating a single-alternative case binding is a bit subtle, as evidenced by #16978. In particular, we must keep in mind that we are merely moving the case and its binders, not the body. For example, suppose 'a' is known to be evaluated and we have \z -> case a of (x,_) ->
After floating we may have: case a of (x,_) -> \z -> {- some expression involving x and z -} When analysing we want to use the /ambient/ level, and /not/ the destination level of the 'case a of (x,-) ->' binding. #16978 was caused by us setting the context level to the destination level of `x` when analysing . This led us to conclude that we needed to quantify over some of its free variables (e.g. z), resulting in shadowing and very confusing Core Lint failures. Note [Check the output scrutinee for exprIsHNF] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this: case x of y { A -> ....(case y of alts).... } Because of the binder-swap, the inner case will get substituted to (case x of ..). So when testing whether the scrutinee is in HNF we must be careful to test the *result* scrutinee ('x' in this case), not the *input* one 'y'. The latter *is* in HNF here (because y is evaluated), but the former is not -- and indeed we can't float the inner case out, at least not unless x is also evaluated at its binding site. See #5453. That's why we apply exprIsHNF to scrut' and not to scrut. See Note [Floating single-alternative cases] for why we use exprIsHNF in the first place. -} lvlNonTailMFE :: LevelEnv -- Level of in-scope names/tyvars -> Bool -- True <=> strict context [body of case -- or let] -> CoreExprWithFVs -- input expression -> LvlM LevelledExpr -- Result expression lvlNonTailMFE env strict_ctxt ann_expr = lvlMFE (placeJoinCeiling env) strict_ctxt ann_expr lvlMFE :: LevelEnv -- Level of in-scope names/tyvars -> Bool -- True <=> strict context [body of case or let] -> CoreExprWithFVs -- input expression -> LvlM LevelledExpr -- Result expression -- lvlMFE is just like lvlExpr, except that it might let-bind -- the expression, so that it can itself be floated. lvlMFE env _ (_, AnnType ty) = return (Type (substTyUnchecked (le_subst env) ty)) -- No point in floating out an expression wrapped in a coercion or note -- If we do we'll transform lvl = e |> co -- to lvl' = e; lvl = lvl' |> co -- and then inline lvl. Better just to float out the payload. lvlMFE env strict_ctxt (_, AnnTick t e) = do { e' <- lvlMFE env strict_ctxt e ; let t' = substTickish (le_subst env) t ; return (Tick t' e') } lvlMFE env strict_ctxt (_, AnnCast e (_, co)) = do { e' <- lvlMFE env strict_ctxt e ; return (Cast e' (substCo (le_subst env) co)) } lvlMFE env strict_ctxt e@(_, AnnCase {}) | strict_ctxt -- Don't share cases in a strict context = lvlExpr env e -- See Note [Case MFEs] lvlMFE env strict_ctxt ann_expr | floatTopLvlOnly env && not (isTopLvl dest_lvl) -- Only floating to the top level is allowed. || hasFreeJoin env fvs -- If there is a free join, don't float -- See Note [Free join points] || not (typeHasFixedRuntimeRep (exprType expr)) -- We can't let-bind an expression if we don't know -- how it will be represented at runtime. -- See Note [Representation polymorphism invariants] in GHC.Core || notWorthFloating expr abs_vars || not float_me = -- Don't float it out lvlExpr env ann_expr | float_is_new_lam || exprIsTopLevelBindable expr expr_ty -- No wrapping needed if the type is lifted, or is a literal string -- or if we are wrapping it in one or more value lambdas = do { expr1 <- lvlFloatRhs abs_vars dest_lvl rhs_env NonRecursive is_bot_lam join_arity_maybe ann_expr -- Treat the expr just like a right-hand side ; var <- newLvlVar expr1 join_arity_maybe is_mk_static ; let var2 = annotateBotStr var float_n_lams mb_bot_str ; return (Let (NonRec (TB var2 (FloatMe dest_lvl)) expr1) (mkVarApps (Var var2) abs_vars)) } -- OK, so the float has an unlifted type (not top-level bindable) -- and no new value lambdas (float_is_new_lam is False) -- Try for the boxing strategy -- See Note [Floating MFEs of unlifted type] | escapes_value_lam , not expr_ok_for_spec -- Boxing/unboxing isn't worth it for cheap expressions -- See Note [Test cheapness with exprOkForSpeculation] , BI_Box { bi_data_con = box_dc, bi_inst_con = boxing_expr , bi_boxed_type = box_ty } <- boxingDataCon expr_ty , let [bx_bndr, ubx_bndr] = mkTemplateLocals [box_ty, expr_ty] = do { expr1 <- lvlExpr rhs_env ann_expr ; let l1r = incMinorLvlFrom rhs_env float_rhs = mkLams abs_vars_w_lvls $ Case expr1 (stayPut l1r ubx_bndr) box_ty [Alt DEFAULT [] (App boxing_expr (Var ubx_bndr))] ; var <- newLvlVar float_rhs Nothing is_mk_static ; let l1u = incMinorLvlFrom env use_expr = Case (mkVarApps (Var var) abs_vars) (stayPut l1u bx_bndr) expr_ty [Alt (DataAlt box_dc) [stayPut l1u ubx_bndr] (Var ubx_bndr)] ; return (Let (NonRec (TB var (FloatMe dest_lvl)) float_rhs) use_expr) } | otherwise -- e.g. do not float unboxed tuples = lvlExpr env ann_expr where expr = deAnnotate ann_expr expr_ty = exprType expr fvs = freeVarsOf ann_expr fvs_ty = tyCoVarsOfType expr_ty is_bot_lam = isJust mb_bot_str -- True of bottoming thunks too! is_function = isFunction ann_expr mb_bot_str = exprBotStrictness_maybe expr -- See Note [Bottoming floats] -- esp Bottoming floats (2) expr_ok_for_spec = exprOkForSpeculation expr abs_vars = abstractVars dest_lvl env fvs dest_lvl = destLevel env fvs fvs_ty is_function is_bot_lam False -- NB: is_bot_lam not is_bot; see (3) in -- Note [Bottoming floats] -- float_is_new_lam: the floated thing will be a new value lambda -- replacing, say (g (x+4)) by (lvl x). No work is saved, nor is -- allocation saved. The benefit is to get it to the top level -- and hence out of the body of this function altogether, making -- it smaller and more inlinable float_is_new_lam = float_n_lams > 0 float_n_lams = count isId abs_vars (rhs_env, abs_vars_w_lvls) = lvlLamBndrs env dest_lvl abs_vars join_arity_maybe = Nothing is_mk_static = isJust (collectMakeStaticArgs expr) -- Yuk: See Note [Grand plan for static forms] in GHC.Iface.Tidy.StaticPtrTable -- A decision to float entails let-binding this thing, and we only do -- that if we'll escape a value lambda, or will go to the top level. float_me = saves_work || saves_alloc || is_mk_static -- We can save work if we can move a redex outside a value lambda -- But if float_is_new_lam is True, then the redex is wrapped in a -- a new lambda, so no work is saved saves_work = escapes_value_lam && not float_is_new_lam escapes_value_lam = dest_lvl `ltMajLvl` (le_ctxt_lvl env) -- See Note [Escaping a value lambda] -- See Note [Floating to the top] saves_alloc = isTopLvl dest_lvl && floatConsts env && ( not strict_ctxt -- (a) || exprIsHNF expr -- (b) || (is_bot_lam && escapes_value_lam)) -- (c) hasFreeJoin :: LevelEnv -> DVarSet -> Bool -- Has a free join point which is not being floated to top level. -- (In the latter case it won't be a join point any more.) -- Not treating top-level ones specially had a massive effect -- on nofib/minimax/Prog.prog hasFreeJoin env fvs = not (maxFvLevel isJoinId env fvs == tOP_LEVEL) {- Note [Floating to the top] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Suppose saves_work is False, i.e. - 'e' does not escape a value lambda (escapes_value_lam), or - 'e' would have added value lambdas if floated (float_is_new_lam) Then we may still be keen to float a sub-expression 'e' to the top level, for two reasons: (i) Doing so makes the function smaller, by floating out bottoming expressions, or integer or string literals. That in turn makes it easier to inline, with less duplication. This only matters if the floated sub-expression is inside a value-lambda, which in turn may be easier to inline. (ii) (Minor) Doing so may turn a dynamic allocation (done by machine instructions) into a static one. Minor because we are assuming we are not escaping a value lambda. But only do so if (saves_alloc): (a) the context is lazy (so we get allocation), or (b) the expression is a HNF (so we get allocation), or (c) the expression is bottoming and (i) applies (NB: if the expression is a lambda, (b) will apply; so this case only catches bottoming thunks) Examples: * (a) Strict. Case scrutinee f = case g True of .... Don't float (g True) to top level; then we have the admin of a top-level thunk to worry about, with zero gain. * (a) Strict. Case alternative h = case y of True -> g True False -> False Don't float (g True) to the top level * (b) HNF f = case y of True -> p:q False -> blah We may as well float the (p:q) so it becomes a static data structure. * (c) Bottoming expressions; see also Note [Bottoming floats] f x = case x of 0 -> error _ -> x+1 Here we want to float (error ) to top level, abstracting over 'x', so as to make f's RHS smaller. But (#22494) if it's more like foo = case error