2 % (c) The AQUA Project, Glasgow University, 1993-1998
4 \section[SimplUtils]{The simplifier utilities}
9 mkLam, mkCase, prepareAlts, bindCaseBndr,
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, mkArgInfo
25 #include "HsVersions.h"
43 import TcGadt ( dataConCanMatch )
52 %************************************************************************
56 %************************************************************************
58 A SimplCont allows the simplifier to traverse the expression in a
59 zipper-like fashion. The SimplCont represents the rest of the expression,
60 "above" the point of interest.
62 You can also think of a SimplCont as an "evaluation context", using
63 that term in the way it is used for operational semantics. This is the
64 way I usually think of it, For example you'll often see a syntax for
65 evaluation context looking like
66 C ::= [] | C e | case C of alts | C `cast` co
67 That's the kind of thing we are doing here, and I use that syntax in
72 * A SimplCont describes a *strict* context (just like
73 evaluation contexts do). E.g. Just [] is not a SimplCont
75 * A SimplCont describes a context that *does not* bind
76 any variables. E.g. \x. [] is not a SimplCont
80 = Stop -- An empty context, or hole, []
81 OutType -- Type of the result
83 Bool -- True <=> There is something interesting about
84 -- the context, and hence the inliner
85 -- should be a bit keener (see interestingCallContext)
87 -- (a) This is the RHS of a thunk whose type suggests
88 -- that update-in-place would be possible
89 -- (b) This is an argument of a function that has RULES
90 -- Inlining the call might allow the rule to fire
92 | CoerceIt -- C `cast` co
93 OutCoercion -- The coercion simplified
98 InExpr SimplEnv -- The argument and its static env
101 | Select -- case C of alts
103 InId [InAlt] SimplEnv -- The case binder, alts, and subst-env
106 -- The two strict forms have no DupFlag, because we never duplicate them
107 | StrictBind -- (\x* \xs. e) C
108 InId [InBndr] -- let x* = [] in e
109 InExpr SimplEnv -- is a special case
113 OutExpr OutType -- e and its type
114 (Bool,[Bool]) -- Whether the function at the head of e has rules,
115 SimplCont -- plus strictness flags for further args
117 data LetRhsFlag = AnArg -- It's just an argument not a let RHS
118 | AnRhs -- It's the RHS of a let (so please float lets out of big lambdas)
120 instance Outputable LetRhsFlag where
121 ppr AnArg = ptext SLIT("arg")
122 ppr AnRhs = ptext SLIT("rhs")
124 instance Outputable SimplCont where
125 ppr (Stop ty is_rhs _) = ptext SLIT("Stop") <> brackets (ppr is_rhs) <+> ppr ty
126 ppr (ApplyTo dup arg se cont) = ((ptext SLIT("ApplyTo") <+> ppr dup <+> pprParendExpr arg) $$
127 nest 2 (pprSimplEnv se)) $$ ppr cont
128 ppr (StrictBind b _ _ _ cont) = (ptext SLIT("StrictBind") <+> ppr b) $$ ppr cont
129 ppr (StrictArg f _ _ cont) = (ptext SLIT("StrictArg") <+> ppr f) $$ ppr cont
130 ppr (Select dup bndr alts se cont) = (ptext SLIT("Select") <+> ppr dup <+> ppr bndr) $$
131 (nest 4 (ppr alts $$ pprSimplEnv se)) $$ ppr cont
132 ppr (CoerceIt co cont) = (ptext SLIT("CoerceIt") <+> ppr co) $$ ppr cont
134 data DupFlag = OkToDup | NoDup
136 instance Outputable DupFlag where
137 ppr OkToDup = ptext SLIT("ok")
138 ppr NoDup = ptext SLIT("nodup")
143 mkBoringStop :: OutType -> SimplCont
144 mkBoringStop ty = Stop ty AnArg False
146 mkLazyArgStop :: OutType -> Bool -> SimplCont
147 mkLazyArgStop ty has_rules = Stop ty AnArg (canUpdateInPlace ty || has_rules)
149 mkRhsStop :: OutType -> SimplCont
150 mkRhsStop ty = Stop ty AnRhs (canUpdateInPlace ty)
152 contIsRhsOrArg (Stop _ _ _) = True
153 contIsRhsOrArg (StrictBind {}) = True
154 contIsRhsOrArg (StrictArg {}) = True
155 contIsRhsOrArg other = False
158 contIsDupable :: SimplCont -> Bool
159 contIsDupable (Stop _ _ _) = True
160 contIsDupable (ApplyTo OkToDup _ _ _) = True
161 contIsDupable (Select OkToDup _ _ _ _) = True
162 contIsDupable (CoerceIt _ cont) = contIsDupable cont
163 contIsDupable other = False
166 contIsTrivial :: SimplCont -> Bool
167 contIsTrivial (Stop _ _ _) = True
168 contIsTrivial (ApplyTo _ (Type _) _ cont) = contIsTrivial cont
169 contIsTrivial (CoerceIt _ cont) = contIsTrivial cont
170 contIsTrivial other = False
173 contResultType :: SimplCont -> OutType
174 contResultType (Stop to_ty _ _) = to_ty
175 contResultType (StrictArg _ _ _ cont) = contResultType cont
176 contResultType (StrictBind _ _ _ _ cont) = contResultType cont
177 contResultType (ApplyTo _ _ _ cont) = contResultType cont
178 contResultType (CoerceIt _ cont) = contResultType cont
179 contResultType (Select _ _ _ _ cont) = contResultType cont
182 countValArgs :: SimplCont -> Int
183 countValArgs (ApplyTo _ (Type ty) se cont) = countValArgs cont
184 countValArgs (ApplyTo _ val_arg se cont) = 1 + countValArgs cont
185 countValArgs other = 0
187 countArgs :: SimplCont -> Int
188 countArgs (ApplyTo _ arg se cont) = 1 + countArgs cont
191 contArgs :: SimplCont -> ([OutExpr], SimplCont)
192 -- Uses substitution to turn each arg into an OutExpr
193 contArgs cont = go [] cont
195 go args (ApplyTo _ arg se cont) = go (substExpr se arg : args) cont
196 go args cont = (reverse args, cont)
198 dropArgs :: Int -> SimplCont -> SimplCont
199 dropArgs 0 cont = cont
200 dropArgs n (ApplyTo _ _ _ cont) = dropArgs (n-1) cont
201 dropArgs n other = pprPanic "dropArgs" (ppr n <+> ppr other)
206 interestingArg :: OutExpr -> Bool
207 -- An argument is interesting if it has *some* structure
208 -- We are here trying to avoid unfolding a function that
209 -- is applied only to variables that have no unfolding
210 -- (i.e. they are probably lambda bound): f x y z
211 -- There is little point in inlining f here.
212 interestingArg (Var v) = hasSomeUnfolding (idUnfolding v)
213 -- Was: isValueUnfolding (idUnfolding v')
214 -- But that seems over-pessimistic
216 -- This accounts for an argument like
217 -- () or [], which is definitely interesting
218 interestingArg (Type _) = False
219 interestingArg (App fn (Type _)) = interestingArg fn
220 interestingArg (Note _ a) = interestingArg a
222 -- Idea (from Sam B); I'm not sure if it's a good idea, so commented out for now
223 -- interestingArg expr | isUnLiftedType (exprType expr)
224 -- -- Unlifted args are only ever interesting if we know what they are
229 interestingArg other = True
230 -- Consider let x = 3 in f x
231 -- The substitution will contain (x -> ContEx 3), and we want to
232 -- to say that x is an interesting argument.
233 -- But consider also (\x. f x y) y
234 -- The substitution will contain (x -> ContEx y), and we want to say
235 -- that x is not interesting (assuming y has no unfolding)
239 Comment about interestingCallContext
240 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
241 We want to avoid inlining an expression where there can't possibly be
242 any gain, such as in an argument position. Hence, if the continuation
243 is interesting (eg. a case scrutinee, application etc.) then we
244 inline, otherwise we don't.
246 Previously some_benefit used to return True only if the variable was
247 applied to some value arguments. This didn't work:
249 let x = _coerce_ (T Int) Int (I# 3) in
250 case _coerce_ Int (T Int) x of
253 we want to inline x, but can't see that it's a constructor in a case
254 scrutinee position, and some_benefit is False.
258 dMonadST = _/\_ t -> :Monad (g1 _@_ t, g2 _@_ t, g3 _@_ t)
260 .... case dMonadST _@_ x0 of (a,b,c) -> ....
262 we'd really like to inline dMonadST here, but we *don't* want to
263 inline if the case expression is just
265 case x of y { DEFAULT -> ... }
267 since we can just eliminate this case instead (x is in WHNF). Similar
268 applies when x is bound to a lambda expression. Hence
269 contIsInteresting looks for case expressions with just a single
273 interestingCallContext :: Bool -- False <=> no args at all
274 -> Bool -- False <=> no value args
276 -- The "lone-variable" case is important. I spent ages
277 -- messing about with unsatisfactory varaints, but this is nice.
278 -- The idea is that if a variable appear all alone
279 -- as an arg of lazy fn, or rhs Stop
280 -- as scrutinee of a case Select
281 -- as arg of a strict fn ArgOf
282 -- then we should not inline it (unless there is some other reason,
283 -- e.g. is is the sole occurrence). We achieve this by making
284 -- interestingCallContext return False for a lone variable.
286 -- Why? At least in the case-scrutinee situation, turning
287 -- let x = (a,b) in case x of y -> ...
289 -- let x = (a,b) in case (a,b) of y -> ...
291 -- let x = (a,b) in let y = (a,b) in ...
292 -- is bad if the binding for x will remain.
294 -- Another example: I discovered that strings
295 -- were getting inlined straight back into applications of 'error'
296 -- because the latter is strict.
298 -- f = \x -> ...(error s)...
300 -- Fundamentally such contexts should not ecourage inlining because
301 -- the context can ``see'' the unfolding of the variable (e.g. case or a RULE)
302 -- so there's no gain.
304 -- However, even a type application or coercion isn't a lone variable.
306 -- case $fMonadST @ RealWorld of { :DMonad a b c -> c }
307 -- We had better inline that sucker! The case won't see through it.
309 -- For now, I'm treating treating a variable applied to types
310 -- in a *lazy* context "lone". The motivating example was
312 -- g = /\a. \y. h (f a)
313 -- There's no advantage in inlining f here, and perhaps
314 -- a significant disadvantage. Hence some_val_args in the Stop case
316 interestingCallContext some_args some_val_args cont
319 interesting (Select {}) = some_args
320 interesting (ApplyTo {}) = True -- Can happen if we have (coerce t (f x)) y
321 -- Perhaps True is a bit over-keen, but I've
322 -- seen (coerce f) x, where f has an INLINE prag,
323 -- So we have to give some motivaiton for inlining it
324 interesting (StrictArg {}) = some_val_args
325 interesting (StrictBind {}) = some_val_args -- ??
326 interesting (Stop ty _ interesting) = some_val_args && interesting
327 interesting (CoerceIt _ cont) = interesting cont
328 -- If this call is the arg of a strict function, the context
329 -- is a bit interesting. If we inline here, we may get useful
330 -- evaluation information to avoid repeated evals: e.g.
332 -- Here the contIsInteresting makes the '*' keener to inline,
333 -- which in turn exposes a constructor which makes the '+' inline.
334 -- Assuming that +,* aren't small enough to inline regardless.
336 -- It's also very important to inline in a strict context for things
339 -- Here, the context of (f x) is strict, and if f's unfolding is
340 -- a build it's *great* to inline it here. So we must ensure that
341 -- the context for (f x) is not totally uninteresting.
346 -> Int -- Number of value args
347 -> SimplCont -- Context of the cal
348 -> (Bool, [Bool]) -- Arg info
349 -- The arg info consists of
350 -- * A Bool indicating if the function has rules (recursively)
351 -- * A [Bool] indicating strictness for each arg
352 -- The [Bool] is usually infinite, but if it is finite it
353 -- guarantees that the function diverges after being given
354 -- that number of args
356 mkArgInfo fun n_val_args call_cont
357 = (interestingArgContext fun call_cont, fun_stricts)
359 vanilla_stricts, fun_stricts :: [Bool]
360 vanilla_stricts = repeat False
363 = case splitStrictSig (idNewStrictness fun) of
364 (demands, result_info)
365 | not (demands `lengthExceeds` n_val_args)
366 -> -- Enough args, use the strictness given.
367 -- For bottoming functions we used to pretend that the arg
368 -- is lazy, so that we don't treat the arg as an
369 -- interesting context. This avoids substituting
370 -- top-level bindings for (say) strings into
371 -- calls to error. But now we are more careful about
372 -- inlining lone variables, so its ok (see SimplUtils.analyseCont)
373 if isBotRes result_info then
374 map isStrictDmd demands -- Finite => result is bottom
376 map isStrictDmd demands ++ vanilla_stricts
378 other -> vanilla_stricts -- Not enough args, or no strictness
380 interestingArgContext :: Id -> SimplCont -> Bool
381 -- If the argument has form (f x y), where x,y are boring,
382 -- and f is marked INLINE, then we don't want to inline f.
383 -- But if the context of the argument is
385 -- where g has rules, then we *do* want to inline f, in case it
386 -- exposes a rule that might fire. Similarly, if the context is
388 -- where h has rules, then we do want to inline f.
389 -- The interesting_arg_ctxt flag makes this happen; if it's
390 -- set, the inliner gets just enough keener to inline f
391 -- regardless of how boring f's arguments are, if it's marked INLINE
393 -- The alternative would be to *always* inline an INLINE function,
394 -- regardless of how boring its context is; but that seems overkill
395 -- For example, it'd mean that wrapper functions were always inlined
396 interestingArgContext fn cont
397 = idHasRules fn || go cont
399 go (Select {}) = False
400 go (ApplyTo {}) = False
401 go (StrictArg {}) = True
402 go (StrictBind {}) = False -- ??
403 go (CoerceIt _ c) = go c
404 go (Stop _ _ interesting) = interesting
407 canUpdateInPlace :: Type -> Bool
408 -- Consider let x = <wurble> in ...
409 -- If <wurble> returns an explicit constructor, we might be able
410 -- to do update in place. So we treat even a thunk RHS context
411 -- as interesting if update in place is possible. We approximate
412 -- this by seeing if the type has a single constructor with a
413 -- small arity. But arity zero isn't good -- we share the single copy
414 -- for that case, so no point in sharing.
417 | not opt_UF_UpdateInPlace = False
419 = case splitTyConApp_maybe ty of
421 Just (tycon, _) -> case tyConDataCons_maybe tycon of
422 Just [dc] -> arity == 1 || arity == 2
424 arity = dataConRepArity dc
430 %************************************************************************
432 \subsection{Decisions about inlining}
434 %************************************************************************
436 Inlining is controlled partly by the SimplifierMode switch. This has two
439 SimplGently (a) Simplifying before specialiser/full laziness
440 (b) Simplifiying inside INLINE pragma
441 (c) Simplifying the LHS of a rule
442 (d) Simplifying a GHCi expression or Template
445 SimplPhase n Used at all other times
447 The key thing about SimplGently is that it does no call-site inlining.
448 Before full laziness we must be careful not to inline wrappers,
449 because doing so inhibits floating
450 e.g. ...(case f x of ...)...
451 ==> ...(case (case x of I# x# -> fw x#) of ...)...
452 ==> ...(case x of I# x# -> case fw x# of ...)...
453 and now the redex (f x) isn't floatable any more.
455 The no-inlining thing is also important for Template Haskell. You might be
456 compiling in one-shot mode with -O2; but when TH compiles a splice before
457 running it, we don't want to use -O2. Indeed, we don't want to inline
458 anything, because the byte-code interpreter might get confused about
459 unboxed tuples and suchlike.
463 SimplGently is also used as the mode to simplify inside an InlineMe note.
466 inlineMode :: SimplifierMode
467 inlineMode = SimplGently
470 It really is important to switch off inlinings inside such
471 expressions. Consider the following example
477 in ...g...g...g...g...g...
479 Now, if that's the ONLY occurrence of f, it will be inlined inside g,
480 and thence copied multiple times when g is inlined.
483 This function may be inlinined in other modules, so we
484 don't want to remove (by inlining) calls to functions that have
485 specialisations, or that may have transformation rules in an importing
488 E.g. {-# INLINE f #-}
491 and suppose that g is strict *and* has specialisations. If we inline
492 g's wrapper, we deny f the chance of getting the specialised version
493 of g when f is inlined at some call site (perhaps in some other
496 It's also important not to inline a worker back into a wrapper.
498 wraper = inline_me (\x -> ...worker... )
499 Normally, the inline_me prevents the worker getting inlined into
500 the wrapper (initially, the worker's only call site!). But,
501 if the wrapper is sure to be called, the strictness analyser will
502 mark it 'demanded', so when the RHS is simplified, it'll get an ArgOf
503 continuation. That's why the keep_inline predicate returns True for
504 ArgOf continuations. It shouldn't do any harm not to dissolve the
505 inline-me note under these circumstances.
507 Note that the result is that we do very little simplification
510 all xs = foldr (&&) True xs
511 any p = all . map p {-# INLINE any #-}
513 Problem: any won't get deforested, and so if it's exported and the
514 importer doesn't use the inlining, (eg passes it as an arg) then we
515 won't get deforestation at all. We havn't solved this problem yet!
518 preInlineUnconditionally
519 ~~~~~~~~~~~~~~~~~~~~~~~~
520 @preInlineUnconditionally@ examines a bndr to see if it is used just
521 once in a completely safe way, so that it is safe to discard the
522 binding inline its RHS at the (unique) usage site, REGARDLESS of how
523 big the RHS might be. If this is the case we don't simplify the RHS
524 first, but just inline it un-simplified.
526 This is much better than first simplifying a perhaps-huge RHS and then
527 inlining and re-simplifying it. Indeed, it can be at least quadratically
536 We may end up simplifying e1 N times, e2 N-1 times, e3 N-3 times etc.
537 This can happen with cascades of functions too:
544 THE MAIN INVARIANT is this:
546 ---- preInlineUnconditionally invariant -----
547 IF preInlineUnconditionally chooses to inline x = <rhs>
548 THEN doing the inlining should not change the occurrence
549 info for the free vars of <rhs>
550 ----------------------------------------------
552 For example, it's tempting to look at trivial binding like
554 and inline it unconditionally. But suppose x is used many times,
555 but this is the unique occurrence of y. Then inlining x would change
556 y's occurrence info, which breaks the invariant. It matters: y
557 might have a BIG rhs, which will now be dup'd at every occurrenc of x.
560 Evne RHSs labelled InlineMe aren't caught here, because there might be
561 no benefit from inlining at the call site.
563 [Sept 01] Don't unconditionally inline a top-level thing, because that
564 can simply make a static thing into something built dynamically. E.g.
568 [Remember that we treat \s as a one-shot lambda.] No point in
569 inlining x unless there is something interesting about the call site.
571 But watch out: if you aren't careful, some useful foldr/build fusion
572 can be lost (most notably in spectral/hartel/parstof) because the
573 foldr didn't see the build. Doing the dynamic allocation isn't a big
574 deal, in fact, but losing the fusion can be. But the right thing here
575 seems to be to do a callSiteInline based on the fact that there is
576 something interesting about the call site (it's strict). Hmm. That
579 Conclusion: inline top level things gaily until Phase 0 (the last
580 phase), at which point don't.
583 preInlineUnconditionally :: SimplEnv -> TopLevelFlag -> InId -> InExpr -> Bool
584 preInlineUnconditionally env top_lvl bndr rhs
586 | opt_SimplNoPreInlining = False
587 | otherwise = case idOccInfo bndr of
588 IAmDead -> True -- Happens in ((\x.1) v)
589 OneOcc in_lam True int_cxt -> try_once in_lam int_cxt
593 active = case phase of
594 SimplGently -> isAlwaysActive prag
595 SimplPhase n -> isActive n prag
596 prag = idInlinePragma bndr
598 try_once in_lam int_cxt -- There's one textual occurrence
599 | not in_lam = isNotTopLevel top_lvl || early_phase
600 | otherwise = int_cxt && canInlineInLam rhs
602 -- Be very careful before inlining inside a lambda, becuase (a) we must not
603 -- invalidate occurrence information, and (b) we want to avoid pushing a
604 -- single allocation (here) into multiple allocations (inside lambda).
605 -- Inlining a *function* with a single *saturated* call would be ok, mind you.
606 -- || (if is_cheap && not (canInlineInLam rhs) then pprTrace "preinline" (ppr bndr <+> ppr rhs) ok else ok)
608 -- is_cheap = exprIsCheap rhs
609 -- ok = is_cheap && int_cxt
611 -- int_cxt The context isn't totally boring
612 -- E.g. let f = \ab.BIG in \y. map f xs
613 -- Don't want to substitute for f, because then we allocate
614 -- its closure every time the \y is called
615 -- But: let f = \ab.BIG in \y. map (f y) xs
616 -- Now we do want to substitute for f, even though it's not
617 -- saturated, because we're going to allocate a closure for
618 -- (f y) every time round the loop anyhow.
620 -- canInlineInLam => free vars of rhs are (Once in_lam) or Many,
621 -- so substituting rhs inside a lambda doesn't change the occ info.
622 -- Sadly, not quite the same as exprIsHNF.
623 canInlineInLam (Lit l) = True
624 canInlineInLam (Lam b e) = isRuntimeVar b || canInlineInLam e
625 canInlineInLam (Note _ e) = canInlineInLam e
626 canInlineInLam _ = False
628 early_phase = case phase of
629 SimplPhase 0 -> False
631 -- If we don't have this early_phase test, consider
632 -- x = length [1,2,3]
633 -- The full laziness pass carefully floats all the cons cells to
634 -- top level, and preInlineUnconditionally floats them all back in.
635 -- Result is (a) static allocation replaced by dynamic allocation
636 -- (b) many simplifier iterations because this tickles
637 -- a related problem; only one inlining per pass
639 -- On the other hand, I have seen cases where top-level fusion is
640 -- lost if we don't inline top level thing (e.g. string constants)
641 -- Hence the test for phase zero (which is the phase for all the final
642 -- simplifications). Until phase zero we take no special notice of
643 -- top level things, but then we become more leery about inlining
648 postInlineUnconditionally
649 ~~~~~~~~~~~~~~~~~~~~~~~~~
650 @postInlineUnconditionally@ decides whether to unconditionally inline
651 a thing based on the form of its RHS; in particular if it has a
652 trivial RHS. If so, we can inline and discard the binding altogether.
654 NB: a loop breaker has must_keep_binding = True and non-loop-breakers
655 only have *forward* references Hence, it's safe to discard the binding
657 NOTE: This isn't our last opportunity to inline. We're at the binding
658 site right now, and we'll get another opportunity when we get to the
661 Note that we do this unconditional inlining only for trival RHSs.
662 Don't inline even WHNFs inside lambdas; doing so may simply increase
663 allocation when the function is called. This isn't the last chance; see
666 NB: Even inline pragmas (e.g. IMustBeINLINEd) are ignored here Why?
667 Because we don't even want to inline them into the RHS of constructor
668 arguments. See NOTE above
670 NB: At one time even NOINLINE was ignored here: if the rhs is trivial
671 it's best to inline it anyway. We often get a=E; b=a from desugaring,
672 with both a and b marked NOINLINE. But that seems incompatible with
673 our new view that inlining is like a RULE, so I'm sticking to the 'active'
677 postInlineUnconditionally
678 :: SimplEnv -> TopLevelFlag
679 -> InId -- The binder (an OutId would be fine too)
680 -> OccInfo -- From the InId
684 postInlineUnconditionally env top_lvl bndr occ_info rhs unfolding
686 | isLoopBreaker occ_info = False -- If it's a loop-breaker of any kind, dont' inline
687 -- because it might be referred to "earlier"
688 | isExportedId bndr = False
689 | exprIsTrivial rhs = True
692 -- The point of examining occ_info here is that for *non-values*
693 -- that occur outside a lambda, the call-site inliner won't have
694 -- a chance (becuase it doesn't know that the thing
695 -- only occurs once). The pre-inliner won't have gotten
696 -- it either, if the thing occurs in more than one branch
697 -- So the main target is things like
700 -- True -> case x of ...
701 -- False -> case x of ...
702 -- I'm not sure how important this is in practice
703 OneOcc in_lam one_br int_cxt -- OneOcc => no code-duplication issue
704 -> smallEnoughToInline unfolding -- Small enough to dup
705 -- ToDo: consider discount on smallEnoughToInline if int_cxt is true
707 -- NB: Do NOT inline arbitrarily big things, even if one_br is True
708 -- Reason: doing so risks exponential behaviour. We simplify a big
709 -- expression, inline it, and simplify it again. But if the
710 -- very same thing happens in the big expression, we get
712 -- PRINCIPLE: when we've already simplified an expression once,
713 -- make sure that we only inline it if it's reasonably small.
715 && ((isNotTopLevel top_lvl && not in_lam) ||
716 -- But outside a lambda, we want to be reasonably aggressive
717 -- about inlining into multiple branches of case
718 -- e.g. let x = <non-value>
719 -- in case y of { C1 -> ..x..; C2 -> ..x..; C3 -> ... }
720 -- Inlining can be a big win if C3 is the hot-spot, even if
721 -- the uses in C1, C2 are not 'interesting'
722 -- An example that gets worse if you add int_cxt here is 'clausify'
724 (isCheapUnfolding unfolding && int_cxt))
725 -- isCheap => acceptable work duplication; in_lam may be true
726 -- int_cxt to prevent us inlining inside a lambda without some
727 -- good reason. See the notes on int_cxt in preInlineUnconditionally
729 IAmDead -> True -- This happens; for example, the case_bndr during case of
730 -- known constructor: case (a,b) of x { (p,q) -> ... }
731 -- Here x isn't mentioned in the RHS, so we don't want to
732 -- create the (dead) let-binding let x = (a,b) in ...
736 -- Here's an example that we don't handle well:
737 -- let f = if b then Left (\x.BIG) else Right (\y.BIG)
738 -- in \y. ....case f of {...} ....
739 -- Here f is used just once, and duplicating the case work is fine (exprIsCheap).
741 -- * We can't preInlineUnconditionally because that woud invalidate
742 -- the occ info for b.
743 -- * We can't postInlineUnconditionally because the RHS is big, and
744 -- that risks exponential behaviour
745 -- * We can't call-site inline, because the rhs is big
749 active = case getMode env of
750 SimplGently -> isAlwaysActive prag
751 SimplPhase n -> isActive n prag
752 prag = idInlinePragma bndr
754 activeInline :: SimplEnv -> OutId -> Bool
756 = case getMode env of
758 -- No inlining at all when doing gentle stuff,
759 -- except for local things that occur once
760 -- The reason is that too little clean-up happens if you
761 -- don't inline use-once things. Also a bit of inlining is *good* for
762 -- full laziness; it can expose constant sub-expressions.
763 -- Example in spectral/mandel/Mandel.hs, where the mandelset
764 -- function gets a useful let-float if you inline windowToViewport
766 -- NB: we used to have a second exception, for data con wrappers.
767 -- On the grounds that we use gentle mode for rule LHSs, and
768 -- they match better when data con wrappers are inlined.
769 -- But that only really applies to the trivial wrappers (like (:)),
770 -- and they are now constructed as Compulsory unfoldings (in MkId)
771 -- so they'll happen anyway.
773 SimplPhase n -> isActive n prag
775 prag = idInlinePragma id
777 activeRule :: SimplEnv -> Maybe (Activation -> Bool)
778 -- Nothing => No rules at all
780 | opt_RulesOff = Nothing
782 = case getMode env of
783 SimplGently -> Just isAlwaysActive
784 -- Used to be Nothing (no rules in gentle mode)
785 -- Main motivation for changing is that I wanted
786 -- lift String ===> ...
787 -- to work in Template Haskell when simplifying
788 -- splices, so we get simpler code for literal strings
789 SimplPhase n -> Just (isActive n)
793 %************************************************************************
797 %************************************************************************
800 mkLam :: [OutBndr] -> OutExpr -> SimplM OutExpr
801 -- mkLam tries three things
802 -- a) eta reduction, if that gives a trivial expression
803 -- b) eta expansion [only if there are some value lambdas]
806 = do { dflags <- getDOptsSmpl
807 ; mkLam' dflags bndrs body }
809 mkLam' :: DynFlags -> [OutBndr] -> OutExpr -> SimplM OutExpr
810 mkLam' dflags bndrs (Cast body@(Lam _ _) co)
811 -- Note [Casts and lambdas]
812 = do { lam <- mkLam' dflags (bndrs ++ bndrs') body'
813 ; return (mkCoerce (mkPiTypes bndrs co) lam) }
815 (bndrs',body') = collectBinders body
817 mkLam' dflags bndrs body
818 | dopt Opt_DoEtaReduction dflags,
819 Just etad_lam <- tryEtaReduce bndrs body
820 = do { tick (EtaReduction (head bndrs))
823 | dopt Opt_DoLambdaEtaExpansion dflags,
824 any isRuntimeVar bndrs
825 = do { body' <- tryEtaExpansion dflags body
826 ; return (mkLams bndrs body') }
829 = returnSmpl (mkLams bndrs body)
832 Note [Casts and lambdas]
833 ~~~~~~~~~~~~~~~~~~~~~~~~
835 (\x. (\y. e) `cast` g1) `cast` g2
836 There is a danger here that the two lambdas look separated, and the
837 full laziness pass might float an expression to between the two.
839 So this equation in mkLam' floats the g1 out, thus:
840 (\x. e `cast` g1) --> (\x.e) `cast` (tx -> g1)
843 In general, this floats casts outside lambdas, where (I hope) they might meet
844 and cancel with some other cast.
847 -- c) floating lets out through big lambdas
848 -- [only if all tyvar lambdas, and only if this lambda
849 -- is the RHS of a let]
851 {- Sept 01: I'm experimenting with getting the
852 full laziness pass to float out past big lambdsa
853 | all isTyVar bndrs, -- Only for big lambdas
854 contIsRhs cont -- Only try the rhs type-lambda floating
855 -- if this is indeed a right-hand side; otherwise
856 -- we end up floating the thing out, only for float-in
857 -- to float it right back in again!
858 = tryRhsTyLam env bndrs body `thenSmpl` \ (floats, body') ->
859 returnSmpl (floats, mkLams bndrs body')
863 %************************************************************************
865 \subsection{Eta expansion and reduction}
867 %************************************************************************
869 We try for eta reduction here, but *only* if we get all the
870 way to an exprIsTrivial expression.
871 We don't want to remove extra lambdas unless we are going
872 to avoid allocating this thing altogether
875 tryEtaReduce :: [OutBndr] -> OutExpr -> Maybe OutExpr
876 tryEtaReduce bndrs body
877 -- We don't use CoreUtils.etaReduce, because we can be more
879 -- (a) we already have the binders
880 -- (b) we can do the triviality test before computing the free vars
881 = go (reverse bndrs) body
883 go (b : bs) (App fun arg) | ok_arg b arg = go bs fun -- Loop round
884 go [] fun | ok_fun fun = Just fun -- Success!
885 go _ _ = Nothing -- Failure!
887 ok_fun fun = exprIsTrivial fun
888 && not (any (`elemVarSet` (exprFreeVars fun)) bndrs)
889 && (exprIsHNF fun || all ok_lam bndrs)
890 ok_lam v = isTyVar v || isDictId v
891 -- The exprIsHNF is because eta reduction is not
892 -- valid in general: \x. bot /= bot
893 -- So we need to be sure that the "fun" is a value.
895 -- However, we always want to reduce (/\a -> f a) to f
896 -- This came up in a RULE: foldr (build (/\a -> g a))
897 -- did not match foldr (build (/\b -> ...something complex...))
898 -- The type checker can insert these eta-expanded versions,
899 -- with both type and dictionary lambdas; hence the slightly
902 ok_arg b arg = varToCoreExpr b `cheapEqExpr` arg
906 Try eta expansion for RHSs
909 f = \x1..xn -> N ==> f = \x1..xn y1..ym -> N y1..ym
912 where (in both cases)
914 * The xi can include type variables
916 * The yi are all value variables
918 * N is a NORMAL FORM (i.e. no redexes anywhere)
919 wanting a suitable number of extra args.
921 We may have to sandwich some coerces between the lambdas
922 to make the types work. exprEtaExpandArity looks through coerces
923 when computing arity; and etaExpand adds the coerces as necessary when
924 actually computing the expansion.
927 tryEtaExpansion :: DynFlags -> OutExpr -> SimplM OutExpr
928 -- There is at least one runtime binder in the binders
929 tryEtaExpansion dflags body
930 = getUniquesSmpl `thenSmpl` \ us ->
931 returnSmpl (etaExpand fun_arity us body (exprType body))
933 fun_arity = exprEtaExpandArity dflags body
937 %************************************************************************
939 \subsection{Floating lets out of big lambdas}
941 %************************************************************************
943 tryRhsTyLam tries this transformation, when the big lambda appears as
944 the RHS of a let(rec) binding:
946 /\abc -> let(rec) x = e in b
948 let(rec) x' = /\abc -> let x = x' a b c in e
950 /\abc -> let x = x' a b c in b
952 This is good because it can turn things like:
954 let f = /\a -> letrec g = ... g ... in g
956 letrec g' = /\a -> ... g' a ...
960 which is better. In effect, it means that big lambdas don't impede
963 This optimisation is CRUCIAL in eliminating the junk introduced by
964 desugaring mutually recursive definitions. Don't eliminate it lightly!
966 So far as the implementation is concerned:
968 Invariant: go F e = /\tvs -> F e
972 = Let x' = /\tvs -> F e
976 G = F . Let x = x' tvs
978 go F (Letrec xi=ei in b)
979 = Letrec {xi' = /\tvs -> G ei}
983 G = F . Let {xi = xi' tvs}
985 [May 1999] If we do this transformation *regardless* then we can
986 end up with some pretty silly stuff. For example,
989 st = /\ s -> let { x1=r1 ; x2=r2 } in ...
994 st = /\s -> ...[y1 s/x1, y2 s/x2]
997 Unless the "..." is a WHNF there is really no point in doing this.
998 Indeed it can make things worse. Suppose x1 is used strictly,
1001 x1* = case f y of { (a,b) -> e }
1003 If we abstract this wrt the tyvar we then can't do the case inline
1004 as we would normally do.
1008 {- Trying to do this in full laziness
1010 tryRhsTyLam :: SimplEnv -> [OutTyVar] -> OutExpr -> SimplM FloatsWithExpr
1011 -- Call ensures that all the binders are type variables
1013 tryRhsTyLam env tyvars body -- Only does something if there's a let
1014 | not (all isTyVar tyvars)
1015 || not (worth_it body) -- inside a type lambda,
1016 = returnSmpl (emptyFloats env, body) -- and a WHNF inside that
1019 = go env (\x -> x) body
1022 worth_it e@(Let _ _) = whnf_in_middle e
1025 whnf_in_middle (Let (NonRec x rhs) e) | isUnLiftedType (idType x) = False
1026 whnf_in_middle (Let _ e) = whnf_in_middle e
1027 whnf_in_middle e = exprIsCheap e
1029 main_tyvar_set = mkVarSet tyvars
1031 go env fn (Let bind@(NonRec var rhs) body)
1033 = go env (fn . Let bind) body
1035 go env fn (Let (NonRec var rhs) body)
1036 = mk_poly tyvars_here var `thenSmpl` \ (var', rhs') ->
1037 addAuxiliaryBind env (NonRec var' (mkLams tyvars_here (fn rhs))) $ \ env ->
1038 go env (fn . Let (mk_silly_bind var rhs')) body
1042 tyvars_here = varSetElems (main_tyvar_set `intersectVarSet` exprSomeFreeVars isTyVar rhs)
1043 -- Abstract only over the type variables free in the rhs
1044 -- wrt which the new binding is abstracted. But the naive
1045 -- approach of abstract wrt the tyvars free in the Id's type
1047 -- /\ a b -> let t :: (a,b) = (e1, e2)
1050 -- Here, b isn't free in x's type, but we must nevertheless
1051 -- abstract wrt b as well, because t's type mentions b.
1052 -- Since t is floated too, we'd end up with the bogus:
1053 -- poly_t = /\ a b -> (e1, e2)
1054 -- poly_x = /\ a -> fst (poly_t a *b*)
1055 -- So for now we adopt the even more naive approach of
1056 -- abstracting wrt *all* the tyvars. We'll see if that
1057 -- gives rise to problems. SLPJ June 98
1059 go env fn (Let (Rec prs) body)
1060 = mapAndUnzipSmpl (mk_poly tyvars_here) vars `thenSmpl` \ (vars', rhss') ->
1062 gn body = fn (foldr Let body (zipWith mk_silly_bind vars rhss'))
1063 pairs = vars' `zip` [mkLams tyvars_here (gn rhs) | rhs <- rhss]
1065 addAuxiliaryBind env (Rec pairs) $ \ env ->
1068 (vars,rhss) = unzip prs
1069 tyvars_here = varSetElems (main_tyvar_set `intersectVarSet` exprsSomeFreeVars isTyVar (map snd prs))
1070 -- See notes with tyvars_here above
1072 go env fn body = returnSmpl (emptyFloats env, fn body)
1074 mk_poly tyvars_here var
1075 = getUniqueSmpl `thenSmpl` \ uniq ->
1077 poly_name = setNameUnique (idName var) uniq -- Keep same name
1078 poly_ty = mkForAllTys tyvars_here (idType var) -- But new type of course
1079 poly_id = mkLocalId poly_name poly_ty
1081 -- In the olden days, it was crucial to copy the occInfo of the original var,
1082 -- because we were looking at occurrence-analysed but as yet unsimplified code!
1083 -- In particular, we mustn't lose the loop breakers. BUT NOW we are looking
1084 -- at already simplified code, so it doesn't matter
1086 -- It's even right to retain single-occurrence or dead-var info:
1087 -- Suppose we started with /\a -> let x = E in B
1088 -- where x occurs once in B. Then we transform to:
1089 -- let x' = /\a -> E in /\a -> let x* = x' a in B
1090 -- where x* has an INLINE prag on it. Now, once x* is inlined,
1091 -- the occurrences of x' will be just the occurrences originally
1094 returnSmpl (poly_id, mkTyApps (Var poly_id) (mkTyVarTys tyvars_here))
1096 mk_silly_bind var rhs = NonRec var (Note InlineMe rhs)
1097 -- Suppose we start with:
1099 -- x = /\ a -> let g = G in E
1101 -- Then we'll float to get
1103 -- x = let poly_g = /\ a -> G
1104 -- in /\ a -> let g = poly_g a in E
1106 -- But now the occurrence analyser will see just one occurrence
1107 -- of poly_g, not inside a lambda, so the simplifier will
1108 -- PreInlineUnconditionally poly_g back into g! Badk to square 1!
1109 -- (I used to think that the "don't inline lone occurrences" stuff
1110 -- would stop this happening, but since it's the *only* occurrence,
1111 -- PreInlineUnconditionally kicks in first!)
1113 -- Solution: put an INLINE note on g's RHS, so that poly_g seems
1114 -- to appear many times. (NB: mkInlineMe eliminates
1115 -- such notes on trivial RHSs, so do it manually.)
1119 %************************************************************************
1123 %************************************************************************
1125 prepareAlts tries these things:
1127 1. If several alternatives are identical, merge them into
1128 a single DEFAULT alternative. I've occasionally seen this
1129 making a big difference:
1131 case e of =====> case e of
1132 C _ -> f x D v -> ....v....
1133 D v -> ....v.... DEFAULT -> f x
1136 The point is that we merge common RHSs, at least for the DEFAULT case.
1137 [One could do something more elaborate but I've never seen it needed.]
1138 To avoid an expensive test, we just merge branches equal to the *first*
1139 alternative; this picks up the common cases
1140 a) all branches equal
1141 b) some branches equal to the DEFAULT (which occurs first)
1144 case e of b { ==> case e of b {
1145 p1 -> rhs1 p1 -> rhs1
1147 pm -> rhsm pm -> rhsm
1148 _ -> case b of b' { pn -> let b'=b in rhsn
1150 ... po -> let b'=b in rhso
1151 po -> rhso _ -> let b'=b in rhsd
1155 which merges two cases in one case when -- the default alternative of
1156 the outer case scrutises the same variable as the outer case This
1157 transformation is called Case Merging. It avoids that the same
1158 variable is scrutinised multiple times.
1161 The case where transformation (1) showed up was like this (lib/std/PrelCError.lhs):
1167 where @is@ was something like
1169 p `is` n = p /= (-1) && p == n
1171 This gave rise to a horrible sequence of cases
1178 and similarly in cascade for all the join points!
1181 ~~~~~~~~~~~~~~~~~~~~
1182 We do this *here*, looking at un-simplified alternatives, because we
1183 have to check that r doesn't mention the variables bound by the
1184 pattern in each alternative, so the binder-info is rather useful.
1187 prepareAlts :: OutExpr -> OutId -> [InAlt] -> SimplM ([AltCon], [InAlt])
1188 prepareAlts scrut case_bndr' alts
1189 = do { dflags <- getDOptsSmpl
1190 ; alts <- combineIdenticalAlts case_bndr' alts
1192 ; let (alts_wo_default, maybe_deflt) = findDefault alts
1193 alt_cons = [con | (con,_,_) <- alts_wo_default]
1194 imposs_deflt_cons = nub (imposs_cons ++ alt_cons)
1195 -- "imposs_deflt_cons" are handled
1196 -- EITHER by the context,
1197 -- OR by a non-DEFAULT branch in this case expression.
1199 ; default_alts <- prepareDefault dflags scrut case_bndr' mb_tc_app
1200 imposs_deflt_cons maybe_deflt
1202 ; let trimmed_alts = filter possible_alt alts_wo_default
1203 merged_alts = mergeAlts trimmed_alts default_alts
1204 -- We need the mergeAlts in case the new default_alt
1205 -- has turned into a constructor alternative.
1206 -- The merge keeps the inner DEFAULT at the front, if there is one
1207 -- and interleaves the alternatives in the right order
1209 ; return (imposs_deflt_cons, merged_alts) }
1211 mb_tc_app = splitTyConApp_maybe (idType case_bndr')
1212 Just (_, inst_tys) = mb_tc_app
1214 imposs_cons = case scrut of
1215 Var v -> otherCons (idUnfolding v)
1218 possible_alt :: CoreAlt -> Bool
1219 possible_alt (con, _, _) | con `elem` imposs_cons = False
1220 possible_alt (DataAlt con, _, _) = dataConCanMatch inst_tys con
1221 possible_alt alt = True
1224 --------------------------------------------------
1225 -- 1. Merge identical branches
1226 --------------------------------------------------
1227 combineIdenticalAlts :: OutId -> [InAlt] -> SimplM [InAlt]
1229 combineIdenticalAlts case_bndr alts@((con1,bndrs1,rhs1) : con_alts)
1230 | all isDeadBinder bndrs1, -- Remember the default
1231 length filtered_alts < length con_alts -- alternative comes first
1232 -- Also Note [Dead binders]
1233 = do { tick (AltMerge case_bndr)
1234 ; return ((DEFAULT, [], rhs1) : filtered_alts) }
1236 filtered_alts = filter keep con_alts
1237 keep (con,bndrs,rhs) = not (all isDeadBinder bndrs && rhs `cheapEqExpr` rhs1)
1239 combineIdenticalAlts case_bndr alts = return alts
1241 -------------------------------------------------------------------------
1242 -- Prepare the default alternative
1243 -------------------------------------------------------------------------
1244 prepareDefault :: DynFlags
1245 -> OutExpr -- Scrutinee
1246 -> OutId -- Case binder; need just for its type. Note that as an
1247 -- OutId, it has maximum information; this is important.
1248 -- Test simpl013 is an example
1249 -> Maybe (TyCon, [Type]) -- Type of scrutinee, decomposed
1250 -> [AltCon] -- These cons can't happen when matching the default
1251 -> Maybe InExpr -- Rhs
1252 -> SimplM [InAlt] -- Still unsimplified
1253 -- We use a list because it's what mergeAlts expects,
1254 -- And becuase case-merging can cause many to show up
1256 ------- Merge nested cases ----------
1257 prepareDefault dflags scrut outer_bndr bndr_ty imposs_cons (Just deflt_rhs)
1258 | dopt Opt_CaseMerge dflags
1259 , Case (Var scrut_var) inner_bndr _ inner_alts <- deflt_rhs
1260 , scruting_same_var scrut_var
1261 = do { tick (CaseMerge outer_bndr)
1263 ; let munge_rhs rhs = bindCaseBndr inner_bndr (Var outer_bndr) rhs
1264 ; return [(con, args, munge_rhs rhs) | (con, args, rhs) <- inner_alts,
1265 not (con `elem` imposs_cons) ]
1266 -- NB: filter out any imposs_cons. Example:
1269 -- DEFAULT -> case x of
1272 -- When we merge, we must ensure that e1 takes
1273 -- precedence over e2 as the value for A!
1275 -- Warning: don't call prepareAlts recursively!
1276 -- Firstly, there's no point, because inner alts have already had
1277 -- mkCase applied to them, so they won't have a case in their default
1278 -- Secondly, if you do, you get an infinite loop, because the bindCaseBndr
1279 -- in munge_rhs may put a case into the DEFAULT branch!
1281 -- We are scrutinising the same variable if it's
1282 -- the outer case-binder, or if the outer case scrutinises a variable
1283 -- (and it's the same). Testing both allows us not to replace the
1284 -- outer scrut-var with the outer case-binder (Simplify.simplCaseBinder).
1285 scruting_same_var = case scrut of
1286 Var outer_scrut -> \ v -> v == outer_bndr || v == outer_scrut
1287 other -> \ v -> v == outer_bndr
1289 --------- Fill in known constructor -----------
1290 prepareDefault dflags scrut case_bndr (Just (tycon, inst_tys)) imposs_cons (Just deflt_rhs)
1291 | -- This branch handles the case where we are
1292 -- scrutinisng an algebraic data type
1293 isAlgTyCon tycon -- It's a data type, tuple, or unboxed tuples.
1294 , not (isNewTyCon tycon) -- We can have a newtype, if we are just doing an eval:
1295 -- case x of { DEFAULT -> e }
1296 -- and we don't want to fill in a default for them!
1297 , Just all_cons <- tyConDataCons_maybe tycon
1298 , not (null all_cons) -- This is a tricky corner case. If the data type has no constructors,
1299 -- which GHC allows, then the case expression will have at most a default
1300 -- alternative. We don't want to eliminate that alternative, because the
1301 -- invariant is that there's always one alternative. It's more convenient
1303 -- case x of { DEFAULT -> e }
1304 -- as it is, rather than transform it to
1305 -- error "case cant match"
1306 -- which would be quite legitmate. But it's a really obscure corner, and
1307 -- not worth wasting code on.
1308 , let imposs_data_cons = [con | DataAlt con <- imposs_cons] -- We now know it's a data type
1309 is_possible con = not (con `elem` imposs_data_cons)
1310 && dataConCanMatch inst_tys con
1311 = case filter is_possible all_cons of
1312 [] -> return [] -- Eliminate the default alternative
1313 -- altogether if it can't match
1315 [con] -> -- It matches exactly one constructor, so fill it in
1316 do { tick (FillInCaseDefault case_bndr)
1317 ; us <- getUniquesSmpl
1318 ; let (ex_tvs, co_tvs, arg_ids) =
1319 dataConRepInstPat us con inst_tys
1320 ; return [(DataAlt con, ex_tvs ++ co_tvs ++ arg_ids, deflt_rhs)] }
1322 two_or_more -> return [(DEFAULT, [], deflt_rhs)]
1324 --------- Catch-all cases -----------
1325 prepareDefault dflags scrut case_bndr bndr_ty imposs_cons (Just deflt_rhs)
1326 = return [(DEFAULT, [], deflt_rhs)]
1328 prepareDefault dflags scrut case_bndr bndr_ty imposs_cons Nothing
1329 = return [] -- No default branch
1334 =================================================================================
1336 mkCase tries these things
1338 1. Eliminate the case altogether if possible
1346 and similar friends.
1350 mkCase :: OutExpr -> OutId -> OutType
1351 -> [OutAlt] -- Increasing order
1354 --------------------------------------------------
1355 -- 1. Check for empty alternatives
1356 --------------------------------------------------
1358 -- This isn't strictly an error. It's possible that the simplifer might "see"
1359 -- that an inner case has no accessible alternatives before it "sees" that the
1360 -- entire branch of an outer case is inaccessible. So we simply
1361 -- put an error case here insteadd
1362 mkCase scrut case_bndr ty []
1363 = pprTrace "mkCase: null alts" (ppr case_bndr <+> ppr scrut) $
1364 return (mkApps (Var eRROR_ID)
1365 [Type ty, Lit (mkStringLit "Impossible alternative")])
1368 --------------------------------------------------
1370 --------------------------------------------------
1372 mkCase scrut case_bndr ty alts -- Identity case
1373 | all identity_alt alts
1374 = tick (CaseIdentity case_bndr) `thenSmpl_`
1375 returnSmpl (re_cast scrut)
1377 identity_alt (con, args, rhs) = check_eq con args (de_cast rhs)
1379 check_eq DEFAULT _ (Var v) = v == case_bndr
1380 check_eq (LitAlt lit') _ (Lit lit) = lit == lit'
1381 check_eq (DataAlt con) args rhs = rhs `cheapEqExpr` mkConApp con (arg_tys ++ varsToCoreExprs args)
1382 || rhs `cheapEqExpr` Var case_bndr
1383 check_eq con args rhs = False
1385 arg_tys = map Type (tyConAppArgs (idType case_bndr))
1388 -- case e of x { _ -> x `cast` c }
1389 -- And we definitely want to eliminate this case, to give
1391 -- So we throw away the cast from the RHS, and reconstruct
1392 -- it at the other end. All the RHS casts must be the same
1393 -- if (all identity_alt alts) holds.
1395 -- Don't worry about nested casts, because the simplifier combines them
1396 de_cast (Cast e _) = e
1399 re_cast scrut = case head alts of
1400 (_,_,Cast _ co) -> Cast scrut co
1405 --------------------------------------------------
1407 --------------------------------------------------
1408 mkCase scrut bndr ty alts = returnSmpl (Case scrut bndr ty alts)
1412 When adding auxiliary bindings for the case binder, it's worth checking if
1413 its dead, because it often is, and occasionally these mkCase transformations
1414 cascade rather nicely.
1417 bindCaseBndr bndr rhs body
1418 | isDeadBinder bndr = body
1419 | otherwise = bindNonRec bndr rhs body