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"
13 import Type hiding ( substTy, extendTvSubst )
16 import MkId ( rUNTIME_ERROR_ID )
17 import FamInstEnv ( FamInstEnv )
22 import FamInstEnv ( topNormaliseType )
23 import DataCon ( dataConRepStrictness, dataConUnivTyVars )
25 import NewDemand ( isStrictDmd, splitStrictSig )
26 import PprCore ( pprParendExpr, pprCoreExpr )
27 import CoreUnfold ( mkUnfolding, callSiteInline, CallCtxt(..) )
29 import CoreArity ( exprArity )
30 import Rules ( lookupRule, getRules )
31 import BasicTypes ( isMarkedStrict )
32 import CostCentre ( currentCCS )
33 import TysPrim ( realWorldStatePrimTy )
34 import PrelInfo ( realWorldPrimId )
35 import BasicTypes ( TopLevelFlag(..), isTopLevel,
36 RecFlag(..), isNonRuleLoopBreaker )
37 import Maybes ( orElse )
38 import Data.List ( mapAccumL )
44 The guts of the simplifier is in this module, but the driver loop for
45 the simplifier is in SimplCore.lhs.
48 -----------------------------------------
49 *** IMPORTANT NOTE ***
50 -----------------------------------------
51 The simplifier used to guarantee that the output had no shadowing, but
52 it does not do so any more. (Actually, it never did!) The reason is
53 documented with simplifyArgs.
56 -----------------------------------------
57 *** IMPORTANT NOTE ***
58 -----------------------------------------
59 Many parts of the simplifier return a bunch of "floats" as well as an
60 expression. This is wrapped as a datatype SimplUtils.FloatsWith.
62 All "floats" are let-binds, not case-binds, but some non-rec lets may
63 be unlifted (with RHS ok-for-speculation).
67 -----------------------------------------
68 ORGANISATION OF FUNCTIONS
69 -----------------------------------------
71 - simplify all top-level binders
72 - for NonRec, call simplRecOrTopPair
73 - for Rec, call simplRecBind
76 ------------------------------
77 simplExpr (applied lambda) ==> simplNonRecBind
78 simplExpr (Let (NonRec ...) ..) ==> simplNonRecBind
79 simplExpr (Let (Rec ...) ..) ==> simplify binders; simplRecBind
81 ------------------------------
82 simplRecBind [binders already simplfied]
83 - use simplRecOrTopPair on each pair in turn
85 simplRecOrTopPair [binder already simplified]
86 Used for: recursive bindings (top level and nested)
87 top-level non-recursive bindings
89 - check for PreInlineUnconditionally
93 Used for: non-top-level non-recursive bindings
94 beta reductions (which amount to the same thing)
95 Because it can deal with strict arts, it takes a
96 "thing-inside" and returns an expression
98 - check for PreInlineUnconditionally
99 - simplify binder, including its IdInfo
108 simplNonRecX: [given a *simplified* RHS, but an *unsimplified* binder]
109 Used for: binding case-binder and constr args in a known-constructor case
110 - check for PreInLineUnconditionally
114 ------------------------------
115 simplLazyBind: [binder already simplified, RHS not]
116 Used for: recursive bindings (top level and nested)
117 top-level non-recursive bindings
118 non-top-level, but *lazy* non-recursive bindings
119 [must not be strict or unboxed]
120 Returns floats + an augmented environment, not an expression
121 - substituteIdInfo and add result to in-scope
122 [so that rules are available in rec rhs]
125 - float if exposes constructor or PAP
129 completeNonRecX: [binder and rhs both simplified]
130 - if the the thing needs case binding (unlifted and not ok-for-spec)
136 completeBind: [given a simplified RHS]
137 [used for both rec and non-rec bindings, top level and not]
138 - try PostInlineUnconditionally
139 - add unfolding [this is the only place we add an unfolding]
144 Right hand sides and arguments
145 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
146 In many ways we want to treat
147 (a) the right hand side of a let(rec), and
148 (b) a function argument
149 in the same way. But not always! In particular, we would
150 like to leave these arguments exactly as they are, so they
151 will match a RULE more easily.
156 It's harder to make the rule match if we ANF-ise the constructor,
157 or eta-expand the PAP:
159 f (let { a = g x; b = h x } in (a,b))
162 On the other hand if we see the let-defns
167 then we *do* want to ANF-ise and eta-expand, so that p and q
168 can be safely inlined.
170 Even floating lets out is a bit dubious. For let RHS's we float lets
171 out if that exposes a value, so that the value can be inlined more vigorously.
174 r = let x = e in (x,x)
176 Here, if we float the let out we'll expose a nice constructor. We did experiments
177 that showed this to be a generally good thing. But it was a bad thing to float
178 lets out unconditionally, because that meant they got allocated more often.
180 For function arguments, there's less reason to expose a constructor (it won't
181 get inlined). Just possibly it might make a rule match, but I'm pretty skeptical.
182 So for the moment we don't float lets out of function arguments either.
187 For eta expansion, we want to catch things like
189 case e of (a,b) -> \x -> case a of (p,q) -> \y -> r
191 If the \x was on the RHS of a let, we'd eta expand to bring the two
192 lambdas together. And in general that's a good thing to do. Perhaps
193 we should eta expand wherever we find a (value) lambda? Then the eta
194 expansion at a let RHS can concentrate solely on the PAP case.
197 %************************************************************************
199 \subsection{Bindings}
201 %************************************************************************
204 simplTopBinds :: SimplEnv -> [InBind] -> SimplM [OutBind]
206 simplTopBinds env0 binds0
207 = do { -- Put all the top-level binders into scope at the start
208 -- so that if a transformation rule has unexpectedly brought
209 -- anything into scope, then we don't get a complaint about that.
210 -- It's rather as if the top-level binders were imported.
211 ; env1 <- simplRecBndrs env0 (bindersOfBinds binds0)
212 ; dflags <- getDOptsSmpl
213 ; let dump_flag = dopt Opt_D_dump_inlinings dflags ||
214 dopt Opt_D_dump_rule_firings dflags
215 ; env2 <- simpl_binds dump_flag env1 binds0
216 ; freeTick SimplifierDone
217 ; return (getFloats env2) }
219 -- We need to track the zapped top-level binders, because
220 -- they should have their fragile IdInfo zapped (notably occurrence info)
221 -- That's why we run down binds and bndrs' simultaneously.
223 -- The dump-flag emits a trace for each top-level binding, which
224 -- helps to locate the tracing for inlining and rule firing
225 simpl_binds :: Bool -> SimplEnv -> [InBind] -> SimplM SimplEnv
226 simpl_binds _ env [] = return env
227 simpl_binds dump env (bind:binds) = do { env' <- trace_bind dump bind $
229 ; simpl_binds dump env' binds }
231 trace_bind True bind = pprTrace "SimplBind" (ppr (bindersOf bind))
232 trace_bind False _ = \x -> x
234 simpl_bind env (Rec pairs) = simplRecBind env TopLevel pairs
235 simpl_bind env (NonRec b r) = simplRecOrTopPair env' TopLevel b b' r
237 (env', b') = addBndrRules env b (lookupRecBndr env b)
241 %************************************************************************
243 \subsection{Lazy bindings}
245 %************************************************************************
247 simplRecBind is used for
248 * recursive bindings only
251 simplRecBind :: SimplEnv -> TopLevelFlag
254 simplRecBind env0 top_lvl pairs0
255 = do { let (env_with_info, triples) = mapAccumL add_rules env0 pairs0
256 ; env1 <- go (zapFloats env_with_info) triples
257 ; return (env0 `addRecFloats` env1) }
258 -- addFloats adds the floats from env1,
259 -- _and_ updates env0 with the in-scope set from env1
261 add_rules :: SimplEnv -> (InBndr,InExpr) -> (SimplEnv, (InBndr, OutBndr, InExpr))
262 -- Add the (substituted) rules to the binder
263 add_rules env (bndr, rhs) = (env', (bndr, bndr', rhs))
265 (env', bndr') = addBndrRules env bndr (lookupRecBndr env bndr)
267 go env [] = return env
269 go env ((old_bndr, new_bndr, rhs) : pairs)
270 = do { env' <- simplRecOrTopPair env top_lvl old_bndr new_bndr rhs
274 simplOrTopPair is used for
275 * recursive bindings (whether top level or not)
276 * top-level non-recursive bindings
278 It assumes the binder has already been simplified, but not its IdInfo.
281 simplRecOrTopPair :: SimplEnv
283 -> InId -> OutBndr -> InExpr -- Binder and rhs
284 -> SimplM SimplEnv -- Returns an env that includes the binding
286 simplRecOrTopPair env top_lvl old_bndr new_bndr rhs
287 | preInlineUnconditionally env top_lvl old_bndr rhs -- Check for unconditional inline
288 = do { tick (PreInlineUnconditionally old_bndr)
289 ; return (extendIdSubst env old_bndr (mkContEx env rhs)) }
292 = simplLazyBind env top_lvl Recursive old_bndr new_bndr rhs env
293 -- May not actually be recursive, but it doesn't matter
297 simplLazyBind is used for
298 * [simplRecOrTopPair] recursive bindings (whether top level or not)
299 * [simplRecOrTopPair] top-level non-recursive bindings
300 * [simplNonRecE] non-top-level *lazy* non-recursive bindings
303 1. It assumes that the binder is *already* simplified,
304 and is in scope, and its IdInfo too, except unfolding
306 2. It assumes that the binder type is lifted.
308 3. It does not check for pre-inline-unconditionallly;
309 that should have been done already.
312 simplLazyBind :: SimplEnv
313 -> TopLevelFlag -> RecFlag
314 -> InId -> OutId -- Binder, both pre-and post simpl
315 -- The OutId has IdInfo, except arity, unfolding
316 -> InExpr -> SimplEnv -- The RHS and its environment
319 simplLazyBind env top_lvl is_rec bndr bndr1 rhs rhs_se
320 = do { let rhs_env = rhs_se `setInScope` env
321 (tvs, body) = case collectTyBinders rhs of
322 (tvs, body) | not_lam body -> (tvs,body)
323 | otherwise -> ([], rhs)
324 not_lam (Lam _ _) = False
326 -- Do not do the "abstract tyyvar" thing if there's
327 -- a lambda inside, becuase it defeats eta-reduction
328 -- f = /\a. \x. g a x
331 ; (body_env, tvs') <- simplBinders rhs_env tvs
332 -- See Note [Floating and type abstraction] in SimplUtils
335 ; (body_env1, body1) <- simplExprF body_env body mkBoringStop
337 -- ANF-ise a constructor or PAP rhs
338 ; (body_env2, body2) <- prepareRhs body_env1 body1
341 <- if not (doFloatFromRhs top_lvl is_rec False body2 body_env2)
342 then -- No floating, just wrap up!
343 do { rhs' <- mkLam env tvs' (wrapFloats body_env2 body2)
344 ; return (env, rhs') }
346 else if null tvs then -- Simple floating
347 do { tick LetFloatFromLet
348 ; return (addFloats env body_env2, body2) }
350 else -- Do type-abstraction first
351 do { tick LetFloatFromLet
352 ; (poly_binds, body3) <- abstractFloats tvs' body_env2 body2
353 ; rhs' <- mkLam env tvs' body3
354 ; let env' = foldl (addPolyBind top_lvl) env poly_binds
355 ; return (env', rhs') }
357 ; completeBind env' top_lvl bndr bndr1 rhs' }
360 A specialised variant of simplNonRec used when the RHS is already simplified,
361 notably in knownCon. It uses case-binding where necessary.
364 simplNonRecX :: SimplEnv
365 -> InId -- Old binder
366 -> OutExpr -- Simplified RHS
369 simplNonRecX env bndr new_rhs
370 | isDeadBinder bndr -- Not uncommon; e.g. case (a,b) of b { (p,q) -> p }
371 = return env -- Here b is dead, and we avoid creating
372 | otherwise -- the binding b = (a,b)
373 = do { (env', bndr') <- simplBinder env bndr
374 ; completeNonRecX env' (isStrictId bndr) bndr bndr' new_rhs }
376 completeNonRecX :: SimplEnv
378 -> InId -- Old binder
379 -> OutId -- New binder
380 -> OutExpr -- Simplified RHS
383 completeNonRecX env is_strict old_bndr new_bndr new_rhs
384 = do { (env1, rhs1) <- prepareRhs (zapFloats env) new_rhs
386 if doFloatFromRhs NotTopLevel NonRecursive is_strict rhs1 env1
387 then do { tick LetFloatFromLet
388 ; return (addFloats env env1, rhs1) } -- Add the floats to the main env
389 else return (env, wrapFloats env1 rhs1) -- Wrap the floats around the RHS
390 ; completeBind env2 NotTopLevel old_bndr new_bndr rhs2 }
393 {- No, no, no! Do not try preInlineUnconditionally in completeNonRecX
394 Doing so risks exponential behaviour, because new_rhs has been simplified once already
395 In the cases described by the folowing commment, postInlineUnconditionally will
396 catch many of the relevant cases.
397 -- This happens; for example, the case_bndr during case of
398 -- known constructor: case (a,b) of x { (p,q) -> ... }
399 -- Here x isn't mentioned in the RHS, so we don't want to
400 -- create the (dead) let-binding let x = (a,b) in ...
402 -- Similarly, single occurrences can be inlined vigourously
403 -- e.g. case (f x, g y) of (a,b) -> ....
404 -- If a,b occur once we can avoid constructing the let binding for them.
406 Furthermore in the case-binding case preInlineUnconditionally risks extra thunks
407 -- Consider case I# (quotInt# x y) of
408 -- I# v -> let w = J# v in ...
409 -- If we gaily inline (quotInt# x y) for v, we end up building an
411 -- let w = J# (quotInt# x y) in ...
412 -- because quotInt# can fail.
414 | preInlineUnconditionally env NotTopLevel bndr new_rhs
415 = thing_inside (extendIdSubst env bndr (DoneEx new_rhs))
418 ----------------------------------
419 prepareRhs takes a putative RHS, checks whether it's a PAP or
420 constructor application and, if so, converts it to ANF, so that the
421 resulting thing can be inlined more easily. Thus
428 We also want to deal well cases like this
429 v = (f e1 `cast` co) e2
430 Here we want to make e1,e2 trivial and get
431 x1 = e1; x2 = e2; v = (f x1 `cast` co) v2
432 That's what the 'go' loop in prepareRhs does
435 prepareRhs :: SimplEnv -> OutExpr -> SimplM (SimplEnv, OutExpr)
436 -- Adds new floats to the env iff that allows us to return a good RHS
437 prepareRhs env (Cast rhs co) -- Note [Float coercions]
438 | (ty1, _ty2) <- coercionKind co -- Do *not* do this if rhs has an unlifted type
439 , not (isUnLiftedType ty1) -- see Note [Float coercions (unlifted)]
440 = do { (env', rhs') <- makeTrivial env rhs
441 ; return (env', Cast rhs' co) }
444 = do { (_is_val, env1, rhs1) <- go 0 env0 rhs0
445 ; return (env1, rhs1) }
447 go n_val_args env (Cast rhs co)
448 = do { (is_val, env', rhs') <- go n_val_args env rhs
449 ; return (is_val, env', Cast rhs' co) }
450 go n_val_args env (App fun (Type ty))
451 = do { (is_val, env', rhs') <- go n_val_args env fun
452 ; return (is_val, env', App rhs' (Type ty)) }
453 go n_val_args env (App fun arg)
454 = do { (is_val, env', fun') <- go (n_val_args+1) env fun
456 True -> do { (env'', arg') <- makeTrivial env' arg
457 ; return (True, env'', App fun' arg') }
458 False -> return (False, env, App fun arg) }
459 go n_val_args env (Var fun)
460 = return (is_val, env, Var fun)
462 is_val = n_val_args > 0 -- There is at least one arg
463 -- ...and the fun a constructor or PAP
464 && (isConLikeId fun || n_val_args < idArity fun)
466 = return (False, env, other)
470 Note [Float coercions]
471 ~~~~~~~~~~~~~~~~~~~~~~
472 When we find the binding
474 we'd like to transform it to
476 x = x `cast` co -- A trivial binding
477 There's a chance that e will be a constructor application or function, or something
478 like that, so moving the coerion to the usage site may well cancel the coersions
479 and lead to further optimisation. Example:
482 data instance T Int = T Int
484 foo :: Int -> Int -> Int
489 go n = case x of { T m -> go (n-m) }
490 -- This case should optimise
492 Note [Float coercions (unlifted)]
493 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
494 BUT don't do [Float coercions] if 'e' has an unlifted type.
497 foo :: Int = (error (# Int,Int #) "urk")
498 `cast` CoUnsafe (# Int,Int #) Int
500 If do the makeTrivial thing to the error call, we'll get
501 foo = case error (# Int,Int #) "urk" of v -> v `cast` ...
502 But 'v' isn't in scope!
504 These strange casts can happen as a result of case-of-case
505 bar = case (case x of { T -> (# 2,3 #); F -> error "urk" }) of
510 makeTrivial :: SimplEnv -> OutExpr -> SimplM (SimplEnv, OutExpr)
511 -- Binds the expression to a variable, if it's not trivial, returning the variable
515 | otherwise -- See Note [Take care] below
516 = do { var <- newId (fsLit "a") (exprType expr)
517 ; env' <- completeNonRecX env False var var expr
518 -- pprTrace "makeTrivial" (vcat [ppr var <+> ppr (exprArity (substExpr env' (Var var)))
520 -- , ppr (substExpr env' (Var var))
521 -- , ppr (idArity (fromJust (lookupInScope (seInScope env') var))) ]) $
522 ; return (env', substExpr env' (Var var)) }
523 -- The substitution is needed becase we're constructing a new binding
525 -- And if rhs is of form (rhs1 |> co), then we might get
528 -- and now a's RHS is trivial and can be substituted out, and that
529 -- is what completeNonRecX will do
533 %************************************************************************
535 \subsection{Completing a lazy binding}
537 %************************************************************************
540 * deals only with Ids, not TyVars
541 * takes an already-simplified binder and RHS
542 * is used for both recursive and non-recursive bindings
543 * is used for both top-level and non-top-level bindings
545 It does the following:
546 - tries discarding a dead binding
547 - tries PostInlineUnconditionally
548 - add unfolding [this is the only place we add an unfolding]
551 It does *not* attempt to do let-to-case. Why? Because it is used for
552 - top-level bindings (when let-to-case is impossible)
553 - many situations where the "rhs" is known to be a WHNF
554 (so let-to-case is inappropriate).
556 Nor does it do the atomic-argument thing
559 completeBind :: SimplEnv
560 -> TopLevelFlag -- Flag stuck into unfolding
561 -> InId -- Old binder
562 -> OutId -> OutExpr -- New binder and RHS
564 -- completeBind may choose to do its work
565 -- * by extending the substitution (e.g. let x = y in ...)
566 -- * or by adding to the floats in the envt
568 completeBind env top_lvl old_bndr new_bndr new_rhs
569 | postInlineUnconditionally env top_lvl new_bndr occ_info new_rhs unfolding
570 -- Inline and discard the binding
571 = do { tick (PostInlineUnconditionally old_bndr)
572 ; -- pprTrace "postInlineUnconditionally" (ppr old_bndr <+> ppr new_bndr <+> ppr new_rhs) $
573 return (extendIdSubst env old_bndr (DoneEx new_rhs)) }
574 -- Use the substitution to make quite, quite sure that the
575 -- substitution will happen, since we are going to discard the binding
578 = return (addNonRecWithUnf env new_bndr new_rhs unfolding wkr)
580 unfolding | omit_unfolding = NoUnfolding
581 | otherwise = mkUnfolding (isTopLevel top_lvl) new_rhs
582 old_info = idInfo old_bndr
583 occ_info = occInfo old_info
584 wkr = substWorker env (workerInfo old_info)
585 omit_unfolding = isNonRuleLoopBreaker occ_info
586 -- or not (activeInline env old_bndr)
587 -- Do *not* trim the unfolding in SimplGently, else
588 -- the specialiser can't see it!
591 addPolyBind :: TopLevelFlag -> SimplEnv -> OutBind -> SimplEnv
592 -- Add a new binding to the environment, complete with its unfolding
593 -- but *do not* do postInlineUnconditionally, because we have already
594 -- processed some of the scope of the binding
595 -- We still want the unfolding though. Consider
597 -- x = /\a. let y = ... in Just y
599 -- Then we float the y-binding out (via abstractFloats and addPolyBind)
600 -- but 'x' may well then be inlined in 'body' in which case we'd like the
601 -- opportunity to inline 'y' too.
603 addPolyBind top_lvl env (NonRec poly_id rhs)
604 = addNonRecWithUnf env poly_id rhs unfolding NoWorker
606 unfolding | not (activeInline env poly_id) = NoUnfolding
607 | otherwise = mkUnfolding (isTopLevel top_lvl) rhs
608 -- addNonRecWithInfo adds the new binding in the
609 -- proper way (ie complete with unfolding etc),
610 -- and extends the in-scope set
612 addPolyBind _ env bind@(Rec _) = extendFloats env bind
613 -- Hack: letrecs are more awkward, so we extend "by steam"
614 -- without adding unfoldings etc. At worst this leads to
615 -- more simplifier iterations
618 addNonRecWithUnf :: SimplEnv
619 -> OutId -> OutExpr -- New binder and RHS
620 -> Unfolding -> WorkerInfo -- and unfolding
622 -- Add suitable IdInfo to the Id, add the binding to the floats, and extend the in-scope set
623 addNonRecWithUnf env new_bndr rhs unfolding wkr
624 = ASSERT( isId new_bndr )
625 WARN( new_arity < old_arity || new_arity < dmd_arity,
626 (ppr final_id <+> ppr old_arity <+> ppr new_arity <+> ppr dmd_arity) $$ ppr rhs )
627 final_id `seq` -- This seq forces the Id, and hence its IdInfo,
628 -- and hence any inner substitutions
629 addNonRec env final_id rhs
630 -- The addNonRec adds it to the in-scope set too
632 dmd_arity = length $ fst $ splitStrictSig $ idNewStrictness new_bndr
633 old_arity = idArity new_bndr
636 new_arity = exprArity rhs
637 new_bndr_info = idInfo new_bndr `setArityInfo` new_arity
640 -- Add the unfolding *only* for non-loop-breakers
641 -- Making loop breakers not have an unfolding at all
642 -- means that we can avoid tests in exprIsConApp, for example.
643 -- This is important: if exprIsConApp says 'yes' for a recursive
644 -- thing, then we can get into an infinite loop
647 -- If the unfolding is a value, the demand info may
648 -- go pear-shaped, so we nuke it. Example:
650 -- case x of (p,q) -> h p q x
651 -- Here x is certainly demanded. But after we've nuked
652 -- the case, we'll get just
653 -- let x = (a,b) in h a b x
654 -- and now x is not demanded (I'm assuming h is lazy)
655 -- This really happens. Similarly
656 -- let f = \x -> e in ...f..f...
657 -- After inlining f at some of its call sites the original binding may
658 -- (for example) be no longer strictly demanded.
659 -- The solution here is a bit ad hoc...
660 info_w_unf = new_bndr_info `setUnfoldingInfo` unfolding
663 final_info | isEvaldUnfolding unfolding = zapDemandInfo info_w_unf `orElse` info_w_unf
664 | otherwise = info_w_unf
666 final_id = new_bndr `setIdInfo` final_info
671 %************************************************************************
673 \subsection[Simplify-simplExpr]{The main function: simplExpr}
675 %************************************************************************
677 The reason for this OutExprStuff stuff is that we want to float *after*
678 simplifying a RHS, not before. If we do so naively we get quadratic
679 behaviour as things float out.
681 To see why it's important to do it after, consider this (real) example:
695 a -- Can't inline a this round, cos it appears twice
699 Each of the ==> steps is a round of simplification. We'd save a
700 whole round if we float first. This can cascade. Consider
705 let f = let d1 = ..d.. in \y -> e
709 in \x -> ...(\y ->e)...
711 Only in this second round can the \y be applied, and it
712 might do the same again.
716 simplExpr :: SimplEnv -> CoreExpr -> SimplM CoreExpr
717 simplExpr env expr = simplExprC env expr mkBoringStop
719 simplExprC :: SimplEnv -> CoreExpr -> SimplCont -> SimplM CoreExpr
720 -- Simplify an expression, given a continuation
721 simplExprC env expr cont
722 = -- pprTrace "simplExprC" (ppr expr $$ ppr cont {- $$ ppr (seIdSubst env) -} $$ ppr (seFloats env) ) $
723 do { (env', expr') <- simplExprF (zapFloats env) expr cont
724 ; -- pprTrace "simplExprC ret" (ppr expr $$ ppr expr') $
725 -- pprTrace "simplExprC ret3" (ppr (seInScope env')) $
726 -- pprTrace "simplExprC ret4" (ppr (seFloats env')) $
727 return (wrapFloats env' expr') }
729 --------------------------------------------------
730 simplExprF :: SimplEnv -> InExpr -> SimplCont
731 -> SimplM (SimplEnv, OutExpr)
733 simplExprF env e cont
734 = -- pprTrace "simplExprF" (ppr e $$ ppr cont $$ ppr (seTvSubst env) $$ ppr (seIdSubst env) {- $$ ppr (seFloats env) -} ) $
735 simplExprF' env e cont
737 simplExprF' :: SimplEnv -> InExpr -> SimplCont
738 -> SimplM (SimplEnv, OutExpr)
739 simplExprF' env (Var v) cont = simplVar env v cont
740 simplExprF' env (Lit lit) cont = rebuild env (Lit lit) cont
741 simplExprF' env (Note n expr) cont = simplNote env n expr cont
742 simplExprF' env (Cast body co) cont = simplCast env body co cont
743 simplExprF' env (App fun arg) cont = simplExprF env fun $
744 ApplyTo NoDup arg env cont
746 simplExprF' env expr@(Lam _ _) cont
747 = simplLam env (map zap bndrs) body cont
748 -- The main issue here is under-saturated lambdas
749 -- (\x1. \x2. e) arg1
750 -- Here x1 might have "occurs-once" occ-info, because occ-info
751 -- is computed assuming that a group of lambdas is applied
752 -- all at once. If there are too few args, we must zap the
755 n_args = countArgs cont
756 n_params = length bndrs
757 (bndrs, body) = collectBinders expr
758 zap | n_args >= n_params = \b -> b
759 | otherwise = \b -> if isTyVar b then b
761 -- NB: we count all the args incl type args
762 -- so we must count all the binders (incl type lambdas)
764 simplExprF' env (Type ty) cont
765 = ASSERT( contIsRhsOrArg cont )
766 do { ty' <- simplType env ty
767 ; rebuild env (Type ty') cont }
769 simplExprF' env (Case scrut bndr _ alts) cont
770 | not (switchIsOn (getSwitchChecker env) NoCaseOfCase)
771 = -- Simplify the scrutinee with a Select continuation
772 simplExprF env scrut (Select NoDup bndr alts env cont)
775 = -- If case-of-case is off, simply simplify the case expression
776 -- in a vanilla Stop context, and rebuild the result around it
777 do { case_expr' <- simplExprC env scrut case_cont
778 ; rebuild env case_expr' cont }
780 case_cont = Select NoDup bndr alts env mkBoringStop
782 simplExprF' env (Let (Rec pairs) body) cont
783 = do { env' <- simplRecBndrs env (map fst pairs)
784 -- NB: bndrs' don't have unfoldings or rules
785 -- We add them as we go down
787 ; env'' <- simplRecBind env' NotTopLevel pairs
788 ; simplExprF env'' body cont }
790 simplExprF' env (Let (NonRec bndr rhs) body) cont
791 = simplNonRecE env bndr (rhs, env) ([], body) cont
793 ---------------------------------
794 simplType :: SimplEnv -> InType -> SimplM OutType
795 -- Kept monadic just so we can do the seqType
797 = -- pprTrace "simplType" (ppr ty $$ ppr (seTvSubst env)) $
798 seqType new_ty `seq` return new_ty
800 new_ty = substTy env ty
804 %************************************************************************
806 \subsection{The main rebuilder}
808 %************************************************************************
811 rebuild :: SimplEnv -> OutExpr -> SimplCont -> SimplM (SimplEnv, OutExpr)
812 -- At this point the substitution in the SimplEnv should be irrelevant
813 -- only the in-scope set and floats should matter
814 rebuild env expr cont0
815 = -- pprTrace "rebuild" (ppr expr $$ ppr cont0 $$ ppr (seFloats env)) $
817 Stop {} -> return (env, expr)
818 CoerceIt co cont -> rebuild env (mkCoerce co expr) cont
819 Select _ bndr alts se cont -> rebuildCase (se `setFloats` env) expr bndr alts cont
820 StrictArg fun _ info cont -> rebuildCall env (fun `App` expr) info cont
821 StrictBind b bs body se cont -> do { env' <- simplNonRecX (se `setFloats` env) b expr
822 ; simplLam env' bs body cont }
823 ApplyTo _ arg se cont -> do { arg' <- simplExpr (se `setInScope` env) arg
824 ; rebuild env (App expr arg') cont }
828 %************************************************************************
832 %************************************************************************
835 simplCast :: SimplEnv -> InExpr -> Coercion -> SimplCont
836 -> SimplM (SimplEnv, OutExpr)
837 simplCast env body co0 cont0
838 = do { co1 <- simplType env co0
839 ; simplExprF env body (addCoerce co1 cont0) }
841 addCoerce co cont = add_coerce co (coercionKind co) cont
843 add_coerce _co (s1, k1) cont -- co :: ty~ty
844 | s1 `coreEqType` k1 = cont -- is a no-op
846 add_coerce co1 (s1, _k2) (CoerceIt co2 cont)
847 | (_l1, t1) <- coercionKind co2
848 -- e |> (g1 :: S1~L) |> (g2 :: L~T1)
851 -- e |> (g1 . g2 :: T1~T2) otherwise
853 -- For example, in the initial form of a worker
854 -- we may find (coerce T (coerce S (\x.e))) y
855 -- and we'd like it to simplify to e[y/x] in one round
857 , s1 `coreEqType` t1 = cont -- The coerces cancel out
858 | otherwise = CoerceIt (mkTransCoercion co1 co2) cont
860 add_coerce co (s1s2, _t1t2) (ApplyTo dup (Type arg_ty) arg_se cont)
861 -- (f |> g) ty ---> (f ty) |> (g @ ty)
862 -- This implements the PushT rule from the paper
863 | Just (tyvar,_) <- splitForAllTy_maybe s1s2
864 , not (isCoVar tyvar)
865 = ApplyTo dup (Type ty') (zapSubstEnv env) (addCoerce (mkInstCoercion co ty') cont)
867 ty' = substTy (arg_se `setInScope` env) arg_ty
869 -- ToDo: the PushC rule is not implemented at all
871 add_coerce co (s1s2, _t1t2) (ApplyTo dup arg arg_se cont)
872 | not (isTypeArg arg) -- This implements the Push rule from the paper
873 , isFunTy s1s2 -- t1t2 must be a function type, becuase it's applied
874 -- (e |> (g :: s1s2 ~ t1->t2)) f
876 -- (e (f |> (arg g :: t1~s1))
877 -- |> (res g :: s2->t2)
879 -- t1t2 must be a function type, t1->t2, because it's applied
880 -- to something but s1s2 might conceivably not be
882 -- When we build the ApplyTo we can't mix the out-types
883 -- with the InExpr in the argument, so we simply substitute
884 -- to make it all consistent. It's a bit messy.
885 -- But it isn't a common case.
887 -- Example of use: Trac #995
888 = ApplyTo dup new_arg (zapSubstEnv env) (addCoerce co2 cont)
890 -- we split coercion t1->t2 ~ s1->s2 into t1 ~ s1 and
891 -- t2 ~ s2 with left and right on the curried form:
892 -- (->) t1 t2 ~ (->) s1 s2
893 [co1, co2] = decomposeCo 2 co
894 new_arg = mkCoerce (mkSymCoercion co1) arg'
895 arg' = substExpr (arg_se `setInScope` env) arg
897 add_coerce co _ cont = CoerceIt co cont
901 %************************************************************************
905 %************************************************************************
908 simplLam :: SimplEnv -> [InId] -> InExpr -> SimplCont
909 -> SimplM (SimplEnv, OutExpr)
911 simplLam env [] body cont = simplExprF env body cont
914 simplLam env (bndr:bndrs) body (ApplyTo _ arg arg_se cont)
915 = do { tick (BetaReduction bndr)
916 ; simplNonRecE env bndr (arg, arg_se) (bndrs, body) cont }
918 -- Not enough args, so there are real lambdas left to put in the result
919 simplLam env bndrs body cont
920 = do { (env', bndrs') <- simplLamBndrs env bndrs
921 ; body' <- simplExpr env' body
922 ; new_lam <- mkLam env' bndrs' body'
923 ; rebuild env' new_lam cont }
926 simplNonRecE :: SimplEnv
927 -> InId -- The binder
928 -> (InExpr, SimplEnv) -- Rhs of binding (or arg of lambda)
929 -> ([InBndr], InExpr) -- Body of the let/lambda
932 -> SimplM (SimplEnv, OutExpr)
934 -- simplNonRecE is used for
935 -- * non-top-level non-recursive lets in expressions
938 -- It deals with strict bindings, via the StrictBind continuation,
939 -- which may abort the whole process
941 -- The "body" of the binding comes as a pair of ([InId],InExpr)
942 -- representing a lambda; so we recurse back to simplLam
943 -- Why? Because of the binder-occ-info-zapping done before
944 -- the call to simplLam in simplExprF (Lam ...)
946 -- First deal with type applications and type lets
947 -- (/\a. e) (Type ty) and (let a = Type ty in e)
948 simplNonRecE env bndr (Type ty_arg, rhs_se) (bndrs, body) cont
949 = ASSERT( isTyVar bndr )
950 do { ty_arg' <- simplType (rhs_se `setInScope` env) ty_arg
951 ; simplLam (extendTvSubst env bndr ty_arg') bndrs body cont }
953 simplNonRecE env bndr (rhs, rhs_se) (bndrs, body) cont
954 | preInlineUnconditionally env NotTopLevel bndr rhs
955 = do { tick (PreInlineUnconditionally bndr)
956 ; simplLam (extendIdSubst env bndr (mkContEx rhs_se rhs)) bndrs body cont }
959 = do { simplExprF (rhs_se `setFloats` env) rhs
960 (StrictBind bndr bndrs body env cont) }
963 = ASSERT( not (isTyVar bndr) )
964 do { (env1, bndr1) <- simplNonRecBndr env bndr
965 ; let (env2, bndr2) = addBndrRules env1 bndr bndr1
966 ; env3 <- simplLazyBind env2 NotTopLevel NonRecursive bndr bndr2 rhs rhs_se
967 ; simplLam env3 bndrs body cont }
971 %************************************************************************
975 %************************************************************************
978 -- Hack alert: we only distinguish subsumed cost centre stacks for the
979 -- purposes of inlining. All other CCCSs are mapped to currentCCS.
980 simplNote :: SimplEnv -> Note -> CoreExpr -> SimplCont
981 -> SimplM (SimplEnv, OutExpr)
982 simplNote env (SCC cc) e cont
983 = do { e' <- simplExpr (setEnclosingCC env currentCCS) e
984 ; rebuild env (mkSCC cc e') cont }
986 -- See notes with SimplMonad.inlineMode
987 simplNote env InlineMe e cont
988 | Just (inside, outside) <- splitInlineCont cont -- Boring boring continuation; see notes above
989 = do { -- Don't inline inside an INLINE expression
990 e' <- simplExprC (setMode inlineMode env) e inside
991 ; rebuild env (mkInlineMe e') outside }
993 | otherwise -- Dissolve the InlineMe note if there's
994 -- an interesting context of any kind to combine with
995 -- (even a type application -- anything except Stop)
996 = simplExprF env e cont
998 simplNote env (CoreNote s) e cont = do
999 e' <- simplExpr env e
1000 rebuild env (Note (CoreNote s) e') cont
1004 %************************************************************************
1006 \subsection{Dealing with calls}
1008 %************************************************************************
1011 simplVar :: SimplEnv -> Id -> SimplCont -> SimplM (SimplEnv, OutExpr)
1012 simplVar env var cont
1013 = case substId env var of
1014 DoneEx e -> simplExprF (zapSubstEnv env) e cont
1015 ContEx tvs ids e -> simplExprF (setSubstEnv env tvs ids) e cont
1016 DoneId var1 -> completeCall (zapSubstEnv env) var1 cont
1017 -- Note [zapSubstEnv]
1018 -- The template is already simplified, so don't re-substitute.
1019 -- This is VITAL. Consider
1021 -- let y = \z -> ...x... in
1023 -- We'll clone the inner \x, adding x->x' in the id_subst
1024 -- Then when we inline y, we must *not* replace x by x' in
1025 -- the inlined copy!!
1027 ---------------------------------------------------------
1028 -- Dealing with a call site
1030 completeCall :: SimplEnv -> Id -> SimplCont -> SimplM (SimplEnv, OutExpr)
1031 completeCall env var cont
1032 = do { dflags <- getDOptsSmpl
1033 ; let (args,call_cont) = contArgs cont
1034 -- The args are OutExprs, obtained by *lazily* substituting
1035 -- in the args found in cont. These args are only examined
1036 -- to limited depth (unless a rule fires). But we must do
1037 -- the substitution; rule matching on un-simplified args would
1040 ------------- First try rules ----------------
1041 -- Do this before trying inlining. Some functions have
1042 -- rules *and* are strict; in this case, we don't want to
1043 -- inline the wrapper of the non-specialised thing; better
1044 -- to call the specialised thing instead.
1046 -- We used to use the black-listing mechanism to ensure that inlining of
1047 -- the wrapper didn't occur for things that have specialisations till a
1048 -- later phase, so but now we just try RULES first
1050 -- Note [Rules for recursive functions]
1051 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1052 -- You might think that we shouldn't apply rules for a loop breaker:
1053 -- doing so might give rise to an infinite loop, because a RULE is
1054 -- rather like an extra equation for the function:
1055 -- RULE: f (g x) y = x+y
1058 -- But it's too drastic to disable rules for loop breakers.
1059 -- Even the foldr/build rule would be disabled, because foldr
1060 -- is recursive, and hence a loop breaker:
1061 -- foldr k z (build g) = g k z
1062 -- So it's up to the programmer: rules can cause divergence
1063 ; rule_base <- getSimplRules
1064 ; let in_scope = getInScope env
1065 rules = getRules rule_base var
1066 maybe_rule = case activeRule dflags env of
1067 Nothing -> Nothing -- No rules apply
1068 Just act_fn -> lookupRule act_fn in_scope
1070 ; case maybe_rule of {
1071 Just (rule, rule_rhs) -> do
1072 tick (RuleFired (ru_name rule))
1073 (if dopt Opt_D_dump_rule_firings dflags then
1074 pprTrace "Rule fired" (vcat [
1075 text "Rule:" <+> ftext (ru_name rule),
1076 text "Before:" <+> ppr var <+> sep (map pprParendExpr args),
1077 text "After: " <+> pprCoreExpr rule_rhs,
1078 text "Cont: " <+> ppr call_cont])
1081 simplExprF env rule_rhs (dropArgs (ruleArity rule) cont)
1082 -- The ruleArity says how many args the rule consumed
1084 ; Nothing -> do -- No rules
1086 ------------- Next try inlining ----------------
1087 { let arg_infos = [interestingArg arg | arg <- args, isValArg arg]
1088 n_val_args = length arg_infos
1089 interesting_cont = interestingCallContext call_cont
1090 active_inline = activeInline env var
1091 maybe_inline = callSiteInline dflags active_inline var
1092 (null args) arg_infos interesting_cont
1093 ; case maybe_inline of {
1094 Just unfolding -- There is an inlining!
1095 -> do { tick (UnfoldingDone var)
1096 ; (if dopt Opt_D_dump_inlinings dflags then
1097 pprTrace ("Inlining done: " ++ showSDoc (ppr var)) (vcat [
1098 text "Before:" <+> ppr var <+> sep (map pprParendExpr args),
1099 text "Inlined fn: " <+> nest 2 (ppr unfolding),
1100 text "Cont: " <+> ppr call_cont])
1103 simplExprF env unfolding cont }
1105 ; Nothing -> -- No inlining!
1107 ------------- No inlining! ----------------
1108 -- Next, look for rules or specialisations that match
1110 rebuildCall env (Var var)
1111 (mkArgInfo var n_val_args call_cont) cont
1114 rebuildCall :: SimplEnv
1115 -> OutExpr -- Function
1118 -> SimplM (SimplEnv, OutExpr)
1119 rebuildCall env fun (ArgInfo { ai_strs = [] }) cont
1120 -- When we run out of strictness args, it means
1121 -- that the call is definitely bottom; see SimplUtils.mkArgInfo
1122 -- Then we want to discard the entire strict continuation. E.g.
1123 -- * case (error "hello") of { ... }
1124 -- * (error "Hello") arg
1125 -- * f (error "Hello") where f is strict
1127 -- Then, especially in the first of these cases, we'd like to discard
1128 -- the continuation, leaving just the bottoming expression. But the
1129 -- type might not be right, so we may have to add a coerce.
1130 | not (contIsTrivial cont) -- Only do this if there is a non-trivial
1131 = return (env, mk_coerce fun) -- contination to discard, else we do it
1132 where -- again and again!
1133 fun_ty = exprType fun
1134 cont_ty = contResultType env fun_ty cont
1135 co = mkUnsafeCoercion fun_ty cont_ty
1136 mk_coerce expr | cont_ty `coreEqType` fun_ty = expr
1137 | otherwise = mkCoerce co expr
1139 rebuildCall env fun info (ApplyTo _ (Type arg_ty) se cont)
1140 = do { ty' <- simplType (se `setInScope` env) arg_ty
1141 ; rebuildCall env (fun `App` Type ty') info cont }
1144 (ArgInfo { ai_rules = has_rules, ai_strs = str:strs, ai_discs = disc:discs })
1145 (ApplyTo _ arg arg_se cont)
1146 | str -- Strict argument
1147 = -- pprTrace "Strict Arg" (ppr arg $$ ppr (seIdSubst env) $$ ppr (seInScope env)) $
1148 simplExprF (arg_se `setFloats` env) arg
1149 (StrictArg fun cci arg_info' cont)
1152 | otherwise -- Lazy argument
1153 -- DO NOT float anything outside, hence simplExprC
1154 -- There is no benefit (unlike in a let-binding), and we'd
1155 -- have to be very careful about bogus strictness through
1156 -- floating a demanded let.
1157 = do { arg' <- simplExprC (arg_se `setInScope` env) arg
1159 ; rebuildCall env (fun `App` arg') arg_info' cont }
1161 arg_info' = ArgInfo { ai_rules = has_rules, ai_strs = strs, ai_discs = discs }
1162 cci | has_rules || disc > 0 = ArgCtxt has_rules disc -- Be keener here
1163 | otherwise = BoringCtxt -- Nothing interesting
1165 rebuildCall env fun _ cont
1166 = rebuild env fun cont
1171 This part of the simplifier may break the no-shadowing invariant
1173 f (...(\a -> e)...) (case y of (a,b) -> e')
1174 where f is strict in its second arg
1175 If we simplify the innermost one first we get (...(\a -> e)...)
1176 Simplifying the second arg makes us float the case out, so we end up with
1177 case y of (a,b) -> f (...(\a -> e)...) e'
1178 So the output does not have the no-shadowing invariant. However, there is
1179 no danger of getting name-capture, because when the first arg was simplified
1180 we used an in-scope set that at least mentioned all the variables free in its
1181 static environment, and that is enough.
1183 We can't just do innermost first, or we'd end up with a dual problem:
1184 case x of (a,b) -> f e (...(\a -> e')...)
1186 I spent hours trying to recover the no-shadowing invariant, but I just could
1187 not think of an elegant way to do it. The simplifier is already knee-deep in
1188 continuations. We have to keep the right in-scope set around; AND we have
1189 to get the effect that finding (error "foo") in a strict arg position will
1190 discard the entire application and replace it with (error "foo"). Getting
1191 all this at once is TOO HARD!
1193 %************************************************************************
1195 Rebuilding a cse expression
1197 %************************************************************************
1199 Note [Case elimination]
1200 ~~~~~~~~~~~~~~~~~~~~~~~
1201 The case-elimination transformation discards redundant case expressions.
1202 Start with a simple situation:
1204 case x# of ===> e[x#/y#]
1207 (when x#, y# are of primitive type, of course). We can't (in general)
1208 do this for algebraic cases, because we might turn bottom into
1211 The code in SimplUtils.prepareAlts has the effect of generalise this
1212 idea to look for a case where we're scrutinising a variable, and we
1213 know that only the default case can match. For example:
1217 DEFAULT -> ...(case x of
1221 Here the inner case is first trimmed to have only one alternative, the
1222 DEFAULT, after which it's an instance of the previous case. This
1223 really only shows up in eliminating error-checking code.
1225 We also make sure that we deal with this very common case:
1230 Here we are using the case as a strict let; if x is used only once
1231 then we want to inline it. We have to be careful that this doesn't
1232 make the program terminate when it would have diverged before, so we
1234 - e is already evaluated (it may so if e is a variable)
1235 - x is used strictly, or
1237 Lastly, the code in SimplUtils.mkCase combines identical RHSs. So
1239 case e of ===> case e of DEFAULT -> r
1243 Now again the case may be elminated by the CaseElim transformation.
1246 Further notes about case elimination
1247 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1248 Consider: test :: Integer -> IO ()
1251 Turns out that this compiles to:
1254 eta1 :: State# RealWorld ->
1255 case PrelNum.< eta PrelNum.zeroInteger of wild { __DEFAULT ->
1257 (PrelNum.jtos eta ($w[] @ Char))
1259 of wild1 { (# new_s, a4 #) -> PrelIO.lvl23 new_s }}
1261 Notice the strange '<' which has no effect at all. This is a funny one.
1262 It started like this:
1264 f x y = if x < 0 then jtos x
1265 else if y==0 then "" else jtos x
1267 At a particular call site we have (f v 1). So we inline to get
1269 if v < 0 then jtos x
1270 else if 1==0 then "" else jtos x
1272 Now simplify the 1==0 conditional:
1274 if v<0 then jtos v else jtos v
1276 Now common-up the two branches of the case:
1278 case (v<0) of DEFAULT -> jtos v
1280 Why don't we drop the case? Because it's strict in v. It's technically
1281 wrong to drop even unnecessary evaluations, and in practice they
1282 may be a result of 'seq' so we *definitely* don't want to drop those.
1283 I don't really know how to improve this situation.
1286 ---------------------------------------------------------
1287 -- Eliminate the case if possible
1289 rebuildCase :: SimplEnv
1290 -> OutExpr -- Scrutinee
1291 -> InId -- Case binder
1292 -> [InAlt] -- Alternatives (inceasing order)
1294 -> SimplM (SimplEnv, OutExpr)
1296 --------------------------------------------------
1297 -- 1. Eliminate the case if there's a known constructor
1298 --------------------------------------------------
1300 rebuildCase env scrut case_bndr alts cont
1301 | Just (con,args) <- exprIsConApp_maybe scrut
1302 -- Works when the scrutinee is a variable with a known unfolding
1303 -- as well as when it's an explicit constructor application
1304 = knownCon env scrut (DataAlt con) args case_bndr alts cont
1306 | Lit lit <- scrut -- No need for same treatment as constructors
1307 -- because literals are inlined more vigorously
1308 = knownCon env scrut (LitAlt lit) [] case_bndr alts cont
1311 --------------------------------------------------
1312 -- 2. Eliminate the case if scrutinee is evaluated
1313 --------------------------------------------------
1315 rebuildCase env scrut case_bndr [(_, bndrs, rhs)] cont
1316 -- See if we can get rid of the case altogether
1317 -- See Note [Case eliminiation]
1318 -- mkCase made sure that if all the alternatives are equal,
1319 -- then there is now only one (DEFAULT) rhs
1320 | all isDeadBinder bndrs -- bndrs are [InId]
1322 -- Check that the scrutinee can be let-bound instead of case-bound
1323 , exprOkForSpeculation scrut
1324 -- OK not to evaluate it
1325 -- This includes things like (==# a# b#)::Bool
1326 -- so that we simplify
1327 -- case ==# a# b# of { True -> x; False -> x }
1330 -- This particular example shows up in default methods for
1331 -- comparision operations (e.g. in (>=) for Int.Int32)
1332 || exprIsHNF scrut -- It's already evaluated
1333 || var_demanded_later scrut -- It'll be demanded later
1335 -- || not opt_SimplPedanticBottoms) -- Or we don't care!
1336 -- We used to allow improving termination by discarding cases, unless -fpedantic-bottoms was on,
1337 -- but that breaks badly for the dataToTag# primop, which relies on a case to evaluate
1338 -- its argument: case x of { y -> dataToTag# y }
1339 -- Here we must *not* discard the case, because dataToTag# just fetches the tag from
1340 -- the info pointer. So we'll be pedantic all the time, and see if that gives any
1342 -- Also we don't want to discard 'seq's
1343 = do { tick (CaseElim case_bndr)
1344 ; env' <- simplNonRecX env case_bndr scrut
1345 ; simplExprF env' rhs cont }
1347 -- The case binder is going to be evaluated later,
1348 -- and the scrutinee is a simple variable
1349 var_demanded_later (Var v) = isStrictDmd (idNewDemandInfo case_bndr)
1350 && not (isTickBoxOp v)
1351 -- ugly hack; covering this case is what
1352 -- exprOkForSpeculation was intended for.
1353 var_demanded_later _ = False
1356 --------------------------------------------------
1357 -- 3. Catch-all case
1358 --------------------------------------------------
1360 rebuildCase env scrut case_bndr alts cont
1361 = do { -- Prepare the continuation;
1362 -- The new subst_env is in place
1363 (env', dup_cont, nodup_cont) <- prepareCaseCont env alts cont
1365 -- Simplify the alternatives
1366 ; (scrut', case_bndr', alts') <- simplAlts env' scrut case_bndr alts dup_cont
1368 -- Check for empty alternatives
1369 ; if null alts' then
1370 -- This isn't strictly an error, although it is unusual.
1371 -- It's possible that the simplifer might "see" that
1372 -- an inner case has no accessible alternatives before
1373 -- it "sees" that the entire branch of an outer case is
1374 -- inaccessible. So we simply put an error case here instead.
1375 pprTrace "mkCase: null alts" (ppr case_bndr <+> ppr scrut) $
1376 let res_ty' = contResultType env' (substTy env' (coreAltsType alts)) dup_cont
1377 lit = mkStringLit "Impossible alternative"
1378 in return (env', mkApps (Var rUNTIME_ERROR_ID) [Type res_ty', lit])
1381 { case_expr <- mkCase scrut' case_bndr' alts'
1383 -- Notice that rebuild gets the in-scope set from env, not alt_env
1384 -- The case binder *not* scope over the whole returned case-expression
1385 ; rebuild env' case_expr nodup_cont } }
1388 simplCaseBinder checks whether the scrutinee is a variable, v. If so,
1389 try to eliminate uses of v in the RHSs in favour of case_bndr; that
1390 way, there's a chance that v will now only be used once, and hence
1393 Historical note: we use to do the "case binder swap" in the Simplifier
1394 so there were additional complications if the scrutinee was a variable.
1395 Now the binder-swap stuff is done in the occurrence analyer; see
1396 OccurAnal Note [Binder swap].
1400 If the case binder is not dead, then neither are the pattern bound
1402 case <any> of x { (a,b) ->
1403 case x of { (p,q) -> p } }
1404 Here (a,b) both look dead, but come alive after the inner case is eliminated.
1405 The point is that we bring into the envt a binding
1407 after the outer case, and that makes (a,b) alive. At least we do unless
1408 the case binder is guaranteed dead.
1410 Note [Improving seq]
1413 type family F :: * -> *
1414 type instance F Int = Int
1416 ... case e of x { DEFAULT -> rhs } ...
1418 where x::F Int. Then we'd like to rewrite (F Int) to Int, getting
1420 case e `cast` co of x'::Int
1421 I# x# -> let x = x' `cast` sym co
1424 so that 'rhs' can take advantage of the form of x'. Notice that Note
1425 [Case of cast] may then apply to the result.
1427 This showed up in Roman's experiments. Example:
1428 foo :: F Int -> Int -> Int
1429 foo t n = t `seq` bar n
1432 bar n = bar (n - case t of TI i -> i)
1433 Here we'd like to avoid repeated evaluating t inside the loop, by
1434 taking advantage of the `seq`.
1436 At one point I did transformation in LiberateCase, but it's more robust here.
1437 (Otherwise, there's a danger that we'll simply drop the 'seq' altogether, before
1438 LiberateCase gets to see it.)
1444 improveSeq :: (FamInstEnv, FamInstEnv) -> SimplEnv
1445 -> OutExpr -> InId -> OutId -> [InAlt]
1446 -> SimplM (SimplEnv, OutExpr, OutId)
1447 -- Note [Improving seq]
1448 improveSeq fam_envs env scrut case_bndr case_bndr1 [(DEFAULT,_,_)]
1449 | Just (co, ty2) <- topNormaliseType fam_envs (idType case_bndr1)
1450 = do { case_bndr2 <- newId (fsLit "nt") ty2
1451 ; let rhs = DoneEx (Var case_bndr2 `Cast` mkSymCoercion co)
1452 env2 = extendIdSubst env case_bndr rhs
1453 ; return (env2, scrut `Cast` co, case_bndr2) }
1455 improveSeq _ env scrut _ case_bndr1 _
1456 = return (env, scrut, case_bndr1)
1459 improve_case_bndr env scrut case_bndr
1460 -- See Note [no-case-of-case]
1461 -- | switchIsOn (getSwitchChecker env) NoCaseOfCase
1462 -- = (env, case_bndr)
1464 | otherwise -- Failed try; see Note [Suppressing the case binder-swap]
1465 -- not (isEvaldUnfolding (idUnfolding v))
1467 Var v -> (modifyInScope env1 v case_bndr', case_bndr')
1468 -- Note about using modifyInScope for v here
1469 -- We could extend the substitution instead, but it would be
1470 -- a hack because then the substitution wouldn't be idempotent
1471 -- any more (v is an OutId). And this does just as well.
1473 Cast (Var v) co -> (addBinderUnfolding env1 v rhs, case_bndr')
1475 rhs = Cast (Var case_bndr') (mkSymCoercion co)
1477 _ -> (env, case_bndr)
1479 case_bndr' = zapIdOccInfo case_bndr
1480 env1 = modifyInScope env case_bndr case_bndr'
1485 simplAlts does two things:
1487 1. Eliminate alternatives that cannot match, including the
1488 DEFAULT alternative.
1490 2. If the DEFAULT alternative can match only one possible constructor,
1491 then make that constructor explicit.
1493 case e of x { DEFAULT -> rhs }
1495 case e of x { (a,b) -> rhs }
1496 where the type is a single constructor type. This gives better code
1497 when rhs also scrutinises x or e.
1499 Here "cannot match" includes knowledge from GADTs
1501 It's a good idea do do this stuff before simplifying the alternatives, to
1502 avoid simplifying alternatives we know can't happen, and to come up with
1503 the list of constructors that are handled, to put into the IdInfo of the
1504 case binder, for use when simplifying the alternatives.
1506 Eliminating the default alternative in (1) isn't so obvious, but it can
1509 data Colour = Red | Green | Blue
1518 DEFAULT -> [ case y of ... ]
1520 If we inline h into f, the default case of the inlined h can't happen.
1521 If we don't notice this, we may end up filtering out *all* the cases
1522 of the inner case y, which give us nowhere to go!
1526 simplAlts :: SimplEnv
1528 -> InId -- Case binder
1529 -> [InAlt] -- Non-empty
1531 -> SimplM (OutExpr, OutId, [OutAlt]) -- Includes the continuation
1532 -- Like simplExpr, this just returns the simplified alternatives;
1533 -- it not return an environment
1535 simplAlts env scrut case_bndr alts cont'
1536 = -- pprTrace "simplAlts" (ppr alts $$ ppr (seIdSubst env)) $
1537 do { let env0 = zapFloats env
1539 ; (env1, case_bndr1) <- simplBinder env0 case_bndr
1541 ; fam_envs <- getFamEnvs
1542 ; (alt_env', scrut', case_bndr') <- improveSeq fam_envs env1 scrut
1543 case_bndr case_bndr1 alts
1545 ; (imposs_deflt_cons, in_alts) <- prepareAlts alt_env' scrut' case_bndr' alts
1547 ; alts' <- mapM (simplAlt alt_env' imposs_deflt_cons case_bndr' cont') in_alts
1548 ; return (scrut', case_bndr', alts') }
1550 ------------------------------------
1551 simplAlt :: SimplEnv
1552 -> [AltCon] -- These constructors can't be present when
1553 -- matching the DEFAULT alternative
1554 -> OutId -- The case binder
1559 simplAlt env imposs_deflt_cons case_bndr' cont' (DEFAULT, bndrs, rhs)
1560 = ASSERT( null bndrs )
1561 do { let env' = addBinderOtherCon env case_bndr' imposs_deflt_cons
1562 -- Record the constructors that the case-binder *can't* be.
1563 ; rhs' <- simplExprC env' rhs cont'
1564 ; return (DEFAULT, [], rhs') }
1566 simplAlt env _ case_bndr' cont' (LitAlt lit, bndrs, rhs)
1567 = ASSERT( null bndrs )
1568 do { let env' = addBinderUnfolding env case_bndr' (Lit lit)
1569 ; rhs' <- simplExprC env' rhs cont'
1570 ; return (LitAlt lit, [], rhs') }
1572 simplAlt env _ case_bndr' cont' (DataAlt con, vs, rhs)
1573 = do { -- Deal with the pattern-bound variables
1574 -- Mark the ones that are in ! positions in the
1575 -- data constructor as certainly-evaluated.
1576 -- NB: simplLamBinders preserves this eval info
1577 let vs_with_evals = add_evals (dataConRepStrictness con)
1578 ; (env', vs') <- simplLamBndrs env vs_with_evals
1580 -- Bind the case-binder to (con args)
1581 ; let inst_tys' = tyConAppArgs (idType case_bndr')
1582 con_args = map Type inst_tys' ++ varsToCoreExprs vs'
1583 env'' = addBinderUnfolding env' case_bndr'
1584 (mkConApp con con_args)
1586 ; rhs' <- simplExprC env'' rhs cont'
1587 ; return (DataAlt con, vs', rhs') }
1589 -- add_evals records the evaluated-ness of the bound variables of
1590 -- a case pattern. This is *important*. Consider
1591 -- data T = T !Int !Int
1593 -- case x of { T a b -> T (a+1) b }
1595 -- We really must record that b is already evaluated so that we don't
1596 -- go and re-evaluate it when constructing the result.
1597 -- See Note [Data-con worker strictness] in MkId.lhs
1602 go (v:vs') strs | isTyVar v = v : go vs' strs
1603 go (v:vs') (str:strs)
1604 | isMarkedStrict str = evald_v : go vs' strs
1605 | otherwise = zapped_v : go vs' strs
1607 zapped_v = zap_occ_info v
1608 evald_v = zapped_v `setIdUnfolding` evaldUnfolding
1609 go _ _ = pprPanic "cat_evals" (ppr con $$ ppr vs $$ ppr the_strs)
1611 -- See Note [zapOccInfo]
1612 -- zap_occ_info: if the case binder is alive, then we add the unfolding
1614 -- to the envt; so vs are now very much alive
1615 -- Note [Aug06] I can't see why this actually matters, but it's neater
1616 -- case e of t { (a,b) -> ...(case t of (p,q) -> p)... }
1617 -- ==> case e of t { (a,b) -> ...(a)... }
1618 -- Look, Ma, a is alive now.
1619 zap_occ_info = zapCasePatIdOcc case_bndr'
1621 addBinderUnfolding :: SimplEnv -> Id -> CoreExpr -> SimplEnv
1622 addBinderUnfolding env bndr rhs
1623 = modifyInScope env (bndr `setIdUnfolding` mkUnfolding False rhs)
1625 addBinderOtherCon :: SimplEnv -> Id -> [AltCon] -> SimplEnv
1626 addBinderOtherCon env bndr cons
1627 = modifyInScope env (bndr `setIdUnfolding` mkOtherCon cons)
1629 zapCasePatIdOcc :: Id -> Id -> Id
1630 -- Consider case e of b { (a,b) -> ... }
1631 -- Then if we bind b to (a,b) in "...", and b is not dead,
1632 -- then we must zap the deadness info on a,b
1633 zapCasePatIdOcc case_bndr
1634 | isDeadBinder case_bndr = \ pat_id -> pat_id
1635 | otherwise = \ pat_id -> zapIdOccInfo pat_id
1639 %************************************************************************
1641 \subsection{Known constructor}
1643 %************************************************************************
1645 We are a bit careful with occurrence info. Here's an example
1647 (\x* -> case x of (a*, b) -> f a) (h v, e)
1649 where the * means "occurs once". This effectively becomes
1650 case (h v, e) of (a*, b) -> f a)
1652 let a* = h v; b = e in f a
1656 All this should happen in one sweep.
1659 knownCon :: SimplEnv -> OutExpr -> AltCon
1660 -> [OutExpr] -- Args *including* the universal args
1661 -> InId -> [InAlt] -> SimplCont
1662 -> SimplM (SimplEnv, OutExpr)
1664 knownCon env scrut con args bndr alts cont
1665 = do { tick (KnownBranch bndr)
1666 ; knownAlt env scrut args bndr (findAlt con alts) cont }
1668 knownAlt :: SimplEnv -> OutExpr -> [OutExpr]
1669 -> InId -> (AltCon, [CoreBndr], InExpr) -> SimplCont
1670 -> SimplM (SimplEnv, OutExpr)
1671 knownAlt env scrut _ bndr (DEFAULT, bs, rhs) cont
1673 do { env' <- simplNonRecX env bndr scrut
1674 -- This might give rise to a binding with non-atomic args
1675 -- like x = Node (f x) (g x)
1676 -- but simplNonRecX will atomic-ify it
1677 ; simplExprF env' rhs cont }
1679 knownAlt env scrut _ bndr (LitAlt _, bs, rhs) cont
1681 do { env' <- simplNonRecX env bndr scrut
1682 ; simplExprF env' rhs cont }
1684 knownAlt env scrut the_args bndr (DataAlt dc, bs, rhs) cont
1685 = do { let n_drop_tys = length (dataConUnivTyVars dc)
1686 ; env' <- bind_args env bs (drop n_drop_tys the_args)
1688 -- It's useful to bind bndr to scrut, rather than to a fresh
1689 -- binding x = Con arg1 .. argn
1690 -- because very often the scrut is a variable, so we avoid
1691 -- creating, and then subsequently eliminating, a let-binding
1692 -- BUT, if scrut is a not a variable, we must be careful
1693 -- about duplicating the arg redexes; in that case, make
1694 -- a new con-app from the args
1695 bndr_rhs = case scrut of
1698 con_app = mkConApp dc (take n_drop_tys the_args ++ con_args)
1699 con_args = [substExpr env' (varToCoreExpr b) | b <- bs]
1700 -- args are aready OutExprs, but bs are InIds
1702 ; env'' <- simplNonRecX env' bndr bndr_rhs
1703 ; simplExprF env'' rhs cont }
1705 zap_occ = zapCasePatIdOcc bndr -- bndr is an InId
1708 bind_args env' [] _ = return env'
1710 bind_args env' (b:bs') (Type ty : args)
1711 = ASSERT( isTyVar b )
1712 bind_args (extendTvSubst env' b ty) bs' args
1714 bind_args env' (b:bs') (arg : args)
1716 do { let b' = zap_occ b
1717 -- Note that the binder might be "dead", because it doesn't
1718 -- occur in the RHS; and simplNonRecX may therefore discard
1719 -- it via postInlineUnconditionally.
1720 -- Nevertheless we must keep it if the case-binder is alive,
1721 -- because it may be used in the con_app. See Note [zapOccInfo]
1722 ; env'' <- simplNonRecX env' b' arg
1723 ; bind_args env'' bs' args }
1726 pprPanic "bind_args" $ ppr dc $$ ppr bs $$ ppr the_args $$
1727 text "scrut:" <+> ppr scrut
1731 %************************************************************************
1733 \subsection{Duplicating continuations}
1735 %************************************************************************
1738 prepareCaseCont :: SimplEnv
1739 -> [InAlt] -> SimplCont
1740 -> SimplM (SimplEnv, SimplCont,SimplCont)
1741 -- Return a duplicatable continuation, a non-duplicable part
1742 -- plus some extra bindings (that scope over the entire
1745 -- No need to make it duplicatable if there's only one alternative
1746 prepareCaseCont env [_] cont = return (env, cont, mkBoringStop)
1747 prepareCaseCont env _ cont = mkDupableCont env cont
1751 mkDupableCont :: SimplEnv -> SimplCont
1752 -> SimplM (SimplEnv, SimplCont, SimplCont)
1754 mkDupableCont env cont
1755 | contIsDupable cont
1756 = return (env, cont, mkBoringStop)
1758 mkDupableCont _ (Stop {}) = panic "mkDupableCont" -- Handled by previous eqn
1760 mkDupableCont env (CoerceIt ty cont)
1761 = do { (env', dup, nodup) <- mkDupableCont env cont
1762 ; return (env', CoerceIt ty dup, nodup) }
1764 mkDupableCont env cont@(StrictBind {})
1765 = return (env, mkBoringStop, cont)
1766 -- See Note [Duplicating strict continuations]
1768 mkDupableCont env cont@(StrictArg {})
1769 = return (env, mkBoringStop, cont)
1770 -- See Note [Duplicating strict continuations]
1772 mkDupableCont env (ApplyTo _ arg se cont)
1773 = -- e.g. [...hole...] (...arg...)
1775 -- let a = ...arg...
1776 -- in [...hole...] a
1777 do { (env', dup_cont, nodup_cont) <- mkDupableCont env cont
1778 ; arg' <- simplExpr (se `setInScope` env') arg
1779 ; (env'', arg'') <- makeTrivial env' arg'
1780 ; let app_cont = ApplyTo OkToDup arg'' (zapSubstEnv env'') dup_cont
1781 ; return (env'', app_cont, nodup_cont) }
1783 mkDupableCont env cont@(Select _ case_bndr [(_, bs, _rhs)] _ _)
1784 -- See Note [Single-alternative case]
1785 -- | not (exprIsDupable rhs && contIsDupable case_cont)
1786 -- | not (isDeadBinder case_bndr)
1787 | all isDeadBinder bs -- InIds
1788 && not (isUnLiftedType (idType case_bndr))
1789 -- Note [Single-alternative-unlifted]
1790 = return (env, mkBoringStop, cont)
1792 mkDupableCont env (Select _ case_bndr alts se cont)
1793 = -- e.g. (case [...hole...] of { pi -> ei })
1795 -- let ji = \xij -> ei
1796 -- in case [...hole...] of { pi -> ji xij }
1797 do { tick (CaseOfCase case_bndr)
1798 ; (env', dup_cont, nodup_cont) <- mkDupableCont env cont
1799 -- NB: call mkDupableCont here, *not* prepareCaseCont
1800 -- We must make a duplicable continuation, whereas prepareCaseCont
1801 -- doesn't when there is a single case branch
1803 ; let alt_env = se `setInScope` env'
1804 ; (alt_env', case_bndr') <- simplBinder alt_env case_bndr
1805 ; alts' <- mapM (simplAlt alt_env' [] case_bndr' dup_cont) alts
1806 -- Safe to say that there are no handled-cons for the DEFAULT case
1807 -- NB: simplBinder does not zap deadness occ-info, so
1808 -- a dead case_bndr' will still advertise its deadness
1809 -- This is really important because in
1810 -- case e of b { (# p,q #) -> ... }
1811 -- b is always dead, and indeed we are not allowed to bind b to (# p,q #),
1812 -- which might happen if e was an explicit unboxed pair and b wasn't marked dead.
1813 -- In the new alts we build, we have the new case binder, so it must retain
1815 -- NB: we don't use alt_env further; it has the substEnv for
1816 -- the alternatives, and we don't want that
1818 ; (env'', alts'') <- mkDupableAlts env' case_bndr' alts'
1819 ; return (env'', -- Note [Duplicated env]
1820 Select OkToDup case_bndr' alts'' (zapSubstEnv env'') mkBoringStop,
1824 mkDupableAlts :: SimplEnv -> OutId -> [InAlt]
1825 -> SimplM (SimplEnv, [InAlt])
1826 -- Absorbs the continuation into the new alternatives
1828 mkDupableAlts env case_bndr' the_alts
1831 go env0 [] = return (env0, [])
1833 = do { (env1, alt') <- mkDupableAlt env0 case_bndr' alt
1834 ; (env2, alts') <- go env1 alts
1835 ; return (env2, alt' : alts' ) }
1837 mkDupableAlt :: SimplEnv -> OutId -> (AltCon, [CoreBndr], CoreExpr)
1838 -> SimplM (SimplEnv, (AltCon, [CoreBndr], CoreExpr))
1839 mkDupableAlt env case_bndr' (con, bndrs', rhs')
1840 | exprIsDupable rhs' -- Note [Small alternative rhs]
1841 = return (env, (con, bndrs', rhs'))
1843 = do { let rhs_ty' = exprType rhs'
1844 used_bndrs' = filter abstract_over (case_bndr' : bndrs')
1846 | isTyVar bndr = True -- Abstract over all type variables just in case
1847 | otherwise = not (isDeadBinder bndr)
1848 -- The deadness info on the new Ids is preserved by simplBinders
1850 ; (final_bndrs', final_args) -- Note [Join point abstraction]
1851 <- if (any isId used_bndrs')
1852 then return (used_bndrs', varsToCoreExprs used_bndrs')
1853 else do { rw_id <- newId (fsLit "w") realWorldStatePrimTy
1854 ; return ([rw_id], [Var realWorldPrimId]) }
1856 ; join_bndr <- newId (fsLit "$j") (mkPiTypes final_bndrs' rhs_ty')
1857 -- Note [Funky mkPiTypes]
1859 ; let -- We make the lambdas into one-shot-lambdas. The
1860 -- join point is sure to be applied at most once, and doing so
1861 -- prevents the body of the join point being floated out by
1862 -- the full laziness pass
1863 really_final_bndrs = map one_shot final_bndrs'
1864 one_shot v | isId v = setOneShotLambda v
1866 join_rhs = mkLams really_final_bndrs rhs'
1867 join_call = mkApps (Var join_bndr) final_args
1869 ; return (addPolyBind NotTopLevel env (NonRec join_bndr join_rhs), (con, bndrs', join_call)) }
1870 -- See Note [Duplicated env]
1873 Note [Duplicated env]
1874 ~~~~~~~~~~~~~~~~~~~~~
1875 Some of the alternatives are simplified, but have not been turned into a join point
1876 So they *must* have an zapped subst-env. So we can't use completeNonRecX to
1877 bind the join point, because it might to do PostInlineUnconditionally, and
1878 we'd lose that when zapping the subst-env. We could have a per-alt subst-env,
1879 but zapping it (as we do in mkDupableCont, the Select case) is safe, and
1880 at worst delays the join-point inlining.
1882 Note [Small alterantive rhs]
1883 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1884 It is worth checking for a small RHS because otherwise we
1885 get extra let bindings that may cause an extra iteration of the simplifier to
1886 inline back in place. Quite often the rhs is just a variable or constructor.
1887 The Ord instance of Maybe in PrelMaybe.lhs, for example, took several extra
1888 iterations because the version with the let bindings looked big, and so wasn't
1889 inlined, but after the join points had been inlined it looked smaller, and so
1892 NB: we have to check the size of rhs', not rhs.
1893 Duplicating a small InAlt might invalidate occurrence information
1894 However, if it *is* dupable, we return the *un* simplified alternative,
1895 because otherwise we'd need to pair it up with an empty subst-env....
1896 but we only have one env shared between all the alts.
1897 (Remember we must zap the subst-env before re-simplifying something).
1898 Rather than do this we simply agree to re-simplify the original (small) thing later.
1900 Note [Funky mkPiTypes]
1901 ~~~~~~~~~~~~~~~~~~~~~~
1902 Notice the funky mkPiTypes. If the contructor has existentials
1903 it's possible that the join point will be abstracted over
1904 type varaibles as well as term variables.
1905 Example: Suppose we have
1906 data T = forall t. C [t]
1908 case (case e of ...) of
1910 We get the join point
1911 let j :: forall t. [t] -> ...
1912 j = /\t \xs::[t] -> rhs
1914 case (case e of ...) of
1915 C t xs::[t] -> j t xs
1917 Note [Join point abstaction]
1918 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1919 If we try to lift a primitive-typed something out
1920 for let-binding-purposes, we will *caseify* it (!),
1921 with potentially-disastrous strictness results. So
1922 instead we turn it into a function: \v -> e
1923 where v::State# RealWorld#. The value passed to this function
1924 is realworld#, which generates (almost) no code.
1926 There's a slight infelicity here: we pass the overall
1927 case_bndr to all the join points if it's used in *any* RHS,
1928 because we don't know its usage in each RHS separately
1930 We used to say "&& isUnLiftedType rhs_ty'" here, but now
1931 we make the join point into a function whenever used_bndrs'
1932 is empty. This makes the join-point more CPR friendly.
1933 Consider: let j = if .. then I# 3 else I# 4
1934 in case .. of { A -> j; B -> j; C -> ... }
1936 Now CPR doesn't w/w j because it's a thunk, so
1937 that means that the enclosing function can't w/w either,
1938 which is a lose. Here's the example that happened in practice:
1939 kgmod :: Int -> Int -> Int
1940 kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
1944 I have seen a case alternative like this:
1946 It's a bit silly to add the realWorld dummy arg in this case, making
1949 (the \v alone is enough to make CPR happy) but I think it's rare
1951 Note [Duplicating strict continuations]
1952 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1953 Do *not* duplicate StrictBind and StritArg continuations. We gain
1954 nothing by propagating them into the expressions, and we do lose a
1955 lot. Here's an example:
1956 && (case x of { T -> F; F -> T }) E
1957 Now, && is strict so we end up simplifying the case with
1958 an ArgOf continuation. If we let-bind it, we get
1960 let $j = \v -> && v E
1961 in simplExpr (case x of { T -> F; F -> T })
1963 And after simplifying more we get
1965 let $j = \v -> && v E
1966 in case x of { T -> $j F; F -> $j T }
1967 Which is a Very Bad Thing
1969 The desire not to duplicate is the entire reason that
1970 mkDupableCont returns a pair of continuations.
1972 The original plan had:
1973 e.g. (...strict-fn...) [...hole...]
1975 let $j = \a -> ...strict-fn...
1978 Note [Single-alternative cases]
1979 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1980 This case is just like the ArgOf case. Here's an example:
1984 case (case x of I# x' ->
1986 True -> I# (negate# x')
1987 False -> I# x') of y {
1989 Because the (case x) has only one alternative, we'll transform to
1991 case (case x' <# 0# of
1992 True -> I# (negate# x')
1993 False -> I# x') of y {
1995 But now we do *NOT* want to make a join point etc, giving
1997 let $j = \y -> MkT y
1999 True -> $j (I# (negate# x'))
2001 In this case the $j will inline again, but suppose there was a big
2002 strict computation enclosing the orginal call to MkT. Then, it won't
2003 "see" the MkT any more, because it's big and won't get duplicated.
2004 And, what is worse, nothing was gained by the case-of-case transform.
2006 When should use this case of mkDupableCont?
2007 However, matching on *any* single-alternative case is a *disaster*;
2008 e.g. case (case ....) of (a,b) -> (# a,b #)
2009 We must push the outer case into the inner one!
2012 * Match [(DEFAULT,_,_)], but in the common case of Int,
2013 the alternative-filling-in code turned the outer case into
2014 case (...) of y { I# _ -> MkT y }
2016 * Match on single alternative plus (not (isDeadBinder case_bndr))
2017 Rationale: pushing the case inwards won't eliminate the construction.
2018 But there's a risk of
2019 case (...) of y { (a,b) -> let z=(a,b) in ... }
2020 Now y looks dead, but it'll come alive again. Still, this
2021 seems like the best option at the moment.
2023 * Match on single alternative plus (all (isDeadBinder bndrs))
2024 Rationale: this is essentially seq.
2026 * Match when the rhs is *not* duplicable, and hence would lead to a
2027 join point. This catches the disaster-case above. We can test
2028 the *un-simplified* rhs, which is fine. It might get bigger or
2029 smaller after simplification; if it gets smaller, this case might
2030 fire next time round. NB also that we must test contIsDupable
2031 case_cont *btoo, because case_cont might be big!
2033 HOWEVER: I found that this version doesn't work well, because
2034 we can get let x = case (...) of { small } in ...case x...
2035 When x is inlined into its full context, we find that it was a bad
2036 idea to have pushed the outer case inside the (...) case.
2038 Note [Single-alternative-unlifted]
2039 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2040 Here's another single-alternative where we really want to do case-of-case:
2048 case y_s6X of tpl_s7m {
2049 M1.Mk1 ipv_s70 -> ipv_s70;
2050 M1.Mk2 ipv_s72 -> ipv_s72;
2056 case x_s74 of tpl_s7n {
2057 M1.Mk1 ipv_s77 -> ipv_s77;
2058 M1.Mk2 ipv_s79 -> ipv_s79;
2062 { __DEFAULT -> ==# [wild1_s7b wild_s7c];
2066 So the outer case is doing *nothing at all*, other than serving as a
2067 join-point. In this case we really want to do case-of-case and decide
2068 whether to use a real join point or just duplicate the continuation.
2070 Hence: check whether the case binder's type is unlifted, because then
2071 the outer case is *not* a seq.