Simon Peyton Jones pushed to branch wip/case-bndr-unf at Glasgow Haskell Compiler / GHC Commits: 1045f6c7 by Simon Peyton Jones at 2026-11-25T09:12:37+00:00 Add splitThunkCpr This commit adds GHC.Core.Opt.WorkWrap.splitThunkCpr, which adds a form of "thunk splitting" for strict bindings that have CPR information. See Note [Thunk splitting] in WorkWrap.hs for the details. It catches a previously-unrecognised optimisation opportunity (see #28158) but it only helps in fairly obscure cases, so I don't expect a big impact in practice. As usually I did lots of refactoring along the way. LLM disclosure: lots of interaction with Claude, but I wrote all the code and comments. - - - - - 9 changed files: - compiler/GHC/Core/Opt/CprAnal.hs - compiler/GHC/Core/Opt/Simplify/Iteration.hs - compiler/GHC/Core/Opt/WorkWrap.hs - compiler/GHC/Core/Opt/WorkWrap/Utils.hs - compiler/GHC/Types/Cpr.hs - compiler/GHC/Utils/Monad.hs - + testsuite/tests/simplCore/should_compile/T28158.hs - + testsuite/tests/simplCore/should_compile/T28158.stderr - testsuite/tests/simplCore/should_compile/all.T Changes: ===================================== compiler/GHC/Core/Opt/CprAnal.hs ===================================== @@ -173,6 +173,25 @@ So currently we have 1. Strictness 2. CPR 3. worker/wrapper (for strictness and CPR) + +Wrinkles + +(CPR1) We have a flag `-fcpr-anal`, which sets `Opt_CprAnal`, enabled in -O1 and + -O1. Strangely, it does /not/ switch off CPR analysis! Rather, it just + switches off the worker/wrapper exploitation of CPR analysis, in `mkWWcpr_entry`. + The analysis itself runes whenever `-fstrictness` is on. + + This is peculiar and, I suspect accidental. It would make more sense to switch + off the analysis itself with `-fno-cpr-anal`. + + It goes back to at least + commit ecb1752ffa12dfa71053f640e6cce64d15e47e8f + Author: Christiaan Baaij <christiaan.baaij@gmail.com> + Date: Wed Aug 5 14:22:14 2015 +0200 + + Make -fcpr-off a dynamic flag + + This note is just a breadcrumb to inform the next person who trips over this. -} -- @@ -343,7 +362,7 @@ cprTransform env id args -- Any local binding, except for data structure bindings -- See Note [Efficient Top sigs in SigEnv] | Just sig <- lookupSigEnv env id - = applyCprTy (getCprSig sig) (length args) + = applyCprTy (cprSigType sig) (length args) -- See Note [CPR for data structures] | Just rhs <- cprDataStructureUnfolding_maybe id = fst $ cprAnal env rhs @@ -362,7 +381,7 @@ cprTransform env id args = cprTransformDataConWork env con args -- Imported function | otherwise - = applyCprTy (getCprSig (idCprSig id)) (length args) + = applyCprTy (cprSigType (idCprSig id)) (length args) -- | Precise, hand-written CPR transformers for select Ids cprTransformBespoke :: Id -> [(CprType, CoreArg)] -> Maybe CprType @@ -870,27 +889,42 @@ Does f have the CPR property? Well, no. However, if the strictness analyser has figured out (in a previous iteration) that it's strict, then we DON'T need to forget the CPR info. Instead we can retain the CPR info and do the thunk-splitting transform -(see WorkWrap.splitThunk). +(see Note [Thunk splitting] esp (B) CPR-led thunk splitting). This made a big difference to PrelBase.modInt, which had something like modInt = \ x -> let r = ... -> I# v in ...body strict in r... -r's RHS isn't a value yet; but modInt returns r in various branches, so -if r doesn't have the CPR property then neither does modInt +r's RHS isn't a value yet; but `modInt` returns `r` in various branches, so +if `r` doesn't have the CPR property then neither does `modInt` + Another case I found in practice (in Complex.magnitude), looks like this: - let k = if ... then I# a else I# b - in ... body strict in k .... + let k* = if ... then I# a else I# b + in ... body strict in k .... (For this example, it doesn't matter whether k is returned as part of the overall result; but it does matter that k's RHS has the CPR property.) + Left to itself, the simplifier will make a join point thus: - let $j k = ...body strict in k... - if ... then $j (I# a) else $j (I# b) + let $j k = ...body strict in k... + if ... then $j (I# a) else $j (I# b) + With thunk-splitting, we get instead - let $j x = let k = I#x in ...body strict in k... - in if ... then $j a else $j b + let k* = case (if ... then I# a else I# b) of I# z -> I# z + in ... body strict in k .... +Now the simplifier should pull out the `case` to give + case (if ... then I# a else I# b) of I# z -> + let k = I# z in ... body strict in k ... +Now case-of-if will give + let $j z = let k = I# z in ...body strict in k... in + if ... then $j a else $j b This is much better; there's a good chance the I# won't get allocated. +TL'DR: During CPR analysis we want to give `k` the CPR property in `body`. + +What if the type involved has more than one constructor? E.g. + let k* = if ... then Just a else Just b + in ... body strict in k .... +That is good too: see (TS5) in Note [Thunk splitting] -But what about botCpr? Consider +Finally, what about botCpr? Consider lvl = error "boom" fac -1 = lvl fac 0 = 1 ===================================== compiler/GHC/Core/Opt/Simplify/Iteration.hs ===================================== @@ -51,7 +51,6 @@ import GHC.Types.Literal ( litIsLifted ) --, mkLitInt ) -- temporarily comment import GHC.Types.SourceText import GHC.Types.Id import GHC.Types.Id.Info -import GHC.Types.Cpr( isTopCprSig ) import GHC.Types.InlinePragma import GHC.Types.Name ( mkSystemVarName, isExternalName, getOccFS ) import GHC.Types.Demand @@ -1830,7 +1829,7 @@ simplNonRecE :: HasDebugCallStack simplNonRecE env from_what bndr (rhs, rhs_se) body cont | assertPpr (isId bndr && not (isJoinId bndr)) (ppr bndr) True - , useStrictBind env from_what bndr + , useStrictBind env from_what bndr rhs = -- Evaluate RHS strictly simplExprF (rhs_se `setInScopeFromE` env) rhs (StrictBind { sc_bndr = bndr, sc_body = body, sc_from = from_what @@ -1865,11 +1864,10 @@ simplRecE env pairs body cont ; return (floats1 `addFloats` floats2, expr') } -useStrictBind :: SimplEnv -> FromWhat -> InId -> Bool +useStrictBind :: SimplEnv -> FromWhat -> InId -> InExpr -> Bool -- Can we use a StrictBind continuation for this let-binding? --- If so, return a binder that is suitable to become a lambda binder, --- i.e. one satisfying `lamBndrInfoOK`; see (SB3) in Note [StrictBind] -useStrictBind env from_what bndr +-- See (SB3) in Note [StrictBind] +useStrictBind env from_what bndr rhs -- If we are coming from a beta-reduction (FromBeta) we must -- establish the let-can-float invariant, so we must go via StrictBind -- If not, the invariant holds already, and it's optional. @@ -1880,6 +1878,10 @@ useStrictBind env from_what bndr | not (isStrUsedDmd dmd_info) = False + -- Not if the RHS is ok-for-spec; no benefit + | exprOkForSpeculation rhs + = False + -- Not if case-of-case is off -- See (SB1) in Note [StrictBind] | not (seCaseCase env) @@ -1894,8 +1896,6 @@ useStrictBind env from_what bndr | isStableUnfolding (unfoldingInfo info) || not (isEmptyRuleInfo (ruleInfo info)) || not (isAlwaysActive (inlinePragmaActivation (inlinePragInfo info))) - || not (isNopSig (dmdSigInfo info)) - || not (isTopCprSig (cprSigInfo info)) = False | otherwise @@ -4243,9 +4243,8 @@ mkDupableAlt _env case_bndr jfloats (Alt con alt_bndrs alt_rhs_in) , alt') } -- See Note [Duplicated env] -{- -Note [Do not add unfoldings to join points at birth] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +{- Note [Do not add unfoldings to join points at birth] +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this (#15360) case (case (case (case ...))) of @@ -4316,7 +4315,7 @@ The simplifier will find (Var v) with continuation Select (pn -> rn) ( Select [I# a -> I# a] ( - StrictBind body Stop + StrictBind body Stop)) So we'll call mkDupableCont on Select [I# a -> I# a] (StrictBind body Stop) @@ -4455,7 +4454,7 @@ hack and bit us in multiple small and not-so-small ways Consider this case (case .. ) of c { - I# c# -> ....c.... + I# c# -> ....c.... } If we make a join point with c but not c# we get $j = \c -> ....c.... @@ -4655,30 +4654,43 @@ We simplify `rhs` with a StrictBind continuation that continues with invariants] in GHC.Core. But a let-binder `x` usually has IdInfo that a lambda binder may not have (an unfolding, arity, a demand signature...). - So `useStrictBind_maybe` zaps that info, keeping only the occurrence info - and the demand info. If it happens to stay as a let-binding arity info will - be re-derived, so nothing is lost. + So when we duplicate StrictBind, in `mkDupableContWithDmds`, we use + `mkLamBndrFromLetBndr` to zap that info, keeping only the occurrence + info and the demand info. - The exceptions are RULES, a stable unfolding, and a non-default inlining - activation: these cannot be re-derived, and we have nowhere convenient to - put them if `x` becomes a lambda binder. For example: + However, if the let-binder has + * RULES + * a stable unfolding + * a non-default inlining activation + we'd permanently lose these things if we lambda-bind it. For example: let {-# NOINLINE x #-} x! = case y of { ... } in blah - If we make a join point j x = blah, we have nowhere convenient - to put that NOINLINE. Ditto INLINE or RULES. So in these cases we - simply don't use StrictBind. It's very unusual, so no harm done. - But it does happen; one example is this, in the Applicative (ST s) - instance in GHC.Internal.Control.Monad.St.Lazy.Imp + If we make a join point j x = blah, we have nowhere convenient to put that + NOINLINE. Ditto INLINE or RULES. It's unusual. But it happens; one example + is the Applicative (ST s) instance in GHC.Internal.Control.Monad.St.Lazy.Imp {-# NOINLINE res1 #-} !res1 = unST fm s - TL;DR: the sc_bndr::Id field in StrictBind always satisfies `lamBndrInfoOK`. - This means that in the above example { x! = case y of ... } we won't - float the `case y` out. And perhaps that's fine because of the NOINLNE. - We could imagine instead imposing these conditions only when we /duplicate/ - the StrictBind, rather than when we /create/ it, but that would require a - bigger refactor. + So in these cases we simply don't use StrictBind -- see `useStrictBind`. We + could imagine instead imposing these conditions only when we /duplicate/ the + StrictBind, rather than when we /create/ it, but that would require a bigger + refactor. + + What if a thunk has a strictness signature, or CPR information? We + could make `useStrictBind` say False in these cases too, but that turns + out to be a net loss: keeping a thunk is worse than losing the strictness + information. Example, where f1,f2 are both strict: + let f* {- Str=<S> -} = case x of { True -> f1; False -> f2 } + in body + Keeping it as-is would use CBV for calls of `f` in `body`. But + allowing StrictBind would give us + join j f* = body + in case x of { True -> j f1; False -> j f2 } + which avoids the thunk. It's a trade-off. + + For CPR info, see Note [Thunk splitting] in GHC.Core.Opt.WorkWrap, + especially (B) CPR-led thunk splitting. Note [Join point abstraction] Historical note ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ===================================== compiler/GHC/Core/Opt/WorkWrap.hs ===================================== @@ -598,13 +598,19 @@ tryWW ww_opts is_rec fn_id rhs = splitFun ww_opts new_fn_id rhs -- See Note [Thunk splitting] - | isNonRec is_rec, is_thunk - = splitThunk ww_opts is_rec new_fn_id rhs + | isNonRec is_rec -- See (TS4) + , is_thunk -- All join points go via splitFun + = do { -- Try strictness then CPR; see (TS5) + rhs' <- splitThunkStr ww_opts new_fn_id rhs `orElseM` + splitThunkCpr ww_opts new_fn_id rhs `orElseM` + return rhs + ; return [ (new_fn_id, rhs') ] } | otherwise = return [ (new_fn_id, rhs) ] where + is_join = isJoinId fn_id fn_info = idInfo fn_id (wrap_dmds, _) = splitDmdSig (dmdSigInfo fn_info) new_fn_id = zap_join_cpr $ zap_usage fn_id @@ -613,14 +619,13 @@ tryWW ww_opts is_rec fn_id rhs -- See Note [Zapping DmdEnv after Demand Analyzer] and -- See Note [Zapping Used Once info in WorkWrap] - zap_join_cpr id - | isJoinId id = id `setIdCprSig` topCprSig - | otherwise = id + zap_join_cpr id | is_join = id `setIdCprSig` topCprSig + | otherwise = id -- See Note [Don't w/w join points for CPR] - is_fun = notNull wrap_dmds || isJoinId fn_id - is_thunk = not is_fun && not (exprIsHNF rhs) && not (isJoinId fn_id) - && not (isUnliftedType (idType fn_id)) + is_fun = notNull wrap_dmds || is_join + is_thunk = not (exprIsHNF rhs) + && not (isUnliftedType (idType fn_id)) {- Note [Zapping DmdEnv after Demand Analyzer] @@ -806,7 +811,7 @@ splitFun ww_opts fn_id rhs (wrap_dmds, div) = splitDmdSig (dmdSigInfo fn_info) - cpr_ty = getCprSig (cprSigInfo fn_info) + cpr_ty = cprSigType (cprSigInfo fn_info) -- Arity of the CPR sig should match idArity when it's not a join point. -- See Note [Arity trimming for CPR signatures] in GHC.Core.Opt.CprAnal cpr = assertPpr (isJoinId fn_id || cpr_ty == topCprType || ct_arty cpr_ty == arityInfo fn_info) @@ -957,114 +962,177 @@ the form [Demand=<L,1*(C(1,...(C(1,U))))>] Note [Thunk splitting] ~~~~~~~~~~~~~~~~~~~~~~ -Suppose x is used strictly; never mind whether it has the CPR -property. I'll use a '*' to mean "x* is demanded strictly". - - let - x* = x-rhs +The worker/wrapper split mainly affects let-bound /functions/. But we can also use +demand and CPR information to improve let-bound /thunks/. Specifically: + +* (A) Demand-led thunk splitting: + If a thunk is demanded strictly, perhaps nestedly, we can turn it into a + case, perhaps nestedly. For example + let x :: (Int, Int) + {- Dmd = SP(S,L) -} + x = rhs + in body + We would ultimately like to get + case rhs of x { (a,b) -> + case a of { I# a# -> + body + + This is much better: no thunk for `rhs`; and known-data-con unfoldings for `x` + and `a` inside `body`. + +* (B) CPR-led thunk splitting: + If a thunk has the (possibly-nested) CPR property /and/ is demanded strictly + at top level, we can again generate a case + let x :: (Int, Int) + {- Dmd = S, Cpr = (_, I# _) -} + x = rhs + in body + The CPR info says that if `x` is evaluated (which it is), it'll return a pair, + whose second component can very cheaply be evaluated to a (I# b#). We would + like to end up with + case rhs of x { (a,b) -> + case b of { I# b# -> + body + which is good for the same reasons as before. See (TS3) for an example. + +Implementation +~~~~~~~~~~~~~~ +The worker/wrapper pass does not generate these nested case expressions directly. +Instead it generates a regular let-binding but, since the binder is marked as +strict, any `case` expressions in the RHS will float out. Specifically: + +(TS1) For (A), `splitThunkStr` generates the binding + let x! = case rhs of { (a,b) -> + case a of { I# a# -> + (I# a, b) + Now when the Simplifier floats the `case` expressions out, we get + case rhs of { (a,b) -> + case a of { I# a# -> + let x = (I# a, b) in body + which is equivalent to the expression in (A) above. -splitThunk transforms like this: - let - x* = let x = x-rhs in - case x of { I# a -> I# a } - in body + `splitThunkStr` also works on /absent/ thunks: see (TS6). -This is a little strange: we are re-using the same `x` in the RHS; and -the RHS takes `x` apart and reboxes it. But because the outer 'let' is -strict, and the inner let mentions `x` only once, the simplifier -transform it to - case x-rhs of - I# a -> let x* = I# a - in body - -That is good: in `body` we know the form of `x`, which - * gives the CPR property, and - * allows case-of-case to happen on x - -Notes -* I tried transforming like this: - let - x* = let x = x-rhs in - case x of { I# a -> x } - in body - where I return `x` itself, rather than reboxing it. But this - turned out to cause some regressions, which I never fully - investigated. - -* Suppose x-rhs is itself a case: - x-rhs = case e of { T -> I# e1; F -> I# e2 } - Then we'll get - join j a = let x* = I# a in body - in case e of { T -> j e1; F -> j e2 } - which is good (no boxing). But in the original, unsplit program - we would transform - let x* = case e of ... in body - ==> join j2 x = body - in case e of { T -> j2 (I# e1); F -> j (I# e2) } - which is not good (boxing). + Rather cleverly, `splitThunkStr` uses `mkWWstr_one`, the /existing/ function + argument w/w splitting function, to do the unpacking. This automatically + deals with nested strictness. -* In fact, splitThunk uses the function argument w/w splitting - function, mkWWstr_one, so that if x's demand is deeper (say U(U(L,L),L)) - then the splitting will go deeper too. +(TS2) For (B), `splitThunkCpr` behaves exactly analogously, again + using `mkWWcpr_one` to do the unpacking. It works only for /demanded/ thunks. -* For recursive thunks, the Simplifier is unable to float `x-rhs` out of - `x*`'s RHS, because `x*` occurs freely in `x-rhs`, and will just change it - back to the original definition, so we just split non-recursive thunks. +Wrinkles: -Note [Thunk splitting for top-level binders] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Top-level bindings are never strict. Yet they can be absent, as T14270 shows: - - module T14270 (mkTrApp) where - mkTrApp x y - | Just ... <- ... typeRepKind x ... - = undefined - | otherwise - = undefined - typeRepKind = Tick scc undefined - -(T19180 is a profiling-free test case for this) -Note that `typeRepKind` is not exported and its only use site in -`mkTrApp` guards a bottoming expression. Thus, demand analysis -figures out that `typeRepKind` is absent and splits the thunk to - - typeRepKind = - let typeRepKind = Tick scc undefined in - let typeRepKind = absentError in - typeRepKind - -But now we have a local binding with an External Name -(See Note [About the NameSorts]). That will trigger a CoreLint error, which we -get around by localising the Id for the auxiliary bindings in 'splitThunk'. +(TS3) Here's an example of (B), thunk-splitting based on CPR information. + Suppose we have + let x! = case e of { T -> Just e1; F -> Just e2 } + in body + If the Simplifier floats the `case` out, we get + join j2 x = body + in case e of { T -> j2 (Just e1); F -> j2 (Just e2) } + which is not good (boxing). + + If we first do the thunk-splitting transformation, we get + let x! = case (case e of { T -> Just e1; F -> Just e2 }) of + Just a -> Just a + in body + + Now when the Simplifier floats we will get: + join j a = let x = Just a in body + in case e of { T -> j e1; F -> j e2 } + which is much better (no boxing). + +(TS4) We only do thunk-splitting for thunks that are non-recursive + For recursive thunks, the Simplifier is unable to float `rhs` out of + x's RHS, because `x` occurs freely in `rhs`, and will just change it + back to the original definition. + +(TS5) Notice that (B) CPR-led thunk splitting can be useful: + * when multi-constructor data types are involved, so that the argument-unboxing + mechanism (A) is impotent. See the example in (TS3), which uses `Maybe`. + * when the binder is only demanded head-strictly, but CPR has nested information. + + So (A) and (B) have complementary benefits. We might do even better by + /combining/ (A) and (B), but at the moment we try (A) first, and then try (B) + if (A) is impotent. Combining them would be more work. + +(TS6) We can also exploit /absence/. Consider + let x {-# Dmd = A #-} = rhs + in body + Generally speaking `x` will be absent becuase it is passed to functions that + don't use it, in which case worker/wrapper on those calls will make `x` unused. + But suppose `x` is absent inside a /lazy/ argument: + let f p = (fst p, 99) in + let x = rhs in + f (True, x) + Here f's argument is lazy, but `x` is definitely absent, and we could replace + `x` with an absent filler. Using (TS1) would give us + let x = absentError "urk" in ... + which is great. + + So `splitThunkStr` works /regardless/ of the demand on `x`; whether it fires is + determined only by the `useful` flag returned by `mkWWstr_one`. + +(TS7) Adopting (TS6) leads to one other complication: a top-level binder with + an External Name (see Note [About the NameSorts]) can be Absent. If so, + it must not be used as a local binder in the `Let` created by `splitThunkStr`. + T19180 is a test case for this rather obscure situation. + + Solution: use `localiseId` to localise the binder for the `Let`. + +(TS8) Consider out poster child test case for `splitThunkCpr`, in (TS3). + x! = case e of { True -> Just 1; False -> Just 2 } + But suppose we have `-fworker-wrapper-cbv` enabled (reminder: see + Note [Worker/wrapper for strict arguments]). Then alas `splitThunkStr` + will fire, but it'll be a no-op in this case. But since it fires, `splitThunkCpr` + never gets a chance. + + Hacky but effective solution: switch off `wo_unlift_strict` locally in `splitThunkStr`. -} --- | See Note [Thunk splitting]. --- --- splitThunk converts the *non-recursive* binding +-- | splitThunkStr converts the *non-recursive* binding -- x = e -- into --- x = let x' = e in --- case x' of I# y -> let x' = I# y in x' --- See comments above. Is it not beautifully short? --- Moreover, it works just as well when there are --- several binders, and if the binders are lifted --- E.g. x = e --- --> x = let x' = e in --- case x' of (a,b) -> let x' = (a,b) in x' --- Here, x' is a localised version of x, in case x is a --- top-level Id with an External Name, because Lint rejects local binders with --- External Names; see Note [About the NameSorts] in GHC.Types.Name. --- --- How can we do thunk-splitting on a top-level binder? See --- Note [Thunk splitting for top-level binders]. -splitThunk :: WwOpts -> RecFlag -> Var -> Expr Var -> UniqSM [(Var, Expr Var)] -splitThunk ww_opts is_rec x rhs - = assert (not (isJoinId x)) $ - do { let x' = localiseId x -- See comment above - ; (useful,_args, wrap_fn, fn_arg) - <- mkWWstr_one ww_opts x' NotMarkedStrict - ; let res = [ (x, Let (NonRec x' rhs) (wrap_fn fn_arg)) ] - ; if useful then assertPpr (isNonRec is_rec) (ppr x) -- The thunk must be non-recursive - return res - else return [(x, rhs)] } +-- x = let x = e in +-- case x of I# y -> I# y +-- See Note [Thunk splitting]. +splitThunkStr :: WwOpts -> Var -> CoreExpr -> UniqSM (Maybe CoreExpr) +splitThunkStr ww_opts x rhs + = -- NB: does not depend on x's demand being strict; it might be absent, see (TS6) + do { let x' = localiseId x -- See (TS7) + ww_opts' = ww_opts { wo_unlift_strict = False } -- See (TS8) + ; (useful, _transit_vars, wrap_fn, fn_arg) <- mkWWstr_one ww_opts' x' NotMarkedStrict + -- Use mkWWstr_one: see (TS1) in Note [Thunk splitting] + + ; if useful + then return (Just (Let (NonRec x' rhs) $ + wrap_fn fn_arg)) + else return Nothing } + +splitThunkCpr :: WwOpts -> Var -> CoreExpr -> UniqSM (Maybe CoreExpr) +-- See Note [Thunk splitting] +-- Given x* = rhs, where x* is used outermost-strictly, and x* has a (nested) CPR +-- property, say Just (Just _), return this new RHS: +-- let x' = rhs in +-- case x' of { Just p -> case p of { Just q -> -- Unpacking code +-- Just (Just q) }} -- Repacking code +-- Works for multi-constructor data types, where splitThunkStr will fail +splitThunkCpr ww_opts x rhs + | wo_cpr_anal ww_opts -- See (CPR1) in Note [Phase ordering] on GHC.Opt.CprAnal + , isStrUsedDmd (idDemandInfo x) -- See (TS2) + = assertPpr (cprTypeArity cpr_type == 0) (ppr x) $ -- It's a thunk + do { (useful, _transit_vars, rebuild_result, unpacker) <- mkWWcpr_one ww_opts x cpr + -- Use mkWWcpr_one: see (TS2) in Note [Thunk splitting] + ; if useful + then return (Just (Let (NonRec x rhs) $ + unpacker rebuild_result)) + else return Nothing } + + | otherwise + = return Nothing + where + cpr_type :: CprType + cpr_type = cprSigType (idCprSig x) + cpr :: Cpr + cpr = cprTypeCpr cpr_type + ===================================== compiler/GHC/Core/Opt/WorkWrap/Utils.hs ===================================== @@ -8,7 +8,7 @@ A library for the ``worker\/wrapper'' back-end to the strictness analyser {-# LANGUAGE ViewPatterns #-} module GHC.Core.Opt.WorkWrap.Utils - ( WwOpts(..), mkWwBodies, mkWWstr, mkWWstr_one + ( WwOpts(..), mkWwBodies, mkWWstr, mkWWstr_one, mkWWcpr_one , needsVoidWorkerArg , DataConPatContext(..) , UnboxingDecision(..), canUnboxArg @@ -139,13 +139,18 @@ data WwOpts = MkWwOpts { -- | Environment of type/data family instances wo_fam_envs :: !FamInstEnvs + , -- | Options for the "Simple optimiser" wo_simple_opts :: !SimpleOpts + , -- | Whether to enable "Constructed Product Result" analysis. -- (Originally from DOI: 10.1017/S0956796803004751) + -- See (CPR1) in Note [Phase ordering] on GHC.Opt.CprAnal wo_cpr_anal :: !Bool + , -- | Used for absent argument error message wo_module :: !Module + , -- | Generate workers even if the only effect is some args get passed -- unlifted. See Note [WW for calling convention] wo_unlift_strict :: !Bool } @@ -230,8 +235,7 @@ mkWwBodies opts fun_id ww_arity arg_vars res_ty demands res_cpr ; let (work_args, work_marks) = unzip work_args_str -- Do CPR w/w. See Note [Always do CPR w/w] - ; (useful2, wrap_fn_cpr, work_fn_cpr) - <- mkWWcpr_entry opts res_ty' res_cpr + ; (useful2, wrap_fn_cpr, work_fn_cpr) <- mkWWcpr_entry opts res_ty' res_cpr ; let (work_lam_args, work_call_args, work_call_str) | needsVoidWorkerArg fun_id arg_vars work_args @@ -662,8 +666,10 @@ canUnboxResult fam_envs ty cpr = DontUnbox where - -- See Note [non-algebraic or open body type warning] - open_body_ty_warning = warnPprTrace True "canUnboxResult: non-algebraic or open body type" (ppr ty) Nothing + -- See Note [Non-algebraic or open body type warning] + open_body_ty_warning + = warnPprTrace True "canUnboxResult: non-algebraic or open body type" + (ppr ty) Nothing @@ -808,7 +814,7 @@ match the number of constructor arguments; this happened in #8037. If so, the worker/wrapper split doesn't work right and we get a Core Lint bug. The fix here is simply to decline to do w/w if that happens. -Note [non-algebraic or open body type warning] +Note [Non-algebraic or open body type warning] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ There are a few cases where the W/W transformation is told that something returns a constructor, but the type at hand doesn't really match this. One @@ -829,8 +835,60 @@ This warning also triggers for the stream fusion library within `text`. We can't easily W/W constructed results like `Stream` because we have no simple way to express existential types in the worker's type signature. +Note [Worker/wrapper for strict arguments] +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Consider + f x = case x of + [] -> blah + (y:ys) -> f ys + +Clearly `f` is strict, but its argument is not a product type, so by default +we don't worker/wrapper it. But it is arguably valuable to do so. We could +do this: + + f x = case x of xx { DEFAULT -> $wf xx } + $wf xx = case xx of + [] -> blah + (y:ys) -> f ys + +Now the worker `$wf` knows that its argument `xx` will be evaluated +and properly tagged, so the code for the `case xx` does not need to do +an "eval" (see `GHC.StgToCmm.Expr.cgCase`). A call (f (a:as)) will +have the wrapper inlined, and will drop the `case x`, so no eval +happens at all. + +The worker `$wf` is a CBV function (see `Note [CBV Function Ids: overview]` +in GHC.Types.Id.Info) and the code generator guarantees that every +call to `$wf` has a properly tagged argument (see `GHC.Stg.EnforceEpt.Rewrite`). + +Is this a win? Not always: +* It can cause slight code size increases. This is since we push evals to every + call sites which there might be many. And the evals will only disappear at + call sites where we already known that the argument is evaluated. + +* It will also cause many more functions to get a worker/wrapper split + which can play badly with rules (see Ticket #20364). In particular + if you depend on rules firing on functions marked as NOINLINE + without marking use sites of these functions as INLINE or INLINEABLE + then things will break. + + But if you want a function to match in a RULE, it is /in any case/ good + practice to have a `INLINE[1]` or `NOINLNE[1]` pragma, to ensure that it + doesn't inline until the rule has had a chance to fire. + +So there is a flag, `-fworker-wrapper-cbv`, to control whether we do +w/w on strict arguments (internally `Opt_WorkerWrapperUnlift`). The +flag is off by default. The choice is made in +GHC.Core.Opt.WorkWrap.Utils.wwUseForUnlifting + +See also `Note [WW for calling convention]` + Note [WW for calling convention] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + NB: This Note is more of a discussion. + Read Note [Worker/wrapper for strict arguments] first, + which covers the same ground with more precision + If we know a function f will always evaluate a particular argument we might decide that it should rather get evaluated by the caller. We call this "unlifting" the argument. @@ -856,10 +914,9 @@ Hence we have the following strategies with different trade-offs: A) Never do W/W *just* for unlifting of arguments. + Very conservative - doesn't break any rules - - Lot's of performance left on the table + - Lots of performance left on the table -B) Do W/W on just about anything where it might be - beneficial. +B) Do W/W on just about anything where it might be beneficial. + Exploits pretty much every opportunity for unlifting. - A bit of compile time/code size cost for all the wrappers. - Can break rules which would otherwise fire. See #20364. @@ -883,10 +940,10 @@ C) Unlift *any* (non-boot exported) functions arguments if they are strict. functionality. I haven't tried this approach because it's not trivial to implement and doing W/W splits seems to work well enough. -Currently we use the first approach A) by default, with a flag that allows users -to fall back to the more aggressive approach B). +Currently we use the first approach (A) by default, with a flag `-fworker-wrapper-cbv` +that allows users to fall back to the more aggressive approach (B). -I also tried the third approach C) using eta-expansion at call sites to avoid +I also tried the third approach (C) using eta-expansion at call sites to avoid modifying the PAP-handling code which wasn't fruitful. See https://gitlab.haskell.org/ghc/ghc/-/merge_requests/5614#note_389903. We could still try to do C) in the future by having PAP calls which will evaluate the @@ -895,53 +952,6 @@ be neither a small nor simple change so we stick with A) and a flag for B) for now. See also Note [EPT enforcement] and Note [CBV Function Ids: overview] - -Note [Worker/wrapper for strict arguments] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Consider - f x = case x of - [] -> blah - (y:ys) -> f ys - -Clearly `f` is strict, but its argument is not a product type, so by default -we don't worker/wrapper it. But it is arguably valuable to do so. We could -do this: - - f x = case x of xx { DEFAULT -> $wf xx } - $wf xx = case xx of - [] -> blah - (y:ys) -> f ys - -Now the worker `$wf` knows that its argument `xx` will be evaluated -and properly tagged, so the code for the `case xx` does not need to do -an "eval" (see `GHC.StgToCmm.Expr.cgCase`). A call (f (a:as)) will -have the wrapper inlined, and will drop the `case x`, so no eval -happens at all. - -The worker `$wf` is a CBV function (see `Note [CBV Function Ids: overview]` -in GHC.Types.Id.Info) and the code generator guarantees that every -call to `$wf` has a properly tagged argument (see `GHC.Stg.EnforceEpt.Rewrite`). - -Is this a win? Not always: -* It can cause slight codesize increases. This is since we push evals to every - call sites which there might be many. And the evals will only disappear at - call sites where we already known that the argument is evaluated. - -* It will also cause many more functions to get a worker/wrapper split - which can play badly with rules (see Ticket #20364). In particular - if you depend on rules firing on functions marked as NOINLINE - without marking use sites of these functions as INLINE or INLINEABLE - then things will break. - But if you want a function to match in a RULE, it is /in any case/ good practice to - have a `INLINE[1]` or `NOINLNE[1]` pragma, to ensure that it doesn't inline until - the rule has had a chance to fire. - -So there is a flag, `-fworker-wrapper-cbv`, to control whether we do -w/w on strict arguments (internally `Opt_WorkerWrapperUnlift`). The -flag is off by default. The choice is made in -GHC.Core.Opt.WorkWrape.Utils.wwUseForUnlifting - -See also `Note [WW for calling convention]` in GHC.Core.Opt.WorkWrap.Utils -} {- @@ -985,6 +995,12 @@ mkWWstr opts args str_marks -- * wrap_arg assumes work_args are in scope, and builds a ConApp that -- reconstructs the RHS of wrap_var that we pass to the original RHS -- See Note [Worker/wrapper for Strictness and Absence] +-- +-- E.g. mkWWstr_one (x :: (Int,Int) with strictess saying to unbox the pair and second Int +-- = ( True -- useful +-- , [p,q#], -- work_args +-- , \e -> case x of (p,q) -> case q of I# q# -> e -- wrap_fn +-- , (p, I# q) ) -- wrap_arg mkWWstr_one :: WwOpts -> Var -> StrictnessMark @@ -1008,7 +1024,7 @@ mkWWstr_one opts arg str_mark = DontUnbox | isStrictDmd arg_dmd || isMarkedStrict str_mark - , wwUseForUnlifting opts -- See Note [WW for calling convention] + , wwUseForUnlifting opts -- See Note [Worker/wrapper for strict arguments] , not (isFunTy arg_ty) , not (isUnliftedType arg_ty) -- Already unlifted! -- NB: function arguments have a fixed RuntimeRep, @@ -1163,7 +1179,7 @@ function is worthy for splitting: 2b But if e.g. a large tuple or product type is always demanded we might decide to "unlift" it. That is tighten the calling convention for that argument to require it to be passed as a pointer to the value itself. - See Note [WW for calling convention]. + See Note [Worker/wrapper for strict arguments] 3. In all other cases (e.g., lazy, used demand and not eval'd), 'finaliseArgBoxities' will have cleared the Boxity flag to 'Boxed' @@ -1604,7 +1620,9 @@ mkWWcpr_entry CoreExpr -> CoreExpr) -- New worker. 'nop_fn' if not useful -- ^ Entrypoint to CPR W/W. See Note [Worker/wrapper for CPR] for an overview. mkWWcpr_entry opts body_ty body_cpr - | not (wo_cpr_anal opts) = return (boringSplit, nop_fn, nop_fn) + | not (wo_cpr_anal opts) -- See (CPR1) in Note [Phase ordering] on GHC.Opt.CprAnal + = return (boringSplit, nop_fn, nop_fn) + | otherwise = do -- Part (1) res_bndr <- mk_res_bndr body_ty @@ -1637,7 +1655,9 @@ mk_res_bndr body_ty = do -- 1. A 'WwUse' capturing whether the split does anything useful. -- 2. The list of transit variables (see the Note). -- 3. The result builder expression for the wrapper. The original case binder if not useful. --- 4. The result unpacking expression for the worker. 'nop_fn' if not useful. +-- Assumes that the transit vars are in scope +-- 4. The result unpacking expression for the worker. 'nop_fn' if not useful +-- Brings the transit vars into scope type CprWwResultOne = (WwUse, OrdList Var, CoreExpr , CoreExpr -> CoreExpr) type CprWwResultMany = (WwUse, OrdList Var, [CoreExpr], CoreExpr -> CoreExpr) @@ -1768,7 +1788,7 @@ To achieve said transformation, 'mkWWcpr_entry' what belongs in the case scrutinee of the unpacker through the communicated Id `r`: The unpacking expression will be free in that variable. (This is a similar contract as that of 'mkWWstr_one' for strict args.) - 3. 'mkWWstr_one' produces a bunch of *transit vars*: Those result variables + 3. 'mkWWcpr_one' produces a bunch of *transit vars*: Those result variables that have to be transferred from the worker to the wrapper, where the constructed result can be rebuilt, `a` and `b` above. Part (3) is responsible for tupling them up in the worker and taking the tuple apart ===================================== compiler/GHC/Types/Cpr.hs ===================================== @@ -8,6 +8,7 @@ module GHC.Types.Cpr ( Cpr (ConCpr), topCpr, botCpr, flatConCpr, asConCpr, CprType (..), topCprType, botCprType, flatConCprType, + cprTypeArity, cprTypeCpr, lubCprType, applyCprTy, abstractCprTy, trimCprTy, UnpackConFieldsResult (..), unpackConFieldsCpr, CprSig (..), topCprSig, isTopCprSig, mkCprSigForArity, mkCprSig, @@ -106,6 +107,12 @@ data CprType -- 'ct_arty' arguments } +cprTypeArity :: CprType -> Arity +cprTypeArity = ct_arty + +cprTypeCpr :: CprType -> Cpr +cprTypeCpr = ct_cpr + instance Eq CprType where a == b = ct_cpr a == ct_cpr b && (ct_arty a == ct_arty b || ct_cpr a == topCpr) @@ -167,7 +174,7 @@ seqCprTy (CprType _ cpr) = seqCpr cpr -- | The arity of the wrapped 'CprType' is the arity at which it is safe -- to unleash. See Note [Understanding DmdType and DmdSig] in "GHC.Types.Demand" -newtype CprSig = CprSig { getCprSig :: CprType } +newtype CprSig = CprSig { cprSigType :: CprType } deriving (Eq, Binary) -- | Turns a 'CprType' computed for the particular 'Arity' into a 'CprSig' ===================================== compiler/GHC/Utils/Monad.hs ===================================== @@ -16,7 +16,7 @@ module GHC.Utils.Monad , mapAccumLM , mapSndM , concatMapM - , mapMaybeM + , mapMaybeM, orElseM , anyM, allM, orM , foldlM, foldlM_, foldrM, foldMapM , whenM, unlessM @@ -250,6 +250,14 @@ unlessM :: Monad m => m Bool -> m () -> m () unlessM condM acc = do { cond <- condM ; unless cond acc } +-- | Monadic version of @orElse@ +infixr 4 `orElseM` +orElseM :: Monad m => m (Maybe a) -> m a -> m a +orElseM ma def = do { mb_r <- ma + ; case mb_r of + Just x -> return x + Nothing -> def } + -- | Like 'filterM', only it reverses the sense of the test. filterOutM :: (Applicative m) => (a -> m Bool) -> [a] -> m [a] filterOutM p = ===================================== testsuite/tests/simplCore/should_compile/T28158.hs ===================================== @@ -0,0 +1,22 @@ +{-# OPTIONS_GHC -fworker-wrapper-cbv #-} +-- Adding this option makes things harder for splitThunkCpr, which +-- this test is testing. See (TS8) in Note [Thunk splitting] + +module T28158 where + +-- Here we miss CPR on y +-- It's a bit of an obscure example, but still; see #28158 +f :: a -> a -> a -> [Int] -> [Int] +f a b c xs = let y = case xs of + [0] -> Just a + [1] -> Just b + _ -> Just c + in h y (case y of + Just z -> reverse (reverse (reverse ( + reverse (reverse (reverse ( + reverse (reverse xs))))))) + Nothing -> xs++xs) + +h :: Maybe a -> b -> b +h (Just y) e = h Nothing e +h Nothing e = e ===================================== testsuite/tests/simplCore/should_compile/T28158.stderr ===================================== @@ -0,0 +1,58 @@ + +==================== Tidy Core ==================== +Result size of Tidy Core + = {terms: 98, types: 108, coercions: 0, joins: 1/1} + +Rec { +$wh + = \ @a @b ds e -> + case ds of ds1 { __DEFAULT -> + case e of e1 { __DEFAULT -> + case ds1 of { + Nothing -> e1; + Just y -> $wh Nothing e1 + } + } + } +end Rec } + +h = \ @a @b ds e -> $wh ds e + +$wf + = \ @a a1 b c xs -> + join { + $j ww + = $wh + (Just ww) + (reverse1 + (reverse1 + (reverse1 + (reverse1 + (reverse1 (reverse1 (reverse1 (reverse1 xs []) []) []) []) []) + []) + []) + []) } in + case xs of { + [] -> jump $j c; + : ds ds1 -> + case ds of { I# ds2 -> + case ds2 of { + __DEFAULT -> jump $j c; + 0# -> + case ds1 of { + [] -> jump $j a1; + : ipv ipv1 -> jump $j c + }; + 1# -> + case ds1 of { + [] -> jump $j b; + : ipv ipv1 -> jump $j c + } + } + } + } + +f = \ @a a1 b c xs -> $wf a1 b c xs + + + ===================================== testsuite/tests/simplCore/should_compile/all.T ===================================== @@ -637,5 +637,5 @@ test('T27963', [grep_errmsg(r'f/42')], compile, ['-O -ddump-rule-firings']) test('T27965', normal, compile, ['-O']) test('T27965a', normal, compile, ['-O']) test('T27965b', normal, compile, ['-O']) - +test('T28158', normal, compile, ['-O -dno-typeable-binds -dsuppress-all -dsuppress-uniques -ddump-simpl']) View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/1045f6c7f26ecab6e993a63aa567a913... -- View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/1045f6c7f26ecab6e993a63aa567a913... You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
participants (1)
-
Simon Peyton Jones (@simonpj)