2 % (c) The AQUA Project, Glasgow University, 1993-1998
4 \section[SimplUtils]{The simplifier utilities}
12 preInlineUnconditionally, postInlineUnconditionally,
13 activeInline, activeRule, inlineMode,
15 -- The continuation type
16 SimplCont(..), DupFlag(..), LetRhsFlag(..),
17 contIsDupable, contResultType, contIsTrivial, contArgs, dropArgs,
18 countValArgs, countArgs,
19 mkBoringStop, mkLazyArgStop, mkRhsStop, contIsRhsOrArg,
20 interestingCallContext, interestingArgContext,
22 interestingArg, isStrictBndr, mkArgInfo
25 #include "HsVersions.h"
50 %************************************************************************
54 %************************************************************************
56 A SimplCont allows the simplifier to traverse the expression in a
57 zipper-like fashion. The SimplCont represents the rest of the expression,
58 "above" the point of interest.
60 You can also think of a SimplCont as an "evaluation context", using
61 that term in the way it is used for operational semantics. This is the
62 way I usually think of it, For example you'll often see a syntax for
63 evaluation context looking like
64 C ::= [] | C e | case C of alts | C `cast` co
65 That's the kind of thing we are doing here, and I use that syntax in
70 * A SimplCont describes a *strict* context (just like
71 evaluation contexts do). E.g. Just [] is not a SimplCont
73 * A SimplCont describes a context that *does not* bind
74 any variables. E.g. \x. [] is not a SimplCont
78 = Stop -- An empty context, or hole, []
79 OutType -- Type of the result
81 Bool -- True <=> There is something interesting about
82 -- the context, and hence the inliner
83 -- should be a bit keener (see interestingCallContext)
85 -- (a) This is the RHS of a thunk whose type suggests
86 -- that update-in-place would be possible
87 -- (b) This is an argument of a function that has RULES
88 -- Inlining the call might allow the rule to fire
90 | CoerceIt -- C `cast` co
91 OutCoercion -- The coercion simplified
96 InExpr SimplEnv -- The argument and its static env
99 | Select -- case C of alts
101 InId [InAlt] SimplEnv -- The case binder, alts, and subst-env
104 -- The two strict forms have no DupFlag, because we never duplicate them
105 | StrictBind -- (\x* \xs. e) C
106 InId [InBndr] -- let x* = [] in e
107 InExpr SimplEnv -- is a special case
111 OutExpr OutType -- e and its type
112 (Bool,[Bool]) -- Whether the function at the head of e has rules,
113 SimplCont -- plus strictness flags for further args
115 data LetRhsFlag = AnArg -- It's just an argument not a let RHS
116 | AnRhs -- It's the RHS of a let (so please float lets out of big lambdas)
118 instance Outputable LetRhsFlag where
119 ppr AnArg = ptext SLIT("arg")
120 ppr AnRhs = ptext SLIT("rhs")
122 instance Outputable SimplCont where
123 ppr (Stop ty is_rhs _) = ptext SLIT("Stop") <> brackets (ppr is_rhs) <+> ppr ty
124 ppr (ApplyTo dup arg se cont) = ((ptext SLIT("ApplyTo") <+> ppr dup <+> pprParendExpr arg) $$
125 nest 2 (pprSimplEnv se)) $$ ppr cont
126 ppr (StrictBind b _ _ _ cont) = (ptext SLIT("StrictBind") <+> ppr b) $$ ppr cont
127 ppr (StrictArg f _ _ cont) = (ptext SLIT("StrictArg") <+> ppr f) $$ ppr cont
128 ppr (Select dup bndr alts se cont) = (ptext SLIT("Select") <+> ppr dup <+> ppr bndr) $$
129 (nest 4 (ppr alts $$ pprSimplEnv se)) $$ ppr cont
130 ppr (CoerceIt co cont) = (ptext SLIT("CoerceIt") <+> ppr co) $$ ppr cont
132 data DupFlag = OkToDup | NoDup
134 instance Outputable DupFlag where
135 ppr OkToDup = ptext SLIT("ok")
136 ppr NoDup = ptext SLIT("nodup")
141 mkBoringStop :: OutType -> SimplCont
142 mkBoringStop ty = Stop ty AnArg False
144 mkLazyArgStop :: OutType -> Bool -> SimplCont
145 mkLazyArgStop ty has_rules = Stop ty AnArg (canUpdateInPlace ty || has_rules)
147 mkRhsStop :: OutType -> SimplCont
148 mkRhsStop ty = Stop ty AnRhs (canUpdateInPlace ty)
150 contIsRhsOrArg (Stop _ _ _) = True
151 contIsRhsOrArg (StrictBind {}) = True
152 contIsRhsOrArg (StrictArg {}) = True
153 contIsRhsOrArg other = False
156 contIsDupable :: SimplCont -> Bool
157 contIsDupable (Stop _ _ _) = True
158 contIsDupable (ApplyTo OkToDup _ _ _) = True
159 contIsDupable (Select OkToDup _ _ _ _) = True
160 contIsDupable (CoerceIt _ cont) = contIsDupable cont
161 contIsDupable other = False
164 contIsTrivial :: SimplCont -> Bool
165 contIsTrivial (Stop _ _ _) = True
166 contIsTrivial (ApplyTo _ (Type _) _ cont) = contIsTrivial cont
167 contIsTrivial (CoerceIt _ cont) = contIsTrivial cont
168 contIsTrivial other = False
171 contResultType :: SimplCont -> OutType
172 contResultType (Stop to_ty _ _) = to_ty
173 contResultType (StrictArg _ _ _ cont) = contResultType cont
174 contResultType (StrictBind _ _ _ _ cont) = contResultType cont
175 contResultType (ApplyTo _ _ _ cont) = contResultType cont
176 contResultType (CoerceIt _ cont) = contResultType cont
177 contResultType (Select _ _ _ _ cont) = contResultType cont
180 countValArgs :: SimplCont -> Int
181 countValArgs (ApplyTo _ (Type ty) se cont) = countValArgs cont
182 countValArgs (ApplyTo _ val_arg se cont) = 1 + countValArgs cont
183 countValArgs other = 0
185 countArgs :: SimplCont -> Int
186 countArgs (ApplyTo _ arg se cont) = 1 + countArgs cont
189 contArgs :: SimplCont -> ([OutExpr], SimplCont)
190 -- Uses substitution to turn each arg into an OutExpr
191 contArgs cont = go [] cont
193 go args (ApplyTo _ arg se cont) = go (substExpr se arg : args) cont
194 go args cont = (reverse args, cont)
196 dropArgs :: Int -> SimplCont -> SimplCont
197 dropArgs 0 cont = cont
198 dropArgs n (ApplyTo _ _ _ cont) = dropArgs (n-1) cont
199 dropArgs n other = pprPanic "dropArgs" (ppr n <+> ppr other)
204 interestingArg :: OutExpr -> Bool
205 -- An argument is interesting if it has *some* structure
206 -- We are here trying to avoid unfolding a function that
207 -- is applied only to variables that have no unfolding
208 -- (i.e. they are probably lambda bound): f x y z
209 -- There is little point in inlining f here.
210 interestingArg (Var v) = hasSomeUnfolding (idUnfolding v)
211 -- Was: isValueUnfolding (idUnfolding v')
212 -- But that seems over-pessimistic
214 -- This accounts for an argument like
215 -- () or [], which is definitely interesting
216 interestingArg (Type _) = False
217 interestingArg (App fn (Type _)) = interestingArg fn
218 interestingArg (Note _ a) = interestingArg a
220 -- Idea (from Sam B); I'm not sure if it's a good idea, so commented out for now
221 -- interestingArg expr | isUnLiftedType (exprType expr)
222 -- -- Unlifted args are only ever interesting if we know what they are
227 interestingArg other = True
228 -- Consider let x = 3 in f x
229 -- The substitution will contain (x -> ContEx 3), and we want to
230 -- to say that x is an interesting argument.
231 -- But consider also (\x. f x y) y
232 -- The substitution will contain (x -> ContEx y), and we want to say
233 -- that x is not interesting (assuming y has no unfolding)
237 Comment about interestingCallContext
238 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
239 We want to avoid inlining an expression where there can't possibly be
240 any gain, such as in an argument position. Hence, if the continuation
241 is interesting (eg. a case scrutinee, application etc.) then we
242 inline, otherwise we don't.
244 Previously some_benefit used to return True only if the variable was
245 applied to some value arguments. This didn't work:
247 let x = _coerce_ (T Int) Int (I# 3) in
248 case _coerce_ Int (T Int) x of
251 we want to inline x, but can't see that it's a constructor in a case
252 scrutinee position, and some_benefit is False.
256 dMonadST = _/\_ t -> :Monad (g1 _@_ t, g2 _@_ t, g3 _@_ t)
258 .... case dMonadST _@_ x0 of (a,b,c) -> ....
260 we'd really like to inline dMonadST here, but we *don't* want to
261 inline if the case expression is just
263 case x of y { DEFAULT -> ... }
265 since we can just eliminate this case instead (x is in WHNF). Similar
266 applies when x is bound to a lambda expression. Hence
267 contIsInteresting looks for case expressions with just a single
271 interestingCallContext :: Bool -- False <=> no args at all
272 -> Bool -- False <=> no value args
274 -- The "lone-variable" case is important. I spent ages
275 -- messing about with unsatisfactory varaints, but this is nice.
276 -- The idea is that if a variable appear all alone
277 -- as an arg of lazy fn, or rhs Stop
278 -- as scrutinee of a case Select
279 -- as arg of a strict fn ArgOf
280 -- then we should not inline it (unless there is some other reason,
281 -- e.g. is is the sole occurrence). We achieve this by making
282 -- interestingCallContext return False for a lone variable.
284 -- Why? At least in the case-scrutinee situation, turning
285 -- let x = (a,b) in case x of y -> ...
287 -- let x = (a,b) in case (a,b) of y -> ...
289 -- let x = (a,b) in let y = (a,b) in ...
290 -- is bad if the binding for x will remain.
292 -- Another example: I discovered that strings
293 -- were getting inlined straight back into applications of 'error'
294 -- because the latter is strict.
296 -- f = \x -> ...(error s)...
298 -- Fundamentally such contexts should not ecourage inlining because
299 -- the context can ``see'' the unfolding of the variable (e.g. case or a RULE)
300 -- so there's no gain.
302 -- However, even a type application or coercion isn't a lone variable.
304 -- case $fMonadST @ RealWorld of { :DMonad a b c -> c }
305 -- We had better inline that sucker! The case won't see through it.
307 -- For now, I'm treating treating a variable applied to types
308 -- in a *lazy* context "lone". The motivating example was
310 -- g = /\a. \y. h (f a)
311 -- There's no advantage in inlining f here, and perhaps
312 -- a significant disadvantage. Hence some_val_args in the Stop case
314 interestingCallContext some_args some_val_args cont
317 interesting (Select {}) = some_args
318 interesting (ApplyTo {}) = True -- Can happen if we have (coerce t (f x)) y
319 -- Perhaps True is a bit over-keen, but I've
320 -- seen (coerce f) x, where f has an INLINE prag,
321 -- So we have to give some motivaiton for inlining it
322 interesting (StrictArg {}) = some_val_args
323 interesting (StrictBind {}) = some_val_args -- ??
324 interesting (Stop ty _ interesting) = some_val_args && interesting
325 interesting (CoerceIt _ cont) = interesting cont
326 -- If this call is the arg of a strict function, the context
327 -- is a bit interesting. If we inline here, we may get useful
328 -- evaluation information to avoid repeated evals: e.g.
330 -- Here the contIsInteresting makes the '*' keener to inline,
331 -- which in turn exposes a constructor which makes the '+' inline.
332 -- Assuming that +,* aren't small enough to inline regardless.
334 -- It's also very important to inline in a strict context for things
337 -- Here, the context of (f x) is strict, and if f's unfolding is
338 -- a build it's *great* to inline it here. So we must ensure that
339 -- the context for (f x) is not totally uninteresting.
344 -> Int -- Number of value args
345 -> SimplCont -- Context of the cal
346 -> (Bool, [Bool]) -- Arg info
347 -- The arg info consists of
348 -- * A Bool indicating if the function has rules (recursively)
349 -- * A [Bool] indicating strictness for each arg
350 -- The [Bool] is usually infinite, but if it is finite it
351 -- guarantees that the function diverges after being given
352 -- that number of args
354 mkArgInfo fun n_val_args call_cont
355 = (interestingArgContext fun call_cont, fun_stricts)
357 vanilla_stricts, fun_stricts :: [Bool]
358 vanilla_stricts = repeat False
361 = case splitStrictSig (idNewStrictness fun) of
362 (demands, result_info)
363 | not (demands `lengthExceeds` n_val_args)
364 -> -- Enough args, use the strictness given.
365 -- For bottoming functions we used to pretend that the arg
366 -- is lazy, so that we don't treat the arg as an
367 -- interesting context. This avoids substituting
368 -- top-level bindings for (say) strings into
369 -- calls to error. But now we are more careful about
370 -- inlining lone variables, so its ok (see SimplUtils.analyseCont)
371 if isBotRes result_info then
372 map isStrictDmd demands -- Finite => result is bottom
374 map isStrictDmd demands ++ vanilla_stricts
376 other -> vanilla_stricts -- Not enough args, or no strictness
378 interestingArgContext :: Id -> SimplCont -> Bool
379 -- If the argument has form (f x y), where x,y are boring,
380 -- and f is marked INLINE, then we don't want to inline f.
381 -- But if the context of the argument is
383 -- where g has rules, then we *do* want to inline f, in case it
384 -- exposes a rule that might fire. Similarly, if the context is
386 -- where h has rules, then we do want to inline f.
387 -- The interesting_arg_ctxt flag makes this happen; if it's
388 -- set, the inliner gets just enough keener to inline f
389 -- regardless of how boring f's arguments are, if it's marked INLINE
391 -- The alternative would be to *always* inline an INLINE function,
392 -- regardless of how boring its context is; but that seems overkill
393 -- For example, it'd mean that wrapper functions were always inlined
394 interestingArgContext fn cont
395 = idHasRules fn || go cont
397 go (Select {}) = False
398 go (ApplyTo {}) = False
399 go (StrictArg {}) = True
400 go (StrictBind {}) = False -- ??
401 go (CoerceIt _ c) = go c
402 go (Stop _ _ interesting) = interesting
405 canUpdateInPlace :: Type -> Bool
406 -- Consider let x = <wurble> in ...
407 -- If <wurble> returns an explicit constructor, we might be able
408 -- to do update in place. So we treat even a thunk RHS context
409 -- as interesting if update in place is possible. We approximate
410 -- this by seeing if the type has a single constructor with a
411 -- small arity. But arity zero isn't good -- we share the single copy
412 -- for that case, so no point in sharing.
415 | not opt_UF_UpdateInPlace = False
417 = case splitTyConApp_maybe ty of
419 Just (tycon, _) -> case tyConDataCons_maybe tycon of
420 Just [dc] -> arity == 1 || arity == 2
422 arity = dataConRepArity dc
428 %************************************************************************
430 \subsection{Decisions about inlining}
432 %************************************************************************
434 Inlining is controlled partly by the SimplifierMode switch. This has two
437 SimplGently (a) Simplifying before specialiser/full laziness
438 (b) Simplifiying inside INLINE pragma
439 (c) Simplifying the LHS of a rule
440 (d) Simplifying a GHCi expression or Template
443 SimplPhase n Used at all other times
445 The key thing about SimplGently is that it does no call-site inlining.
446 Before full laziness we must be careful not to inline wrappers,
447 because doing so inhibits floating
448 e.g. ...(case f x of ...)...
449 ==> ...(case (case x of I# x# -> fw x#) of ...)...
450 ==> ...(case x of I# x# -> case fw x# of ...)...
451 and now the redex (f x) isn't floatable any more.
453 The no-inlining thing is also important for Template Haskell. You might be
454 compiling in one-shot mode with -O2; but when TH compiles a splice before
455 running it, we don't want to use -O2. Indeed, we don't want to inline
456 anything, because the byte-code interpreter might get confused about
457 unboxed tuples and suchlike.
461 SimplGently is also used as the mode to simplify inside an InlineMe note.
464 inlineMode :: SimplifierMode
465 inlineMode = SimplGently
468 It really is important to switch off inlinings inside such
469 expressions. Consider the following example
475 in ...g...g...g...g...g...
477 Now, if that's the ONLY occurrence of f, it will be inlined inside g,
478 and thence copied multiple times when g is inlined.
481 This function may be inlinined in other modules, so we
482 don't want to remove (by inlining) calls to functions that have
483 specialisations, or that may have transformation rules in an importing
486 E.g. {-# INLINE f #-}
489 and suppose that g is strict *and* has specialisations. If we inline
490 g's wrapper, we deny f the chance of getting the specialised version
491 of g when f is inlined at some call site (perhaps in some other
494 It's also important not to inline a worker back into a wrapper.
496 wraper = inline_me (\x -> ...worker... )
497 Normally, the inline_me prevents the worker getting inlined into
498 the wrapper (initially, the worker's only call site!). But,
499 if the wrapper is sure to be called, the strictness analyser will
500 mark it 'demanded', so when the RHS is simplified, it'll get an ArgOf
501 continuation. That's why the keep_inline predicate returns True for
502 ArgOf continuations. It shouldn't do any harm not to dissolve the
503 inline-me note under these circumstances.
505 Note that the result is that we do very little simplification
508 all xs = foldr (&&) True xs
509 any p = all . map p {-# INLINE any #-}
511 Problem: any won't get deforested, and so if it's exported and the
512 importer doesn't use the inlining, (eg passes it as an arg) then we
513 won't get deforestation at all. We havn't solved this problem yet!
516 preInlineUnconditionally
517 ~~~~~~~~~~~~~~~~~~~~~~~~
518 @preInlineUnconditionally@ examines a bndr to see if it is used just
519 once in a completely safe way, so that it is safe to discard the
520 binding inline its RHS at the (unique) usage site, REGARDLESS of how
521 big the RHS might be. If this is the case we don't simplify the RHS
522 first, but just inline it un-simplified.
524 This is much better than first simplifying a perhaps-huge RHS and then
525 inlining and re-simplifying it. Indeed, it can be at least quadratically
534 We may end up simplifying e1 N times, e2 N-1 times, e3 N-3 times etc.
535 This can happen with cascades of functions too:
542 THE MAIN INVARIANT is this:
544 ---- preInlineUnconditionally invariant -----
545 IF preInlineUnconditionally chooses to inline x = <rhs>
546 THEN doing the inlining should not change the occurrence
547 info for the free vars of <rhs>
548 ----------------------------------------------
550 For example, it's tempting to look at trivial binding like
552 and inline it unconditionally. But suppose x is used many times,
553 but this is the unique occurrence of y. Then inlining x would change
554 y's occurrence info, which breaks the invariant. It matters: y
555 might have a BIG rhs, which will now be dup'd at every occurrenc of x.
558 Evne RHSs labelled InlineMe aren't caught here, because there might be
559 no benefit from inlining at the call site.
561 [Sept 01] Don't unconditionally inline a top-level thing, because that
562 can simply make a static thing into something built dynamically. E.g.
566 [Remember that we treat \s as a one-shot lambda.] No point in
567 inlining x unless there is something interesting about the call site.
569 But watch out: if you aren't careful, some useful foldr/build fusion
570 can be lost (most notably in spectral/hartel/parstof) because the
571 foldr didn't see the build. Doing the dynamic allocation isn't a big
572 deal, in fact, but losing the fusion can be. But the right thing here
573 seems to be to do a callSiteInline based on the fact that there is
574 something interesting about the call site (it's strict). Hmm. That
577 Conclusion: inline top level things gaily until Phase 0 (the last
578 phase), at which point don't.
581 preInlineUnconditionally :: SimplEnv -> TopLevelFlag -> InId -> InExpr -> Bool
582 preInlineUnconditionally env top_lvl bndr rhs
584 | opt_SimplNoPreInlining = False
585 | otherwise = case idOccInfo bndr of
586 IAmDead -> True -- Happens in ((\x.1) v)
587 OneOcc in_lam True int_cxt -> try_once in_lam int_cxt
591 active = case phase of
592 SimplGently -> isAlwaysActive prag
593 SimplPhase n -> isActive n prag
594 prag = idInlinePragma bndr
596 try_once in_lam int_cxt -- There's one textual occurrence
597 | not in_lam = isNotTopLevel top_lvl || early_phase
598 | otherwise = int_cxt && canInlineInLam rhs
600 -- Be very careful before inlining inside a lambda, becuase (a) we must not
601 -- invalidate occurrence information, and (b) we want to avoid pushing a
602 -- single allocation (here) into multiple allocations (inside lambda).
603 -- Inlining a *function* with a single *saturated* call would be ok, mind you.
604 -- || (if is_cheap && not (canInlineInLam rhs) then pprTrace "preinline" (ppr bndr <+> ppr rhs) ok else ok)
606 -- is_cheap = exprIsCheap rhs
607 -- ok = is_cheap && int_cxt
609 -- int_cxt The context isn't totally boring
610 -- E.g. let f = \ab.BIG in \y. map f xs
611 -- Don't want to substitute for f, because then we allocate
612 -- its closure every time the \y is called
613 -- But: let f = \ab.BIG in \y. map (f y) xs
614 -- Now we do want to substitute for f, even though it's not
615 -- saturated, because we're going to allocate a closure for
616 -- (f y) every time round the loop anyhow.
618 -- canInlineInLam => free vars of rhs are (Once in_lam) or Many,
619 -- so substituting rhs inside a lambda doesn't change the occ info.
620 -- Sadly, not quite the same as exprIsHNF.
621 canInlineInLam (Lit l) = True
622 canInlineInLam (Lam b e) = isRuntimeVar b || canInlineInLam e
623 canInlineInLam (Note _ e) = canInlineInLam e
624 canInlineInLam _ = False
626 early_phase = case phase of
627 SimplPhase 0 -> False
629 -- If we don't have this early_phase test, consider
630 -- x = length [1,2,3]
631 -- The full laziness pass carefully floats all the cons cells to
632 -- top level, and preInlineUnconditionally floats them all back in.
633 -- Result is (a) static allocation replaced by dynamic allocation
634 -- (b) many simplifier iterations because this tickles
635 -- a related problem; only one inlining per pass
637 -- On the other hand, I have seen cases where top-level fusion is
638 -- lost if we don't inline top level thing (e.g. string constants)
639 -- Hence the test for phase zero (which is the phase for all the final
640 -- simplifications). Until phase zero we take no special notice of
641 -- top level things, but then we become more leery about inlining
646 postInlineUnconditionally
647 ~~~~~~~~~~~~~~~~~~~~~~~~~
648 @postInlineUnconditionally@ decides whether to unconditionally inline
649 a thing based on the form of its RHS; in particular if it has a
650 trivial RHS. If so, we can inline and discard the binding altogether.
652 NB: a loop breaker has must_keep_binding = True and non-loop-breakers
653 only have *forward* references Hence, it's safe to discard the binding
655 NOTE: This isn't our last opportunity to inline. We're at the binding
656 site right now, and we'll get another opportunity when we get to the
659 Note that we do this unconditional inlining only for trival RHSs.
660 Don't inline even WHNFs inside lambdas; doing so may simply increase
661 allocation when the function is called. This isn't the last chance; see
664 NB: Even inline pragmas (e.g. IMustBeINLINEd) are ignored here Why?
665 Because we don't even want to inline them into the RHS of constructor
666 arguments. See NOTE above
668 NB: At one time even NOINLINE was ignored here: if the rhs is trivial
669 it's best to inline it anyway. We often get a=E; b=a from desugaring,
670 with both a and b marked NOINLINE. But that seems incompatible with
671 our new view that inlining is like a RULE, so I'm sticking to the 'active'
675 postInlineUnconditionally
676 :: SimplEnv -> TopLevelFlag
677 -> InId -- The binder (an OutId would be fine too)
678 -> OccInfo -- From the InId
682 postInlineUnconditionally env top_lvl bndr occ_info rhs unfolding
684 | isLoopBreaker occ_info = False -- If it's a loop-breaker of any kind, dont' inline
685 -- because it might be referred to "earlier"
686 | isExportedId bndr = False
687 | exprIsTrivial rhs = True
690 -- The point of examining occ_info here is that for *non-values*
691 -- that occur outside a lambda, the call-site inliner won't have
692 -- a chance (becuase it doesn't know that the thing
693 -- only occurs once). The pre-inliner won't have gotten
694 -- it either, if the thing occurs in more than one branch
695 -- So the main target is things like
698 -- True -> case x of ...
699 -- False -> case x of ...
700 -- I'm not sure how important this is in practice
701 OneOcc in_lam one_br int_cxt -- OneOcc => no code-duplication issue
702 -> smallEnoughToInline unfolding -- Small enough to dup
703 -- ToDo: consider discount on smallEnoughToInline if int_cxt is true
705 -- NB: Do NOT inline arbitrarily big things, even if one_br is True
706 -- Reason: doing so risks exponential behaviour. We simplify a big
707 -- expression, inline it, and simplify it again. But if the
708 -- very same thing happens in the big expression, we get
710 -- PRINCIPLE: when we've already simplified an expression once,
711 -- make sure that we only inline it if it's reasonably small.
713 && ((isNotTopLevel top_lvl && not in_lam) ||
714 -- But outside a lambda, we want to be reasonably aggressive
715 -- about inlining into multiple branches of case
716 -- e.g. let x = <non-value>
717 -- in case y of { C1 -> ..x..; C2 -> ..x..; C3 -> ... }
718 -- Inlining can be a big win if C3 is the hot-spot, even if
719 -- the uses in C1, C2 are not 'interesting'
720 -- An example that gets worse if you add int_cxt here is 'clausify'
722 (isCheapUnfolding unfolding && int_cxt))
723 -- isCheap => acceptable work duplication; in_lam may be true
724 -- int_cxt to prevent us inlining inside a lambda without some
725 -- good reason. See the notes on int_cxt in preInlineUnconditionally
727 IAmDead -> True -- This happens; for example, the case_bndr during case of
728 -- known constructor: case (a,b) of x { (p,q) -> ... }
729 -- Here x isn't mentioned in the RHS, so we don't want to
730 -- create the (dead) let-binding let x = (a,b) in ...
734 -- Here's an example that we don't handle well:
735 -- let f = if b then Left (\x.BIG) else Right (\y.BIG)
736 -- in \y. ....case f of {...} ....
737 -- Here f is used just once, and duplicating the case work is fine (exprIsCheap).
739 -- * We can't preInlineUnconditionally because that woud invalidate
740 -- the occ info for b.
741 -- * We can't postInlineUnconditionally because the RHS is big, and
742 -- that risks exponential behaviour
743 -- * We can't call-site inline, because the rhs is big
747 active = case getMode env of
748 SimplGently -> isAlwaysActive prag
749 SimplPhase n -> isActive n prag
750 prag = idInlinePragma bndr
752 activeInline :: SimplEnv -> OutId -> Bool
754 = case getMode env of
756 -- No inlining at all when doing gentle stuff,
757 -- except for local things that occur once
758 -- The reason is that too little clean-up happens if you
759 -- don't inline use-once things. Also a bit of inlining is *good* for
760 -- full laziness; it can expose constant sub-expressions.
761 -- Example in spectral/mandel/Mandel.hs, where the mandelset
762 -- function gets a useful let-float if you inline windowToViewport
764 -- NB: we used to have a second exception, for data con wrappers.
765 -- On the grounds that we use gentle mode for rule LHSs, and
766 -- they match better when data con wrappers are inlined.
767 -- But that only really applies to the trivial wrappers (like (:)),
768 -- and they are now constructed as Compulsory unfoldings (in MkId)
769 -- so they'll happen anyway.
771 SimplPhase n -> isActive n prag
773 prag = idInlinePragma id
775 activeRule :: SimplEnv -> Maybe (Activation -> Bool)
776 -- Nothing => No rules at all
778 | opt_RulesOff = Nothing
780 = case getMode env of
781 SimplGently -> Just isAlwaysActive
782 -- Used to be Nothing (no rules in gentle mode)
783 -- Main motivation for changing is that I wanted
784 -- lift String ===> ...
785 -- to work in Template Haskell when simplifying
786 -- splices, so we get simpler code for literal strings
787 SimplPhase n -> Just (isActive n)
791 %************************************************************************
795 %************************************************************************
798 mkLam :: [OutBndr] -> OutExpr -> SimplM OutExpr
799 -- mkLam tries three things
800 -- a) eta reduction, if that gives a trivial expression
801 -- b) eta expansion [only if there are some value lambdas]
804 = do { dflags <- getDOptsSmpl
805 ; mkLam' dflags bndrs body }
807 mkLam' dflags bndrs body
808 | dopt Opt_DoEtaReduction dflags,
809 Just etad_lam <- tryEtaReduce bndrs body
810 = do { tick (EtaReduction (head bndrs))
813 | dopt Opt_DoLambdaEtaExpansion dflags,
814 any isRuntimeVar bndrs
815 = do { body' <- tryEtaExpansion dflags body
816 ; return (mkLams bndrs body') }
819 = returnSmpl (mkLams bndrs body)
822 -- c) floating lets out through big lambdas
823 -- [only if all tyvar lambdas, and only if this lambda
824 -- is the RHS of a let]
826 {- Sept 01: I'm experimenting with getting the
827 full laziness pass to float out past big lambdsa
828 | all isTyVar bndrs, -- Only for big lambdas
829 contIsRhs cont -- Only try the rhs type-lambda floating
830 -- if this is indeed a right-hand side; otherwise
831 -- we end up floating the thing out, only for float-in
832 -- to float it right back in again!
833 = tryRhsTyLam env bndrs body `thenSmpl` \ (floats, body') ->
834 returnSmpl (floats, mkLams bndrs body')
838 %************************************************************************
840 \subsection{Eta expansion and reduction}
842 %************************************************************************
844 We try for eta reduction here, but *only* if we get all the
845 way to an exprIsTrivial expression.
846 We don't want to remove extra lambdas unless we are going
847 to avoid allocating this thing altogether
850 tryEtaReduce :: [OutBndr] -> OutExpr -> Maybe OutExpr
851 tryEtaReduce bndrs body
852 -- We don't use CoreUtils.etaReduce, because we can be more
854 -- (a) we already have the binders
855 -- (b) we can do the triviality test before computing the free vars
856 = go (reverse bndrs) body
858 go (b : bs) (App fun arg) | ok_arg b arg = go bs fun -- Loop round
859 go [] fun | ok_fun fun = Just fun -- Success!
860 go _ _ = Nothing -- Failure!
862 ok_fun fun = exprIsTrivial fun
863 && not (any (`elemVarSet` (exprFreeVars fun)) bndrs)
864 && (exprIsHNF fun || all ok_lam bndrs)
865 ok_lam v = isTyVar v || isDictId v
866 -- The exprIsHNF is because eta reduction is not
867 -- valid in general: \x. bot /= bot
868 -- So we need to be sure that the "fun" is a value.
870 -- However, we always want to reduce (/\a -> f a) to f
871 -- This came up in a RULE: foldr (build (/\a -> g a))
872 -- did not match foldr (build (/\b -> ...something complex...))
873 -- The type checker can insert these eta-expanded versions,
874 -- with both type and dictionary lambdas; hence the slightly
877 ok_arg b arg = varToCoreExpr b `cheapEqExpr` arg
881 Try eta expansion for RHSs
884 f = \x1..xn -> N ==> f = \x1..xn y1..ym -> N y1..ym
887 where (in both cases)
889 * The xi can include type variables
891 * The yi are all value variables
893 * N is a NORMAL FORM (i.e. no redexes anywhere)
894 wanting a suitable number of extra args.
896 We may have to sandwich some coerces between the lambdas
897 to make the types work. exprEtaExpandArity looks through coerces
898 when computing arity; and etaExpand adds the coerces as necessary when
899 actually computing the expansion.
902 tryEtaExpansion :: DynFlags -> OutExpr -> SimplM OutExpr
903 -- There is at least one runtime binder in the binders
904 tryEtaExpansion dflags body
905 = getUniquesSmpl `thenSmpl` \ us ->
906 returnSmpl (etaExpand fun_arity us body (exprType body))
908 fun_arity = exprEtaExpandArity dflags body
912 %************************************************************************
914 \subsection{Floating lets out of big lambdas}
916 %************************************************************************
918 tryRhsTyLam tries this transformation, when the big lambda appears as
919 the RHS of a let(rec) binding:
921 /\abc -> let(rec) x = e in b
923 let(rec) x' = /\abc -> let x = x' a b c in e
925 /\abc -> let x = x' a b c in b
927 This is good because it can turn things like:
929 let f = /\a -> letrec g = ... g ... in g
931 letrec g' = /\a -> ... g' a ...
935 which is better. In effect, it means that big lambdas don't impede
938 This optimisation is CRUCIAL in eliminating the junk introduced by
939 desugaring mutually recursive definitions. Don't eliminate it lightly!
941 So far as the implementation is concerned:
943 Invariant: go F e = /\tvs -> F e
947 = Let x' = /\tvs -> F e
951 G = F . Let x = x' tvs
953 go F (Letrec xi=ei in b)
954 = Letrec {xi' = /\tvs -> G ei}
958 G = F . Let {xi = xi' tvs}
960 [May 1999] If we do this transformation *regardless* then we can
961 end up with some pretty silly stuff. For example,
964 st = /\ s -> let { x1=r1 ; x2=r2 } in ...
969 st = /\s -> ...[y1 s/x1, y2 s/x2]
972 Unless the "..." is a WHNF there is really no point in doing this.
973 Indeed it can make things worse. Suppose x1 is used strictly,
976 x1* = case f y of { (a,b) -> e }
978 If we abstract this wrt the tyvar we then can't do the case inline
979 as we would normally do.
983 {- Trying to do this in full laziness
985 tryRhsTyLam :: SimplEnv -> [OutTyVar] -> OutExpr -> SimplM FloatsWithExpr
986 -- Call ensures that all the binders are type variables
988 tryRhsTyLam env tyvars body -- Only does something if there's a let
989 | not (all isTyVar tyvars)
990 || not (worth_it body) -- inside a type lambda,
991 = returnSmpl (emptyFloats env, body) -- and a WHNF inside that
994 = go env (\x -> x) body
997 worth_it e@(Let _ _) = whnf_in_middle e
1000 whnf_in_middle (Let (NonRec x rhs) e) | isUnLiftedType (idType x) = False
1001 whnf_in_middle (Let _ e) = whnf_in_middle e
1002 whnf_in_middle e = exprIsCheap e
1004 main_tyvar_set = mkVarSet tyvars
1006 go env fn (Let bind@(NonRec var rhs) body)
1008 = go env (fn . Let bind) body
1010 go env fn (Let (NonRec var rhs) body)
1011 = mk_poly tyvars_here var `thenSmpl` \ (var', rhs') ->
1012 addAuxiliaryBind env (NonRec var' (mkLams tyvars_here (fn rhs))) $ \ env ->
1013 go env (fn . Let (mk_silly_bind var rhs')) body
1017 tyvars_here = varSetElems (main_tyvar_set `intersectVarSet` exprSomeFreeVars isTyVar rhs)
1018 -- Abstract only over the type variables free in the rhs
1019 -- wrt which the new binding is abstracted. But the naive
1020 -- approach of abstract wrt the tyvars free in the Id's type
1022 -- /\ a b -> let t :: (a,b) = (e1, e2)
1025 -- Here, b isn't free in x's type, but we must nevertheless
1026 -- abstract wrt b as well, because t's type mentions b.
1027 -- Since t is floated too, we'd end up with the bogus:
1028 -- poly_t = /\ a b -> (e1, e2)
1029 -- poly_x = /\ a -> fst (poly_t a *b*)
1030 -- So for now we adopt the even more naive approach of
1031 -- abstracting wrt *all* the tyvars. We'll see if that
1032 -- gives rise to problems. SLPJ June 98
1034 go env fn (Let (Rec prs) body)
1035 = mapAndUnzipSmpl (mk_poly tyvars_here) vars `thenSmpl` \ (vars', rhss') ->
1037 gn body = fn (foldr Let body (zipWith mk_silly_bind vars rhss'))
1038 pairs = vars' `zip` [mkLams tyvars_here (gn rhs) | rhs <- rhss]
1040 addAuxiliaryBind env (Rec pairs) $ \ env ->
1043 (vars,rhss) = unzip prs
1044 tyvars_here = varSetElems (main_tyvar_set `intersectVarSet` exprsSomeFreeVars isTyVar (map snd prs))
1045 -- See notes with tyvars_here above
1047 go env fn body = returnSmpl (emptyFloats env, fn body)
1049 mk_poly tyvars_here var
1050 = getUniqueSmpl `thenSmpl` \ uniq ->
1052 poly_name = setNameUnique (idName var) uniq -- Keep same name
1053 poly_ty = mkForAllTys tyvars_here (idType var) -- But new type of course
1054 poly_id = mkLocalId poly_name poly_ty
1056 -- In the olden days, it was crucial to copy the occInfo of the original var,
1057 -- because we were looking at occurrence-analysed but as yet unsimplified code!
1058 -- In particular, we mustn't lose the loop breakers. BUT NOW we are looking
1059 -- at already simplified code, so it doesn't matter
1061 -- It's even right to retain single-occurrence or dead-var info:
1062 -- Suppose we started with /\a -> let x = E in B
1063 -- where x occurs once in B. Then we transform to:
1064 -- let x' = /\a -> E in /\a -> let x* = x' a in B
1065 -- where x* has an INLINE prag on it. Now, once x* is inlined,
1066 -- the occurrences of x' will be just the occurrences originally
1069 returnSmpl (poly_id, mkTyApps (Var poly_id) (mkTyVarTys tyvars_here))
1071 mk_silly_bind var rhs = NonRec var (Note InlineMe rhs)
1072 -- Suppose we start with:
1074 -- x = /\ a -> let g = G in E
1076 -- Then we'll float to get
1078 -- x = let poly_g = /\ a -> G
1079 -- in /\ a -> let g = poly_g a in E
1081 -- But now the occurrence analyser will see just one occurrence
1082 -- of poly_g, not inside a lambda, so the simplifier will
1083 -- PreInlineUnconditionally poly_g back into g! Badk to square 1!
1084 -- (I used to think that the "don't inline lone occurrences" stuff
1085 -- would stop this happening, but since it's the *only* occurrence,
1086 -- PreInlineUnconditionally kicks in first!)
1088 -- Solution: put an INLINE note on g's RHS, so that poly_g seems
1089 -- to appear many times. (NB: mkInlineMe eliminates
1090 -- such notes on trivial RHSs, so do it manually.)
1094 %************************************************************************
1096 \subsection{Case absorption and identity-case elimination}
1098 %************************************************************************
1101 mkCase puts a case expression back together, trying various transformations first.
1104 mkCase :: OutExpr -> OutId -> OutType
1105 -> [OutAlt] -- Increasing order
1108 mkCase scrut case_bndr ty alts
1109 = getDOptsSmpl `thenSmpl` \dflags ->
1110 mkAlts dflags scrut case_bndr alts `thenSmpl` \ better_alts ->
1111 mkCase1 scrut case_bndr ty better_alts
1115 mkAlts tries these things:
1117 1. If several alternatives are identical, merge them into
1118 a single DEFAULT alternative. I've occasionally seen this
1119 making a big difference:
1121 case e of =====> case e of
1122 C _ -> f x D v -> ....v....
1123 D v -> ....v.... DEFAULT -> f x
1126 The point is that we merge common RHSs, at least for the DEFAULT case.
1127 [One could do something more elaborate but I've never seen it needed.]
1128 To avoid an expensive test, we just merge branches equal to the *first*
1129 alternative; this picks up the common cases
1130 a) all branches equal
1131 b) some branches equal to the DEFAULT (which occurs first)
1134 case e of b { ==> case e of b {
1135 p1 -> rhs1 p1 -> rhs1
1137 pm -> rhsm pm -> rhsm
1138 _ -> case b of b' { pn -> let b'=b in rhsn
1140 ... po -> let b'=b in rhso
1141 po -> rhso _ -> let b'=b in rhsd
1145 which merges two cases in one case when -- the default alternative of
1146 the outer case scrutises the same variable as the outer case This
1147 transformation is called Case Merging. It avoids that the same
1148 variable is scrutinised multiple times.
1151 The case where transformation (1) showed up was like this (lib/std/PrelCError.lhs):
1157 where @is@ was something like
1159 p `is` n = p /= (-1) && p == n
1161 This gave rise to a horrible sequence of cases
1168 and similarly in cascade for all the join points!
1173 --------------------------------------------------
1174 -- 1. Merge identical branches
1175 --------------------------------------------------
1176 mkAlts dflags scrut case_bndr alts@((con1,bndrs1,rhs1) : con_alts)
1177 | all isDeadBinder bndrs1, -- Remember the default
1178 length filtered_alts < length con_alts -- alternative comes first
1179 = tick (AltMerge case_bndr) `thenSmpl_`
1180 returnSmpl better_alts
1182 filtered_alts = filter keep con_alts
1183 keep (con,bndrs,rhs) = not (all isDeadBinder bndrs && rhs `cheapEqExpr` rhs1)
1184 better_alts = (DEFAULT, [], rhs1) : filtered_alts
1187 --------------------------------------------------
1188 -- 2. Merge nested cases
1189 --------------------------------------------------
1191 mkAlts dflags scrut outer_bndr outer_alts
1192 | dopt Opt_CaseMerge dflags,
1193 (outer_alts_without_deflt, maybe_outer_deflt) <- findDefault outer_alts,
1194 Just (Case (Var scrut_var) inner_bndr _ inner_alts) <- maybe_outer_deflt,
1195 scruting_same_var scrut_var
1197 munged_inner_alts = [(con, args, munge_rhs rhs) | (con, args, rhs) <- inner_alts]
1198 munge_rhs rhs = bindCaseBndr inner_bndr (Var outer_bndr) rhs
1200 new_alts = mergeAlts outer_alts_without_deflt munged_inner_alts
1201 -- The merge keeps the inner DEFAULT at the front, if there is one
1202 -- and eliminates any inner_alts that are shadowed by the outer_alts
1204 tick (CaseMerge outer_bndr) `thenSmpl_`
1206 -- Warning: don't call mkAlts recursively!
1207 -- Firstly, there's no point, because inner alts have already had
1208 -- mkCase applied to them, so they won't have a case in their default
1209 -- Secondly, if you do, you get an infinite loop, because the bindCaseBndr
1210 -- in munge_rhs may put a case into the DEFAULT branch!
1212 -- We are scrutinising the same variable if it's
1213 -- the outer case-binder, or if the outer case scrutinises a variable
1214 -- (and it's the same). Testing both allows us not to replace the
1215 -- outer scrut-var with the outer case-binder (Simplify.simplCaseBinder).
1216 scruting_same_var = case scrut of
1217 Var outer_scrut -> \ v -> v == outer_bndr || v == outer_scrut
1218 other -> \ v -> v == outer_bndr
1220 ------------------------------------------------
1222 ------------------------------------------------
1224 mkAlts dflags scrut case_bndr other_alts = returnSmpl other_alts
1229 =================================================================================
1231 mkCase1 tries these things
1233 1. Eliminate the case altogether if possible
1241 and similar friends.
1244 Start with a simple situation:
1246 case x# of ===> e[x#/y#]
1249 (when x#, y# are of primitive type, of course). We can't (in general)
1250 do this for algebraic cases, because we might turn bottom into
1253 Actually, we generalise this idea to look for a case where we're
1254 scrutinising a variable, and we know that only the default case can
1259 other -> ...(case x of
1263 Here the inner case can be eliminated. This really only shows up in
1264 eliminating error-checking code.
1266 We also make sure that we deal with this very common case:
1271 Here we are using the case as a strict let; if x is used only once
1272 then we want to inline it. We have to be careful that this doesn't
1273 make the program terminate when it would have diverged before, so we
1275 - x is used strictly, or
1276 - e is already evaluated (it may so if e is a variable)
1278 Lastly, we generalise the transformation to handle this:
1284 We only do this for very cheaply compared r's (constructors, literals
1285 and variables). If pedantic bottoms is on, we only do it when the
1286 scrutinee is a PrimOp which can't fail.
1288 We do it *here*, looking at un-simplified alternatives, because we
1289 have to check that r doesn't mention the variables bound by the
1290 pattern in each alternative, so the binder-info is rather useful.
1292 So the case-elimination algorithm is:
1294 1. Eliminate alternatives which can't match
1296 2. Check whether all the remaining alternatives
1297 (a) do not mention in their rhs any of the variables bound in their pattern
1298 and (b) have equal rhss
1300 3. Check we can safely ditch the case:
1301 * PedanticBottoms is off,
1302 or * the scrutinee is an already-evaluated variable
1303 or * the scrutinee is a primop which is ok for speculation
1304 -- ie we want to preserve divide-by-zero errors, and
1305 -- calls to error itself!
1307 or * [Prim cases] the scrutinee is a primitive variable
1309 or * [Alg cases] the scrutinee is a variable and
1310 either * the rhs is the same variable
1311 (eg case x of C a b -> x ===> x)
1312 or * there is only one alternative, the default alternative,
1313 and the binder is used strictly in its scope.
1314 [NB this is helped by the "use default binder where
1315 possible" transformation; see below.]
1318 If so, then we can replace the case with one of the rhss.
1320 Further notes about case elimination
1321 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1322 Consider: test :: Integer -> IO ()
1325 Turns out that this compiles to:
1328 eta1 :: State# RealWorld ->
1329 case PrelNum.< eta PrelNum.zeroInteger of wild { __DEFAULT ->
1331 (PrelNum.jtos eta ($w[] @ Char))
1333 of wild1 { (# new_s, a4 #) -> PrelIO.lvl23 new_s }}
1335 Notice the strange '<' which has no effect at all. This is a funny one.
1336 It started like this:
1338 f x y = if x < 0 then jtos x
1339 else if y==0 then "" else jtos x
1341 At a particular call site we have (f v 1). So we inline to get
1343 if v < 0 then jtos x
1344 else if 1==0 then "" else jtos x
1346 Now simplify the 1==0 conditional:
1348 if v<0 then jtos v else jtos v
1350 Now common-up the two branches of the case:
1352 case (v<0) of DEFAULT -> jtos v
1354 Why don't we drop the case? Because it's strict in v. It's technically
1355 wrong to drop even unnecessary evaluations, and in practice they
1356 may be a result of 'seq' so we *definitely* don't want to drop those.
1357 I don't really know how to improve this situation.
1361 --------------------------------------------------
1362 -- 0. Check for empty alternatives
1363 --------------------------------------------------
1365 -- This isn't strictly an error. It's possible that the simplifer might "see"
1366 -- that an inner case has no accessible alternatives before it "sees" that the
1367 -- entire branch of an outer case is inaccessible. So we simply
1368 -- put an error case here insteadd
1369 mkCase1 scrut case_bndr ty []
1370 = pprTrace "mkCase1: null alts" (ppr case_bndr <+> ppr scrut) $
1371 return (mkApps (Var eRROR_ID)
1372 [Type ty, Lit (mkStringLit "Impossible alternative")])
1374 --------------------------------------------------
1375 -- 1. Eliminate the case altogether if poss
1376 --------------------------------------------------
1378 mkCase1 scrut case_bndr ty [(con,bndrs,rhs)]
1379 -- See if we can get rid of the case altogether
1380 -- See the extensive notes on case-elimination above
1381 -- mkCase made sure that if all the alternatives are equal,
1382 -- then there is now only one (DEFAULT) rhs
1383 | all isDeadBinder bndrs,
1385 -- Check that the scrutinee can be let-bound instead of case-bound
1386 exprOkForSpeculation scrut
1387 -- OK not to evaluate it
1388 -- This includes things like (==# a# b#)::Bool
1389 -- so that we simplify
1390 -- case ==# a# b# of { True -> x; False -> x }
1393 -- This particular example shows up in default methods for
1394 -- comparision operations (e.g. in (>=) for Int.Int32)
1395 || exprIsHNF scrut -- It's already evaluated
1396 || var_demanded_later scrut -- It'll be demanded later
1398 -- || not opt_SimplPedanticBottoms) -- Or we don't care!
1399 -- We used to allow improving termination by discarding cases, unless -fpedantic-bottoms was on,
1400 -- but that breaks badly for the dataToTag# primop, which relies on a case to evaluate
1401 -- its argument: case x of { y -> dataToTag# y }
1402 -- Here we must *not* discard the case, because dataToTag# just fetches the tag from
1403 -- the info pointer. So we'll be pedantic all the time, and see if that gives any
1405 -- Also we don't want to discard 'seq's
1406 = tick (CaseElim case_bndr) `thenSmpl_`
1407 returnSmpl (bindCaseBndr case_bndr scrut rhs)
1410 -- The case binder is going to be evaluated later,
1411 -- and the scrutinee is a simple variable
1412 var_demanded_later (Var v) = isStrictDmd (idNewDemandInfo case_bndr)
1413 var_demanded_later other = False
1416 --------------------------------------------------
1418 --------------------------------------------------
1420 mkCase1 scrut case_bndr ty alts -- Identity case
1421 | all identity_alt alts
1422 = tick (CaseIdentity case_bndr) `thenSmpl_`
1423 returnSmpl (re_cast scrut)
1425 identity_alt (con, args, rhs) = de_cast rhs `cheapEqExpr` mk_id_rhs con args
1427 mk_id_rhs (DataAlt con) args = mkConApp con (arg_tys ++ varsToCoreExprs args)
1428 mk_id_rhs (LitAlt lit) _ = Lit lit
1429 mk_id_rhs DEFAULT _ = Var case_bndr
1431 arg_tys = map Type (tyConAppArgs (idType case_bndr))
1434 -- case e of x { _ -> x `cast` c }
1435 -- And we definitely want to eliminate this case, to give
1437 -- So we throw away the cast from the RHS, and reconstruct
1438 -- it at the other end. All the RHS casts must be the same
1439 -- if (all identity_alt alts) holds.
1441 -- Don't worry about nested casts, because the simplifier combines them
1442 de_cast (Cast e _) = e
1445 re_cast scrut = case head alts of
1446 (_,_,Cast _ co) -> Cast scrut co
1451 --------------------------------------------------
1453 --------------------------------------------------
1454 mkCase1 scrut bndr ty alts = returnSmpl (Case scrut bndr ty alts)
1458 When adding auxiliary bindings for the case binder, it's worth checking if
1459 its dead, because it often is, and occasionally these mkCase transformations
1460 cascade rather nicely.
1463 bindCaseBndr bndr rhs body
1464 | isDeadBinder bndr = body
1465 | otherwise = bindNonRec bndr rhs body