\end{code}
The guts of the simplifier is in this module, but the driver loop for
the simplifier is in SimplCore.lhs.
-----------------------------------------
*** IMPORTANT NOTE ***
-----------------------------------------
The simplifier used to guarantee that the output had no shadowing, but
it does not do so any more. (Actually, it never did!) The reason is
documented with simplifyArgs.
-----------------------------------------
*** IMPORTANT NOTE ***
-----------------------------------------
Many parts of the simplifier return a bunch of "floats" as well as an
expression. This is wrapped as a datatype SimplUtils.FloatsWith.
All "floats" are let-binds, not case-binds, but some non-rec lets may
be unlifted (with RHS ok-for-speculation).
-----------------------------------------
ORGANISATION OF FUNCTIONS
-----------------------------------------
simplTopBinds
- simplify all top-level binders
- for NonRec, call simplRecOrTopPair
- for Rec, call simplRecBind
------------------------------
simplExpr (applied lambda) ==> simplNonRecBind
simplExpr (Let (NonRec ...) ..) ==> simplNonRecBind
simplExpr (Let (Rec ...) ..) ==> simplify binders; simplRecBind
------------------------------
simplRecBind [binders already simplfied]
- use simplRecOrTopPair on each pair in turn
simplRecOrTopPair [binder already simplified]
Used for: recursive bindings (top level and nested)
top-level non-recursive bindings
Returns:
- check for PreInlineUnconditionally
- simplLazyBind
simplNonRecBind
Used for: non-top-level non-recursive bindings
beta reductions (which amount to the same thing)
Because it can deal with strict arts, it takes a
"thing-inside" and returns an expression
- check for PreInlineUnconditionally
- simplify binder, including its IdInfo
- if strict binding
simplStrictArg
mkAtomicArgs
completeNonRecX
else
simplLazyBind
addFloats
simplNonRecX: [given a *simplified* RHS, but an *unsimplified* binder]
Used for: binding case-binder and constr args in a known-constructor case
- check for PreInLineUnconditionally
- simplify binder
- completeNonRecX
------------------------------
simplLazyBind: [binder already simplified, RHS not]
Used for: recursive bindings (top level and nested)
top-level non-recursive bindings
non-top-level, but *lazy* non-recursive bindings
[must not be strict or unboxed]
Returns floats + an augmented environment, not an expression
- substituteIdInfo and add result to in-scope
[so that rules are available in rec rhs]
- simplify rhs
- mkAtomicArgs
- float if exposes constructor or PAP
- completeBind
completeNonRecX: [binder and rhs both simplified]
- if the the thing needs case binding (unlifted and not ok-for-spec)
build a Case
else
completeBind
addFloats
completeBind: [given a simplified RHS]
[used for both rec and non-rec bindings, top level and not]
- try PostInlineUnconditionally
- add unfolding [this is the only place we add an unfolding]
- add arity
Right hand sides and arguments
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In many ways we want to treat
(a) the right hand side of a let(rec), and
(b) a function argument
in the same way. But not always! In particular, we would
like to leave these arguments exactly as they are, so they
will match a RULE more easily.
f (g x, h x)
g (+ x)
It's harder to make the rule match if we ANF-ise the constructor,
or eta-expand the PAP:
f (let { a = g x; b = h x } in (a,b))
g (\y. + x y)
On the other hand if we see the let-defns
p = (g x, h x)
q = + x
then we *do* want to ANF-ise and eta-expand, so that p and q
can be safely inlined.
Even floating lets out is a bit dubious. For let RHS's we float lets
out if that exposes a value, so that the value can be inlined more vigorously.
For example
r = let x = e in (x,x)
Here, if we float the let out we'll expose a nice constructor. We did experiments
that showed this to be a generally good thing. But it was a bad thing to float
lets out unconditionally, because that meant they got allocated more often.
For function arguments, there's less reason to expose a constructor (it won't
get inlined). Just possibly it might make a rule match, but I'm pretty skeptical.
So for the moment we don't float lets out of function arguments either.
Eta expansion
~~~~~~~~~~~~~~
For eta expansion, we want to catch things like
case e of (a,b) -> \x -> case a of (p,q) -> \y -> r
If the \x was on the RHS of a let, we'd eta expand to bring the two
lambdas together. And in general that's a good thing to do. Perhaps
we should eta expand wherever we find a (value) lambda? Then the eta
expansion at a let RHS can concentrate solely on the PAP case.
%************************************************************************
%* *
\subsection{Bindings}
%* *
%************************************************************************
\begin{code}

simplTopBinds::SimplEnv->[InBind]->SimplMSimplEnvsimplTopBindsenv0binds0=do{-- Put all the top-level binders into scope at the start-- so that if a transformation rule has unexpectedly brought-- anything into scope, then we don't get a complaint about that.-- It's rather as if the top-level binders were imported.-- See note [Glomming] in OccurAnal.;env1<-simplRecBndrsenv0(bindersOfBindsbinds0);dflags<-getDynFlags;letdump_flag=doptOpt_D_verbose_core2coredflags;env2<-simpl_bindsdump_flagenv1binds0;freeTickSimplifierDone;returnenv2}where-- We need to track the zapped top-level binders, because-- they should have their fragile IdInfo zapped (notably occurrence info)-- That's why we run down binds and bndrs' simultaneously.---- The dump-flag emits a trace for each top-level binding, which-- helps to locate the tracing for inlining and rule firingsimpl_binds::Bool->SimplEnv->[InBind]->SimplMSimplEnvsimpl_binds_env[]=returnenvsimpl_bindsdumpenv(bind:binds)=do{env'<-trace_binddumpbind$simpl_bindenvbind;simpl_bindsdumpenv'binds}trace_bindTruebind=pprTrace"SimplBind"(ppr(bindersOfbind))trace_bindFalse_=\x->xsimpl_bindenv(Recpairs)=simplRecBindenvTopLevelpairssimpl_bindenv(NonRecbr)=simplRecOrTopPairenv'TopLevelNonRecursivebb'rwhere(env',b')=addBndrRulesenvb(lookupRecBndrenvb)

simplRecBind::SimplEnv->TopLevelFlag->[(InId,InExpr)]->SimplMSimplEnvsimplRecBindenv0top_lvlpairs0=do{let(env_with_info,triples)=mapAccumLadd_rulesenv0pairs0;env1<-go(zapFloatsenv_with_info)triples;return(env0`addRecFloats`env1)}-- addFloats adds the floats from env1,-- _and_ updates env0 with the in-scope set from env1whereadd_rules::SimplEnv->(InBndr,InExpr)->(SimplEnv,(InBndr,OutBndr,InExpr))-- Add the (substituted) rules to the binderadd_rulesenv(bndr,rhs)=(env',(bndr,bndr',rhs))where(env',bndr')=addBndrRulesenvbndr(lookupRecBndrenvbndr)goenv[]=returnenvgoenv((old_bndr,new_bndr,rhs):pairs)=do{env'<-simplRecOrTopPairenvtop_lvlRecursiveold_bndrnew_bndrrhs;goenv'pairs}

\end{code}
simplOrTopPair is used for
* recursive bindings (whether top level or not)
* top-level non-recursive bindings
It assumes the binder has already been simplified, but not its IdInfo.
\begin{code}

simplRecOrTopPair::SimplEnv->TopLevelFlag->RecFlag->InId->OutBndr->InExpr-- Binder and rhs->SimplMSimplEnv-- Returns an env that includes the bindingsimplRecOrTopPairenvtop_lvlis_recold_bndrnew_bndrrhs=dodflags<-getDynFlags-- Check for unconditional inlineifpreInlineUnconditionallydflagsenvtop_lvlold_bndrrhsthendotick(PreInlineUnconditionallyold_bndr)return(extendIdSubstenvold_bndr(mkContExenvrhs))elsesimplLazyBindenvtop_lvlis_recold_bndrnew_bndrrhsenv

\end{code}
simplLazyBind is used for
* [simplRecOrTopPair] recursive bindings (whether top level or not)
* [simplRecOrTopPair] top-level non-recursive bindings
* [simplNonRecE] non-top-level *lazy* non-recursive bindings
Nota bene:
1. It assumes that the binder is *already* simplified,
and is in scope, and its IdInfo too, except unfolding
2. It assumes that the binder type is lifted.
3. It does not check for pre-inline-unconditionallly;
that should have been done already.
\begin{code}

\end{code}
A specialised variant of simplNonRec used when the RHS is already simplified,
notably in knownCon. It uses case-binding where necessary.
\begin{code}

simplNonRecX::SimplEnv->InId-- Old binder->OutExpr-- Simplified RHS->SimplMSimplEnvsimplNonRecXenvbndrnew_rhs|isDeadBinderbndr-- Not uncommon; e.g. case (a,b) of c { (p,q) -> p }=returnenv-- Here c is dead, and we avoid creating-- the binding c = (a,b)|Coercionco<-new_rhs=return(extendCvSubstenvbndrco)|otherwise=do{(env',bndr')<-simplBinderenvbndr;completeNonRecXNotTopLevelenv'(isStrictIdbndr)bndrbndr'new_rhs}-- simplNonRecX is only used for NotTopLevel thingscompleteNonRecX::TopLevelFlag->SimplEnv->Bool->InId-- Old binder->OutId-- New binder->OutExpr-- Simplified RHS->SimplMSimplEnvcompleteNonRecXtop_lvlenvis_strictold_bndrnew_bndrnew_rhs=do{(env1,rhs1)<-prepareRhstop_lvl(zapFloatsenv)new_bndrnew_rhs;(env2,rhs2)<-ifdoFloatFromRhsNotTopLevelNonRecursiveis_strictrhs1env1thendo{tickLetFloatFromLet;return(addFloatsenvenv1,rhs1)}-- Add the floats to the main envelsereturn(env,wrapFloatsenv1rhs1)-- Wrap the floats around the RHS;completeBindenv2NotTopLevelold_bndrnew_bndrrhs2}

prepareRhs::TopLevelFlag->SimplEnv->OutId->OutExpr->SimplM(SimplEnv,OutExpr)-- Adds new floats to the env iff that allows us to return a good RHSprepareRhstop_lvlenvid(Castrhsco)-- Note [Float coercions]|Pairty1_ty2<-coercionKindco-- Do *not* do this if rhs has an unlifted type,not(isUnLiftedTypety1)-- see Note [Float coercions (unlifted)]=do{(env',rhs')<-makeTrivialWithInfotop_lvlenvsanitised_inforhs;return(env',Castrhs'co)}wheresanitised_info=vanillaIdInfo`setStrictnessInfo`strictnessInfoinfo`setDemandInfo`demandInfoinfoinfo=idInfoidprepareRhstop_lvlenv0_rhs0=do{(_is_exp,env1,rhs1)<-go0env0rhs0;return(env1,rhs1)}wheregon_val_argsenv(Castrhsco)=do{(is_exp,env',rhs')<-gon_val_argsenvrhs;return(is_exp,env',Castrhs'co)}gon_val_argsenv(Appfun(Typety))=do{(is_exp,env',rhs')<-gon_val_argsenvfun;return(is_exp,env',Apprhs'(Typety))}gon_val_argsenv(Appfunarg)=do{(is_exp,env',fun')<-go(n_val_args+1)envfun;caseis_expofTrue->do{(env'',arg')<-makeTrivialtop_lvlenv'arg;return(True,env'',Appfun'arg')}False->return(False,env,Appfunarg)}gon_val_argsenv(Varfun)=return(is_exp,env,Varfun)whereis_exp=isExpandableAppfunn_val_args-- The fun a constructor or PAP-- See Note [CONLIKE pragma] in BasicTypes-- The definition of is_exp should match that in-- OccurAnal.occAnalAppgo_envother=return(False,env,other)

makeTrivialArg::SimplEnv->ArgSpec->SimplM(SimplEnv,ArgSpec)makeTrivialArgenv(ValArge)=do{(env',e')<-makeTrivialNotTopLevelenve;return(env',ValArge')}makeTrivialArgenv(CastByco)=return(env,CastByco)makeTrivial::TopLevelFlag->SimplEnv->OutExpr->SimplM(SimplEnv,OutExpr)-- Binds the expression to a variable, if it's not trivial, returning the variablemakeTrivialtop_lvlenvexpr=makeTrivialWithInfotop_lvlenvvanillaIdInfoexprmakeTrivialWithInfo::TopLevelFlag->SimplEnv->IdInfo->OutExpr->SimplM(SimplEnv,OutExpr)-- Propagate strictness and demand info to the new binder-- Note [Preserve strictness when floating coercions]-- Returned SimplEnv has same substitution as incoming onemakeTrivialWithInfotop_lvlenvinfoexpr|exprIsTrivialexpr-- Already trivial||not(bindingOktop_lvlexprexpr_ty)-- Cannot trivialise-- See Note [Cannot trivialise]=return(env,expr)|otherwise-- See Note [Take care] below=do{uniq<-getUniqueM;letname=mkSystemVarNameuniq(fsLit"a")var=mkLocalIdWithInfonameexpr_tyinfo;env'<-completeNonRecXtop_lvlenvFalsevarvarexpr;expr'<-simplVarenv'var;return(env',expr')}-- The simplVar is needed becase we're constructing a new binding-- a = rhs-- And if rhs is of form (rhs1 |> co), then we might get-- a1 = rhs1-- a = a1 |> co-- and now a's RHS is trivial and can be substituted out, and that-- is what completeNonRecX will do-- To put it another way, it's as if we'd simplified-- let var = e in varwhereexpr_ty=exprTypeexprbindingOk::TopLevelFlag->CoreExpr->Type->Bool-- True iff we can have a binding of this expression at this level-- Precondition: the type is the type of the expressionbindingOktop_lvl_expr_ty|isTopLeveltop_lvl=not(isUnLiftedTypeexpr_ty)|otherwise=True

\end{code}
Note [Cannot trivialise]
~~~~~~~~~~~~~~~~~~~~~~~~
Consider tih
f :: Int -> Addr#
foo :: Bar
foo = Bar (f 3)
Then we can't ANF-ise foo, even though we'd like to, because
we can't make a top-level binding for the Addr# (f 3). And if
so we don't want to turn it into
foo = let x = f 3 in Bar x
because we'll just end up inlining x back, and that makes the
simplifier loop. Better not to ANF-ise it at all.
A case in point is literal strings (a MachStr is not regarded as
trivial):
foo = Ptr "blob"#
We don't want to ANF-ise this.
%************************************************************************
%* *
\subsection{Completing a lazy binding}
%* *
%************************************************************************
completeBind
* deals only with Ids, not TyVars
* takes an already-simplified binder and RHS
* is used for both recursive and non-recursive bindings
* is used for both top-level and non-top-level bindings
It does the following:
- tries discarding a dead binding
- tries PostInlineUnconditionally
- add unfolding [this is the only place we add an unfolding]
- add arity
It does *not* attempt to do let-to-case. Why? Because it is used for
- top-level bindings (when let-to-case is impossible)
- many situations where the "rhs" is known to be a WHNF
(so let-to-case is inappropriate).
Nor does it do the atomic-argument thing
\begin{code}

completeBind::SimplEnv->TopLevelFlag-- Flag stuck into unfolding->InId-- Old binder->OutId->OutExpr-- New binder and RHS->SimplMSimplEnv-- completeBind may choose to do its work-- * by extending the substitution (e.g. let x = y in ...)-- * or by adding to the floats in the envtcompleteBindenvtop_lvlold_bndrnew_bndrnew_rhs|isCoVarold_bndr=casenew_rhsofCoercionco->return(extendCvSubstenvold_bndrco)_->return(addNonRecenvnew_bndrnew_rhs)|otherwise=ASSERT(isIdnew_bndr)do{letold_info=idInfoold_bndrold_unf=unfoldingInfoold_infoocc_info=occInfoold_info-- Do eta-expansion on the RHS of the binding-- See Note [Eta-expanding at let bindings] in SimplUtils;(new_arity,final_rhs)<-tryEtaExpandRhsenvnew_bndrnew_rhs-- Simplify the unfolding;new_unfolding<-simplUnfoldingenvtop_lvlold_bndrfinal_rhsold_unf;dflags<-getDynFlags;ifpostInlineUnconditionallydflagsenvtop_lvlnew_bndrocc_infofinal_rhsnew_unfolding-- Inline and discard the bindingthendo{tick(PostInlineUnconditionallyold_bndr);return(extendIdSubstenvold_bndr(DoneExfinal_rhs))}-- Use the substitution to make quite, quite sure that the-- substitution will happen, since we are going to discard the bindingelsedo{letinfo1=idInfonew_bndr`setArityInfo`new_arity-- Unfolding info: Note [Setting the new unfolding]info2=info1`setUnfoldingInfo`new_unfolding-- Demand info: Note [Setting the demand info]---- We also have to nuke demand info if for some reason-- eta-expansion *reduces* the arity of the binding to less-- than that of the strictness sig. This can happen: see Note [Arity decrease].info3|isEvaldUnfoldingnew_unfolding||(casestrictnessInfoinfo2ofStrictSigdmd_ty->new_arity<dmdTypeDepthdmd_ty)=zapDemandInfoinfo2`orElse`info2|otherwise=info2final_id=new_bndr`setIdInfo`info3;-- pprTrace "Binding" (ppr final_id <+> ppr new_unfolding) $return(addNonRecenvfinal_idfinal_rhs)}}-- The addNonRec adds it to the in-scope set too------------------------------addPolyBind::TopLevelFlag->SimplEnv->OutBind->SimplMSimplEnv-- Add a new binding to the environment, complete with its unfolding-- but *do not* do postInlineUnconditionally, because we have already-- processed some of the scope of the binding-- We still want the unfolding though. Consider-- let-- x = /\a. let y = ... in Just y-- in body-- Then we float the y-binding out (via abstractFloats and addPolyBind)-- but 'x' may well then be inlined in 'body' in which case we'd like the-- opportunity to inline 'y' too.---- INVARIANT: the arity is correct on the incoming bindersaddPolyBindtop_lvlenv(NonRecpoly_idrhs)=do{unfolding<-simplUnfoldingenvtop_lvlpoly_idrhsnoUnfolding-- Assumes that poly_id did not have an INLINE prag-- which is perhaps wrong. ToDo: think about this;letfinal_id=setIdInfopoly_id$idInfopoly_id`setUnfoldingInfo`unfolding;return(addNonRecenvfinal_idrhs)}addPolyBind_envbind@(Rec_)=return(extendFloatsenvbind)-- Hack: letrecs are more awkward, so we extend "by steam"-- without adding unfoldings etc. At worst this leads to-- more simplifier iterations------------------------------simplUnfolding::SimplEnv->TopLevelFlag->InId->OutExpr->Unfolding->SimplMUnfolding-- Note [Setting the new unfolding]simplUnfoldingenvtop_lvlidnew_rhsunf=caseunfofDFunUnfolding{df_bndrs=bndrs,df_con=con,df_args=args}->do{(env',bndrs')<-simplBindersrule_envbndrs;args'<-mapM(simplExprenv')args;return(mkDFunUnfoldingbndrs'conargs')}CoreUnfolding{uf_tmpl=expr,uf_arity=arity,uf_src=src,uf_guidance=guide}|isStableSourcesrc->do{expr'<-simplExprrule_envexpr;caseguideofUnfWhensat_ok_-- Happens for INLINE things->letguide'=UnfWhensat_ok(inlineBoringOkexpr')-- Refresh the boring-ok flag, in case expr'-- has got small. This happens, notably in the inlinings-- for dfuns for single-method classes; see-- Note [Single-method classes] in TcInstDcls.-- A test case is Trac #4138inreturn(mkCoreUnfoldingsrcis_top_lvlexpr'arityguide')-- See Note [Top-level flag on inline rules] in CoreUnfold_other-- Happens for INLINABLE things->bottoming`seq`-- See Note [Force bottoming field]do{dflags<-getDynFlags;return(mkUnfoldingdflagssrcis_top_lvlbottomingexpr')}}-- If the guidance is UnfIfGoodArgs, this is an INLINABLE-- unfolding, and we need to make sure the guidance is kept up-- to date with respect to any changes in the unfolding._other->bottoming`seq`-- See Note [Force bottoming field]do{dflags<-getDynFlags;return(mkUnfoldingdflagsInlineRhsis_top_lvlbottomingnew_rhs)}-- We make an unfolding *even for loop-breakers*.-- Reason: (a) It might be useful to know that they are WHNF-- (b) In TidyPgm we currently assume that, if we want to-- expose the unfolding then indeed we *have* an unfolding-- to expose. (We could instead use the RHS, but currently-- we don't.) The simple thing is always to have one.wherebottoming=isBottomingIdidis_top_lvl=isTopLeveltop_lvlact=idInlineActivationidrule_env=updMode(updModeForInlineRulesact)env-- See Note [Simplifying inside InlineRules] in SimplUtils

\end{code}
Note [Force bottoming field]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We need to force bottoming, or the new unfolding holds
on to the old unfolding (which is part of the id).
Note [Arity decrease]
~~~~~~~~~~~~~~~~~~~~~
Generally speaking the arity of a binding should not decrease. But it *can*
legitimately happen because of RULES. Eg
f = g Int
where g has arity 2, will have arity 2. But if there's a rewrite rule
g Int --> h
where h has arity 1, then f's arity will decrease. Here's a real-life example,
which is in the output of Specialise:
Rec {
$dm {Arity 2} = \d.\x. op d
{-# RULES forall d. $dm Int d = $s$dm #-}
dInt = MkD .... opInt ...
opInt {Arity 1} = $dm dInt
$s$dm {Arity 0} = \x. op dInt }
Here opInt has arity 1; but when we apply the rule its arity drops to 0.
That's why Specialise goes to a little trouble to pin the right arity
on specialised functions too.
Note [Setting the new unfolding]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* If there's an INLINE pragma, we simplify the RHS gently. Maybe we
should do nothing at all, but simplifying gently might get rid of
more crap.
* If not, we make an unfolding from the new RHS. But *only* for
non-loop-breakers. Making loop breakers not have an unfolding at all
means that we can avoid tests in exprIsConApp, for example. This is
important: if exprIsConApp says 'yes' for a recursive thing, then we
can get into an infinite loop
If there's an InlineRule on a loop breaker, we hang on to the inlining.
It's pretty dodgy, but the user did say 'INLINE'. May need to revisit
this choice.
Note [Setting the demand info]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If the unfolding is a value, the demand info may
go pear-shaped, so we nuke it. Example:
let x = (a,b) in
case x of (p,q) -> h p q x
Here x is certainly demanded. But after we've nuked
the case, we'll get just
let x = (a,b) in h a b x
and now x is not demanded (I'm assuming h is lazy)
This really happens. Similarly
let f = \x -> e in ...f..f...
After inlining f at some of its call sites the original binding may
(for example) be no longer strictly demanded.
The solution here is a bit ad hoc...
%************************************************************************
%* *
\subsection[Simplify-simplExpr]{The main function: simplExpr}
%* *
%************************************************************************
The reason for this OutExprStuff stuff is that we want to float *after*
simplifying a RHS, not before. If we do so naively we get quadratic
behaviour as things float out.
To see why it's important to do it after, consider this (real) example:
let t = f x
in fst t
==>
let t = let a = e1
b = e2
in (a,b)
in fst t
==>
let a = e1
b = e2
t = (a,b)
in
a -- Can't inline a this round, cos it appears twice
==>
e1
Each of the ==> steps is a round of simplification. We'd save a
whole round if we float first. This can cascade. Consider
let f = g d
in \x -> ...f...
==>
let f = let d1 = ..d.. in \y -> e
in \x -> ...f...
==>
let d1 = ..d..
in \x -> ...(\y ->e)...
Only in this second round can the \y be applied, and it
might do the same again.
\begin{code}

simplExpr::SimplEnv->CoreExpr->SimplMCoreExprsimplExprenvexpr=simplExprCenvexpr(mkBoringStopexpr_out_ty)whereexpr_out_ty::OutTypeexpr_out_ty=substTyenv(exprTypeexpr)simplExprC::SimplEnv->CoreExpr->SimplCont->SimplMCoreExpr-- Simplify an expression, given a continuationsimplExprCenvexprcont=-- pprTrace "simplExprC" (ppr expr $$ ppr cont {- $$ ppr (seIdSubst env) -} $$ ppr (seFloats env) ) $do{(env',expr')<-simplExprF(zapFloatsenv)exprcont;-- pprTrace "simplExprC ret" (ppr expr $$ ppr expr') $-- pprTrace "simplExprC ret3" (ppr (seInScope env')) $-- pprTrace "simplExprC ret4" (ppr (seFloats env')) $return(wrapFloatsenv'expr')}--------------------------------------------------simplExprF::SimplEnv->InExpr->SimplCont->SimplM(SimplEnv,OutExpr)simplExprFenvecont={- pprTrace "simplExprF" (vcat
[ ppr e
, text "cont =" <+> ppr cont
, text "inscope =" <+> ppr (seInScope env)
, text "tvsubst =" <+> ppr (seTvSubst env)
, text "idsubst =" <+> ppr (seIdSubst env)
, text "cvsubst =" <+> ppr (seCvSubst env)
{- , ppr (seFloats env) -}
]) $ -}simplExprF1envecontsimplExprF1::SimplEnv->InExpr->SimplCont->SimplM(SimplEnv,OutExpr)simplExprF1env(Varv)cont=simplIdFenvvcontsimplExprF1env(Litlit)cont=rebuildenv(Litlit)contsimplExprF1env(Ticktexpr)cont=simplTickenvtexprcontsimplExprF1env(Castbodyco)cont=simplCastenvbodycocontsimplExprF1env(Coercionco)cont=simplCoercionFenvcocontsimplExprF1env(Typety)cont=ASSERT(contIsRhsOrArgcont)rebuildenv(Type(substTyenvty))contsimplExprF1env(Appfunarg)cont=simplExprFenvfun$ApplyToNoDupargenvcontsimplExprF1envexpr@(Lam{})cont=simplLamenvzapped_bndrsbodycont-- The main issue here is under-saturated lambdas-- (\x1. \x2. e) arg1-- Here x1 might have "occurs-once" occ-info, because occ-info-- is computed assuming that a group of lambdas is applied-- all at once. If there are too few args, we must zap the-- occ-info, UNLESS the remaining binders are one-shotwhere(bndrs,body)=collectBindersexprzapped_bndrs|need_to_zap=mapzapbndrs|otherwise=bndrsneed_to_zap=anyzappable_bndr(dropn_argsbndrs)n_args=countArgscont-- NB: countArgs counts all the args (incl type args)-- and likewise drop counts all binders (incl type lambdas)zappable_bndrb=isIdb&&not(isOneShotBndrb)zapb|isTyVarb=b|otherwise=zapLamIdInfobsimplExprF1env(Casescrutbndralts_tyalts)cont|sm_case_case(getModeenv)=-- Simplify the scrutinee with a Select continuationsimplExprFenvscrut(SelectNoDupbndraltsenvcont)|otherwise=-- If case-of-case is off, simply simplify the case expression-- in a vanilla Stop context, and rebuild the result around itdo{case_expr'<-simplExprCenvscrut(SelectNoDupbndraltsenv(mkBoringStopalts_out_ty));rebuildenvcase_expr'cont}wherealts_out_ty=substTyenvalts_tysimplExprF1env(Let(Recpairs)body)cont=do{env'<-simplRecBndrsenv(mapfstpairs)-- NB: bndrs' don't have unfoldings or rules-- We add them as we go down;env''<-simplRecBindenv'NotTopLevelpairs;simplExprFenv''bodycont}simplExprF1env(Let(NonRecbndrrhs)body)cont=simplNonRecEenvbndr(rhs,env)([],body)cont---------------------------------simplType::SimplEnv->InType->SimplMOutType-- Kept monadic just so we can do the seqTypesimplTypeenvty=-- pprTrace "simplType" (ppr ty $$ ppr (seTvSubst env)) $seqTypenew_ty`seq`returnnew_tywherenew_ty=substTyenvty---------------------------------simplCoercionF::SimplEnv->InCoercion->SimplCont->SimplM(SimplEnv,OutExpr)simplCoercionFenvcocont=do{co'<-simplCoercionenvco;rebuildenv(Coercionco')cont}simplCoercion::SimplEnv->InCoercion->SimplMOutCoercionsimplCoercionenvco=letopt_co=optCoercion(getCvSubstenv)coinseqCoopt_co`seq`returnopt_co------------------------------------- | Push a TickIt context outwards past applications and cases, as-- long as this is a non-scoping tick, to let case and application-- optimisations apply.simplTick::SimplEnv->TickishId->InExpr->SimplCont->SimplM(SimplEnv,OutExpr)simplTickenvtickishexprcont-- A scoped tick turns into a continuation, so that we can spot-- (scc t (\x . e)) in simplLam and eliminate the scc. If we didn't do-- it this way, then it would take two passes of the simplifier to-- reduce ((scc t (\x . e)) e').-- NB, don't do this with counting ticks, because if the expr is-- bottom, then rebuildCall will discard the continuation.-- XXX: we cannot do this, because the simplifier assumes that-- the context can be pushed into a case with a single branch. e.g.-- scc<f> case expensive of p -> e-- becomes-- case expensive of p -> scc<f> e---- So I'm disabling this for now. It just means we will do more-- simplifier iterations that necessary in some cases.-- | tickishScoped tickish && not (tickishCounts tickish)-- = simplExprF env expr (TickIt tickish cont)-- For non-scoped ticks, we push the continuation inside the-- tick. This has the effect of moving the tick to the outside of a-- case or application context, allowing the normal case and-- application optimisations to fire.|not(tickishScopedtickish)=do{(env',expr')<-simplExprFenvexprcont;return(env',mkTicktickishexpr')}-- For breakpoints, we cannot do any floating of bindings around the-- tick, because breakpoints cannot be split into tick/scope pairs.|not(tickishCanSplittickish)=no_floating_past_tick|interesting_cont,Justexpr'<-push_tick_insidetickishexpr-- see Note [case-of-scc-of-case]=simplExprFenvexpr'cont|otherwise=no_floating_past_tick-- was: wrap_floats, see belowwhereinteresting_cont=casecontofSelect{}->True_->Falsepush_tick_insidetexpr0=ASSERT(tickishScopedt)caseexpr0ofTickt'expr-- scc t (tick t' E)-- Pull the tick to the outside-- This one is important for #5363|not(tickishScopedt')->Just(Tickt'(Ticktexpr))-- scc t (scc t' E)-- Try to push t' into E first, and if that works,-- try to push t in again|Justexpr'<-push_tick_insidet'expr->push_tick_insidetexpr'|otherwise->NothingCasescrutbndrtyalts|not(tickishCanSplitt)->Nothing|otherwise->Just(Case(mkTicktscrut)bndrtyalts')wheret_scope=mkNoCountt-- drop the tick on the dup'd onesalts'=[(c,bs,mkTickt_scopee)|(c,bs,e)<-alts]_other->Nothingwhereno_floating_past_tick=do{let(inc,outc)=splitContcont;(env',expr')<-simplExprF(zapFloatsenv)exprinc;lettickish'=simplTickishenvtickish;(env'',expr'')<-rebuild(zapFloatsenv')(wrapFloatsenv'expr')(TickIttickish'outc);return(addFloatsenvenv'',expr'')}-- Alternative version that wraps outgoing floats with the tick. This-- results in ticks being duplicated, as we don't make any attempt to-- eliminate the tick if we re-inline the binding (because the tick-- semantics allows unrestricted inlining of HNFs), so I'm not doing-- this any more. FloatOut will catch any real opportunities for-- floating.---- wrap_floats =-- do { let (inc,outc) = splitCont cont-- ; (env', expr') <- simplExprF (zapFloats env) expr inc-- ; let tickish' = simplTickish env tickish-- ; let wrap_float (b,rhs) = (zapIdStrictness (setIdArity b 0),-- mkTick (mkNoCount tickish') rhs)-- -- when wrapping a float with mkTick, we better zap the Id's-- -- strictness info and arity, because it might be wrong now.-- ; let env'' = addFloats env (mapFloats env' wrap_float)-- ; rebuild env'' expr' (TickIt tickish' outc)-- }simplTickishenvtickish|Breakpointnids<-tickish=Breakpointn(map(getDoneId.substIdenv)ids)|otherwise=tickish-- push type application and coercion inside a ticksplitCont::SimplCont->(SimplCont,SimplCont)splitCont(ApplyTof(Typet)envc)=(ApplyTof(Typet)envinc,outc)where(inc,outc)=splitContcsplitCont(CoerceItcoc)=(CoerceItcoinc,outc)where(inc,outc)=splitContcsplitContother=(mkBoringStop(contInputTypeother),other)getDoneId(DoneIdid)=idgetDoneId(DoneExe)=getIdFromTrivialExpre-- Note [substTickish] in CoreSubstgetDoneIdother=pprPanic"getDoneId"(pprother)-- Note [case-of-scc-of-case]-- It's pretty important to be able to transform case-of-case when-- there's an SCC in the way. For example, the following comes up-- in nofib/real/compress/Encode.hs:---- case scctick<code_string.r1>-- case $wcode_string_r13s wild_XC w1_s137 w2_s138 l_aje-- of _ { (# ww1_s13f, ww2_s13g, ww3_s13h #) ->-- (ww1_s13f, ww2_s13g, ww3_s13h)-- }-- of _ { (ww_s12Y, ww1_s12Z, ww2_s130) ->-- tick<code_string.f1>-- (ww_s12Y,-- ww1_s12Z,-- PTTrees.PT-- @ GHC.Types.Char @ GHC.Types.Int wild2_Xj ww2_s130 r_ajf)-- }---- We really want this case-of-case to fire, because then the 3-tuple-- will go away (indeed, the CPR optimisation is relying on this-- happening). But the scctick is in the way - we need to push it-- inside to expose the case-of-case. So we perform this-- transformation on the inner case:---- scctick c (case e of { p1 -> e1; ...; pn -> en })-- ==>-- case (scctick c e) of { p1 -> scc c e1; ...; pn -> scc c en }---- So we've moved a constant amount of work out of the scc to expose-- the case. We only do this when the continuation is interesting: in-- for now, it has to be another Case (maybe generalise this later).

rebuild::SimplEnv->OutExpr->SimplCont->SimplM(SimplEnv,OutExpr)-- At this point the substitution in the SimplEnv should be irrelevant-- only the in-scope set and floats should matterrebuildenvexprcont=casecontofStop{}->return(env,expr)CoerceItcocont->rebuildenv(mkCastexprco)cont-- NB: mkCast implements the (Coercion co |> g) optimisationSelect_bndraltssecont->rebuildCase(se`setFloats`env)exprbndraltscontStrictArginfo_cont->rebuildCallenv(info`addArgTo`expr)contStrictBindbbsbodysecont->do{env'<-simplNonRecX(se`setFloats`env)bexpr;simplLamenv'bsbodycont}ApplyTodup_flagargsecont-- See Note [Avoid redundant simplification]|isSimplifieddup_flag->rebuildenv(Appexprarg)cont|otherwise->do{arg'<-simplExpr(se`setInScope`env)arg;rebuildenv(Appexprarg')cont}TickIttcont->rebuildenv(mkTicktexpr)cont

simplCast::SimplEnv->InExpr->Coercion->SimplCont->SimplM(SimplEnv,OutExpr)simplCastenvbodyco0cont0=do{co1<-simplCoercionenvco0;-- pprTrace "simplCast" (ppr co1) $simplExprFenvbody(addCoerceco1cont0)}whereaddCoercecocont=add_coerceco(coercionKindco)contadd_coerce_co(Pairs1k1)cont-- co :: ty~ty|s1`eqType`k1=cont-- is a no-opadd_coerceco1(Pairs1_k2)(CoerceItco2cont)|(Pair_l1t1)<-coercionKindco2-- e |> (g1 :: S1~L) |> (g2 :: L~T1)-- ==>-- e, if S1=T1-- e |> (g1 . g2 :: S1~T1) otherwise---- For example, in the initial form of a worker-- we may find (coerce T (coerce S (\x.e))) y-- and we'd like it to simplify to e[y/x] in one round-- of simplification,s1`eqType`t1=cont-- The coerces cancel out|otherwise=CoerceIt(mkTransCoco1co2)contadd_coerceco(Pairs1s2_t1t2)(ApplyTodup(Typearg_ty)arg_secont)-- (f |> g) ty ---> (f ty) |> (g @ ty)-- This implements the PushT rule from the paper|Just(tyvar,_)<-splitForAllTy_maybes1s2=ASSERT(isTyVartyvar)ApplyToSimplified(Typearg_ty')(zapSubstEnvarg_se)(addCoercenew_castcont)wherenew_cast=mkInstCocoarg_ty'arg_ty'|isSimplifieddup=arg_ty|otherwise=substTy(arg_se`setInScope`env)arg_tyadd_coerceco(Pairs1s2t1t2)(ApplyTodupargarg_secont)|isFunTys1s2-- This implements the Push rule from the paper,isFunTyt1t2-- Check t1t2 to ensure 'arg' is a value arg-- (e |> (g :: s1s2 ~ t1->t2)) f-- ===>-- (e (f |> (arg g :: t1~s1))-- |> (res g :: s2->t2)---- t1t2 must be a function type, t1->t2, because it's applied-- to something but s1s2 might conceivably not be---- When we build the ApplyTo we can't mix the out-types-- with the InExpr in the argument, so we simply substitute-- to make it all consistent. It's a bit messy.-- But it isn't a common case.---- Example of use: Trac #995=ApplyTodupnew_arg(zapSubstEnvarg_se)(addCoerceco2cont)where-- we split coercion t1->t2 ~ s1->s2 into t1 ~ s1 and-- t2 ~ s2 with left and right on the curried form:-- (->) t1 t2 ~ (->) s1 s2[co1,co2]=decomposeCo2conew_arg=mkCastarg'(mkSymCoco1)arg'=substExpr(text"move-cast")arg_se'argarg_se'=arg_se`setInScope`envadd_coerceco_cont=CoerceItcocont

\end{code}
%************************************************************************
%* *
\subsection{Lambdas}
%* *
%************************************************************************
Note [Zap unfolding when beta-reducing]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Lambda-bound variables can have stable unfoldings, such as
$j = \x. \b{Unf=Just x}. e
See Note [Case binders and join points] below; the unfolding for lets
us optimise e better. However when we beta-reduce it we want to
revert to using the actual value, otherwise we can end up in the
stupid situation of
let x = blah in
let b{Unf=Just x} = y
in ...b...
Here it'd be far better to drop the unfolding and use the actual RHS.
\begin{code}

simplLam::SimplEnv->[InId]->InExpr->SimplCont->SimplM(SimplEnv,OutExpr)simplLamenv[]bodycont=simplExprFenvbodycont-- Beta reductionsimplLamenv(bndr:bndrs)body(ApplyTo_argarg_secont)=do{tick(BetaReductionbndr);simplNonRecEenv(zap_unfoldingbndr)(arg,arg_se)(bndrs,body)cont}wherezap_unfoldingbndr-- See Note [Zap unfolding when beta-reducing]|isIdbndr,isStableUnfolding(realIdUnfoldingbndr)=setIdUnfoldingbndrNoUnfolding|otherwise=bndr-- discard a non-counting tick on a lambda. This may change the-- cost attribution slightly (moving the allocation of the-- lambda elsewhere), but we don't care: optimisation changes-- cost attribution all the time.simplLamenvbndrsbody(TickIttickishcont)|not(tickishCountstickish)=simplLamenvbndrsbodycont-- Not enough args, so there are real lambdas left to put in the resultsimplLamenvbndrsbodycont=do{(env',bndrs')<-simplLamBndrsenvbndrs;body'<-simplExprenv'body;new_lam<-mkLambndrs'body'cont;rebuildenv'new_lamcont}------------------simplNonRecE::SimplEnv->InBndr-- The binder->(InExpr,SimplEnv)-- Rhs of binding (or arg of lambda)->([InBndr],InExpr)-- Body of the let/lambda-- \xs.e->SimplCont->SimplM(SimplEnv,OutExpr)-- simplNonRecE is used for-- * non-top-level non-recursive lets in expressions-- * beta reduction---- It deals with strict bindings, via the StrictBind continuation,-- which may abort the whole process---- The "body" of the binding comes as a pair of ([InId],InExpr)-- representing a lambda; so we recurse back to simplLam-- Why? Because of the binder-occ-info-zapping done before-- the call to simplLam in simplExprF (Lam ...)-- First deal with type applications and type lets-- (/\a. e) (Type ty) and (let a = Type ty in e)simplNonRecEenvbndr(Typety_arg,rhs_se)(bndrs,body)cont=ASSERT(isTyVarbndr)do{ty_arg'<-simplType(rhs_se`setInScope`env)ty_arg;simplLam(extendTvSubstenvbndrty_arg')bndrsbodycont}simplNonRecEenvbndr(rhs,rhs_se)(bndrs,body)cont=dodflags<-getDynFlagscase()of_|preInlineUnconditionallydflagsenvNotTopLevelbndrrhs->do{tick(PreInlineUnconditionallybndr);-- pprTrace "preInlineUncond" (ppr bndr <+> ppr rhs) $simplLam(extendIdSubstenvbndr(mkContExrhs_serhs))bndrsbodycont}|isStrictIdbndr->-- Includes coercionsdo{simplExprF(rhs_se`setFloats`env)rhs(StrictBindbndrbndrsbodyenvcont)}|otherwise->ASSERT(not(isTyVarbndr))do{(env1,bndr1)<-simplNonRecBndrenvbndr;let(env2,bndr2)=addBndrRulesenv1bndrbndr1;env3<-simplLazyBindenv2NotTopLevelNonRecursivebndrbndr2rhsrhs_se;simplLamenv3bndrsbodycont}

simplVar::SimplEnv->InVar->SimplMOutExpr-- Look up an InVar in the environmentsimplVarenvvar|isTyVarvar=return(Type(substTyVarenvvar))|isCoVarvar=return(Coercion(substCoVarenvvar))|otherwise=casesubstIdenvvarofDoneIdvar1->return(Varvar1)DoneExe->returneContExtvscvsidse->simplExpr(setSubstEnvenvtvscvsids)esimplIdF::SimplEnv->InId->SimplCont->SimplM(SimplEnv,OutExpr)simplIdFenvvarcont=casesubstIdenvvarofDoneExe->simplExprF(zapSubstEnvenv)econtContExtvscvsidse->simplExprF(setSubstEnvenvtvscvsids)econtDoneIdvar1->completeCallenvvar1cont-- Note [zapSubstEnv]-- The template is already simplified, so don't re-substitute.-- This is VITAL. Consider-- let x = e in-- let y = \z -> ...x... in-- \ x -> ...y...-- We'll clone the inner \x, adding x->x' in the id_subst-- Then when we inline y, we must *not* replace x by x' in-- the inlined copy!!----------------------------------------------------------- Dealing with a call sitecompleteCall::SimplEnv->OutId->SimplCont->SimplM(SimplEnv,OutExpr)completeCallenvvarcont=do{------------- Try inlining ----------------dflags<-getDynFlags;let(lone_variable,arg_infos,call_cont)=contArgscontn_val_args=lengtharg_infosinteresting_cont=interestingCallContextcall_contunfolding=activeUnfoldingenvvarmaybe_inline=callSiteInlinedflagsvarunfoldinglone_variablearg_infosinteresting_cont;casemaybe_inlineof{Justexpr-- There is an inlining!->do{checkedTick(UnfoldingDonevar);dump_inlinedflagsexprcont;simplExprF(zapSubstEnvenv)exprcont};Nothing->do-- No inlining!{rule_base<-getSimplRules;letinfo=mkArgInfovar(getRulesrule_basevar)n_val_argscall_cont;rebuildCallenvinfocont}}}wheredump_inlinedflagsunfoldingcont|not(doptOpt_D_dump_inliningsdflags)=return()|not(doptOpt_D_verbose_core2coredflags)=when(isExternalName(idNamevar))$liftIO$printInfoForUserdflagsalwaysQualify$sep[text"Inlining done:",nest4(pprvar)]|otherwise=liftIO$printInfoForUserdflagsalwaysQualify$sep[text"Inlining done: "<>pprvar,nest4(vcat[text"Inlined fn: "<+>nest2(pprunfolding),text"Cont: "<+>pprcont])]rebuildCall::SimplEnv->ArgInfo->SimplCont->SimplM(SimplEnv,OutExpr)rebuildCallenv(ArgInfo{ai_fun=fun,ai_args=rev_args,ai_strs=[]})cont-- When we run out of strictness args, it means-- that the call is definitely bottom; see SimplUtils.mkArgInfo-- Then we want to discard the entire strict continuation. E.g.-- * case (error "hello") of { ... }-- * (error "Hello") arg-- * f (error "Hello") where f is strict-- etc-- Then, especially in the first of these cases, we'd like to discard-- the continuation, leaving just the bottoming expression. But the-- type might not be right, so we may have to add a coerce.|not(contIsTrivialcont)-- Only do this if there is a non-trivial=return(env,castBottomExprrescont_ty)-- contination to discard, else we do itwhere-- again and again!res=argInfoExprfunrev_argscont_ty=contResultTypecontrebuildCallenvinfo(CoerceItcocont)=rebuildCallenv(addCastToinfoco)contrebuildCallenvinfo(ApplyTodup_flag(Typearg_ty)secont)=do{arg_ty'<-ifisSimplifieddup_flagthenreturnarg_tyelsesimplType(se`setInScope`env)arg_ty;rebuildCallenv(info`addArgTo`Typearg_ty')cont}rebuildCallenvinfo@(ArgInfo{ai_encl=encl_rules,ai_type=fun_ty,ai_strs=str:strs,ai_discs=disc:discs})(ApplyTodup_flagargarg_secont)|isSimplifieddup_flag-- See Note [Avoid redundant simplification]=rebuildCallenv(addArgToinfo'arg)cont|str-- Strict argument=-- pprTrace "Strict Arg" (ppr arg $$ ppr (seIdSubst env) $$ ppr (seInScope env)) $simplExprF(arg_se`setFloats`env)arg(StrictArginfo'ccicont)-- Note [Shadowing]|otherwise-- Lazy argument-- DO NOT float anything outside, hence simplExprC-- There is no benefit (unlike in a let-binding), and we'd-- have to be very careful about bogus strictness through-- floating a demanded let.=do{arg'<-simplExprC(arg_se`setInScope`env)arg(mkLazyArgStop(funArgTyfun_ty)cci);rebuildCallenv(addArgToinfo'arg')cont}whereinfo'=info{ai_strs=strs,ai_discs=discs}cci|encl_rules=RuleArgCtxt|disc>0=DiscArgCtxt-- Be keener here|otherwise=BoringCtxt-- Nothing interestingrebuildCallenv(ArgInfo{ai_fun=fun,ai_args=rev_args,ai_rules=rules})cont|nullrules=rebuildenv(argInfoExprfunrev_args)cont-- No rules, common case|otherwise=do{-- We've accumulated a simplified call in <fun,rev_args>-- so try rewrite rules; see Note [RULEs apply to simplified arguments]-- See also Note [Rules for recursive functions];letenv'=zapSubstEnvenv(args,cont')=argInfoValArgsenv'rev_argscont;mb_rule<-tryRulesenv'rulesfunargscont';casemb_ruleof{Just(rule_rhs,cont'')->simplExprFenv'rule_rhscont''-- Rules don't match;Nothing->rebuildenv(argInfoExprfunrev_args)cont-- No rules}}

\end{code}
Note [RULES apply to simplified arguments]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It's very desirable to try RULES once the arguments have been simplified, because
doing so ensures that rule cascades work in one pass. Consider
{-# RULES g (h x) = k x
f (k x) = x #-}
...f (g (h x))...
Then we want to rewrite (g (h x)) to (k x) and only then try f's rules. If
we match f's rules against the un-simplified RHS, it won't match. This
makes a particularly big difference when superclass selectors are involved:
op ($p1 ($p2 (df d)))
We want all this to unravel in one sweeep.
Note [Avoid redundant simplification]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Because RULES apply to simplified arguments, there's a danger of repeatedly
simplifying already-simplified arguments. An important example is that of
(>>=) d e1 e2
Here e1, e2 are simplified before the rule is applied, but don't really
participate in the rule firing. So we mark them as Simplified to avoid
re-simplifying them.
Note [Shadowing]
~~~~~~~~~~~~~~~~
This part of the simplifier may break the no-shadowing invariant
Consider
f (...(\a -> e)...) (case y of (a,b) -> e')
where f is strict in its second arg
If we simplify the innermost one first we get (...(\a -> e)...)
Simplifying the second arg makes us float the case out, so we end up with
case y of (a,b) -> f (...(\a -> e)...) e'
So the output does not have the no-shadowing invariant. However, there is
no danger of getting name-capture, because when the first arg was simplified
we used an in-scope set that at least mentioned all the variables free in its
static environment, and that is enough.
We can't just do innermost first, or we'd end up with a dual problem:
case x of (a,b) -> f e (...(\a -> e')...)
I spent hours trying to recover the no-shadowing invariant, but I just could
not think of an elegant way to do it. The simplifier is already knee-deep in
continuations. We have to keep the right in-scope set around; AND we have
to get the effect that finding (error "foo") in a strict arg position will
discard the entire application and replace it with (error "foo"). Getting
all this at once is TOO HARD!
%************************************************************************
%* *
Rewrite rules
%* *
%************************************************************************
\begin{code}

\end{code}
Note [Optimising tagToEnum#]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If we have an enumeration data type:
data Foo = A | B | C
Then we want to transform
case tagToEnum# x of ==> case x of
A -> e1 DEFAULT -> e1
B -> e2 1# -> e2
C -> e3 2# -> e3
thereby getting rid of the tagToEnum# altogether. If there was a DEFAULT
alternative we retain it (remember it comes first). If not the case must
be exhaustive, and we reflect that in the transformed version by adding
a DEFAULT. Otherwise Lint complains that the new case is not exhaustive.
See #8317.
Note [Rules for recursive functions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You might think that we shouldn't apply rules for a loop breaker:
doing so might give rise to an infinite loop, because a RULE is
rather like an extra equation for the function:
RULE: f (g x) y = x+y
Eqn: f a y = a-y
But it's too drastic to disable rules for loop breakers.
Even the foldr/build rule would be disabled, because foldr
is recursive, and hence a loop breaker:
foldr k z (build g) = g k z
So it's up to the programmer: rules can cause divergence
%************************************************************************
%* *
Rebuilding a case expression
%* *
%************************************************************************
Note [Case elimination]
~~~~~~~~~~~~~~~~~~~~~~~
The case-elimination transformation discards redundant case expressions.
Start with a simple situation:
case x# of ===> let y# = x# in e
y# -> e
(when x#, y# are of primitive type, of course). We can't (in general)
do this for algebraic cases, because we might turn bottom into
non-bottom!
The code in SimplUtils.prepareAlts has the effect of generalise this
idea to look for a case where we're scrutinising a variable, and we
know that only the default case can match. For example:
case x of
0# -> ...
DEFAULT -> ...(case x of
0# -> ...
DEFAULT -> ...) ...
Here the inner case is first trimmed to have only one alternative, the
DEFAULT, after which it's an instance of the previous case. This
really only shows up in eliminating error-checking code.
Note that SimplUtils.mkCase combines identical RHSs. So
case e of ===> case e of DEFAULT -> r
True -> r
False -> r
Now again the case may be elminated by the CaseElim transformation.
This includes things like (==# a# b#)::Bool so that we simplify
case ==# a# b# of { True -> x; False -> x }
to just
x
This particular example shows up in default methods for
comparision operations (e.g. in (>=) for Int.Int32)
Note [Case elimination: lifted case]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We also make sure that we deal with this very common case,
where x has a lifted type:
case e of
x -> ...x...
Here we are using the case as a strict let; if x is used only once
then we want to inline it. We have to be careful that this doesn't
make the program terminate when it would have diverged before, so we
check that
(a) 'e' is already evaluated (it may so if e is a variable)
Specifically we check (exprIsHNF e)
or
(b) 'x' is not used at all and e is ok-for-speculation
For the (b), consider
case (case a ># b of { True -> (p,q); False -> (q,p) }) of
r -> blah
The scrutinee is ok-for-speculation (it looks inside cases), but we do
not want to transform to
let r = case a ># b of { True -> (p,q); False -> (q,p) }
in blah
because that builds an unnecessary thunk.
Note [Case binder next]
~~~~~~~~~~~~~~~~~~~~~~~
If we have
case e of f { _ -> f e1 e2 }
then we can safely do CaseElim. The main criterion is that the
case-binder is evaluated *next*. Previously we just asked that
the case-binder is used strictly; but that can change
case x of { _ -> error "bad" }
--> error "bad"
which is very puzzling if 'x' is later bound to (error "good").
Where the order of evaluation is specified (via seq or case)
we should respect it.
See also Note [Empty case alternatives] in CoreSyn.
So instead we use case_bndr_evald_next to see when f is the *next*
thing to be eval'd. This came up when fixing Trac #7542.
See also Note [Eta reduction of an eval'd function] in CoreUtils.
For reference, the old code was an extra disjunct in elim_lifted
|| (strict_case_bndr && scrut_is_var scrut)
strict_case_bndr = isStrictDmd (idDemandInfo case_bndr)
scrut_is_var (Cast s _) = scrut_is_var s
scrut_is_var (Var _) = True
scrut_is_var _ = False
-- True if evaluation of the case_bndr is the next
-- thing to be eval'd. Then dropping the case
Note [Case elimination: unlifted case]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
case a +# b of r -> ...r...
Then we do case-elimination (to make a let) followed by inlining,
to get
.....(a +# b)....
If we have
case indexArray# a i of r -> ...r...
we might like to do the same, and inline the (indexArray# a i).
But indexArray# is not okForSpeculation, so we don't build a let
in rebuildCase (lest it get floated *out*), so the inlining doesn't
happen either.
This really isn't a big deal I think. The let can be
Further notes about case elimination
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider: test :: Integer -> IO ()
test = print
Turns out that this compiles to:
Print.test
= \ eta :: Integer
eta1 :: Void# ->
case PrelNum.< eta PrelNum.zeroInteger of wild { __DEFAULT ->
case hPutStr stdout
(PrelNum.jtos eta ($w[] @ Char))
eta1
of wild1 { (# new_s, a4 #) -> PrelIO.lvl23 new_s }}
Notice the strange ' jtos v
Why don't we drop the case? Because it's strict in v. It's technically
wrong to drop even unnecessary evaluations, and in practice they
may be a result of 'seq' so we *definitely* don't want to drop those.
I don't really know how to improve this situation.
\begin{code}

----------------------------------------------------------- Eliminate the case if possiblerebuildCase,reallyRebuildCase::SimplEnv->OutExpr-- Scrutinee->InId-- Case binder->[InAlt]-- Alternatives (inceasing order)->SimplCont->SimplM(SimplEnv,OutExpr)---------------------------------------------------- 1. Eliminate the case if there's a known constructor--------------------------------------------------rebuildCaseenvscrutcase_bndraltscont|Litlit<-scrut-- No need for same treatment as constructors-- because literals are inlined more vigorously,not(litIsLiftedlit)=do{tick(KnownBranchcase_bndr);casefindAlt(LitAltlit)altsofNothing->missingAltenvcase_bndraltscontJust(_,bs,rhs)->simple_rhsbsrhs}|Just(con,ty_args,other_args)<-exprIsConApp_maybe(getUnfoldingInRuleMatchenv)scrut-- Works when the scrutinee is a variable with a known unfolding-- as well as when it's an explicit constructor application=do{tick(KnownBranchcase_bndr);casefindAlt(DataAltcon)altsofNothing->missingAltenvcase_bndraltscontJust(DEFAULT,bs,rhs)->simple_rhsbsrhsJust(_,bs,rhs)->knownConenvscrutconty_argsother_argscase_bndrbsrhscont}wheresimple_rhsbsrhs=ASSERT(nullbs)do{env'<-simplNonRecXenvcase_bndrscrut;simplExprFenv'rhscont}---------------------------------------------------- 2. Eliminate the case if scrutinee is evaluated--------------------------------------------------rebuildCaseenvscrutcase_bndr[(_,bndrs,rhs)]cont-- See if we can get rid of the case altogether-- See Note [Case elimination]-- mkCase made sure that if all the alternatives are equal,-- then there is now only one (DEFAULT) rhs|allisDeadBinderbndrs-- bndrs are [InId],ifisUnLiftedType(idTypecase_bndr)thenelim_unlifted-- Satisfy the let-binding invariantelseelim_lifted=do{-- pprTrace "case elim" (vcat [ppr case_bndr, ppr (exprIsHNF scrut),-- ppr ok_for_spec,-- ppr scrut]) $tick(CaseElimcase_bndr);env'<-simplNonRecXenvcase_bndrscrut-- If case_bndr is dead, simplNonRecX will discard;simplExprFenv'rhscont}whereelim_lifted-- See Note [Case elimination: lifted case]=exprIsHNFscrut||(is_plain_seq&&ok_for_spec)-- Note: not the same as exprIsHNF||case_bndr_evald_nextrhselim_unlifted|is_plain_seq=exprOkForSideEffectsscrut-- The entire case is dead, so we can drop it,-- _unless_ the scrutinee has side effects|otherwise=ok_for_spec-- The case-binder is alive, but we may be able-- turn the case into a let, if the expression is ok-for-spec-- See Note [Case elimination: unlifted case]ok_for_spec=exprOkForSpeculationscrutis_plain_seq=isDeadBindercase_bndr-- Evaluation *only* for effectcase_bndr_evald_next::CoreExpr->Bool-- See Note [Case binder next]case_bndr_evald_next(Varv)=v==case_bndrcase_bndr_evald_next(Caste_)=case_bndr_evald_nextecase_bndr_evald_next(Appe_)=case_bndr_evald_nextecase_bndr_evald_next(Casee___)=case_bndr_evald_nextecase_bndr_evald_next_=False-- Could add a case for Let,-- but I'm worried it could become expensive---------------------------------------------------- 3. Try seq rules; see Note [User-defined RULES for seq] in MkId--------------------------------------------------rebuildCaseenvscrutcase_bndralts@[(_,bndrs,rhs)]cont|allisDeadBinder(case_bndr:bndrs)-- So this is just 'seq'=do{letrhs'=substExpr(text"rebuild-case")envrhsenv'=zapSubstEnvenvout_args=[Type(substTyenv(idTypecase_bndr)),Type(exprTyperhs'),scrut,rhs']-- Lazily evaluated, so we don't do most of this;rule_base<-getSimplRules;mb_rule<-tryRulesenv'(getRulesrule_baseseqId)seqIdout_argscont;casemb_ruleofJust(rule_rhs,cont')->simplExprFenv'rule_rhscont'Nothing->reallyRebuildCaseenvscrutcase_bndraltscont}rebuildCaseenvscrutcase_bndraltscont=reallyRebuildCaseenvscrutcase_bndraltscont---------------------------------------------------- 3. Catch-all case--------------------------------------------------reallyRebuildCaseenvscrutcase_bndraltscont=do{-- Prepare the continuation;-- The new subst_env is in place(env',dup_cont,nodup_cont)<-prepareCaseContenvaltscont-- Simplify the alternatives;(scrut',case_bndr',alts')<-simplAltsenv'scrutcase_bndraltsdup_cont;dflags<-getDynFlags;letalts_ty'=contResultTypedup_cont;case_expr<-mkCasedflagsscrut'case_bndr'alts_ty'alts'-- Notice that rebuild gets the in-scope set from env', not alt_env-- (which in any case is only build in simplAlts)-- The case binder *not* scope over the whole returned case-expression;rebuildenv'case_exprnodup_cont}

\end{code}
simplCaseBinder checks whether the scrutinee is a variable, v. If so,
try to eliminate uses of v in the RHSs in favour of case_bndr; that
way, there's a chance that v will now only be used once, and hence
inlined.
Historical note: we use to do the "case binder swap" in the Simplifier
so there were additional complications if the scrutinee was a variable.
Now the binder-swap stuff is done in the occurrence analyer; see
OccurAnal Note [Binder swap].
Note [knownCon occ info]
~~~~~~~~~~~~~~~~~~~~~~~~
If the case binder is not dead, then neither are the pattern bound
variables:
case of x { (a,b) ->
case x of { (p,q) -> p } }
Here (a,b) both look dead, but come alive after the inner case is eliminated.
The point is that we bring into the envt a binding
let x = (a,b)
after the outer case, and that makes (a,b) alive. At least we do unless
the case binder is guaranteed dead.
Note [Case alternative occ info]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we are simply reconstructing a case (the common case), we always
zap the occurrence info on the binders in the alternatives. Even
if the case binder is dead, the scrutinee is usually a variable, and *that*
can bring the case-alternative binders back to life.
See Note [Add unfolding for scrutinee]
Note [Improving seq]
~~~~~~~~~~~~~~~~~~~
Consider
type family F :: * -> *
type instance F Int = Int
... case e of x { DEFAULT -> rhs } ...
where x::F Int. Then we'd like to rewrite (F Int) to Int, getting
case e `cast` co of x'::Int
I# x# -> let x = x' `cast` sym co
in rhs
so that 'rhs' can take advantage of the form of x'.
Notice that Note [Case of cast] (in OccurAnal) may then apply to the result.
Nota Bene: We only do the [Improving seq] transformation if the
case binder 'x' is actually used in the rhs; that is, if the case
is *not* a *pure* seq.
a) There is no point in adding the cast to a pure seq.
b) There is a good reason not to: doing so would interfere
with seq rules (Note [Built-in RULES for seq] in MkId).
In particular, this [Improving seq] thing *adds* a cast
while [Built-in RULES for seq] *removes* one, so they
just flip-flop.
You might worry about
case v of x { __DEFAULT ->
... case (v `cast` co) of y { I# -> ... }}
This is a pure seq (since x is unused), so [Improving seq] won't happen.
But it's ok: the simplifier will replace 'v' by 'x' in the rhs to get
case v of x { __DEFAULT ->
... case (x `cast` co) of y { I# -> ... }}
Now the outer case is not a pure seq, so [Improving seq] will happen,
and then the inner case will disappear.
The need for [Improving seq] showed up in Roman's experiments. Example:
foo :: F Int -> Int -> Int
foo t n = t `seq` bar n
where
bar 0 = 0
bar n = bar (n - case t of TI i -> i)
Here we'd like to avoid repeated evaluating t inside the loop, by
taking advantage of the `seq`.
At one point I did transformation in LiberateCase, but it's more
robust here. (Otherwise, there's a danger that we'll simply drop the
'seq' altogether, before LiberateCase gets to see it.)
\begin{code}

simplAlts::SimplEnv->OutExpr->InId-- Case binder->[InAlt]-- Non-empty->SimplCont->SimplM(OutExpr,OutId,[OutAlt])-- Includes the continuation-- Like simplExpr, this just returns the simplified alternatives;-- it does not return an environment-- The returned alternatives can be empty, none are possiblesimplAltsenvscrutcase_bndraltscont'=do{letenv0=zapFloatsenv;(env1,case_bndr1)<-simplBinderenv0case_bndr;fam_envs<-getFamEnvs;(alt_env',scrut',case_bndr')<-improveSeqfam_envsenv1scrutcase_bndrcase_bndr1alts;(imposs_deflt_cons,in_alts)<-prepareAltsscrut'case_bndr'alts-- NB: it's possible that the returned in_alts is empty: this is handled-- by the caller (rebuildCase) in the missingAlt function;alts'<-mapM(simplAltalt_env'(Justscrut')imposs_deflt_conscase_bndr'cont')in_alts;-- pprTrace "simplAlts" (ppr case_bndr $$ ppr alts_ty $$ ppr alts_ty' $$ ppr alts $$ ppr cont') $return(scrut',case_bndr',alts')}------------------------------------improveSeq::(FamInstEnv,FamInstEnv)->SimplEnv->OutExpr->InId->OutId->[InAlt]->SimplM(SimplEnv,OutExpr,OutId)-- Note [Improving seq]improveSeqfam_envsenvscrutcase_bndrcase_bndr1[(DEFAULT,_,_)]|not(isDeadBindercase_bndr)-- Not a pure seq! See Note [Improving seq],Just(co,ty2)<-topNormaliseType_maybefam_envs(idTypecase_bndr1)=do{case_bndr2<-newId(fsLit"nt")ty2;letrhs=DoneEx(Varcase_bndr2`Cast`mkSymCoco)env2=extendIdSubstenvcase_bndrrhs;return(env2,scrut`Cast`co,case_bndr2)}improveSeq_envscrut_case_bndr1_=return(env,scrut,case_bndr1)------------------------------------simplAlt::SimplEnv->MaybeOutExpr-- The scrutinee->[AltCon]-- These constructors can't be present when-- matching the DEFAULT alternative->OutId-- The case binder->SimplCont->InAlt->SimplMOutAltsimplAltenv_imposs_deflt_conscase_bndr'cont'(DEFAULT,bndrs,rhs)=ASSERT(nullbndrs)do{letenv'=addBinderUnfoldingenvcase_bndr'(mkOtherConimposs_deflt_cons)-- Record the constructors that the case-binder *can't* be.;rhs'<-simplExprCenv'rhscont';return(DEFAULT,[],rhs')}simplAltenvscrut'_case_bndr'cont'(LitAltlit,bndrs,rhs)=ASSERT(nullbndrs)do{env'<-addAltUnfoldingsenvscrut'case_bndr'(Litlit);rhs'<-simplExprCenv'rhscont';return(LitAltlit,[],rhs')}simplAltenvscrut'_case_bndr'cont'(DataAltcon,vs,rhs)=do{-- Deal with the pattern-bound variables-- Mark the ones that are in ! positions in the-- data constructor as certainly-evaluated.-- NB: simplLamBinders preserves this eval info;letvs_with_evals=add_evals(dataConRepStrictnesscon);(env',vs')<-simplLamBndrsenvvs_with_evals-- Bind the case-binder to (con args);letinst_tys'=tyConAppArgs(idTypecase_bndr')con_app::OutExprcon_app=mkConApp2coninst_tys'vs';env''<-addAltUnfoldingsenv'scrut'case_bndr'con_app;rhs'<-simplExprCenv''rhscont';return(DataAltcon,vs',rhs')}where-- add_evals records the evaluated-ness of the bound variables of-- a case pattern. This is *important*. Consider-- data T = T !Int !Int---- case x of { T a b -> T (a+1) b }---- We really must record that b is already evaluated so that we don't-- go and re-evaluate it when constructing the result.-- See Note [Data-con worker strictness] in MkId.lhsadd_evalsthe_strs=govsthe_strswherego[][]=[]go(v:vs')strs|isTyVarv=v:govs'strsgo(v:vs')(str:strs)|isMarkedStrictstr=evald_v:govs'strs|otherwise=zapped_v:govs'strswherezapped_v=zapIdOccInfov-- See Note [Case alternative occ info]evald_v=zapped_v`setIdUnfolding`evaldUnfoldinggo__=pprPanic"cat_evals"(pprcon$$pprvs$$pprthe_strs)addAltUnfoldings::SimplEnv->MaybeOutExpr->OutId->OutExpr->SimplMSimplEnvaddAltUnfoldingsenvscrutcase_bndrcon_app=do{dflags<-getDynFlags;letcon_app_unf=mkSimpleUnfoldingdflagscon_appenv1=addBinderUnfoldingenvcase_bndrcon_app_unf-- See Note [Add unfolding for scrutinee]env2=casescrutofJust(Varv)->addBinderUnfoldingenv1vcon_app_unfJust(Cast(Varv)co)->addBinderUnfoldingenv1v$mkSimpleUnfoldingdflags(Castcon_app(mkSymCoco))_->env1;traceSmpl"addAltUnf"(vcat[pprcase_bndr<+>pprscrut,pprcon_app]);returnenv2}addBinderUnfolding::SimplEnv->Id->Unfolding->SimplEnvaddBinderUnfoldingenvbndrunf|debugIsOn,Justtmpl<-maybeUnfoldingTemplateunf=WARN(not(eqType(idTypebndr)(exprTypetmpl)),pprbndr$$ppr(idTypebndr)$$pprtmpl$$ppr(exprTypetmpl))modifyInScopeenv(bndr`setIdUnfolding`unf)|otherwise=modifyInScopeenv(bndr`setIdUnfolding`unf)zapBndrOccInfo::Bool->Id->Id-- Consider case e of b { (a,b) -> ... }-- Then if we bind b to (a,b) in "...", and b is not dead,-- then we must zap the deadness info on a,bzapBndrOccInfokeep_occ_infopat_id|keep_occ_info=pat_id|otherwise=zapIdOccInfopat_id

\end{code}
Note [Add unfolding for scrutinee]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In general it's unlikely that a variable scrutinee will appear
in the case alternatives case x of { ...x unlikely to appear... }
because the binder-swap in OccAnal has got rid of all such occcurrences
See Note [Binder swap] in OccAnal.
BUT it is still VERY IMPORTANT to add a suitable unfolding for a
variable scrutinee, in simplAlt. Here's why
case x of y
(a,b) -> case b of c
I# v -> ...(f y)...
There is no occurrence of 'b' in the (...(f y)...). But y gets
the unfolding (a,b), and *that* mentions b. If f has a RULE
RULE f (p, I# q) = ...
we want that rule to match, so we must extend the in-scope env with a
suitable unfolding for 'y'. It's *essential* for rule matching; but
it's also good for case-elimintation -- suppose that 'f' was inlined
and did multi-level case analysis, then we'd solve it in one
simplifier sweep instead of two.
Exactly the same issue arises in SpecConstr;
see Note [Add scrutinee to ValueEnv too] in SpecConstr
HOWEVER, given
case x of y { Just a -> r1; Nothing -> r2 }
we do not want to add the unfolding x -> y to 'x', which might seem cool,
since 'y' itself has different unfoldings in r1 and r2. Reason: if we
did that, we'd have to zap y's deadness info and that is a very useful
piece of information.
So instead we add the unfolding x -> Just a, and x -> Nothing in the
respective RHSs.
%************************************************************************
%* *
\subsection{Known constructor}
%* *
%************************************************************************
We are a bit careful with occurrence info. Here's an example
(\x* -> case x of (a*, b) -> f a) (h v, e)
where the * means "occurs once". This effectively becomes
case (h v, e) of (a*, b) -> f a)
and then
let a* = h v; b = e in f a
and then
f (h v)
All this should happen in one sweep.
\begin{code}

knownCon::SimplEnv->OutExpr-- The scrutinee->DataCon->[OutType]->[OutExpr]-- The scrutinee (in pieces)->InId->[InBndr]->InExpr-- The alternative->SimplCont->SimplM(SimplEnv,OutExpr)knownConenvscrutdcdc_ty_argsdc_argsbndrbsrhscont=do{env'<-bind_argsenvbsdc_args;env''<-bind_case_bndrenv';simplExprFenv''rhscont}wherezap_occ=zapBndrOccInfo(isDeadBinderbndr)-- bndr is an InId-- Ugh!bind_argsenv'[]_=returnenv'bind_argsenv'(b:bs')(Typety:args)=ASSERT(isTyVarb)bind_args(extendTvSubstenv'bty)bs'argsbind_argsenv'(b:bs')(arg:args)=ASSERT(isIdb)do{letb'=zap_occb-- Note that the binder might be "dead", because it doesn't-- occur in the RHS; and simplNonRecX may therefore discard-- it via postInlineUnconditionally.-- Nevertheless we must keep it if the case-binder is alive,-- because it may be used in the con_app. See Note [knownCon occ info];env''<-simplNonRecXenv'b'arg;bind_argsenv''bs'args}bind_args___=pprPanic"bind_args"$pprdc$$pprbs$$pprdc_args$$text"scrut:"<+>pprscrut-- It's useful to bind bndr to scrut, rather than to a fresh-- binding x = Con arg1 .. argn-- because very often the scrut is a variable, so we avoid-- creating, and then subsequently eliminating, a let-binding-- BUT, if scrut is a not a variable, we must be careful-- about duplicating the arg redexes; in that case, make-- a new con-app from the argsbind_case_bndrenv|isDeadBinderbndr=returnenv|exprIsTrivialscrut=return(extendIdSubstenvbndr(DoneExscrut))|otherwise=do{dc_args<-mapM(simplVarenv)bs-- dc_ty_args are aready OutTypes,-- but bs are InBndrs;letcon_app=Var(dataConWorkIddc)`mkTyApps`dc_ty_args`mkApps`dc_args;simplNonRecXenvbndrcon_app}-------------------missingAlt::SimplEnv->Id->[InAlt]->SimplCont->SimplM(SimplEnv,OutExpr)-- This isn't strictly an error, although it is unusual.-- It's possible that the simplifer might "see" that-- an inner case has no accessible alternatives before-- it "sees" that the entire branch of an outer case is-- inaccessible. So we simply put an error case here instead.missingAltenvcase_bndr_cont=WARN(True,ptext(sLit"missingAlt")<+>pprcase_bndr)return(env,mkImpossibleExpr(contResultTypecont))

\end{code}
Note [Bottom alternatives]
~~~~~~~~~~~~~~~~~~~~~~~~~~
When we have
case (case x of { A -> error .. ; B -> e; C -> error ..)
of alts
then we can just duplicate those alts because the A and C cases
will disappear immediately. This is more direct than creating
join points and inlining them away; and in some cases we would
not even create the join points (see Note [Single-alternative case])
and we would keep the case-of-case which is silly. See Trac #4930.
\begin{code}

mkDupableCont::SimplEnv->SimplCont->SimplM(SimplEnv,SimplCont,SimplCont)mkDupableContenvcont|contIsDupablecont=return(env,cont,mkBoringStop(contResultTypecont))mkDupableCont_(Stop{})=panic"mkDupableCont"-- Handled by previous eqnmkDupableContenv(CoerceIttycont)=do{(env',dup,nodup)<-mkDupableContenvcont;return(env',CoerceIttydup,nodup)}-- Duplicating ticks for now, not sure if this is good or notmkDupableContenvcont@(TickIt{})=return(env,mkBoringStop(contInputTypecont),cont)mkDupableContenvcont@(StrictBind{})=return(env,mkBoringStop(contInputTypecont),cont)-- See Note [Duplicating StrictBind]mkDupableContenv(StrictArginfoccicont)-- See Note [Duplicating StrictArg]=do{(env',dup,nodup)<-mkDupableContenvcont;(env'',args')<-mapAccumLMmakeTrivialArgenv'(ai_argsinfo);return(env'',StrictArg(info{ai_args=args'})ccidup,nodup)}mkDupableContenv(ApplyTo_argsecont)=-- e.g. [...hole...] (...arg...)-- ==>-- let a = ...arg...-- in [...hole...] ado{(env',dup_cont,nodup_cont)<-mkDupableContenvcont;arg'<-simplExpr(se`setInScope`env')arg;(env'',arg'')<-makeTrivialNotTopLevelenv'arg';letapp_cont=ApplyToOkToDuparg''(zapSubstEnvenv'')dup_cont;return(env'',app_cont,nodup_cont)}mkDupableContenvcont@(Select_case_bndr[(_,bs,_rhs)]__)-- See Note [Single-alternative case]-- | not (exprIsDupable rhs && contIsDupable case_cont)-- | not (isDeadBinder case_bndr)|allisDeadBinderbs-- InIds&&not(isUnLiftedType(idTypecase_bndr))-- Note [Single-alternative-unlifted]=return(env,mkBoringStop(contInputTypecont),cont)mkDupableContenv(Select_case_bndraltssecont)=-- e.g. (case [...hole...] of { pi -> ei })-- ===>-- let ji = \xij -> ei-- in case [...hole...] of { pi -> ji xij }do{tick(CaseOfCasecase_bndr);(env',dup_cont,nodup_cont)<-prepareCaseContenvaltscont-- NB: We call prepareCaseCont here. If there is only one-- alternative, then dup_cont may be big, but that's ok-- because we push it into the single alternative, and then-- use mkDupableAlt to turn that simplified alternative into-- a join point if it's too big to duplicate.-- And this is important: see Note [Fusing case continuations];letalt_env=se`setInScope`env';(alt_env',case_bndr')<-simplBinderalt_envcase_bndr;alts'<-mapM(simplAltalt_env'Nothing[]case_bndr'dup_cont)alts-- Safe to say that there are no handled-cons for the DEFAULT case-- NB: simplBinder does not zap deadness occ-info, so-- a dead case_bndr' will still advertise its deadness-- This is really important because in-- case e of b { (# p,q #) -> ... }-- b is always dead, and indeed we are not allowed to bind b to (# p,q #),-- which might happen if e was an explicit unboxed pair and b wasn't marked dead.-- In the new alts we build, we have the new case binder, so it must retain-- its deadness.-- NB: we don't use alt_env further; it has the substEnv for-- the alternatives, and we don't want that;(env'',alts'')<-mkDupableAltsenv'case_bndr'alts';return(env'',-- Note [Duplicated env]SelectOkToDupcase_bndr'alts''(zapSubstEnvenv'')(mkBoringStop(contInputTypenodup_cont)),nodup_cont)}mkDupableAlts::SimplEnv->OutId->[InAlt]->SimplM(SimplEnv,[InAlt])-- Absorbs the continuation into the new alternativesmkDupableAltsenvcase_bndr'the_alts=goenvthe_altswheregoenv0[]=return(env0,[])goenv0(alt:alts)=do{(env1,alt')<-mkDupableAltenv0case_bndr'alt;(env2,alts')<-goenv1alts;return(env2,alt':alts')}mkDupableAlt::SimplEnv->OutId->(AltCon,[CoreBndr],CoreExpr)->SimplM(SimplEnv,(AltCon,[CoreBndr],CoreExpr))mkDupableAltenvcase_bndr(con,bndrs',rhs')=dodflags<-getDynFlagsifexprIsDupabledflagsrhs'-- Note [Small alternative rhs]thenreturn(env,(con,bndrs',rhs'))elsedo{letrhs_ty'=exprTyperhs'scrut_ty=idTypecase_bndrcase_bndr_w_unf=caseconofDEFAULT->case_bndrDataAltdc->setIdUnfoldingcase_bndrunfwhere-- See Note [Case binders and join points]unf=mkInlineUnfoldingNothingrhsrhs=mkConApp2dc(tyConAppArgsscrut_ty)bndrs'LitAlt{}->WARN(True,ptext(sLit"mkDupableAlt")<+>pprcase_bndr<+>pprcon)case_bndr-- The case binder is alive but trivial, so why has-- it not been substituted away?used_bndrs'|isDeadBindercase_bndr=filterabstract_overbndrs'|otherwise=bndrs'++[case_bndr_w_unf]abstract_overbndr|isTyVarbndr=True-- Abstract over all type variables just in case|otherwise=not(isDeadBinderbndr)-- The deadness info on the new Ids is preserved by simplBinders;(final_bndrs',final_args)-- Note [Join point abstraction]<-if(anyisIdused_bndrs')thenreturn(used_bndrs',varsToCoreExprsused_bndrs')elsedo{rw_id<-newId(fsLit"w")voidPrimTy;return([setOneShotLambdarw_id],[VarvoidPrimId])};join_bndr<-newId(fsLit"$j")(mkPiTypesfinal_bndrs'rhs_ty')-- Note [Funky mkPiTypes];let-- We make the lambdas into one-shot-lambdas. The-- join point is sure to be applied at most once, and doing so-- prevents the body of the join point being floated out by-- the full laziness passreally_final_bndrs=mapone_shotfinal_bndrs'one_shotv|isIdv=setOneShotLambdav|otherwise=vjoin_rhs=mkLamsreally_final_bndrsrhs'join_arity=exprArityjoin_rhsjoin_call=mkApps(Varjoin_bndr)final_args;env'<-addPolyBindNotTopLevelenv(NonRec(join_bndr`setIdArity`join_arity)join_rhs);return(env',(con,bndrs',join_call))}-- See Note [Duplicated env]

\end{code}
Note [Fusing case continuations]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It's important to fuse two successive case continuations when the
first has one alternative. That's why we call prepareCaseCont here.
Consider this, which arises from thunk splitting (see Note [Thunk
splitting] in WorkWrap):
let
x* = case (case v of {pn -> rn}) of
I# a -> I# a
in body
The simplifier will find
(Var v) with continuation
Select (pn -> rn) (
Select [I# a -> I# a] (
StrictBind body Stop
So we'll call mkDupableCont on
Select [I# a -> I# a] (StrictBind body Stop)
There is just one alternative in the first Select, so we want to
simplify the rhs (I# a) with continuation (StricgtBind body Stop)
Supposing that body is big, we end up with
let $j a =
in case v of { pn -> case rn of
I# a -> $j a }
This is just what we want because the rn produces a box that
the case rn cancels with.
See Trac #4957 a fuller example.
Note [Case binders and join points]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this
case (case .. ) of c {
I# c# -> ....c....
If we make a join point with c but not c# we get
$j = \c -> ....c....
But if later inlining scrutines the c, thus
$j = \c -> ... case c of { I# y -> ... } ...
we won't see that 'c' has already been scrutinised. This actually
happens in the 'tabulate' function in wave4main, and makes a significant
difference to allocation.
An alternative plan is this:
$j = \c# -> let c = I# c# in ...c....
but that is bad if 'c' is *not* later scrutinised.
So instead we do both: we pass 'c' and 'c#' , and record in c's inlining
(an InlineRule) that it's really I# c#, thus
$j = \c# -> \c[=I# c#] -> ...c....
Absence analysis may later discard 'c'.
NB: take great care when doing strictness analysis;
see Note [Lamba-bound unfoldings] in DmdAnal.
Also note that we can still end up passing stuff that isn't used. Before
strictness analysis we have
let $j x y c{=(x,y)} = (h c, ...)
in ...
After strictness analysis we see that h is strict, we end up with
let $j x y c{=(x,y)} = ($wh x y, ...)
and c is unused.
Note [Duplicated env]
~~~~~~~~~~~~~~~~~~~~~
Some of the alternatives are simplified, but have not been turned into a join point
So they *must* have an zapped subst-env. So we can't use completeNonRecX to
bind the join point, because it might to do PostInlineUnconditionally, and
we'd lose that when zapping the subst-env. We could have a per-alt subst-env,
but zapping it (as we do in mkDupableCont, the Select case) is safe, and
at worst delays the join-point inlining.
Note [Small alternative rhs]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It is worth checking for a small RHS because otherwise we
get extra let bindings that may cause an extra iteration of the simplifier to
inline back in place. Quite often the rhs is just a variable or constructor.
The Ord instance of Maybe in PrelMaybe.lhs, for example, took several extra
iterations because the version with the let bindings looked big, and so wasn't
inlined, but after the join points had been inlined it looked smaller, and so
was inlined.
NB: we have to check the size of rhs', not rhs.
Duplicating a small InAlt might invalidate occurrence information
However, if it *is* dupable, we return the *un* simplified alternative,
because otherwise we'd need to pair it up with an empty subst-env....
but we only have one env shared between all the alts.
(Remember we must zap the subst-env before re-simplifying something).
Rather than do this we simply agree to re-simplify the original (small) thing later.
Note [Funky mkPiTypes]
~~~~~~~~~~~~~~~~~~~~~~
Notice the funky mkPiTypes. If the contructor has existentials
it's possible that the join point will be abstracted over
type varaibles as well as term variables.
Example: Suppose we have
data T = forall t. C [t]
Then faced with
case (case e of ...) of
C t xs::[t] -> rhs
We get the join point
let j :: forall t. [t] -> ...
j = /\t \xs::[t] -> rhs
in
case (case e of ...) of
C t xs::[t] -> j t xs
Note [Join point abstraction]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Join points always have at least one value argument,
for several reasons
* If we try to lift a primitive-typed something out
for let-binding-purposes, we will *caseify* it (!),
with potentially-disastrous strictness results. So
instead we turn it into a function: \v -> e
where v::Void#. The value passed to this function is void,
which generates (almost) no code.
* CPR. We used to say "&& isUnLiftedType rhs_ty'" here, but now
we make the join point into a function whenever used_bndrs'
is empty. This makes the join-point more CPR friendly.
Consider: let j = if .. then I# 3 else I# 4
in case .. of { A -> j; B -> j; C -> ... }
Now CPR doesn't w/w j because it's a thunk, so
that means that the enclosing function can't w/w either,
which is a lose. Here's the example that happened in practice:
kgmod :: Int -> Int -> Int
kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
then 78
else 5
* Let-no-escape. We want a join point to turn into a let-no-escape
so that it is implemented as a jump, and one of the conditions
for LNE is that it's not updatable. In CoreToStg, see
Note [What is a non-escaping let]
* Floating. Since a join point will be entered once, no sharing is
gained by floating out, but something might be lost by doing
so because it might be allocated.
I have seen a case alternative like this:
True -> \v -> ...
It's a bit silly to add the realWorld dummy arg in this case, making
$j = \s v -> ...
True -> $j s
(the \v alone is enough to make CPR happy) but I think it's rare
There's a slight infelicity here: we pass the overall
case_bndr to all the join points if it's used in *any* RHS,
because we don't know its usage in each RHS separately
Note [Duplicating StrictArg]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The original plan had (where E is a big argument)
e.g. f E [..hole..]
==> let $j = \a -> f E a
in $j [..hole..]
But this is terrible! Here's an example:
&& E (case x of { T -> F; F -> T })
Now, && is strict so we end up simplifying the case with
an ArgOf continuation. If we let-bind it, we get
let $j = \v -> && E v
in simplExpr (case x of { T -> F; F -> T })
(ArgOf (\r -> $j r)
And after simplifying more we get
let $j = \v -> && E v
in case x of { T -> $j F; F -> $j T }
Which is a Very Bad Thing
What we do now is this
f E [..hole..]
==> let a = E
in f a [..hole..]
Now if the thing in the hole is a case expression (which is when
we'll call mkDupableCont), we'll push the function call into the
branches, which is what we want. Now RULES for f may fire, and
call-pattern specialisation. Here's an example from Trac #3116
go (n+1) (case l of
1 -> bs'
_ -> Chunk p fpc (o+1) (l-1) bs')
If we can push the call for 'go' inside the case, we get
call-pattern specialisation for 'go', which is *crucial* for
this program.
Here is the (&&) example:
&& E (case x of { T -> F; F -> T })
==> let a = E in
case x of { T -> && a F; F -> && a T }
Much better!
Notice that
* Arguments to f *after* the strict one are handled by
the ApplyTo case of mkDupableCont. Eg
f [..hole..] E
* We can only do the let-binding of E because the function
part of a StrictArg continuation is an explicit syntax
tree. In earlier versions we represented it as a function
(CoreExpr -> CoreEpxr) which we couldn't take apart.
Do *not* duplicate StrictBind and StritArg continuations. We gain
nothing by propagating them into the expressions, and we do lose a
lot.
The desire not to duplicate is the entire reason that
mkDupableCont returns a pair of continuations.
Note [Duplicating StrictBind]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unlike StrictArg, there doesn't seem anything to gain from
duplicating a StrictBind continuation, so we don't.
Note [Single-alternative cases]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This case is just like the ArgOf case. Here's an example:
data T a = MkT !a
...(MkT (abs x))...
Then we get
case (case x of I# x' ->
case x' I# (negate# x')
False -> I# x') of y {
DEFAULT -> MkT y
Because the (case x) has only one alternative, we'll transform to
case x of I# x' ->
case (case x' I# (negate# x')
False -> I# x') of y {
DEFAULT -> MkT y
But now we do *NOT* want to make a join point etc, giving
case x of I# x' ->
let $j = \y -> MkT y
in case x' $j (I# (negate# x'))
False -> $j (I# x')
In this case the $j will inline again, but suppose there was a big
strict computation enclosing the orginal call to MkT. Then, it won't
"see" the MkT any more, because it's big and won't get duplicated.
And, what is worse, nothing was gained by the case-of-case transform.
So, in circumstances like these, we don't want to build join points
and push the outer case into the branches of the inner one. Instead,
don't duplicate the continuation.
When should we use this strategy? We should not use it on *every*
single-alternative case:
e.g. case (case ....) of (a,b) -> (# a,b #)
Here we must push the outer case into the inner one!
Other choices:
* Match [(DEFAULT,_,_)], but in the common case of Int,
the alternative-filling-in code turned the outer case into
case (...) of y { I# _ -> MkT y }
* Match on single alternative plus (not (isDeadBinder case_bndr))
Rationale: pushing the case inwards won't eliminate the construction.
But there's a risk of
case (...) of y { (a,b) -> let z=(a,b) in ... }
Now y looks dead, but it'll come alive again. Still, this
seems like the best option at the moment.
* Match on single alternative plus (all (isDeadBinder bndrs))
Rationale: this is essentially seq.
* Match when the rhs is *not* duplicable, and hence would lead to a
join point. This catches the disaster-case above. We can test
the *un-simplified* rhs, which is fine. It might get bigger or
smaller after simplification; if it gets smaller, this case might
fire next time round. NB also that we must test contIsDupable
case_cont *too, because case_cont might be big!
HOWEVER: I found that this version doesn't work well, because
we can get let x = case (...) of { small } in ...case x...
When x is inlined into its full context, we find that it was a bad
idea to have pushed the outer case inside the (...) case.
Note [Single-alternative-unlifted]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Here's another single-alternative where we really want to do case-of-case:
data Mk1 = Mk1 Int# | Mk2 Int#
M1.f =
\r [x_s74 y_s6X]
case
case y_s6X of tpl_s7m {
M1.Mk1 ipv_s70 -> ipv_s70;
M1.Mk2 ipv_s72 -> ipv_s72;
}
of
wild_s7c
{ __DEFAULT ->
case
case x_s74 of tpl_s7n {
M1.Mk1 ipv_s77 -> ipv_s77;
M1.Mk2 ipv_s79 -> ipv_s79;
}
of
wild1_s7b
{ __DEFAULT -> ==# [wild1_s7b wild_s7c];
};
};
So the outer case is doing *nothing at all*, other than serving as a
join-point. In this case we really want to do case-of-case and decide
whether to use a real join point or just duplicate the continuation:
let $j s7c = case x of
Mk1 ipv77 -> (==) s7c ipv77
Mk1 ipv79 -> (==) s7c ipv79
in
case y of
Mk1 ipv70 -> $j ipv70
Mk2 ipv72 -> $j ipv72
Hence: check whether the case binder's type is unlifted, because then
the outer case is *not* a seq.