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 se cont) = (ptext (sLit "Select") <+> ppr dup <+> ppr bndr) $$
151 (nest 2 $ vcat [ppr (seTvSubst se), 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 -> (Bool, [ArgSummary], SimplCont)
226 -- Uses substitution to turn each arg into an OutExpr
227 contArgs cont@(ApplyTo {})
228 = case go [] cont of { (args, cont') -> (False, args, cont') }
230 go args (ApplyTo _ arg se cont)
231 | isTypeArg arg = go args cont
232 | otherwise = go (is_interesting arg se : args) cont
233 go args cont = (reverse args, cont)
235 is_interesting arg se = interestingArg (substExpr (text "contArgs") se arg)
236 -- Do *not* use short-cutting substitution here
237 -- because we want to get as much IdInfo as possible
239 contArgs cont = (True, [], cont)
241 pushArgs :: SimplEnv -> [CoreExpr] -> SimplCont -> SimplCont
242 pushArgs _env [] cont = cont
243 pushArgs env (arg:args) cont = ApplyTo NoDup arg env (pushArgs env args cont)
245 dropArgs :: Int -> SimplCont -> SimplCont
246 dropArgs 0 cont = cont
247 dropArgs n (ApplyTo _ _ _ cont) = dropArgs (n-1) cont
248 dropArgs n other = pprPanic "dropArgs" (ppr n <+> ppr other)
252 Note [Interesting call context]
253 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
254 We want to avoid inlining an expression where there can't possibly be
255 any gain, such as in an argument position. Hence, if the continuation
256 is interesting (eg. a case scrutinee, application etc.) then we
257 inline, otherwise we don't.
259 Previously some_benefit used to return True only if the variable was
260 applied to some value arguments. This didn't work:
262 let x = _coerce_ (T Int) Int (I# 3) in
263 case _coerce_ Int (T Int) x of
266 we want to inline x, but can't see that it's a constructor in a case
267 scrutinee position, and some_benefit is False.
271 dMonadST = _/\_ t -> :Monad (g1 _@_ t, g2 _@_ t, g3 _@_ t)
273 .... case dMonadST _@_ x0 of (a,b,c) -> ....
275 we'd really like to inline dMonadST here, but we *don't* want to
276 inline if the case expression is just
278 case x of y { DEFAULT -> ... }
280 since we can just eliminate this case instead (x is in WHNF). Similar
281 applies when x is bound to a lambda expression. Hence
282 contIsInteresting looks for case expressions with just a single
287 interestingCallContext :: SimplCont -> CallCtxt
288 -- See Note [Interesting call context]
289 interestingCallContext cont
292 interesting (Select _ bndr _ _ _)
293 | isDeadBinder bndr = CaseCtxt
294 | otherwise = ArgCtxt False -- If the binder is used, this
295 -- is like a strict let
296 -- See Note [RHS of lets] in CoreUnfold
298 interesting (ApplyTo _ arg _ cont)
299 | isTypeArg arg = interesting cont
300 | otherwise = ValAppCtxt -- Can happen if we have (f Int |> co) y
301 -- If f has an INLINE prag we need to give it some
302 -- motivation to inline. See Note [Cast then apply]
305 interesting (StrictArg _ cci _) = cci
306 interesting (StrictBind {}) = BoringCtxt
307 interesting (Stop cci) = cci
308 interesting (CoerceIt _ cont) = interesting cont
309 -- If this call is the arg of a strict function, the context
310 -- is a bit interesting. If we inline here, we may get useful
311 -- evaluation information to avoid repeated evals: e.g.
313 -- Here the contIsInteresting makes the '*' keener to inline,
314 -- which in turn exposes a constructor which makes the '+' inline.
315 -- Assuming that +,* aren't small enough to inline regardless.
317 -- It's also very important to inline in a strict context for things
320 -- Here, the context of (f x) is strict, and if f's unfolding is
321 -- a build it's *great* to inline it here. So we must ensure that
322 -- the context for (f x) is not totally uninteresting.
327 -> [CoreRule] -- Rules for function
328 -> Int -- Number of value args
329 -> SimplCont -- Context of the call
332 mkArgInfo fun rules n_val_args call_cont
333 | n_val_args < idArity fun -- Note [Unsaturated functions]
334 = ArgInfo { ai_fun = fun, ai_args = [], ai_rules = rules
336 , ai_strs = vanilla_stricts
337 , ai_discs = vanilla_discounts }
339 = ArgInfo { ai_fun = fun, ai_args = [], ai_rules = rules
340 , ai_encl = interestingArgContext rules call_cont
341 , ai_strs = add_type_str (idType fun) arg_stricts
342 , ai_discs = arg_discounts }
344 vanilla_discounts, arg_discounts :: [Int]
345 vanilla_discounts = repeat 0
346 arg_discounts = case idUnfolding fun of
347 CoreUnfolding {uf_guidance = UnfIfGoodArgs {ug_args = discounts}}
348 -> discounts ++ vanilla_discounts
349 _ -> vanilla_discounts
351 vanilla_stricts, arg_stricts :: [Bool]
352 vanilla_stricts = repeat False
355 = case splitStrictSig (idStrictness fun) of
356 (demands, result_info)
357 | not (demands `lengthExceeds` n_val_args)
358 -> -- Enough args, use the strictness given.
359 -- For bottoming functions we used to pretend that the arg
360 -- is lazy, so that we don't treat the arg as an
361 -- interesting context. This avoids substituting
362 -- top-level bindings for (say) strings into
363 -- calls to error. But now we are more careful about
364 -- inlining lone variables, so its ok (see SimplUtils.analyseCont)
365 if isBotRes result_info then
366 map isStrictDmd demands -- Finite => result is bottom
368 map isStrictDmd demands ++ vanilla_stricts
370 -> WARN( True, text "More demands than arity" <+> ppr fun <+> ppr (idArity fun)
371 <+> ppr n_val_args <+> ppr demands )
372 vanilla_stricts -- Not enough args, or no strictness
374 add_type_str :: Type -> [Bool] -> [Bool]
375 -- If the function arg types are strict, record that in the 'strictness bits'
376 -- No need to instantiate because unboxed types (which dominate the strict
377 -- types) can't instantiate type variables.
378 -- add_type_str is done repeatedly (for each call); might be better
379 -- once-for-all in the function
380 -- But beware primops/datacons with no strictness
381 add_type_str _ [] = []
382 add_type_str fun_ty strs -- Look through foralls
383 | Just (_, fun_ty') <- splitForAllTy_maybe fun_ty -- Includes coercions
384 = add_type_str fun_ty' strs
385 add_type_str fun_ty (str:strs) -- Add strict-type info
386 | Just (arg_ty, fun_ty') <- splitFunTy_maybe fun_ty
387 = (str || isStrictType arg_ty) : add_type_str fun_ty' strs
391 {- Note [Unsaturated functions]
392 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
393 Consider (test eyeball/inline4)
396 where f has arity 2. Then we do not want to inline 'x', because
397 it'll just be floated out again. Even if f has lots of discounts
398 on its first argument -- it must be saturated for these to kick in
401 interestingArgContext :: [CoreRule] -> SimplCont -> Bool
402 -- If the argument has form (f x y), where x,y are boring,
403 -- and f is marked INLINE, then we don't want to inline f.
404 -- But if the context of the argument is
406 -- where g has rules, then we *do* want to inline f, in case it
407 -- exposes a rule that might fire. Similarly, if the context is
409 -- where h has rules, then we do want to inline f; hence the
410 -- call_cont argument to interestingArgContext
412 -- The ai-rules flag makes this happen; if it's
413 -- set, the inliner gets just enough keener to inline f
414 -- regardless of how boring f's arguments are, if it's marked INLINE
416 -- The alternative would be to *always* inline an INLINE function,
417 -- regardless of how boring its context is; but that seems overkill
418 -- For example, it'd mean that wrapper functions were always inlined
419 interestingArgContext rules call_cont
420 = notNull rules || enclosing_fn_has_rules
422 enclosing_fn_has_rules = go call_cont
424 go (Select {}) = False
425 go (ApplyTo {}) = False
426 go (StrictArg _ cci _) = interesting cci
427 go (StrictBind {}) = False -- ??
428 go (CoerceIt _ c) = go c
429 go (Stop cci) = interesting cci
431 interesting (ArgCtxt rules) = rules
432 interesting _ = False
437 %************************************************************************
439 \subsection{Decisions about inlining}
441 %************************************************************************
443 Inlining is controlled partly by the SimplifierMode switch. This has two
446 SimplGently (a) Simplifying before specialiser/full laziness
447 (b) Simplifiying inside InlineRules
448 (c) Simplifying the LHS of a rule
449 (d) Simplifying a GHCi expression or Template
452 SimplPhase n _ Used at all other times
456 Gentle mode has a separate boolean flag to control
457 a) inlining (sm_inline flag)
458 b) rules (sm_rules flag)
459 A key invariant about Gentle mode is that it is treated as the EARLIEST
460 phase. Something is inlined if the sm_inline flag is on AND the thing
461 is inlinable in the earliest phase. This is important. Example
463 {-# INLINE [~1] g #-}
469 If we were to inline g into f's inlining, then an importing module would
471 f e --> g (g e) ---> RULE fires
472 because the InlineRule for f has had g inlined into it.
474 On the other hand, it is bad not to do ANY inlining into an
475 InlineRule, because then recursive knots in instance declarations
476 don't get unravelled.
478 However, *sometimes* SimplGently must do no call-site inlining at all
479 (hence sm_inline = False). Before full laziness we must be careful
480 not to inline wrappers, because doing so inhibits floating
481 e.g. ...(case f x of ...)...
482 ==> ...(case (case x of I# x# -> fw x#) of ...)...
483 ==> ...(case x of I# x# -> case fw x# of ...)...
484 and now the redex (f x) isn't floatable any more.
486 The no-inlining thing is also important for Template Haskell. You might be
487 compiling in one-shot mode with -O2; but when TH compiles a splice before
488 running it, we don't want to use -O2. Indeed, we don't want to inline
489 anything, because the byte-code interpreter might get confused about
490 unboxed tuples and suchlike.
492 Note [RULEs enabled in SimplGently]
493 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
494 RULES are enabled when doing "gentle" simplification. Two reasons:
496 * We really want the class-op cancellation to happen:
497 op (df d1 d2) --> $cop3 d1 d2
498 because this breaks the mutual recursion between 'op' and 'df'
502 to work in Template Haskell when simplifying
503 splices, so we get simpler code for literal strings
505 But watch out: list fusion can prevent floating. So use phase control
506 to switch off those rules until after floating.
508 Note [Simplifying inside InlineRules]
509 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
510 We must take care with simplification inside InlineRules (which come from
513 First, consider the following example
518 in ...g...g...g...g...g...
519 Now, if that's the ONLY occurrence of f, it might be inlined inside g,
520 and thence copied multiple times when g is inlined. HENCE we treat
521 any occurrence in an InlineRule as a multiple occurrence, not a single
522 one; see OccurAnal.addRuleUsage.
524 Second, we do want *do* to some modest rules/inlining stuff in InlineRules,
525 partly to eliminate senseless crap, and partly to break the recursive knots
526 generated by instance declarations. To keep things simple, we always set
527 the phase to 'gentle' when processing InlineRules. OK, so suppose we have
528 {-# INLINE <act> f #-}
530 meaning "inline f in phases p where activation <act>(p) holds".
531 Then what inlinings/rules can we apply to the copy of <rhs> captured in
532 f's InlineRule? Our model is that literally <rhs> is substituted for
533 f when it is inlined. So our conservative plan (implemented by
534 updModeForInlineRules) is this:
536 -------------------------------------------------------------
537 When simplifying the RHS of an InlineRule,
538 If the InlineRule becomes active in phase p, then
539 if the current phase is *earlier than* p,
540 make no inlinings or rules active when simplifying the RHS
542 set the phase to p when simplifying the RHS
543 -------------------------------------------------------------
547 a) Rules/inlinings that *cease* being active before p will
548 not apply to the InlineRule rhs, consistent with it being
549 inlined in its *original* form in phase p.
551 b) Rules/inlinings that only become active *after* p will
552 not apply to the InlineRule rhs, again to be consistent with
553 inlining the *original* rhs in phase p.
559 {-# NOINLINE [1] g #-}
562 {-# RULE h g = ... #-}
563 Here we must not inline g into f's RHS, even when we get to phase 0,
564 because when f is later inlined into some other module we want the
572 and suppose that there are auto-generated specialisations and a strictness
573 wrapper for g. The specialisations get activation AlwaysActive, and the
574 strictness wrapper get activation (ActiveAfter 0). So the strictness
575 wrepper fails the test and won't be inlined into f's InlineRule. That
576 means f can inline, expose the specialised call to g, so the specialisation
579 A note about wrappers
580 ~~~~~~~~~~~~~~~~~~~~~
581 It's also important not to inline a worker back into a wrapper.
583 wraper = inline_me (\x -> ...worker... )
584 Normally, the inline_me prevents the worker getting inlined into
585 the wrapper (initially, the worker's only call site!). But,
586 if the wrapper is sure to be called, the strictness analyser will
587 mark it 'demanded', so when the RHS is simplified, it'll get an ArgOf
591 simplEnvForGHCi :: SimplEnv
592 simplEnvForGHCi = mkSimplEnv allOffSwitchChecker $
593 SimplGently { sm_rules = False, sm_inline = False }
594 -- Do not do any inlining, in case we expose some unboxed
595 -- tuple stuff that confuses the bytecode interpreter
597 simplEnvForRules :: SimplEnv
598 simplEnvForRules = mkSimplEnv allOffSwitchChecker $
599 SimplGently { sm_rules = True, sm_inline = False }
601 updModeForInlineRules :: Activation -> SimplifierMode -> SimplifierMode
602 -- See Note [Simplifying inside InlineRules]
603 -- Treat Gentle as phase "infinity"
604 -- If current_phase `earlier than` inline_rule_start_phase
607 -- if current_phase `same phase` inline_rule_start_phase
608 -- then current_phase (keep gentle flags)
609 -- else inline_rule_start_phase
610 updModeForInlineRules inline_rule_act current_mode
611 = case inline_rule_act of
613 AlwaysActive -> mk_gentle current_mode
614 ActiveBefore {} -> mk_gentle current_mode
615 ActiveAfter n -> mk_phase n current_mode
617 no_op = SimplGently { sm_rules = False, sm_inline = False }
619 mk_gentle (SimplGently {}) = current_mode
620 mk_gentle _ = SimplGently { sm_rules = True, sm_inline = True }
622 mk_phase n (SimplPhase _ ss) = SimplPhase n ss
623 mk_phase n (SimplGently {}) = SimplPhase n ["gentle-rules"]
627 preInlineUnconditionally
628 ~~~~~~~~~~~~~~~~~~~~~~~~
629 @preInlineUnconditionally@ examines a bndr to see if it is used just
630 once in a completely safe way, so that it is safe to discard the
631 binding inline its RHS at the (unique) usage site, REGARDLESS of how
632 big the RHS might be. If this is the case we don't simplify the RHS
633 first, but just inline it un-simplified.
635 This is much better than first simplifying a perhaps-huge RHS and then
636 inlining and re-simplifying it. Indeed, it can be at least quadratically
645 We may end up simplifying e1 N times, e2 N-1 times, e3 N-3 times etc.
646 This can happen with cascades of functions too:
653 THE MAIN INVARIANT is this:
655 ---- preInlineUnconditionally invariant -----
656 IF preInlineUnconditionally chooses to inline x = <rhs>
657 THEN doing the inlining should not change the occurrence
658 info for the free vars of <rhs>
659 ----------------------------------------------
661 For example, it's tempting to look at trivial binding like
663 and inline it unconditionally. But suppose x is used many times,
664 but this is the unique occurrence of y. Then inlining x would change
665 y's occurrence info, which breaks the invariant. It matters: y
666 might have a BIG rhs, which will now be dup'd at every occurrenc of x.
669 Even RHSs labelled InlineMe aren't caught here, because there might be
670 no benefit from inlining at the call site.
672 [Sept 01] Don't unconditionally inline a top-level thing, because that
673 can simply make a static thing into something built dynamically. E.g.
677 [Remember that we treat \s as a one-shot lambda.] No point in
678 inlining x unless there is something interesting about the call site.
680 But watch out: if you aren't careful, some useful foldr/build fusion
681 can be lost (most notably in spectral/hartel/parstof) because the
682 foldr didn't see the build. Doing the dynamic allocation isn't a big
683 deal, in fact, but losing the fusion can be. But the right thing here
684 seems to be to do a callSiteInline based on the fact that there is
685 something interesting about the call site (it's strict). Hmm. That
688 Conclusion: inline top level things gaily until Phase 0 (the last
689 phase), at which point don't.
691 Note [pre/postInlineUnconditionally in gentle mode]
692 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
693 Even in gentle mode we want to do preInlineUnconditionally. The
694 reason is that too little clean-up happens if you don't inline
695 use-once things. Also a bit of inlining is *good* for full laziness;
696 it can expose constant sub-expressions. Example in
697 spectral/mandel/Mandel.hs, where the mandelset function gets a useful
698 let-float if you inline windowToViewport
700 However, as usual for Gentle mode, do not inline things that are
701 inactive in the intial stages. See Note [Gentle mode].
703 Note [InlineRule and preInlineUnconditionally]
704 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
705 Surprisingly, do not pre-inline-unconditionally Ids with INLINE pragmas!
715 ...fInt...fInt...fInt...
717 Here f occurs just once, in the RHS of f1. But if we inline it there
718 we'll lose the opportunity to inline at each of fInt's call sites.
719 The INLINE pragma will only inline when the application is saturated
720 for exactly this reason; and we don't want PreInlineUnconditionally
721 to second-guess it. A live example is Trac #3736.
722 c.f. Note [InlineRule and postInlineUnconditionally]
724 Note [Top-level botomming Ids]
725 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
726 Don't inline top-level Ids that are bottoming, even if they are used just
727 once, because FloatOut has gone to some trouble to extract them out.
728 Inlining them won't make the program run faster!
731 preInlineUnconditionally :: SimplEnv -> TopLevelFlag -> InId -> InExpr -> Bool
732 preInlineUnconditionally env top_lvl bndr rhs
734 | isStableUnfolding (idUnfolding bndr) = False -- Note [InlineRule and preInlineUnconditionally]
735 | isTopLevel top_lvl && isBottomingId bndr = False -- Note [Top-level bottoming Ids]
736 | opt_SimplNoPreInlining = False
737 | otherwise = case idOccInfo bndr of
738 IAmDead -> True -- Happens in ((\x.1) v)
739 OneOcc in_lam True int_cxt -> try_once in_lam int_cxt
743 active = case phase of
744 SimplGently {} -> isEarlyActive act
745 -- See Note [pre/postInlineUnconditionally in gentle mode]
746 SimplPhase n _ -> isActive n act
747 act = idInlineActivation bndr
748 try_once in_lam int_cxt -- There's one textual occurrence
749 | not in_lam = isNotTopLevel top_lvl || early_phase
750 | otherwise = int_cxt && canInlineInLam rhs
752 -- Be very careful before inlining inside a lambda, because (a) we must not
753 -- invalidate occurrence information, and (b) we want to avoid pushing a
754 -- single allocation (here) into multiple allocations (inside lambda).
755 -- Inlining a *function* with a single *saturated* call would be ok, mind you.
756 -- || (if is_cheap && not (canInlineInLam rhs) then pprTrace "preinline" (ppr bndr <+> ppr rhs) ok else ok)
758 -- is_cheap = exprIsCheap rhs
759 -- ok = is_cheap && int_cxt
761 -- int_cxt The context isn't totally boring
762 -- E.g. let f = \ab.BIG in \y. map f xs
763 -- Don't want to substitute for f, because then we allocate
764 -- its closure every time the \y is called
765 -- But: let f = \ab.BIG in \y. map (f y) xs
766 -- Now we do want to substitute for f, even though it's not
767 -- saturated, because we're going to allocate a closure for
768 -- (f y) every time round the loop anyhow.
770 -- canInlineInLam => free vars of rhs are (Once in_lam) or Many,
771 -- so substituting rhs inside a lambda doesn't change the occ info.
772 -- Sadly, not quite the same as exprIsHNF.
773 canInlineInLam (Lit _) = True
774 canInlineInLam (Lam b e) = isRuntimeVar b || canInlineInLam e
775 canInlineInLam (Note _ e) = canInlineInLam e
776 canInlineInLam _ = False
778 early_phase = case phase of
779 SimplPhase 0 _ -> False
781 -- If we don't have this early_phase test, consider
782 -- x = length [1,2,3]
783 -- The full laziness pass carefully floats all the cons cells to
784 -- top level, and preInlineUnconditionally floats them all back in.
785 -- Result is (a) static allocation replaced by dynamic allocation
786 -- (b) many simplifier iterations because this tickles
787 -- a related problem; only one inlining per pass
789 -- On the other hand, I have seen cases where top-level fusion is
790 -- lost if we don't inline top level thing (e.g. string constants)
791 -- Hence the test for phase zero (which is the phase for all the final
792 -- simplifications). Until phase zero we take no special notice of
793 -- top level things, but then we become more leery about inlining
798 postInlineUnconditionally
799 ~~~~~~~~~~~~~~~~~~~~~~~~~
800 @postInlineUnconditionally@ decides whether to unconditionally inline
801 a thing based on the form of its RHS; in particular if it has a
802 trivial RHS. If so, we can inline and discard the binding altogether.
804 NB: a loop breaker has must_keep_binding = True and non-loop-breakers
805 only have *forward* references Hence, it's safe to discard the binding
807 NOTE: This isn't our last opportunity to inline. We're at the binding
808 site right now, and we'll get another opportunity when we get to the
811 Note that we do this unconditional inlining only for trival RHSs.
812 Don't inline even WHNFs inside lambdas; doing so may simply increase
813 allocation when the function is called. This isn't the last chance; see
816 NB: Even inline pragmas (e.g. IMustBeINLINEd) are ignored here Why?
817 Because we don't even want to inline them into the RHS of constructor
818 arguments. See NOTE above
820 NB: At one time even NOINLINE was ignored here: if the rhs is trivial
821 it's best to inline it anyway. We often get a=E; b=a from desugaring,
822 with both a and b marked NOINLINE. But that seems incompatible with
823 our new view that inlining is like a RULE, so I'm sticking to the 'active'
827 postInlineUnconditionally
828 :: SimplEnv -> TopLevelFlag
829 -> OutId -- The binder (an InId would be fine too)
830 -> OccInfo -- From the InId
834 postInlineUnconditionally env top_lvl bndr occ_info rhs unfolding
836 | isLoopBreaker occ_info = False -- If it's a loop-breaker of any kind, don't inline
837 -- because it might be referred to "earlier"
838 | isExportedId bndr = False
839 | isStableUnfolding unfolding = False -- Note [InlineRule and postInlineUnconditionally]
840 | exprIsTrivial rhs = True
841 | isTopLevel top_lvl = False -- Note [Top level and postInlineUnconditionally]
844 -- The point of examining occ_info here is that for *non-values*
845 -- that occur outside a lambda, the call-site inliner won't have
846 -- a chance (becuase it doesn't know that the thing
847 -- only occurs once). The pre-inliner won't have gotten
848 -- it either, if the thing occurs in more than one branch
849 -- So the main target is things like
852 -- True -> case x of ...
853 -- False -> case x of ...
854 -- This is very important in practice; e.g. wheel-seive1 doubles
855 -- in allocation if you miss this out
856 OneOcc in_lam _one_br int_cxt -- OneOcc => no code-duplication issue
857 -> smallEnoughToInline unfolding -- Small enough to dup
858 -- ToDo: consider discount on smallEnoughToInline if int_cxt is true
860 -- NB: Do NOT inline arbitrarily big things, even if one_br is True
861 -- Reason: doing so risks exponential behaviour. We simplify a big
862 -- expression, inline it, and simplify it again. But if the
863 -- very same thing happens in the big expression, we get
865 -- PRINCIPLE: when we've already simplified an expression once,
866 -- make sure that we only inline it if it's reasonably small.
869 -- Outside a lambda, we want to be reasonably aggressive
870 -- about inlining into multiple branches of case
871 -- e.g. let x = <non-value>
872 -- in case y of { C1 -> ..x..; C2 -> ..x..; C3 -> ... }
873 -- Inlining can be a big win if C3 is the hot-spot, even if
874 -- the uses in C1, C2 are not 'interesting'
875 -- An example that gets worse if you add int_cxt here is 'clausify'
877 (isCheapUnfolding unfolding && int_cxt))
878 -- isCheap => acceptable work duplication; in_lam may be true
879 -- int_cxt to prevent us inlining inside a lambda without some
880 -- good reason. See the notes on int_cxt in preInlineUnconditionally
882 IAmDead -> True -- This happens; for example, the case_bndr during case of
883 -- known constructor: case (a,b) of x { (p,q) -> ... }
884 -- Here x isn't mentioned in the RHS, so we don't want to
885 -- create the (dead) let-binding let x = (a,b) in ...
889 -- Here's an example that we don't handle well:
890 -- let f = if b then Left (\x.BIG) else Right (\y.BIG)
891 -- in \y. ....case f of {...} ....
892 -- Here f is used just once, and duplicating the case work is fine (exprIsCheap).
894 -- - We can't preInlineUnconditionally because that woud invalidate
895 -- the occ info for b.
896 -- - We can't postInlineUnconditionally because the RHS is big, and
897 -- that risks exponential behaviour
898 -- - We can't call-site inline, because the rhs is big
902 active = case getMode env of
903 SimplGently {} -> isEarlyActive act
904 -- See Note [pre/postInlineUnconditionally in gentle mode]
905 SimplPhase n _ -> isActive n act
906 act = idInlineActivation bndr
908 activeUnfolding :: SimplEnv -> IdUnfoldingFun
910 = case getMode env of
911 SimplGently { sm_inline = False } -> active_unfolding_minimal
912 SimplGently { sm_inline = True } -> active_unfolding_gentle
913 SimplPhase n _ -> active_unfolding n
915 activeUnfInRule :: SimplEnv -> IdUnfoldingFun
916 -- When matching in RULE, we want to "look through" an unfolding
917 -- if *rules* are on, even if *inlinings* are not. A notable example
918 -- is DFuns, which really we want to match in rules like (op dfun)
921 = case getMode env of
922 SimplGently { sm_rules = False } -> active_unfolding_minimal
923 SimplGently { sm_rules = True } -> active_unfolding_gentle
924 SimplPhase n _ -> active_unfolding n
926 active_unfolding_minimal :: IdUnfoldingFun
927 -- Compuslory unfoldings only
928 -- Ignore SimplGently, because we want to inline regardless;
929 -- the Id has no top-level binding at all
931 -- NB: we used to have a second exception, for data con wrappers.
932 -- On the grounds that we use gentle mode for rule LHSs, and
933 -- they match better when data con wrappers are inlined.
934 -- But that only really applies to the trivial wrappers (like (:)),
935 -- and they are now constructed as Compulsory unfoldings (in MkId)
936 -- so they'll happen anyway.
937 active_unfolding_minimal id
938 | isCompulsoryUnfolding unf = unf
939 | otherwise = NoUnfolding
941 unf = realIdUnfolding id -- Never a loop breaker
943 active_unfolding_gentle :: IdUnfoldingFun
944 -- Anything that is early-active
945 -- See Note [Gentle mode]
946 active_unfolding_gentle id
947 | isEarlyActive (idInlineActivation id) = idUnfolding id
948 | otherwise = NoUnfolding
949 -- idUnfolding checks for loop-breakers
950 -- Things with an INLINE pragma may have
951 -- an unfolding *and* be a loop breaker
952 -- (maybe the knot is not yet untied)
954 active_unfolding :: CompilerPhase -> IdUnfoldingFun
955 active_unfolding n id
956 | isActive n (idInlineActivation id) = idUnfolding id
957 | otherwise = NoUnfolding
959 activeRule :: DynFlags -> SimplEnv -> Maybe (Activation -> Bool)
960 -- Nothing => No rules at all
961 activeRule dflags env
962 | not (dopt Opt_EnableRewriteRules dflags)
963 = Nothing -- Rewriting is off
965 = case getMode env of
966 SimplGently { sm_rules = rules_on }
967 | rules_on -> Just isEarlyActive -- Note [RULEs enabled in SimplGently]
968 | otherwise -> Nothing
969 SimplPhase n _ -> Just (isActive n)
972 Note [Top level and postInlineUnconditionally]
973 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
974 We don't do postInlineUnconditionally for top-level things (exept ones that
976 * There is no point, because the main goal is to get rid of local
977 bindings used in multiple case branches.
978 * Doing so will inline top-level error expressions that have been
979 carefully floated out by FloatOut. More generally, it might
980 replace static allocation with dynamic.
982 Note [InlineRule and postInlineUnconditionally]
983 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
984 Do not do postInlineUnconditionally if the Id has an InlineRule, otherwise
985 we lose the unfolding. Example
987 -- f has InlineRule with rhs (e |> co)
991 Then there's a danger we'll optimise to
996 and now postInlineUnconditionally, losing the InlineRule on f. Now f'
997 won't inline because 'e' is too big.
999 c.f. Note [InlineRule and preInlineUnconditionally]
1002 %************************************************************************
1006 %************************************************************************
1009 mkLam :: SimplEnv -> [OutBndr] -> OutExpr -> SimplM OutExpr
1010 -- mkLam tries three things
1011 -- a) eta reduction, if that gives a trivial expression
1012 -- b) eta expansion [only if there are some value lambdas]
1016 mkLam _env bndrs body
1017 = do { dflags <- getDOptsSmpl
1018 ; mkLam' dflags bndrs body }
1020 mkLam' :: DynFlags -> [OutBndr] -> OutExpr -> SimplM OutExpr
1021 mkLam' dflags bndrs (Cast body co)
1022 | not (any bad bndrs)
1023 -- Note [Casts and lambdas]
1024 = do { lam <- mkLam' dflags bndrs body
1025 ; return (mkCoerce (mkPiTypes bndrs co) lam) }
1027 co_vars = tyVarsOfType co
1028 bad bndr = isCoVar bndr && bndr `elemVarSet` co_vars
1030 mkLam' dflags bndrs body
1031 | dopt Opt_DoEtaReduction dflags,
1032 Just etad_lam <- tryEtaReduce bndrs body
1033 = do { tick (EtaReduction (head bndrs))
1036 | dopt Opt_DoLambdaEtaExpansion dflags,
1037 not (all isTyVar bndrs) -- Don't eta expand type abstractions
1038 = do { let body' = tryEtaExpansion dflags body
1039 ; return (mkLams bndrs body') }
1042 = return (mkLams bndrs body)
1045 Note [Casts and lambdas]
1046 ~~~~~~~~~~~~~~~~~~~~~~~~
1048 (\x. (\y. e) `cast` g1) `cast` g2
1049 There is a danger here that the two lambdas look separated, and the
1050 full laziness pass might float an expression to between the two.
1052 So this equation in mkLam' floats the g1 out, thus:
1053 (\x. e `cast` g1) --> (\x.e) `cast` (tx -> g1)
1056 In general, this floats casts outside lambdas, where (I hope) they
1057 might meet and cancel with some other cast:
1058 \x. e `cast` co ===> (\x. e) `cast` (tx -> co)
1059 /\a. e `cast` co ===> (/\a. e) `cast` (/\a. co)
1060 /\g. e `cast` co ===> (/\g. e) `cast` (/\g. co)
1061 (if not (g `in` co))
1063 Notice that it works regardless of 'e'. Originally it worked only
1064 if 'e' was itself a lambda, but in some cases that resulted in
1065 fruitless iteration in the simplifier. A good example was when
1066 compiling Text.ParserCombinators.ReadPrec, where we had a definition
1067 like (\x. Get `cast` g)
1068 where Get is a constructor with nonzero arity. Then mkLam eta-expanded
1069 the Get, and the next iteration eta-reduced it, and then eta-expanded
1072 Note also the side condition for the case of coercion binders.
1073 It does not make sense to transform
1074 /\g. e `cast` g ==> (/\g.e) `cast` (/\g.g)
1075 because the latter is not well-kinded.
1077 -- c) floating lets out through big lambdas
1078 -- [only if all tyvar lambdas, and only if this lambda
1079 -- is the RHS of a let]
1081 {- Sept 01: I'm experimenting with getting the
1082 full laziness pass to float out past big lambdsa
1083 | all isTyVar bndrs, -- Only for big lambdas
1084 contIsRhs cont -- Only try the rhs type-lambda floating
1085 -- if this is indeed a right-hand side; otherwise
1086 -- we end up floating the thing out, only for float-in
1087 -- to float it right back in again!
1088 = do (floats, body') <- tryRhsTyLam env bndrs body
1089 return (floats, mkLams bndrs body')
1093 %************************************************************************
1097 %************************************************************************
1099 Note [Eta reduction conditions]
1100 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1101 We try for eta reduction here, but *only* if we get all the way to an
1102 trivial expression. We don't want to remove extra lambdas unless we
1103 are going to avoid allocating this thing altogether.
1105 There are some particularly delicate points here:
1107 * Eta reduction is not valid in general:
1109 This matters, partly for old-fashioned correctness reasons but,
1110 worse, getting it wrong can yield a seg fault. Consider
1112 h y = case (case y of { True -> f `seq` True; False -> False }) of
1113 True -> ...; False -> ...
1115 If we (unsoundly) eta-reduce f to get f=f, the strictness analyser
1116 says f=bottom, and replaces the (f `seq` True) with just
1117 (f `cast` unsafe-co). BUT, as thing stand, 'f' got arity 1, and it
1118 *keeps* arity 1 (perhaps also wrongly). So CorePrep eta-expands
1119 the definition again, so that it does not termninate after all.
1120 Result: seg-fault because the boolean case actually gets a function value.
1123 So it's important to to the right thing.
1125 * Note [Arity care]: we need to be careful if we just look at f's
1126 arity. Currently (Dec07), f's arity is visible in its own RHS (see
1127 Note [Arity robustness] in SimplEnv) so we must *not* trust the
1128 arity when checking that 'f' is a value. Otherwise we will
1133 Which might change a terminiating program (think (f `seq` e)) to a
1134 non-terminating one. So we check for being a loop breaker first.
1136 However for GlobalIds we can look at the arity; and for primops we
1137 must, since they have no unfolding.
1139 * Regardless of whether 'f' is a value, we always want to
1140 reduce (/\a -> f a) to f
1141 This came up in a RULE: foldr (build (/\a -> g a))
1142 did not match foldr (build (/\b -> ...something complex...))
1143 The type checker can insert these eta-expanded versions,
1144 with both type and dictionary lambdas; hence the slightly
1147 * Never *reduce* arity. For example
1149 Then if h has arity 1 we don't want to eta-reduce because then
1150 f's arity would decrease, and that is bad
1152 These delicacies are why we don't use exprIsTrivial and exprIsHNF here.
1156 tryEtaReduce :: [OutBndr] -> OutExpr -> Maybe OutExpr
1157 tryEtaReduce bndrs body
1158 = go (reverse bndrs) body
1160 incoming_arity = count isId bndrs
1162 go (b : bs) (App fun arg) | ok_arg b arg = go bs fun -- Loop round
1163 go [] fun | ok_fun fun = Just fun -- Success!
1164 go _ _ = Nothing -- Failure!
1166 -- Note [Eta reduction conditions]
1167 ok_fun (App fun (Type ty))
1168 | not (any (`elemVarSet` tyVarsOfType ty) bndrs)
1171 = not (fun_id `elem` bndrs)
1172 && (ok_fun_id fun_id || all ok_lam bndrs)
1175 ok_fun_id fun = fun_arity fun >= incoming_arity
1177 fun_arity fun -- See Note [Arity care]
1178 | isLocalId fun && isLoopBreaker (idOccInfo fun) = 0
1179 | otherwise = idArity fun
1181 ok_lam v = isTyVar v || isDictId v
1183 ok_arg b arg = varToCoreExpr b `cheapEqExpr` arg
1187 %************************************************************************
1191 %************************************************************************
1195 f = \x1..xn -> N ==> f = \x1..xn y1..ym -> N y1..ym
1198 where (in both cases)
1200 * The xi can include type variables
1202 * The yi are all value variables
1204 * N is a NORMAL FORM (i.e. no redexes anywhere)
1205 wanting a suitable number of extra args.
1207 The biggest reason for doing this is for cases like
1213 Here we want to get the lambdas together. A good exmaple is the nofib
1214 program fibheaps, which gets 25% more allocation if you don't do this
1217 We may have to sandwich some coerces between the lambdas
1218 to make the types work. exprEtaExpandArity looks through coerces
1219 when computing arity; and etaExpand adds the coerces as necessary when
1220 actually computing the expansion.
1223 tryEtaExpansion :: DynFlags -> OutExpr -> OutExpr
1224 -- There is at least one runtime binder in the binders
1225 tryEtaExpansion dflags body
1226 = etaExpand fun_arity body
1228 fun_arity = exprEtaExpandArity dflags body
1232 %************************************************************************
1234 \subsection{Floating lets out of big lambdas}
1236 %************************************************************************
1238 Note [Floating and type abstraction]
1239 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1242 We'd like to float this to
1245 x = /\a. C (y1 a) (y2 a)
1246 for the usual reasons: we want to inline x rather vigorously.
1248 You may think that this kind of thing is rare. But in some programs it is
1249 common. For example, if you do closure conversion you might get:
1251 data a :-> b = forall e. (e -> a -> b) :$ e
1253 f_cc :: forall a. a :-> a
1254 f_cc = /\a. (\e. id a) :$ ()
1256 Now we really want to inline that f_cc thing so that the
1257 construction of the closure goes away.
1259 So I have elaborated simplLazyBind to understand right-hand sides that look
1263 and treat them specially. The real work is done in SimplUtils.abstractFloats,
1264 but there is quite a bit of plumbing in simplLazyBind as well.
1266 The same transformation is good when there are lets in the body:
1268 /\abc -> let(rec) x = e in b
1270 let(rec) x' = /\abc -> let x = x' a b c in e
1272 /\abc -> let x = x' a b c in b
1274 This is good because it can turn things like:
1276 let f = /\a -> letrec g = ... g ... in g
1278 letrec g' = /\a -> ... g' a ...
1280 let f = /\ a -> g' a
1282 which is better. In effect, it means that big lambdas don't impede
1285 This optimisation is CRUCIAL in eliminating the junk introduced by
1286 desugaring mutually recursive definitions. Don't eliminate it lightly!
1288 [May 1999] If we do this transformation *regardless* then we can
1289 end up with some pretty silly stuff. For example,
1292 st = /\ s -> let { x1=r1 ; x2=r2 } in ...
1297 st = /\s -> ...[y1 s/x1, y2 s/x2]
1300 Unless the "..." is a WHNF there is really no point in doing this.
1301 Indeed it can make things worse. Suppose x1 is used strictly,
1304 x1* = case f y of { (a,b) -> e }
1306 If we abstract this wrt the tyvar we then can't do the case inline
1307 as we would normally do.
1309 That's why the whole transformation is part of the same process that
1310 floats let-bindings and constructor arguments out of RHSs. In particular,
1311 it is guarded by the doFloatFromRhs call in simplLazyBind.
1315 abstractFloats :: [OutTyVar] -> SimplEnv -> OutExpr -> SimplM ([OutBind], OutExpr)
1316 abstractFloats main_tvs body_env body
1317 = ASSERT( notNull body_floats )
1318 do { (subst, float_binds) <- mapAccumLM abstract empty_subst body_floats
1319 ; return (float_binds, CoreSubst.substExpr (text "abstract_floats1") subst body) }
1321 main_tv_set = mkVarSet main_tvs
1322 body_floats = getFloats body_env
1323 empty_subst = CoreSubst.mkEmptySubst (seInScope body_env)
1325 abstract :: CoreSubst.Subst -> OutBind -> SimplM (CoreSubst.Subst, OutBind)
1326 abstract subst (NonRec id rhs)
1327 = do { (poly_id, poly_app) <- mk_poly tvs_here id
1328 ; let poly_rhs = mkLams tvs_here rhs'
1329 subst' = CoreSubst.extendIdSubst subst id poly_app
1330 ; return (subst', (NonRec poly_id poly_rhs)) }
1332 rhs' = CoreSubst.substExpr (text "abstract_floats2") subst rhs
1333 tvs_here | any isCoVar main_tvs = main_tvs -- Note [Abstract over coercions]
1335 = varSetElems (main_tv_set `intersectVarSet` exprSomeFreeVars isTyVar rhs')
1337 -- Abstract only over the type variables free in the rhs
1338 -- wrt which the new binding is abstracted. But the naive
1339 -- approach of abstract wrt the tyvars free in the Id's type
1341 -- /\ a b -> let t :: (a,b) = (e1, e2)
1344 -- Here, b isn't free in x's type, but we must nevertheless
1345 -- abstract wrt b as well, because t's type mentions b.
1346 -- Since t is floated too, we'd end up with the bogus:
1347 -- poly_t = /\ a b -> (e1, e2)
1348 -- poly_x = /\ a -> fst (poly_t a *b*)
1349 -- So for now we adopt the even more naive approach of
1350 -- abstracting wrt *all* the tyvars. We'll see if that
1351 -- gives rise to problems. SLPJ June 98
1353 abstract subst (Rec prs)
1354 = do { (poly_ids, poly_apps) <- mapAndUnzipM (mk_poly tvs_here) ids
1355 ; let subst' = CoreSubst.extendSubstList subst (ids `zip` poly_apps)
1356 poly_rhss = [mkLams tvs_here (CoreSubst.substExpr (text "abstract_floats3") subst' rhs)
1358 ; return (subst', Rec (poly_ids `zip` poly_rhss)) }
1360 (ids,rhss) = unzip prs
1361 -- For a recursive group, it's a bit of a pain to work out the minimal
1362 -- set of tyvars over which to abstract:
1363 -- /\ a b c. let x = ...a... in
1364 -- letrec { p = ...x...q...
1365 -- q = .....p...b... } in
1367 -- Since 'x' is abstracted over 'a', the {p,q} group must be abstracted
1368 -- over 'a' (because x is replaced by (poly_x a)) as well as 'b'.
1369 -- Since it's a pain, we just use the whole set, which is always safe
1371 -- If you ever want to be more selective, remember this bizarre case too:
1373 -- Here, we must abstract 'x' over 'a'.
1376 mk_poly tvs_here var
1377 = do { uniq <- getUniqueM
1378 ; let poly_name = setNameUnique (idName var) uniq -- Keep same name
1379 poly_ty = mkForAllTys tvs_here (idType var) -- But new type of course
1380 poly_id = transferPolyIdInfo var tvs_here $ -- Note [transferPolyIdInfo] in Id.lhs
1381 mkLocalId poly_name poly_ty
1382 ; return (poly_id, mkTyApps (Var poly_id) (mkTyVarTys tvs_here)) }
1383 -- In the olden days, it was crucial to copy the occInfo of the original var,
1384 -- because we were looking at occurrence-analysed but as yet unsimplified code!
1385 -- In particular, we mustn't lose the loop breakers. BUT NOW we are looking
1386 -- at already simplified code, so it doesn't matter
1388 -- It's even right to retain single-occurrence or dead-var info:
1389 -- Suppose we started with /\a -> let x = E in B
1390 -- where x occurs once in B. Then we transform to:
1391 -- let x' = /\a -> E in /\a -> let x* = x' a in B
1392 -- where x* has an INLINE prag on it. Now, once x* is inlined,
1393 -- the occurrences of x' will be just the occurrences originally
1397 Note [Abstract over coercions]
1398 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1399 If a coercion variable (g :: a ~ Int) is free in the RHS, then so is the
1400 type variable a. Rather than sort this mess out, we simply bale out and abstract
1401 wrt all the type variables if any of them are coercion variables.
1404 Historical note: if you use let-bindings instead of a substitution, beware of this:
1406 -- Suppose we start with:
1408 -- x = /\ a -> let g = G in E
1410 -- Then we'll float to get
1412 -- x = let poly_g = /\ a -> G
1413 -- in /\ a -> let g = poly_g a in E
1415 -- But now the occurrence analyser will see just one occurrence
1416 -- of poly_g, not inside a lambda, so the simplifier will
1417 -- PreInlineUnconditionally poly_g back into g! Badk to square 1!
1418 -- (I used to think that the "don't inline lone occurrences" stuff
1419 -- would stop this happening, but since it's the *only* occurrence,
1420 -- PreInlineUnconditionally kicks in first!)
1422 -- Solution: put an INLINE note on g's RHS, so that poly_g seems
1423 -- to appear many times. (NB: mkInlineMe eliminates
1424 -- such notes on trivial RHSs, so do it manually.)
1426 %************************************************************************
1430 %************************************************************************
1432 prepareAlts tries these things:
1434 1. Eliminate alternatives that cannot match, including the
1435 DEFAULT alternative.
1437 2. If the DEFAULT alternative can match only one possible constructor,
1438 then make that constructor explicit.
1440 case e of x { DEFAULT -> rhs }
1442 case e of x { (a,b) -> rhs }
1443 where the type is a single constructor type. This gives better code
1444 when rhs also scrutinises x or e.
1446 3. Returns a list of the constructors that cannot holds in the
1447 DEFAULT alternative (if there is one)
1449 Here "cannot match" includes knowledge from GADTs
1451 It's a good idea do do this stuff before simplifying the alternatives, to
1452 avoid simplifying alternatives we know can't happen, and to come up with
1453 the list of constructors that are handled, to put into the IdInfo of the
1454 case binder, for use when simplifying the alternatives.
1456 Eliminating the default alternative in (1) isn't so obvious, but it can
1459 data Colour = Red | Green | Blue
1468 DEFAULT -> [ case y of ... ]
1470 If we inline h into f, the default case of the inlined h can't happen.
1471 If we don't notice this, we may end up filtering out *all* the cases
1472 of the inner case y, which give us nowhere to go!
1475 prepareAlts :: OutExpr -> OutId -> [InAlt] -> SimplM ([AltCon], [InAlt])
1476 prepareAlts scrut case_bndr' alts
1477 = do { let (alts_wo_default, maybe_deflt) = findDefault alts
1478 alt_cons = [con | (con,_,_) <- alts_wo_default]
1479 imposs_deflt_cons = nub (imposs_cons ++ alt_cons)
1480 -- "imposs_deflt_cons" are handled
1481 -- EITHER by the context,
1482 -- OR by a non-DEFAULT branch in this case expression.
1484 ; default_alts <- prepareDefault case_bndr' mb_tc_app
1485 imposs_deflt_cons maybe_deflt
1487 ; let trimmed_alts = filterOut impossible_alt alts_wo_default
1488 merged_alts = mergeAlts trimmed_alts default_alts
1489 -- We need the mergeAlts in case the new default_alt
1490 -- has turned into a constructor alternative.
1491 -- The merge keeps the inner DEFAULT at the front, if there is one
1492 -- and interleaves the alternatives in the right order
1494 ; return (imposs_deflt_cons, merged_alts) }
1496 mb_tc_app = splitTyConApp_maybe (idType case_bndr')
1497 Just (_, inst_tys) = mb_tc_app
1499 imposs_cons = case scrut of
1500 Var v -> otherCons (idUnfolding v)
1503 impossible_alt :: CoreAlt -> Bool
1504 impossible_alt (con, _, _) | con `elem` imposs_cons = True
1505 impossible_alt (DataAlt con, _, _) = dataConCannotMatch inst_tys con
1506 impossible_alt _ = False
1509 prepareDefault :: OutId -- Case binder; need just for its type. Note that as an
1510 -- OutId, it has maximum information; this is important.
1511 -- Test simpl013 is an example
1512 -> Maybe (TyCon, [Type]) -- Type of scrutinee, decomposed
1513 -> [AltCon] -- These cons can't happen when matching the default
1514 -> Maybe InExpr -- Rhs
1515 -> SimplM [InAlt] -- Still unsimplified
1516 -- We use a list because it's what mergeAlts expects,
1518 --------- Fill in known constructor -----------
1519 prepareDefault case_bndr (Just (tycon, inst_tys)) imposs_cons (Just deflt_rhs)
1520 | -- This branch handles the case where we are
1521 -- scrutinisng an algebraic data type
1522 isAlgTyCon tycon -- It's a data type, tuple, or unboxed tuples.
1523 , not (isNewTyCon tycon) -- We can have a newtype, if we are just doing an eval:
1524 -- case x of { DEFAULT -> e }
1525 -- and we don't want to fill in a default for them!
1526 , Just all_cons <- tyConDataCons_maybe tycon
1527 , not (null all_cons) -- This is a tricky corner case. If the data type has no constructors,
1528 -- which GHC allows, then the case expression will have at most a default
1529 -- alternative. We don't want to eliminate that alternative, because the
1530 -- invariant is that there's always one alternative. It's more convenient
1532 -- case x of { DEFAULT -> e }
1533 -- as it is, rather than transform it to
1534 -- error "case cant match"
1535 -- which would be quite legitmate. But it's a really obscure corner, and
1536 -- not worth wasting code on.
1537 , let imposs_data_cons = [con | DataAlt con <- imposs_cons] -- We now know it's a data type
1538 impossible con = con `elem` imposs_data_cons || dataConCannotMatch inst_tys con
1539 = case filterOut impossible all_cons of
1540 [] -> return [] -- Eliminate the default alternative
1541 -- altogether if it can't match
1543 [con] -> -- It matches exactly one constructor, so fill it in
1544 do { tick (FillInCaseDefault case_bndr)
1546 ; let (ex_tvs, co_tvs, arg_ids) =
1547 dataConRepInstPat us con inst_tys
1548 ; return [(DataAlt con, ex_tvs ++ co_tvs ++ arg_ids, deflt_rhs)] }
1550 _ -> return [(DEFAULT, [], deflt_rhs)]
1552 | debugIsOn, isAlgTyCon tycon, not (isOpenTyCon tycon), null (tyConDataCons tycon)
1553 -- Check for no data constructors
1554 -- This can legitimately happen for type families, so don't report that
1555 = pprTrace "prepareDefault" (ppr case_bndr <+> ppr tycon)
1556 $ return [(DEFAULT, [], deflt_rhs)]
1558 --------- Catch-all cases -----------
1559 prepareDefault _case_bndr _bndr_ty _imposs_cons (Just deflt_rhs)
1560 = return [(DEFAULT, [], deflt_rhs)]
1562 prepareDefault _case_bndr _bndr_ty _imposs_cons Nothing
1563 = return [] -- No default branch
1568 %************************************************************************
1572 %************************************************************************
1574 mkCase tries these things
1576 1. Merge Nested Cases
1578 case e of b { ==> case e of b {
1579 p1 -> rhs1 p1 -> rhs1
1581 pm -> rhsm pm -> rhsm
1582 _ -> case b of b' { pn -> let b'=b in rhsn
1584 ... po -> let b'=b in rhso
1585 po -> rhso _ -> let b'=b in rhsd
1589 which merges two cases in one case when -- the default alternative of
1590 the outer case scrutises the same variable as the outer case. This
1591 transformation is called Case Merging. It avoids that the same
1592 variable is scrutinised multiple times.
1594 2. Eliminate Identity Case
1600 and similar friends.
1602 3. Merge identical alternatives.
1603 If several alternatives are identical, merge them into
1604 a single DEFAULT alternative. I've occasionally seen this
1605 making a big difference:
1607 case e of =====> case e of
1608 C _ -> f x D v -> ....v....
1609 D v -> ....v.... DEFAULT -> f x
1612 The point is that we merge common RHSs, at least for the DEFAULT case.
1613 [One could do something more elaborate but I've never seen it needed.]
1614 To avoid an expensive test, we just merge branches equal to the *first*
1615 alternative; this picks up the common cases
1616 a) all branches equal
1617 b) some branches equal to the DEFAULT (which occurs first)
1619 The case where Merge Identical Alternatives transformation showed up
1620 was like this (base/Foreign/C/Err/Error.lhs):
1626 where @is@ was something like
1628 p `is` n = p /= (-1) && p == n
1630 This gave rise to a horrible sequence of cases
1637 and similarly in cascade for all the join points!
1641 mkCase, mkCase1, mkCase2
1644 -> [OutAlt] -- Alternatives in standard (increasing) order
1647 --------------------------------------------------
1648 -- 1. Merge Nested Cases
1649 --------------------------------------------------
1651 mkCase dflags scrut outer_bndr ((DEFAULT, _, deflt_rhs) : outer_alts)
1652 | dopt Opt_CaseMerge dflags
1653 , Case (Var inner_scrut_var) inner_bndr _ inner_alts <- deflt_rhs
1654 , inner_scrut_var == outer_bndr
1655 = do { tick (CaseMerge outer_bndr)
1657 ; let wrap_alt (con, args, rhs) = ASSERT( outer_bndr `notElem` args )
1658 (con, args, wrap_rhs rhs)
1659 -- Simplifier's no-shadowing invariant should ensure
1660 -- that outer_bndr is not shadowed by the inner patterns
1661 wrap_rhs rhs = Let (NonRec inner_bndr (Var outer_bndr)) rhs
1662 -- The let is OK even for unboxed binders,
1664 wrapped_alts | isDeadBinder inner_bndr = inner_alts
1665 | otherwise = map wrap_alt inner_alts
1667 merged_alts = mergeAlts outer_alts wrapped_alts
1668 -- NB: mergeAlts gives priority to the left
1671 -- DEFAULT -> case x of
1674 -- When we merge, we must ensure that e1 takes
1675 -- precedence over e2 as the value for A!
1677 ; mkCase1 dflags scrut outer_bndr merged_alts
1679 -- Warning: don't call mkCase recursively!
1680 -- Firstly, there's no point, because inner alts have already had
1681 -- mkCase applied to them, so they won't have a case in their default
1682 -- Secondly, if you do, you get an infinite loop, because the bindCaseBndr
1683 -- in munge_rhs may put a case into the DEFAULT branch!
1685 mkCase dflags scrut bndr alts = mkCase1 dflags scrut bndr alts
1687 --------------------------------------------------
1688 -- 2. Eliminate Identity Case
1689 --------------------------------------------------
1691 mkCase1 _dflags scrut case_bndr alts -- Identity case
1692 | all identity_alt alts
1693 = do { tick (CaseIdentity case_bndr)
1694 ; return (re_cast scrut) }
1696 identity_alt (con, args, rhs) = check_eq con args (de_cast rhs)
1698 check_eq DEFAULT _ (Var v) = v == case_bndr
1699 check_eq (LitAlt lit') _ (Lit lit) = lit == lit'
1700 check_eq (DataAlt con) args rhs = rhs `cheapEqExpr` mkConApp con (arg_tys ++ varsToCoreExprs args)
1701 || rhs `cheapEqExpr` Var case_bndr
1702 check_eq _ _ _ = False
1704 arg_tys = map Type (tyConAppArgs (idType case_bndr))
1707 -- case e of x { _ -> x `cast` c }
1708 -- And we definitely want to eliminate this case, to give
1710 -- So we throw away the cast from the RHS, and reconstruct
1711 -- it at the other end. All the RHS casts must be the same
1712 -- if (all identity_alt alts) holds.
1714 -- Don't worry about nested casts, because the simplifier combines them
1715 de_cast (Cast e _) = e
1718 re_cast scrut = case head alts of
1719 (_,_,Cast _ co) -> Cast scrut co
1722 --------------------------------------------------
1723 -- 3. Merge Identical Alternatives
1724 --------------------------------------------------
1725 mkCase1 dflags scrut case_bndr ((_con1,bndrs1,rhs1) : con_alts)
1726 | all isDeadBinder bndrs1 -- Remember the default
1727 , length filtered_alts < length con_alts -- alternative comes first
1728 -- Also Note [Dead binders]
1729 = do { tick (AltMerge case_bndr)
1730 ; mkCase2 dflags scrut case_bndr alts' }
1732 alts' = (DEFAULT, [], rhs1) : filtered_alts
1733 filtered_alts = filter keep con_alts
1734 keep (_con,bndrs,rhs) = not (all isDeadBinder bndrs && rhs `cheapEqExpr` rhs1)
1736 mkCase1 dflags scrut bndr alts = mkCase2 dflags scrut bndr alts
1738 --------------------------------------------------
1740 --------------------------------------------------
1741 mkCase2 _dflags scrut bndr alts
1742 = return (Case scrut bndr (coreAltsType alts) alts)
1746 ~~~~~~~~~~~~~~~~~~~~
1747 Note that dead-ness is maintained by the simplifier, so that it is
1748 accurate after simplification as well as before.
1751 Note [Cascading case merge]
1752 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1753 Case merging should cascade in one sweep, because it
1757 DEFAULT -> case a of b
1758 DEFAULT -> case b of c {
1765 DEFAULT -> case a of b
1766 DEFAULT -> let c = b in e
1767 A -> let c = b in ea
1772 DEFAULT -> let b = a in let c = b in e
1773 A -> let b = a in let c = b in ea
1774 B -> let b = a in eb
1778 However here's a tricky case that we still don't catch, and I don't
1779 see how to catch it in one pass:
1781 case x of c1 { I# a1 ->
1784 DEFAULT -> case x of c3 { I# a2 ->
1787 After occurrence analysis (and its binder-swap) we get this
1789 case x of c1 { I# a1 ->
1790 let x = c1 in -- Binder-swap addition
1793 DEFAULT -> case x of c3 { I# a2 ->
1796 When we simplify the inner case x, we'll see that
1797 x=c1=I# a1. So we'll bind a2 to a1, and get
1799 case x of c1 { I# a1 ->
1802 DEFAULT -> case a1 of ...
1804 This is corect, but we can't do a case merge in this sweep
1805 because c2 /= a1. Reason: the binding c1=I# a1 went inwards
1806 without getting changed to c1=I# c2.
1808 I don't think this is worth fixing, even if I knew how. It'll
1809 all come out in the next pass anyway.