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 FamInstEnv ( FamInstEnv )
18 import MkId ( mkImpossibleExpr, seqId )
21 import Name ( mkSystemVarName, isExternalName )
23 import FamInstEnv ( topNormaliseType )
24 import DataCon ( DataCon, dataConWorkId, dataConRepStrictness )
25 import CoreMonad ( SimplifierSwitch(..), Tick(..) )
27 import Demand ( isStrictDmd, splitStrictSig )
28 import PprCore ( pprParendExpr, pprCoreExpr )
29 import CoreUnfold ( mkUnfolding, mkCoreUnfolding, mkInlineRule,
30 exprIsConApp_maybe, callSiteInline, CallCtxt(..) )
32 import qualified CoreSubst
33 import CoreArity ( exprArity )
34 import Rules ( lookupRule, getRules )
35 import BasicTypes ( isMarkedStrict, Arity )
36 import CostCentre ( currentCCS, pushCCisNop )
37 import TysPrim ( realWorldStatePrimTy )
38 import PrelInfo ( realWorldPrimId )
39 import BasicTypes ( TopLevelFlag(..), isTopLevel, RecFlag(..) )
40 import MonadUtils ( foldlM, mapAccumLM )
41 import Maybes ( orElse )
42 import Data.List ( mapAccumL )
48 The guts of the simplifier is in this module, but the driver loop for
49 the simplifier is in SimplCore.lhs.
52 -----------------------------------------
53 *** IMPORTANT NOTE ***
54 -----------------------------------------
55 The simplifier used to guarantee that the output had no shadowing, but
56 it does not do so any more. (Actually, it never did!) The reason is
57 documented with simplifyArgs.
60 -----------------------------------------
61 *** IMPORTANT NOTE ***
62 -----------------------------------------
63 Many parts of the simplifier return a bunch of "floats" as well as an
64 expression. This is wrapped as a datatype SimplUtils.FloatsWith.
66 All "floats" are let-binds, not case-binds, but some non-rec lets may
67 be unlifted (with RHS ok-for-speculation).
71 -----------------------------------------
72 ORGANISATION OF FUNCTIONS
73 -----------------------------------------
75 - simplify all top-level binders
76 - for NonRec, call simplRecOrTopPair
77 - for Rec, call simplRecBind
80 ------------------------------
81 simplExpr (applied lambda) ==> simplNonRecBind
82 simplExpr (Let (NonRec ...) ..) ==> simplNonRecBind
83 simplExpr (Let (Rec ...) ..) ==> simplify binders; simplRecBind
85 ------------------------------
86 simplRecBind [binders already simplfied]
87 - use simplRecOrTopPair on each pair in turn
89 simplRecOrTopPair [binder already simplified]
90 Used for: recursive bindings (top level and nested)
91 top-level non-recursive bindings
93 - check for PreInlineUnconditionally
97 Used for: non-top-level non-recursive bindings
98 beta reductions (which amount to the same thing)
99 Because it can deal with strict arts, it takes a
100 "thing-inside" and returns an expression
102 - check for PreInlineUnconditionally
103 - simplify binder, including its IdInfo
112 simplNonRecX: [given a *simplified* RHS, but an *unsimplified* binder]
113 Used for: binding case-binder and constr args in a known-constructor case
114 - check for PreInLineUnconditionally
118 ------------------------------
119 simplLazyBind: [binder already simplified, RHS not]
120 Used for: recursive bindings (top level and nested)
121 top-level non-recursive bindings
122 non-top-level, but *lazy* non-recursive bindings
123 [must not be strict or unboxed]
124 Returns floats + an augmented environment, not an expression
125 - substituteIdInfo and add result to in-scope
126 [so that rules are available in rec rhs]
129 - float if exposes constructor or PAP
133 completeNonRecX: [binder and rhs both simplified]
134 - if the the thing needs case binding (unlifted and not ok-for-spec)
140 completeBind: [given a simplified RHS]
141 [used for both rec and non-rec bindings, top level and not]
142 - try PostInlineUnconditionally
143 - add unfolding [this is the only place we add an unfolding]
148 Right hand sides and arguments
149 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
150 In many ways we want to treat
151 (a) the right hand side of a let(rec), and
152 (b) a function argument
153 in the same way. But not always! In particular, we would
154 like to leave these arguments exactly as they are, so they
155 will match a RULE more easily.
160 It's harder to make the rule match if we ANF-ise the constructor,
161 or eta-expand the PAP:
163 f (let { a = g x; b = h x } in (a,b))
166 On the other hand if we see the let-defns
171 then we *do* want to ANF-ise and eta-expand, so that p and q
172 can be safely inlined.
174 Even floating lets out is a bit dubious. For let RHS's we float lets
175 out if that exposes a value, so that the value can be inlined more vigorously.
178 r = let x = e in (x,x)
180 Here, if we float the let out we'll expose a nice constructor. We did experiments
181 that showed this to be a generally good thing. But it was a bad thing to float
182 lets out unconditionally, because that meant they got allocated more often.
184 For function arguments, there's less reason to expose a constructor (it won't
185 get inlined). Just possibly it might make a rule match, but I'm pretty skeptical.
186 So for the moment we don't float lets out of function arguments either.
191 For eta expansion, we want to catch things like
193 case e of (a,b) -> \x -> case a of (p,q) -> \y -> r
195 If the \x was on the RHS of a let, we'd eta expand to bring the two
196 lambdas together. And in general that's a good thing to do. Perhaps
197 we should eta expand wherever we find a (value) lambda? Then the eta
198 expansion at a let RHS can concentrate solely on the PAP case.
201 %************************************************************************
203 \subsection{Bindings}
205 %************************************************************************
208 simplTopBinds :: SimplEnv -> [InBind] -> SimplM SimplEnv
210 simplTopBinds env0 binds0
211 = do { -- Put all the top-level binders into scope at the start
212 -- so that if a transformation rule has unexpectedly brought
213 -- anything into scope, then we don't get a complaint about that.
214 -- It's rather as if the top-level binders were imported.
215 ; env1 <- simplRecBndrs env0 (bindersOfBinds binds0)
216 ; dflags <- getDOptsSmpl
217 ; let dump_flag = dopt Opt_D_verbose_core2core dflags
218 ; env2 <- simpl_binds dump_flag env1 binds0
219 ; freeTick SimplifierDone
222 -- We need to track the zapped top-level binders, because
223 -- they should have their fragile IdInfo zapped (notably occurrence info)
224 -- That's why we run down binds and bndrs' simultaneously.
226 -- The dump-flag emits a trace for each top-level binding, which
227 -- helps to locate the tracing for inlining and rule firing
228 simpl_binds :: Bool -> SimplEnv -> [InBind] -> SimplM SimplEnv
229 simpl_binds _ env [] = return env
230 simpl_binds dump env (bind:binds) = do { env' <- trace_bind dump bind $
232 ; simpl_binds dump env' binds }
234 trace_bind True bind = pprTrace "SimplBind" (ppr (bindersOf bind))
235 trace_bind False _ = \x -> x
237 simpl_bind env (Rec pairs) = simplRecBind env TopLevel pairs
238 simpl_bind env (NonRec b r) = simplRecOrTopPair env' TopLevel b b' r
240 (env', b') = addBndrRules env b (lookupRecBndr env b)
244 %************************************************************************
246 \subsection{Lazy bindings}
248 %************************************************************************
250 simplRecBind is used for
251 * recursive bindings only
254 simplRecBind :: SimplEnv -> TopLevelFlag
257 simplRecBind env0 top_lvl pairs0
258 = do { let (env_with_info, triples) = mapAccumL add_rules env0 pairs0
259 ; env1 <- go (zapFloats env_with_info) triples
260 ; return (env0 `addRecFloats` env1) }
261 -- addFloats adds the floats from env1,
262 -- _and_ updates env0 with the in-scope set from env1
264 add_rules :: SimplEnv -> (InBndr,InExpr) -> (SimplEnv, (InBndr, OutBndr, InExpr))
265 -- Add the (substituted) rules to the binder
266 add_rules env (bndr, rhs) = (env', (bndr, bndr', rhs))
268 (env', bndr') = addBndrRules env bndr (lookupRecBndr env bndr)
270 go env [] = return env
272 go env ((old_bndr, new_bndr, rhs) : pairs)
273 = do { env' <- simplRecOrTopPair env top_lvl old_bndr new_bndr rhs
277 simplOrTopPair is used for
278 * recursive bindings (whether top level or not)
279 * top-level non-recursive bindings
281 It assumes the binder has already been simplified, but not its IdInfo.
284 simplRecOrTopPair :: SimplEnv
286 -> InId -> OutBndr -> InExpr -- Binder and rhs
287 -> SimplM SimplEnv -- Returns an env that includes the binding
289 simplRecOrTopPair env top_lvl old_bndr new_bndr rhs
290 | preInlineUnconditionally env top_lvl old_bndr rhs -- Check for unconditional inline
291 = do { tick (PreInlineUnconditionally old_bndr)
292 ; return (extendIdSubst env old_bndr (mkContEx env rhs)) }
295 = simplLazyBind env top_lvl Recursive old_bndr new_bndr rhs env
296 -- May not actually be recursive, but it doesn't matter
300 simplLazyBind is used for
301 * [simplRecOrTopPair] recursive bindings (whether top level or not)
302 * [simplRecOrTopPair] top-level non-recursive bindings
303 * [simplNonRecE] non-top-level *lazy* non-recursive bindings
306 1. It assumes that the binder is *already* simplified,
307 and is in scope, and its IdInfo too, except unfolding
309 2. It assumes that the binder type is lifted.
311 3. It does not check for pre-inline-unconditionallly;
312 that should have been done already.
315 simplLazyBind :: SimplEnv
316 -> TopLevelFlag -> RecFlag
317 -> InId -> OutId -- Binder, both pre-and post simpl
318 -- The OutId has IdInfo, except arity, unfolding
319 -> InExpr -> SimplEnv -- The RHS and its environment
322 simplLazyBind env top_lvl is_rec bndr bndr1 rhs rhs_se
323 = do { let rhs_env = rhs_se `setInScope` env
324 (tvs, body) = case collectTyBinders rhs of
325 (tvs, body) | not_lam body -> (tvs,body)
326 | otherwise -> ([], rhs)
327 not_lam (Lam _ _) = False
329 -- Do not do the "abstract tyyvar" thing if there's
330 -- a lambda inside, becuase it defeats eta-reduction
331 -- f = /\a. \x. g a x
334 ; (body_env, tvs') <- simplBinders rhs_env tvs
335 -- See Note [Floating and type abstraction] in SimplUtils
338 ; (body_env1, body1) <- simplExprF body_env body mkRhsStop
339 -- ANF-ise a constructor or PAP rhs
340 ; (body_env2, body2) <- prepareRhs body_env1 bndr1 body1
343 <- if not (doFloatFromRhs top_lvl is_rec False body2 body_env2)
344 then -- No floating, just wrap up!
345 do { rhs' <- mkLam env tvs' (wrapFloats body_env2 body2)
346 ; return (env, rhs') }
348 else if null tvs then -- Simple floating
349 do { tick LetFloatFromLet
350 ; return (addFloats env body_env2, body2) }
352 else -- Do type-abstraction first
353 do { tick LetFloatFromLet
354 ; (poly_binds, body3) <- abstractFloats tvs' body_env2 body2
355 ; rhs' <- mkLam env tvs' body3
356 ; env' <- foldlM (addPolyBind top_lvl) env poly_binds
357 ; return (env', rhs') }
359 ; completeBind env' top_lvl bndr bndr1 rhs' }
362 A specialised variant of simplNonRec used when the RHS is already simplified,
363 notably in knownCon. It uses case-binding where necessary.
366 simplNonRecX :: SimplEnv
367 -> InId -- Old binder
368 -> OutExpr -- Simplified RHS
371 simplNonRecX env bndr new_rhs
372 | isDeadBinder bndr -- Not uncommon; e.g. case (a,b) of b { (p,q) -> p }
373 = return env -- Here b is dead, and we avoid creating
374 | otherwise -- the binding b = (a,b)
375 = do { (env', bndr') <- simplBinder env bndr
376 ; completeNonRecX env' (isStrictId bndr) bndr bndr' new_rhs }
378 completeNonRecX :: SimplEnv
380 -> InId -- Old binder
381 -> OutId -- New binder
382 -> OutExpr -- Simplified RHS
385 completeNonRecX env is_strict old_bndr new_bndr new_rhs
386 = do { (env1, rhs1) <- prepareRhs (zapFloats env) new_bndr new_rhs
388 if doFloatFromRhs NotTopLevel NonRecursive is_strict rhs1 env1
389 then do { tick LetFloatFromLet
390 ; return (addFloats env env1, rhs1) } -- Add the floats to the main env
391 else return (env, wrapFloats env1 rhs1) -- Wrap the floats around the RHS
392 ; completeBind env2 NotTopLevel old_bndr new_bndr rhs2 }
395 {- No, no, no! Do not try preInlineUnconditionally in completeNonRecX
396 Doing so risks exponential behaviour, because new_rhs has been simplified once already
397 In the cases described by the folowing commment, postInlineUnconditionally will
398 catch many of the relevant cases.
399 -- This happens; for example, the case_bndr during case of
400 -- known constructor: case (a,b) of x { (p,q) -> ... }
401 -- Here x isn't mentioned in the RHS, so we don't want to
402 -- create the (dead) let-binding let x = (a,b) in ...
404 -- Similarly, single occurrences can be inlined vigourously
405 -- e.g. case (f x, g y) of (a,b) -> ....
406 -- If a,b occur once we can avoid constructing the let binding for them.
408 Furthermore in the case-binding case preInlineUnconditionally risks extra thunks
409 -- Consider case I# (quotInt# x y) of
410 -- I# v -> let w = J# v in ...
411 -- If we gaily inline (quotInt# x y) for v, we end up building an
413 -- let w = J# (quotInt# x y) in ...
414 -- because quotInt# can fail.
416 | preInlineUnconditionally env NotTopLevel bndr new_rhs
417 = thing_inside (extendIdSubst env bndr (DoneEx new_rhs))
420 ----------------------------------
421 prepareRhs takes a putative RHS, checks whether it's a PAP or
422 constructor application and, if so, converts it to ANF, so that the
423 resulting thing can be inlined more easily. Thus
430 We also want to deal well cases like this
431 v = (f e1 `cast` co) e2
432 Here we want to make e1,e2 trivial and get
433 x1 = e1; x2 = e2; v = (f x1 `cast` co) v2
434 That's what the 'go' loop in prepareRhs does
437 prepareRhs :: SimplEnv -> OutId -> OutExpr -> SimplM (SimplEnv, OutExpr)
438 -- Adds new floats to the env iff that allows us to return a good RHS
439 prepareRhs env id (Cast rhs co) -- Note [Float coercions]
440 | (ty1, _ty2) <- coercionKind co -- Do *not* do this if rhs has an unlifted type
441 , not (isUnLiftedType ty1) -- see Note [Float coercions (unlifted)]
442 = do { (env', rhs') <- makeTrivialWithInfo env sanitised_info rhs
443 ; return (env', Cast rhs' co) }
445 sanitised_info = vanillaIdInfo `setStrictnessInfo` strictnessInfo info
446 `setDemandInfo` demandInfo info
449 prepareRhs env0 _ rhs0
450 = do { (_is_exp, env1, rhs1) <- go 0 env0 rhs0
451 ; return (env1, rhs1) }
453 go n_val_args env (Cast rhs co)
454 = do { (is_exp, env', rhs') <- go n_val_args env rhs
455 ; return (is_exp, env', Cast rhs' co) }
456 go n_val_args env (App fun (Type ty))
457 = do { (is_exp, env', rhs') <- go n_val_args env fun
458 ; return (is_exp, env', App rhs' (Type ty)) }
459 go n_val_args env (App fun arg)
460 = do { (is_exp, env', fun') <- go (n_val_args+1) env fun
462 True -> do { (env'', arg') <- makeTrivial env' arg
463 ; return (True, env'', App fun' arg') }
464 False -> return (False, env, App fun arg) }
465 go n_val_args env (Var fun)
466 = return (is_exp, env, Var fun)
468 is_exp = isExpandableApp fun n_val_args -- The fun a constructor or PAP
469 -- See Note [CONLIKE pragma] in BasicTypes
470 -- The definition of is_exp should match that in
471 -- OccurAnal.occAnalApp
474 = return (False, env, other)
478 Note [Float coercions]
479 ~~~~~~~~~~~~~~~~~~~~~~
480 When we find the binding
482 we'd like to transform it to
484 x = x `cast` co -- A trivial binding
485 There's a chance that e will be a constructor application or function, or something
486 like that, so moving the coerion to the usage site may well cancel the coersions
487 and lead to further optimisation. Example:
490 data instance T Int = T Int
492 foo :: Int -> Int -> Int
497 go n = case x of { T m -> go (n-m) }
498 -- This case should optimise
500 Note [Preserve strictness when floating coercions]
501 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
502 In the Note [Float coercions] transformation, keep the strictness info.
504 f = e `cast` co -- f has strictness SSL
506 f' = e -- f' also has strictness SSL
507 f = f' `cast` co -- f still has strictness SSL
509 Its not wrong to drop it on the floor, but better to keep it.
511 Note [Float coercions (unlifted)]
512 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
513 BUT don't do [Float coercions] if 'e' has an unlifted type.
516 foo :: Int = (error (# Int,Int #) "urk")
517 `cast` CoUnsafe (# Int,Int #) Int
519 If do the makeTrivial thing to the error call, we'll get
520 foo = case error (# Int,Int #) "urk" of v -> v `cast` ...
521 But 'v' isn't in scope!
523 These strange casts can happen as a result of case-of-case
524 bar = case (case x of { T -> (# 2,3 #); F -> error "urk" }) of
529 makeTrivial :: SimplEnv -> OutExpr -> SimplM (SimplEnv, OutExpr)
530 -- Binds the expression to a variable, if it's not trivial, returning the variable
531 makeTrivial env expr = makeTrivialWithInfo env vanillaIdInfo expr
533 makeTrivialWithInfo :: SimplEnv -> IdInfo -> OutExpr -> SimplM (SimplEnv, OutExpr)
534 -- Propagate strictness and demand info to the new binder
535 -- Note [Preserve strictness when floating coercions]
536 makeTrivialWithInfo env info expr
539 | otherwise -- See Note [Take care] below
540 = do { uniq <- getUniqueM
541 ; let name = mkSystemVarName uniq (fsLit "a")
542 var = mkLocalIdWithInfo name (exprType expr) info
543 ; env' <- completeNonRecX env False var var expr
544 ; return (env', substExpr env' (Var var)) }
545 -- The substitution is needed becase we're constructing a new binding
547 -- And if rhs is of form (rhs1 |> co), then we might get
550 -- and now a's RHS is trivial and can be substituted out, and that
551 -- is what completeNonRecX will do
555 %************************************************************************
557 \subsection{Completing a lazy binding}
559 %************************************************************************
562 * deals only with Ids, not TyVars
563 * takes an already-simplified binder and RHS
564 * is used for both recursive and non-recursive bindings
565 * is used for both top-level and non-top-level bindings
567 It does the following:
568 - tries discarding a dead binding
569 - tries PostInlineUnconditionally
570 - add unfolding [this is the only place we add an unfolding]
573 It does *not* attempt to do let-to-case. Why? Because it is used for
574 - top-level bindings (when let-to-case is impossible)
575 - many situations where the "rhs" is known to be a WHNF
576 (so let-to-case is inappropriate).
578 Nor does it do the atomic-argument thing
581 completeBind :: SimplEnv
582 -> TopLevelFlag -- Flag stuck into unfolding
583 -> InId -- Old binder
584 -> OutId -> OutExpr -- New binder and RHS
586 -- completeBind may choose to do its work
587 -- * by extending the substitution (e.g. let x = y in ...)
588 -- * or by adding to the floats in the envt
590 completeBind env top_lvl old_bndr new_bndr new_rhs
591 = do { let old_info = idInfo old_bndr
592 old_unf = unfoldingInfo old_info
593 occ_info = occInfo old_info
595 ; new_unfolding <- simplUnfolding env top_lvl old_bndr occ_info new_rhs old_unf
597 ; if postInlineUnconditionally env top_lvl new_bndr occ_info new_rhs new_unfolding
598 -- Inline and discard the binding
599 then do { tick (PostInlineUnconditionally old_bndr)
600 ; -- pprTrace "postInlineUnconditionally" (ppr old_bndr <+> equals <+> ppr new_rhs) $
601 return (extendIdSubst env old_bndr (DoneEx new_rhs)) }
602 -- Use the substitution to make quite, quite sure that the
603 -- substitution will happen, since we are going to discard the binding
605 else return (addNonRecWithUnf env new_bndr new_rhs new_unfolding) }
607 ------------------------------
608 addPolyBind :: TopLevelFlag -> SimplEnv -> OutBind -> SimplM SimplEnv
609 -- Add a new binding to the environment, complete with its unfolding
610 -- but *do not* do postInlineUnconditionally, because we have already
611 -- processed some of the scope of the binding
612 -- We still want the unfolding though. Consider
614 -- x = /\a. let y = ... in Just y
616 -- Then we float the y-binding out (via abstractFloats and addPolyBind)
617 -- but 'x' may well then be inlined in 'body' in which case we'd like the
618 -- opportunity to inline 'y' too.
620 addPolyBind top_lvl env (NonRec poly_id rhs)
621 = do { unfolding <- simplUnfolding env top_lvl poly_id NoOccInfo rhs noUnfolding
622 -- Assumes that poly_id did not have an INLINE prag
623 -- which is perhaps wrong. ToDo: think about this
624 ; return (addNonRecWithUnf env poly_id rhs unfolding) }
626 addPolyBind _ env bind@(Rec _) = return (extendFloats env bind)
627 -- Hack: letrecs are more awkward, so we extend "by steam"
628 -- without adding unfoldings etc. At worst this leads to
629 -- more simplifier iterations
631 ------------------------------
632 addNonRecWithUnf :: SimplEnv
633 -> OutId -> OutExpr -- New binder and RHS
634 -> Unfolding -- New unfolding
636 addNonRecWithUnf env new_bndr new_rhs new_unfolding
637 = let new_arity = exprArity new_rhs
638 old_arity = idArity new_bndr
639 info1 = idInfo new_bndr `setArityInfo` new_arity
641 -- Unfolding info: Note [Setting the new unfolding]
642 info2 = info1 `setUnfoldingInfo` new_unfolding
644 -- Demand info: Note [Setting the demand info]
645 info3 | isEvaldUnfolding new_unfolding = zapDemandInfo info2 `orElse` info2
648 final_id = new_bndr `setIdInfo` info3
649 dmd_arity = length $ fst $ splitStrictSig $ idStrictness new_bndr
651 ASSERT( isId new_bndr )
652 WARN( new_arity < old_arity || new_arity < dmd_arity,
653 (ptext (sLit "Arity decrease:") <+> ppr final_id <+> ppr old_arity
654 <+> ppr new_arity <+> ppr dmd_arity) )
655 -- Note [Arity decrease]
657 final_id `seq` -- This seq forces the Id, and hence its IdInfo,
658 -- and hence any inner substitutions
659 -- pprTrace "Binding" (ppr final_id <+> ppr unfolding) $
660 addNonRec env final_id new_rhs
661 -- The addNonRec adds it to the in-scope set too
663 ------------------------------
664 simplUnfolding :: SimplEnv-> TopLevelFlag
666 -> OccInfo -> OutExpr
667 -> Unfolding -> SimplM Unfolding
668 -- Note [Setting the new unfolding]
669 simplUnfolding env _ _ _ _ (DFunUnfolding con ops)
670 = return (DFunUnfolding con ops')
672 ops' = map (CoreSubst.substExpr (mkCoreSubst env)) ops
674 simplUnfolding env top_lvl id _ _
675 (CoreUnfolding { uf_tmpl = expr, uf_arity = arity
676 , uf_src = src, uf_guidance = guide })
677 | isInlineRuleSource src
678 = -- pprTrace "su" (vcat [ppr id, ppr act, ppr (getMode env), ppr (getMode rule_env)]) $
679 do { expr' <- simplExpr rule_env expr
680 ; let src' = CoreSubst.substUnfoldingSource (mkCoreSubst env) src
681 ; return (mkCoreUnfolding (isTopLevel top_lvl) src' expr' arity guide) }
682 -- See Note [Top-level flag on inline rules] in CoreUnfold
684 act = idInlineActivation id
685 rule_env = updMode (updModeForInlineRules act) env
686 -- See Note [Simplifying gently inside InlineRules] in SimplUtils
688 simplUnfolding _ top_lvl id _occ_info new_rhs _
689 = return (mkUnfolding (isTopLevel top_lvl) (isBottomingId id) new_rhs)
690 -- We make an unfolding *even for loop-breakers*.
691 -- Reason: (a) It might be useful to know that they are WHNF
692 -- (b) In TidyPgm we currently assume that, if we want to
693 -- expose the unfolding then indeed we *have* an unfolding
694 -- to expose. (We could instead use the RHS, but currently
695 -- we don't.) The simple thing is always to have one.
698 Note [Arity decrease]
699 ~~~~~~~~~~~~~~~~~~~~~
700 Generally speaking the arity of a binding should not decrease. But it *can*
701 legitimately happen becuase of RULES. Eg
703 where g has arity 2, will have arity 2. But if there's a rewrite rule
705 where h has arity 1, then f's arity will decrease. Here's a real-life example,
706 which is in the output of Specialise:
709 $dm {Arity 2} = \d.\x. op d
710 {-# RULES forall d. $dm Int d = $s$dm #-}
712 dInt = MkD .... opInt ...
713 opInt {Arity 1} = $dm dInt
715 $s$dm {Arity 0} = \x. op dInt }
717 Here opInt has arity 1; but when we apply the rule its arity drops to 0.
718 That's why Specialise goes to a little trouble to pin the right arity
719 on specialised functions too.
721 Note [Setting the new unfolding]
722 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
723 * If there's an INLINE pragma, we simplify the RHS gently. Maybe we
724 should do nothing at all, but simplifying gently might get rid of
727 * If not, we make an unfolding from the new RHS. But *only* for
728 non-loop-breakers. Making loop breakers not have an unfolding at all
729 means that we can avoid tests in exprIsConApp, for example. This is
730 important: if exprIsConApp says 'yes' for a recursive thing, then we
731 can get into an infinite loop
733 If there's an InlineRule on a loop breaker, we hang on to the inlining.
734 It's pretty dodgy, but the user did say 'INLINE'. May need to revisit
737 Note [Setting the demand info]
738 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
739 If the unfolding is a value, the demand info may
740 go pear-shaped, so we nuke it. Example:
742 case x of (p,q) -> h p q x
743 Here x is certainly demanded. But after we've nuked
744 the case, we'll get just
745 let x = (a,b) in h a b x
746 and now x is not demanded (I'm assuming h is lazy)
747 This really happens. Similarly
748 let f = \x -> e in ...f..f...
749 After inlining f at some of its call sites the original binding may
750 (for example) be no longer strictly demanded.
751 The solution here is a bit ad hoc...
754 %************************************************************************
756 \subsection[Simplify-simplExpr]{The main function: simplExpr}
758 %************************************************************************
760 The reason for this OutExprStuff stuff is that we want to float *after*
761 simplifying a RHS, not before. If we do so naively we get quadratic
762 behaviour as things float out.
764 To see why it's important to do it after, consider this (real) example:
778 a -- Can't inline a this round, cos it appears twice
782 Each of the ==> steps is a round of simplification. We'd save a
783 whole round if we float first. This can cascade. Consider
788 let f = let d1 = ..d.. in \y -> e
792 in \x -> ...(\y ->e)...
794 Only in this second round can the \y be applied, and it
795 might do the same again.
799 simplExpr :: SimplEnv -> CoreExpr -> SimplM CoreExpr
800 simplExpr env expr = simplExprC env expr mkBoringStop
802 simplExprC :: SimplEnv -> CoreExpr -> SimplCont -> SimplM CoreExpr
803 -- Simplify an expression, given a continuation
804 simplExprC env expr cont
805 = -- pprTrace "simplExprC" (ppr expr $$ ppr cont {- $$ ppr (seIdSubst env) -} $$ ppr (seFloats env) ) $
806 do { (env', expr') <- simplExprF (zapFloats env) expr cont
807 ; -- pprTrace "simplExprC ret" (ppr expr $$ ppr expr') $
808 -- pprTrace "simplExprC ret3" (ppr (seInScope env')) $
809 -- pprTrace "simplExprC ret4" (ppr (seFloats env')) $
810 return (wrapFloats env' expr') }
812 --------------------------------------------------
813 simplExprF :: SimplEnv -> InExpr -> SimplCont
814 -> SimplM (SimplEnv, OutExpr)
816 simplExprF env e cont
817 = -- pprTrace "simplExprF" (ppr e $$ ppr cont $$ ppr (seTvSubst env) $$ ppr (seIdSubst env) {- $$ ppr (seFloats env) -} ) $
818 simplExprF' env e cont
820 simplExprF' :: SimplEnv -> InExpr -> SimplCont
821 -> SimplM (SimplEnv, OutExpr)
822 simplExprF' env (Var v) cont = simplVar env v cont
823 simplExprF' env (Lit lit) cont = rebuild env (Lit lit) cont
824 simplExprF' env (Note n expr) cont = simplNote env n expr cont
825 simplExprF' env (Cast body co) cont = simplCast env body co cont
826 simplExprF' env (App fun arg) cont = simplExprF env fun $
827 ApplyTo NoDup arg env cont
829 simplExprF' env expr@(Lam _ _) cont
830 = simplLam env (map zap bndrs) body cont
831 -- The main issue here is under-saturated lambdas
832 -- (\x1. \x2. e) arg1
833 -- Here x1 might have "occurs-once" occ-info, because occ-info
834 -- is computed assuming that a group of lambdas is applied
835 -- all at once. If there are too few args, we must zap the
838 n_args = countArgs cont
839 n_params = length bndrs
840 (bndrs, body) = collectBinders expr
841 zap | n_args >= n_params = \b -> b
842 | otherwise = \b -> if isTyVar b then b
844 -- NB: we count all the args incl type args
845 -- so we must count all the binders (incl type lambdas)
847 simplExprF' env (Type ty) cont
848 = ASSERT( contIsRhsOrArg cont )
849 do { ty' <- simplCoercion env ty
850 ; rebuild env (Type ty') cont }
852 simplExprF' env (Case scrut bndr _ alts) cont
853 | not (switchIsOn (getSwitchChecker env) NoCaseOfCase)
854 = -- Simplify the scrutinee with a Select continuation
855 simplExprF env scrut (Select NoDup bndr alts env cont)
858 = -- If case-of-case is off, simply simplify the case expression
859 -- in a vanilla Stop context, and rebuild the result around it
860 do { case_expr' <- simplExprC env scrut case_cont
861 ; rebuild env case_expr' cont }
863 case_cont = Select NoDup bndr alts env mkBoringStop
865 simplExprF' env (Let (Rec pairs) body) cont
866 = do { env' <- simplRecBndrs env (map fst pairs)
867 -- NB: bndrs' don't have unfoldings or rules
868 -- We add them as we go down
870 ; env'' <- simplRecBind env' NotTopLevel pairs
871 ; simplExprF env'' body cont }
873 simplExprF' env (Let (NonRec bndr rhs) body) cont
874 = simplNonRecE env bndr (rhs, env) ([], body) cont
876 ---------------------------------
877 simplType :: SimplEnv -> InType -> SimplM OutType
878 -- Kept monadic just so we can do the seqType
880 = -- pprTrace "simplType" (ppr ty $$ ppr (seTvSubst env)) $
881 seqType new_ty `seq` return new_ty
883 new_ty = substTy env ty
885 ---------------------------------
886 simplCoercion :: SimplEnv -> InType -> SimplM OutType
887 -- The InType isn't *necessarily* a coercion, but it might be
888 -- (in a type application, say) and optCoercion is a no-op on types
890 = seqType new_co `seq` return new_co
892 new_co = optCoercion (getTvSubst env) co
896 %************************************************************************
898 \subsection{The main rebuilder}
900 %************************************************************************
903 rebuild :: SimplEnv -> OutExpr -> SimplCont -> SimplM (SimplEnv, OutExpr)
904 -- At this point the substitution in the SimplEnv should be irrelevant
905 -- only the in-scope set and floats should matter
906 rebuild env expr cont0
907 = -- pprTrace "rebuild" (ppr expr $$ ppr cont0 $$ ppr (seFloats env)) $
909 Stop {} -> return (env, expr)
910 CoerceIt co cont -> rebuild env (mkCoerce co expr) cont
911 Select _ bndr alts se cont -> rebuildCase (se `setFloats` env) expr bndr alts cont
912 StrictArg info _ cont -> rebuildCall env (info `addArgTo` expr) cont
913 StrictBind b bs body se cont -> do { env' <- simplNonRecX (se `setFloats` env) b expr
914 ; simplLam env' bs body cont }
915 ApplyTo _ arg se cont -> do { arg' <- simplExpr (se `setInScope` env) arg
916 ; rebuild env (App expr arg') cont }
920 %************************************************************************
924 %************************************************************************
927 simplCast :: SimplEnv -> InExpr -> Coercion -> SimplCont
928 -> SimplM (SimplEnv, OutExpr)
929 simplCast env body co0 cont0
930 = do { co1 <- simplCoercion env co0
931 ; simplExprF env body (addCoerce co1 cont0) }
933 addCoerce co cont = add_coerce co (coercionKind co) cont
935 add_coerce _co (s1, k1) cont -- co :: ty~ty
936 | s1 `coreEqType` k1 = cont -- is a no-op
938 add_coerce co1 (s1, _k2) (CoerceIt co2 cont)
939 | (_l1, t1) <- coercionKind co2
940 -- e |> (g1 :: S1~L) |> (g2 :: L~T1)
943 -- e |> (g1 . g2 :: S1~T1) otherwise
945 -- For example, in the initial form of a worker
946 -- we may find (coerce T (coerce S (\x.e))) y
947 -- and we'd like it to simplify to e[y/x] in one round
949 , s1 `coreEqType` t1 = cont -- The coerces cancel out
950 | otherwise = CoerceIt (mkTransCoercion co1 co2) cont
952 add_coerce co (s1s2, _t1t2) (ApplyTo dup (Type arg_ty) arg_se cont)
953 -- (f |> g) ty ---> (f ty) |> (g @ ty)
954 -- This implements the PushT and PushC rules from the paper
955 | Just (tyvar,_) <- splitForAllTy_maybe s1s2
957 (new_arg_ty, new_cast)
958 | isCoVar tyvar = (new_arg_co, mkCselRCoercion co) -- PushC rule
959 | otherwise = (ty', mkInstCoercion co ty') -- PushT rule
961 ApplyTo dup (Type new_arg_ty) (zapSubstEnv arg_se) (addCoerce new_cast cont)
963 ty' = substTy (arg_se `setInScope` env) arg_ty
964 new_arg_co = mkCsel1Coercion co `mkTransCoercion`
965 ty' `mkTransCoercion`
966 mkSymCoercion (mkCsel2Coercion co)
968 add_coerce co (s1s2, _t1t2) (ApplyTo dup arg arg_se cont)
969 | not (isTypeArg arg) -- This implements the Push rule from the paper
970 , isFunTy s1s2 -- t1t2 must be a function type, becuase it's applied
971 -- (e |> (g :: s1s2 ~ t1->t2)) f
973 -- (e (f |> (arg g :: t1~s1))
974 -- |> (res g :: s2->t2)
976 -- t1t2 must be a function type, t1->t2, because it's applied
977 -- to something but s1s2 might conceivably not be
979 -- When we build the ApplyTo we can't mix the out-types
980 -- with the InExpr in the argument, so we simply substitute
981 -- to make it all consistent. It's a bit messy.
982 -- But it isn't a common case.
984 -- Example of use: Trac #995
985 = ApplyTo dup new_arg (zapSubstEnv arg_se) (addCoerce co2 cont)
987 -- we split coercion t1->t2 ~ s1->s2 into t1 ~ s1 and
988 -- t2 ~ s2 with left and right on the curried form:
989 -- (->) t1 t2 ~ (->) s1 s2
990 [co1, co2] = decomposeCo 2 co
991 new_arg = mkCoerce (mkSymCoercion co1) arg'
992 arg' = substExpr (arg_se `setInScope` env) arg
994 add_coerce co _ cont = CoerceIt co cont
998 %************************************************************************
1000 \subsection{Lambdas}
1002 %************************************************************************
1005 simplLam :: SimplEnv -> [InId] -> InExpr -> SimplCont
1006 -> SimplM (SimplEnv, OutExpr)
1008 simplLam env [] body cont = simplExprF env body cont
1011 simplLam env (bndr:bndrs) body (ApplyTo _ arg arg_se cont)
1012 = do { tick (BetaReduction bndr)
1013 ; simplNonRecE env bndr (arg, arg_se) (bndrs, body) cont }
1015 -- Not enough args, so there are real lambdas left to put in the result
1016 simplLam env bndrs body cont
1017 = do { (env', bndrs') <- simplLamBndrs env bndrs
1018 ; body' <- simplExpr env' body
1019 ; new_lam <- mkLam env' bndrs' body'
1020 ; rebuild env' new_lam cont }
1023 simplNonRecE :: SimplEnv
1024 -> InBndr -- The binder
1025 -> (InExpr, SimplEnv) -- Rhs of binding (or arg of lambda)
1026 -> ([InBndr], InExpr) -- Body of the let/lambda
1029 -> SimplM (SimplEnv, OutExpr)
1031 -- simplNonRecE is used for
1032 -- * non-top-level non-recursive lets in expressions
1035 -- It deals with strict bindings, via the StrictBind continuation,
1036 -- which may abort the whole process
1038 -- The "body" of the binding comes as a pair of ([InId],InExpr)
1039 -- representing a lambda; so we recurse back to simplLam
1040 -- Why? Because of the binder-occ-info-zapping done before
1041 -- the call to simplLam in simplExprF (Lam ...)
1043 -- First deal with type applications and type lets
1044 -- (/\a. e) (Type ty) and (let a = Type ty in e)
1045 simplNonRecE env bndr (Type ty_arg, rhs_se) (bndrs, body) cont
1046 = ASSERT( isTyVar bndr )
1047 do { ty_arg' <- simplType (rhs_se `setInScope` env) ty_arg
1048 ; simplLam (extendTvSubst env bndr ty_arg') bndrs body cont }
1050 simplNonRecE env bndr (rhs, rhs_se) (bndrs, body) cont
1051 | preInlineUnconditionally env NotTopLevel bndr rhs
1052 = do { tick (PreInlineUnconditionally bndr)
1053 ; simplLam (extendIdSubst env bndr (mkContEx rhs_se rhs)) bndrs body cont }
1056 = do { simplExprF (rhs_se `setFloats` env) rhs
1057 (StrictBind bndr bndrs body env cont) }
1060 = ASSERT( not (isTyVar bndr) )
1061 do { (env1, bndr1) <- simplNonRecBndr env bndr
1062 ; let (env2, bndr2) = addBndrRules env1 bndr bndr1
1063 ; env3 <- simplLazyBind env2 NotTopLevel NonRecursive bndr bndr2 rhs rhs_se
1064 ; simplLam env3 bndrs body cont }
1068 %************************************************************************
1072 %************************************************************************
1075 -- Hack alert: we only distinguish subsumed cost centre stacks for the
1076 -- purposes of inlining. All other CCCSs are mapped to currentCCS.
1077 simplNote :: SimplEnv -> Note -> CoreExpr -> SimplCont
1078 -> SimplM (SimplEnv, OutExpr)
1079 simplNote env (SCC cc) e cont
1080 | pushCCisNop cc (getEnclosingCC env) -- scc "f" (...(scc "f" e)...)
1081 = simplExprF env e cont -- ==> scc "f" (...e...)
1083 = do { e' <- simplExpr (setEnclosingCC env currentCCS) e
1084 ; rebuild env (mkSCC cc e') cont }
1086 simplNote env (CoreNote s) e cont
1087 = do { e' <- simplExpr env e
1088 ; rebuild env (Note (CoreNote s) e') cont }
1092 %************************************************************************
1094 \subsection{Dealing with calls}
1096 %************************************************************************
1099 simplVar :: SimplEnv -> Id -> SimplCont -> SimplM (SimplEnv, OutExpr)
1100 simplVar env var cont
1101 = case substId env var of
1102 DoneEx e -> simplExprF (zapSubstEnv env) e cont
1103 ContEx tvs ids e -> simplExprF (setSubstEnv env tvs ids) e cont
1104 DoneId var1 -> completeCall env var1 cont
1105 -- Note [zapSubstEnv]
1106 -- The template is already simplified, so don't re-substitute.
1107 -- This is VITAL. Consider
1109 -- let y = \z -> ...x... in
1111 -- We'll clone the inner \x, adding x->x' in the id_subst
1112 -- Then when we inline y, we must *not* replace x by x' in
1113 -- the inlined copy!!
1115 ---------------------------------------------------------
1116 -- Dealing with a call site
1118 completeCall :: SimplEnv -> Id -> SimplCont -> SimplM (SimplEnv, OutExpr)
1119 completeCall env var cont
1120 = do { ------------- Try inlining ----------------
1121 dflags <- getDOptsSmpl
1122 ; let (args,call_cont) = contArgs cont
1123 -- The args are OutExprs, obtained by *lazily* substituting
1124 -- in the args found in cont. These args are only examined
1125 -- to limited depth (unless a rule fires). But we must do
1126 -- the substitution; rule matching on un-simplified args would
1129 arg_infos = [interestingArg arg | arg <- args, isValArg arg]
1130 n_val_args = length arg_infos
1131 interesting_cont = interestingCallContext call_cont
1132 unfolding = activeUnfolding env var
1133 maybe_inline = callSiteInline dflags var unfolding
1134 (null args) arg_infos interesting_cont
1135 ; case maybe_inline of {
1136 Just unfolding -- There is an inlining!
1137 -> do { tick (UnfoldingDone var)
1138 ; trace_inline dflags unfolding args call_cont $
1139 simplExprF (zapSubstEnv env) unfolding cont }
1141 ; Nothing -> do -- No inlining!
1143 { rule_base <- getSimplRules
1144 ; let info = mkArgInfo var (getRules rule_base var) n_val_args call_cont
1145 ; rebuildCall env info cont
1148 trace_inline dflags unfolding args call_cont stuff
1149 | not (dopt Opt_D_dump_inlinings dflags) = stuff
1150 | not (dopt Opt_D_verbose_core2core dflags)
1151 = if isExternalName (idName var) then
1152 pprTrace "Inlining done:" (ppr var) stuff
1155 = pprTrace ("Inlining done: " ++ showSDoc (ppr var))
1156 (vcat [text "Before:" <+> ppr var <+> sep (map pprParendExpr args),
1157 text "Inlined fn: " <+> nest 2 (ppr unfolding),
1158 text "Cont: " <+> ppr call_cont])
1161 rebuildCall :: SimplEnv
1164 -> SimplM (SimplEnv, OutExpr)
1165 rebuildCall env (ArgInfo { ai_fun = fun, ai_args = rev_args, ai_strs = [] }) cont
1166 -- When we run out of strictness args, it means
1167 -- that the call is definitely bottom; see SimplUtils.mkArgInfo
1168 -- Then we want to discard the entire strict continuation. E.g.
1169 -- * case (error "hello") of { ... }
1170 -- * (error "Hello") arg
1171 -- * f (error "Hello") where f is strict
1173 -- Then, especially in the first of these cases, we'd like to discard
1174 -- the continuation, leaving just the bottoming expression. But the
1175 -- type might not be right, so we may have to add a coerce.
1176 | not (contIsTrivial cont) -- Only do this if there is a non-trivial
1177 = return (env, mk_coerce res) -- contination to discard, else we do it
1178 where -- again and again!
1179 res = mkApps (Var fun) (reverse rev_args)
1180 res_ty = exprType res
1181 cont_ty = contResultType env res_ty cont
1182 co = mkUnsafeCoercion res_ty cont_ty
1183 mk_coerce expr | cont_ty `coreEqType` res_ty = expr
1184 | otherwise = mkCoerce co expr
1186 rebuildCall env info (ApplyTo _ (Type arg_ty) se cont)
1187 = do { ty' <- simplCoercion (se `setInScope` env) arg_ty
1188 ; rebuildCall env (info `addArgTo` Type ty') cont }
1190 rebuildCall env info@(ArgInfo { ai_encl = encl_rules
1191 , ai_strs = str:strs, ai_discs = disc:discs })
1192 (ApplyTo _ arg arg_se cont)
1193 | str -- Strict argument
1194 = -- pprTrace "Strict Arg" (ppr arg $$ ppr (seIdSubst env) $$ ppr (seInScope env)) $
1195 simplExprF (arg_se `setFloats` env) arg
1196 (StrictArg info' cci cont)
1199 | otherwise -- Lazy argument
1200 -- DO NOT float anything outside, hence simplExprC
1201 -- There is no benefit (unlike in a let-binding), and we'd
1202 -- have to be very careful about bogus strictness through
1203 -- floating a demanded let.
1204 = do { arg' <- simplExprC (arg_se `setInScope` env) arg
1206 ; rebuildCall env (addArgTo info' arg') cont }
1208 info' = info { ai_strs = strs, ai_discs = discs }
1209 cci | encl_rules || disc > 0 = ArgCtxt encl_rules -- Be keener here
1210 | otherwise = BoringCtxt -- Nothing interesting
1212 rebuildCall env (ArgInfo { ai_fun = fun, ai_args = rev_args, ai_rules = rules }) cont
1213 = do { -- We've accumulated a simplified call in <fun,rev_args>
1214 -- so try rewrite rules; see Note [RULEs apply to simplified arguments]
1215 -- See also Note [Rules for recursive functions]
1216 ; let args = reverse rev_args
1217 env' = zapSubstEnv env
1218 ; mb_rule <- tryRules env rules fun args cont
1220 Just (n_args, rule_rhs) -> simplExprF env' rule_rhs $
1221 pushArgs env' (drop n_args args) cont ;
1222 -- n_args says how many args the rule consumed
1223 ; Nothing -> rebuild env (mkApps (Var fun) args) cont -- No rules
1227 Note [RULES apply to simplified arguments]
1228 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1229 It's very desirable to try RULES once the arguments have been simplified, because
1230 doing so ensures that rule cascades work in one pass. Consider
1231 {-# RULES g (h x) = k x
1234 Then we want to rewrite (g (h x)) to (k x) and only then try f's rules. If
1235 we match f's rules against the un-simplified RHS, it won't match. This
1236 makes a particularly big difference when superclass selectors are involved:
1237 op ($p1 ($p2 (df d)))
1238 We want all this to unravel in one sweeep.
1242 This part of the simplifier may break the no-shadowing invariant
1244 f (...(\a -> e)...) (case y of (a,b) -> e')
1245 where f is strict in its second arg
1246 If we simplify the innermost one first we get (...(\a -> e)...)
1247 Simplifying the second arg makes us float the case out, so we end up with
1248 case y of (a,b) -> f (...(\a -> e)...) e'
1249 So the output does not have the no-shadowing invariant. However, there is
1250 no danger of getting name-capture, because when the first arg was simplified
1251 we used an in-scope set that at least mentioned all the variables free in its
1252 static environment, and that is enough.
1254 We can't just do innermost first, or we'd end up with a dual problem:
1255 case x of (a,b) -> f e (...(\a -> e')...)
1257 I spent hours trying to recover the no-shadowing invariant, but I just could
1258 not think of an elegant way to do it. The simplifier is already knee-deep in
1259 continuations. We have to keep the right in-scope set around; AND we have
1260 to get the effect that finding (error "foo") in a strict arg position will
1261 discard the entire application and replace it with (error "foo"). Getting
1262 all this at once is TOO HARD!
1265 %************************************************************************
1269 %************************************************************************
1272 tryRules :: SimplEnv -> [CoreRule]
1273 -> Id -> [OutExpr] -> SimplCont
1274 -> SimplM (Maybe (Arity, CoreExpr)) -- The arity is the number of
1275 -- args consumed by the rule
1276 tryRules env rules fn args call_cont
1280 = do { dflags <- getDOptsSmpl
1281 ; case activeRule dflags env of {
1282 Nothing -> return Nothing ; -- No rules apply
1284 case lookupRule act_fn (activeUnfInRule env) (getInScope env) fn args rules of {
1285 Nothing -> return Nothing ; -- No rule matches
1286 Just (rule, rule_rhs) ->
1288 do { tick (RuleFired (ru_name rule))
1289 ; trace_dump dflags rule rule_rhs $
1290 return (Just (ruleArity rule, rule_rhs)) }}}}
1292 trace_dump dflags rule rule_rhs stuff
1293 | not (dopt Opt_D_dump_rule_firings dflags) = stuff
1294 | not (dopt Opt_D_verbose_core2core dflags)
1296 = pprTrace "Rule fired:" (ftext (ru_name rule)) stuff
1298 = pprTrace "Rule fired"
1299 (vcat [text "Rule:" <+> ftext (ru_name rule),
1300 text "Before:" <+> ppr fn <+> sep (map pprParendExpr args),
1301 text "After: " <+> pprCoreExpr rule_rhs,
1302 text "Cont: " <+> ppr call_cont])
1306 Note [Rules for recursive functions]
1307 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1308 You might think that we shouldn't apply rules for a loop breaker:
1309 doing so might give rise to an infinite loop, because a RULE is
1310 rather like an extra equation for the function:
1311 RULE: f (g x) y = x+y
1314 But it's too drastic to disable rules for loop breakers.
1315 Even the foldr/build rule would be disabled, because foldr
1316 is recursive, and hence a loop breaker:
1317 foldr k z (build g) = g k z
1318 So it's up to the programmer: rules can cause divergence
1321 %************************************************************************
1323 Rebuilding a cse expression
1325 %************************************************************************
1327 Note [Case elimination]
1328 ~~~~~~~~~~~~~~~~~~~~~~~
1329 The case-elimination transformation discards redundant case expressions.
1330 Start with a simple situation:
1332 case x# of ===> e[x#/y#]
1335 (when x#, y# are of primitive type, of course). We can't (in general)
1336 do this for algebraic cases, because we might turn bottom into
1339 The code in SimplUtils.prepareAlts has the effect of generalise this
1340 idea to look for a case where we're scrutinising a variable, and we
1341 know that only the default case can match. For example:
1345 DEFAULT -> ...(case x of
1349 Here the inner case is first trimmed to have only one alternative, the
1350 DEFAULT, after which it's an instance of the previous case. This
1351 really only shows up in eliminating error-checking code.
1353 We also make sure that we deal with this very common case:
1358 Here we are using the case as a strict let; if x is used only once
1359 then we want to inline it. We have to be careful that this doesn't
1360 make the program terminate when it would have diverged before, so we
1362 - e is already evaluated (it may so if e is a variable)
1363 - x is used strictly, or
1365 Lastly, the code in SimplUtils.mkCase combines identical RHSs. So
1367 case e of ===> case e of DEFAULT -> r
1371 Now again the case may be elminated by the CaseElim transformation.
1374 Further notes about case elimination
1375 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1376 Consider: test :: Integer -> IO ()
1379 Turns out that this compiles to:
1382 eta1 :: State# RealWorld ->
1383 case PrelNum.< eta PrelNum.zeroInteger of wild { __DEFAULT ->
1385 (PrelNum.jtos eta ($w[] @ Char))
1387 of wild1 { (# new_s, a4 #) -> PrelIO.lvl23 new_s }}
1389 Notice the strange '<' which has no effect at all. This is a funny one.
1390 It started like this:
1392 f x y = if x < 0 then jtos x
1393 else if y==0 then "" else jtos x
1395 At a particular call site we have (f v 1). So we inline to get
1397 if v < 0 then jtos x
1398 else if 1==0 then "" else jtos x
1400 Now simplify the 1==0 conditional:
1402 if v<0 then jtos v else jtos v
1404 Now common-up the two branches of the case:
1406 case (v<0) of DEFAULT -> jtos v
1408 Why don't we drop the case? Because it's strict in v. It's technically
1409 wrong to drop even unnecessary evaluations, and in practice they
1410 may be a result of 'seq' so we *definitely* don't want to drop those.
1411 I don't really know how to improve this situation.
1414 ---------------------------------------------------------
1415 -- Eliminate the case if possible
1417 rebuildCase, reallyRebuildCase
1419 -> OutExpr -- Scrutinee
1420 -> InId -- Case binder
1421 -> [InAlt] -- Alternatives (inceasing order)
1423 -> SimplM (SimplEnv, OutExpr)
1425 --------------------------------------------------
1426 -- 1. Eliminate the case if there's a known constructor
1427 --------------------------------------------------
1429 rebuildCase env scrut case_bndr alts cont
1430 | Lit lit <- scrut -- No need for same treatment as constructors
1431 -- because literals are inlined more vigorously
1432 = do { tick (KnownBranch case_bndr)
1433 ; case findAlt (LitAlt lit) alts of
1434 Nothing -> missingAlt env case_bndr alts cont
1435 Just (_, bs, rhs) -> simple_rhs bs rhs }
1437 | Just (con, ty_args, other_args) <- exprIsConApp_maybe (activeUnfInRule env) scrut
1438 -- Works when the scrutinee is a variable with a known unfolding
1439 -- as well as when it's an explicit constructor application
1440 = do { tick (KnownBranch case_bndr)
1441 ; case findAlt (DataAlt con) alts of
1442 Nothing -> missingAlt env case_bndr alts cont
1443 Just (DEFAULT, bs, rhs) -> simple_rhs bs rhs
1444 Just (_, bs, rhs) -> knownCon env scrut con ty_args other_args
1445 case_bndr bs rhs cont
1448 simple_rhs bs rhs = ASSERT( null bs )
1449 do { env' <- simplNonRecX env case_bndr scrut
1450 ; simplExprF env' rhs cont }
1453 --------------------------------------------------
1454 -- 2. Eliminate the case if scrutinee is evaluated
1455 --------------------------------------------------
1457 rebuildCase env scrut case_bndr [(_, bndrs, rhs)] cont
1458 -- See if we can get rid of the case altogether
1459 -- See Note [Case eliminiation]
1460 -- mkCase made sure that if all the alternatives are equal,
1461 -- then there is now only one (DEFAULT) rhs
1462 | all isDeadBinder bndrs -- bndrs are [InId]
1464 -- Check that the scrutinee can be let-bound instead of case-bound
1465 , exprOkForSpeculation scrut
1466 -- OK not to evaluate it
1467 -- This includes things like (==# a# b#)::Bool
1468 -- so that we simplify
1469 -- case ==# a# b# of { True -> x; False -> x }
1472 -- This particular example shows up in default methods for
1473 -- comparision operations (e.g. in (>=) for Int.Int32)
1474 || exprIsHNF scrut -- It's already evaluated
1475 || var_demanded_later scrut -- It'll be demanded later
1477 -- || not opt_SimplPedanticBottoms) -- Or we don't care!
1478 -- We used to allow improving termination by discarding cases, unless -fpedantic-bottoms was on,
1479 -- but that breaks badly for the dataToTag# primop, which relies on a case to evaluate
1480 -- its argument: case x of { y -> dataToTag# y }
1481 -- Here we must *not* discard the case, because dataToTag# just fetches the tag from
1482 -- the info pointer. So we'll be pedantic all the time, and see if that gives any
1484 -- Also we don't want to discard 'seq's
1485 = do { tick (CaseElim case_bndr)
1486 ; env' <- simplNonRecX env case_bndr scrut
1487 ; simplExprF env' rhs cont }
1489 -- The case binder is going to be evaluated later,
1490 -- and the scrutinee is a simple variable
1491 var_demanded_later (Var v) = isStrictDmd (idDemandInfo case_bndr)
1492 && not (isTickBoxOp v)
1493 -- ugly hack; covering this case is what
1494 -- exprOkForSpeculation was intended for.
1495 var_demanded_later _ = False
1497 --------------------------------------------------
1498 -- 3. Try seq rules; see Note [User-defined RULES for seq] in MkId
1499 --------------------------------------------------
1501 rebuildCase env scrut case_bndr alts@[(_, bndrs, rhs)] cont
1502 | all isDeadBinder (case_bndr : bndrs) -- So this is just 'seq'
1503 = do { let rhs' = substExpr env rhs
1504 out_args = [Type (substTy env (idType case_bndr)),
1505 Type (exprType rhs'), scrut, rhs']
1506 -- Lazily evaluated, so we don't do most of this
1508 ; rule_base <- getSimplRules
1509 ; mb_rule <- tryRules env (getRules rule_base seqId) seqId out_args cont
1511 Just (n_args, res) -> simplExprF (zapSubstEnv env)
1512 (mkApps res (drop n_args out_args))
1514 Nothing -> reallyRebuildCase env scrut case_bndr alts cont }
1516 rebuildCase env scrut case_bndr alts cont
1517 = reallyRebuildCase env scrut case_bndr alts cont
1519 --------------------------------------------------
1520 -- 3. Catch-all case
1521 --------------------------------------------------
1523 reallyRebuildCase env scrut case_bndr alts cont
1524 = do { -- Prepare the continuation;
1525 -- The new subst_env is in place
1526 (env', dup_cont, nodup_cont) <- prepareCaseCont env alts cont
1528 -- Simplify the alternatives
1529 ; (scrut', case_bndr', alts') <- simplAlts env' scrut case_bndr alts dup_cont
1531 -- Check for empty alternatives
1532 ; if null alts' then missingAlt env case_bndr alts cont
1534 { dflags <- getDOptsSmpl
1535 ; case_expr <- mkCase dflags scrut' case_bndr' alts'
1537 -- Notice that rebuild gets the in-scope set from env', not alt_env
1538 -- (which in any case is only build in simplAlts)
1539 -- The case binder *not* scope over the whole returned case-expression
1540 ; rebuild env' case_expr nodup_cont } }
1543 simplCaseBinder checks whether the scrutinee is a variable, v. If so,
1544 try to eliminate uses of v in the RHSs in favour of case_bndr; that
1545 way, there's a chance that v will now only be used once, and hence
1548 Historical note: we use to do the "case binder swap" in the Simplifier
1549 so there were additional complications if the scrutinee was a variable.
1550 Now the binder-swap stuff is done in the occurrence analyer; see
1551 OccurAnal Note [Binder swap].
1555 If the case binder is not dead, then neither are the pattern bound
1557 case <any> of x { (a,b) ->
1558 case x of { (p,q) -> p } }
1559 Here (a,b) both look dead, but come alive after the inner case is eliminated.
1560 The point is that we bring into the envt a binding
1562 after the outer case, and that makes (a,b) alive. At least we do unless
1563 the case binder is guaranteed dead.
1565 In practice, the scrutinee is almost always a variable, so we pretty
1566 much always zap the OccInfo of the binders. It doesn't matter much though.
1571 Consider case (v `cast` co) of x { I# y ->
1572 ... (case (v `cast` co) of {...}) ...
1573 We'd like to eliminate the inner case. We can get this neatly by
1574 arranging that inside the outer case we add the unfolding
1575 v |-> x `cast` (sym co)
1576 to v. Then we should inline v at the inner case, cancel the casts, and away we go
1578 Note [Improving seq]
1581 type family F :: * -> *
1582 type instance F Int = Int
1584 ... case e of x { DEFAULT -> rhs } ...
1586 where x::F Int. Then we'd like to rewrite (F Int) to Int, getting
1588 case e `cast` co of x'::Int
1589 I# x# -> let x = x' `cast` sym co
1592 so that 'rhs' can take advantage of the form of x'.
1594 Notice that Note [Case of cast] may then apply to the result.
1596 Nota Bene: We only do the [Improving seq] transformation if the
1597 case binder 'x' is actually used in the rhs; that is, if the case
1598 is *not* a *pure* seq.
1599 a) There is no point in adding the cast to a pure seq.
1600 b) There is a good reason not to: doing so would interfere
1601 with seq rules (Note [Built-in RULES for seq] in MkId).
1602 In particular, this [Improving seq] thing *adds* a cast
1603 while [Built-in RULES for seq] *removes* one, so they
1606 You might worry about
1607 case v of x { __DEFAULT ->
1608 ... case (v `cast` co) of y { I# -> ... }}
1609 This is a pure seq (since x is unused), so [Improving seq] won't happen.
1610 But it's ok: the simplifier will replace 'v' by 'x' in the rhs to get
1611 case v of x { __DEFAULT ->
1612 ... case (x `cast` co) of y { I# -> ... }}
1613 Now the outer case is not a pure seq, so [Improving seq] will happen,
1614 and then the inner case will disappear.
1616 The need for [Improving seq] showed up in Roman's experiments. Example:
1617 foo :: F Int -> Int -> Int
1618 foo t n = t `seq` bar n
1621 bar n = bar (n - case t of TI i -> i)
1622 Here we'd like to avoid repeated evaluating t inside the loop, by
1623 taking advantage of the `seq`.
1625 At one point I did transformation in LiberateCase, but it's more
1626 robust here. (Otherwise, there's a danger that we'll simply drop the
1627 'seq' altogether, before LiberateCase gets to see it.)
1630 simplAlts :: SimplEnv
1632 -> InId -- Case binder
1633 -> [InAlt] -- Non-empty
1635 -> SimplM (OutExpr, OutId, [OutAlt]) -- Includes the continuation
1636 -- Like simplExpr, this just returns the simplified alternatives;
1637 -- it does not return an environment
1639 simplAlts env scrut case_bndr alts cont'
1640 = -- pprTrace "simplAlts" (ppr alts $$ ppr (seIdSubst env)) $
1641 do { let env0 = zapFloats env
1643 ; (env1, case_bndr1) <- simplBinder env0 case_bndr
1645 ; fam_envs <- getFamEnvs
1646 ; (alt_env', scrut', case_bndr') <- improveSeq fam_envs env1 scrut
1647 case_bndr case_bndr1 alts
1649 ; (imposs_deflt_cons, in_alts) <- prepareAlts scrut' case_bndr' alts
1651 ; alts' <- mapM (simplAlt alt_env' imposs_deflt_cons case_bndr' cont') in_alts
1652 ; return (scrut', case_bndr', alts') }
1655 ------------------------------------
1656 improveSeq :: (FamInstEnv, FamInstEnv) -> SimplEnv
1657 -> OutExpr -> InId -> OutId -> [InAlt]
1658 -> SimplM (SimplEnv, OutExpr, OutId)
1659 -- Note [Improving seq]
1660 improveSeq fam_envs env scrut case_bndr case_bndr1 [(DEFAULT,_,_)]
1661 | not (isDeadBinder case_bndr) -- Not a pure seq! See the Note!
1662 , Just (co, ty2) <- topNormaliseType fam_envs (idType case_bndr1)
1663 = do { case_bndr2 <- newId (fsLit "nt") ty2
1664 ; let rhs = DoneEx (Var case_bndr2 `Cast` mkSymCoercion co)
1665 env2 = extendIdSubst env case_bndr rhs
1666 ; return (env2, scrut `Cast` co, case_bndr2) }
1668 improveSeq _ env scrut _ case_bndr1 _
1669 = return (env, scrut, case_bndr1)
1672 ------------------------------------
1673 simplAlt :: SimplEnv
1674 -> [AltCon] -- These constructors can't be present when
1675 -- matching the DEFAULT alternative
1676 -> OutId -- The case binder
1681 simplAlt env imposs_deflt_cons case_bndr' cont' (DEFAULT, bndrs, rhs)
1682 = ASSERT( null bndrs )
1683 do { let env' = addBinderOtherCon env case_bndr' imposs_deflt_cons
1684 -- Record the constructors that the case-binder *can't* be.
1685 ; rhs' <- simplExprC env' rhs cont'
1686 ; return (DEFAULT, [], rhs') }
1688 simplAlt env _ case_bndr' cont' (LitAlt lit, bndrs, rhs)
1689 = ASSERT( null bndrs )
1690 do { let env' = addBinderUnfolding env case_bndr' (Lit lit)
1691 ; rhs' <- simplExprC env' rhs cont'
1692 ; return (LitAlt lit, [], rhs') }
1694 simplAlt env _ case_bndr' cont' (DataAlt con, vs, rhs)
1695 = do { -- Deal with the pattern-bound variables
1696 -- Mark the ones that are in ! positions in the
1697 -- data constructor as certainly-evaluated.
1698 -- NB: simplLamBinders preserves this eval info
1699 let vs_with_evals = add_evals (dataConRepStrictness con)
1700 ; (env', vs') <- simplLamBndrs env vs_with_evals
1702 -- Bind the case-binder to (con args)
1703 ; let inst_tys' = tyConAppArgs (idType case_bndr')
1704 con_args = map Type inst_tys' ++ varsToCoreExprs vs'
1705 env'' = addBinderUnfolding env' case_bndr'
1706 (mkConApp con con_args)
1708 ; rhs' <- simplExprC env'' rhs cont'
1709 ; return (DataAlt con, vs', rhs') }
1711 -- add_evals records the evaluated-ness of the bound variables of
1712 -- a case pattern. This is *important*. Consider
1713 -- data T = T !Int !Int
1715 -- case x of { T a b -> T (a+1) b }
1717 -- We really must record that b is already evaluated so that we don't
1718 -- go and re-evaluate it when constructing the result.
1719 -- See Note [Data-con worker strictness] in MkId.lhs
1724 go (v:vs') strs | isTyVar v = v : go vs' strs
1725 go (v:vs') (str:strs)
1726 | isMarkedStrict str = evald_v : go vs' strs
1727 | otherwise = zapped_v : go vs' strs
1729 zapped_v = zap_occ_info v
1730 evald_v = zapped_v `setIdUnfolding` evaldUnfolding
1731 go _ _ = pprPanic "cat_evals" (ppr con $$ ppr vs $$ ppr the_strs)
1733 -- See Note [zapOccInfo]
1734 -- zap_occ_info: if the case binder is alive, then we add the unfolding
1736 -- to the envt; so vs are now very much alive
1737 -- Note [Aug06] I can't see why this actually matters, but it's neater
1738 -- case e of t { (a,b) -> ...(case t of (p,q) -> p)... }
1739 -- ==> case e of t { (a,b) -> ...(a)... }
1740 -- Look, Ma, a is alive now.
1741 zap_occ_info = zapCasePatIdOcc case_bndr'
1743 addBinderUnfolding :: SimplEnv -> Id -> CoreExpr -> SimplEnv
1744 addBinderUnfolding env bndr rhs
1745 = modifyInScope env (bndr `setIdUnfolding` mkUnfolding False False rhs)
1747 addBinderOtherCon :: SimplEnv -> Id -> [AltCon] -> SimplEnv
1748 addBinderOtherCon env bndr cons
1749 = modifyInScope env (bndr `setIdUnfolding` mkOtherCon cons)
1751 zapCasePatIdOcc :: Id -> Id -> Id
1752 -- Consider case e of b { (a,b) -> ... }
1753 -- Then if we bind b to (a,b) in "...", and b is not dead,
1754 -- then we must zap the deadness info on a,b
1755 zapCasePatIdOcc case_bndr
1756 | isDeadBinder case_bndr = \ pat_id -> pat_id
1757 | otherwise = \ pat_id -> zapIdOccInfo pat_id
1761 %************************************************************************
1763 \subsection{Known constructor}
1765 %************************************************************************
1767 We are a bit careful with occurrence info. Here's an example
1769 (\x* -> case x of (a*, b) -> f a) (h v, e)
1771 where the * means "occurs once". This effectively becomes
1772 case (h v, e) of (a*, b) -> f a)
1774 let a* = h v; b = e in f a
1778 All this should happen in one sweep.
1781 knownCon :: SimplEnv
1782 -> OutExpr -- The scrutinee
1783 -> DataCon -> [OutType] -> [OutExpr] -- The scrutinee (in pieces)
1784 -> InId -> [InBndr] -> InExpr -- The alternative
1786 -> SimplM (SimplEnv, OutExpr)
1788 knownCon env scrut dc dc_ty_args dc_args bndr bs rhs cont
1789 = do { env' <- bind_args env bs dc_args
1791 -- It's useful to bind bndr to scrut, rather than to a fresh
1792 -- binding x = Con arg1 .. argn
1793 -- because very often the scrut is a variable, so we avoid
1794 -- creating, and then subsequently eliminating, a let-binding
1795 -- BUT, if scrut is a not a variable, we must be careful
1796 -- about duplicating the arg redexes; in that case, make
1797 -- a new con-app from the args
1798 bndr_rhs | exprIsTrivial scrut = scrut
1799 | otherwise = con_app
1800 con_app = Var (dataConWorkId dc)
1801 `mkTyApps` dc_ty_args
1802 `mkApps` [substExpr env' (varToCoreExpr b) | b <- bs]
1803 -- dc_ty_args are aready OutTypes, but bs are InBndrs
1805 ; env'' <- simplNonRecX env' bndr bndr_rhs
1806 ; simplExprF env'' rhs cont }
1808 zap_occ = zapCasePatIdOcc bndr -- bndr is an InId
1811 bind_args env' [] _ = return env'
1813 bind_args env' (b:bs') (Type ty : args)
1814 = ASSERT( isTyVar b )
1815 bind_args (extendTvSubst env' b ty) bs' args
1817 bind_args env' (b:bs') (arg : args)
1819 do { let b' = zap_occ b
1820 -- Note that the binder might be "dead", because it doesn't
1821 -- occur in the RHS; and simplNonRecX may therefore discard
1822 -- it via postInlineUnconditionally.
1823 -- Nevertheless we must keep it if the case-binder is alive,
1824 -- because it may be used in the con_app. See Note [zapOccInfo]
1825 ; env'' <- simplNonRecX env' b' arg
1826 ; bind_args env'' bs' args }
1829 pprPanic "bind_args" $ ppr dc $$ ppr bs $$ ppr dc_args $$
1830 text "scrut:" <+> ppr scrut
1833 missingAlt :: SimplEnv -> Id -> [InAlt] -> SimplCont -> SimplM (SimplEnv, OutExpr)
1834 -- This isn't strictly an error, although it is unusual.
1835 -- It's possible that the simplifer might "see" that
1836 -- an inner case has no accessible alternatives before
1837 -- it "sees" that the entire branch of an outer case is
1838 -- inaccessible. So we simply put an error case here instead.
1839 missingAlt env case_bndr alts cont
1840 = WARN( True, ptext (sLit "missingAlt") <+> ppr case_bndr )
1841 return (env, mkImpossibleExpr res_ty)
1843 res_ty = contResultType env (substTy env (coreAltsType alts)) cont
1847 %************************************************************************
1849 \subsection{Duplicating continuations}
1851 %************************************************************************
1854 prepareCaseCont :: SimplEnv
1855 -> [InAlt] -> SimplCont
1856 -> SimplM (SimplEnv, SimplCont,SimplCont)
1857 -- Return a duplicatable continuation, a non-duplicable part
1858 -- plus some extra bindings (that scope over the entire
1861 -- No need to make it duplicatable if there's only one alternative
1862 prepareCaseCont env [_] cont = return (env, cont, mkBoringStop)
1863 prepareCaseCont env _ cont = mkDupableCont env cont
1867 mkDupableCont :: SimplEnv -> SimplCont
1868 -> SimplM (SimplEnv, SimplCont, SimplCont)
1870 mkDupableCont env cont
1871 | contIsDupable cont
1872 = return (env, cont, mkBoringStop)
1874 mkDupableCont _ (Stop {}) = panic "mkDupableCont" -- Handled by previous eqn
1876 mkDupableCont env (CoerceIt ty cont)
1877 = do { (env', dup, nodup) <- mkDupableCont env cont
1878 ; return (env', CoerceIt ty dup, nodup) }
1880 mkDupableCont env cont@(StrictBind {})
1881 = return (env, mkBoringStop, cont)
1882 -- See Note [Duplicating StrictBind]
1884 mkDupableCont env (StrictArg info cci cont)
1885 -- See Note [Duplicating StrictArg]
1886 = do { (env', dup, nodup) <- mkDupableCont env cont
1887 ; (env'', args') <- mapAccumLM makeTrivial env' (ai_args info)
1888 ; return (env'', StrictArg (info { ai_args = args' }) cci dup, nodup) }
1890 mkDupableCont env (ApplyTo _ arg se cont)
1891 = -- e.g. [...hole...] (...arg...)
1893 -- let a = ...arg...
1894 -- in [...hole...] a
1895 do { (env', dup_cont, nodup_cont) <- mkDupableCont env cont
1896 ; arg' <- simplExpr (se `setInScope` env') arg
1897 ; (env'', arg'') <- makeTrivial env' arg'
1898 ; let app_cont = ApplyTo OkToDup arg'' (zapSubstEnv env'') dup_cont
1899 ; return (env'', app_cont, nodup_cont) }
1901 mkDupableCont env cont@(Select _ case_bndr [(_, bs, _rhs)] _ _)
1902 -- See Note [Single-alternative case]
1903 -- | not (exprIsDupable rhs && contIsDupable case_cont)
1904 -- | not (isDeadBinder case_bndr)
1905 | all isDeadBinder bs -- InIds
1906 && not (isUnLiftedType (idType case_bndr))
1907 -- Note [Single-alternative-unlifted]
1908 = return (env, mkBoringStop, cont)
1910 mkDupableCont env (Select _ case_bndr alts se cont)
1911 = -- e.g. (case [...hole...] of { pi -> ei })
1913 -- let ji = \xij -> ei
1914 -- in case [...hole...] of { pi -> ji xij }
1915 do { tick (CaseOfCase case_bndr)
1916 ; (env', dup_cont, nodup_cont) <- mkDupableCont env cont
1917 -- NB: call mkDupableCont here, *not* prepareCaseCont
1918 -- We must make a duplicable continuation, whereas prepareCaseCont
1919 -- doesn't when there is a single case branch
1921 ; let alt_env = se `setInScope` env'
1922 ; (alt_env', case_bndr') <- simplBinder alt_env case_bndr
1923 ; alts' <- mapM (simplAlt alt_env' [] case_bndr' dup_cont) alts
1924 -- Safe to say that there are no handled-cons for the DEFAULT case
1925 -- NB: simplBinder does not zap deadness occ-info, so
1926 -- a dead case_bndr' will still advertise its deadness
1927 -- This is really important because in
1928 -- case e of b { (# p,q #) -> ... }
1929 -- b is always dead, and indeed we are not allowed to bind b to (# p,q #),
1930 -- which might happen if e was an explicit unboxed pair and b wasn't marked dead.
1931 -- In the new alts we build, we have the new case binder, so it must retain
1933 -- NB: we don't use alt_env further; it has the substEnv for
1934 -- the alternatives, and we don't want that
1936 ; (env'', alts'') <- mkDupableAlts env' case_bndr' alts'
1937 ; return (env'', -- Note [Duplicated env]
1938 Select OkToDup case_bndr' alts'' (zapSubstEnv env'') mkBoringStop,
1942 mkDupableAlts :: SimplEnv -> OutId -> [InAlt]
1943 -> SimplM (SimplEnv, [InAlt])
1944 -- Absorbs the continuation into the new alternatives
1946 mkDupableAlts env case_bndr' the_alts
1949 go env0 [] = return (env0, [])
1951 = do { (env1, alt') <- mkDupableAlt env0 case_bndr' alt
1952 ; (env2, alts') <- go env1 alts
1953 ; return (env2, alt' : alts' ) }
1955 mkDupableAlt :: SimplEnv -> OutId -> (AltCon, [CoreBndr], CoreExpr)
1956 -> SimplM (SimplEnv, (AltCon, [CoreBndr], CoreExpr))
1957 mkDupableAlt env case_bndr (con, bndrs', rhs')
1958 | exprIsDupable rhs' -- Note [Small alternative rhs]
1959 = return (env, (con, bndrs', rhs'))
1961 = do { let rhs_ty' = exprType rhs'
1962 scrut_ty = idType case_bndr
1965 DEFAULT -> case_bndr
1966 DataAlt dc -> setIdUnfolding case_bndr unf
1968 -- See Note [Case binders and join points]
1969 unf = mkInlineRule needSaturated rhs 0
1970 rhs = mkConApp dc (map Type (tyConAppArgs scrut_ty)
1971 ++ varsToCoreExprs bndrs')
1973 LitAlt {} -> WARN( True, ptext (sLit "mkDupableAlt")
1974 <+> ppr case_bndr <+> ppr con )
1976 -- The case binder is alive but trivial, so why has
1977 -- it not been substituted away?
1979 used_bndrs' | isDeadBinder case_bndr = filter abstract_over bndrs'
1980 | otherwise = bndrs' ++ [case_bndr_w_unf]
1983 | isTyVar bndr = True -- Abstract over all type variables just in case
1984 | otherwise = not (isDeadBinder bndr)
1985 -- The deadness info on the new Ids is preserved by simplBinders
1987 ; (final_bndrs', final_args) -- Note [Join point abstraction]
1988 <- if (any isId used_bndrs')
1989 then return (used_bndrs', varsToCoreExprs used_bndrs')
1990 else do { rw_id <- newId (fsLit "w") realWorldStatePrimTy
1991 ; return ([rw_id], [Var realWorldPrimId]) }
1993 ; join_bndr <- newId (fsLit "$j") (mkPiTypes final_bndrs' rhs_ty')
1994 -- Note [Funky mkPiTypes]
1996 ; let -- We make the lambdas into one-shot-lambdas. The
1997 -- join point is sure to be applied at most once, and doing so
1998 -- prevents the body of the join point being floated out by
1999 -- the full laziness pass
2000 really_final_bndrs = map one_shot final_bndrs'
2001 one_shot v | isId v = setOneShotLambda v
2003 join_rhs = mkLams really_final_bndrs rhs'
2004 join_call = mkApps (Var join_bndr) final_args
2006 ; env' <- addPolyBind NotTopLevel env (NonRec join_bndr join_rhs)
2007 ; return (env', (con, bndrs', join_call)) }
2008 -- See Note [Duplicated env]
2011 Note [Case binders and join points]
2012 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2014 case (case .. ) of c {
2017 If we make a join point with c but not c# we get
2018 $j = \c -> ....c....
2020 But if later inlining scrutines the c, thus
2022 $j = \c -> ... case c of { I# y -> ... } ...
2024 we won't see that 'c' has already been scrutinised. This actually
2025 happens in the 'tabulate' function in wave4main, and makes a significant
2026 difference to allocation.
2028 An alternative plan is this:
2030 $j = \c# -> let c = I# c# in ...c....
2032 but that is bad if 'c' is *not* later scrutinised.
2034 So instead we do both: we pass 'c' and 'c#' , and record in c's inlining
2035 that it's really I# c#, thus
2037 $j = \c# -> \c[=I# c#] -> ...c....
2039 Absence analysis may later discard 'c'.
2042 Note [Duplicated env]
2043 ~~~~~~~~~~~~~~~~~~~~~
2044 Some of the alternatives are simplified, but have not been turned into a join point
2045 So they *must* have an zapped subst-env. So we can't use completeNonRecX to
2046 bind the join point, because it might to do PostInlineUnconditionally, and
2047 we'd lose that when zapping the subst-env. We could have a per-alt subst-env,
2048 but zapping it (as we do in mkDupableCont, the Select case) is safe, and
2049 at worst delays the join-point inlining.
2051 Note [Small alternative rhs]
2052 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2053 It is worth checking for a small RHS because otherwise we
2054 get extra let bindings that may cause an extra iteration of the simplifier to
2055 inline back in place. Quite often the rhs is just a variable or constructor.
2056 The Ord instance of Maybe in PrelMaybe.lhs, for example, took several extra
2057 iterations because the version with the let bindings looked big, and so wasn't
2058 inlined, but after the join points had been inlined it looked smaller, and so
2061 NB: we have to check the size of rhs', not rhs.
2062 Duplicating a small InAlt might invalidate occurrence information
2063 However, if it *is* dupable, we return the *un* simplified alternative,
2064 because otherwise we'd need to pair it up with an empty subst-env....
2065 but we only have one env shared between all the alts.
2066 (Remember we must zap the subst-env before re-simplifying something).
2067 Rather than do this we simply agree to re-simplify the original (small) thing later.
2069 Note [Funky mkPiTypes]
2070 ~~~~~~~~~~~~~~~~~~~~~~
2071 Notice the funky mkPiTypes. If the contructor has existentials
2072 it's possible that the join point will be abstracted over
2073 type varaibles as well as term variables.
2074 Example: Suppose we have
2075 data T = forall t. C [t]
2077 case (case e of ...) of
2079 We get the join point
2080 let j :: forall t. [t] -> ...
2081 j = /\t \xs::[t] -> rhs
2083 case (case e of ...) of
2084 C t xs::[t] -> j t xs
2086 Note [Join point abstaction]
2087 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2088 If we try to lift a primitive-typed something out
2089 for let-binding-purposes, we will *caseify* it (!),
2090 with potentially-disastrous strictness results. So
2091 instead we turn it into a function: \v -> e
2092 where v::State# RealWorld#. The value passed to this function
2093 is realworld#, which generates (almost) no code.
2095 There's a slight infelicity here: we pass the overall
2096 case_bndr to all the join points if it's used in *any* RHS,
2097 because we don't know its usage in each RHS separately
2099 We used to say "&& isUnLiftedType rhs_ty'" here, but now
2100 we make the join point into a function whenever used_bndrs'
2101 is empty. This makes the join-point more CPR friendly.
2102 Consider: let j = if .. then I# 3 else I# 4
2103 in case .. of { A -> j; B -> j; C -> ... }
2105 Now CPR doesn't w/w j because it's a thunk, so
2106 that means that the enclosing function can't w/w either,
2107 which is a lose. Here's the example that happened in practice:
2108 kgmod :: Int -> Int -> Int
2109 kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
2113 I have seen a case alternative like this:
2115 It's a bit silly to add the realWorld dummy arg in this case, making
2118 (the \v alone is enough to make CPR happy) but I think it's rare
2120 Note [Duplicating StrictArg]
2121 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2122 The original plan had (where E is a big argument)
2124 ==> let $j = \a -> f E a
2127 But this is terrible! Here's an example:
2128 && E (case x of { T -> F; F -> T })
2129 Now, && is strict so we end up simplifying the case with
2130 an ArgOf continuation. If we let-bind it, we get
2131 let $j = \v -> && E v
2132 in simplExpr (case x of { T -> F; F -> T })
2134 And after simplifying more we get
2135 let $j = \v -> && E v
2136 in case x of { T -> $j F; F -> $j T }
2137 Which is a Very Bad Thing
2139 What we do now is this
2143 Now if the thing in the hole is a case expression (which is when
2144 we'll call mkDupableCont), we'll push the function call into the
2145 branches, which is what we want. Now RULES for f may fire, and
2146 call-pattern specialisation. Here's an example from Trac #3116
2149 _ -> Chunk p fpc (o+1) (l-1) bs')
2150 If we can push the call for 'go' inside the case, we get
2151 call-pattern specialisation for 'go', which is *crucial* for
2154 Here is the (&&) example:
2155 && E (case x of { T -> F; F -> T })
2157 case x of { T -> && a F; F -> && a T }
2161 * Arguments to f *after* the strict one are handled by
2162 the ApplyTo case of mkDupableCont. Eg
2165 * We can only do the let-binding of E because the function
2166 part of a StrictArg continuation is an explicit syntax
2167 tree. In earlier versions we represented it as a function
2168 (CoreExpr -> CoreEpxr) which we couldn't take apart.
2170 Do *not* duplicate StrictBind and StritArg continuations. We gain
2171 nothing by propagating them into the expressions, and we do lose a
2174 The desire not to duplicate is the entire reason that
2175 mkDupableCont returns a pair of continuations.
2177 Note [Duplicating StrictBind]
2178 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2179 Unlike StrictArg, there doesn't seem anything to gain from
2180 duplicating a StrictBind continuation, so we don't.
2182 The desire not to duplicate is the entire reason that
2183 mkDupableCont returns a pair of continuations.
2186 Note [Single-alternative cases]
2187 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2188 This case is just like the ArgOf case. Here's an example:
2192 case (case x of I# x' ->
2194 True -> I# (negate# x')
2195 False -> I# x') of y {
2197 Because the (case x) has only one alternative, we'll transform to
2199 case (case x' <# 0# of
2200 True -> I# (negate# x')
2201 False -> I# x') of y {
2203 But now we do *NOT* want to make a join point etc, giving
2205 let $j = \y -> MkT y
2207 True -> $j (I# (negate# x'))
2209 In this case the $j will inline again, but suppose there was a big
2210 strict computation enclosing the orginal call to MkT. Then, it won't
2211 "see" the MkT any more, because it's big and won't get duplicated.
2212 And, what is worse, nothing was gained by the case-of-case transform.
2214 When should use this case of mkDupableCont?
2215 However, matching on *any* single-alternative case is a *disaster*;
2216 e.g. case (case ....) of (a,b) -> (# a,b #)
2217 We must push the outer case into the inner one!
2220 * Match [(DEFAULT,_,_)], but in the common case of Int,
2221 the alternative-filling-in code turned the outer case into
2222 case (...) of y { I# _ -> MkT y }
2224 * Match on single alternative plus (not (isDeadBinder case_bndr))
2225 Rationale: pushing the case inwards won't eliminate the construction.
2226 But there's a risk of
2227 case (...) of y { (a,b) -> let z=(a,b) in ... }
2228 Now y looks dead, but it'll come alive again. Still, this
2229 seems like the best option at the moment.
2231 * Match on single alternative plus (all (isDeadBinder bndrs))
2232 Rationale: this is essentially seq.
2234 * Match when the rhs is *not* duplicable, and hence would lead to a
2235 join point. This catches the disaster-case above. We can test
2236 the *un-simplified* rhs, which is fine. It might get bigger or
2237 smaller after simplification; if it gets smaller, this case might
2238 fire next time round. NB also that we must test contIsDupable
2239 case_cont *btoo, because case_cont might be big!
2241 HOWEVER: I found that this version doesn't work well, because
2242 we can get let x = case (...) of { small } in ...case x...
2243 When x is inlined into its full context, we find that it was a bad
2244 idea to have pushed the outer case inside the (...) case.
2246 Note [Single-alternative-unlifted]
2247 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2248 Here's another single-alternative where we really want to do case-of-case:
2256 case y_s6X of tpl_s7m {
2257 M1.Mk1 ipv_s70 -> ipv_s70;
2258 M1.Mk2 ipv_s72 -> ipv_s72;
2264 case x_s74 of tpl_s7n {
2265 M1.Mk1 ipv_s77 -> ipv_s77;
2266 M1.Mk2 ipv_s79 -> ipv_s79;
2270 { __DEFAULT -> ==# [wild1_s7b wild_s7c];
2274 So the outer case is doing *nothing at all*, other than serving as a
2275 join-point. In this case we really want to do case-of-case and decide
2276 whether to use a real join point or just duplicate the continuation.
2278 Hence: check whether the case binder's type is unlifted, because then
2279 the outer case is *not* a seq.