2 % (c) The AQUA Project, Glasgow University, 1993-1998
4 \section[SimplUtils]{The simplifier utilities}
9 mkLam, mkCase, prepareAlts,
12 preInlineUnconditionally, postInlineUnconditionally,
13 activeUnfolding, activeUnfInRule, activeRule,
14 simplEnvForGHCi, simplEnvForRules, updModeForInlineRules,
16 -- The continuation type
17 SimplCont(..), DupFlag(..), ArgInfo(..),
18 contIsDupable, contResultType, contIsTrivial, contArgs, dropArgs,
19 pushArgs, countValArgs, countArgs, addArgTo,
20 mkBoringStop, mkRhsStop, mkLazyArgStop, contIsRhsOrArg,
21 interestingCallContext,
23 interestingArg, mkArgInfo,
28 #include "HsVersions.h"
31 import CoreMonad ( SimplifierMode(..), Tick(..) )
35 import qualified CoreSubst
39 import CoreArity ( etaExpand, exprEtaExpandArity )
43 import Var ( isCoVar )
46 import Type hiding( substTy )
47 import Coercion ( coercionKind )
49 import Unify ( dataConCannotMatch )
61 %************************************************************************
65 %************************************************************************
67 A SimplCont allows the simplifier to traverse the expression in a
68 zipper-like fashion. The SimplCont represents the rest of the expression,
69 "above" the point of interest.
71 You can also think of a SimplCont as an "evaluation context", using
72 that term in the way it is used for operational semantics. This is the
73 way I usually think of it, For example you'll often see a syntax for
74 evaluation context looking like
75 C ::= [] | C e | case C of alts | C `cast` co
76 That's the kind of thing we are doing here, and I use that syntax in
81 * A SimplCont describes a *strict* context (just like
82 evaluation contexts do). E.g. Just [] is not a SimplCont
84 * A SimplCont describes a context that *does not* bind
85 any variables. E.g. \x. [] is not a SimplCont
89 = Stop -- An empty context, or hole, []
90 CallCtxt -- True <=> There is something interesting about
91 -- the context, and hence the inliner
92 -- should be a bit keener (see interestingCallContext)
94 -- This is an argument of a function that has RULES
95 -- Inlining the call might allow the rule to fire
97 | CoerceIt -- C `cast` co
98 OutCoercion -- The coercion simplified
103 InExpr StaticEnv -- The argument and its static env
106 | Select -- case C of alts
108 InId [InAlt] StaticEnv -- The case binder, alts, and subst-env
111 -- The two strict forms have no DupFlag, because we never duplicate them
112 | StrictBind -- (\x* \xs. e) C
113 InId [InBndr] -- let x* = [] in e
114 InExpr StaticEnv -- is a special case
117 | StrictArg -- f e1 ..en C
118 ArgInfo -- Specifies f, e1..en, Whether f has rules, etc
119 -- plus strictness flags for *further* args
120 CallCtxt -- Whether *this* argument position is interesting
125 ai_fun :: Id, -- The function
126 ai_args :: [OutExpr], -- ...applied to these args (which are in *reverse* order)
127 ai_rules :: [CoreRule], -- Rules for this function
129 ai_encl :: Bool, -- Flag saying whether this function
130 -- or an enclosing one has rules (recursively)
131 -- True => be keener to inline in all args
133 ai_strs :: [Bool], -- Strictness of remaining arguments
134 -- Usually infinite, but if it is finite it guarantees
135 -- that the function diverges after being given
136 -- that number of args
137 ai_discs :: [Int] -- Discounts for remaining arguments; non-zero => be keener to inline
141 addArgTo :: ArgInfo -> OutExpr -> ArgInfo
142 addArgTo ai arg = ai { ai_args = arg : ai_args ai }
144 instance Outputable SimplCont where
145 ppr (Stop interesting) = ptext (sLit "Stop") <> brackets (ppr interesting)
146 ppr (ApplyTo dup arg _ cont) = ((ptext (sLit "ApplyTo") <+> ppr dup <+> pprParendExpr arg)
147 {- $$ nest 2 (pprSimplEnv se) -}) $$ ppr cont
148 ppr (StrictBind b _ _ _ cont) = (ptext (sLit "StrictBind") <+> ppr b) $$ ppr cont
149 ppr (StrictArg ai _ cont) = (ptext (sLit "StrictArg") <+> ppr (ai_fun ai)) $$ ppr cont
150 ppr (Select dup bndr alts _ cont) = (ptext (sLit "Select") <+> ppr dup <+> ppr bndr) $$
151 (nest 4 (ppr alts)) $$ ppr cont
152 ppr (CoerceIt co cont) = (ptext (sLit "CoerceIt") <+> ppr co) $$ ppr cont
154 data DupFlag = OkToDup | NoDup
156 instance Outputable DupFlag where
157 ppr OkToDup = ptext (sLit "ok")
158 ppr NoDup = ptext (sLit "nodup")
163 mkBoringStop :: SimplCont
164 mkBoringStop = Stop BoringCtxt
166 mkRhsStop :: SimplCont -- See Note [RHS of lets] in CoreUnfold
167 mkRhsStop = Stop (ArgCtxt False)
169 mkLazyArgStop :: CallCtxt -> SimplCont
170 mkLazyArgStop cci = Stop cci
173 contIsRhsOrArg :: SimplCont -> Bool
174 contIsRhsOrArg (Stop {}) = True
175 contIsRhsOrArg (StrictBind {}) = True
176 contIsRhsOrArg (StrictArg {}) = True
177 contIsRhsOrArg _ = False
180 contIsDupable :: SimplCont -> Bool
181 contIsDupable (Stop {}) = True
182 contIsDupable (ApplyTo OkToDup _ _ _) = True
183 contIsDupable (Select OkToDup _ _ _ _) = True
184 contIsDupable (CoerceIt _ cont) = contIsDupable cont
185 contIsDupable _ = False
188 contIsTrivial :: SimplCont -> Bool
189 contIsTrivial (Stop {}) = True
190 contIsTrivial (ApplyTo _ (Type _) _ cont) = contIsTrivial cont
191 contIsTrivial (CoerceIt _ cont) = contIsTrivial cont
192 contIsTrivial _ = False
195 contResultType :: SimplEnv -> OutType -> SimplCont -> OutType
196 contResultType env ty cont
199 subst_ty se ty = substTy (se `setInScope` env) ty
202 go (CoerceIt co cont) _ = go cont (snd (coercionKind co))
203 go (StrictBind _ bs body se cont) _ = go cont (subst_ty se (exprType (mkLams bs body)))
204 go (StrictArg ai _ cont) _ = go cont (funResultTy (argInfoResultTy ai))
205 go (Select _ _ alts se cont) _ = go cont (subst_ty se (coreAltsType alts))
206 go (ApplyTo _ arg se cont) ty = go cont (apply_to_arg ty arg se)
208 apply_to_arg ty (Type ty_arg) se = applyTy ty (subst_ty se ty_arg)
209 apply_to_arg ty _ _ = funResultTy ty
211 argInfoResultTy :: ArgInfo -> OutType
212 argInfoResultTy (ArgInfo { ai_fun = fun, ai_args = args })
213 = foldr (\arg fn_ty -> applyTypeToArg fn_ty arg) (idType fun) args
216 countValArgs :: SimplCont -> Int
217 countValArgs (ApplyTo _ (Type _) _ cont) = countValArgs cont
218 countValArgs (ApplyTo _ _ _ cont) = 1 + countValArgs cont
221 countArgs :: SimplCont -> Int
222 countArgs (ApplyTo _ _ _ cont) = 1 + countArgs cont
225 contArgs :: SimplCont -> ([OutExpr], SimplCont)
226 -- Uses substitution to turn each arg into an OutExpr
227 contArgs cont = go [] cont
229 go args (ApplyTo _ arg se cont) = go (substExpr se arg : args) cont
230 go args cont = (reverse args, cont)
232 pushArgs :: SimplEnv -> [CoreExpr] -> SimplCont -> SimplCont
233 pushArgs _env [] cont = cont
234 pushArgs env (arg:args) cont = ApplyTo NoDup arg env (pushArgs env args cont)
236 dropArgs :: Int -> SimplCont -> SimplCont
237 dropArgs 0 cont = cont
238 dropArgs n (ApplyTo _ _ _ cont) = dropArgs (n-1) cont
239 dropArgs n other = pprPanic "dropArgs" (ppr n <+> ppr other)
243 Note [Interesting call context]
244 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
245 We want to avoid inlining an expression where there can't possibly be
246 any gain, such as in an argument position. Hence, if the continuation
247 is interesting (eg. a case scrutinee, application etc.) then we
248 inline, otherwise we don't.
250 Previously some_benefit used to return True only if the variable was
251 applied to some value arguments. This didn't work:
253 let x = _coerce_ (T Int) Int (I# 3) in
254 case _coerce_ Int (T Int) x of
257 we want to inline x, but can't see that it's a constructor in a case
258 scrutinee position, and some_benefit is False.
262 dMonadST = _/\_ t -> :Monad (g1 _@_ t, g2 _@_ t, g3 _@_ t)
264 .... case dMonadST _@_ x0 of (a,b,c) -> ....
266 we'd really like to inline dMonadST here, but we *don't* want to
267 inline if the case expression is just
269 case x of y { DEFAULT -> ... }
271 since we can just eliminate this case instead (x is in WHNF). Similar
272 applies when x is bound to a lambda expression. Hence
273 contIsInteresting looks for case expressions with just a single
278 interestingCallContext :: SimplCont -> CallCtxt
279 -- See Note [Interesting call context]
280 interestingCallContext cont
283 interesting (Select _ bndr _ _ _)
284 | isDeadBinder bndr = CaseCtxt
285 | otherwise = ArgCtxt False -- If the binder is used, this
286 -- is like a strict let
287 -- See Note [RHS of lets] in CoreUnfold
289 interesting (ApplyTo _ arg _ cont)
290 | isTypeArg arg = interesting cont
291 | otherwise = ValAppCtxt -- Can happen if we have (f Int |> co) y
292 -- If f has an INLINE prag we need to give it some
293 -- motivation to inline. See Note [Cast then apply]
296 interesting (StrictArg _ cci _) = cci
297 interesting (StrictBind {}) = BoringCtxt
298 interesting (Stop cci) = cci
299 interesting (CoerceIt _ cont) = interesting cont
300 -- If this call is the arg of a strict function, the context
301 -- is a bit interesting. If we inline here, we may get useful
302 -- evaluation information to avoid repeated evals: e.g.
304 -- Here the contIsInteresting makes the '*' keener to inline,
305 -- which in turn exposes a constructor which makes the '+' inline.
306 -- Assuming that +,* aren't small enough to inline regardless.
308 -- It's also very important to inline in a strict context for things
311 -- Here, the context of (f x) is strict, and if f's unfolding is
312 -- a build it's *great* to inline it here. So we must ensure that
313 -- the context for (f x) is not totally uninteresting.
318 -> [CoreRule] -- Rules for function
319 -> Int -- Number of value args
320 -> SimplCont -- Context of the call
323 mkArgInfo fun rules n_val_args call_cont
324 | n_val_args < idArity fun -- Note [Unsaturated functions]
325 = ArgInfo { ai_fun = fun, ai_args = [], ai_rules = rules
327 , ai_strs = vanilla_stricts
328 , ai_discs = vanilla_discounts }
330 = ArgInfo { ai_fun = fun, ai_args = [], ai_rules = rules
331 , ai_encl = interestingArgContext rules call_cont
332 , ai_strs = add_type_str (idType fun) arg_stricts
333 , ai_discs = arg_discounts }
335 vanilla_discounts, arg_discounts :: [Int]
336 vanilla_discounts = repeat 0
337 arg_discounts = case idUnfolding fun of
338 CoreUnfolding {uf_guidance = UnfIfGoodArgs {ug_args = discounts}}
339 -> discounts ++ vanilla_discounts
340 _ -> vanilla_discounts
342 vanilla_stricts, arg_stricts :: [Bool]
343 vanilla_stricts = repeat False
346 = case splitStrictSig (idStrictness fun) of
347 (demands, result_info)
348 | not (demands `lengthExceeds` n_val_args)
349 -> -- Enough args, use the strictness given.
350 -- For bottoming functions we used to pretend that the arg
351 -- is lazy, so that we don't treat the arg as an
352 -- interesting context. This avoids substituting
353 -- top-level bindings for (say) strings into
354 -- calls to error. But now we are more careful about
355 -- inlining lone variables, so its ok (see SimplUtils.analyseCont)
356 if isBotRes result_info then
357 map isStrictDmd demands -- Finite => result is bottom
359 map isStrictDmd demands ++ vanilla_stricts
361 -> WARN( True, text "More demands than arity" <+> ppr fun <+> ppr (idArity fun)
362 <+> ppr n_val_args <+> ppr demands )
363 vanilla_stricts -- Not enough args, or no strictness
365 add_type_str :: Type -> [Bool] -> [Bool]
366 -- If the function arg types are strict, record that in the 'strictness bits'
367 -- No need to instantiate because unboxed types (which dominate the strict
368 -- types) can't instantiate type variables.
369 -- add_type_str is done repeatedly (for each call); might be better
370 -- once-for-all in the function
371 -- But beware primops/datacons with no strictness
372 add_type_str _ [] = []
373 add_type_str fun_ty strs -- Look through foralls
374 | Just (_, fun_ty') <- splitForAllTy_maybe fun_ty -- Includes coercions
375 = add_type_str fun_ty' strs
376 add_type_str fun_ty (str:strs) -- Add strict-type info
377 | Just (arg_ty, fun_ty') <- splitFunTy_maybe fun_ty
378 = (str || isStrictType arg_ty) : add_type_str fun_ty' strs
382 {- Note [Unsaturated functions]
383 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
384 Consider (test eyeball/inline4)
387 where f has arity 2. Then we do not want to inline 'x', because
388 it'll just be floated out again. Even if f has lots of discounts
389 on its first argument -- it must be saturated for these to kick in
392 interestingArgContext :: [CoreRule] -> SimplCont -> Bool
393 -- If the argument has form (f x y), where x,y are boring,
394 -- and f is marked INLINE, then we don't want to inline f.
395 -- But if the context of the argument is
397 -- where g has rules, then we *do* want to inline f, in case it
398 -- exposes a rule that might fire. Similarly, if the context is
400 -- where h has rules, then we do want to inline f; hence the
401 -- call_cont argument to interestingArgContext
403 -- The ai-rules flag makes this happen; if it's
404 -- set, the inliner gets just enough keener to inline f
405 -- regardless of how boring f's arguments are, if it's marked INLINE
407 -- The alternative would be to *always* inline an INLINE function,
408 -- regardless of how boring its context is; but that seems overkill
409 -- For example, it'd mean that wrapper functions were always inlined
410 interestingArgContext rules call_cont
411 = notNull rules || enclosing_fn_has_rules
413 enclosing_fn_has_rules = go call_cont
415 go (Select {}) = False
416 go (ApplyTo {}) = False
417 go (StrictArg _ cci _) = interesting cci
418 go (StrictBind {}) = False -- ??
419 go (CoerceIt _ c) = go c
420 go (Stop cci) = interesting cci
422 interesting (ArgCtxt rules) = rules
423 interesting _ = False
428 %************************************************************************
430 \subsection{Decisions about inlining}
432 %************************************************************************
434 Inlining is controlled partly by the SimplifierMode switch. This has two
437 SimplGently (a) Simplifying before specialiser/full laziness
438 (b) Simplifiying inside InlineRules
439 (c) Simplifying the LHS of a rule
440 (d) Simplifying a GHCi expression or Template
443 SimplPhase n _ Used at all other times
447 Gentle mode has a separate boolean flag to control
448 a) inlining (sm_inline flag)
449 b) rules (sm_rules flag)
450 A key invariant about Gentle mode is that it is treated as the EARLIEST
451 phase. Something is inlined if the sm_inline flag is on AND the thing
452 is inlinable in the earliest phase. This is important. Example
454 {-# INLINE [~1] g #-}
460 If we were to inline g into f's inlining, then an importing module would
462 f e --> g (g e) ---> RULE fires
463 because the InlineRule for f has had g inlined into it.
465 On the other hand, it is bad not to do ANY inlining into an
466 InlineRule, because then recursive knots in instance declarations
467 don't get unravelled.
469 However, *sometimes* SimplGently must do no call-site inlining at all.
470 Before full laziness we must be careful not to inline wrappers,
471 because doing so inhibits floating
472 e.g. ...(case f x of ...)...
473 ==> ...(case (case x of I# x# -> fw x#) of ...)...
474 ==> ...(case x of I# x# -> case fw x# of ...)...
475 and now the redex (f x) isn't floatable any more.
477 The no-inlining thing is also important for Template Haskell. You might be
478 compiling in one-shot mode with -O2; but when TH compiles a splice before
479 running it, we don't want to use -O2. Indeed, we don't want to inline
480 anything, because the byte-code interpreter might get confused about
481 unboxed tuples and suchlike.
483 Note [RULEs enabled in SimplGently]
484 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
485 RULES are enabled when doing "gentle" simplification. Two reasons:
487 * We really want the class-op cancellation to happen:
488 op (df d1 d2) --> $cop3 d1 d2
489 because this breaks the mutual recursion between 'op' and 'df'
493 to work in Template Haskell when simplifying
494 splices, so we get simpler code for literal strings
496 Note [Simplifying inside InlineRules]
497 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
498 We must take care with simplification inside InlineRules (which come from
501 First, consider the following example
506 in ...g...g...g...g...g...
507 Now, if that's the ONLY occurrence of f, it might be inlined inside g,
508 and thence copied multiple times when g is inlined. HENCE we treat
509 any occurrence in an InlineRule as a multiple occurrence, not a single
510 one; see OccurAnal.addRuleUsage.
512 Second, we do want *do* to some modest rules/inlining stuff in InlineRules,
513 partly to eliminate senseless crap, and partly to break the recursive knots
514 generated by instance declarations. To keep things simple, we always set
515 the phase to 'gentle' when processing InlineRules. OK, so suppose we have
516 {-# INLINE <act> f #-}
518 meaning "inline f in phases p where activation <act>(p) holds".
519 Then what inlinings/rules can we apply to the copy of <rhs> captured in
520 f's InlineRule? Our model is that literally <rhs> is substituted for
521 f when it is inlined. So our conservative plan (implemented by
522 updModeForInlineRules) is this:
524 -------------------------------------------------------------
525 When simplifying the RHS of an InlineRule,
526 If the InlineRule becomes active in phase p, then
527 if the current phase is *earlier than* p,
528 make no inlinings or rules active when simplifying the RHS
530 set the phase to p when simplifying the RHS
531 -------------------------------------------------------------
535 a) Rules/inlinings that *cease* being active before p will
536 not apply to the InlineRule rhs, consistent with it being
537 inlined in its *original* form in phase p.
539 b) Rules/inlinings that only become active *after* p will
540 not apply to the InlineRule rhs, again to be consistent with
541 inlining the *original* rhs in phase p.
547 {-# NOINLINE [1] g #-}
550 {-# RULE h g = ... #-}
551 Here we must not inline g into f's RHS, even when we get to phase 0,
552 because when f is later inlined into some other module we want the
560 and suppose that there are auto-generated specialisations and a strictness
561 wrapper for g. The specialisations get activation AlwaysActive, and the
562 strictness wrapper get activation (ActiveAfter 0). So the strictness
563 wrepper fails the test and won't be inlined into f's InlineRule. That
564 means f can inline, expose the specialised call to g, so the specialisation
567 A note about wrappers
568 ~~~~~~~~~~~~~~~~~~~~~
569 It's also important not to inline a worker back into a wrapper.
571 wraper = inline_me (\x -> ...worker... )
572 Normally, the inline_me prevents the worker getting inlined into
573 the wrapper (initially, the worker's only call site!). But,
574 if the wrapper is sure to be called, the strictness analyser will
575 mark it 'demanded', so when the RHS is simplified, it'll get an ArgOf
579 simplEnvForGHCi :: SimplEnv
580 simplEnvForGHCi = mkSimplEnv allOffSwitchChecker $
581 SimplGently { sm_rules = False, sm_inline = False }
582 -- Do not do any inlining, in case we expose some unboxed
583 -- tuple stuff that confuses the bytecode interpreter
585 simplEnvForRules :: SimplEnv
586 simplEnvForRules = mkSimplEnv allOffSwitchChecker $
587 SimplGently { sm_rules = True, sm_inline = False }
589 updModeForInlineRules :: Activation -> SimplifierMode -> SimplifierMode
590 -- See Note [Simplifying inside InlineRules]
591 -- Treat Gentle as phase "infinity"
592 -- If current_phase `earlier than` inline_rule_start_phase
595 -- if current_phase `same phase` inline_rule_start_phase
596 -- then current_phase (keep gentle flags)
597 -- else inline_rule_start_phase
598 updModeForInlineRules inline_rule_act current_mode
599 = case inline_rule_act of
601 AlwaysActive -> mk_gentle current_mode
602 ActiveBefore {} -> mk_gentle current_mode
603 ActiveAfter n -> mk_phase n current_mode
605 no_op = SimplGently { sm_rules = False, sm_inline = False }
607 mk_gentle (SimplGently {}) = current_mode
608 mk_gentle _ = SimplGently { sm_rules = True, sm_inline = True }
610 mk_phase n (SimplPhase _ ss) = SimplPhase n ss
611 mk_phase n (SimplGently {}) = SimplPhase n ["gentle-rules"]
615 preInlineUnconditionally
616 ~~~~~~~~~~~~~~~~~~~~~~~~
617 @preInlineUnconditionally@ examines a bndr to see if it is used just
618 once in a completely safe way, so that it is safe to discard the
619 binding inline its RHS at the (unique) usage site, REGARDLESS of how
620 big the RHS might be. If this is the case we don't simplify the RHS
621 first, but just inline it un-simplified.
623 This is much better than first simplifying a perhaps-huge RHS and then
624 inlining and re-simplifying it. Indeed, it can be at least quadratically
633 We may end up simplifying e1 N times, e2 N-1 times, e3 N-3 times etc.
634 This can happen with cascades of functions too:
641 THE MAIN INVARIANT is this:
643 ---- preInlineUnconditionally invariant -----
644 IF preInlineUnconditionally chooses to inline x = <rhs>
645 THEN doing the inlining should not change the occurrence
646 info for the free vars of <rhs>
647 ----------------------------------------------
649 For example, it's tempting to look at trivial binding like
651 and inline it unconditionally. But suppose x is used many times,
652 but this is the unique occurrence of y. Then inlining x would change
653 y's occurrence info, which breaks the invariant. It matters: y
654 might have a BIG rhs, which will now be dup'd at every occurrenc of x.
657 Even RHSs labelled InlineMe aren't caught here, because there might be
658 no benefit from inlining at the call site.
660 [Sept 01] Don't unconditionally inline a top-level thing, because that
661 can simply make a static thing into something built dynamically. E.g.
665 [Remember that we treat \s as a one-shot lambda.] No point in
666 inlining x unless there is something interesting about the call site.
668 But watch out: if you aren't careful, some useful foldr/build fusion
669 can be lost (most notably in spectral/hartel/parstof) because the
670 foldr didn't see the build. Doing the dynamic allocation isn't a big
671 deal, in fact, but losing the fusion can be. But the right thing here
672 seems to be to do a callSiteInline based on the fact that there is
673 something interesting about the call site (it's strict). Hmm. That
676 Conclusion: inline top level things gaily until Phase 0 (the last
677 phase), at which point don't.
679 Note [pre/postInlineUnconditionally in gentle mode]
680 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
681 Even in gentle mode we want to do preInlineUnconditionally. The
682 reason is that too little clean-up happens if you don't inline
683 use-once things. Also a bit of inlining is *good* for full laziness;
684 it can expose constant sub-expressions. Example in
685 spectral/mandel/Mandel.hs, where the mandelset function gets a useful
686 let-float if you inline windowToViewport
688 However, as usual for Gentle mode, do not inline things that are
689 inactive in the intial stages. See Note [Gentle mode].
691 Note [Top-level botomming Ids]
692 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
693 Don't inline top-level Ids that are bottoming, even if they are used just
694 once, because FloatOut has gone to some trouble to extract them out.
695 Inlining them won't make the program run faster!
698 preInlineUnconditionally :: SimplEnv -> TopLevelFlag -> InId -> InExpr -> Bool
699 preInlineUnconditionally env top_lvl bndr rhs
701 | isTopLevel top_lvl && isBottomingId bndr = False -- Note [Top-level bottoming Ids]
702 | opt_SimplNoPreInlining = False
703 | otherwise = case idOccInfo bndr of
704 IAmDead -> True -- Happens in ((\x.1) v)
705 OneOcc in_lam True int_cxt -> try_once in_lam int_cxt
709 active = case phase of
710 SimplGently {} -> isEarlyActive act
711 -- See Note [pre/postInlineUnconditionally in gentle mode]
712 SimplPhase n _ -> isActive n act
713 act = idInlineActivation bndr
714 try_once in_lam int_cxt -- There's one textual occurrence
715 | not in_lam = isNotTopLevel top_lvl || early_phase
716 | otherwise = int_cxt && canInlineInLam rhs
718 -- Be very careful before inlining inside a lambda, because (a) we must not
719 -- invalidate occurrence information, and (b) we want to avoid pushing a
720 -- single allocation (here) into multiple allocations (inside lambda).
721 -- Inlining a *function* with a single *saturated* call would be ok, mind you.
722 -- || (if is_cheap && not (canInlineInLam rhs) then pprTrace "preinline" (ppr bndr <+> ppr rhs) ok else ok)
724 -- is_cheap = exprIsCheap rhs
725 -- ok = is_cheap && int_cxt
727 -- int_cxt The context isn't totally boring
728 -- E.g. let f = \ab.BIG in \y. map f xs
729 -- Don't want to substitute for f, because then we allocate
730 -- its closure every time the \y is called
731 -- But: let f = \ab.BIG in \y. map (f y) xs
732 -- Now we do want to substitute for f, even though it's not
733 -- saturated, because we're going to allocate a closure for
734 -- (f y) every time round the loop anyhow.
736 -- canInlineInLam => free vars of rhs are (Once in_lam) or Many,
737 -- so substituting rhs inside a lambda doesn't change the occ info.
738 -- Sadly, not quite the same as exprIsHNF.
739 canInlineInLam (Lit _) = True
740 canInlineInLam (Lam b e) = isRuntimeVar b || canInlineInLam e
741 canInlineInLam (Note _ e) = canInlineInLam e
742 canInlineInLam _ = False
744 early_phase = case phase of
745 SimplPhase 0 _ -> False
747 -- If we don't have this early_phase test, consider
748 -- x = length [1,2,3]
749 -- The full laziness pass carefully floats all the cons cells to
750 -- top level, and preInlineUnconditionally floats them all back in.
751 -- Result is (a) static allocation replaced by dynamic allocation
752 -- (b) many simplifier iterations because this tickles
753 -- a related problem; only one inlining per pass
755 -- On the other hand, I have seen cases where top-level fusion is
756 -- lost if we don't inline top level thing (e.g. string constants)
757 -- Hence the test for phase zero (which is the phase for all the final
758 -- simplifications). Until phase zero we take no special notice of
759 -- top level things, but then we become more leery about inlining
764 postInlineUnconditionally
765 ~~~~~~~~~~~~~~~~~~~~~~~~~
766 @postInlineUnconditionally@ decides whether to unconditionally inline
767 a thing based on the form of its RHS; in particular if it has a
768 trivial RHS. If so, we can inline and discard the binding altogether.
770 NB: a loop breaker has must_keep_binding = True and non-loop-breakers
771 only have *forward* references Hence, it's safe to discard the binding
773 NOTE: This isn't our last opportunity to inline. We're at the binding
774 site right now, and we'll get another opportunity when we get to the
777 Note that we do this unconditional inlining only for trival RHSs.
778 Don't inline even WHNFs inside lambdas; doing so may simply increase
779 allocation when the function is called. This isn't the last chance; see
782 NB: Even inline pragmas (e.g. IMustBeINLINEd) are ignored here Why?
783 Because we don't even want to inline them into the RHS of constructor
784 arguments. See NOTE above
786 NB: At one time even NOINLINE was ignored here: if the rhs is trivial
787 it's best to inline it anyway. We often get a=E; b=a from desugaring,
788 with both a and b marked NOINLINE. But that seems incompatible with
789 our new view that inlining is like a RULE, so I'm sticking to the 'active'
793 postInlineUnconditionally
794 :: SimplEnv -> TopLevelFlag
795 -> OutId -- The binder (an InId would be fine too)
796 -> OccInfo -- From the InId
800 postInlineUnconditionally env top_lvl bndr occ_info rhs unfolding
802 | isLoopBreaker occ_info = False -- If it's a loop-breaker of any kind, don't inline
803 -- because it might be referred to "earlier"
804 | isExportedId bndr = False
805 | isStableUnfolding unfolding = False -- Note [InlineRule and postInlineUnconditionally]
806 | exprIsTrivial rhs = True
807 | isTopLevel top_lvl = False -- Note [Top level and postInlineUnconditionally]
810 -- The point of examining occ_info here is that for *non-values*
811 -- that occur outside a lambda, the call-site inliner won't have
812 -- a chance (becuase it doesn't know that the thing
813 -- only occurs once). The pre-inliner won't have gotten
814 -- it either, if the thing occurs in more than one branch
815 -- So the main target is things like
818 -- True -> case x of ...
819 -- False -> case x of ...
820 -- This is very important in practice; e.g. wheel-seive1 doubles
821 -- in allocation if you miss this out
822 OneOcc in_lam _one_br int_cxt -- OneOcc => no code-duplication issue
823 -> smallEnoughToInline unfolding -- Small enough to dup
824 -- ToDo: consider discount on smallEnoughToInline if int_cxt is true
826 -- NB: Do NOT inline arbitrarily big things, even if one_br is True
827 -- Reason: doing so risks exponential behaviour. We simplify a big
828 -- expression, inline it, and simplify it again. But if the
829 -- very same thing happens in the big expression, we get
831 -- PRINCIPLE: when we've already simplified an expression once,
832 -- make sure that we only inline it if it's reasonably small.
835 -- Outside a lambda, we want to be reasonably aggressive
836 -- about inlining into multiple branches of case
837 -- e.g. let x = <non-value>
838 -- in case y of { C1 -> ..x..; C2 -> ..x..; C3 -> ... }
839 -- Inlining can be a big win if C3 is the hot-spot, even if
840 -- the uses in C1, C2 are not 'interesting'
841 -- An example that gets worse if you add int_cxt here is 'clausify'
843 (isCheapUnfolding unfolding && int_cxt))
844 -- isCheap => acceptable work duplication; in_lam may be true
845 -- int_cxt to prevent us inlining inside a lambda without some
846 -- good reason. See the notes on int_cxt in preInlineUnconditionally
848 IAmDead -> True -- This happens; for example, the case_bndr during case of
849 -- known constructor: case (a,b) of x { (p,q) -> ... }
850 -- Here x isn't mentioned in the RHS, so we don't want to
851 -- create the (dead) let-binding let x = (a,b) in ...
855 -- Here's an example that we don't handle well:
856 -- let f = if b then Left (\x.BIG) else Right (\y.BIG)
857 -- in \y. ....case f of {...} ....
858 -- Here f is used just once, and duplicating the case work is fine (exprIsCheap).
860 -- - We can't preInlineUnconditionally because that woud invalidate
861 -- the occ info for b.
862 -- - We can't postInlineUnconditionally because the RHS is big, and
863 -- that risks exponential behaviour
864 -- - We can't call-site inline, because the rhs is big
868 active = case getMode env of
869 SimplGently {} -> isEarlyActive act
870 -- See Note [pre/postInlineUnconditionally in gentle mode]
871 SimplPhase n _ -> isActive n act
872 act = idInlineActivation bndr
874 activeUnfolding :: SimplEnv -> IdUnfoldingFun
876 = case getMode env of
877 SimplGently { sm_inline = False } -> active_unfolding_minimal
878 SimplGently { sm_inline = True } -> active_unfolding_gentle
879 SimplPhase n _ -> active_unfolding n
881 activeUnfInRule :: SimplEnv -> IdUnfoldingFun
882 -- When matching in RULE, we want to "look through" an unfolding
883 -- if *rules* are on, even if *inlinings* are not. A notable example
884 -- is DFuns, which really we want to match in rules like (op dfun)
887 = case getMode env of
888 SimplGently { sm_rules = False } -> active_unfolding_minimal
889 SimplGently { sm_rules = True } -> active_unfolding_gentle
890 SimplPhase n _ -> active_unfolding n
892 active_unfolding_minimal :: IdUnfoldingFun
893 -- Compuslory unfoldings only
894 -- Ignore SimplGently, because we want to inline regardless;
895 -- the Id has no top-level binding at all
897 -- NB: we used to have a second exception, for data con wrappers.
898 -- On the grounds that we use gentle mode for rule LHSs, and
899 -- they match better when data con wrappers are inlined.
900 -- But that only really applies to the trivial wrappers (like (:)),
901 -- and they are now constructed as Compulsory unfoldings (in MkId)
902 -- so they'll happen anyway.
903 active_unfolding_minimal id
904 | isCompulsoryUnfolding unf = unf
905 | otherwise = NoUnfolding
907 unf = realIdUnfolding id -- Never a loop breaker
909 active_unfolding_gentle :: IdUnfoldingFun
910 -- Anything that is early-active
911 -- See Note [Gentle mode]
912 active_unfolding_gentle id
913 | isEarlyActive (idInlineActivation id) = idUnfolding id
914 | otherwise = NoUnfolding
915 -- idUnfolding checks for loop-breakers
916 -- Things with an INLINE pragma may have
917 -- an unfolding *and* be a loop breaker
918 -- (maybe the knot is not yet untied)
920 active_unfolding :: CompilerPhase -> IdUnfoldingFun
921 active_unfolding n id
922 | isActive n (idInlineActivation id) = idUnfolding id
923 | otherwise = NoUnfolding
925 activeRule :: DynFlags -> SimplEnv -> Maybe (Activation -> Bool)
926 -- Nothing => No rules at all
927 activeRule dflags env
928 | not (dopt Opt_EnableRewriteRules dflags)
929 = Nothing -- Rewriting is off
931 = case getMode env of
932 SimplGently { sm_rules = rules_on }
933 | rules_on -> Just isEarlyActive -- Note [RULEs enabled in SimplGently]
934 | otherwise -> Nothing
935 SimplPhase n _ -> Just (isActive n)
938 Note [Top level and postInlineUnconditionally]
939 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
940 We don't do postInlineUnconditionally for top-level things (exept ones that
942 * There is no point, because the main goal is to get rid of local
943 bindings used in multiple case branches.
944 * Doing so will inline top-level error expressions that have been
945 carefully floated out by FloatOut. More generally, it might
946 replace static allocation with dynamic.
948 Note [InlineRule and postInlineUnconditionally]
949 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
950 Do not do postInlineUnconditionally if the Id has an InlineRule, otherwise
951 we lose the unfolding. Example
953 -- f has InlineRule with rhs (e |> co)
957 Then there's a danger we'll optimise to
962 and now postInlineUnconditionally, losing the InlineRule on f. Now f'
963 won't inline because 'e' is too big.
966 %************************************************************************
970 %************************************************************************
973 mkLam :: SimplEnv -> [OutBndr] -> OutExpr -> SimplM OutExpr
974 -- mkLam tries three things
975 -- a) eta reduction, if that gives a trivial expression
976 -- b) eta expansion [only if there are some value lambdas]
981 = do { dflags <- getDOptsSmpl
982 ; mkLam' dflags bndrs body }
984 mkLam' :: DynFlags -> [OutBndr] -> OutExpr -> SimplM OutExpr
985 mkLam' dflags bndrs (Cast body co)
986 | not (any bad bndrs)
987 -- Note [Casts and lambdas]
988 = do { lam <- mkLam' dflags bndrs body
989 ; return (mkCoerce (mkPiTypes bndrs co) lam) }
991 co_vars = tyVarsOfType co
992 bad bndr = isCoVar bndr && bndr `elemVarSet` co_vars
994 mkLam' dflags bndrs body
995 | dopt Opt_DoEtaReduction dflags,
996 Just etad_lam <- tryEtaReduce bndrs body
997 = do { tick (EtaReduction (head bndrs))
1000 | dopt Opt_DoLambdaEtaExpansion dflags,
1001 not (inGentleMode env), -- In gentle mode don't eta-expansion
1002 any isRuntimeVar bndrs -- because it can clutter up the code
1003 -- with casts etc that may not be removed
1004 = do { let body' = tryEtaExpansion dflags body
1005 ; return (mkLams bndrs body') }
1008 = return (mkLams bndrs body)
1011 Note [Casts and lambdas]
1012 ~~~~~~~~~~~~~~~~~~~~~~~~
1014 (\x. (\y. e) `cast` g1) `cast` g2
1015 There is a danger here that the two lambdas look separated, and the
1016 full laziness pass might float an expression to between the two.
1018 So this equation in mkLam' floats the g1 out, thus:
1019 (\x. e `cast` g1) --> (\x.e) `cast` (tx -> g1)
1022 In general, this floats casts outside lambdas, where (I hope) they
1023 might meet and cancel with some other cast:
1024 \x. e `cast` co ===> (\x. e) `cast` (tx -> co)
1025 /\a. e `cast` co ===> (/\a. e) `cast` (/\a. co)
1026 /\g. e `cast` co ===> (/\g. e) `cast` (/\g. co)
1027 (if not (g `in` co))
1029 Notice that it works regardless of 'e'. Originally it worked only
1030 if 'e' was itself a lambda, but in some cases that resulted in
1031 fruitless iteration in the simplifier. A good example was when
1032 compiling Text.ParserCombinators.ReadPrec, where we had a definition
1033 like (\x. Get `cast` g)
1034 where Get is a constructor with nonzero arity. Then mkLam eta-expanded
1035 the Get, and the next iteration eta-reduced it, and then eta-expanded
1038 Note also the side condition for the case of coercion binders.
1039 It does not make sense to transform
1040 /\g. e `cast` g ==> (/\g.e) `cast` (/\g.g)
1041 because the latter is not well-kinded.
1043 -- c) floating lets out through big lambdas
1044 -- [only if all tyvar lambdas, and only if this lambda
1045 -- is the RHS of a let]
1047 {- Sept 01: I'm experimenting with getting the
1048 full laziness pass to float out past big lambdsa
1049 | all isTyVar bndrs, -- Only for big lambdas
1050 contIsRhs cont -- Only try the rhs type-lambda floating
1051 -- if this is indeed a right-hand side; otherwise
1052 -- we end up floating the thing out, only for float-in
1053 -- to float it right back in again!
1054 = do (floats, body') <- tryRhsTyLam env bndrs body
1055 return (floats, mkLams bndrs body')
1059 %************************************************************************
1063 %************************************************************************
1065 Note [Eta reduction conditions]
1066 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1067 We try for eta reduction here, but *only* if we get all the way to an
1068 trivial expression. We don't want to remove extra lambdas unless we
1069 are going to avoid allocating this thing altogether.
1071 There are some particularly delicate points here:
1073 * Eta reduction is not valid in general:
1075 This matters, partly for old-fashioned correctness reasons but,
1076 worse, getting it wrong can yield a seg fault. Consider
1078 h y = case (case y of { True -> f `seq` True; False -> False }) of
1079 True -> ...; False -> ...
1081 If we (unsoundly) eta-reduce f to get f=f, the strictness analyser
1082 says f=bottom, and replaces the (f `seq` True) with just
1083 (f `cast` unsafe-co). BUT, as thing stand, 'f' got arity 1, and it
1084 *keeps* arity 1 (perhaps also wrongly). So CorePrep eta-expands
1085 the definition again, so that it does not termninate after all.
1086 Result: seg-fault because the boolean case actually gets a function value.
1089 So it's important to to the right thing.
1091 * Note [Arity care]: we need to be careful if we just look at f's
1092 arity. Currently (Dec07), f's arity is visible in its own RHS (see
1093 Note [Arity robustness] in SimplEnv) so we must *not* trust the
1094 arity when checking that 'f' is a value. Otherwise we will
1099 Which might change a terminiating program (think (f `seq` e)) to a
1100 non-terminating one. So we check for being a loop breaker first.
1102 However for GlobalIds we can look at the arity; and for primops we
1103 must, since they have no unfolding.
1105 * Regardless of whether 'f' is a value, we always want to
1106 reduce (/\a -> f a) to f
1107 This came up in a RULE: foldr (build (/\a -> g a))
1108 did not match foldr (build (/\b -> ...something complex...))
1109 The type checker can insert these eta-expanded versions,
1110 with both type and dictionary lambdas; hence the slightly
1113 * Never *reduce* arity. For example
1115 Then if h has arity 1 we don't want to eta-reduce because then
1116 f's arity would decrease, and that is bad
1118 These delicacies are why we don't use exprIsTrivial and exprIsHNF here.
1122 tryEtaReduce :: [OutBndr] -> OutExpr -> Maybe OutExpr
1123 tryEtaReduce bndrs body
1124 = go (reverse bndrs) body
1126 incoming_arity = count isId bndrs
1128 go (b : bs) (App fun arg) | ok_arg b arg = go bs fun -- Loop round
1129 go [] fun | ok_fun fun = Just fun -- Success!
1130 go _ _ = Nothing -- Failure!
1132 -- Note [Eta reduction conditions]
1133 ok_fun (App fun (Type ty))
1134 | not (any (`elemVarSet` tyVarsOfType ty) bndrs)
1137 = not (fun_id `elem` bndrs)
1138 && (ok_fun_id fun_id || all ok_lam bndrs)
1141 ok_fun_id fun = fun_arity fun >= incoming_arity
1143 fun_arity fun -- See Note [Arity care]
1144 | isLocalId fun && isLoopBreaker (idOccInfo fun) = 0
1145 | otherwise = idArity fun
1147 ok_lam v = isTyVar v || isDictId v
1149 ok_arg b arg = varToCoreExpr b `cheapEqExpr` arg
1153 %************************************************************************
1157 %************************************************************************
1161 f = \x1..xn -> N ==> f = \x1..xn y1..ym -> N y1..ym
1164 where (in both cases)
1166 * The xi can include type variables
1168 * The yi are all value variables
1170 * N is a NORMAL FORM (i.e. no redexes anywhere)
1171 wanting a suitable number of extra args.
1173 The biggest reason for doing this is for cases like
1179 Here we want to get the lambdas together. A good exmaple is the nofib
1180 program fibheaps, which gets 25% more allocation if you don't do this
1183 We may have to sandwich some coerces between the lambdas
1184 to make the types work. exprEtaExpandArity looks through coerces
1185 when computing arity; and etaExpand adds the coerces as necessary when
1186 actually computing the expansion.
1189 tryEtaExpansion :: DynFlags -> OutExpr -> OutExpr
1190 -- There is at least one runtime binder in the binders
1191 tryEtaExpansion dflags body
1192 = etaExpand fun_arity body
1194 fun_arity = exprEtaExpandArity dflags body
1198 %************************************************************************
1200 \subsection{Floating lets out of big lambdas}
1202 %************************************************************************
1204 Note [Floating and type abstraction]
1205 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1208 We'd like to float this to
1211 x = /\a. C (y1 a) (y2 a)
1212 for the usual reasons: we want to inline x rather vigorously.
1214 You may think that this kind of thing is rare. But in some programs it is
1215 common. For example, if you do closure conversion you might get:
1217 data a :-> b = forall e. (e -> a -> b) :$ e
1219 f_cc :: forall a. a :-> a
1220 f_cc = /\a. (\e. id a) :$ ()
1222 Now we really want to inline that f_cc thing so that the
1223 construction of the closure goes away.
1225 So I have elaborated simplLazyBind to understand right-hand sides that look
1229 and treat them specially. The real work is done in SimplUtils.abstractFloats,
1230 but there is quite a bit of plumbing in simplLazyBind as well.
1232 The same transformation is good when there are lets in the body:
1234 /\abc -> let(rec) x = e in b
1236 let(rec) x' = /\abc -> let x = x' a b c in e
1238 /\abc -> let x = x' a b c in b
1240 This is good because it can turn things like:
1242 let f = /\a -> letrec g = ... g ... in g
1244 letrec g' = /\a -> ... g' a ...
1246 let f = /\ a -> g' a
1248 which is better. In effect, it means that big lambdas don't impede
1251 This optimisation is CRUCIAL in eliminating the junk introduced by
1252 desugaring mutually recursive definitions. Don't eliminate it lightly!
1254 [May 1999] If we do this transformation *regardless* then we can
1255 end up with some pretty silly stuff. For example,
1258 st = /\ s -> let { x1=r1 ; x2=r2 } in ...
1263 st = /\s -> ...[y1 s/x1, y2 s/x2]
1266 Unless the "..." is a WHNF there is really no point in doing this.
1267 Indeed it can make things worse. Suppose x1 is used strictly,
1270 x1* = case f y of { (a,b) -> e }
1272 If we abstract this wrt the tyvar we then can't do the case inline
1273 as we would normally do.
1275 That's why the whole transformation is part of the same process that
1276 floats let-bindings and constructor arguments out of RHSs. In particular,
1277 it is guarded by the doFloatFromRhs call in simplLazyBind.
1281 abstractFloats :: [OutTyVar] -> SimplEnv -> OutExpr -> SimplM ([OutBind], OutExpr)
1282 abstractFloats main_tvs body_env body
1283 = ASSERT( notNull body_floats )
1284 do { (subst, float_binds) <- mapAccumLM abstract empty_subst body_floats
1285 ; return (float_binds, CoreSubst.substExpr subst body) }
1287 main_tv_set = mkVarSet main_tvs
1288 body_floats = getFloats body_env
1289 empty_subst = CoreSubst.mkEmptySubst (seInScope body_env)
1291 abstract :: CoreSubst.Subst -> OutBind -> SimplM (CoreSubst.Subst, OutBind)
1292 abstract subst (NonRec id rhs)
1293 = do { (poly_id, poly_app) <- mk_poly tvs_here id
1294 ; let poly_rhs = mkLams tvs_here rhs'
1295 subst' = CoreSubst.extendIdSubst subst id poly_app
1296 ; return (subst', (NonRec poly_id poly_rhs)) }
1298 rhs' = CoreSubst.substExpr subst rhs
1299 tvs_here | any isCoVar main_tvs = main_tvs -- Note [Abstract over coercions]
1301 = varSetElems (main_tv_set `intersectVarSet` exprSomeFreeVars isTyVar rhs')
1303 -- Abstract only over the type variables free in the rhs
1304 -- wrt which the new binding is abstracted. But the naive
1305 -- approach of abstract wrt the tyvars free in the Id's type
1307 -- /\ a b -> let t :: (a,b) = (e1, e2)
1310 -- Here, b isn't free in x's type, but we must nevertheless
1311 -- abstract wrt b as well, because t's type mentions b.
1312 -- Since t is floated too, we'd end up with the bogus:
1313 -- poly_t = /\ a b -> (e1, e2)
1314 -- poly_x = /\ a -> fst (poly_t a *b*)
1315 -- So for now we adopt the even more naive approach of
1316 -- abstracting wrt *all* the tyvars. We'll see if that
1317 -- gives rise to problems. SLPJ June 98
1319 abstract subst (Rec prs)
1320 = do { (poly_ids, poly_apps) <- mapAndUnzipM (mk_poly tvs_here) ids
1321 ; let subst' = CoreSubst.extendSubstList subst (ids `zip` poly_apps)
1322 poly_rhss = [mkLams tvs_here (CoreSubst.substExpr subst' rhs) | rhs <- rhss]
1323 ; return (subst', Rec (poly_ids `zip` poly_rhss)) }
1325 (ids,rhss) = unzip prs
1326 -- For a recursive group, it's a bit of a pain to work out the minimal
1327 -- set of tyvars over which to abstract:
1328 -- /\ a b c. let x = ...a... in
1329 -- letrec { p = ...x...q...
1330 -- q = .....p...b... } in
1332 -- Since 'x' is abstracted over 'a', the {p,q} group must be abstracted
1333 -- over 'a' (because x is replaced by (poly_x a)) as well as 'b'.
1334 -- Since it's a pain, we just use the whole set, which is always safe
1336 -- If you ever want to be more selective, remember this bizarre case too:
1338 -- Here, we must abstract 'x' over 'a'.
1341 mk_poly tvs_here var
1342 = do { uniq <- getUniqueM
1343 ; let poly_name = setNameUnique (idName var) uniq -- Keep same name
1344 poly_ty = mkForAllTys tvs_here (idType var) -- But new type of course
1345 poly_id = transferPolyIdInfo var tvs_here $ -- Note [transferPolyIdInfo] in Id.lhs
1346 mkLocalId poly_name poly_ty
1347 ; return (poly_id, mkTyApps (Var poly_id) (mkTyVarTys tvs_here)) }
1348 -- In the olden days, it was crucial to copy the occInfo of the original var,
1349 -- because we were looking at occurrence-analysed but as yet unsimplified code!
1350 -- In particular, we mustn't lose the loop breakers. BUT NOW we are looking
1351 -- at already simplified code, so it doesn't matter
1353 -- It's even right to retain single-occurrence or dead-var info:
1354 -- Suppose we started with /\a -> let x = E in B
1355 -- where x occurs once in B. Then we transform to:
1356 -- let x' = /\a -> E in /\a -> let x* = x' a in B
1357 -- where x* has an INLINE prag on it. Now, once x* is inlined,
1358 -- the occurrences of x' will be just the occurrences originally
1362 Note [Abstract over coercions]
1363 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1364 If a coercion variable (g :: a ~ Int) is free in the RHS, then so is the
1365 type variable a. Rather than sort this mess out, we simply bale out and abstract
1366 wrt all the type variables if any of them are coercion variables.
1369 Historical note: if you use let-bindings instead of a substitution, beware of this:
1371 -- Suppose we start with:
1373 -- x = /\ a -> let g = G in E
1375 -- Then we'll float to get
1377 -- x = let poly_g = /\ a -> G
1378 -- in /\ a -> let g = poly_g a in E
1380 -- But now the occurrence analyser will see just one occurrence
1381 -- of poly_g, not inside a lambda, so the simplifier will
1382 -- PreInlineUnconditionally poly_g back into g! Badk to square 1!
1383 -- (I used to think that the "don't inline lone occurrences" stuff
1384 -- would stop this happening, but since it's the *only* occurrence,
1385 -- PreInlineUnconditionally kicks in first!)
1387 -- Solution: put an INLINE note on g's RHS, so that poly_g seems
1388 -- to appear many times. (NB: mkInlineMe eliminates
1389 -- such notes on trivial RHSs, so do it manually.)
1391 %************************************************************************
1395 %************************************************************************
1397 prepareAlts tries these things:
1399 1. Eliminate alternatives that cannot match, including the
1400 DEFAULT alternative.
1402 2. If the DEFAULT alternative can match only one possible constructor,
1403 then make that constructor explicit.
1405 case e of x { DEFAULT -> rhs }
1407 case e of x { (a,b) -> rhs }
1408 where the type is a single constructor type. This gives better code
1409 when rhs also scrutinises x or e.
1411 3. Returns a list of the constructors that cannot holds in the
1412 DEFAULT alternative (if there is one)
1414 Here "cannot match" includes knowledge from GADTs
1416 It's a good idea do do this stuff before simplifying the alternatives, to
1417 avoid simplifying alternatives we know can't happen, and to come up with
1418 the list of constructors that are handled, to put into the IdInfo of the
1419 case binder, for use when simplifying the alternatives.
1421 Eliminating the default alternative in (1) isn't so obvious, but it can
1424 data Colour = Red | Green | Blue
1433 DEFAULT -> [ case y of ... ]
1435 If we inline h into f, the default case of the inlined h can't happen.
1436 If we don't notice this, we may end up filtering out *all* the cases
1437 of the inner case y, which give us nowhere to go!
1440 prepareAlts :: OutExpr -> OutId -> [InAlt] -> SimplM ([AltCon], [InAlt])
1441 prepareAlts scrut case_bndr' alts
1442 = do { let (alts_wo_default, maybe_deflt) = findDefault alts
1443 alt_cons = [con | (con,_,_) <- alts_wo_default]
1444 imposs_deflt_cons = nub (imposs_cons ++ alt_cons)
1445 -- "imposs_deflt_cons" are handled
1446 -- EITHER by the context,
1447 -- OR by a non-DEFAULT branch in this case expression.
1449 ; default_alts <- prepareDefault case_bndr' mb_tc_app
1450 imposs_deflt_cons maybe_deflt
1452 ; let trimmed_alts = filterOut impossible_alt alts_wo_default
1453 merged_alts = mergeAlts trimmed_alts default_alts
1454 -- We need the mergeAlts in case the new default_alt
1455 -- has turned into a constructor alternative.
1456 -- The merge keeps the inner DEFAULT at the front, if there is one
1457 -- and interleaves the alternatives in the right order
1459 ; return (imposs_deflt_cons, merged_alts) }
1461 mb_tc_app = splitTyConApp_maybe (idType case_bndr')
1462 Just (_, inst_tys) = mb_tc_app
1464 imposs_cons = case scrut of
1465 Var v -> otherCons (idUnfolding v)
1468 impossible_alt :: CoreAlt -> Bool
1469 impossible_alt (con, _, _) | con `elem` imposs_cons = True
1470 impossible_alt (DataAlt con, _, _) = dataConCannotMatch inst_tys con
1471 impossible_alt _ = False
1474 prepareDefault :: OutId -- Case binder; need just for its type. Note that as an
1475 -- OutId, it has maximum information; this is important.
1476 -- Test simpl013 is an example
1477 -> Maybe (TyCon, [Type]) -- Type of scrutinee, decomposed
1478 -> [AltCon] -- These cons can't happen when matching the default
1479 -> Maybe InExpr -- Rhs
1480 -> SimplM [InAlt] -- Still unsimplified
1481 -- We use a list because it's what mergeAlts expects,
1483 --------- Fill in known constructor -----------
1484 prepareDefault case_bndr (Just (tycon, inst_tys)) imposs_cons (Just deflt_rhs)
1485 | -- This branch handles the case where we are
1486 -- scrutinisng an algebraic data type
1487 isAlgTyCon tycon -- It's a data type, tuple, or unboxed tuples.
1488 , not (isNewTyCon tycon) -- We can have a newtype, if we are just doing an eval:
1489 -- case x of { DEFAULT -> e }
1490 -- and we don't want to fill in a default for them!
1491 , Just all_cons <- tyConDataCons_maybe tycon
1492 , not (null all_cons) -- This is a tricky corner case. If the data type has no constructors,
1493 -- which GHC allows, then the case expression will have at most a default
1494 -- alternative. We don't want to eliminate that alternative, because the
1495 -- invariant is that there's always one alternative. It's more convenient
1497 -- case x of { DEFAULT -> e }
1498 -- as it is, rather than transform it to
1499 -- error "case cant match"
1500 -- which would be quite legitmate. But it's a really obscure corner, and
1501 -- not worth wasting code on.
1502 , let imposs_data_cons = [con | DataAlt con <- imposs_cons] -- We now know it's a data type
1503 impossible con = con `elem` imposs_data_cons || dataConCannotMatch inst_tys con
1504 = case filterOut impossible all_cons of
1505 [] -> return [] -- Eliminate the default alternative
1506 -- altogether if it can't match
1508 [con] -> -- It matches exactly one constructor, so fill it in
1509 do { tick (FillInCaseDefault case_bndr)
1511 ; let (ex_tvs, co_tvs, arg_ids) =
1512 dataConRepInstPat us con inst_tys
1513 ; return [(DataAlt con, ex_tvs ++ co_tvs ++ arg_ids, deflt_rhs)] }
1515 _ -> return [(DEFAULT, [], deflt_rhs)]
1517 | debugIsOn, isAlgTyCon tycon, not (isOpenTyCon tycon), null (tyConDataCons tycon)
1518 -- Check for no data constructors
1519 -- This can legitimately happen for type families, so don't report that
1520 = pprTrace "prepareDefault" (ppr case_bndr <+> ppr tycon)
1521 $ return [(DEFAULT, [], deflt_rhs)]
1523 --------- Catch-all cases -----------
1524 prepareDefault _case_bndr _bndr_ty _imposs_cons (Just deflt_rhs)
1525 = return [(DEFAULT, [], deflt_rhs)]
1527 prepareDefault _case_bndr _bndr_ty _imposs_cons Nothing
1528 = return [] -- No default branch
1533 %************************************************************************
1537 %************************************************************************
1539 mkCase tries these things
1541 1. Merge Nested Cases
1543 case e of b { ==> case e of b {
1544 p1 -> rhs1 p1 -> rhs1
1546 pm -> rhsm pm -> rhsm
1547 _ -> case b of b' { pn -> let b'=b in rhsn
1549 ... po -> let b'=b in rhso
1550 po -> rhso _ -> let b'=b in rhsd
1554 which merges two cases in one case when -- the default alternative of
1555 the outer case scrutises the same variable as the outer case. This
1556 transformation is called Case Merging. It avoids that the same
1557 variable is scrutinised multiple times.
1559 2. Eliminate Identity Case
1565 and similar friends.
1567 3. Merge identical alternatives.
1568 If several alternatives are identical, merge them into
1569 a single DEFAULT alternative. I've occasionally seen this
1570 making a big difference:
1572 case e of =====> case e of
1573 C _ -> f x D v -> ....v....
1574 D v -> ....v.... DEFAULT -> f x
1577 The point is that we merge common RHSs, at least for the DEFAULT case.
1578 [One could do something more elaborate but I've never seen it needed.]
1579 To avoid an expensive test, we just merge branches equal to the *first*
1580 alternative; this picks up the common cases
1581 a) all branches equal
1582 b) some branches equal to the DEFAULT (which occurs first)
1584 The case where Merge Identical Alternatives transformation showed up
1585 was like this (base/Foreign/C/Err/Error.lhs):
1591 where @is@ was something like
1593 p `is` n = p /= (-1) && p == n
1595 This gave rise to a horrible sequence of cases
1602 and similarly in cascade for all the join points!
1606 mkCase, mkCase1, mkCase2
1609 -> [OutAlt] -- Alternatives in standard (increasing) order
1612 --------------------------------------------------
1613 -- 1. Merge Nested Cases
1614 --------------------------------------------------
1616 mkCase dflags scrut outer_bndr ((DEFAULT, _, deflt_rhs) : outer_alts)
1617 | dopt Opt_CaseMerge dflags
1618 , Case (Var inner_scrut_var) inner_bndr _ inner_alts <- deflt_rhs
1619 , inner_scrut_var == outer_bndr
1620 = do { tick (CaseMerge outer_bndr)
1622 ; let wrap_alt (con, args, rhs) = ASSERT( outer_bndr `notElem` args )
1623 (con, args, wrap_rhs rhs)
1624 -- Simplifier's no-shadowing invariant should ensure
1625 -- that outer_bndr is not shadowed by the inner patterns
1626 wrap_rhs rhs = Let (NonRec inner_bndr (Var outer_bndr)) rhs
1627 -- The let is OK even for unboxed binders,
1629 wrapped_alts | isDeadBinder inner_bndr = inner_alts
1630 | otherwise = map wrap_alt inner_alts
1632 merged_alts = mergeAlts outer_alts wrapped_alts
1633 -- NB: mergeAlts gives priority to the left
1636 -- DEFAULT -> case x of
1639 -- When we merge, we must ensure that e1 takes
1640 -- precedence over e2 as the value for A!
1642 ; mkCase1 dflags scrut outer_bndr merged_alts
1644 -- Warning: don't call mkCase recursively!
1645 -- Firstly, there's no point, because inner alts have already had
1646 -- mkCase applied to them, so they won't have a case in their default
1647 -- Secondly, if you do, you get an infinite loop, because the bindCaseBndr
1648 -- in munge_rhs may put a case into the DEFAULT branch!
1650 mkCase dflags scrut bndr alts = mkCase1 dflags scrut bndr alts
1652 --------------------------------------------------
1653 -- 2. Eliminate Identity Case
1654 --------------------------------------------------
1656 mkCase1 _dflags scrut case_bndr alts -- Identity case
1657 | all identity_alt alts
1658 = do { tick (CaseIdentity case_bndr)
1659 ; return (re_cast scrut) }
1661 identity_alt (con, args, rhs) = check_eq con args (de_cast rhs)
1663 check_eq DEFAULT _ (Var v) = v == case_bndr
1664 check_eq (LitAlt lit') _ (Lit lit) = lit == lit'
1665 check_eq (DataAlt con) args rhs = rhs `cheapEqExpr` mkConApp con (arg_tys ++ varsToCoreExprs args)
1666 || rhs `cheapEqExpr` Var case_bndr
1667 check_eq _ _ _ = False
1669 arg_tys = map Type (tyConAppArgs (idType case_bndr))
1672 -- case e of x { _ -> x `cast` c }
1673 -- And we definitely want to eliminate this case, to give
1675 -- So we throw away the cast from the RHS, and reconstruct
1676 -- it at the other end. All the RHS casts must be the same
1677 -- if (all identity_alt alts) holds.
1679 -- Don't worry about nested casts, because the simplifier combines them
1680 de_cast (Cast e _) = e
1683 re_cast scrut = case head alts of
1684 (_,_,Cast _ co) -> Cast scrut co
1687 --------------------------------------------------
1688 -- 3. Merge Identical Alternatives
1689 --------------------------------------------------
1690 mkCase1 dflags scrut case_bndr ((_con1,bndrs1,rhs1) : con_alts)
1691 | all isDeadBinder bndrs1 -- Remember the default
1692 , length filtered_alts < length con_alts -- alternative comes first
1693 -- Also Note [Dead binders]
1694 = do { tick (AltMerge case_bndr)
1695 ; mkCase2 dflags scrut case_bndr alts' }
1697 alts' = (DEFAULT, [], rhs1) : filtered_alts
1698 filtered_alts = filter keep con_alts
1699 keep (_con,bndrs,rhs) = not (all isDeadBinder bndrs && rhs `cheapEqExpr` rhs1)
1701 mkCase1 dflags scrut bndr alts = mkCase2 dflags scrut bndr alts
1703 --------------------------------------------------
1705 --------------------------------------------------
1706 mkCase2 _dflags scrut bndr alts
1707 = return (Case scrut bndr (coreAltsType alts) alts)
1711 ~~~~~~~~~~~~~~~~~~~~
1712 Note that dead-ness is maintained by the simplifier, so that it is
1713 accurate after simplification as well as before.
1716 Note [Cascading case merge]
1717 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1718 Case merging should cascade in one sweep, because it
1722 DEFAULT -> case a of b
1723 DEFAULT -> case b of c {
1730 DEFAULT -> case a of b
1731 DEFAULT -> let c = b in e
1732 A -> let c = b in ea
1737 DEFAULT -> let b = a in let c = b in e
1738 A -> let b = a in let c = b in ea
1739 B -> let b = a in eb
1743 However here's a tricky case that we still don't catch, and I don't
1744 see how to catch it in one pass:
1746 case x of c1 { I# a1 ->
1749 DEFAULT -> case x of c3 { I# a2 ->
1752 After occurrence analysis (and its binder-swap) we get this
1754 case x of c1 { I# a1 ->
1755 let x = c1 in -- Binder-swap addition
1758 DEFAULT -> case x of c3 { I# a2 ->
1761 When we simplify the inner case x, we'll see that
1762 x=c1=I# a1. So we'll bind a2 to a1, and get
1764 case x of c1 { I# a1 ->
1767 DEFAULT -> case a1 of ...
1769 This is corect, but we can't do a case merge in this sweep
1770 because c2 /= a1. Reason: the binding c1=I# a1 went inwards
1771 without getting changed to c1=I# c2.
1773 I don't think this is worth fixing, even if I knew how. It'll
1774 all come out in the next pass anyway.