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(..), ArgInfo(..),
17 contIsDupable, contResultType, contIsTrivial, contArgs, dropArgs,
18 countValArgs, countArgs, splitInlineCont,
19 mkBoringStop, mkLazyArgStop, contIsRhsOrArg,
20 interestingCallContext, interestingArgContext,
22 interestingArg, mkArgInfo,
27 #include "HsVersions.h"
33 import qualified CoreSubst
40 import Var ( isCoVar )
43 import Type hiding( substTy )
44 import Coercion ( coercionKind )
46 import Unify ( dataConCannotMatch )
58 %************************************************************************
62 %************************************************************************
64 A SimplCont allows the simplifier to traverse the expression in a
65 zipper-like fashion. The SimplCont represents the rest of the expression,
66 "above" the point of interest.
68 You can also think of a SimplCont as an "evaluation context", using
69 that term in the way it is used for operational semantics. This is the
70 way I usually think of it, For example you'll often see a syntax for
71 evaluation context looking like
72 C ::= [] | C e | case C of alts | C `cast` co
73 That's the kind of thing we are doing here, and I use that syntax in
78 * A SimplCont describes a *strict* context (just like
79 evaluation contexts do). E.g. Just [] is not a SimplCont
81 * A SimplCont describes a context that *does not* bind
82 any variables. E.g. \x. [] is not a SimplCont
86 = Stop -- An empty context, or hole, []
87 CallCtxt -- True <=> There is something interesting about
88 -- the context, and hence the inliner
89 -- should be a bit keener (see interestingCallContext)
91 -- This is an argument of a function that has RULES
92 -- Inlining the call might allow the rule to fire
94 | CoerceIt -- C `cast` co
95 OutCoercion -- The coercion simplified
100 InExpr SimplEnv -- The argument and its static env
103 | Select -- case C of alts
105 InId [InAlt] SimplEnv -- The case binder, alts, and subst-env
108 -- The two strict forms have no DupFlag, because we never duplicate them
109 | StrictBind -- (\x* \xs. e) C
110 InId [InBndr] -- let x* = [] in e
111 InExpr SimplEnv -- is a special case
116 CallCtxt -- Whether *this* argument position is interesting
117 ArgInfo -- Whether the function at the head of e has rules, etc
118 SimplCont -- plus strictness flags for *further* args
122 ai_rules :: Bool, -- Function has rules (recursively)
123 -- => be keener to inline in all args
124 ai_strs :: [Bool], -- Strictness of arguments
125 -- Usually infinite, but if it is finite it guarantees
126 -- that the function diverges after being given
127 -- that number of args
128 ai_discs :: [Int] -- Discounts for arguments; non-zero => be keener to inline
132 instance Outputable SimplCont where
133 ppr (Stop interesting) = ptext (sLit "Stop") <> brackets (ppr interesting)
134 ppr (ApplyTo dup arg _ cont) = ((ptext (sLit "ApplyTo") <+> ppr dup <+> pprParendExpr arg)
135 {- $$ nest 2 (pprSimplEnv se) -}) $$ ppr cont
136 ppr (StrictBind b _ _ _ cont) = (ptext (sLit "StrictBind") <+> ppr b) $$ ppr cont
137 ppr (StrictArg f _ _ cont) = (ptext (sLit "StrictArg") <+> ppr f) $$ ppr cont
138 ppr (Select dup bndr alts _ cont) = (ptext (sLit "Select") <+> ppr dup <+> ppr bndr) $$
139 (nest 4 (ppr alts)) $$ ppr cont
140 ppr (CoerceIt co cont) = (ptext (sLit "CoerceIt") <+> ppr co) $$ ppr cont
142 data DupFlag = OkToDup | NoDup
144 instance Outputable DupFlag where
145 ppr OkToDup = ptext (sLit "ok")
146 ppr NoDup = ptext (sLit "nodup")
151 mkBoringStop :: SimplCont
152 mkBoringStop = Stop BoringCtxt
154 mkLazyArgStop :: CallCtxt -> SimplCont
155 mkLazyArgStop cci = Stop cci
158 contIsRhsOrArg :: SimplCont -> Bool
159 contIsRhsOrArg (Stop {}) = True
160 contIsRhsOrArg (StrictBind {}) = True
161 contIsRhsOrArg (StrictArg {}) = True
162 contIsRhsOrArg _ = False
165 contIsDupable :: SimplCont -> Bool
166 contIsDupable (Stop {}) = True
167 contIsDupable (ApplyTo OkToDup _ _ _) = True
168 contIsDupable (Select OkToDup _ _ _ _) = True
169 contIsDupable (CoerceIt _ cont) = contIsDupable cont
170 contIsDupable _ = False
173 contIsTrivial :: SimplCont -> Bool
174 contIsTrivial (Stop {}) = True
175 contIsTrivial (ApplyTo _ (Type _) _ cont) = contIsTrivial cont
176 contIsTrivial (CoerceIt _ cont) = contIsTrivial cont
177 contIsTrivial _ = False
180 contResultType :: SimplEnv -> OutType -> SimplCont -> OutType
181 contResultType env ty cont
184 subst_ty se ty = substTy (se `setInScope` env) ty
187 go (CoerceIt co cont) _ = go cont (snd (coercionKind co))
188 go (StrictBind _ bs body se cont) _ = go cont (subst_ty se (exprType (mkLams bs body)))
189 go (StrictArg fn _ _ cont) _ = go cont (funResultTy (exprType fn))
190 go (Select _ _ alts se cont) _ = go cont (subst_ty se (coreAltsType alts))
191 go (ApplyTo _ arg se cont) ty = go cont (apply_to_arg ty arg se)
193 apply_to_arg ty (Type ty_arg) se = applyTy ty (subst_ty se ty_arg)
194 apply_to_arg ty _ _ = funResultTy ty
197 countValArgs :: SimplCont -> Int
198 countValArgs (ApplyTo _ (Type _) _ cont) = countValArgs cont
199 countValArgs (ApplyTo _ _ _ cont) = 1 + countValArgs cont
202 countArgs :: SimplCont -> Int
203 countArgs (ApplyTo _ _ _ cont) = 1 + countArgs cont
206 contArgs :: SimplCont -> ([OutExpr], SimplCont)
207 -- Uses substitution to turn each arg into an OutExpr
208 contArgs cont = go [] cont
210 go args (ApplyTo _ arg se cont) = go (substExpr se arg : args) cont
211 go args cont = (reverse args, cont)
213 dropArgs :: Int -> SimplCont -> SimplCont
214 dropArgs 0 cont = cont
215 dropArgs n (ApplyTo _ _ _ cont) = dropArgs (n-1) cont
216 dropArgs n other = pprPanic "dropArgs" (ppr n <+> ppr other)
219 splitInlineCont :: SimplCont -> Maybe (SimplCont, SimplCont)
220 -- Returns Nothing if the continuation should dissolve an InlineMe Note
221 -- Return Just (c1,c2) otherwise,
222 -- where c1 is the continuation to put inside the InlineMe
225 -- Example: (__inline_me__ (/\a. e)) ty
226 -- Here we want to do the beta-redex without dissolving the InlineMe
227 -- See test simpl017 (and Trac #1627) for a good example of why this is important
229 splitInlineCont (ApplyTo dup (Type ty) se c)
230 | Just (c1, c2) <- splitInlineCont c = Just (ApplyTo dup (Type ty) se c1, c2)
231 splitInlineCont cont@(Stop {}) = Just (mkBoringStop, cont)
232 splitInlineCont cont@(StrictBind {}) = Just (mkBoringStop, cont)
233 splitInlineCont cont@(StrictArg {}) = Just (mkBoringStop, cont)
234 splitInlineCont _ = Nothing
239 interestingArg :: OutExpr -> Bool
240 -- An argument is interesting if it has *some* structure
241 -- We are here trying to avoid unfolding a function that
242 -- is applied only to variables that have no unfolding
243 -- (i.e. they are probably lambda bound): f x y z
244 -- There is little point in inlining f here.
245 interestingArg (Var v) = hasSomeUnfolding (idUnfolding v)
246 -- Was: isValueUnfolding (idUnfolding v')
247 -- But that seems over-pessimistic
249 -- This accounts for an argument like
250 -- () or [], which is definitely interesting
251 interestingArg (Type _) = False
252 interestingArg (App fn (Type _)) = interestingArg fn
253 interestingArg (Note _ a) = interestingArg a
255 -- Idea (from Sam B); I'm not sure if it's a good idea, so commented out for now
256 -- interestingArg expr | isUnLiftedType (exprType expr)
257 -- -- Unlifted args are only ever interesting if we know what they are
262 interestingArg _ = True
263 -- Consider let x = 3 in f x
264 -- The substitution will contain (x -> ContEx 3), and we want to
265 -- to say that x is an interesting argument.
266 -- But consider also (\x. f x y) y
267 -- The substitution will contain (x -> ContEx y), and we want to say
268 -- that x is not interesting (assuming y has no unfolding)
272 Comment about interestingCallContext
273 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
274 We want to avoid inlining an expression where there can't possibly be
275 any gain, such as in an argument position. Hence, if the continuation
276 is interesting (eg. a case scrutinee, application etc.) then we
277 inline, otherwise we don't.
279 Previously some_benefit used to return True only if the variable was
280 applied to some value arguments. This didn't work:
282 let x = _coerce_ (T Int) Int (I# 3) in
283 case _coerce_ Int (T Int) x of
286 we want to inline x, but can't see that it's a constructor in a case
287 scrutinee position, and some_benefit is False.
291 dMonadST = _/\_ t -> :Monad (g1 _@_ t, g2 _@_ t, g3 _@_ t)
293 .... case dMonadST _@_ x0 of (a,b,c) -> ....
295 we'd really like to inline dMonadST here, but we *don't* want to
296 inline if the case expression is just
298 case x of y { DEFAULT -> ... }
300 since we can just eliminate this case instead (x is in WHNF). Similar
301 applies when x is bound to a lambda expression. Hence
302 contIsInteresting looks for case expressions with just a single
307 interestingCallContext :: SimplCont -> CallCtxt
308 interestingCallContext cont
311 interestingCtxt = ArgCtxt False 2 -- Give *some* incentive!
313 interesting (Select _ bndr _ _ _)
314 | isDeadBinder bndr = CaseCtxt
315 | otherwise = interestingCtxt
317 interesting (ApplyTo {}) = interestingCtxt
318 -- Can happen if we have (coerce t (f x)) y
319 -- Perhaps interestingCtxt 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 motivation for inlining it
323 interesting (StrictArg _ cci _ _) = cci
324 interesting (StrictBind {}) = BoringCtxt
325 interesting (Stop cci) = cci
326 interesting (CoerceIt _ cont) = interesting cont
327 -- If this call is the arg of a strict function, the context
328 -- is a bit interesting. If we inline here, we may get useful
329 -- evaluation information to avoid repeated evals: e.g.
331 -- Here the contIsInteresting makes the '*' keener to inline,
332 -- which in turn exposes a constructor which makes the '+' inline.
333 -- Assuming that +,* aren't small enough to inline regardless.
335 -- It's also very important to inline in a strict context for things
338 -- Here, the context of (f x) is strict, and if f's unfolding is
339 -- a build it's *great* to inline it here. So we must ensure that
340 -- the context for (f x) is not totally uninteresting.
345 -> Int -- Number of value args
346 -> SimplCont -- Context of the cal
349 mkArgInfo fun n_val_args call_cont
350 | n_val_args < idArity fun -- Note [Unsaturated functions]
351 = ArgInfo { ai_rules = False
352 , ai_strs = vanilla_stricts
353 , ai_discs = vanilla_discounts }
355 = ArgInfo { ai_rules = interestingArgContext fun call_cont
356 , ai_strs = add_type_str (idType fun) arg_stricts
357 , ai_discs = arg_discounts }
359 vanilla_discounts, arg_discounts :: [Int]
360 vanilla_discounts = repeat 0
361 arg_discounts = case idUnfolding fun of
362 CoreUnfolding _ _ _ _ (UnfoldIfGoodArgs _ discounts _ _)
363 -> discounts ++ vanilla_discounts
364 _ -> vanilla_discounts
366 vanilla_stricts, arg_stricts :: [Bool]
367 vanilla_stricts = repeat False
370 = case splitStrictSig (idNewStrictness fun) of
371 (demands, result_info)
372 | not (demands `lengthExceeds` n_val_args)
373 -> -- Enough args, use the strictness given.
374 -- For bottoming functions we used to pretend that the arg
375 -- is lazy, so that we don't treat the arg as an
376 -- interesting context. This avoids substituting
377 -- top-level bindings for (say) strings into
378 -- calls to error. But now we are more careful about
379 -- inlining lone variables, so its ok (see SimplUtils.analyseCont)
380 if isBotRes result_info then
381 map isStrictDmd demands -- Finite => result is bottom
383 map isStrictDmd demands ++ vanilla_stricts
385 -> WARN( True, text "More demands than arity" <+> ppr fun <+> ppr (idArity fun)
386 <+> ppr n_val_args <+> ppr demands )
387 vanilla_stricts -- Not enough args, or no strictness
389 add_type_str :: Type -> [Bool] -> [Bool]
390 -- If the function arg types are strict, record that in the 'strictness bits'
391 -- No need to instantiate because unboxed types (which dominate the strict
392 -- types) can't instantiate type variables.
393 -- add_type_str is done repeatedly (for each call); might be better
394 -- once-for-all in the function
395 -- But beware primops/datacons with no strictness
396 add_type_str _ [] = []
397 add_type_str fun_ty strs -- Look through foralls
398 | Just (_, fun_ty') <- splitForAllTy_maybe fun_ty -- Includes coercions
399 = add_type_str fun_ty' strs
400 add_type_str fun_ty (str:strs) -- Add strict-type info
401 | Just (arg_ty, fun_ty') <- splitFunTy_maybe fun_ty
402 = (str || isStrictType arg_ty) : add_type_str fun_ty' strs
406 {- Note [Unsaturated functions]
407 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
408 Consider (test eyeball/inline4)
411 where f has arity 2. Then we do not want to inline 'x', because
412 it'll just be floated out again. Even if f has lots of discounts
413 on its first argument -- it must be saturated for these to kick in
416 interestingArgContext :: Id -> SimplCont -> Bool
417 -- If the argument has form (f x y), where x,y are boring,
418 -- and f is marked INLINE, then we don't want to inline f.
419 -- But if the context of the argument is
421 -- where g has rules, then we *do* want to inline f, in case it
422 -- exposes a rule that might fire. Similarly, if the context is
424 -- where h has rules, then we do want to inline f; hence the
425 -- call_cont argument to interestingArgContext
427 -- The interesting_arg_ctxt flag makes this happen; if it's
428 -- set, the inliner gets just enough keener to inline f
429 -- regardless of how boring f's arguments are, if it's marked INLINE
431 -- The alternative would be to *always* inline an INLINE function,
432 -- regardless of how boring its context is; but that seems overkill
433 -- For example, it'd mean that wrapper functions were always inlined
434 interestingArgContext fn call_cont
435 = idHasRules fn || go call_cont
437 go (Select {}) = False
438 go (ApplyTo {}) = False
439 go (StrictArg _ cci _ _) = interesting cci
440 go (StrictBind {}) = False -- ??
441 go (CoerceIt _ c) = go c
442 go (Stop cci) = interesting cci
444 interesting (ArgCtxt rules _) = rules
445 interesting _ = False
450 %************************************************************************
452 \subsection{Decisions about inlining}
454 %************************************************************************
456 Inlining is controlled partly by the SimplifierMode switch. This has two
459 SimplGently (a) Simplifying before specialiser/full laziness
460 (b) Simplifiying inside INLINE pragma
461 (c) Simplifying the LHS of a rule
462 (d) Simplifying a GHCi expression or Template
465 SimplPhase n _ Used at all other times
467 The key thing about SimplGently is that it does no call-site inlining.
468 Before full laziness we must be careful not to inline wrappers,
469 because doing so inhibits floating
470 e.g. ...(case f x of ...)...
471 ==> ...(case (case x of I# x# -> fw x#) of ...)...
472 ==> ...(case x of I# x# -> case fw x# of ...)...
473 and now the redex (f x) isn't floatable any more.
475 The no-inlining thing is also important for Template Haskell. You might be
476 compiling in one-shot mode with -O2; but when TH compiles a splice before
477 running it, we don't want to use -O2. Indeed, we don't want to inline
478 anything, because the byte-code interpreter might get confused about
479 unboxed tuples and suchlike.
483 SimplGently is also used as the mode to simplify inside an InlineMe note.
486 inlineMode :: SimplifierMode
487 inlineMode = SimplGently
490 It really is important to switch off inlinings inside such
491 expressions. Consider the following example
497 in ...g...g...g...g...g...
499 Now, if that's the ONLY occurrence of f, it will be inlined inside g,
500 and thence copied multiple times when g is inlined.
503 This function may be inlinined in other modules, so we
504 don't want to remove (by inlining) calls to functions that have
505 specialisations, or that may have transformation rules in an importing
508 E.g. {-# INLINE f #-}
511 and suppose that g is strict *and* has specialisations. If we inline
512 g's wrapper, we deny f the chance of getting the specialised version
513 of g when f is inlined at some call site (perhaps in some other
516 It's also important not to inline a worker back into a wrapper.
518 wraper = inline_me (\x -> ...worker... )
519 Normally, the inline_me prevents the worker getting inlined into
520 the wrapper (initially, the worker's only call site!). But,
521 if the wrapper is sure to be called, the strictness analyser will
522 mark it 'demanded', so when the RHS is simplified, it'll get an ArgOf
523 continuation. That's why the keep_inline predicate returns True for
524 ArgOf continuations. It shouldn't do any harm not to dissolve the
525 inline-me note under these circumstances.
527 Note that the result is that we do very little simplification
530 all xs = foldr (&&) True xs
531 any p = all . map p {-# INLINE any #-}
533 Problem: any won't get deforested, and so if it's exported and the
534 importer doesn't use the inlining, (eg passes it as an arg) then we
535 won't get deforestation at all. We havn't solved this problem yet!
538 preInlineUnconditionally
539 ~~~~~~~~~~~~~~~~~~~~~~~~
540 @preInlineUnconditionally@ examines a bndr to see if it is used just
541 once in a completely safe way, so that it is safe to discard the
542 binding inline its RHS at the (unique) usage site, REGARDLESS of how
543 big the RHS might be. If this is the case we don't simplify the RHS
544 first, but just inline it un-simplified.
546 This is much better than first simplifying a perhaps-huge RHS and then
547 inlining and re-simplifying it. Indeed, it can be at least quadratically
556 We may end up simplifying e1 N times, e2 N-1 times, e3 N-3 times etc.
557 This can happen with cascades of functions too:
564 THE MAIN INVARIANT is this:
566 ---- preInlineUnconditionally invariant -----
567 IF preInlineUnconditionally chooses to inline x = <rhs>
568 THEN doing the inlining should not change the occurrence
569 info for the free vars of <rhs>
570 ----------------------------------------------
572 For example, it's tempting to look at trivial binding like
574 and inline it unconditionally. But suppose x is used many times,
575 but this is the unique occurrence of y. Then inlining x would change
576 y's occurrence info, which breaks the invariant. It matters: y
577 might have a BIG rhs, which will now be dup'd at every occurrenc of x.
580 Even RHSs labelled InlineMe aren't caught here, because there might be
581 no benefit from inlining at the call site.
583 [Sept 01] Don't unconditionally inline a top-level thing, because that
584 can simply make a static thing into something built dynamically. E.g.
588 [Remember that we treat \s as a one-shot lambda.] No point in
589 inlining x unless there is something interesting about the call site.
591 But watch out: if you aren't careful, some useful foldr/build fusion
592 can be lost (most notably in spectral/hartel/parstof) because the
593 foldr didn't see the build. Doing the dynamic allocation isn't a big
594 deal, in fact, but losing the fusion can be. But the right thing here
595 seems to be to do a callSiteInline based on the fact that there is
596 something interesting about the call site (it's strict). Hmm. That
599 Conclusion: inline top level things gaily until Phase 0 (the last
600 phase), at which point don't.
603 preInlineUnconditionally :: SimplEnv -> TopLevelFlag -> InId -> InExpr -> Bool
604 preInlineUnconditionally env top_lvl bndr rhs
606 | opt_SimplNoPreInlining = False
607 | otherwise = case idOccInfo bndr of
608 IAmDead -> True -- Happens in ((\x.1) v)
609 OneOcc in_lam True int_cxt -> try_once in_lam int_cxt
613 active = case phase of
614 SimplGently -> isAlwaysActive prag
615 SimplPhase n _ -> isActive n prag
616 prag = idInlinePragma bndr
618 try_once in_lam int_cxt -- There's one textual occurrence
619 | not in_lam = isNotTopLevel top_lvl || early_phase
620 | otherwise = int_cxt && canInlineInLam rhs
622 -- Be very careful before inlining inside a lambda, becuase (a) we must not
623 -- invalidate occurrence information, and (b) we want to avoid pushing a
624 -- single allocation (here) into multiple allocations (inside lambda).
625 -- Inlining a *function* with a single *saturated* call would be ok, mind you.
626 -- || (if is_cheap && not (canInlineInLam rhs) then pprTrace "preinline" (ppr bndr <+> ppr rhs) ok else ok)
628 -- is_cheap = exprIsCheap rhs
629 -- ok = is_cheap && int_cxt
631 -- int_cxt The context isn't totally boring
632 -- E.g. let f = \ab.BIG in \y. map f xs
633 -- Don't want to substitute for f, because then we allocate
634 -- its closure every time the \y is called
635 -- But: let f = \ab.BIG in \y. map (f y) xs
636 -- Now we do want to substitute for f, even though it's not
637 -- saturated, because we're going to allocate a closure for
638 -- (f y) every time round the loop anyhow.
640 -- canInlineInLam => free vars of rhs are (Once in_lam) or Many,
641 -- so substituting rhs inside a lambda doesn't change the occ info.
642 -- Sadly, not quite the same as exprIsHNF.
643 canInlineInLam (Lit _) = True
644 canInlineInLam (Lam b e) = isRuntimeVar b || canInlineInLam e
645 canInlineInLam (Note _ e) = canInlineInLam e
646 canInlineInLam _ = False
648 early_phase = case phase of
649 SimplPhase 0 _ -> False
651 -- If we don't have this early_phase test, consider
652 -- x = length [1,2,3]
653 -- The full laziness pass carefully floats all the cons cells to
654 -- top level, and preInlineUnconditionally floats them all back in.
655 -- Result is (a) static allocation replaced by dynamic allocation
656 -- (b) many simplifier iterations because this tickles
657 -- a related problem; only one inlining per pass
659 -- On the other hand, I have seen cases where top-level fusion is
660 -- lost if we don't inline top level thing (e.g. string constants)
661 -- Hence the test for phase zero (which is the phase for all the final
662 -- simplifications). Until phase zero we take no special notice of
663 -- top level things, but then we become more leery about inlining
668 postInlineUnconditionally
669 ~~~~~~~~~~~~~~~~~~~~~~~~~
670 @postInlineUnconditionally@ decides whether to unconditionally inline
671 a thing based on the form of its RHS; in particular if it has a
672 trivial RHS. If so, we can inline and discard the binding altogether.
674 NB: a loop breaker has must_keep_binding = True and non-loop-breakers
675 only have *forward* references Hence, it's safe to discard the binding
677 NOTE: This isn't our last opportunity to inline. We're at the binding
678 site right now, and we'll get another opportunity when we get to the
681 Note that we do this unconditional inlining only for trival RHSs.
682 Don't inline even WHNFs inside lambdas; doing so may simply increase
683 allocation when the function is called. This isn't the last chance; see
686 NB: Even inline pragmas (e.g. IMustBeINLINEd) are ignored here Why?
687 Because we don't even want to inline them into the RHS of constructor
688 arguments. See NOTE above
690 NB: At one time even NOINLINE was ignored here: if the rhs is trivial
691 it's best to inline it anyway. We often get a=E; b=a from desugaring,
692 with both a and b marked NOINLINE. But that seems incompatible with
693 our new view that inlining is like a RULE, so I'm sticking to the 'active'
697 postInlineUnconditionally
698 :: SimplEnv -> TopLevelFlag
699 -> InId -- The binder (an OutId would be fine too)
700 -> OccInfo -- From the InId
704 postInlineUnconditionally env top_lvl bndr occ_info rhs unfolding
706 | isLoopBreaker occ_info = False -- If it's a loop-breaker of any kind, don't inline
707 -- because it might be referred to "earlier"
708 | isExportedId bndr = False
709 | exprIsTrivial rhs = True
712 -- The point of examining occ_info here is that for *non-values*
713 -- that occur outside a lambda, the call-site inliner won't have
714 -- a chance (becuase it doesn't know that the thing
715 -- only occurs once). The pre-inliner won't have gotten
716 -- it either, if the thing occurs in more than one branch
717 -- So the main target is things like
720 -- True -> case x of ...
721 -- False -> case x of ...
722 -- I'm not sure how important this is in practice
723 OneOcc in_lam _one_br int_cxt -- OneOcc => no code-duplication issue
724 -> smallEnoughToInline unfolding -- Small enough to dup
725 -- ToDo: consider discount on smallEnoughToInline if int_cxt is true
727 -- NB: Do NOT inline arbitrarily big things, even if one_br is True
728 -- Reason: doing so risks exponential behaviour. We simplify a big
729 -- expression, inline it, and simplify it again. But if the
730 -- very same thing happens in the big expression, we get
732 -- PRINCIPLE: when we've already simplified an expression once,
733 -- make sure that we only inline it if it's reasonably small.
735 && ((isNotTopLevel top_lvl && not in_lam) ||
736 -- But outside a lambda, we want to be reasonably aggressive
737 -- about inlining into multiple branches of case
738 -- e.g. let x = <non-value>
739 -- in case y of { C1 -> ..x..; C2 -> ..x..; C3 -> ... }
740 -- Inlining can be a big win if C3 is the hot-spot, even if
741 -- the uses in C1, C2 are not 'interesting'
742 -- An example that gets worse if you add int_cxt here is 'clausify'
744 (isCheapUnfolding unfolding && int_cxt))
745 -- isCheap => acceptable work duplication; in_lam may be true
746 -- int_cxt to prevent us inlining inside a lambda without some
747 -- good reason. See the notes on int_cxt in preInlineUnconditionally
749 IAmDead -> True -- This happens; for example, the case_bndr during case of
750 -- known constructor: case (a,b) of x { (p,q) -> ... }
751 -- Here x isn't mentioned in the RHS, so we don't want to
752 -- create the (dead) let-binding let x = (a,b) in ...
756 -- Here's an example that we don't handle well:
757 -- let f = if b then Left (\x.BIG) else Right (\y.BIG)
758 -- in \y. ....case f of {...} ....
759 -- Here f is used just once, and duplicating the case work is fine (exprIsCheap).
761 -- - We can't preInlineUnconditionally because that woud invalidate
762 -- the occ info for b.
763 -- - We can't postInlineUnconditionally because the RHS is big, and
764 -- that risks exponential behaviour
765 -- - We can't call-site inline, because the rhs is big
769 active = case getMode env of
770 SimplGently -> isAlwaysActive prag
771 SimplPhase n _ -> isActive n prag
772 prag = idInlinePragma bndr
774 activeInline :: SimplEnv -> OutId -> Bool
776 = case getMode env of
778 -- No inlining at all when doing gentle stuff,
779 -- except for local things that occur once (pre/postInlineUnconditionally)
780 -- The reason is that too little clean-up happens if you
781 -- don't inline use-once things. Also a bit of inlining is *good* for
782 -- full laziness; it can expose constant sub-expressions.
783 -- Example in spectral/mandel/Mandel.hs, where the mandelset
784 -- function gets a useful let-float if you inline windowToViewport
786 -- NB: we used to have a second exception, for data con wrappers.
787 -- On the grounds that we use gentle mode for rule LHSs, and
788 -- they match better when data con wrappers are inlined.
789 -- But that only really applies to the trivial wrappers (like (:)),
790 -- and they are now constructed as Compulsory unfoldings (in MkId)
791 -- so they'll happen anyway.
793 SimplPhase n _ -> isActive n prag
795 prag = idInlinePragma id
797 activeRule :: DynFlags -> SimplEnv -> Maybe (Activation -> Bool)
798 -- Nothing => No rules at all
799 activeRule dflags env
800 | not (dopt Opt_RewriteRules dflags)
801 = Nothing -- Rewriting is off
803 = case getMode env of
804 SimplGently -> Just isAlwaysActive
805 -- Used to be Nothing (no rules in gentle mode)
806 -- Main motivation for changing is that I wanted
807 -- lift String ===> ...
808 -- to work in Template Haskell when simplifying
809 -- splices, so we get simpler code for literal strings
810 SimplPhase n _ -> Just (isActive n)
814 %************************************************************************
818 %************************************************************************
821 mkLam :: [OutBndr] -> OutExpr -> SimplM OutExpr
822 -- mkLam tries three things
823 -- a) eta reduction, if that gives a trivial expression
824 -- b) eta expansion [only if there are some value lambdas]
829 = do { dflags <- getDOptsSmpl
830 ; mkLam' dflags bndrs body }
832 mkLam' :: DynFlags -> [OutBndr] -> OutExpr -> SimplM OutExpr
833 mkLam' dflags bndrs (Cast body co)
834 | not (any bad bndrs)
835 -- Note [Casts and lambdas]
836 = do { lam <- mkLam' dflags bndrs body
837 ; return (mkCoerce (mkPiTypes bndrs co) lam) }
839 co_vars = tyVarsOfType co
840 bad bndr = isCoVar bndr && bndr `elemVarSet` co_vars
842 mkLam' dflags bndrs body
843 | dopt Opt_DoEtaReduction dflags,
844 Just etad_lam <- tryEtaReduce bndrs body
845 = do { tick (EtaReduction (head bndrs))
848 | dopt Opt_DoLambdaEtaExpansion dflags,
849 any isRuntimeVar bndrs
850 = do { body' <- tryEtaExpansion dflags body
851 ; return (mkLams bndrs body') }
854 = return (mkLams bndrs body)
857 Note [Casts and lambdas]
858 ~~~~~~~~~~~~~~~~~~~~~~~~
860 (\x. (\y. e) `cast` g1) `cast` g2
861 There is a danger here that the two lambdas look separated, and the
862 full laziness pass might float an expression to between the two.
864 So this equation in mkLam' floats the g1 out, thus:
865 (\x. e `cast` g1) --> (\x.e) `cast` (tx -> g1)
868 In general, this floats casts outside lambdas, where (I hope) they
869 might meet and cancel with some other cast:
870 \x. e `cast` co ===> (\x. e) `cast` (tx -> co)
871 /\a. e `cast` co ===> (/\a. e) `cast` (/\a. co)
872 /\g. e `cast` co ===> (/\g. e) `cast` (/\g. co)
875 Notice that it works regardless of 'e'. Originally it worked only
876 if 'e' was itself a lambda, but in some cases that resulted in
877 fruitless iteration in the simplifier. A good example was when
878 compiling Text.ParserCombinators.ReadPrec, where we had a definition
879 like (\x. Get `cast` g)
880 where Get is a constructor with nonzero arity. Then mkLam eta-expanded
881 the Get, and the next iteration eta-reduced it, and then eta-expanded
884 Note also the side condition for the case of coercion binders.
885 It does not make sense to transform
886 /\g. e `cast` g ==> (/\g.e) `cast` (/\g.g)
887 because the latter is not well-kinded.
889 -- c) floating lets out through big lambdas
890 -- [only if all tyvar lambdas, and only if this lambda
891 -- is the RHS of a let]
893 {- Sept 01: I'm experimenting with getting the
894 full laziness pass to float out past big lambdsa
895 | all isTyVar bndrs, -- Only for big lambdas
896 contIsRhs cont -- Only try the rhs type-lambda floating
897 -- if this is indeed a right-hand side; otherwise
898 -- we end up floating the thing out, only for float-in
899 -- to float it right back in again!
900 = do (floats, body') <- tryRhsTyLam env bndrs body
901 return (floats, mkLams bndrs body')
905 %************************************************************************
909 %************************************************************************
911 Note [Eta reduction conditions]
912 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
913 We try for eta reduction here, but *only* if we get all the way to an
914 trivial expression. We don't want to remove extra lambdas unless we
915 are going to avoid allocating this thing altogether.
917 There are some particularly delicate points here:
919 * Eta reduction is not valid in general:
921 This matters, partly for old-fashioned correctness reasons but,
922 worse, getting it wrong can yield a seg fault. Consider
924 h y = case (case y of { True -> f `seq` True; False -> False }) of
925 True -> ...; False -> ...
927 If we (unsoundly) eta-reduce f to get f=f, the strictness analyser
928 says f=bottom, and replaces the (f `seq` True) with just
929 (f `cast` unsafe-co). BUT, as thing stand, 'f' got arity 1, and it
930 *keeps* arity 1 (perhaps also wrongly). So CorePrep eta-expands
931 the definition again, so that it does not termninate after all.
932 Result: seg-fault because the boolean case actually gets a function value.
935 So it's important to to the right thing.
937 * We need to be careful if we just look at f's arity. Currently (Dec07),
938 f's arity is visible in its own RHS (see Note [Arity robustness] in
939 SimplEnv) so we must *not* trust the arity when checking that 'f' is
940 a value. Instead, look at the unfolding.
942 However for GlobalIds we can look at the arity; and for primops we
943 must, since they have no unfolding.
945 * Regardless of whether 'f' is a value, we always want to
946 reduce (/\a -> f a) to f
947 This came up in a RULE: foldr (build (/\a -> g a))
948 did not match foldr (build (/\b -> ...something complex...))
949 The type checker can insert these eta-expanded versions,
950 with both type and dictionary lambdas; hence the slightly
953 These delicacies are why we don't use exprIsTrivial and exprIsHNF here.
957 tryEtaReduce :: [OutBndr] -> OutExpr -> Maybe OutExpr
958 tryEtaReduce bndrs body
959 = go (reverse bndrs) body
961 go (b : bs) (App fun arg) | ok_arg b arg = go bs fun -- Loop round
962 go [] fun | ok_fun fun = Just fun -- Success!
963 go _ _ = Nothing -- Failure!
965 -- Note [Eta reduction conditions]
966 ok_fun (App fun (Type ty))
967 | not (any (`elemVarSet` tyVarsOfType ty) bndrs)
970 = not (fun_id `elem` bndrs)
971 && (ok_fun_id fun_id || all ok_lam bndrs)
975 | isLocalId fun = isEvaldUnfolding (idUnfolding fun)
976 | isDataConWorkId fun = True
977 | isGlobalId fun = idArity fun > 0
978 | otherwise = panic "tryEtaReduce/ok_fun_id"
980 ok_lam v = isTyVar v || isDictId v
982 ok_arg b arg = varToCoreExpr b `cheapEqExpr` arg
986 %************************************************************************
990 %************************************************************************
994 f = \x1..xn -> N ==> f = \x1..xn y1..ym -> N y1..ym
997 where (in both cases)
999 * The xi can include type variables
1001 * The yi are all value variables
1003 * N is a NORMAL FORM (i.e. no redexes anywhere)
1004 wanting a suitable number of extra args.
1006 The biggest reason for doing this is for cases like
1012 Here we want to get the lambdas together. A good exmaple is the nofib
1013 program fibheaps, which gets 25% more allocation if you don't do this
1016 We may have to sandwich some coerces between the lambdas
1017 to make the types work. exprEtaExpandArity looks through coerces
1018 when computing arity; and etaExpand adds the coerces as necessary when
1019 actually computing the expansion.
1022 tryEtaExpansion :: DynFlags -> OutExpr -> SimplM OutExpr
1023 -- There is at least one runtime binder in the binders
1024 tryEtaExpansion dflags body = do
1026 return (etaExpand fun_arity us body (exprType body))
1028 fun_arity = exprEtaExpandArity dflags body
1032 %************************************************************************
1034 \subsection{Floating lets out of big lambdas}
1036 %************************************************************************
1038 Note [Floating and type abstraction]
1039 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1042 We'd like to float this to
1045 x = /\a. C (y1 a) (y2 a)
1046 for the usual reasons: we want to inline x rather vigorously.
1048 You may think that this kind of thing is rare. But in some programs it is
1049 common. For example, if you do closure conversion you might get:
1051 data a :-> b = forall e. (e -> a -> b) :$ e
1053 f_cc :: forall a. a :-> a
1054 f_cc = /\a. (\e. id a) :$ ()
1056 Now we really want to inline that f_cc thing so that the
1057 construction of the closure goes away.
1059 So I have elaborated simplLazyBind to understand right-hand sides that look
1063 and treat them specially. The real work is done in SimplUtils.abstractFloats,
1064 but there is quite a bit of plumbing in simplLazyBind as well.
1066 The same transformation is good when there are lets in the body:
1068 /\abc -> let(rec) x = e in b
1070 let(rec) x' = /\abc -> let x = x' a b c in e
1072 /\abc -> let x = x' a b c in b
1074 This is good because it can turn things like:
1076 let f = /\a -> letrec g = ... g ... in g
1078 letrec g' = /\a -> ... g' a ...
1080 let f = /\ a -> g' a
1082 which is better. In effect, it means that big lambdas don't impede
1085 This optimisation is CRUCIAL in eliminating the junk introduced by
1086 desugaring mutually recursive definitions. Don't eliminate it lightly!
1088 [May 1999] If we do this transformation *regardless* then we can
1089 end up with some pretty silly stuff. For example,
1092 st = /\ s -> let { x1=r1 ; x2=r2 } in ...
1097 st = /\s -> ...[y1 s/x1, y2 s/x2]
1100 Unless the "..." is a WHNF there is really no point in doing this.
1101 Indeed it can make things worse. Suppose x1 is used strictly,
1104 x1* = case f y of { (a,b) -> e }
1106 If we abstract this wrt the tyvar we then can't do the case inline
1107 as we would normally do.
1109 That's why the whole transformation is part of the same process that
1110 floats let-bindings and constructor arguments out of RHSs. In particular,
1111 it is guarded by the doFloatFromRhs call in simplLazyBind.
1115 abstractFloats :: [OutTyVar] -> SimplEnv -> OutExpr -> SimplM ([OutBind], OutExpr)
1116 abstractFloats main_tvs body_env body
1117 = ASSERT( notNull body_floats )
1118 do { (subst, float_binds) <- mapAccumLM abstract empty_subst body_floats
1119 ; return (float_binds, CoreSubst.substExpr subst body) }
1121 main_tv_set = mkVarSet main_tvs
1122 body_floats = getFloats body_env
1123 empty_subst = CoreSubst.mkEmptySubst (seInScope body_env)
1125 abstract :: CoreSubst.Subst -> OutBind -> SimplM (CoreSubst.Subst, OutBind)
1126 abstract subst (NonRec id rhs)
1127 = do { (poly_id, poly_app) <- mk_poly tvs_here id
1128 ; let poly_rhs = mkLams tvs_here rhs'
1129 subst' = CoreSubst.extendIdSubst subst id poly_app
1130 ; return (subst', (NonRec poly_id poly_rhs)) }
1132 rhs' = CoreSubst.substExpr subst rhs
1133 tvs_here | any isCoVar main_tvs = main_tvs -- Note [Abstract over coercions]
1135 = varSetElems (main_tv_set `intersectVarSet` exprSomeFreeVars isTyVar rhs')
1137 -- Abstract only over the type variables free in the rhs
1138 -- wrt which the new binding is abstracted. But the naive
1139 -- approach of abstract wrt the tyvars free in the Id's type
1141 -- /\ a b -> let t :: (a,b) = (e1, e2)
1144 -- Here, b isn't free in x's type, but we must nevertheless
1145 -- abstract wrt b as well, because t's type mentions b.
1146 -- Since t is floated too, we'd end up with the bogus:
1147 -- poly_t = /\ a b -> (e1, e2)
1148 -- poly_x = /\ a -> fst (poly_t a *b*)
1149 -- So for now we adopt the even more naive approach of
1150 -- abstracting wrt *all* the tyvars. We'll see if that
1151 -- gives rise to problems. SLPJ June 98
1153 abstract subst (Rec prs)
1154 = do { (poly_ids, poly_apps) <- mapAndUnzipM (mk_poly tvs_here) ids
1155 ; let subst' = CoreSubst.extendSubstList subst (ids `zip` poly_apps)
1156 poly_rhss = [mkLams tvs_here (CoreSubst.substExpr subst' rhs) | rhs <- rhss]
1157 ; return (subst', Rec (poly_ids `zip` poly_rhss)) }
1159 (ids,rhss) = unzip prs
1160 -- For a recursive group, it's a bit of a pain to work out the minimal
1161 -- set of tyvars over which to abstract:
1162 -- /\ a b c. let x = ...a... in
1163 -- letrec { p = ...x...q...
1164 -- q = .....p...b... } in
1166 -- Since 'x' is abstracted over 'a', the {p,q} group must be abstracted
1167 -- over 'a' (because x is replaced by (poly_x a)) as well as 'b'.
1168 -- Since it's a pain, we just use the whole set, which is always safe
1170 -- If you ever want to be more selective, remember this bizarre case too:
1172 -- Here, we must abstract 'x' over 'a'.
1175 mk_poly tvs_here var
1176 = do { uniq <- getUniqueM
1177 ; let poly_name = setNameUnique (idName var) uniq -- Keep same name
1178 poly_ty = mkForAllTys tvs_here (idType var) -- But new type of course
1179 poly_id = transferPolyIdInfo var $ -- Note [transferPolyIdInfo] in Id.lhs
1180 mkLocalId poly_name poly_ty
1181 ; return (poly_id, mkTyApps (Var poly_id) (mkTyVarTys tvs_here)) }
1182 -- In the olden days, it was crucial to copy the occInfo of the original var,
1183 -- because we were looking at occurrence-analysed but as yet unsimplified code!
1184 -- In particular, we mustn't lose the loop breakers. BUT NOW we are looking
1185 -- at already simplified code, so it doesn't matter
1187 -- It's even right to retain single-occurrence or dead-var info:
1188 -- Suppose we started with /\a -> let x = E in B
1189 -- where x occurs once in B. Then we transform to:
1190 -- let x' = /\a -> E in /\a -> let x* = x' a in B
1191 -- where x* has an INLINE prag on it. Now, once x* is inlined,
1192 -- the occurrences of x' will be just the occurrences originally
1196 Note [Abstract over coercions]
1197 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1198 If a coercion variable (g :: a ~ Int) is free in the RHS, then so is the
1199 type variable a. Rather than sort this mess out, we simply bale out and abstract
1200 wrt all the type variables if any of them are coercion variables.
1203 Historical note: if you use let-bindings instead of a substitution, beware of this:
1205 -- Suppose we start with:
1207 -- x = /\ a -> let g = G in E
1209 -- Then we'll float to get
1211 -- x = let poly_g = /\ a -> G
1212 -- in /\ a -> let g = poly_g a in E
1214 -- But now the occurrence analyser will see just one occurrence
1215 -- of poly_g, not inside a lambda, so the simplifier will
1216 -- PreInlineUnconditionally poly_g back into g! Badk to square 1!
1217 -- (I used to think that the "don't inline lone occurrences" stuff
1218 -- would stop this happening, but since it's the *only* occurrence,
1219 -- PreInlineUnconditionally kicks in first!)
1221 -- Solution: put an INLINE note on g's RHS, so that poly_g seems
1222 -- to appear many times. (NB: mkInlineMe eliminates
1223 -- such notes on trivial RHSs, so do it manually.)
1225 %************************************************************************
1229 %************************************************************************
1231 prepareAlts tries these things:
1233 1. If several alternatives are identical, merge them into
1234 a single DEFAULT alternative. I've occasionally seen this
1235 making a big difference:
1237 case e of =====> case e of
1238 C _ -> f x D v -> ....v....
1239 D v -> ....v.... DEFAULT -> f x
1242 The point is that we merge common RHSs, at least for the DEFAULT case.
1243 [One could do something more elaborate but I've never seen it needed.]
1244 To avoid an expensive test, we just merge branches equal to the *first*
1245 alternative; this picks up the common cases
1246 a) all branches equal
1247 b) some branches equal to the DEFAULT (which occurs first)
1250 case e of b { ==> case e of b {
1251 p1 -> rhs1 p1 -> rhs1
1253 pm -> rhsm pm -> rhsm
1254 _ -> case b of b' { pn -> let b'=b in rhsn
1256 ... po -> let b'=b in rhso
1257 po -> rhso _ -> let b'=b in rhsd
1261 which merges two cases in one case when -- the default alternative of
1262 the outer case scrutises the same variable as the outer case This
1263 transformation is called Case Merging. It avoids that the same
1264 variable is scrutinised multiple times.
1267 The case where transformation (1) showed up was like this (lib/std/PrelCError.lhs):
1273 where @is@ was something like
1275 p `is` n = p /= (-1) && p == n
1277 This gave rise to a horrible sequence of cases
1284 and similarly in cascade for all the join points!
1287 ~~~~~~~~~~~~~~~~~~~~
1288 We do this *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.
1293 prepareAlts :: SimplEnv -> OutExpr -> OutId -> [InAlt] -> SimplM ([AltCon], [InAlt])
1294 prepareAlts env scrut case_bndr' alts
1295 = do { dflags <- getDOptsSmpl
1296 ; alts <- combineIdenticalAlts case_bndr' alts
1298 ; let (alts_wo_default, maybe_deflt) = findDefault alts
1299 alt_cons = [con | (con,_,_) <- alts_wo_default]
1300 imposs_deflt_cons = nub (imposs_cons ++ alt_cons)
1301 -- "imposs_deflt_cons" are handled
1302 -- EITHER by the context,
1303 -- OR by a non-DEFAULT branch in this case expression.
1305 ; default_alts <- prepareDefault dflags env case_bndr' mb_tc_app
1306 imposs_deflt_cons maybe_deflt
1308 ; let trimmed_alts = filterOut impossible_alt alts_wo_default
1309 merged_alts = mergeAlts trimmed_alts default_alts
1310 -- We need the mergeAlts in case the new default_alt
1311 -- has turned into a constructor alternative.
1312 -- The merge keeps the inner DEFAULT at the front, if there is one
1313 -- and interleaves the alternatives in the right order
1315 ; return (imposs_deflt_cons, merged_alts) }
1317 mb_tc_app = splitTyConApp_maybe (idType case_bndr')
1318 Just (_, inst_tys) = mb_tc_app
1320 imposs_cons = case scrut of
1321 Var v -> otherCons (idUnfolding v)
1324 impossible_alt :: CoreAlt -> Bool
1325 impossible_alt (con, _, _) | con `elem` imposs_cons = True
1326 impossible_alt (DataAlt con, _, _) = dataConCannotMatch inst_tys con
1327 impossible_alt _ = False
1330 --------------------------------------------------
1331 -- 1. Merge identical branches
1332 --------------------------------------------------
1333 combineIdenticalAlts :: OutId -> [InAlt] -> SimplM [InAlt]
1335 combineIdenticalAlts case_bndr ((_con1,bndrs1,rhs1) : con_alts)
1336 | all isDeadBinder bndrs1, -- Remember the default
1337 length filtered_alts < length con_alts -- alternative comes first
1338 -- Also Note [Dead binders]
1339 = do { tick (AltMerge case_bndr)
1340 ; return ((DEFAULT, [], rhs1) : filtered_alts) }
1342 filtered_alts = filter keep con_alts
1343 keep (_con,bndrs,rhs) = not (all isDeadBinder bndrs && rhs `cheapEqExpr` rhs1)
1345 combineIdenticalAlts _ alts = return alts
1347 -------------------------------------------------------------------------
1348 -- Prepare the default alternative
1349 -------------------------------------------------------------------------
1350 prepareDefault :: DynFlags
1352 -> OutId -- Case binder; need just for its type. Note that as an
1353 -- OutId, it has maximum information; this is important.
1354 -- Test simpl013 is an example
1355 -> Maybe (TyCon, [Type]) -- Type of scrutinee, decomposed
1356 -> [AltCon] -- These cons can't happen when matching the default
1357 -> Maybe InExpr -- Rhs
1358 -> SimplM [InAlt] -- Still unsimplified
1359 -- We use a list because it's what mergeAlts expects,
1360 -- And becuase case-merging can cause many to show up
1362 ------- Merge nested cases ----------
1363 prepareDefault dflags env outer_bndr _bndr_ty imposs_cons (Just deflt_rhs)
1364 | dopt Opt_CaseMerge dflags
1365 , Case (Var inner_scrut_var) inner_bndr _ inner_alts <- deflt_rhs
1366 , DoneId inner_scrut_var' <- substId env inner_scrut_var
1367 -- Remember, inner_scrut_var is an InId, but outer_bndr is an OutId
1368 , inner_scrut_var' == outer_bndr
1369 -- NB: the substId means that if the outer scrutinee was a
1370 -- variable, and inner scrutinee is the same variable,
1371 -- then inner_scrut_var' will be outer_bndr
1372 -- via the magic of simplCaseBinder
1373 = do { tick (CaseMerge outer_bndr)
1375 ; let munge_rhs rhs = bindCaseBndr inner_bndr (Var outer_bndr) rhs
1376 ; return [(con, args, munge_rhs rhs) | (con, args, rhs) <- inner_alts,
1377 not (con `elem` imposs_cons) ]
1378 -- NB: filter out any imposs_cons. Example:
1381 -- DEFAULT -> case x of
1384 -- When we merge, we must ensure that e1 takes
1385 -- precedence over e2 as the value for A!
1387 -- Warning: don't call prepareAlts recursively!
1388 -- Firstly, there's no point, because inner alts have already had
1389 -- mkCase applied to them, so they won't have a case in their default
1390 -- Secondly, if you do, you get an infinite loop, because the bindCaseBndr
1391 -- in munge_rhs may put a case into the DEFAULT branch!
1394 --------- Fill in known constructor -----------
1395 prepareDefault _ _ case_bndr (Just (tycon, inst_tys)) imposs_cons (Just deflt_rhs)
1396 | -- This branch handles the case where we are
1397 -- scrutinisng an algebraic data type
1398 isAlgTyCon tycon -- It's a data type, tuple, or unboxed tuples.
1399 , not (isNewTyCon tycon) -- We can have a newtype, if we are just doing an eval:
1400 -- case x of { DEFAULT -> e }
1401 -- and we don't want to fill in a default for them!
1402 , Just all_cons <- tyConDataCons_maybe tycon
1403 , not (null all_cons) -- This is a tricky corner case. If the data type has no constructors,
1404 -- which GHC allows, then the case expression will have at most a default
1405 -- alternative. We don't want to eliminate that alternative, because the
1406 -- invariant is that there's always one alternative. It's more convenient
1408 -- case x of { DEFAULT -> e }
1409 -- as it is, rather than transform it to
1410 -- error "case cant match"
1411 -- which would be quite legitmate. But it's a really obscure corner, and
1412 -- not worth wasting code on.
1413 , let imposs_data_cons = [con | DataAlt con <- imposs_cons] -- We now know it's a data type
1414 impossible con = con `elem` imposs_data_cons || dataConCannotMatch inst_tys con
1415 = case filterOut impossible all_cons of
1416 [] -> return [] -- Eliminate the default alternative
1417 -- altogether if it can't match
1419 [con] -> -- It matches exactly one constructor, so fill it in
1420 do { tick (FillInCaseDefault case_bndr)
1422 ; let (ex_tvs, co_tvs, arg_ids) =
1423 dataConRepInstPat us con inst_tys
1424 ; return [(DataAlt con, ex_tvs ++ co_tvs ++ arg_ids, deflt_rhs)] }
1426 _ -> return [(DEFAULT, [], deflt_rhs)]
1428 | debugIsOn, isAlgTyCon tycon, [] <- tyConDataCons tycon
1429 = pprTrace "prepareDefault" (ppr case_bndr <+> ppr tycon)
1430 -- This can legitimately happen for type families
1431 $ return [(DEFAULT, [], deflt_rhs)]
1433 --------- Catch-all cases -----------
1434 prepareDefault _dflags _env _case_bndr _bndr_ty _imposs_cons (Just deflt_rhs)
1435 = return [(DEFAULT, [], deflt_rhs)]
1437 prepareDefault _dflags _env _case_bndr _bndr_ty _imposs_cons Nothing
1438 = return [] -- No default branch
1443 =================================================================================
1445 mkCase tries these things
1447 1. Eliminate the case altogether if possible
1455 and similar friends.
1459 mkCase :: OutExpr -> OutId -> [OutAlt] -- Increasing order
1462 --------------------------------------------------
1464 --------------------------------------------------
1466 mkCase scrut case_bndr alts -- Identity case
1467 | all identity_alt alts
1468 = do tick (CaseIdentity case_bndr)
1469 return (re_cast scrut)
1471 identity_alt (con, args, rhs) = check_eq con args (de_cast rhs)
1473 check_eq DEFAULT _ (Var v) = v == case_bndr
1474 check_eq (LitAlt lit') _ (Lit lit) = lit == lit'
1475 check_eq (DataAlt con) args rhs = rhs `cheapEqExpr` mkConApp con (arg_tys ++ varsToCoreExprs args)
1476 || rhs `cheapEqExpr` Var case_bndr
1477 check_eq _ _ _ = False
1479 arg_tys = map Type (tyConAppArgs (idType case_bndr))
1482 -- case e of x { _ -> x `cast` c }
1483 -- And we definitely want to eliminate this case, to give
1485 -- So we throw away the cast from the RHS, and reconstruct
1486 -- it at the other end. All the RHS casts must be the same
1487 -- if (all identity_alt alts) holds.
1489 -- Don't worry about nested casts, because the simplifier combines them
1490 de_cast (Cast e _) = e
1493 re_cast scrut = case head alts of
1494 (_,_,Cast _ co) -> Cast scrut co
1499 --------------------------------------------------
1501 --------------------------------------------------
1502 mkCase scrut bndr alts = return (Case scrut bndr (coreAltsType alts) alts)
1506 When adding auxiliary bindings for the case binder, it's worth checking if
1507 its dead, because it often is, and occasionally these mkCase transformations
1508 cascade rather nicely.
1511 bindCaseBndr :: Id -> CoreExpr -> CoreExpr -> CoreExpr
1512 bindCaseBndr bndr rhs body
1513 | isDeadBinder bndr = body
1514 | otherwise = bindNonRec bndr rhs body