2 % (c) The AQUA Project, Glasgow University, 1993-1998
4 \section[Simplify]{The main module of the simplifier}
7 module Simplify ( simplTopBinds, simplExpr ) where
9 #include "HsVersions.h"
11 import CmdLineOpts ( dopt, DynFlag(Opt_D_dump_inlinings),
15 import SimplUtils ( mkCase, mkLam, newId, prepareAlts,
16 simplBinder, simplBinders, simplLamBndrs, simplRecBndrs, simplLetBndr,
17 SimplCont(..), DupFlag(..), LetRhsFlag(..),
18 mkStop, mkBoringStop, pushContArgs,
19 contResultType, countArgs, contIsDupable, contIsRhsOrArg,
20 getContArgs, interestingCallContext, interestingArg, isStrictType
22 import Var ( mustHaveLocalBinding )
24 import Id ( Id, idType, idInfo, idArity, isDataConWorkId,
25 setIdUnfolding, isDeadBinder,
26 idNewDemandInfo, setIdInfo,
27 setIdOccInfo, zapLamIdInfo, setOneShotLambda,
29 import OccName ( encodeFS )
30 import IdInfo ( OccInfo(..), isLoopBreaker,
35 import NewDemand ( isStrictDmd )
36 import DataCon ( dataConNumInstArgs, dataConRepStrictness )
38 import PprCore ( pprParendExpr, pprCoreExpr )
39 import CoreUnfold ( mkOtherCon, mkUnfolding, callSiteInline )
40 import CoreUtils ( exprIsDupable, exprIsTrivial, needsCaseBinding,
41 exprIsConApp_maybe, mkPiTypes, findAlt,
42 exprType, exprIsValue,
43 exprOkForSpeculation, exprArity,
44 mkCoerce, mkCoerce2, mkSCC, mkInlineMe, mkAltExpr, applyTypeToArg
46 import Rules ( lookupRule )
47 import BasicTypes ( isMarkedStrict )
48 import CostCentre ( currentCCS )
49 import Type ( isUnLiftedType, seqType, tyConAppArgs, funArgTy,
50 splitFunTy_maybe, splitFunTy, eqType
52 import Subst ( mkSubst, substTy, substExpr,
53 isInScope, lookupIdSubst, simplIdInfo
55 import TysPrim ( realWorldStatePrimTy )
56 import PrelInfo ( realWorldPrimId )
57 import BasicTypes ( TopLevelFlag(..), isTopLevel,
61 import Maybe ( Maybe )
63 import Util ( notNull )
67 The guts of the simplifier is in this module, but the driver loop for
68 the simplifier is in SimplCore.lhs.
71 -----------------------------------------
72 *** IMPORTANT NOTE ***
73 -----------------------------------------
74 The simplifier used to guarantee that the output had no shadowing, but
75 it does not do so any more. (Actually, it never did!) The reason is
76 documented with simplifyArgs.
79 -----------------------------------------
80 *** IMPORTANT NOTE ***
81 -----------------------------------------
82 Many parts of the simplifier return a bunch of "floats" as well as an
83 expression. This is wrapped as a datatype SimplUtils.FloatsWith.
85 All "floats" are let-binds, not case-binds, but some non-rec lets may
86 be unlifted (with RHS ok-for-speculation).
90 -----------------------------------------
91 ORGANISATION OF FUNCTIONS
92 -----------------------------------------
94 - simplify all top-level binders
95 - for NonRec, call simplRecOrTopPair
96 - for Rec, call simplRecBind
99 ------------------------------
100 simplExpr (applied lambda) ==> simplNonRecBind
101 simplExpr (Let (NonRec ...) ..) ==> simplNonRecBind
102 simplExpr (Let (Rec ...) ..) ==> simplify binders; simplRecBind
104 ------------------------------
105 simplRecBind [binders already simplfied]
106 - use simplRecOrTopPair on each pair in turn
108 simplRecOrTopPair [binder already simplified]
109 Used for: recursive bindings (top level and nested)
110 top-level non-recursive bindings
112 - check for PreInlineUnconditionally
116 Used for: non-top-level non-recursive bindings
117 beta reductions (which amount to the same thing)
118 Because it can deal with strict arts, it takes a
119 "thing-inside" and returns an expression
121 - check for PreInlineUnconditionally
122 - simplify binder, including its IdInfo
131 simplNonRecX: [given a *simplified* RHS, but an *unsimplified* binder]
132 Used for: binding case-binder and constr args in a known-constructor case
133 - check for PreInLineUnconditionally
137 ------------------------------
138 simplLazyBind: [binder already simplified, RHS not]
139 Used for: recursive bindings (top level and nested)
140 top-level non-recursive bindings
141 non-top-level, but *lazy* non-recursive bindings
142 [must not be strict or unboxed]
143 Returns floats + an augmented environment, not an expression
144 - substituteIdInfo and add result to in-scope
145 [so that rules are available in rec rhs]
148 - float if exposes constructor or PAP
152 completeNonRecX: [binder and rhs both simplified]
153 - if the the thing needs case binding (unlifted and not ok-for-spec)
159 completeLazyBind: [given a simplified RHS]
160 [used for both rec and non-rec bindings, top level and not]
161 - try PostInlineUnconditionally
162 - add unfolding [this is the only place we add an unfolding]
167 Right hand sides and arguments
168 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
169 In many ways we want to treat
170 (a) the right hand side of a let(rec), and
171 (b) a function argument
172 in the same way. But not always! In particular, we would
173 like to leave these arguments exactly as they are, so they
174 will match a RULE more easily.
179 It's harder to make the rule match if we ANF-ise the constructor,
180 or eta-expand the PAP:
182 f (let { a = g x; b = h x } in (a,b))
185 On the other hand if we see the let-defns
190 then we *do* want to ANF-ise and eta-expand, so that p and q
191 can be safely inlined.
193 Even floating lets out is a bit dubious. For let RHS's we float lets
194 out if that exposes a value, so that the value can be inlined more vigorously.
197 r = let x = e in (x,x)
199 Here, if we float the let out we'll expose a nice constructor. We did experiments
200 that showed this to be a generally good thing. But it was a bad thing to float
201 lets out unconditionally, because that meant they got allocated more often.
203 For function arguments, there's less reason to expose a constructor (it won't
204 get inlined). Just possibly it might make a rule match, but I'm pretty skeptical.
205 So for the moment we don't float lets out of function arguments either.
210 For eta expansion, we want to catch things like
212 case e of (a,b) -> \x -> case a of (p,q) -> \y -> r
214 If the \x was on the RHS of a let, we'd eta expand to bring the two
215 lambdas together. And in general that's a good thing to do. Perhaps
216 we should eta expand wherever we find a (value) lambda? Then the eta
217 expansion at a let RHS can concentrate solely on the PAP case.
220 %************************************************************************
222 \subsection{Bindings}
224 %************************************************************************
227 simplTopBinds :: SimplEnv -> [InBind] -> SimplM [OutBind]
229 simplTopBinds env binds
230 = -- Put all the top-level binders into scope at the start
231 -- so that if a transformation rule has unexpectedly brought
232 -- anything into scope, then we don't get a complaint about that.
233 -- It's rather as if the top-level binders were imported.
234 simplRecBndrs env (bindersOfBinds binds) `thenSmpl` \ (env, bndrs') ->
235 simpl_binds env binds bndrs' `thenSmpl` \ (floats, _) ->
236 freeTick SimplifierDone `thenSmpl_`
237 returnSmpl (floatBinds floats)
239 -- We need to track the zapped top-level binders, because
240 -- they should have their fragile IdInfo zapped (notably occurrence info)
241 -- That's why we run down binds and bndrs' simultaneously.
242 simpl_binds :: SimplEnv -> [InBind] -> [OutId] -> SimplM (FloatsWith ())
243 simpl_binds env [] bs = ASSERT( null bs ) returnSmpl (emptyFloats env, ())
244 simpl_binds env (bind:binds) bs = simpl_bind env bind bs `thenSmpl` \ (floats,env) ->
245 addFloats env floats $ \env ->
246 simpl_binds env binds (drop_bs bind bs)
248 drop_bs (NonRec _ _) (_ : bs) = bs
249 drop_bs (Rec prs) bs = drop (length prs) bs
251 simpl_bind env bind bs
252 = getDOptsSmpl `thenSmpl` \ dflags ->
253 if dopt Opt_D_dump_inlinings dflags then
254 pprTrace "SimplBind" (ppr (bindersOf bind)) $ simpl_bind1 env bind bs
256 simpl_bind1 env bind bs
258 simpl_bind1 env (NonRec b r) (b':_) = simplRecOrTopPair env TopLevel b b' r
259 simpl_bind1 env (Rec pairs) bs' = simplRecBind env TopLevel pairs bs'
263 %************************************************************************
265 \subsection{simplNonRec}
267 %************************************************************************
269 simplNonRecBind is used for
270 * non-top-level non-recursive lets in expressions
274 * An unsimplified (binder, rhs) pair
275 * The env for the RHS. It may not be the same as the
276 current env because the bind might occur via (\x.E) arg
278 It uses the CPS form because the binding might be strict, in which
279 case we might discard the continuation:
280 let x* = error "foo" in (...x...)
282 It needs to turn unlifted bindings into a @case@. They can arise
283 from, say: (\x -> e) (4# + 3#)
286 simplNonRecBind :: SimplEnv
288 -> InExpr -> SimplEnv -- Arg, with its subst-env
289 -> OutType -- Type of thing computed by the context
290 -> (SimplEnv -> SimplM FloatsWithExpr) -- The body
291 -> SimplM FloatsWithExpr
293 simplNonRecBind env bndr rhs rhs_se cont_ty thing_inside
295 = pprPanic "simplNonRecBind" (ppr bndr <+> ppr rhs)
298 simplNonRecBind env bndr rhs rhs_se cont_ty thing_inside
299 | preInlineUnconditionally env NotTopLevel bndr
300 = tick (PreInlineUnconditionally bndr) `thenSmpl_`
301 thing_inside (extendSubst env bndr (ContEx (getSubstEnv rhs_se) rhs))
304 | isStrictDmd (idNewDemandInfo bndr) || isStrictType (idType bndr) -- A strict let
305 = -- Don't use simplBinder because that doesn't keep
306 -- fragile occurrence info in the substitution
307 simplLetBndr env bndr `thenSmpl` \ (env, bndr') ->
309 -- simplLetBndr doesn't deal with the IdInfo, so we must
310 -- do so here (c.f. simplLazyBind)
311 bndr'' = bndr' `setIdInfo` simplIdInfo (getSubst env) (idInfo bndr)
312 env1 = modifyInScope env bndr'' bndr''
314 simplStrictArg AnRhs env1 rhs rhs_se (idType bndr') cont_ty $ \ env rhs1 ->
316 -- Now complete the binding and simplify the body
317 completeNonRecX env True {- strict -} bndr bndr'' rhs1 thing_inside
319 | otherwise -- Normal, lazy case
320 = -- Don't use simplBinder because that doesn't keep
321 -- fragile occurrence info in the substitution
322 simplLetBndr env bndr `thenSmpl` \ (env, bndr') ->
323 simplLazyBind env NotTopLevel NonRecursive
324 bndr bndr' rhs rhs_se `thenSmpl` \ (floats, env) ->
325 addFloats env floats thing_inside
328 A specialised variant of simplNonRec used when the RHS is already simplified, notably
329 in knownCon. It uses case-binding where necessary.
332 simplNonRecX :: SimplEnv
333 -> InId -- Old binder
334 -> OutExpr -- Simplified RHS
335 -> (SimplEnv -> SimplM FloatsWithExpr)
336 -> SimplM FloatsWithExpr
338 simplNonRecX env bndr new_rhs thing_inside
339 | needsCaseBinding (idType bndr) new_rhs
340 -- Make this test *before* the preInlineUnconditionally
341 -- Consider case I# (quotInt# x y) of
342 -- I# v -> let w = J# v in ...
343 -- If we gaily inline (quotInt# x y) for v, we end up building an
345 -- let w = J# (quotInt# x y) in ...
346 -- because quotInt# can fail.
347 = simplBinder env bndr `thenSmpl` \ (env, bndr') ->
348 thing_inside env `thenSmpl` \ (floats, body) ->
349 returnSmpl (emptyFloats env, Case new_rhs bndr' [(DEFAULT, [], wrapFloats floats body)])
351 | preInlineUnconditionally env NotTopLevel bndr
352 -- This happens; for example, the case_bndr during case of
353 -- known constructor: case (a,b) of x { (p,q) -> ... }
354 -- Here x isn't mentioned in the RHS, so we don't want to
355 -- create the (dead) let-binding let x = (a,b) in ...
357 -- Similarly, single occurrences can be inlined vigourously
358 -- e.g. case (f x, g y) of (a,b) -> ....
359 -- If a,b occur once we can avoid constructing the let binding for them.
360 = thing_inside (extendSubst env bndr (ContEx emptySubstEnv new_rhs))
363 = simplBinder env bndr `thenSmpl` \ (env, bndr') ->
364 completeNonRecX env False {- Non-strict; pessimistic -}
365 bndr bndr' new_rhs thing_inside
367 completeNonRecX env is_strict old_bndr new_bndr new_rhs thing_inside
368 = mkAtomicArgs is_strict
369 True {- OK to float unlifted -}
370 new_rhs `thenSmpl` \ (aux_binds, rhs2) ->
372 -- Make the arguments atomic if necessary,
373 -- adding suitable bindings
374 addAtomicBindsE env (fromOL aux_binds) $ \ env ->
375 completeLazyBind env NotTopLevel
376 old_bndr new_bndr rhs2 `thenSmpl` \ (floats, env) ->
377 addFloats env floats thing_inside
381 %************************************************************************
383 \subsection{Lazy bindings}
385 %************************************************************************
387 simplRecBind is used for
388 * recursive bindings only
391 simplRecBind :: SimplEnv -> TopLevelFlag
392 -> [(InId, InExpr)] -> [OutId]
393 -> SimplM (FloatsWith SimplEnv)
394 simplRecBind env top_lvl pairs bndrs'
395 = go env pairs bndrs' `thenSmpl` \ (floats, env) ->
396 returnSmpl (flattenFloats floats, env)
398 go env [] _ = returnSmpl (emptyFloats env, env)
400 go env ((bndr, rhs) : pairs) (bndr' : bndrs')
401 = simplRecOrTopPair env top_lvl bndr bndr' rhs `thenSmpl` \ (floats, env) ->
402 addFloats env floats (\env -> go env pairs bndrs')
406 simplRecOrTopPair is used for
407 * recursive bindings (whether top level or not)
408 * top-level non-recursive bindings
410 It assumes the binder has already been simplified, but not its IdInfo.
413 simplRecOrTopPair :: SimplEnv
415 -> InId -> OutId -- Binder, both pre-and post simpl
416 -> InExpr -- The RHS and its environment
417 -> SimplM (FloatsWith SimplEnv)
419 simplRecOrTopPair env top_lvl bndr bndr' rhs
420 | preInlineUnconditionally env top_lvl bndr -- Check for unconditional inline
421 = tick (PreInlineUnconditionally bndr) `thenSmpl_`
422 returnSmpl (emptyFloats env, extendSubst env bndr (ContEx (getSubstEnv env) rhs))
425 = simplLazyBind env top_lvl Recursive bndr bndr' rhs env
426 -- May not actually be recursive, but it doesn't matter
430 simplLazyBind is used for
431 * recursive bindings (whether top level or not)
432 * top-level non-recursive bindings
433 * non-top-level *lazy* non-recursive bindings
435 [Thus it deals with the lazy cases from simplNonRecBind, and all cases
436 from SimplRecOrTopBind]
439 1. It assumes that the binder is *already* simplified,
440 and is in scope, but not its IdInfo
442 2. It assumes that the binder type is lifted.
444 3. It does not check for pre-inline-unconditionallly;
445 that should have been done already.
448 simplLazyBind :: SimplEnv
449 -> TopLevelFlag -> RecFlag
450 -> InId -> OutId -- Binder, both pre-and post simpl
451 -> InExpr -> SimplEnv -- The RHS and its environment
452 -> SimplM (FloatsWith SimplEnv)
454 simplLazyBind env top_lvl is_rec bndr bndr' rhs rhs_se
455 = -- Substitute IdInfo on binder, in the light of earlier
456 -- substitutions in this very letrec, and extend the
457 -- in-scope env, so that the IdInfo for this binder extends
458 -- over the RHS for the binder itself.
460 -- This is important. Manuel found cases where he really, really
461 -- wanted a RULE for a recursive function to apply in that function's
462 -- own right-hand side.
464 -- NB: does no harm for non-recursive bindings
466 bndr'' = bndr' `setIdInfo` simplIdInfo (getSubst env) (idInfo bndr)
467 env1 = modifyInScope env bndr'' bndr''
468 rhs_env = setInScope rhs_se env1
469 is_top_level = isTopLevel top_lvl
470 ok_float_unlifted = not is_top_level && isNonRec is_rec
471 rhs_cont = mkStop (idType bndr') AnRhs
473 -- Simplify the RHS; note the mkStop, which tells
474 -- the simplifier that this is the RHS of a let.
475 simplExprF rhs_env rhs rhs_cont `thenSmpl` \ (floats, rhs1) ->
477 -- If any of the floats can't be floated, give up now
478 -- (The allLifted predicate says True for empty floats.)
479 if (not ok_float_unlifted && not (allLifted floats)) then
480 completeLazyBind env1 top_lvl bndr bndr''
481 (wrapFloats floats rhs1)
484 -- ANF-ise a constructor or PAP rhs
485 mkAtomicArgs False {- Not strict -}
486 ok_float_unlifted rhs1 `thenSmpl` \ (aux_binds, rhs2) ->
488 -- If the result is a PAP, float the floats out, else wrap them
489 -- By this time it's already been ANF-ised (if necessary)
490 if isEmptyFloats floats && isNilOL aux_binds then -- Shortcut a common case
491 completeLazyBind env1 top_lvl bndr bndr'' rhs2
493 -- We use exprIsTrivial here because we want to reveal lone variables.
494 -- E.g. let { x = letrec { y = E } in y } in ...
495 -- Here we definitely want to float the y=E defn.
496 -- exprIsValue definitely isn't right for that.
498 -- BUT we can't use "exprIsCheap", because that causes a strictness bug.
499 -- x = let y* = E in case (scc y) of { T -> F; F -> T}
500 -- The case expression is 'cheap', but it's wrong to transform to
501 -- y* = E; x = case (scc y) of {...}
502 -- Either we must be careful not to float demanded non-values, or
503 -- we must use exprIsValue for the test, which ensures that the
504 -- thing is non-strict. I think. The WARN below tests for this.
505 else if is_top_level || exprIsTrivial rhs2 || exprIsValue rhs2 then
507 -- There's a subtlety here. There may be a binding (x* = e) in the
508 -- floats, where the '*' means 'will be demanded'. So is it safe
509 -- to float it out? Answer no, but it won't matter because
510 -- we only float if (a) arg' is a WHNF, or (b) it's going to top level
511 -- and so there can't be any 'will be demanded' bindings in the floats.
513 WARN( not is_top_level && any demanded_float (floatBinds floats),
514 ppr (filter demanded_float (floatBinds floats)) )
516 tick LetFloatFromLet `thenSmpl_` (
517 addFloats env1 floats $ \ env2 ->
518 addAtomicBinds env2 (fromOL aux_binds) $ \ env3 ->
519 completeLazyBind env3 top_lvl bndr bndr'' rhs2)
522 completeLazyBind env1 top_lvl bndr bndr'' (wrapFloats floats rhs1)
525 demanded_float (NonRec b r) = isStrictDmd (idNewDemandInfo b) && not (isUnLiftedType (idType b))
526 -- Unlifted-type (cheap-eagerness) lets may well have a demanded flag on them
527 demanded_float (Rec _) = False
532 %************************************************************************
534 \subsection{Completing a lazy binding}
536 %************************************************************************
539 * deals only with Ids, not TyVars
540 * takes an already-simplified binder and RHS
541 * is used for both recursive and non-recursive bindings
542 * is used for both top-level and non-top-level bindings
544 It does the following:
545 - tries discarding a dead binding
546 - tries PostInlineUnconditionally
547 - add unfolding [this is the only place we add an unfolding]
550 It does *not* attempt to do let-to-case. Why? Because it is used for
551 - top-level bindings (when let-to-case is impossible)
552 - many situations where the "rhs" is known to be a WHNF
553 (so let-to-case is inappropriate).
556 completeLazyBind :: SimplEnv
557 -> TopLevelFlag -- Flag stuck into unfolding
558 -> InId -- Old binder
559 -> OutId -- New binder
560 -> OutExpr -- Simplified RHS
561 -> SimplM (FloatsWith SimplEnv)
562 -- We return a new SimplEnv, because completeLazyBind may choose to do its work
563 -- by extending the substitution (e.g. let x = y in ...)
564 -- The new binding (if any) is returned as part of the floats.
565 -- NB: the returned SimplEnv has the right SubstEnv, but you should
566 -- (as usual) use the in-scope-env from the floats
568 completeLazyBind env top_lvl old_bndr new_bndr new_rhs
569 | postInlineUnconditionally env new_bndr occ_info new_rhs
570 = -- Drop the binding
571 tick (PostInlineUnconditionally old_bndr) `thenSmpl_`
572 returnSmpl (emptyFloats env, extendSubst env old_bndr (DoneEx new_rhs))
573 -- Use the substitution to make quite, quite sure that the substitution
574 -- will happen, since we are going to discard the binding
579 new_bndr_info = idInfo new_bndr `setArityInfo` exprArity new_rhs
581 -- Add the unfolding *only* for non-loop-breakers
582 -- Making loop breakers not have an unfolding at all
583 -- means that we can avoid tests in exprIsConApp, for example.
584 -- This is important: if exprIsConApp says 'yes' for a recursive
585 -- thing, then we can get into an infinite loop
586 info_w_unf | loop_breaker = new_bndr_info
587 | otherwise = new_bndr_info `setUnfoldingInfo` unfolding
588 unfolding = mkUnfolding (isTopLevel top_lvl) new_rhs
590 final_id = new_bndr `setIdInfo` info_w_unf
592 -- These seqs forces the Id, and hence its IdInfo,
593 -- and hence any inner substitutions
595 returnSmpl (unitFloat env final_id new_rhs, env)
598 loop_breaker = isLoopBreaker occ_info
599 old_info = idInfo old_bndr
600 occ_info = occInfo old_info
605 %************************************************************************
607 \subsection[Simplify-simplExpr]{The main function: simplExpr}
609 %************************************************************************
611 The reason for this OutExprStuff stuff is that we want to float *after*
612 simplifying a RHS, not before. If we do so naively we get quadratic
613 behaviour as things float out.
615 To see why it's important to do it after, consider this (real) example:
629 a -- Can't inline a this round, cos it appears twice
633 Each of the ==> steps is a round of simplification. We'd save a
634 whole round if we float first. This can cascade. Consider
639 let f = let d1 = ..d.. in \y -> e
643 in \x -> ...(\y ->e)...
645 Only in this second round can the \y be applied, and it
646 might do the same again.
650 simplExpr :: SimplEnv -> CoreExpr -> SimplM CoreExpr
651 simplExpr env expr = simplExprC env expr (mkStop expr_ty' AnArg)
653 expr_ty' = substTy (getSubst env) (exprType expr)
654 -- The type in the Stop continuation, expr_ty', is usually not used
655 -- It's only needed when discarding continuations after finding
656 -- a function that returns bottom.
657 -- Hence the lazy substitution
660 simplExprC :: SimplEnv -> CoreExpr -> SimplCont -> SimplM CoreExpr
661 -- Simplify an expression, given a continuation
662 simplExprC env expr cont
663 = simplExprF env expr cont `thenSmpl` \ (floats, expr) ->
664 returnSmpl (wrapFloats floats expr)
666 simplExprF :: SimplEnv -> InExpr -> SimplCont -> SimplM FloatsWithExpr
667 -- Simplify an expression, returning floated binds
669 simplExprF env (Var v) cont = simplVar env v cont
670 simplExprF env (Lit lit) cont = rebuild env (Lit lit) cont
671 simplExprF env expr@(Lam _ _) cont = simplLam env expr cont
672 simplExprF env (Note note expr) cont = simplNote env note expr cont
673 simplExprF env (App fun arg) cont = simplExprF env fun (ApplyTo NoDup arg env cont)
675 simplExprF env (Type ty) cont
676 = ASSERT( contIsRhsOrArg cont )
677 simplType env ty `thenSmpl` \ ty' ->
678 rebuild env (Type ty') cont
680 simplExprF env (Case scrut bndr alts) cont
681 | not (switchIsOn (getSwitchChecker env) NoCaseOfCase)
682 = -- Simplify the scrutinee with a Select continuation
683 simplExprF env scrut (Select NoDup bndr alts env cont)
686 = -- If case-of-case is off, simply simplify the case expression
687 -- in a vanilla Stop context, and rebuild the result around it
688 simplExprC env scrut case_cont `thenSmpl` \ case_expr' ->
689 rebuild env case_expr' cont
691 case_cont = Select NoDup bndr alts env (mkBoringStop (contResultType cont))
693 simplExprF env (Let (Rec pairs) body) cont
694 = simplRecBndrs env (map fst pairs) `thenSmpl` \ (env, bndrs') ->
695 -- NB: bndrs' don't have unfoldings or spec-envs
696 -- We add them as we go down, using simplPrags
698 simplRecBind env NotTopLevel pairs bndrs' `thenSmpl` \ (floats, env) ->
699 addFloats env floats $ \ env ->
700 simplExprF env body cont
702 -- A non-recursive let is dealt with by simplNonRecBind
703 simplExprF env (Let (NonRec bndr rhs) body) cont
704 = simplNonRecBind env bndr rhs env (contResultType cont) $ \ env ->
705 simplExprF env body cont
708 ---------------------------------
709 simplType :: SimplEnv -> InType -> SimplM OutType
710 -- Kept monadic just so we can do the seqType
712 = seqType new_ty `seq` returnSmpl new_ty
714 new_ty = substTy (getSubst env) ty
718 %************************************************************************
722 %************************************************************************
725 simplLam env fun cont
728 zap_it = mkLamBndrZapper fun (countArgs cont)
729 cont_ty = contResultType cont
731 -- Type-beta reduction
732 go env (Lam bndr body) (ApplyTo _ (Type ty_arg) arg_se body_cont)
733 = ASSERT( isTyVar bndr )
734 tick (BetaReduction bndr) `thenSmpl_`
735 simplType (setInScope arg_se env) ty_arg `thenSmpl` \ ty_arg' ->
736 go (extendSubst env bndr (DoneTy ty_arg')) body body_cont
738 -- Ordinary beta reduction
739 go env (Lam bndr body) cont@(ApplyTo _ arg arg_se body_cont)
740 = tick (BetaReduction bndr) `thenSmpl_`
741 simplNonRecBind env (zap_it bndr) arg arg_se cont_ty $ \ env ->
742 go env body body_cont
744 -- Not enough args, so there are real lambdas left to put in the result
745 go env lam@(Lam _ _) cont
746 = simplLamBndrs env bndrs `thenSmpl` \ (env, bndrs') ->
747 simplExpr env body `thenSmpl` \ body' ->
748 mkLam env bndrs' body' cont `thenSmpl` \ (floats, new_lam) ->
749 addFloats env floats $ \ env ->
750 rebuild env new_lam cont
752 (bndrs,body) = collectBinders lam
754 -- Exactly enough args
755 go env expr cont = simplExprF env expr cont
757 mkLamBndrZapper :: CoreExpr -- Function
758 -> Int -- Number of args supplied, *including* type args
759 -> Id -> Id -- Use this to zap the binders
760 mkLamBndrZapper fun n_args
761 | n_args >= n_params fun = \b -> b -- Enough args
762 | otherwise = \b -> zapLamIdInfo b
764 -- NB: we count all the args incl type args
765 -- so we must count all the binders (incl type lambdas)
766 n_params (Note _ e) = n_params e
767 n_params (Lam b e) = 1 + n_params e
768 n_params other = 0::Int
772 %************************************************************************
776 %************************************************************************
779 simplNote env (Coerce to from) body cont
781 in_scope = getInScope env
783 addCoerce s1 k1 (CoerceIt t1 cont)
784 -- coerce T1 S1 (coerce S1 K1 e)
787 -- coerce T1 K1 e, otherwise
789 -- For example, in the initial form of a worker
790 -- we may find (coerce T (coerce S (\x.e))) y
791 -- and we'd like it to simplify to e[y/x] in one round
793 | t1 `eqType` k1 = cont -- The coerces cancel out
794 | otherwise = CoerceIt t1 cont -- They don't cancel, but
795 -- the inner one is redundant
797 addCoerce t1t2 s1s2 (ApplyTo dup arg arg_se cont)
798 | not (isTypeArg arg), -- This whole case only works for value args
799 -- Could upgrade to have equiv thing for type apps too
800 Just (s1, s2) <- splitFunTy_maybe s1s2
801 -- (coerce (T1->T2) (S1->S2) F) E
803 -- coerce T2 S2 (F (coerce S1 T1 E))
805 -- t1t2 must be a function type, T1->T2, because it's applied to something
806 -- but s1s2 might conceivably not be
808 -- When we build the ApplyTo we can't mix the out-types
809 -- with the InExpr in the argument, so we simply substitute
810 -- to make it all consistent. It's a bit messy.
811 -- But it isn't a common case.
813 (t1,t2) = splitFunTy t1t2
814 new_arg = mkCoerce2 s1 t1 (substExpr (mkSubst in_scope (getSubstEnv arg_se)) arg)
816 ApplyTo dup new_arg (zapSubstEnv env) (addCoerce t2 s2 cont)
818 addCoerce to' _ cont = CoerceIt to' cont
820 simplType env to `thenSmpl` \ to' ->
821 simplType env from `thenSmpl` \ from' ->
822 simplExprF env body (addCoerce to' from' cont)
825 -- Hack: we only distinguish subsumed cost centre stacks for the purposes of
826 -- inlining. All other CCCSs are mapped to currentCCS.
827 simplNote env (SCC cc) e cont
828 = simplExpr (setEnclosingCC env currentCCS) e `thenSmpl` \ e' ->
829 rebuild env (mkSCC cc e') cont
831 simplNote env InlineCall e cont
832 = simplExprF env e (InlinePlease cont)
834 -- See notes with SimplMonad.inlineMode
835 simplNote env InlineMe e cont
836 | contIsRhsOrArg cont -- Totally boring continuation; see notes above
837 = -- Don't inline inside an INLINE expression
838 simplExpr (setMode inlineMode env ) e `thenSmpl` \ e' ->
839 rebuild env (mkInlineMe e') cont
841 | otherwise -- Dissolve the InlineMe note if there's
842 -- an interesting context of any kind to combine with
843 -- (even a type application -- anything except Stop)
844 = simplExprF env e cont
846 simplNote env (CoreNote s) e cont
847 = simplExpr env e `thenSmpl` \ e' ->
848 rebuild env (Note (CoreNote s) e') cont
852 %************************************************************************
854 \subsection{Dealing with calls}
856 %************************************************************************
859 simplVar env var cont
860 = case lookupIdSubst (getSubst env) var of
861 DoneEx e -> simplExprF (zapSubstEnv env) e cont
862 ContEx se e -> simplExprF (setSubstEnv env se) e cont
863 DoneId var1 occ -> WARN( not (isInScope var1 (getSubst env)) && mustHaveLocalBinding var1,
864 text "simplVar:" <+> ppr var )
865 completeCall (zapSubstEnv env) var1 occ cont
866 -- The template is already simplified, so don't re-substitute.
867 -- This is VITAL. Consider
869 -- let y = \z -> ...x... in
871 -- We'll clone the inner \x, adding x->x' in the id_subst
872 -- Then when we inline y, we must *not* replace x by x' in
873 -- the inlined copy!!
875 ---------------------------------------------------------
876 -- Dealing with a call site
878 completeCall env var occ_info cont
879 = -- Simplify the arguments
880 getDOptsSmpl `thenSmpl` \ dflags ->
882 chkr = getSwitchChecker env
883 (args, call_cont, inline_call) = getContArgs chkr var cont
886 simplifyArgs env fn_ty args (contResultType call_cont) $ \ env args ->
888 -- Next, look for rules or specialisations that match
890 -- It's important to simplify the args first, because the rule-matcher
891 -- doesn't do substitution as it goes. We don't want to use subst_args
892 -- (defined in the 'where') because that throws away useful occurrence info,
893 -- and perhaps-very-important specialisations.
895 -- Some functions have specialisations *and* are strict; in this case,
896 -- we don't want to inline the wrapper of the non-specialised thing; better
897 -- to call the specialised thing instead.
898 -- We used to use the black-listing mechanism to ensure that inlining of
899 -- the wrapper didn't occur for things that have specialisations till a
900 -- later phase, so but now we just try RULES first
902 -- You might think that we shouldn't apply rules for a loop breaker:
903 -- doing so might give rise to an infinite loop, because a RULE is
904 -- rather like an extra equation for the function:
905 -- RULE: f (g x) y = x+y
908 -- But it's too drastic to disable rules for loop breakers.
909 -- Even the foldr/build rule would be disabled, because foldr
910 -- is recursive, and hence a loop breaker:
911 -- foldr k z (build g) = g k z
912 -- So it's up to the programmer: rules can cause divergence
915 in_scope = getInScope env
916 maybe_rule = case activeRule env of
917 Nothing -> Nothing -- No rules apply
918 Just act_fn -> lookupRule act_fn in_scope var args
921 Just (rule_name, rule_rhs) ->
922 tick (RuleFired rule_name) `thenSmpl_`
923 (if dopt Opt_D_dump_inlinings dflags then
924 pprTrace "Rule fired" (vcat [
925 text "Rule:" <+> ftext rule_name,
926 text "Before:" <+> ppr var <+> sep (map pprParendExpr args),
927 text "After: " <+> pprCoreExpr rule_rhs,
928 text "Cont: " <+> ppr call_cont])
931 simplExprF env rule_rhs call_cont ;
933 Nothing -> -- No rules
935 -- Next, look for an inlining
937 arg_infos = [ interestingArg arg | arg <- args, isValArg arg]
939 interesting_cont = interestingCallContext (notNull args)
943 active_inline = activeInline env var occ_info
944 maybe_inline = callSiteInline dflags active_inline inline_call occ_info
945 var arg_infos interesting_cont
947 case maybe_inline of {
948 Just unfolding -- There is an inlining!
949 -> tick (UnfoldingDone var) `thenSmpl_`
950 makeThatCall env var unfolding args call_cont
953 Nothing -> -- No inlining!
956 rebuild env (mkApps (Var var) args) call_cont
959 makeThatCall :: SimplEnv
961 -> InExpr -- Inlined function rhs
962 -> [OutExpr] -- Arguments, already simplified
963 -> SimplCont -- After the call
964 -> SimplM FloatsWithExpr
965 -- Similar to simplLam, but this time
966 -- the arguments are already simplified
967 makeThatCall orig_env var fun@(Lam _ _) args cont
968 = go orig_env fun args
970 zap_it = mkLamBndrZapper fun (length args)
972 -- Type-beta reduction
973 go env (Lam bndr body) (Type ty_arg : args)
974 = ASSERT( isTyVar bndr )
975 tick (BetaReduction bndr) `thenSmpl_`
976 go (extendSubst env bndr (DoneTy ty_arg)) body args
978 -- Ordinary beta reduction
979 go env (Lam bndr body) (arg : args)
980 = tick (BetaReduction bndr) `thenSmpl_`
981 simplNonRecX env (zap_it bndr) arg $ \ env ->
984 -- Not enough args, so there are real lambdas left to put in the result
986 = simplExprF env fun (pushContArgs orig_env args cont)
987 -- NB: orig_env; the correct environment to capture with
988 -- the arguments.... env has been augmented with substitutions
989 -- from the beta reductions.
991 makeThatCall env var fun args cont
992 = simplExprF env fun (pushContArgs env args cont)
996 %************************************************************************
998 \subsection{Arguments}
1000 %************************************************************************
1003 ---------------------------------------------------------
1004 -- Simplifying the arguments of a call
1006 simplifyArgs :: SimplEnv
1007 -> OutType -- Type of the function
1008 -> [(InExpr, SimplEnv, Bool)] -- Details of the arguments
1009 -> OutType -- Type of the continuation
1010 -> (SimplEnv -> [OutExpr] -> SimplM FloatsWithExpr)
1011 -> SimplM FloatsWithExpr
1013 -- [CPS-like because of strict arguments]
1015 -- Simplify the arguments to a call.
1016 -- This part of the simplifier may break the no-shadowing invariant
1018 -- f (...(\a -> e)...) (case y of (a,b) -> e')
1019 -- where f is strict in its second arg
1020 -- If we simplify the innermost one first we get (...(\a -> e)...)
1021 -- Simplifying the second arg makes us float the case out, so we end up with
1022 -- case y of (a,b) -> f (...(\a -> e)...) e'
1023 -- So the output does not have the no-shadowing invariant. However, there is
1024 -- no danger of getting name-capture, because when the first arg was simplified
1025 -- we used an in-scope set that at least mentioned all the variables free in its
1026 -- static environment, and that is enough.
1028 -- We can't just do innermost first, or we'd end up with a dual problem:
1029 -- case x of (a,b) -> f e (...(\a -> e')...)
1031 -- I spent hours trying to recover the no-shadowing invariant, but I just could
1032 -- not think of an elegant way to do it. The simplifier is already knee-deep in
1033 -- continuations. We have to keep the right in-scope set around; AND we have
1034 -- to get the effect that finding (error "foo") in a strict arg position will
1035 -- discard the entire application and replace it with (error "foo"). Getting
1036 -- all this at once is TOO HARD!
1038 simplifyArgs env fn_ty args cont_ty thing_inside
1039 = go env fn_ty args thing_inside
1041 go env fn_ty [] thing_inside = thing_inside env []
1042 go env fn_ty (arg:args) thing_inside = simplifyArg env fn_ty arg cont_ty $ \ env arg' ->
1043 go env (applyTypeToArg fn_ty arg') args $ \ env args' ->
1044 thing_inside env (arg':args')
1046 simplifyArg env fn_ty (Type ty_arg, se, _) cont_ty thing_inside
1047 = simplType (setInScope se env) ty_arg `thenSmpl` \ new_ty_arg ->
1048 thing_inside env (Type new_ty_arg)
1050 simplifyArg env fn_ty (val_arg, arg_se, is_strict) cont_ty thing_inside
1052 = simplStrictArg AnArg env val_arg arg_se arg_ty cont_ty thing_inside
1054 | otherwise -- Lazy argument
1055 -- DO NOT float anything outside, hence simplExprC
1056 -- There is no benefit (unlike in a let-binding), and we'd
1057 -- have to be very careful about bogus strictness through
1058 -- floating a demanded let.
1059 = simplExprC (setInScope arg_se env) val_arg
1060 (mkStop arg_ty AnArg) `thenSmpl` \ arg1 ->
1061 thing_inside env arg1
1063 arg_ty = funArgTy fn_ty
1066 simplStrictArg :: LetRhsFlag
1067 -> SimplEnv -- The env of the call
1068 -> InExpr -> SimplEnv -- The arg plus its env
1069 -> OutType -- arg_ty: type of the argument
1070 -> OutType -- cont_ty: Type of thing computed by the context
1071 -> (SimplEnv -> OutExpr -> SimplM FloatsWithExpr)
1072 -- Takes an expression of type rhs_ty,
1073 -- returns an expression of type cont_ty
1074 -- The env passed to this continuation is the
1075 -- env of the call, plus any new in-scope variables
1076 -> SimplM FloatsWithExpr -- An expression of type cont_ty
1078 simplStrictArg is_rhs call_env arg arg_env arg_ty cont_ty thing_inside
1079 = simplExprF (setInScope arg_env call_env) arg
1080 (ArgOf is_rhs arg_ty cont_ty (\ new_env -> thing_inside (setInScope call_env new_env)))
1081 -- Notice the way we use arg_env (augmented with in-scope vars from call_env)
1082 -- to simplify the argument
1083 -- and call-env (augmented with in-scope vars from the arg) to pass to the continuation
1087 %************************************************************************
1089 \subsection{mkAtomicArgs}
1091 %************************************************************************
1093 mkAtomicArgs takes a putative RHS, checks whether it's a PAP or
1094 constructor application and, if so, converts it to ANF, so that the
1095 resulting thing can be inlined more easily. Thus
1102 There are three sorts of binding context, specified by the two
1108 N N Top-level or recursive Only bind args of lifted type
1110 N Y Non-top-level and non-recursive, Bind args of lifted type, or
1111 but lazy unlifted-and-ok-for-speculation
1113 Y Y Non-top-level, non-recursive, Bind all args
1114 and strict (demanded)
1121 there is no point in transforming to
1123 x = case (y div# z) of r -> MkC r
1125 because the (y div# z) can't float out of the let. But if it was
1126 a *strict* let, then it would be a good thing to do. Hence the
1127 context information.
1130 mkAtomicArgs :: Bool -- A strict binding
1131 -> Bool -- OK to float unlifted args
1133 -> SimplM (OrdList (OutId,OutExpr), -- The floats (unusually) may include
1134 OutExpr) -- things that need case-binding,
1135 -- if the strict-binding flag is on
1137 mkAtomicArgs is_strict ok_float_unlifted rhs
1138 | (Var fun, args) <- collectArgs rhs, -- It's an application
1139 isDataConWorkId fun || valArgCount args < idArity fun -- And it's a constructor or PAP
1140 = go fun nilOL [] args -- Have a go
1142 | otherwise = bale_out -- Give up
1145 bale_out = returnSmpl (nilOL, rhs)
1147 go fun binds rev_args []
1148 = returnSmpl (binds, mkApps (Var fun) (reverse rev_args))
1150 go fun binds rev_args (arg : args)
1151 | exprIsTrivial arg -- Easy case
1152 = go fun binds (arg:rev_args) args
1154 | not can_float_arg -- Can't make this arg atomic
1155 = bale_out -- ... so give up
1157 | otherwise -- Don't forget to do it recursively
1158 -- E.g. x = a:b:c:[]
1159 = mkAtomicArgs is_strict ok_float_unlifted arg `thenSmpl` \ (arg_binds, arg') ->
1160 newId FSLIT("a") arg_ty `thenSmpl` \ arg_id ->
1161 go fun ((arg_binds `snocOL` (arg_id,arg')) `appOL` binds)
1162 (Var arg_id : rev_args) args
1164 arg_ty = exprType arg
1165 can_float_arg = is_strict
1166 || not (isUnLiftedType arg_ty)
1167 || (ok_float_unlifted && exprOkForSpeculation arg)
1170 addAtomicBinds :: SimplEnv -> [(OutId,OutExpr)]
1171 -> (SimplEnv -> SimplM (FloatsWith a))
1172 -> SimplM (FloatsWith a)
1173 addAtomicBinds env [] thing_inside = thing_inside env
1174 addAtomicBinds env ((v,r):bs) thing_inside = addAuxiliaryBind env (NonRec v r) $ \ env ->
1175 addAtomicBinds env bs thing_inside
1177 addAtomicBindsE :: SimplEnv -> [(OutId,OutExpr)]
1178 -> (SimplEnv -> SimplM FloatsWithExpr)
1179 -> SimplM FloatsWithExpr
1180 -- Same again, but this time we're in an expression context,
1181 -- and may need to do some case bindings
1183 addAtomicBindsE env [] thing_inside
1185 addAtomicBindsE env ((v,r):bs) thing_inside
1186 | needsCaseBinding (idType v) r
1187 = addAtomicBindsE (addNewInScopeIds env [v]) bs thing_inside `thenSmpl` \ (floats, expr) ->
1188 WARN( exprIsTrivial expr, ppr v <+> pprCoreExpr expr )
1189 returnSmpl (emptyFloats env, Case r v [(DEFAULT,[], wrapFloats floats expr)])
1192 = addAuxiliaryBind env (NonRec v r) $ \ env ->
1193 addAtomicBindsE env bs thing_inside
1197 %************************************************************************
1199 \subsection{The main rebuilder}
1201 %************************************************************************
1204 rebuild :: SimplEnv -> OutExpr -> SimplCont -> SimplM FloatsWithExpr
1206 rebuild env expr (Stop _ _ _) = rebuildDone env expr
1207 rebuild env expr (ArgOf _ _ _ cont_fn) = cont_fn env expr
1208 rebuild env expr (CoerceIt to_ty cont) = rebuild env (mkCoerce to_ty expr) cont
1209 rebuild env expr (InlinePlease cont) = rebuild env (Note InlineCall expr) cont
1210 rebuild env expr (Select _ bndr alts se cont) = rebuildCase (setInScope se env) expr bndr alts cont
1211 rebuild env expr (ApplyTo _ arg se cont) = rebuildApp (setInScope se env) expr arg cont
1213 rebuildApp env fun arg cont
1214 = simplExpr env arg `thenSmpl` \ arg' ->
1215 rebuild env (App fun arg') cont
1217 rebuildDone env expr = returnSmpl (emptyFloats env, expr)
1221 %************************************************************************
1223 \subsection{Functions dealing with a case}
1225 %************************************************************************
1227 Blob of helper functions for the "case-of-something-else" situation.
1230 ---------------------------------------------------------
1231 -- Eliminate the case if possible
1233 rebuildCase :: SimplEnv
1234 -> OutExpr -- Scrutinee
1235 -> InId -- Case binder
1236 -> [InAlt] -- Alternatives
1238 -> SimplM FloatsWithExpr
1240 rebuildCase env scrut case_bndr alts cont
1241 | Just (con,args) <- exprIsConApp_maybe scrut
1242 -- Works when the scrutinee is a variable with a known unfolding
1243 -- as well as when it's an explicit constructor application
1244 = knownCon env (DataAlt con) args case_bndr alts cont
1246 | Lit lit <- scrut -- No need for same treatment as constructors
1247 -- because literals are inlined more vigorously
1248 = knownCon env (LitAlt lit) [] case_bndr alts cont
1251 = prepareAlts scrut case_bndr alts `thenSmpl` \ (better_alts, handled_cons) ->
1253 -- Deal with the case binder, and prepare the continuation;
1254 -- The new subst_env is in place
1255 prepareCaseCont env better_alts cont `thenSmpl` \ (floats, (dup_cont, nondup_cont)) ->
1256 addFloats env floats $ \ env ->
1258 -- Deal with variable scrutinee
1259 simplCaseBinder env scrut case_bndr `thenSmpl` \ (alt_env, case_bndr', zap_occ_info) ->
1261 -- Deal with the case alternatives
1262 simplAlts alt_env zap_occ_info handled_cons
1263 case_bndr' better_alts dup_cont `thenSmpl` \ alts' ->
1265 -- Put the case back together
1266 mkCase scrut case_bndr' alts' `thenSmpl` \ case_expr ->
1268 -- Notice that rebuildDone returns the in-scope set from env, not alt_env
1269 -- The case binder *not* scope over the whole returned case-expression
1270 rebuild env case_expr nondup_cont
1273 simplCaseBinder checks whether the scrutinee is a variable, v. If so,
1274 try to eliminate uses of v in the RHSs in favour of case_bndr; that
1275 way, there's a chance that v will now only be used once, and hence
1280 There is a time we *don't* want to do that, namely when
1281 -fno-case-of-case is on. This happens in the first simplifier pass,
1282 and enhances full laziness. Here's the bad case:
1283 f = \ y -> ...(case x of I# v -> ...(case x of ...) ... )
1284 If we eliminate the inner case, we trap it inside the I# v -> arm,
1285 which might prevent some full laziness happening. I've seen this
1286 in action in spectral/cichelli/Prog.hs:
1287 [(m,n) | m <- [1..max], n <- [1..max]]
1288 Hence the check for NoCaseOfCase.
1292 There is another situation when we don't want to do it. If we have
1294 case x of w1 { DEFAULT -> case x of w2 { A -> e1; B -> e2 }
1295 ...other cases .... }
1297 We'll perform the binder-swap for the outer case, giving
1299 case x of w1 { DEFAULT -> case w1 of w2 { A -> e1; B -> e2 }
1300 ...other cases .... }
1302 But there is no point in doing it for the inner case, because w1 can't
1303 be inlined anyway. Furthermore, doing the case-swapping involves
1304 zapping w2's occurrence info (see paragraphs that follow), and that
1305 forces us to bind w2 when doing case merging. So we get
1307 case x of w1 { A -> let w2 = w1 in e1
1308 B -> let w2 = w1 in e2
1309 ...other cases .... }
1311 This is plain silly in the common case where w2 is dead.
1313 Even so, I can't see a good way to implement this idea. I tried
1314 not doing the binder-swap if the scrutinee was already evaluated
1315 but that failed big-time:
1319 case v of w { MkT x ->
1320 case x of x1 { I# y1 ->
1321 case x of x2 { I# y2 -> ...
1323 Notice that because MkT is strict, x is marked "evaluated". But to
1324 eliminate the last case, we must either make sure that x (as well as
1325 x1) has unfolding MkT y1. THe straightforward thing to do is to do
1326 the binder-swap. So this whole note is a no-op.
1330 If we replace the scrutinee, v, by tbe case binder, then we have to nuke
1331 any occurrence info (eg IAmDead) in the case binder, because the
1332 case-binder now effectively occurs whenever v does. AND we have to do
1333 the same for the pattern-bound variables! Example:
1335 (case x of { (a,b) -> a }) (case x of { (p,q) -> q })
1337 Here, b and p are dead. But when we move the argment inside the first
1338 case RHS, and eliminate the second case, we get
1340 case x or { (a,b) -> a b }
1342 Urk! b is alive! Reason: the scrutinee was a variable, and case elimination
1343 happened. Hence the zap_occ_info function returned by simplCaseBinder
1346 simplCaseBinder env (Var v) case_bndr
1347 | not (switchIsOn (getSwitchChecker env) NoCaseOfCase)
1349 -- Failed try [see Note 2 above]
1350 -- not (isEvaldUnfolding (idUnfolding v))
1352 = simplBinder env (zap case_bndr) `thenSmpl` \ (env, case_bndr') ->
1353 returnSmpl (modifyInScope env v case_bndr', case_bndr', zap)
1354 -- We could extend the substitution instead, but it would be
1355 -- a hack because then the substitution wouldn't be idempotent
1356 -- any more (v is an OutId). And this just just as well.
1358 zap b = b `setIdOccInfo` NoOccInfo
1360 simplCaseBinder env other_scrut case_bndr
1361 = simplBinder env case_bndr `thenSmpl` \ (env, case_bndr') ->
1362 returnSmpl (env, case_bndr', \ bndr -> bndr) -- NoOp on bndr
1368 simplAlts :: SimplEnv
1369 -> (InId -> InId) -- Occ-info zapper
1370 -> [AltCon] -- Alternatives the scrutinee can't be
1371 -- in the default case
1372 -> OutId -- Case binder
1373 -> [InAlt] -> SimplCont
1374 -> SimplM [OutAlt] -- Includes the continuation
1376 simplAlts env zap_occ_info handled_cons case_bndr' alts cont'
1377 = mapSmpl simpl_alt alts
1379 inst_tys' = tyConAppArgs (idType case_bndr')
1381 simpl_alt (DEFAULT, _, rhs)
1383 -- In the default case we record the constructors that the
1384 -- case-binder *can't* be.
1385 -- We take advantage of any OtherCon info in the case scrutinee
1386 case_bndr_w_unf = case_bndr' `setIdUnfolding` mkOtherCon handled_cons
1387 env_with_unf = modifyInScope env case_bndr' case_bndr_w_unf
1389 simplExprC env_with_unf rhs cont' `thenSmpl` \ rhs' ->
1390 returnSmpl (DEFAULT, [], rhs')
1392 simpl_alt (con, vs, rhs)
1393 = -- Deal with the pattern-bound variables
1394 -- Mark the ones that are in ! positions in the data constructor
1395 -- as certainly-evaluated.
1396 -- NB: it happens that simplBinders does *not* erase the OtherCon
1397 -- form of unfolding, so it's ok to add this info before
1398 -- doing simplBinders
1399 simplBinders env (add_evals con vs) `thenSmpl` \ (env, vs') ->
1401 -- Bind the case-binder to (con args)
1403 unfolding = mkUnfolding False (mkAltExpr con vs' inst_tys')
1404 env_with_unf = modifyInScope env case_bndr' (case_bndr' `setIdUnfolding` unfolding)
1406 simplExprC env_with_unf rhs cont' `thenSmpl` \ rhs' ->
1407 returnSmpl (con, vs', rhs')
1410 -- add_evals records the evaluated-ness of the bound variables of
1411 -- a case pattern. This is *important*. Consider
1412 -- data T = T !Int !Int
1414 -- case x of { T a b -> T (a+1) b }
1416 -- We really must record that b is already evaluated so that we don't
1417 -- go and re-evaluate it when constructing the result.
1419 add_evals (DataAlt dc) vs = cat_evals vs (dataConRepStrictness dc)
1420 add_evals other_con vs = vs
1422 cat_evals [] [] = []
1423 cat_evals (v:vs) (str:strs)
1424 | isTyVar v = v : cat_evals vs (str:strs)
1425 | isMarkedStrict str = evald_v : cat_evals vs strs
1426 | otherwise = zapped_v : cat_evals vs strs
1428 zapped_v = zap_occ_info v
1429 evald_v = zapped_v `setIdUnfolding` mkOtherCon []
1433 %************************************************************************
1435 \subsection{Known constructor}
1437 %************************************************************************
1439 We are a bit careful with occurrence info. Here's an example
1441 (\x* -> case x of (a*, b) -> f a) (h v, e)
1443 where the * means "occurs once". This effectively becomes
1444 case (h v, e) of (a*, b) -> f a)
1446 let a* = h v; b = e in f a
1450 All this should happen in one sweep.
1453 knownCon :: SimplEnv -> AltCon -> [OutExpr]
1454 -> InId -> [InAlt] -> SimplCont
1455 -> SimplM FloatsWithExpr
1457 knownCon env con args bndr alts cont
1458 = tick (KnownBranch bndr) `thenSmpl_`
1459 case findAlt con alts of
1460 (DEFAULT, bs, rhs) -> ASSERT( null bs )
1461 simplNonRecX env bndr scrut $ \ env ->
1462 -- This might give rise to a binding with non-atomic args
1463 -- like x = Node (f x) (g x)
1464 -- but no harm will be done
1465 simplExprF env rhs cont
1468 LitAlt lit -> Lit lit
1469 DataAlt dc -> mkConApp dc args
1471 (LitAlt lit, bs, rhs) -> ASSERT( null bs )
1472 simplNonRecX env bndr (Lit lit) $ \ env ->
1473 simplExprF env rhs cont
1475 (DataAlt dc, bs, rhs) -> ASSERT( length bs + n_tys == length args )
1476 bind_args env bs (drop n_tys args) $ \ env ->
1478 con_app = mkConApp dc (take n_tys args ++ con_args)
1479 con_args = [substExpr (getSubst env) (varToCoreExpr b) | b <- bs]
1480 -- args are aready OutExprs, but bs are InIds
1482 simplNonRecX env bndr con_app $ \ env ->
1483 simplExprF env rhs cont
1485 n_tys = dataConNumInstArgs dc -- Non-existential type args
1487 bind_args env [] _ thing_inside = thing_inside env
1489 bind_args env (b:bs) (Type ty : args) thing_inside
1490 = bind_args (extendSubst env b (DoneTy ty)) bs args thing_inside
1492 bind_args env (b:bs) (arg : args) thing_inside
1493 = simplNonRecX env b arg $ \ env ->
1494 bind_args env bs args thing_inside
1498 %************************************************************************
1500 \subsection{Duplicating continuations}
1502 %************************************************************************
1505 prepareCaseCont :: SimplEnv
1506 -> [InAlt] -> SimplCont
1507 -> SimplM (FloatsWith (SimplCont,SimplCont))
1508 -- Return a duplicatable continuation, a non-duplicable part
1509 -- plus some extra bindings
1511 -- No need to make it duplicatable if there's only one alternative
1512 prepareCaseCont env [alt] cont = returnSmpl (emptyFloats env, (cont, mkBoringStop (contResultType cont)))
1513 prepareCaseCont env alts cont = mkDupableCont env cont
1517 mkDupableCont :: SimplEnv -> SimplCont
1518 -> SimplM (FloatsWith (SimplCont, SimplCont))
1520 mkDupableCont env cont
1521 | contIsDupable cont
1522 = returnSmpl (emptyFloats env, (cont, mkBoringStop (contResultType cont)))
1524 mkDupableCont env (CoerceIt ty cont)
1525 = mkDupableCont env cont `thenSmpl` \ (floats, (dup_cont, nondup_cont)) ->
1526 returnSmpl (floats, (CoerceIt ty dup_cont, nondup_cont))
1528 mkDupableCont env (InlinePlease cont)
1529 = mkDupableCont env cont `thenSmpl` \ (floats, (dup_cont, nondup_cont)) ->
1530 returnSmpl (floats, (InlinePlease dup_cont, nondup_cont))
1532 mkDupableCont env cont@(ArgOf _ arg_ty _ _)
1533 = returnSmpl (emptyFloats env, (mkBoringStop arg_ty, cont))
1534 -- Do *not* duplicate an ArgOf continuation
1535 -- Because ArgOf continuations are opaque, we gain nothing by
1536 -- propagating them into the expressions, and we do lose a lot.
1537 -- Here's an example:
1538 -- && (case x of { T -> F; F -> T }) E
1539 -- Now, && is strict so we end up simplifying the case with
1540 -- an ArgOf continuation. If we let-bind it, we get
1542 -- let $j = \v -> && v E
1543 -- in simplExpr (case x of { T -> F; F -> T })
1544 -- (ArgOf (\r -> $j r)
1545 -- And after simplifying more we get
1547 -- let $j = \v -> && v E
1548 -- in case of { T -> $j F; F -> $j T }
1549 -- Which is a Very Bad Thing
1551 -- The desire not to duplicate is the entire reason that
1552 -- mkDupableCont returns a pair of continuations.
1554 -- The original plan had:
1555 -- e.g. (...strict-fn...) [...hole...]
1557 -- let $j = \a -> ...strict-fn...
1558 -- in $j [...hole...]
1560 mkDupableCont env (ApplyTo _ arg se cont)
1561 = -- e.g. [...hole...] (...arg...)
1563 -- let a = ...arg...
1564 -- in [...hole...] a
1565 simplExpr (setInScope se env) arg `thenSmpl` \ arg' ->
1567 mkDupableCont env cont `thenSmpl` \ (floats, (dup_cont, nondup_cont)) ->
1568 addFloats env floats $ \ env ->
1570 if exprIsDupable arg' then
1571 returnSmpl (emptyFloats env, (ApplyTo OkToDup arg' (zapSubstEnv se) dup_cont, nondup_cont))
1573 newId FSLIT("a") (exprType arg') `thenSmpl` \ arg_id ->
1575 tick (CaseOfCase arg_id) `thenSmpl_`
1576 -- Want to tick here so that we go round again,
1577 -- and maybe copy or inline the code.
1578 -- Not strictly CaseOfCase, but never mind
1580 returnSmpl (unitFloat env arg_id arg',
1581 (ApplyTo OkToDup (Var arg_id) (zapSubstEnv se) dup_cont,
1583 -- But what if the arg should be case-bound?
1584 -- This has been this way for a long time, so I'll leave it,
1585 -- but I can't convince myself that it's right.
1588 mkDupableCont env (Select _ case_bndr alts se cont)
1589 = -- e.g. (case [...hole...] of { pi -> ei })
1591 -- let ji = \xij -> ei
1592 -- in case [...hole...] of { pi -> ji xij }
1593 tick (CaseOfCase case_bndr) `thenSmpl_`
1595 alt_env = setInScope se env
1597 prepareCaseCont alt_env alts cont `thenSmpl` \ (floats1, (dup_cont, nondup_cont)) ->
1598 addFloats alt_env floats1 $ \ alt_env ->
1600 simplBinder alt_env case_bndr `thenSmpl` \ (alt_env, case_bndr') ->
1601 -- NB: simplBinder does not zap deadness occ-info, so
1602 -- a dead case_bndr' will still advertise its deadness
1603 -- This is really important because in
1604 -- case e of b { (# a,b #) -> ... }
1605 -- b is always dead, and indeed we are not allowed to bind b to (# a,b #),
1606 -- which might happen if e was an explicit unboxed pair and b wasn't marked dead.
1607 -- In the new alts we build, we have the new case binder, so it must retain
1610 mkDupableAlts alt_env case_bndr' alts dup_cont `thenSmpl` \ (floats2, alts') ->
1611 addFloats alt_env floats2 $ \ alt_env ->
1612 returnSmpl (emptyFloats alt_env,
1613 (Select OkToDup case_bndr' alts' (zapSubstEnv se)
1614 (mkBoringStop (contResultType dup_cont)),
1617 mkDupableAlts :: SimplEnv -> OutId -> [InAlt] -> SimplCont
1618 -> SimplM (FloatsWith [InAlt])
1619 -- Absorbs the continuation into the new alternatives
1621 mkDupableAlts env case_bndr' alts dupable_cont
1624 go env [] = returnSmpl (emptyFloats env, [])
1626 = mkDupableAlt env case_bndr' dupable_cont alt `thenSmpl` \ (floats1, alt') ->
1627 addFloats env floats1 $ \ env ->
1628 go env alts `thenSmpl` \ (floats2, alts') ->
1629 returnSmpl (floats2, alt' : alts')
1631 mkDupableAlt env case_bndr' cont alt@(con, bndrs, rhs)
1632 = simplBinders env bndrs `thenSmpl` \ (env, bndrs') ->
1633 simplExprC env rhs cont `thenSmpl` \ rhs' ->
1635 if exprIsDupable rhs' then
1636 returnSmpl (emptyFloats env, (con, bndrs', rhs'))
1637 -- It is worth checking for a small RHS because otherwise we
1638 -- get extra let bindings that may cause an extra iteration of the simplifier to
1639 -- inline back in place. Quite often the rhs is just a variable or constructor.
1640 -- The Ord instance of Maybe in PrelMaybe.lhs, for example, took several extra
1641 -- iterations because the version with the let bindings looked big, and so wasn't
1642 -- inlined, but after the join points had been inlined it looked smaller, and so
1645 -- NB: we have to check the size of rhs', not rhs.
1646 -- Duplicating a small InAlt might invalidate occurrence information
1647 -- However, if it *is* dupable, we return the *un* simplified alternative,
1648 -- because otherwise we'd need to pair it up with an empty subst-env....
1649 -- but we only have one env shared between all the alts.
1650 -- (Remember we must zap the subst-env before re-simplifying something).
1651 -- Rather than do this we simply agree to re-simplify the original (small) thing later.
1655 rhs_ty' = exprType rhs'
1656 used_bndrs' = filter (not . isDeadBinder) (case_bndr' : bndrs')
1657 -- The deadness info on the new binders is unscathed
1659 -- If we try to lift a primitive-typed something out
1660 -- for let-binding-purposes, we will *caseify* it (!),
1661 -- with potentially-disastrous strictness results. So
1662 -- instead we turn it into a function: \v -> e
1663 -- where v::State# RealWorld#. The value passed to this function
1664 -- is realworld#, which generates (almost) no code.
1666 -- There's a slight infelicity here: we pass the overall
1667 -- case_bndr to all the join points if it's used in *any* RHS,
1668 -- because we don't know its usage in each RHS separately
1670 -- We used to say "&& isUnLiftedType rhs_ty'" here, but now
1671 -- we make the join point into a function whenever used_bndrs'
1672 -- is empty. This makes the join-point more CPR friendly.
1673 -- Consider: let j = if .. then I# 3 else I# 4
1674 -- in case .. of { A -> j; B -> j; C -> ... }
1676 -- Now CPR doesn't w/w j because it's a thunk, so
1677 -- that means that the enclosing function can't w/w either,
1678 -- which is a lose. Here's the example that happened in practice:
1679 -- kgmod :: Int -> Int -> Int
1680 -- kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
1684 -- I have seen a case alternative like this:
1685 -- True -> \v -> ...
1686 -- It's a bit silly to add the realWorld dummy arg in this case, making
1689 -- (the \v alone is enough to make CPR happy) but I think it's rare
1691 ( if null used_bndrs'
1692 then newId FSLIT("w") realWorldStatePrimTy `thenSmpl` \ rw_id ->
1693 returnSmpl ([rw_id], [Var realWorldPrimId])
1695 returnSmpl (used_bndrs', map varToCoreExpr used_bndrs')
1696 ) `thenSmpl` \ (final_bndrs', final_args) ->
1698 -- See comment about "$j" name above
1699 newId (encodeFS FSLIT("$j")) (mkPiTypes final_bndrs' rhs_ty') `thenSmpl` \ join_bndr ->
1700 -- Notice the funky mkPiTypes. If the contructor has existentials
1701 -- it's possible that the join point will be abstracted over
1702 -- type varaibles as well as term variables.
1703 -- Example: Suppose we have
1704 -- data T = forall t. C [t]
1706 -- case (case e of ...) of
1707 -- C t xs::[t] -> rhs
1708 -- We get the join point
1709 -- let j :: forall t. [t] -> ...
1710 -- j = /\t \xs::[t] -> rhs
1712 -- case (case e of ...) of
1713 -- C t xs::[t] -> j t xs
1715 -- We make the lambdas into one-shot-lambdas. The
1716 -- join point is sure to be applied at most once, and doing so
1717 -- prevents the body of the join point being floated out by
1718 -- the full laziness pass
1719 really_final_bndrs = map one_shot final_bndrs'
1720 one_shot v | isId v = setOneShotLambda v
1722 join_rhs = mkLams really_final_bndrs rhs'
1723 join_call = mkApps (Var join_bndr) final_args
1725 returnSmpl (unitFloat env join_bndr join_rhs, (con, bndrs', join_call))