Simon Peyton Jones pushed to branch wip/T27212 at Glasgow Haskell Compiler / GHC Commits: 21747490 by Simon Peyton Jones at 2026-11-20T12:21:46+00:00 Update comments and user manual This commit addresses the comment-related suggestions in #27973 - - - - - c4818edc by Simon Peyton Jones at 2026-11-20T12:28:08+00:00 Update eta-reduction documentation; ignore multiplicities Triggered by #27212, this patch does several related things: * Update documentation about eta expansion and reduction, especially * Make it clear in `findRhsArity` that we eta expand only to increase `exprArity`, not `manifestArity`. (The latter was a misconception of #27212.) * Relabel the criteria in Note [Eta reduction soundness] as (EtaA), (EtaS), (EtaR), (EtaE), (EtaT), (EtaJ), (EtaB), (EtaW), fix references to them (including stale references to a non-existent Note [Eta reduction makes sense]), and add historical notes (EtaMult) and (EtaBot). * Refactor GHC.Core.Opt.Arity.tryEtaReduce, which was hard to understand. New code is simpler and more efficient. (Side note: this introduces a tiresome function `mkEtaReduceForAllMCo` but it will go away again once !17006 lands.) * As part of this refactor I dropped the tricky checks on multiplicity, which sometimes disabled eta-reduction. Note [Linting linearity] in GHC.Core.Lint already said that we don't try to preserve linearity when doing eta-reduction, so the change here just executes that claim. - - - - - 20 changed files: - compiler/GHC/Core/Coercion.hs - compiler/GHC/Core/Opt/Arity.hs - compiler/GHC/Core/Opt/OccurAnal.hs - compiler/GHC/Core/Opt/Pipeline.hs - compiler/GHC/Core/Opt/Simplify/Env.hs - compiler/GHC/Core/Opt/Simplify/Inline.hs - compiler/GHC/Core/Opt/Simplify/Iteration.hs - compiler/GHC/Core/Opt/Simplify/Utils.hs - compiler/GHC/Core/Opt/Specialise.hs - compiler/GHC/Core/TyCo/Make.hs - compiler/GHC/Core/Type.hs - compiler/GHC/Core/Utils.hs - compiler/GHC/Driver/Config/Core/Opt/Simplify.hs - compiler/Language/Haskell/Syntax/Binds/InlinePragma.hs - docs/users_guide/debug-info.rst - docs/users_guide/using-optimisation.rst - testsuite/tests/dmdanal/sigs/T21888a.stderr - testsuite/tests/printer/T18052a.stderr - + testsuite/tests/simplCore/should_compile/T27212.hs - testsuite/tests/simplCore/should_compile/all.T Changes: ===================================== compiler/GHC/Core/Coercion.hs ===================================== @@ -74,7 +74,7 @@ module GHC.Core.Coercion ( isReflCoVar_maybe, assertGoodForAllCo, - coToMCo, kindCoToMKindCo, + coToMCo, kindCoToMKindCo, mCoToCo, mkTransMCo, mkTransMCoL, mkTransMCoR, mkCastTyMCo, mkSymMCo, mkFunResMCo, mkPiMCos, isReflMCo, checkReflexiveMCo, ===================================== compiler/GHC/Core/Opt/Arity.hs ===================================== @@ -886,8 +886,14 @@ findRhsArity :: ArityOpts -> RecFlag -> Id -> CoreExpr -- This implements the fixpoint loop for arity analysis -- See Note [Arity analysis] -- --- The Bool is True if the returned arity is greater than (exprArity rhs) --- so the caller should do eta-expansion +-- The Bool is True if +-- the returned arity is greater than (exprArity rhs) +-- so the caller should do eta-expansion +-- NB: `exprArity`, not `manifestArity`: +-- a PAP such as (\x. f x), where f has arity 3, has exprArity 3, +-- so we do not eta-expand it to (\x y z. f x y z) +-- See Note [Do not eta-expand PAPs] in GHC.Core.Opt.Simplify.Utils +-- -- That Bool is never True for join points, which are never eta-expanded -- -- Returns an SafeArityType that is guaranteed trimmed to typeArity of 'bndr' @@ -903,10 +909,11 @@ findRhsArity opts is_rec bndr rhs | otherwise = (arity_increased, non_join_arity_type) - -- arity_increased: eta-expand if we'll get more lambdas - -- to the top of the RHS + -- arity_increased: eta-expand if the analysis finds a greater arity + -- than exprArity, which already takes account of PAPs where - old_arity = exprArity rhs + old_arity = exprArity rhs -- See Note [Do not eta-expand PAPs] + -- in GHC.Core.Opt.Simplify.Utils init_env :: ArityEnv init_env = findRhsArityEnv opts (isJoinId bndr) @@ -2388,6 +2395,7 @@ mkEtaForAllMCo (Bndr tcv vis) ty mco -- and is SymCo'd in `etaInfoAbs`. Hence the orientation of the visibility -- flags. A bit of a brain-strain (#27557). + {- ************************************************************************ * * @@ -2452,16 +2460,20 @@ perform eta reduction on an expression with n leading lambdas `\xs. e xs` (checked in 'is_eta_reduction_sound' in 'tryEtaReduce', which focuses on the case where `e` is trivial): -(A) It is sound to eta-reduce n arguments as long as n does not exceed the - `exprArity` of `e`. (Needs Arity analysis.) - This criterion exploits information about how `e` is *defined*. +(EtaA) It is sound to eta-reduce n arguments as long as n does not exceed the + `exprArity` of `e`. (Needs Arity analysis.) This criterion exploits information + about how `e` is *defined*. For example: + f = \xy. g x y ===> f = g + This eta-reduction is good only if `g` has arity at least 2, otherwise + f's arity will decrease from 2 to 1. + c.f. Note [Arity robustness] in GHC.Core.Opt.Simplify.Env. - Example: If `e = \x. bot` then we know it won't diverge until it is called - with one argument. Hence it is safe to eta-reduce `\x. e x` to `e`. + Another example: If `e = \x. bot` then we know it won't diverge until it + is called with one argument. Hence it is safe to eta-reduce `\x. e x` to `e`. By contrast, it would be *unsound* to eta-reduce 2 args, `\x y. e x y` to `e`: `e 42` diverges when `(\x y. e x y) 42` does not. -(S) It is sound to eta-reduce n arguments in an evaluation context in which all +(EtaS) It is sound to eta-reduce n arguments in an evaluation context in which all calls happen with at least n arguments. (Needs Strictness analysis.) NB: This treats evaluations like a call with 0 args. NB: This criterion exploits information about how `e` is *used*. @@ -2488,26 +2500,22 @@ case where `e` is trivial): See Note [Eta reduction based on evaluation context] for the implementation details. This criterion is tested extensively in T21261. -(R) Note [Eta reduction in recursive RHSs] tells us that we should not +(EtaR) Note [Eta reduction in recursive RHSs] tells us that we should not eta-reduce `f` in its own RHS and describes our fix. There we have `f = \x. f x` and we should not eta-reduce to `f=f`. Which might change a terminating program (think @f `seq` e@) to a non-terminating one. -(E) (See fun_arity in tryEtaReduce.) As a perhaps special case on the - boundary of (A) and (S), when we know that a fun binder `f` is in +(EtaE) (See fun_arity in tryEtaReduce.) As a perhaps special case on the + boundary of (EtaA) and (EtaS), when we know that a fun binder `f` is in WHNF, we simply assume it has arity 1 and apply (A). Example: g f = f `seq` \x. f x Here it's sound eta-reduce `\x. f x` to `f`, because `f` can't be bottom after the `seq`. This turned up in #7542. - T. If the binders are all type arguments, it's always safe to eta-reduce, - regardless of the arity of f. - /\a b. f @a @b --> f - -2. Type and dictionary abstraction. Regardless of whether 'f' is a value, it +(EtaT) Type and dictionary abstraction. Regardless of whether 'f' is a value, it is always sound to reduce /type lambdas/, thus: - (/\a -> f a) --> f + (/\a -> f @a) --> f Moreover, we always want to, because it makes RULEs apply more often: This RULE: `forall g. foldr (build (/\a -> g a))` should match `foldr (build (/\b -> ...something complex...))` @@ -2523,18 +2531,25 @@ case where `e` is trivial): And here are a few more technical criteria for when it is *not* sound to eta-reduce that are specific to Core and GHC: -(J) We may not undersaturate join points. +(EtaJ) We may not undersaturate join points. See Note [Invariants on join points] in GHC.Core, and #20599. -(B) We may not undersaturate functions with no binding. +(EtaB) We may not undersaturate functions with no binding. See Note [Eta expanding primops]. -(W) We may not undersaturate StrictWorkerIds. +(EtaW) We may not undersaturate StrictWorkerIds. See Note [CBV Function Ids: overview] in GHC.Types.Id.Info. -Here is a list of historic accidents surrounding unsound eta-reduction: -* Consider +Here is a list of historic notes surrounding unsound eta-reduction: + +(EtaMult) We used to disable eta-reduction if performing it would change multiplicity. + For example: + (\x. K x) :: Int -> T but K :: Int %1 -> T + But that (a) inhibits beneficial eta-reduction (b) costs extra work to check, and + now we don't even try. See Note [Linting linearity] in GHC.Core.Lint, esp EXAMPLE 4 + +(EtaBot) Consider f = \x.f x h y = case (case y of { True -> f `seq` True; False -> False }) of True -> ...; False -> ... @@ -2548,16 +2563,6 @@ Here is a list of historic accidents surrounding unsound eta-reduction: Result: seg-fault because the boolean case actually gets a function value. See #1947. -* Never *reduce* arity. For example - f = \xy. g x y - Then if h has arity 1 we don't want to eta-reduce because then - f's arity would decrease, and that is bad - [SG in 2022: I don't understand this point. There is no `h`, perhaps that - should have been `g`. Even then, this proposed eta-reduction is invalid by - criterion (A), which might actually be the point this anecdote is trying to - make. Perhaps the "no arity decrease" idea is also related to - Note [Arity robustness]?] - Note [Do not eta reduce PAPs] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ I considered eta-reducing if the result is a PAP: @@ -2713,13 +2718,13 @@ tryEtaReduce :: UnVarSet -> [Var] -> CoreExpr -> SubDemand -> Maybe CoreExpr -- and Note [Eta reduction makes sense] when that is the case. -- and Note [Eta reduction based on evaluation context] for the `eval_sd` arg tryEtaReduce rec_ids bndrs body eval_sd - = go (reverse bndrs) body (mkRepReflCo (exprType body)) + = go (reverse bndrs) body MRefl where - incoming_arity = count isId bndrs -- See Note [Eta reduction makes sense], point (2) + incoming_arity = count isId bndrs -- See (EtaA) in Note [Eta reduction soundness] go :: [Var] -- Binders, innermost first, types [a3,a2,a1] -> CoreExpr -- Of type tr - -> Coercion -- Of type tr ~ ts + -> MCoercion -- Of type tr ~ ts -> Maybe CoreExpr -- Of type a1 -> a2 -> a3 -> ts -- See Note [Eta reduction with casted arguments] -- for why we have an accumulating coercion @@ -2729,19 +2734,35 @@ tryEtaReduce rec_ids bndrs body eval_sd -- See Note [Eta reduction with casted function] go bs (Cast e co1) co2 - = go bs e (co1 `mkTransCo` co2) + = go bs e (co1 `mkTransMCoR` co2) go bs (Tick t e) co | tickishFloatable t = fmap (Tick t) $ go bs e co -- Float app ticks: \x -> Tick t (e x) ==> Tick t e - go (b : bs) (App fun arg) co - | Just (co', ticks) <- ok_arg b arg co (exprType fun) - = fmap (flip (foldr mkTick) ticks) $ go bs fun co' - -- Float arg ticks: \x -> e (Tick t x) ==> Tick t e + go all_bs@(b : bs) all_e@(App fun (Type arg_ty)) mco + | Just tv <- getTyVar_maybe arg_ty + , b == tv + , Just (bndr, body_ty) <- splitForAllForAllTyBinder_maybe (exprType fun) + = go bs fun (mkEtaReduceForAllMCo bndr body_ty tv mco) + + | otherwise + = go_finish all_bs all_e mco + -- Want to go to the finish case; see the call + -- to (all isTyVar remaining_bndrs) there + + go (b : bs) (App fun val_arg) mco + | Just (v, arg_mco, arg_ticks) <- getTrivialHead_maybe val_arg + , b == v + , Just co' <- mkEtaReduceFunCo (exprType fun) arg_mco mco + = fmap (flip (foldr mkTick) arg_ticks) $ + go bs fun co' + -- Float arg ticks: \x -> e (Tick t x) ==> Tick t e - go remaining_bndrs fun co + go bs fun co = go_finish bs fun co + + go_finish remaining_bndrs fun co | all isTyVar remaining_bndrs -- If all the remaining_bnrs are tyvars, then the etad_exp -- will be trivial, which is what we want. @@ -2752,7 +2773,7 @@ tryEtaReduce rec_ids bndrs body eval_sd , remaining_bndrs `ltLength` bndrs -- Only reply Just if /something/ has happened , ok_fun fun - , let used_vars = exprFreeVars fun `unionVarSet` tyCoVarsOfCo co + , let used_vars = exprFreeVars fun `unionVarSet` tyCoVarsOfMCo co reduced_bndrs = mkVarSet (dropList remaining_bndrs bndrs) -- reduced_bndrs are the ones we are eta-reducing away , used_vars `disjointVarSet` reduced_bndrs @@ -2761,10 +2782,10 @@ tryEtaReduce rec_ids bndrs body eval_sd -- See Note [Eta reduction makes sense], intro and point (1) -- NB: don't compute used_vars from exprFreeVars (mkCast fun co) -- because the latter may be ill formed if the guard fails (#21801) - = Just (mkLams (reverse remaining_bndrs) (mkCast fun co)) + = Just (mkLams (reverse remaining_bndrs) (mkCastMCo fun co)) - go _remaining_bndrs _fun _ = -- pprTrace "tER fail" (ppr _fun $$ ppr _remaining_bndrs) $ - Nothing + | otherwise + = Nothing --------------- -- See Note [Eta reduction makes sense], point (1) @@ -2777,18 +2798,18 @@ tryEtaReduce rec_ids bndrs body eval_sd --------------- -- See Note [Eta reduction soundness], this is THE place to check soundness! is_eta_reduction_sound fun - | fun `elemUnVarSet` rec_ids -- Criterion (R) + | fun `elemUnVarSet` rec_ids -- Criterion (EtaR) = False -- Don't eta-reduce in fun in its own recursive RHSs - | cantEtaReduceFun fun -- Criteria (J), (W), (B) + | cantEtaReduceFun fun -- Criteria (EtaJ), (EtaW), (EtaB) = False -- Function can't be eta reduced to arity 0 -- without violating invariants of Core and GHC | otherwise = -- Check that eta-reduction won't make the program stricter... - fun_arity fun >= incoming_arity -- Criterion (A) and (E) - || all_calls_with_arity incoming_arity -- Criterion (S) - || all ok_lam bndrs -- Criterion (T) + fun_arity fun >= incoming_arity -- Criterion (EtaA) and (EtaE) + || all_calls_with_arity incoming_arity -- Criterion (EtaS) + || all ok_lam bndrs -- Criterion (EtaT) all_calls_with_arity n = isStrict (fst $ peelManyCalls n eval_sd) -- See Note [Eta reduction based on evaluation context] @@ -2797,57 +2818,77 @@ tryEtaReduce rec_ids bndrs body eval_sd fun_arity fun | arity > 0 = arity | isEvaldUnfolding (idUnfolding fun) = 1 - -- See Note [Eta reduction soundness], criterion (E) + -- See Note [Eta reduction soundness], criterion (EtaE) | otherwise = 0 where arity = idArity fun --------------- ok_lam v = isTyVar v || isEvId v - -- See Note [Eta reduction makes sense], point (2) - - --------------- - ok_arg :: Var -- Of type bndr_t - -> CoreExpr -- Of type arg_t - -> Coercion -- Of kind (t1~t2) - -> Type -- Type (arg_t -> t1) of the function - -- to which the argument is supplied - -> Maybe (Coercion -- Of type (arg_t -> t1 ~ bndr_t -> t2) - -- (and similarly for tyvars, coercion args) - , [CoreTickish]) - -- See Note [Eta reduction with casted arguments] - ok_arg bndr (Type arg_ty) co fun_ty - | Just tv <- getTyVar_maybe arg_ty - , bndr == tv = case splitForAllForAllTyBinder_maybe fun_ty of - Just (Bndr _ vis, _) -> Just (fco, []) - where !fco = mkForAllCo tv vis coreTyLamForAllTyFlag MRefl co - -- The lambda we are eta-reducing always has visibility - -- 'coreTyLamForAllTyFlag' which may or may not match - -- the visibility on the inner function (#24014) - Nothing -> pprPanic "tryEtaReduce: type arg to non-forall type" - (text "fun:" <+> ppr bndr - $$ text "arg:" <+> ppr arg_ty - $$ text "fun_ty:" <+> ppr fun_ty) - ok_arg bndr (Var v) co fun_ty - | bndr == v - , let mult = idMult bndr - , Just (_af, fun_mult, _, _) <- splitFunTy_maybe fun_ty - , mult `eqType` fun_mult -- There is no change in multiplicity, otherwise we must abort - = Just (mkFunResCo Representational bndr co, []) - ok_arg bndr (Cast e co_arg) co fun_ty - | (ticks, Var v) <- stripTicksTop tickishFloatable e - , Just (_, fun_mult, _, _) <- splitFunTy_maybe fun_ty - , bndr == v - , fun_mult `eqType` idMult bndr - = Just (mkFunCoNoFTF Representational (multToCo fun_mult) (mkSymCo co_arg) co, ticks) - -- The simplifier combines multiple casts into one, - -- so we can have a simple-minded pattern match here - ok_arg bndr (Tick t arg) co fun_ty - | tickishFloatable t, Just (co', ticks) <- ok_arg bndr arg co fun_ty - = Just (co', t:ticks) - - ok_arg _ _ _ _ = Nothing + -- See Note [Eta reduction soundness], point (EtaT) + + +----------------- +getTrivialHead_maybe :: CoreExpr -> Maybe (Id, MCoercion, [CoreTickish]) +-- (go e) returns (Just (fn, co,ts)) +-- if `e` looks like (Tick ts (fn |> co)) and ts are floatable +-- So co :: fn_ty ~ arg_ty + +getTrivialHead_maybe (Var v) + = Just (v, MRefl, []) + +getTrivialHead_maybe (Cast e co_outer) + = do { (v, mco_inner, ticks) <- getTrivialHead_maybe e + ; return (v, mco_inner `mkTransMCoL` co_outer, ticks) } + +getTrivialHead_maybe (Tick t arg) + | tickishFloatable t + = do { (v, co, ticks) <- getTrivialHead_maybe arg + ; return (v, co, t:ticks) } + +getTrivialHead_maybe _ = Nothing + +----------------- +mkEtaReduceFunCo :: Type -> MCoercion -> MCoercion -> Maybe MCoercion +mkEtaReduceFunCo _ MRefl MRefl + = Just MRefl -- Very common case +mkEtaReduceFunCo fun_ty arg_mco res_mco + | Just (ftf, mult, arg_ty, res_ty) <- splitFunTy_maybe fun_ty + -- fun_ty = arg_ty -> res_ty + -- sym arg_mco : arg_ty ~ inner_arg_ty + -- res_mco : res_ty ~ outer_res_ty + , let arg_co = mCoToCo Representational arg_ty arg_mco + res_co = mCoToCo Representational res_ty res_mco + mult_co = multToCo mult + ftf' = chooseFunTyFlag (coercionLKind arg_co) (coercionRKind res_co) + = Just (MCo (mkFunCo2 Representational ftf ftf' mult_co (mkSymCo arg_co) res_co)) + -- (arg_ty -> res_ty) ~ (inner_arg_ty -> outer_res_ty) + | otherwise + = Nothing + where +----------------- +mkEtaReduceForAllMCo :: ForAllTyBinder -> Type -> TyVar -> MCoercion -> MCoercion +-- Very similar to mkEtaForAllMCo, but with +-- the visibilities the other way around. Tiresome. +-- mkEtaReduceForAllMCo (forall a[vis]. body_ty) b (co :: ty1 ~ ty2) +-- (where `b` may be free in `ty1` and `ty2`) +-- = ForAllCo a[vis]~[spec]. ty1 ~ ty2 +-- where `coreTyLamForAllTyFlag` is [spec] +mkEtaReduceForAllMCo (Bndr fun_tv vis) body_ty tv mco + = case mco of + MRefl | isCoreTyLamForAllTyFlag vis + -- The lambda we are eta-reducing always has visibility + -- 'coreTyLamForAllTyFlag' which may or may not match the + -- visibility on the inner function (#24014) + -> MRefl + | otherwise + -> MCo $ mkForAllCo fun_tv vis coreTyLamForAllTyFlag MRefl refl_co + MCo co -> MCo $ mkForAllCo tv vis coreTyLamForAllTyFlag MRefl co + -- Tricky: `fun_tv` scopes over `body_ty` and hence over `refl_co` + -- but: `tv` scopes over `mco` and hence over `co` + where + refl_co = mkRepReflCo body_ty {- ********************************************************************* * * ===================================== compiler/GHC/Core/Opt/OccurAnal.hs ===================================== @@ -42,7 +42,6 @@ import GHC.Core.Utils ( exprIsTrivial, isDefaultAlt, isExpandableApp, import GHC.Core.Opt.Arity ( joinRhsArity, isOneShotBndr ) import GHC.Core.Coercion import GHC.Core.Type -import GHC.Core.TyCo.FVs ( tyCoVarsOfMCo ) import GHC.Data.Maybe( orElse ) import GHC.Data.Graph.Directed ( SCC(..), Node(..) @@ -2227,7 +2226,7 @@ lambda and casts, e.g. * Why do we take care to account for intervening casts? Answer: currently we don't do eta-expansion and cast-swizzling in a stable - unfolding (see Historical-note [Eta-expansion in stable unfoldings]). + unfolding (see Note [Eta expansion in stable unfoldings and rules]) So we can get f = \x. ((\y. ...x...y...) |> co) Now, since the lambdas aren't together, the occurrence analyser will ===================================== compiler/GHC/Core/Opt/Pipeline.hs ===================================== @@ -352,8 +352,25 @@ runMaybe :: Maybe a -> (a -> CoreToDo) -> CoreToDo runMaybe (Just x) f = f x runMaybe Nothing _ = CoreDoNothing -{- Note [Inline in InitialPhase] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +{- Note [The InitialPhase of the Simplifier] +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +The first run of the simplifier, historically called "gentle" simplification, +has phase=InitialPhase, which does a number of things: + +* Usually sm_case_case is switched off in this phase; see + Note [Case-of-case and full laziness] and `initGentleSimplMode` + +* Inlining, however, is not switched off in InitialPhase. + See Note [Inline in InitialPhase] + +* Rules can run in InitialPhase + Note [RULEs enabled in InitialPhase] + +* Lint is a little agressive about loop-breaker warnings in InitialPhase. + See `check_lbs` in `GHC.Core.Lint.perPassFlags`. + +Note [Inline in InitialPhase] +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In GHC 8 and earlier we did not inline anything in the InitialPhase. But that is confusing for users because when they say INLINE they expect the function to inline right away. ===================================== compiler/GHC/Core/Opt/Simplify/Env.hs ===================================== @@ -355,12 +355,18 @@ This simplifier phase is stored in the sm_phase field of SimplMode, usin the 'SimplPhase' constructor. This allows us to determine which rules/inlinings are active. -When we invoke the simplifier on the RHS of a rule, such as 'rhs' above, instead -of setting the simplifier mode to a single phase, we use a phase range -corresponding to the range of phases in which the rule is active, with the -'SimplPhaseRange' constructor. This allows us to check whether other rules or -inlinings are active throughout the whole activation of the rule. -See Note [What is active in the RHS of a RULE or unfolding?] in GHC.Core.Opt.Simplify.Utils. +Wrinkles + +(SP1) InitialPhase: see Note [The InitialPhase of the Simplifier] + in GHC.Core.Opt.Pipeline. + +(SP2) Phase ranges. When we invoke the simplifier on the RHS of a rule, such as + `rhs` above, instead of setting the simplifier mode to a single phase, we use a + phase /range/ corresponding to the range of phases in which the rule is active, + with the 'SimplPhaseRange' constructor. This allows us to check whether other + rules or inlinings are active throughout the whole activation of the rule. See + Note [What is active in the RHS of a RULE or unfolding?] in + GHC.Core.Opt.Simplify.Utils. -} instance Outputable SimplMode where @@ -1234,6 +1240,8 @@ out_id so that its arity is visible in its RHS. Examples: Example: `f = \x. f x`. See Note [Eta reduction in recursive RHSs] for how we prevent that. +c.f. (EtaA) in Note [Eta reduction soundness] in GHC.Core.Opt.Arity. + Note [Robust OccInfo] ~~~~~~~~~~~~~~~~~~~~~ It's important that we *do* retain the loop-breaker OccInfo, because ===================================== compiler/GHC/Core/Opt/Simplify/Inline.hs ===================================== @@ -126,11 +126,6 @@ activeUnfolding mode id | otherwise = isActive (sm_phase mode) (idInlineActivation id) && sm_inline mode - -- `or` isStableUnfolding (realIdUnfolding id) - -- Inline things when - -- (a) they are active - -- (b) sm_inline says so, except that for stable unfoldings - -- (ie pragmas) we inline anyway -- | Report the inlining of an identifier's RHS to the user, if requested. traceInline :: Logger -> UnfoldingOpts -> Id -> String -> SDoc -> a -> a ===================================== compiler/GHC/Core/Opt/Simplify/Iteration.hs ===================================== @@ -4959,7 +4959,7 @@ eta-expand the stable unfolding to arity N too. Simple and consistent. Wrinkles -* See Historical-note [Eta-expansion in stable unfoldings] in +* See Note [Eta expansion in stable unfoldings and rules] GHC.Core.Opt.Simplify.Utils * Don't eta-expand a trivial expr, else each pass will eta-reduce it, ===================================== compiler/GHC/Core/Opt/Simplify/Utils.hs ===================================== @@ -1319,43 +1319,6 @@ But this old note is no longer relevant because the specialiser has improved: see Note [Account for casts in binding] in GHC.Core.Opt.Specialise. So we seem to have a free choice. -Note [Inlining in gentle mode] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Something is inlined if - (i) the sm_inline flag is on, AND - (ii) the thing has an INLINE pragma, AND - (iii) the thing is inlinable in the earliest phase. - -Example of why (iii) is important: - {-# INLINE [~1] g #-} - g = ... - - {-# INLINE f #-} - f x = g (g x) - -If we were to inline g into f's inlining, then an importing module would -never be able to do - f e --> g (g e) ---> RULE fires -because the stable unfolding for f has had g inlined into it. - -On the other hand, it is bad not to do ANY inlining into an -stable unfolding, because then recursive knots in instance declarations -don't get unravelled. - -However, *sometimes* SimplGently must do no call-site inlining at all -(hence sm_inline = False). Before full laziness we must be careful -not to inline wrappers, because doing so inhibits floating - e.g. ...(case f x of ...)... - ==> ...(case (case x of I# x# -> fw x#) of ...)... - ==> ...(case x of I# x# -> case fw x# of ...)... -and now the redex (f x) isn't floatable any more. - -The no-inlining thing is also important for Template Haskell. You might be -compiling in one-shot mode with -O2; but when TH compiles a splice before -running it, we don't want to use -O2. Indeed, we don't want to inline -anything, because the byte-code interpreter might get confused about -unboxed tuples and suchlike. - Note [What is active in the RHS of a RULE or unfolding?] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Suppose we have either a RULE or a stable unfolding with an explicit activation: @@ -1448,7 +1411,7 @@ First, consider the following example Now, if that's the ONLY occurrence of f, it might be inlined inside g, and thence copied multiple times when g is inlined. HENCE we treat any occurrence in a stable unfolding as a multiple occurrence, not a single -one; see OccurAnal.addRuleUsage. +one; see Note [Occurrences in stable unfoldings and RULES] in GHC.Core.opt.OccurAnal. Second, we must be careful when simplifying the RHS that we do not apply RULES which are not active over the whole active range of the stable unfolding. @@ -1477,17 +1440,6 @@ strictness wrapper get activation (ActiveAfter 0). So the strictness wrepper fails the test and won't be inlined into f's stable unfolding. That means f can inline, expose the specialised call to g, so the specialisation rules can fire. - -A note about wrappers -~~~~~~~~~~~~~~~~~~~~~ -It's also important not to inline a worker back into a wrapper. -A wrapper looks like - wraper = inline_me (\x -> ...worker... ) -Normally, the inline_me prevents the worker getting inlined into -the wrapper (initially, the worker's only call site!). But, -if the wrapper is sure to be called, the strictness analyser will -mark it 'demanded', so when the RHS is simplified, it'll get an ArgOf -continuation. -} getUnfoldingInRuleMatch :: SimplEnv -> InScopeEnv @@ -2158,8 +2110,9 @@ tryEtaExpandRhs :: SimplEnv -> BindContext -> OutId -> OutExpr tryEtaExpandRhs env bind_cxt bndr rhs | seEtaExpand env -- If Eta-expansion is on , wantEtaExpansion rhs -- and we'd like to eta-expand e - , do_eta_expand -- and e's manifest arity is lower than - -- what it could be + , do_eta_expand -- and arity analysis finds a greater arity + -- than (exprArity e); NB: not manifestArity + -- See Note [Do not eta-expand PAPs] -- (never true for join points) = -- Do eta-expansion. assertPpr( not (isJoinBC bind_cxt) ) (ppr bndr) $ @@ -2178,7 +2131,8 @@ tryEtaExpandRhs env bind_cxt bndr rhs (do_eta_expand, arity_type) = findRhsArity arity_opts is_rec bndr rhs wantEtaExpansion :: CoreExpr -> Bool --- Mostly True; but False of PAPs which will immediately eta-reduce again +-- Mostly True; but False of trivial RHSs, and of PAPs at the top of the RHS +-- (PAPs under value lambdas are dealt with by findRhsArity) -- See Note [Which RHSs do we eta-expand?] wantEtaExpansion (Cast e _) = wantEtaExpansion e wantEtaExpansion (Tick _ e) = wantEtaExpansion e @@ -2195,24 +2149,6 @@ We now eta expand at let-bindings, which is where the payoff comes. The most significant thing is that we can do a simple arity analysis (in GHC.Core.Opt.Arity.findRhsArity), which we can't do for free-floating lambdas -One useful consequence of not eta-expanding lambdas is this example: - genMap :: C a => ... - {-# INLINE genMap #-} - genMap f xs = ... - - myMap :: D a => ... - {-# INLINE myMap #-} - myMap = genMap - -Notice that 'genMap' should only inline if applied to two arguments. -In the stable unfolding for myMap we'll have the unfolding - (\d -> genMap Int (..d..)) -We do not want to eta-expand to - (\d f xs -> genMap Int (..d..) f xs) -because then 'genMap' will inline, and it really shouldn't: at least -as far as the programmer is concerned, it's not applied to two -arguments! - Note [Which RHSs do we eta-expand?] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We don't eta-expand: @@ -2234,7 +2170,22 @@ seems like a Good idea. Note [Do not eta-expand PAPs] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -We used to have old_arity = manifestArity rhs, which meant that we +We do not eta-expand a RHS that is a partial application (PAP). This +is achieved in two places: + +(DEP1) A PAP at the top of the RHS, such as + f = g d -- g has arity 2 + is rejected by `wantEtaExpansion`. + +(DEP2) A PAP under value lambdas, such as + f = \x. g x -- g has arity 3 + is not eta-expanded because `findRhsArity` asks for eta-expansion + only if the arity it finds is greater than (exprArity rhs), and + `exprArity` takes account of PAPs: here (exprArity rhs) = 3. + Using `manifestArity` (which is 1 here) instead would eta-expand + to f = \x y z. g x y z. + +Up to 2014 we used old_arity = manifestArity rhs, which meant that we would eta-expand even PAPs. But this gives no particular advantage, and can lead to a massive blow-up in code size, exhibited by #9020. Suppose we have a PAP @@ -2250,6 +2201,17 @@ coercions and whatnot that eventually disappear again. For T9020, GHC allocated 6.6G before, and 0.8G afterwards; and residency dropped from 1.8G to 45M. +#27212 tried switching (DEP2) back to manifestArity, with these results: + +* T13960: bytestring's + cstring1 = \(a::Addr#) @r. cstring2 @r a -- cstring2 has arity 4 + was eta-expanded to (\a @r k br s. cstring2 @r a k br s). That bigger + unfolding is inlined at every string literal, adding 6 terms per + literal; compile-time allocation went up by 9%. + +* T13056: a derived-instance method (\ @a d. lvl @a), where `lvl` is + bottoming, was eta-expanded, and then needlessly worker/wrappered. + Moreover, if we eta expand f = g d ==> f = \x. g d x that might in turn make g inline (if it has an inline pragma), which @@ -2261,6 +2223,24 @@ But note that this won't eta-expand, say Does it matter not eta-expanding such functions? I'm not sure. Perhaps strictness analysis will have less to bite on? +One useful consequence of not eta-expanding PAPs is this example: + genMap :: C a => ... + {-# INLINE genMap #-} + genMap f xs = ... + + myMap :: D a => ... + {-# INLINE myMap #-} + myMap = genMap + +Notice that 'genMap' should only inline if applied to two arguments. +In the stable unfolding for myMap we'll have the unfolding + (\d -> genMap Int (..d..)) +We do not want to eta-expand to + (\d f xs -> genMap Int (..d..) f xs) +because then 'genMap' will inline, and it really shouldn't: at least +as far as the programmer is concerned, it's not applied to two +arguments! + ************************************************************************ * * ===================================== compiler/GHC/Core/Opt/Specialise.hs ===================================== @@ -3345,7 +3345,7 @@ pair_fvs :: (Id, CoreExpr) -> VarSet pair_fvs (bndr, rhs) = exprSomeFreeVars interesting rhs `unionVarSet` bndrFreeVars bndr -- bndrFreeVars: don't forget variables mentioned in - -- the rules of the bndr. C.f. OccAnal.addRuleUsage + -- the rules or unfolding of the bndr. -- Also tyvars mentioned in its type; they may not appear -- in the RHS -- type T a = Int ===================================== compiler/GHC/Core/TyCo/Make.hs ===================================== @@ -58,7 +58,7 @@ module GHC.Core.TyCo.Make ( , mkAxInstCo , mkTransCo, mkTransMCo, mkTransMCoL, mkTransMCoR , mkProofIrrelCo - , coToMCo, kindCoToMKindCo + , coToMCo, kindCoToMKindCo, mCoToCo , mkCoherenceLeftCo, mkCoherenceRightCo, mkCoherenceRightMCo , toPhantomCo, mkPhantomCo , isReflCo, isReflMCo, isReflKindCo, isReflKindMCo, isReflCo_maybe @@ -860,7 +860,7 @@ mkHomoForAllCos vs orig_co = foldr go orig_co vs where go :: ForAllTyBinder -> Coercion -> Coercion - go (Bndr var vis) co = mk_forall_co var vis vis MRefl co + go (Bndr var vis) co = mkForAllCoNonRefl var vis vis MRefl co mkHomoForAllCo :: TyVar -> Coercion -> Coercion -- Specialised for a single TyVar, @@ -869,7 +869,7 @@ mkHomoForAllCo tv orig_co | Just (ty, r) <- isReflCo_maybe orig_co = mkReflCo r (mkForAllTy (Bndr tv vis) ty) | otherwise - = mk_forall_co tv vis vis MRefl orig_co + = mkForAllCoNonRefl tv vis vis MRefl orig_co where vis = coreTyLamForAllTyFlag @@ -892,15 +892,15 @@ mkForAllCo v visL visR kind_co co | Just refl_co <- isReflForAllCo v visL visR kind_co co = refl_co | otherwise - = mk_forall_co v visL visR kind_co co + = mkForAllCoNonRefl v visL visR kind_co co --- | `mk_forall_co` just builds a ForAllCo. +-- | `mkForAllCoNonRefl` just builds a ForAllCo. -- With debug on, it checks invariants (e.g. he kind of the tycovar should -- be the left-hand kind of the kind coercion). -- Callers should have done any isReflCo short-cutting. -mk_forall_co :: TyCoVar -> ForAllTyFlag -> ForAllTyFlag - -> KindMCoercion -> Coercion -> Coercion -mk_forall_co tcv visL visR kind_co co +mkForAllCoNonRefl :: TyCoVar -> ForAllTyFlag -> ForAllTyFlag + -> KindMCoercion -> Coercion -> Coercion +mkForAllCoNonRefl tcv visL visR kind_co co = assertGoodForAllCo tcv visL visR kind_co co $ assertPpr (not (isReflCo co && isReflMCo kind_co && visL `eqForAllVis` visR)) (ppr co) $ ForAllCo { fco_tcv = tcv, fco_visL = visL, fco_visR = visR @@ -1289,6 +1289,10 @@ coToMCo :: Coercion -> MCoercion coToMCo co | isReflCo co = MRefl | otherwise = MCo co +mCoToCo :: Role -> Type -> MCoercion -> Coercion +mCoToCo role ty MRefl = mkReflCo role ty +mCoToCo _ _ (MCo co) = co + kindCoToMKindCo :: KindCoercion -> KindMCoercion -- Convert a KindCoercion to a KindMCoercion, -- coToMCo doesn't eliminate GRefl, but kindCoToMCo can ===================================== compiler/GHC/Core/Type.hs ===================================== @@ -160,7 +160,7 @@ module GHC.Core.Type ( -- * Type free variables tyCoVarsOfType, tyCoVarsOfTypes, tyCoVarsOfTypeDSet, - coVarsOfType, coVarsOfTypes, + tyCoVarsOfMCo, coVarsOfType, coVarsOfTypes, anyFreeVarsOfType, anyFreeVarsOfTypes, noFreeVarsOfType, ===================================== compiler/GHC/Core/Utils.hs ===================================== @@ -3295,17 +3295,16 @@ Now the caller guarantees to pass an EPT argument (see Note [EPT enforcement] in GHC.Core.Stg.EnforceEpt) - * The code generator will discard that "extra eval" case, because $wfoo is - CBV. + * The code generator will discard that "extra eval" case, because $wfoo is CBV. See also Note [CBV Function Ids: overview]. -In tihs case the argument is known to be properly tagged at the call site so there is +In this case the argument is known to be properly tagged at the call site so there is no additional work for the caller and the worker can be more efficient since it can assume the presence of a tag. This is especially true for recursive functions like this: - -- myPred expect it's argument properly tagged + -- myPred expects its argument properly tagged -- The EnforceEPT pass has made it a CBV function myPred !x = ... @@ -3414,16 +3413,17 @@ This note deals with the second part. There are multiple reasons why we might not want to insert a seq in the rhs to strictify a functions argument: -1) The argument doesn't exist at runtime. - For zero width types (like Types) there is no benefit as we don't operate on them - at runtime at all. This includes things like void#, coercions and state tokens. +(WIS1) The argument doesn't exist at runtime: types are erased. -2) The argument is a unlifted type. +(WIS2) For zero width types there is no benefit as we don't operate on them at + runtime at all. This includes things like void#, coercions and state tokens. + +(WIS3) The argument is a unlifted type. If the argument is a unlifted type the calling convention already is explicitly cbv. This means inserting a seq on this argument wouldn't do anything as the seq would be a no-op *and* it wouldn't affect the calling convention. -3) The argument is absent. +(WIS4) The argument is absent. If the argument is absent in the body there is no advantage to it being passed as cbv to the function. The function won't ever look at it so we don't save any work. @@ -3445,7 +3445,7 @@ strictify a functions argument: Note [Absent fillers] has an example of this. However this is so rare it's not worth caring about here. -5) Functions +(WIS5) Functions Functions are tricky (see Note [TagInfo of functions] in EnforceEpt). But the gist of it even if we make a higher order function argument strict we can't avoid the tag check when it's used later in the body. @@ -3453,7 +3453,7 @@ strictify a functions argument: Wrinkles: -(WIS1) You might have thought that we can omit the eval if the argument is used +(WIS6) You might have thought that we can omit the eval if the argument is used strictly demanded in the body. But you'd be wrong. Consider this code: data T = MkT ![Int] f t = case t of MkT xs{Dmd=STR} -> reverse xs @@ -3509,25 +3509,30 @@ Wrinkles: wantCbvForId :: Var -> Bool wantCbvForId v -- Must be a runtime var. - -- See Note [Which Ids should be strictified] point 1) - | isId v - , not $ isZeroBitTy ty + -- See (WIS1) in Note [Which Ids should be strictified] + | not (isRuntimeVar v) = False + + -- Not zero-width value + -- See (WIS2) in Note [Which Ids should be strictified] + | isZeroBitTy ty = False + -- Unlifted things don't need special measures to be treated as cbv - -- See Note [Which Ids should be strictified] point 2) - , mightBeLiftedType ty + -- See (WIS3) in Note [Which Ids should be strictified] + | definitelyUnliftedType ty = False + + -- If the var is absent, don't add a seq + -- See (WIS4) in Note [Which Ids should be strictified] + | isAbsDmd (idDemandInfo v) = False + -- Functions sometimes get a zero tag so we can't eliminate the tag check. -- See Note [TagInfo of functions] in EnforceEpt. - -- See Note [Which Ids should be strictified] point 5) - , not $ isFunTy ty - -- If the var is strict already a seq is redundant. - -- See Note [Which Ids should be strictified] point 4) - , not (isAbsDmd dmd) - = True - | otherwise - = False + -- See (WIS5) in Note [Which Ids should be strictified] + | isFunTy ty = False + + -- Finally! We should add a `seq` + | otherwise = True where ty = idType v - dmd = idDemandInfo v {- ********************************************************************* * * ===================================== compiler/GHC/Driver/Config/Core/Opt/Simplify.hs ===================================== @@ -77,6 +77,7 @@ initSimplMode dflags phase name = SimplMode } initGentleSimplMode :: DynFlags -> SimplMode +-- See Note [The InitialPhase of the Simplifier] in GHC.Core.Opt.Pipeline initGentleSimplMode dflags = (initSimplMode dflags InitialPhase "Gentle") { -- Don't do case-of-case transformations. -- This makes full laziness work better ===================================== compiler/Language/Haskell/Syntax/Binds/InlinePragma.hs ===================================== @@ -124,11 +124,15 @@ Note [inl_inline and inl_act] INLINABLE, OPAQUE, or nothing at all * inl_act says in what phases the unfolding is active or inactive - E.g If you write INLINE[1] then inl_act will be set to ActiveAfter 1 - If you write NOINLINE[1] then inl_act will be set to ActiveBefore 1 - If you write NOINLINE[~1] then inl_act will be set to ActiveAfter 1 - So note that inl_act does not say what pragma you wrote: it just - expresses its consequences + E.g If you write then inl_act will be set to + INLINE AlwaysActive + INLINE[1] ActiveAfter 1 + INLINE[~1] ActiveBefore 1 + NOINLINE[1] ActiveAfter 1 + NOINLINE[~1] ActiveBefore 1 + NOINLINE NeverActive + So note that inl_act does not say what pragma you wrote: + it just expresses its consequences * inl_act just says when the unfolding is active; it doesn't say what to inline. If you say INLINE f, then f's inl_act will be AlwaysActive, ===================================== docs/users_guide/debug-info.rst ===================================== @@ -69,8 +69,9 @@ Here we used the ``-g`` option to inform GHC that it should add debugging information in the produced binary. There are three levels of debugging output: ``-g0`` (no debugging information, the default), ``-g1`` (sufficient for basic backtraces), ``-g2`` (or just ``-g`` for short; emitting everything GHC knows). -Note that this debugging information does not affect the optimizations performed -by GHC. +Note that this debugging information does not affect the optimizations +that GHC attempts to perform; but it can affect how successful it is in +performing them (see #21471, #27687) .. tip:: Under Mac OS X debug information is kept apart from the executable. After ===================================== docs/users_guide/using-optimisation.rst ===================================== @@ -1817,7 +1817,7 @@ as such you shouldn't need to set any of them explicitly. A flag :type: dynamic :category: - :default: 80 + :default: 90 .. index:: single: inlining, controlling ===================================== testsuite/tests/dmdanal/sigs/T21888a.stderr ===================================== @@ -7,7 +7,7 @@ T21888a.wombat: <S!P(S)>b ==================== Cpr signatures ==================== -T21888a.f: 2 +T21888a.f: T21888a.g: 1 T21888a.wombat: b ===================================== testsuite/tests/printer/T18052a.stderr ===================================== @@ -10,11 +10,11 @@ Dependent packages: [(normal, base-4.23.0.0)] ==================== Tidy Core ==================== Result size of Tidy Core - = {terms: 24, types: 52, coercions: 0, joins: 0/0} + = {terms: 18, types: 46, coercions: 0, joins: 0/0} --- RHS size: {terms: 7, types: 6, coercions: 0, joins: 0/0} +-- RHS size: {terms: 1, types: 0, coercions: 0, joins: 0/0} T18052a.$b:||: :: forall {a} {b}. a -> b -> (a, b) -T18052a.$b:||: = \ (@a) (@b) (x :: a) (y :: b) -> (x, y) +T18052a.$b:||: = GHC.Internal.Tuple.(,) -- RHS size: {terms: 1, types: 0, coercions: 0, joins: 0/0} (+++) :: forall {a}. [a] -> [a] -> [a] ===================================== testsuite/tests/simplCore/should_compile/T27212.hs ===================================== @@ -0,0 +1,17 @@ +module T27212 where + +import Unsafe.Coerce + +class Given a where given :: a +newtype Gift a r = Gift (Given a => r) + +useIt :: Given Int => Int +useIt = given + 1 +{-# NOINLINE useIt #-} + +foo :: [Int] -> [Int] +foo xs = case unsafeEqualityProof @(Gift Int Int) @(Int -> Int) of + UnsafeRefl -> map (\y -> (Gift useIt :: Gift Int Int) y) xs + -- That (\y. glah y) can eta-reduce to `glah` + -- but doing doing so make a FunCo coercion that crosses from + -- Type to constraint. Tricky. ===================================== testsuite/tests/simplCore/should_compile/all.T ===================================== @@ -631,3 +631,4 @@ test('T27936', normal, compile, ['']) test('T27910', grep_errmsg(r'KnownBranch'), compile, ['-O -dno-typeable-binds -ddump-simpl-stats -dsuppress-uniques']) test('T27892', grep_errmsg(r'^f = g$'), compile, ['-O -ddump-cse -dsuppress-all -dsuppress-uniques']) test('T28095a', grep_errmsg(r'^f = g$'), compile, ['-O -ddump-cse -dsuppress-all -dsuppress-uniques']) +test('T27212', normal, compile, ['-O']) View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/0d032608b133f5f194ba6109b839d6e... -- View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/0d032608b133f5f194ba6109b839d6e... 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)