[Git][ghc/ghc][wip/T22428] Fix contification with stable unfoldings (#22428)
Sebastian Graf (@sgraf812)
gitlab at gitlab.haskell.org
Thu Nov 24 16:47:48 UTC 2022
Sebastian Graf pushed to branch wip/T22428 at Glasgow Haskell Compiler / GHC
Commits:
fd3c063a by Sebastian Graf at 2022-11-24T17:47:24+01:00
Fix contification with stable unfoldings (#22428)
Many functions now return a `TailUsageDetails` that adorns a `UsageDetails` with
a `JoinArity` that reflects the number of join point binders around the body
for which the `UsageDetails` was computed. `TailUsageDetails` is now returned by
`occAnalLamTail` as well as `occAnalUnfolding` and `occAnalRules`.
I adjusted `Note [Join points and unfoldings/rules]` and
`Note [Adjusting right-hand sides]` to account for the new machinery.
I also renamed
* `occAnalLam` to `occAnalLamTail`
* `occAnalRhs` to `occAnalLam`
* `adjustRhsUsage` to `adjustTailUsage`
* a few other less important functions
and properly documented the that each call of `occAnalLamTail` must pair up with
`adjustTailUsage`.
I removed `Note [Unfoldings and join points]` because it was redundant with
`Note [Occurrences in stable unfoldings]`.
Fixes #22428.
- - - - -
5 changed files:
- compiler/GHC/Core/Opt/OccurAnal.hs
- compiler/GHC/Utils/Misc.hs
- + testsuite/tests/simplCore/should_compile/T22428.hs
- + testsuite/tests/simplCore/should_compile/T22428.stderr
- testsuite/tests/simplCore/should_compile/all.T
Changes:
=====================================
compiler/GHC/Core/Opt/OccurAnal.hs
=====================================
@@ -59,7 +59,7 @@ import GHC.Builtin.Names( runRWKey )
import GHC.Unit.Module( Module )
import Data.List (mapAccumL, mapAccumR)
-import Data.List.NonEmpty (NonEmpty (..), nonEmpty)
+import Data.List.NonEmpty (NonEmpty (..))
import qualified Data.List.NonEmpty as NE
{-
@@ -510,6 +510,13 @@ of the file.
at any of the definitions. This is done by Simplify.simplRecBind,
when it calls addLetIdInfo.
+Note that the UsageDetails stored in the Details are as if the binding was a
+*non-recursive join point*, which is quite optimistic. The reason is that
+the binding might actually become a non-recursive join point after dependency
+analysis and in which case we can pretend that the whole RHS is only entered
+once. We do the delayed 'adjustTailUsage' in 'occAnalRec'/'tagRecBinders'.
+See Note [Join points and unfoldings/rules] for more details on the contract.
+
Note [Stable unfoldings]
~~~~~~~~~~~~~~~~~~~~~~~~
None of the above stuff about RULES applies to a stable unfolding
@@ -608,6 +615,53 @@ tail call with `n` arguments (counting both value and type arguments). Otherwise
'occ_tail' will be 'NoTailCallInfo'. The tail call info flows bottom-up with the
rest of 'OccInfo' until it goes on the binder.
+Note [Join arity prediction for recursive functions]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Recall the contification transformation in Fig. 5 of
+"Compiling without Continuations". The letrec case looks like this
+
+ letrec f = /\as.\xs. L[us] in L'[es]
+ ... and a bunch of conditions establishing that f only occurs
+ in app heads of join arity (len as + len xs) inside us and es ...
+
+So for a recursive group, the possible join arity of each binding is determined
+by two sources:
+
+ O. The arity of AlwaysTailCalled occurrences in the let body and its RHSs
+ after stripping off all manifest lambdas (because a lambda body is not a
+ tail context)
+ M. The manifest join arity of the RHSs, which is (len as + len xs) above
+
+If (O) and (M) do not agree, we may not turn the letrec into a join point.
+What goes wrong if we ignore (M)? Consider
+
+ letrec f x y = if ... then f x else True
+ in f 42
+
+According to (O), we'd turn `f` into a join point of arity 1. But that is wrong,
+because then the recursive jump in its RHS is not in tail position!
+
+We can use (M) and conclude that *if* f becomes a join point, then it will have
+join arity 2. Generally, we can predict the join arity of a recursive binding
+by the manifest join arity of its RHS, which is exactly the join arity returned
+when analysing the RHS with 'occAnalLamTail'.
+
+However, for non-recursive functions, this prediction can be wrong.
+Note again the definition of contification from the paper:
+
+ let f = /\as.\xs.u in L[es] ... conditions ...
+
+Note the occurrence of u, not L[us]. u might indeed be a lambda itself, e.g.,
+
+ let f x y = rhs
+ in if b then f 1 else f 2
+
+And based on (O) we'll turn it into a join point of arity 1, because, unlike for
+letrec, f may not occur in rhs. So we adjust the result returned by
+'occAnalLamTail', spoiling all tail calls, see Note [Adjusting right-hand sides].
+It's also possible for (M) to yield a lower prediction than (O); then the
+Simplifier will eta-expand accordingly.
+
Note [Join points and unfoldings/rules]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
@@ -618,8 +672,10 @@ Consider
Before j is inlined, we'll have occurrences of j2 in
both j's RHS and in its stable unfolding. We want to discover
-j2 as a join point. So we must do the adjustRhsUsage thing
-on j's RHS. That's why we pass mb_join_arity to calcUnfolding.
+j2 as a join point. So 'occAnalUnfolding' returns an unadjusted
+'TailUsageDetails', like 'occAnalLamTail'. We adjust the usage details of the
+unfolding to the actual join arity using the same 'adjustTailArity' as for
+the RHS, see Note [Adjusting right-hand sides].
Same with rules. Suppose we have:
@@ -636,14 +692,31 @@ up. So provided the join-point arity of k matches the args of the
rule we can allow the tail-call info from the RHS of the rule to
propagate.
-* Wrinkle for Rec case. In the recursive case we don't know the
- join-point arity in advance, when calling occAnalUnfolding and
- occAnalRules. (See makeNode.) We don't want to pass Nothing,
- because then a recursive joinrec might lose its join-poin-hood
- when SpecConstr adds a RULE. So we just make do with the
- *current* join-poin-hood, stored in the Id.
+* Note that the join arity of the RHS and that of the unfolding or RULE might
+ mismatch:
+
+ let j x y = j2 (x+x)
+ {-# INLINE[2] j = \x. g #-}
+ {-# RULE forall x y z. j x y z = h 17 #-}
+ in j 1 2
+
+ So it is crucial that we adjust each TailUsageDetails individually
+ with the actual join arity 2 here before we combine with `andUDs`.
+ Here, that means losing tail call info on `g` and `h`.
+
+* Wrinkle for Rec case: We store one TailUsageDetails in the node Details for
+ RHS, unfolding and RULE combined. Clearly, if they don't agree on their join
+ arity, we have to do some adjusting. We choose to adjust to the join arity
+ of the RHS, because that is likely the join arity that the join point will
+ have; see Note [Join arity prediction for recursive functions].
- In the non-recursive case things are simple: see occAnalNonRecBind
+ If the guess is correct, then tail calls in the RHS are preserved; a necessary
+ condition for the whole binding becoming a join rec.
+ The guess can only be incorrect in the 'AcyclicSCC' case when the binding
+ becomes a non-recursive join point with a different join arity. But then the
+ eventual call to 'adjustTailUsage' in 'tagRecBinders'/'occAnalRec' will
+ be with a different join arity and destroy unsound tail call info with
+ 'markNonTail'.
* Wrinkle for RULES. Suppose the example was a bit different:
let j :: Int -> Int
@@ -669,28 +742,21 @@ propagate.
This appears to be very rare in practice. TODO Perhaps we should gather
statistics to be sure.
-Note [Unfoldings and join points]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-We assume that anything in an unfolding occurs multiple times, since
-unfoldings are often copied (that's the whole point!). But we still
-need to track tail calls for the purpose of finding join points.
-
-
------------------------------------------------------------
Note [Adjusting right-hand sides]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There's a bit of a dance we need to do after analysing a lambda expression or
a right-hand side. In particular, we need to
- a) call 'markAllInsideLam' *unless* the binding is for a thunk, a one-shot
- lambda, or a non-recursive join point; and
- b) call 'markAllNonTail' *unless* the binding is for a join point, and
- the RHS has the right arity; e.g.
+ a) call 'markAllNonTail' *unless* the binding is for a join point, and
+ the TailUsageDetails from the RHS has the right join arity; e.g.
join j x y = case ... of
A -> j2 p
B -> j2 q
in j a b
Here we want the tail calls to j2 to be tail calls of the whole expression
+ b) call 'markAllInsideLam' *unless* the binding is for a thunk, a one-shot
+ lambda, or a non-recursive join point
Some examples, with how the free occurrences in e (assumed not to be a value
lambda) get marked:
@@ -707,26 +773,30 @@ lambda) get marked:
There are a few other caveats; most importantly, if we're marking a binding as
'AlwaysTailCalled', it's *going* to be a join point, so we treat it as one so
that the effect cascades properly. Consequently, at the time the RHS is
-analysed, we won't know what adjustments to make; thus 'occAnalLamOrRhs' must
-return the unadjusted 'UsageDetails', to be adjusted by 'adjustRhsUsage' once
-join-point-hood has been decided.
+analysed, we won't know what adjustments to make; thus 'occAnalLamTail' must
+return the unadjusted 'UsageDetails', to be adjusted by 'adjustTailUsage' once
+join-point-hood has been decided and eventual one-shot annotations have been
+added through 'markNonRecJoinOneShots'.
Thus the overall sequence taking place in 'occAnalNonRecBind' and
'occAnalRecBind' is as follows:
- 1. Call 'occAnalLamOrRhs' to find usage information for the RHS.
+ 1. Call 'occAnalLamTail' to find usage information for the RHS.
2. Call 'tagNonRecBinder' or 'tagRecBinders', which decides whether to make
the binding a join point.
- 3. Call 'adjustRhsUsage' accordingly. (Done as part of 'tagRecBinders' when
+ 3. Call 'markNonRecJoinOneShots' so that we recognise every non-recursive join
+ point as one-shot
+ 4. Call 'adjustTailUsage' accordingly. (Done as part of 'tagRecBinders' when
recursive.)
-(In the recursive case, this logic is spread between 'makeNode' and
-'occAnalRec'.)
+In the recursive case, this logic is spread: Step 1 is done in 'makeNode' and
+steps (2)-(4) are done in the 'AcyclicSCC' case of 'occAnalRec'.
-}
-
data WithUsageDetails a = WithUsageDetails !UsageDetails !a
+data WithTailUsageDetails a = WithTailUsageDetails !TailUsageDetails !a
+
------------------------------------------------------------------
-- occAnalBind
------------------------------------------------------------------
@@ -754,12 +824,11 @@ occAnalNonRecBind !env lvl imp_rule_edges bndr rhs body_usage
= WithUsageDetails body_usage []
| otherwise -- It's mentioned in the body
- = WithUsageDetails (body_usage' `andUDs` rhs_usage) [NonRec final_bndr rhs']
+ = WithUsageDetails (body_usage' `andUDs` rhs_usage) [NonRec final_bndr rhs2]
where
(body_usage', tagged_bndr) = tagNonRecBinder lvl body_usage bndr
- final_bndr = tagged_bndr `setIdUnfolding` unf'
+ final_bndr = tagged_bndr `setIdUnfolding` unf2
`setIdSpecialisation` mkRuleInfo rules'
- rhs_usage = rhs_uds `andUDs` unf_uds `andUDs` rule_uds
-- Get the join info from the *new* decision
-- See Note [Join points and unfoldings/rules]
@@ -773,17 +842,29 @@ occAnalNonRecBind !env lvl imp_rule_edges bndr rhs body_usage
-- See Note [Sources of one-shot information]
rhs_env = env1 { occ_one_shots = argOneShots dmd }
- (WithUsageDetails rhs_uds rhs') = occAnalRhs rhs_env NonRecursive mb_join_arity rhs
+ WithTailUsageDetails rhs_uds rhs1 = occAnalLamTail rhs_env rhs
+ adj_rhs_uds = adjustTailUsage mb_join_arity rhs2 rhs_uds
+ -- corresponding call to adjustTailUsage directly below
+ rhs_usage = adj_rhs_uds `andUDs` adj_unf_uds `andUDs` adj_rule_uds
--------- Unfolding ---------
- -- See Note [Unfoldings and join points]
+ -- See Note [Join points and unfoldings/rules]
unf | isId bndr = idUnfolding bndr
| otherwise = NoUnfolding
- (WithUsageDetails unf_uds unf') = occAnalUnfolding rhs_env NonRecursive mb_join_arity unf
+ WithTailUsageDetails unf_uds unf1 = occAnalUnfolding rhs_env unf
+ adj_unf_uds = adjustTailArity mb_join_arity unf_uds
+
+ --------- Marking (non-rec) join binders one-shot ---------
+ (rhs2,unf2) | isJust mb_join_arity
+ = (mark rhs1, overStableCoreUnfoldingTmpl mark unf1)
+ | otherwise
+ = (rhs1,unf1)
+ where mark = markNonRecJoinOneShots mb_join_arity
--------- Rules ---------
-- See Note [Rules are extra RHSs] and Note [Rule dependency info]
- rules_w_uds = occAnalRules rhs_env mb_join_arity bndr
+ -- and Note [Join points and unfoldings/rules]
+ rules_w_uds = occAnalRules rhs_env bndr
rules' = map fstOf3 rules_w_uds
imp_rule_uds = impRulesScopeUsage (lookupImpRules imp_rule_edges bndr)
-- imp_rule_uds: consider
@@ -794,8 +875,9 @@ occAnalNonRecBind !env lvl imp_rule_edges bndr rhs body_usage
-- that g is (since the RULE might turn g into h), so
-- we make g mention h.
- rule_uds = foldr add_rule_uds imp_rule_uds rules_w_uds
- add_rule_uds (_, l, r) uds = l `andUDs` r `andUDs` uds
+ adj_rule_uds = foldr add_rule_uds imp_rule_uds rules_w_uds
+ add_rule_uds (_, l, r) uds
+ = l `andUDs` adjustTailArity mb_join_arity r `andUDs` uds
----------
occ = idOccInfo tagged_bndr
@@ -848,11 +930,22 @@ occAnalRec !_ lvl (AcyclicSCC (ND { nd_bndr = bndr, nd_rhs = rhs
| otherwise -- It's mentioned in the body
= WithUsageDetails (body_uds' `andUDs` rhs_uds')
- (NonRec tagged_bndr rhs : binds)
+ (NonRec bndr2 rhs2 : binds)
where
- (body_uds', tagged_bndr) = tagNonRecBinder lvl body_uds bndr
- rhs_uds' = adjustRhsUsage mb_join_arity rhs rhs_uds
- mb_join_arity = willBeJoinId_maybe tagged_bndr
+ (body_uds', bndr1) = tagNonRecBinder lvl body_uds bndr
+ rhs1 = markNonRecJoinOneShots mb_join_arity rhs
+ rhs_uds' = adjustTailUsage mb_join_arity rhs1 rhs_uds
+ -- corresponding call to occAnalLamTail is in makeNode
+ -- rhs_uds is for a non-recursive join point; we should to do the same
+ -- as occAnalNonRecBind, so we do 'markNonRecJoinOneShots' before.
+ mb_join_arity = willBeJoinId_maybe bndr1
+ (rhs2,bndr2) | isJust mb_join_arity
+ = (mark rhs1, bndr1 `setIdUnfolding` unf2)
+ | otherwise
+ = (rhs1,bndr1)
+ where mark = markNonRecJoinOneShots mb_join_arity
+ unf1 = idUnfolding bndr1
+ unf2 = overStableCoreUnfoldingTmpl mark unf1
-- The Rec case is the interesting one
-- See Note [Recursive bindings: the grand plan]
@@ -1329,9 +1422,11 @@ data Details
, nd_rhs :: CoreExpr -- RHS, already occ-analysed
- , nd_uds :: UsageDetails -- Usage from RHS, and RULES, and stable unfoldings
- -- ignoring phase (ie assuming all are active)
- -- See Note [Forming Rec groups]
+ , nd_uds :: TailUsageDetails -- Usage from RHS, and RULES, and stable unfoldings
+ -- ignoring phase (ie assuming all are active)
+ -- NB: Unadjusted TailUsageDetails, as if
+ -- this Node becomes a non-recursive join point!
+ -- See Note [Forming Rec groups]
, nd_inl :: IdSet -- Free variables of the stable unfolding and the RHS
-- but excluding any RULES
@@ -1398,41 +1493,47 @@ makeNode !env imp_rule_edges bndr_set (bndr, rhs)
bndr' = bndr `setIdUnfolding` unf'
`setIdSpecialisation` mkRuleInfo rules'
- inl_uds = rhs_uds `andUDs` unf_uds
- scope_uds = inl_uds `andUDs` rule_uds
+ -- NB: Both adj_unf_uds and adj_rule_uds have been adjusted to match the
+ -- JoinArity rhs_ja of unadj_rhs_uds.
+ unadj_inl_uds = unadj_rhs_uds `andUDs` adj_unf_uds
+ unadj_scope_uds = unadj_inl_uds `andUDs` adj_rule_uds
+ scope_uds = TUD rhs_ja unadj_scope_uds
-- Note [Rules are extra RHSs]
-- Note [Rule dependency info]
- scope_fvs = udFreeVars bndr_set scope_uds
+ scope_fvs = udFreeVars bndr_set unadj_scope_uds
-- scope_fvs: all occurrences from this binder: RHS, unfolding,
-- and RULES, both LHS and RHS thereof, active or inactive
- inl_fvs = udFreeVars bndr_set inl_uds
+ inl_fvs = udFreeVars bndr_set unadj_inl_uds
-- inl_fvs: vars that would become free if the function was inlined.
-- We conservatively approximate that by thefree vars from the RHS
-- and the unfolding together.
-- See Note [inl_fvs]
- mb_join_arity = isJoinId_maybe bndr
- -- Get join point info from the *current* decision
- -- We don't know what the new decision will be!
- -- Using the old decision at least allows us to
- -- preserve existing join point, even RULEs are added
- -- See Note [Join points and unfoldings/rules]
--------- Right hand side ---------
-- Constructing the edges for the main Rec computation
-- See Note [Forming Rec groups]
- -- Do not use occAnalRhs because we don't yet know the final
- -- answer for mb_join_arity; instead, do the occAnalLam call from
- -- occAnalRhs, and postpone adjustRhsUsage until occAnalRec
- rhs_env = rhsCtxt env
- (WithUsageDetails rhs_uds rhs') = occAnalLam rhs_env rhs
+ -- Compared to occAnalLam, we can't yet adjust the RHS because
+ -- (a) we don't yet know the final answer for pred_join_arity. It might be
+ -- Nothing!
+ -- (b) we don't even know whether it stays a recursive RHS after the SCC
+ -- analysis we are about to seed! So we can't markAllInsideLam in
+ -- advance, because if it ends up as a non-recursive join point we'll
+ -- consider it as one-shot and don't need to markAllInsideLam.
+ -- Instead, do the occAnalLamTail call from occAnalLam, and postpone
+ -- adjustTailUsage until occAnalRec. In effect, we pretend that the RHS
+ -- becomes a non-recursive join point and fix up later with adjustTailUsage.
+ rhs_env = rhsCtxt env
+ WithTailUsageDetails (TUD rhs_ja unadj_rhs_uds) rhs' = occAnalLamTail rhs_env rhs
+ -- corresponding call to adjustTailUsage in occAnalRec and tagRecBinders
--------- Unfolding ---------
- -- See Note [Unfoldings and join points]
+ -- See Note [Join points and unfoldings/rules]
unf = realIdUnfolding bndr -- realIdUnfolding: Ignore loop-breaker-ness
-- here because that is what we are setting!
- (WithUsageDetails unf_uds unf') = occAnalUnfolding rhs_env Recursive mb_join_arity unf
+ WithTailUsageDetails unf_tuds unf' = occAnalUnfolding rhs_env unf
+ adj_unf_uds = adjustTailArity (Just rhs_ja) unf_tuds
--------- IMP-RULES --------
is_active = occ_rule_act env :: Activation -> Bool
@@ -1441,11 +1542,13 @@ makeNode !env imp_rule_edges bndr_set (bndr, rhs)
imp_rule_fvs = impRulesActiveFvs is_active bndr_set imp_rule_info
--------- All rules --------
+ -- See Note [Join points and unfoldings/rules]
rules_w_uds :: [(CoreRule, UsageDetails, UsageDetails)]
- rules_w_uds = occAnalRules rhs_env mb_join_arity bndr
+ rules_w_uds = [ (r,l,adjustTailArity (Just rhs_ja) rhs_tuds)
+ | (r,l,rhs_tuds) <- occAnalRules rhs_env bndr ]
rules' = map fstOf3 rules_w_uds
- rule_uds = foldr add_rule_uds imp_rule_uds rules_w_uds
+ adj_rule_uds = foldr add_rule_uds imp_rule_uds rules_w_uds
add_rule_uds (_, l, r) uds = l `andUDs` r `andUDs` uds
-------- active_rule_fvs ------------
@@ -1748,7 +1851,7 @@ lambda and casts, e.g.
* Occurrence analyser: we just mark each binder in the lambda-group
(here: x,y,z) with its occurrence info in the *body* of the
- lambda-group. See occAnalLam.
+ lambda-group. See occAnalLamTail.
* Simplifier. The simplifier is careful when partially applying
lambda-groups. See the call to zapLambdaBndrs in
@@ -1804,7 +1907,7 @@ zapLambdaBndrs fun arg_count
zap_bndr b | isTyVar b = b
| otherwise = zapLamIdInfo b
-occAnalLam :: OccEnv -> CoreExpr -> (WithUsageDetails CoreExpr)
+occAnalLamTail :: OccEnv -> CoreExpr -> WithTailUsageDetails CoreExpr
-- See Note [Occurrence analysis for lambda binders]
-- It does the following:
-- * Sets one-shot info on the lambda binder from the OccEnv, and
@@ -1815,13 +1918,17 @@ occAnalLam :: OccEnv -> CoreExpr -> (WithUsageDetails CoreExpr)
-- This function does /not/ do
-- markAllInsideLam or
-- markAllNonTail
--- The caller does that, either in occAnal (Lam {}), or in adjustRhsUsage
+-- The caller does that, either in occAnalLam, or calling adjustTailUsage directly.
+-- Every call site links to its respective adjustTailUsage call and vice versa.
+--
+-- In effect, the analysis result is for a non-recursive join point with
+-- manifest arity and adjustTailUsage does the fixup.
-- See Note [Adjusting right-hand sides]
-occAnalLam env (Lam bndr expr)
+occAnalLamTail env (Lam bndr expr)
| isTyVar bndr
- = let (WithUsageDetails usage expr') = occAnalLam env expr
- in WithUsageDetails usage (Lam bndr expr')
+ , WithTailUsageDetails tusage expr' <- occAnalLamTail env expr
+ = WithTailUsageDetails tusage (Lam bndr expr')
-- Important: Keep the 'env' unchanged so that with a RHS like
-- \(@ x) -> K @x (f @x)
-- we'll see that (K @x (f @x)) is in a OccRhs, and hence refrain
@@ -1839,14 +1946,14 @@ occAnalLam env (Lam bndr expr)
env1 = env { occ_encl = OccVanilla, occ_one_shots = env_one_shots' }
env2 = addOneInScope env1 bndr
- (WithUsageDetails usage expr') = occAnalLam env2 expr
+ WithTailUsageDetails (TUD ja usage) expr' = occAnalLamTail env2 expr
(usage', bndr2) = tagLamBinder usage bndr1
- in WithUsageDetails usage' (Lam bndr2 expr')
+ in WithTailUsageDetails (TUD (ja+1) usage') (Lam bndr2 expr')
-- For casts, keep going in the same lambda-group
-- See Note [Occurrence analysis for lambda binders]
-occAnalLam env (Cast expr co)
- = let (WithUsageDetails usage expr') = occAnalLam env expr
+occAnalLamTail env (Cast expr co)
+ = let WithTailUsageDetails (TUD ja usage) expr' = occAnalLamTail env expr
-- usage1: see Note [Gather occurrences of coercion variables]
usage1 = addManyOccs usage (coVarsOfCo co)
@@ -1856,15 +1963,16 @@ occAnalLam env (Cast expr co)
_ -> usage1
-- usage3: you might think this was not necessary, because of
- -- the markAllNonTail in adjustRhsUsage; but not so! For a
- -- join point, adjustRhsUsage doesn't do this; yet if there is
+ -- the markAllNonTail in adjustTailUsage; but not so! For a
+ -- join point, adjustTailUsage doesn't do this; yet if there is
-- a cast, we must! Also: why markAllNonTail? See
-- GHC.Core.Lint: Note Note [Join points and casts]
usage3 = markAllNonTail usage2
- in WithUsageDetails usage3 (Cast expr' co)
+ in WithTailUsageDetails (TUD ja usage3) (Cast expr' co)
-occAnalLam env expr = occAnal env expr
+occAnalLamTail env expr = case occAnal env expr of
+ WithUsageDetails usage expr' -> WithTailUsageDetails (TUD 0 usage) expr'
{- Note [Occ-anal and cast worker/wrapper]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -1884,8 +1992,8 @@ RHS. So it'll get a Many occ-info. (Maybe Cast w/w should create a stable
unfolding, which would obviate this Note; but that seems a bit of a
heavyweight solution.)
-We only need to this in occAnalLam, not occAnal, because the top leve
-of a right hand side is handled by occAnalLam.
+We only need to this in occAnalLamTail, not occAnal, because the top leve
+of a right hand side is handled by occAnalLamTail.
-}
@@ -1895,57 +2003,36 @@ of a right hand side is handled by occAnalLam.
* *
********************************************************************* -}
-occAnalRhs :: OccEnv -> RecFlag -> Maybe JoinArity
+occAnalLam :: OccEnv -> Maybe JoinArity
-> CoreExpr -- RHS
-> WithUsageDetails CoreExpr
-occAnalRhs !env is_rec mb_join_arity rhs
- = let (WithUsageDetails usage rhs1) = occAnalLam env rhs
- -- We call occAnalLam here, not occAnalExpr, so that it doesn't
- -- do the markAllInsideLam and markNonTailCall stuff before
- -- we've had a chance to help with join points; that comes next
- rhs2 = markJoinOneShots is_rec mb_join_arity rhs1
- rhs_usage = adjustRhsUsage mb_join_arity rhs2 usage
- in WithUsageDetails rhs_usage rhs2
-
-
-
-markJoinOneShots :: RecFlag -> Maybe JoinArity -> CoreExpr -> CoreExpr
--- For a /non-recursive/ join point we can mark all
--- its join-lambda as one-shot; and it's a good idea to do so
-markJoinOneShots NonRecursive (Just join_arity) rhs
- = go join_arity rhs
+-- ^ This function immediately does adjustTailUsage with the fixed join arity
+-- after the call to occAnalLamTail.
+-- It's useful for anonymous lambdas and unfoldings.
+occAnalLam !env mb_join_arity rhs
+ = WithUsageDetails (adjustTailUsage mb_join_arity rhs2 tusage) rhs2
where
- go 0 rhs = rhs
- go n (Lam b rhs) = Lam (if isId b then setOneShotLambda b else b)
- (go (n-1) rhs)
- go _ rhs = rhs -- Not enough lambdas. This can legitimately happen.
- -- e.g. let j = case ... in j True
- -- This will become an arity-1 join point after the
- -- simplifier has eta-expanded it; but it may not have
- -- enough lambdas /yet/. (Lint checks that JoinIds do
- -- have enough lambdas.)
-markJoinOneShots _ _ rhs
- = rhs
+ rhs2 = markNonRecJoinOneShots mb_join_arity rhs1
+ WithTailUsageDetails tusage rhs1 = occAnalLamTail env rhs
+
occAnalUnfolding :: OccEnv
- -> RecFlag
- -> Maybe JoinArity -- See Note [Join points and unfoldings/rules]
-> Unfolding
- -> WithUsageDetails Unfolding
+ -> WithTailUsageDetails Unfolding
-- Occurrence-analyse a stable unfolding;
--- discard a non-stable one altogether.
-occAnalUnfolding !env is_rec mb_join_arity unf
+-- discard a non-stable one altogether and return empty usage details.
+occAnalUnfolding !env unf
= case unf of
unf@(CoreUnfolding { uf_tmpl = rhs, uf_src = src })
| isStableSource src ->
let
- (WithUsageDetails usage rhs') = occAnalRhs env is_rec mb_join_arity rhs
+ WithTailUsageDetails (TUD rhs_ja usage) rhs' = occAnalLamTail env rhs
unf' | noBinderSwaps env = unf -- Note [Unfoldings and rules]
| otherwise = unf { uf_tmpl = rhs' }
- in WithUsageDetails (markAllMany usage) unf'
+ in WithTailUsageDetails (TUD rhs_ja (markAllMany usage)) unf'
-- markAllMany: see Note [Occurrences in stable unfoldings]
- | otherwise -> WithUsageDetails emptyDetails unf
+ | otherwise -> WithTailUsageDetails (TUD 0 emptyDetails) unf
-- For non-Stable unfoldings we leave them undisturbed, but
-- don't count their usage because the simplifier will discard them.
-- We leave them undisturbed because nodeScore uses their size info
@@ -1954,29 +2041,26 @@ occAnalUnfolding !env is_rec mb_join_arity unf
-- scope remain in scope; there is no cloning etc.
unf@(DFunUnfolding { df_bndrs = bndrs, df_args = args })
- -> WithUsageDetails final_usage (unf { df_args = args' })
+ -> WithTailUsageDetails (TUD 0 final_usage) (unf { df_args = args' })
where
env' = env `addInScope` bndrs
(WithUsageDetails usage args') = occAnalList env' args
- final_usage = markAllManyNonTail (delDetailsList usage bndrs)
- `addLamCoVarOccs` bndrs
- `delDetailsList` bndrs
+ final_usage = usage `addLamCoVarOccs` bndrs `delDetailsList` bndrs
-- delDetailsList; no need to use tagLamBinders because we
-- never inline DFuns so the occ-info on binders doesn't matter
- unf -> WithUsageDetails emptyDetails unf
+ unf -> WithTailUsageDetails (TUD 0 emptyDetails) unf
occAnalRules :: OccEnv
- -> Maybe JoinArity -- See Note [Join points and unfoldings/rules]
-> Id -- Get rules from here
-> [(CoreRule, -- Each (non-built-in) rule
UsageDetails, -- Usage details for LHS
- UsageDetails)] -- Usage details for RHS
-occAnalRules !env mb_join_arity bndr
+ TailUsageDetails)] -- Usage details for RHS
+occAnalRules !env bndr
= map occ_anal_rule (idCoreRules bndr)
where
occ_anal_rule rule@(Rule { ru_bndrs = bndrs, ru_args = args, ru_rhs = rhs })
- = (rule', lhs_uds', rhs_uds')
+ = (rule', lhs_uds', TUD rhs_ja rhs_uds')
where
env' = env `addInScope` bndrs
rule' | noBinderSwaps env = rule -- Note [Unfoldings and rules]
@@ -1989,14 +2073,11 @@ occAnalRules !env mb_join_arity bndr
(WithUsageDetails rhs_uds rhs') = occAnal env' rhs
-- Note [Rules are extra RHSs]
-- Note [Rule dependency info]
- rhs_uds' = markAllNonTailIf (not exact_join) $
- markAllMany $
+ rhs_uds' = markAllMany $
rhs_uds `delDetailsList` bndrs
+ rhs_ja = length args -- See Note [Join points and unfoldings/rules]
- exact_join = exactJoin mb_join_arity args
- -- See Note [Join points and unfoldings/rules]
-
- occ_anal_rule other_rule = (other_rule, emptyDetails, emptyDetails)
+ occ_anal_rule other_rule = (other_rule, emptyDetails, TUD 0 emptyDetails)
{- Note [Join point RHSs]
~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -2031,6 +2112,8 @@ Another way to think about it: if we inlined g as-is into multiple
call sites, now there's be multiple calls to f.
Bottom line: treat all occurrences in a stable unfolding as "Many".
+We still leave tail call information in tact, though, as to not spoil
+potential join points.
Note [Unfoldings and rules]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -2208,10 +2291,7 @@ occAnal env app@(App _ _)
= occAnalApp env (collectArgsTicks tickishFloatable app)
occAnal env expr@(Lam {})
- = let (WithUsageDetails usage expr') = occAnalLam env expr
- final_usage = markAllInsideLamIf (not (isOneShotFun expr')) $
- markAllNonTail usage
- in WithUsageDetails final_usage expr'
+ = occAnalLam env Nothing expr -- mb_join_arity == Nothing <=> markAllManyNonTail
occAnal env (Case scrut bndr ty alts)
= let
@@ -2286,7 +2366,7 @@ occAnalApp !env (Var fun, args, ticks)
-- This caused #18296
| fun `hasKey` runRWKey
, [t1, t2, arg] <- args
- , let (WithUsageDetails usage arg') = occAnalRhs env NonRecursive (Just 1) arg
+ , WithUsageDetails usage arg' <- occAnalLam env (Just 1) arg
= WithUsageDetails usage (mkTicks ticks $ mkApps (Var fun) [t1, t2, arg'])
occAnalApp env (Var fun_id, args, ticks)
@@ -2865,6 +2945,13 @@ lookupBndrSwap env@(OccEnv { occ_bs_env = bs_env }) bndr
case lookupBndrSwap env bndr1 of
(fun, fun_id) -> (mkCastMCo fun mco, fun_id) }
+overStableCoreUnfoldingTmpl :: (CoreExpr -> CoreExpr) -> Unfolding -> Unfolding
+overStableCoreUnfoldingTmpl f uf = case uf of
+ CoreUnfolding{uf_tmpl=tmpl,uf_src=src}
+ | isStableSource src
+ , let !tmpl' = f tmpl
+ -> uf{uf_tmpl=tmpl'}
+ _ -> uf
{- Historical note [Proxy let-bindings]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -2991,6 +3078,14 @@ data UsageDetails
instance Outputable UsageDetails where
ppr ud = ppr (ud_env (flattenUsageDetails ud))
+-- | A 'UsageDetails' for a join body of the given 'JoinArity'.
+-- Call 'adjustTailArity'/'adjustTailUsage' to pick out the 'UsageDetails'.
+data TailUsageDetails = TUD !JoinArity !UsageDetails
+
+instance Outputable TailUsageDetails where
+ ppr (TUD ja uds) = lambda <> ppr ja <> ppr uds
+
+
-------------------
-- UsageDetails API
@@ -3132,24 +3227,42 @@ flattenUsageDetails ud@(UD { ud_env = env })
-------------------
-- See Note [Adjusting right-hand sides]
-adjustRhsUsage :: Maybe JoinArity
- -> CoreExpr -- Rhs, AFTER occ anal
- -> UsageDetails -- From body of lambda
+adjustTailUsage :: Maybe JoinArity
+ -> CoreExpr -- Rhs, AFTER occAnalLamTail
+ -> TailUsageDetails -- From body of lambda
-> UsageDetails
-adjustRhsUsage mb_join_arity rhs usage
+adjustTailUsage mb_join_arity rhs (TUD rhs_ja usage)
= -- c.f. occAnal (Lam {})
markAllInsideLamIf (not one_shot) $
markAllNonTailIf (not exact_join) $
usage
where
one_shot = isOneShotFun rhs
- exact_join = exactJoin mb_join_arity bndrs
- (bndrs,_) = collectBinders rhs
+ exact_join = mb_join_arity == Just rhs_ja
+
+adjustTailArity :: Maybe JoinArity -> TailUsageDetails -> UsageDetails
+adjustTailArity mb_rhs_ja (TUD ud_ja usage) =
+ markAllNonTailIf (mb_rhs_ja /= Just ud_ja) usage
-exactJoin :: Maybe JoinArity -> [a] -> Bool
-exactJoin Nothing _ = False
-exactJoin (Just join_arity) args = args `lengthIs` join_arity
- -- Remember join_arity includes type binders
+assumeCorrectTailArity :: TailUsageDetails -> UsageDetails
+assumeCorrectTailArity (TUD _ usage) = usage
+
+markNonRecJoinOneShots :: Maybe JoinArity -> CoreExpr -> CoreExpr
+-- For a /non-recursive/ join point we can mark all
+-- its join-lambda as one-shot; and it's a good idea to do so
+markNonRecJoinOneShots Nothing rhs = rhs
+markNonRecJoinOneShots (Just join_arity) rhs
+ = go join_arity rhs
+ where
+ go 0 rhs = rhs
+ go n (Lam b rhs) = Lam (if isId b then setOneShotLambda b else b)
+ (go (n-1) rhs)
+ go _ rhs = rhs -- Not enough lambdas. This can legitimately happen.
+ -- e.g. let j = case ... in j True
+ -- This will become an arity-1 join point after the
+ -- simplifier has eta-expanded it; but it may not have
+ -- enough lambdas /yet/. (Lint checks that JoinIds do
+ -- have enough lambdas.)
type IdWithOccInfo = Id
@@ -3214,17 +3327,16 @@ tagRecBinders lvl body_uds details_s
rhs_udss = map nd_uds details_s
-- 1. Determine join-point-hood of whole group, as determined by
- -- the *unadjusted* usage details
- unadj_uds = foldr andUDs body_uds rhs_udss
+ -- the *unadjusted* usage details, as if they all ended up as join
+ -- points. Hence 'assumeCorrectTailArity'.
+ unadj_uds = foldr (andUDs . assumeCorrectTailArity) body_uds rhs_udss
- -- This is only used in `mb_join_arity`, to adjust each `Details` in `details_s`, thus,
- -- when `bndrs` is non-empty. So, we only write `maybe False` as `decideJoinPointHood`
- -- takes a `NonEmpty CoreBndr`; the default value `False` won't affect program behavior.
- will_be_joins = maybe False (decideJoinPointHood lvl unadj_uds) (nonEmpty bndrs)
+ bndr_ne = expectNonEmpty "List of binders is never empty" bndrs
+ will_be_joins = decideJoinPointHood lvl unadj_uds bndr_ne
-- 2. Adjust usage details of each RHS, taking into account the
-- join-point-hood decision
- rhs_udss' = [ adjustRhsUsage (mb_join_arity bndr) rhs rhs_uds
+ rhs_udss' = [ adjustTailUsage (mb_join_arity bndr) rhs rhs_uds -- matching occAnalLamTail in makeNode
| ND { nd_bndr = bndr, nd_uds = rhs_uds
, nd_rhs = rhs } <- details_s ]
=====================================
compiler/GHC/Utils/Misc.hs
=====================================
@@ -39,7 +39,7 @@ module GHC.Utils.Misc (
equalLength, compareLength, leLength, ltLength,
isSingleton, only, expectOnly, GHC.Utils.Misc.singleton,
- notNull, snocView,
+ notNull, expectNonEmpty, snocView,
chunkList,
@@ -504,7 +504,6 @@ expectOnly _ (a:_) = a
#endif
expectOnly msg _ = panic ("expectOnly: " ++ msg)
-
-- | Split a list into chunks of /n/ elements
chunkList :: Int -> [a] -> [[a]]
chunkList _ [] = []
@@ -523,6 +522,16 @@ changeLast [] _ = panic "changeLast"
changeLast [_] x = [x]
changeLast (x:xs) x' = x : changeLast xs x'
+-- | Like @expectJust msg . nonEmpty@; a better alternative to 'NE.fromList'.
+expectNonEmpty :: HasCallStack => String -> [a] -> NonEmpty a
+{-# INLINE expectNonEmpty #-}
+expectNonEmpty _ (x:xs) = x:|xs
+expectNonEmpty msg [] = expectNonEmptyPanic msg
+
+expectNonEmptyPanic :: String -> a
+expectNonEmptyPanic msg = panic ("expectNonEmpty: " ++ msg)
+{-# NOINLINE expectNonEmptyPanic #-}
+
-- | Apply an effectful function to the last list element.
mapLastM :: Functor f => (a -> f a) -> NonEmpty a -> f (NonEmpty a)
mapLastM f (x:|[]) = NE.singleton <$> f x
=====================================
testsuite/tests/simplCore/should_compile/T22428.hs
=====================================
@@ -0,0 +1,9 @@
+module T22428 where
+
+f :: Integer -> Integer -> Integer
+f x y = go y
+ where
+ go :: Integer -> Integer
+ go 0 = x
+ go n = go (n-1)
+ {-# INLINE go #-}
=====================================
testsuite/tests/simplCore/should_compile/T22428.stderr
=====================================
@@ -0,0 +1,45 @@
+
+==================== Tidy Core ====================
+Result size of Tidy Core
+ = {terms: 32, types: 14, coercions: 0, joins: 1/1}
+
+-- RHS size: {terms: 2, types: 0, coercions: 0, joins: 0/0}
+T22428.f1 :: Integer
+[GblId,
+ Unf=Unf{Src=<vanilla>, TopLvl=True, Value=True, ConLike=True,
+ WorkFree=True, Expandable=True, Guidance=IF_ARGS [] 10 10}]
+T22428.f1 = GHC.Num.Integer.IS 1#
+
+-- RHS size: {terms: 28, types: 10, coercions: 0, joins: 1/1}
+f :: Integer -> Integer -> Integer
+[GblId,
+ Arity=2,
+ Str=<SL><1L>,
+ Unf=Unf{Src=<vanilla>, TopLvl=True, Value=True, ConLike=True,
+ WorkFree=True, Expandable=True, Guidance=IF_ARGS [0 0] 156 0}]
+f = \ (x :: Integer) (y :: Integer) ->
+ joinrec {
+ go [InlPrag=INLINE (sat-args=1), Occ=LoopBreaker, Dmd=SC(S,L)]
+ :: Integer -> Integer
+ [LclId[JoinId(1)(Just [!])],
+ Arity=1,
+ Str=<1L>,
+ Unf=Unf{Src=StableUser, TopLvl=False, Value=True, ConLike=True,
+ WorkFree=True, Expandable=True,
+ Guidance=ALWAYS_IF(arity=1,unsat_ok=False,boring_ok=False)}]
+ go (ds :: Integer)
+ = case ds of wild {
+ GHC.Num.Integer.IS x1 ->
+ case x1 of {
+ __DEFAULT -> jump go (GHC.Num.Integer.integerSub wild T22428.f1);
+ 0# -> x
+ };
+ GHC.Num.Integer.IP x1 ->
+ jump go (GHC.Num.Integer.integerSub wild T22428.f1);
+ GHC.Num.Integer.IN x1 ->
+ jump go (GHC.Num.Integer.integerSub wild T22428.f1)
+ }; } in
+ jump go y
+
+
+
=====================================
testsuite/tests/simplCore/should_compile/all.T
=====================================
@@ -450,5 +450,9 @@ test('T22375', normal, compile, ['-O -ddump-simpl -dsuppress-uniques -dno-typeab
# One module, T21851_2.hs, has OPTIONS_GHC -ddump-simpl
# Expecting to see $s$wwombat
test('T21851_2', [grep_errmsg(r'wwombat') ], multimod_compile, ['T21851_2', '-O -dno-typeable-binds -dsuppress-uniques'])
+
# Should not inline m, so there shouldn't be a single YES
test('T22317', [grep_errmsg(r'ANSWER = YES') ], compile, ['-O -dinline-check m -ddebug-output'])
+
+# go should become a join point
+test('T22428', [grep_errmsg(r'jump go') ], compile, ['-O -ddump-simpl -dsuppress-uniques -dno-typeable-binds -dsuppress-unfoldings'])
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/fd3c063a95b095f1733f9451bcf6b1a838026a0b
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/fd3c063a95b095f1733f9451bcf6b1a838026a0b
You're receiving this email because of your account on gitlab.haskell.org.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/ghc-commits/attachments/20221124/34388aad/attachment-0001.html>
More information about the ghc-commits
mailing list