2 % (c) The University of Glasgow 2006
3 % (c) The AQUA Project, Glasgow University, 1994-1998
8 Unfoldings (which can travel across module boundaries) are in Core
9 syntax (namely @CoreExpr@s).
11 The type @Unfolding@ sits ``above'' simply-Core-expressions
12 unfoldings, capturing ``higher-level'' things we know about a binding,
13 usually things that the simplifier found out (e.g., ``it's a
14 literal''). In the corner of a @CoreUnfolding@ unfolding, you will
15 find, unsurprisingly, a Core expression.
19 Unfolding, UnfoldingGuidance, -- Abstract types
21 noUnfolding, mkTopUnfolding, mkImplicitUnfolding, mkUnfolding,
22 mkCompulsoryUnfolding, seqUnfolding,
23 evaldUnfolding, mkOtherCon, otherCons,
24 unfoldingTemplate, maybeUnfoldingTemplate,
25 isEvaldUnfolding, isValueUnfolding, isExpandableUnfolding, isCompulsoryUnfolding,
26 hasUnfolding, hasSomeUnfolding, neverUnfold,
28 couldBeSmallEnoughToInline,
29 certainlyWillInline, smallEnoughToInline,
31 callSiteInline, CallCtxt(..)
38 import PprCore () -- Instances
40 import CoreSubst ( Subst, emptySubst, substTy, extendIdSubst, extendTvSubst
41 , lookupIdSubst, substBndr, substBndrs, substRecBndrs )
48 import Type hiding( substTy, extendTvSubst )
58 %************************************************************************
60 \subsection{Making unfoldings}
62 %************************************************************************
65 mkTopUnfolding :: CoreExpr -> Unfolding
66 mkTopUnfolding expr = mkUnfolding True {- Top level -} expr
68 mkImplicitUnfolding :: CoreExpr -> Unfolding
69 -- For implicit Ids, do a tiny bit of optimising first
70 mkImplicitUnfolding expr
71 = CoreUnfolding (simpleOptExpr emptySubst expr)
75 (exprIsExpandable expr)
76 (calcUnfoldingGuidance opt_UF_CreationThreshold expr)
78 mkUnfolding :: Bool -> CoreExpr -> Unfolding
79 mkUnfolding top_lvl expr
80 = CoreUnfolding (occurAnalyseExpr expr)
87 -- OK to inline inside a lambda
89 (exprIsExpandable expr)
91 (calcUnfoldingGuidance opt_UF_CreationThreshold expr)
92 -- Sometimes during simplification, there's a large let-bound thing
93 -- which has been substituted, and so is now dead; so 'expr' contains
94 -- two copies of the thing while the occurrence-analysed expression doesn't
95 -- Nevertheless, we don't occ-analyse before computing the size because the
96 -- size computation bales out after a while, whereas occurrence analysis does not.
98 -- This can occasionally mean that the guidance is very pessimistic;
99 -- it gets fixed up next round
101 instance Outputable Unfolding where
102 ppr NoUnfolding = ptext (sLit "No unfolding")
103 ppr (OtherCon cs) = ptext (sLit "OtherCon") <+> ppr cs
104 ppr (CompulsoryUnfolding e) = ptext (sLit "Compulsory") <+> ppr e
105 ppr (CoreUnfolding e top hnf cheap expable g)
106 = ptext (sLit "Unf") <+> sep [ppr top <+> ppr hnf <+> ppr cheap <+> ppr expable <+> ppr g,
109 mkCompulsoryUnfolding :: CoreExpr -> Unfolding
110 mkCompulsoryUnfolding expr -- Used for things that absolutely must be unfolded
111 = CompulsoryUnfolding (occurAnalyseExpr expr)
115 %************************************************************************
117 \subsection{The UnfoldingGuidance type}
119 %************************************************************************
122 instance Outputable UnfoldingGuidance where
123 ppr UnfoldNever = ptext (sLit "NEVER")
124 ppr (UnfoldIfGoodArgs v cs size discount)
125 = hsep [ ptext (sLit "IF_ARGS"), int v,
126 brackets (hsep (map int cs)),
133 calcUnfoldingGuidance
134 :: Int -- bomb out if size gets bigger than this
135 -> CoreExpr -- expression to look at
137 calcUnfoldingGuidance bOMB_OUT_SIZE expr
138 = case collect_val_bndrs expr of { (inline, val_binders, body) ->
140 n_val_binders = length val_binders
142 max_inline_size = n_val_binders+2
143 -- The idea is that if there is an INLINE pragma (inline is True)
144 -- and there's a big body, we give a size of n_val_binders+2. This
145 -- This is just enough to fail the no-size-increase test in callSiteInline,
146 -- so that INLINE things don't get inlined into entirely boring contexts,
150 case (sizeExpr (iUnbox bOMB_OUT_SIZE) val_binders body) of
153 | not inline -> UnfoldNever
154 -- A big function with an INLINE pragma must
155 -- have an UnfoldIfGoodArgs guidance
156 | otherwise -> UnfoldIfGoodArgs n_val_binders
157 (map (const 0) val_binders)
160 SizeIs size cased_args scrut_discount
163 (map discount_for val_binders)
165 (iBox scrut_discount)
167 boxed_size = iBox size
169 final_size | inline = boxed_size `min` max_inline_size
170 | otherwise = boxed_size
172 -- Sometimes an INLINE thing is smaller than n_val_binders+2.
173 -- A particular case in point is a constructor, which has size 1.
174 -- We want to inline this regardless, hence the `min`
176 discount_for b = foldlBag (\acc (b',n) -> if b==b' then acc+n else acc)
180 collect_val_bndrs e = go False [] e
181 -- We need to be a bit careful about how we collect the
182 -- value binders. In ptic, if we see
183 -- __inline_me (\x y -> e)
184 -- We want to say "2 value binders". Why? So that
185 -- we take account of information given for the arguments
187 go _ rev_vbs (Note InlineMe e) = go True rev_vbs e
188 go inline rev_vbs (Lam b e) | isId b = go inline (b:rev_vbs) e
189 | otherwise = go inline rev_vbs e
190 go inline rev_vbs e = (inline, reverse rev_vbs, e)
194 sizeExpr :: FastInt -- Bomb out if it gets bigger than this
195 -> [Id] -- Arguments; we're interested in which of these
200 sizeExpr bOMB_OUT_SIZE top_args expr
203 size_up (Type _) = sizeZero -- Types cost nothing
204 size_up (Var _) = sizeOne
206 size_up (Note InlineMe _) = sizeOne -- Inline notes make it look very small
207 -- This can be important. If you have an instance decl like this:
208 -- instance Foo a => Foo [a] where
209 -- {-# INLINE op1, op2 #-}
212 -- then we'll get a dfun which is a pair of two INLINE lambdas
214 size_up (Note _ body) = size_up body -- Other notes cost nothing
216 size_up (Cast e _) = size_up e
218 size_up (App fun (Type _)) = size_up fun
219 size_up (App fun arg) = size_up_app fun [arg]
221 size_up (Lit lit) = sizeN (litSize lit)
223 size_up (Lam b e) | isId b = lamScrutDiscount (size_up e `addSizeN` 1)
224 | otherwise = size_up e
226 size_up (Let (NonRec binder rhs) body)
227 = nukeScrutDiscount (size_up rhs) `addSize`
228 size_up body `addSizeN`
229 (if isUnLiftedType (idType binder) then 0 else 1)
230 -- For the allocation
231 -- If the binder has an unlifted type there is no allocation
233 size_up (Let (Rec pairs) body)
234 = nukeScrutDiscount rhs_size `addSize`
235 size_up body `addSizeN`
236 length pairs -- For the allocation
238 rhs_size = foldr (addSize . size_up . snd) sizeZero pairs
240 size_up (Case (Var v) _ _ alts)
241 | v `elem` top_args -- We are scrutinising an argument variable
243 {- I'm nuking this special case; BUT see the comment with case alternatives.
245 (a) It's too eager. We don't want to inline a wrapper into a
246 context with no benefit.
247 E.g. \ x. f (x+x) no point in inlining (+) here!
249 (b) It's ineffective. Once g's wrapper is inlined, its case-expressions
250 aren't scrutinising arguments any more
254 [alt] -> size_up_alt alt `addSize` SizeIs (_ILIT(0)) (unitBag (v, 1)) (_ILIT(0))
255 -- We want to make wrapper-style evaluation look cheap, so that
256 -- when we inline a wrapper it doesn't make call site (much) bigger
257 -- Otherwise we get nasty phase ordering stuff:
260 -- If we inline g's wrapper, f looks big, and doesn't get inlined
261 -- into h; if we inline f first, while it looks small, then g's
262 -- wrapper will get inlined later anyway. To avoid this nasty
263 -- ordering difference, we make (case a of (x,y) -> ...),
264 -- *where a is one of the arguments* look free.
268 alts_size (foldr addSize sizeOne alt_sizes) -- The 1 is for the scrutinee
269 (foldr1 maxSize alt_sizes)
271 -- Good to inline if an arg is scrutinised, because
272 -- that may eliminate allocation in the caller
273 -- And it eliminates the case itself
276 alt_sizes = map size_up_alt alts
278 -- alts_size tries to compute a good discount for
279 -- the case when we are scrutinising an argument variable
280 alts_size (SizeIs tot _tot_disc _tot_scrut) -- Size of all alternatives
281 (SizeIs max max_disc max_scrut) -- Size of biggest alternative
282 = SizeIs tot (unitBag (v, iBox (_ILIT(1) +# tot -# max)) `unionBags` max_disc) max_scrut
283 -- If the variable is known, we produce a discount that
284 -- will take us back to 'max', the size of rh largest alternative
285 -- The 1+ is a little discount for reduced allocation in the caller
286 alts_size tot_size _ = tot_size
288 size_up (Case e _ _ alts) = nukeScrutDiscount (size_up e) `addSize`
289 foldr (addSize . size_up_alt) sizeZero alts
290 -- We don't charge for the case itself
291 -- It's a strict thing, and the price of the call
292 -- is paid by scrut. Also consider
293 -- case f x of DEFAULT -> e
294 -- This is just ';'! Don't charge for it.
297 size_up_app (App fun arg) args
298 | isTypeArg arg = size_up_app fun args
299 | otherwise = size_up_app fun (arg:args)
300 size_up_app fun args = foldr (addSize . nukeScrutDiscount . size_up)
301 (size_up_fun fun args)
304 -- A function application with at least one value argument
305 -- so if the function is an argument give it an arg-discount
307 -- Also behave specially if the function is a build
309 -- Also if the function is a constant Id (constr or primop)
310 -- compute discounts specially
311 size_up_fun (Var fun) args
312 | fun `hasKey` buildIdKey = buildSize
313 | fun `hasKey` augmentIdKey = augmentSize
315 = case idDetails fun of
316 DataConWorkId dc -> conSizeN dc (valArgCount args)
318 FCallId _ -> sizeN opt_UF_DearOp
319 PrimOpId op -> primOpSize op (valArgCount args)
320 -- foldr addSize (primOpSize op) (map arg_discount args)
321 -- At one time I tried giving an arg-discount if a primop
322 -- is applied to one of the function's arguments, but it's
323 -- not good. At the moment, any unlifted-type arg gets a
324 -- 'True' for 'yes I'm evald', so we collect the discount even
325 -- if we know nothing about it. And just having it in a primop
326 -- doesn't help at all if we don't know something more.
328 _ -> fun_discount fun `addSizeN`
329 (1 + length (filter (not . exprIsTrivial) args))
330 -- The 1+ is for the function itself
331 -- Add 1 for each non-trivial arg;
332 -- the allocation cost, as in let(rec)
333 -- Slight hack here: for constructors the args are almost always
334 -- trivial; and for primops they are almost always prim typed
335 -- We should really only count for non-prim-typed args in the
336 -- general case, but that seems too much like hard work
338 size_up_fun other _ = size_up other
341 size_up_alt (_con, _bndrs, rhs) = size_up rhs
342 -- Don't charge for args, so that wrappers look cheap
343 -- (See comments about wrappers with Case)
346 -- We want to record if we're case'ing, or applying, an argument
347 fun_discount v | v `elem` top_args = SizeIs (_ILIT(0)) (unitBag (v, opt_UF_FunAppDiscount)) (_ILIT(0))
348 fun_discount _ = sizeZero
351 -- These addSize things have to be here because
352 -- I don't want to give them bOMB_OUT_SIZE as an argument
354 addSizeN TooBig _ = TooBig
355 addSizeN (SizeIs n xs d) m = mkSizeIs bOMB_OUT_SIZE (n +# iUnbox m) xs d
357 addSize TooBig _ = TooBig
358 addSize _ TooBig = TooBig
359 addSize (SizeIs n1 xs d1) (SizeIs n2 ys d2)
360 = mkSizeIs bOMB_OUT_SIZE (n1 +# n2) (xs `unionBags` ys) (d1 +# d2)
363 Code for manipulating sizes
366 data ExprSize = TooBig
367 | SizeIs FastInt -- Size found
368 (Bag (Id,Int)) -- Arguments cased herein, and discount for each such
369 FastInt -- Size to subtract if result is scrutinised
370 -- by a case expression
372 -- subtract the discount before deciding whether to bale out. eg. we
373 -- want to inline a large constructor application into a selector:
374 -- tup = (a_1, ..., a_99)
375 -- x = case tup of ...
377 mkSizeIs :: FastInt -> FastInt -> Bag (Id, Int) -> FastInt -> ExprSize
378 mkSizeIs max n xs d | (n -# d) ># max = TooBig
379 | otherwise = SizeIs n xs d
381 maxSize :: ExprSize -> ExprSize -> ExprSize
382 maxSize TooBig _ = TooBig
383 maxSize _ TooBig = TooBig
384 maxSize s1@(SizeIs n1 _ _) s2@(SizeIs n2 _ _) | n1 ># n2 = s1
387 sizeZero, sizeOne :: ExprSize
388 sizeN :: Int -> ExprSize
389 conSizeN :: DataCon ->Int -> ExprSize
391 sizeZero = SizeIs (_ILIT(0)) emptyBag (_ILIT(0))
392 sizeOne = SizeIs (_ILIT(1)) emptyBag (_ILIT(0))
393 sizeN n = SizeIs (iUnbox n) emptyBag (_ILIT(0))
395 | isUnboxedTupleCon dc = SizeIs (_ILIT(0)) emptyBag (iUnbox n +# _ILIT(1))
396 | otherwise = SizeIs (_ILIT(1)) emptyBag (iUnbox n +# _ILIT(1))
397 -- Treat constructors as size 1; we are keen to expose them
398 -- (and we charge separately for their args). We can't treat
399 -- them as size zero, else we find that (iBox x) has size 1,
400 -- which is the same as a lone variable; and hence 'v' will
401 -- always be replaced by (iBox x), where v is bound to iBox x.
403 -- However, unboxed tuples count as size zero
404 -- I found occasions where we had
405 -- f x y z = case op# x y z of { s -> (# s, () #) }
406 -- and f wasn't getting inlined
408 primOpSize :: PrimOp -> Int -> ExprSize
410 | not (primOpIsDupable op) = sizeN opt_UF_DearOp
411 | not (primOpOutOfLine op) = sizeN (2 - n_args)
412 -- Be very keen to inline simple primops.
413 -- We give a discount of 1 for each arg so that (op# x y z) costs 2.
414 -- We can't make it cost 1, else we'll inline let v = (op# x y z)
415 -- at every use of v, which is excessive.
417 -- A good example is:
418 -- let x = +# p q in C {x}
419 -- Even though x get's an occurrence of 'many', its RHS looks cheap,
420 -- and there's a good chance it'll get inlined back into C's RHS. Urgh!
421 | otherwise = sizeOne
423 buildSize :: ExprSize
424 buildSize = SizeIs (_ILIT(-2)) emptyBag (_ILIT(4))
425 -- We really want to inline applications of build
426 -- build t (\cn -> e) should cost only the cost of e (because build will be inlined later)
427 -- Indeed, we should add a result_discount becuause build is
428 -- very like a constructor. We don't bother to check that the
429 -- build is saturated (it usually is). The "-2" discounts for the \c n,
430 -- The "4" is rather arbitrary.
432 augmentSize :: ExprSize
433 augmentSize = SizeIs (_ILIT(-2)) emptyBag (_ILIT(4))
434 -- Ditto (augment t (\cn -> e) ys) should cost only the cost of
435 -- e plus ys. The -2 accounts for the \cn
437 nukeScrutDiscount :: ExprSize -> ExprSize
438 nukeScrutDiscount (SizeIs n vs _) = SizeIs n vs (_ILIT(0))
439 nukeScrutDiscount TooBig = TooBig
441 -- When we return a lambda, give a discount if it's used (applied)
442 lamScrutDiscount :: ExprSize -> ExprSize
443 lamScrutDiscount (SizeIs n vs _) = case opt_UF_FunAppDiscount of { d -> SizeIs n vs (iUnbox d) }
444 lamScrutDiscount TooBig = TooBig
448 %************************************************************************
450 \subsection[considerUnfolding]{Given all the info, do (not) do the unfolding}
452 %************************************************************************
454 We have very limited information about an unfolding expression: (1)~so
455 many type arguments and so many value arguments expected---for our
456 purposes here, we assume we've got those. (2)~A ``size'' or ``cost,''
457 a single integer. (3)~An ``argument info'' vector. For this, what we
458 have at the moment is a Boolean per argument position that says, ``I
459 will look with great favour on an explicit constructor in this
460 position.'' (4)~The ``discount'' to subtract if the expression
461 is being scrutinised.
463 Assuming we have enough type- and value arguments (if not, we give up
464 immediately), then we see if the ``discounted size'' is below some
465 (semi-arbitrary) threshold. It works like this: for every argument
466 position where we're looking for a constructor AND WE HAVE ONE in our
467 hands, we get a (again, semi-arbitrary) discount [proportion to the
468 number of constructors in the type being scrutinized].
470 If we're in the context of a scrutinee ( \tr{(case <expr > of A .. -> ...;.. )})
471 and the expression in question will evaluate to a constructor, we use
472 the computed discount size *for the result only* rather than
473 computing the argument discounts. Since we know the result of
474 the expression is going to be taken apart, discounting its size
475 is more accurate (see @sizeExpr@ above for how this discount size
478 We use this one to avoid exporting inlinings that we ``couldn't possibly
479 use'' on the other side. Can be overridden w/ flaggery.
480 Just the same as smallEnoughToInline, except that it has no actual arguments.
483 couldBeSmallEnoughToInline :: Int -> CoreExpr -> Bool
484 couldBeSmallEnoughToInline threshold rhs = case calcUnfoldingGuidance threshold rhs of
488 certainlyWillInline :: Unfolding -> Bool
489 -- Sees if the unfolding is pretty certain to inline
490 certainlyWillInline (CoreUnfolding _ _ _ is_cheap _ (UnfoldIfGoodArgs n_vals _ size _))
491 = is_cheap && size - (n_vals +1) <= opt_UF_UseThreshold
492 certainlyWillInline _
495 smallEnoughToInline :: Unfolding -> Bool
496 smallEnoughToInline (CoreUnfolding _ _ _ _ _ (UnfoldIfGoodArgs _ _ size _))
497 = size <= opt_UF_UseThreshold
498 smallEnoughToInline _
502 %************************************************************************
504 \subsection{callSiteInline}
506 %************************************************************************
508 This is the key function. It decides whether to inline a variable at a call site
510 callSiteInline is used at call sites, so it is a bit more generous.
511 It's a very important function that embodies lots of heuristics.
512 A non-WHNF can be inlined if it doesn't occur inside a lambda,
513 and occurs exactly once or
514 occurs once in each branch of a case and is small
516 If the thing is in WHNF, there's no danger of duplicating work,
517 so we can inline if it occurs once, or is small
519 NOTE: we don't want to inline top-level functions that always diverge.
520 It just makes the code bigger. Tt turns out that the convenient way to prevent
521 them inlining is to give them a NOINLINE pragma, which we do in
522 StrictAnal.addStrictnessInfoToTopId
525 callSiteInline :: DynFlags
526 -> Bool -- True <=> the Id can be inlined
528 -> Bool -- True if there are are no arguments at all (incl type args)
529 -> [Bool] -- One for each value arg; True if it is interesting
530 -> CallCtxt -- True <=> continuation is interesting
531 -> Maybe CoreExpr -- Unfolding, if any
534 data CallCtxt = BoringCtxt
536 | ArgCtxt Bool -- We're somewhere in the RHS of function with rules
537 -- => be keener to inline
538 Int -- We *are* the argument of a function with this arg discount
539 -- => be keener to inline
540 -- INVARIANT: ArgCtxt False 0 ==> BoringCtxt
542 | ValAppCtxt -- We're applied to at least one value arg
543 -- This arises when we have ((f x |> co) y)
544 -- Then the (f x) has argument 'x' but in a ValAppCtxt
546 | CaseCtxt -- We're the scrutinee of a case
547 -- that decomposes its scrutinee
549 instance Outputable CallCtxt where
550 ppr BoringCtxt = ptext (sLit "BoringCtxt")
551 ppr (ArgCtxt _ _) = ptext (sLit "ArgCtxt")
552 ppr CaseCtxt = ptext (sLit "CaseCtxt")
553 ppr ValAppCtxt = ptext (sLit "ValAppCtxt")
555 callSiteInline dflags active_inline id lone_variable arg_infos cont_info
556 = case idUnfolding id of {
557 NoUnfolding -> Nothing ;
558 OtherCon _ -> Nothing ;
560 CompulsoryUnfolding unf_template -> Just unf_template ;
561 -- CompulsoryUnfolding => there is no top-level binding
562 -- for these things, so we must inline it.
563 -- Only a couple of primop-like things have
564 -- compulsory unfoldings (see MkId.lhs).
565 -- We don't allow them to be inactive
567 CoreUnfolding unf_template is_top is_value is_cheap is_expable guidance ->
570 result | yes_or_no = Just unf_template
571 | otherwise = Nothing
573 n_val_args = length arg_infos
575 yes_or_no = active_inline && is_cheap && consider_safe
576 -- We consider even the once-in-one-branch
577 -- occurrences, because they won't all have been
578 -- caught by preInlineUnconditionally. In particular,
579 -- if the occurrence is once inside a lambda, and the
580 -- rhs is cheap but not a manifest lambda, then
581 -- pre-inline will not have inlined it for fear of
582 -- invalidating the occurrence info in the rhs.
585 -- consider_safe decides whether it's a good idea to
586 -- inline something, given that there's no
587 -- work-duplication issue (the caller checks that).
590 UnfoldIfGoodArgs n_vals_wanted arg_discounts size res_discount
591 | enough_args && size <= (n_vals_wanted + 1)
592 -- Inline unconditionally if there no size increase
593 -- Size of call is n_vals_wanted (+1 for the function)
597 -> some_benefit && small_enough && inline_enough_args
600 enough_args = n_val_args >= n_vals_wanted
602 not (dopt Opt_InlineIfEnoughArgs dflags) || enough_args
605 some_benefit = or arg_infos || really_interesting_cont
606 -- There must be something interesting
607 -- about some argument, or the result
608 -- context, to make it worth inlining
610 really_interesting_cont
611 | n_val_args < n_vals_wanted = False -- Too few args
612 | n_val_args == n_vals_wanted = interesting_saturated_call
613 | otherwise = True -- Extra args
614 -- really_interesting_cont tells if the result of the
615 -- call is in an interesting context.
617 interesting_saturated_call
619 BoringCtxt -> not is_top && n_vals_wanted > 0 -- Note [Nested functions]
620 CaseCtxt -> not lone_variable || not is_value -- Note [Lone variables]
621 ArgCtxt {} -> n_vals_wanted > 0 -- Note [Inlining in ArgCtxt]
622 ValAppCtxt -> True -- Note [Cast then apply]
624 small_enough = (size - discount) <= opt_UF_UseThreshold
625 discount = computeDiscount n_vals_wanted arg_discounts
626 res_discount' arg_infos
627 res_discount' = case cont_info of
629 CaseCtxt -> res_discount
630 _other -> 4 `min` res_discount
631 -- res_discount can be very large when a function returns
632 -- construtors; but we only want to invoke that large discount
633 -- when there's a case continuation.
634 -- Otherwise we, rather arbitrarily, threshold it. Yuk.
635 -- But we want to aovid inlining large functions that return
636 -- constructors into contexts that are simply "interesting"
639 if dopt Opt_D_dump_inlinings dflags then
640 pprTrace ("Considering inlining: " ++ showSDoc (ppr id))
641 (vcat [text "active:" <+> ppr active_inline,
642 text "arg infos" <+> ppr arg_infos,
643 text "interesting continuation" <+> ppr cont_info,
644 text "is value:" <+> ppr is_value,
645 text "is cheap:" <+> ppr is_cheap,
646 text "is expandable:" <+> ppr is_expable,
647 text "guidance" <+> ppr guidance,
648 text "ANSWER =" <+> if yes_or_no then text "YES" else text "NO"])
655 Note [Nested functions]
656 ~~~~~~~~~~~~~~~~~~~~~~~
657 If a function has a nested defn we also record some-benefit, on the
658 grounds that we are often able to eliminate the binding, and hence the
659 allocation, for the function altogether; this is good for join points.
660 But this only makes sense for *functions*; inlining a constructor
661 doesn't help allocation unless the result is scrutinised. UNLESS the
662 constructor occurs just once, albeit possibly in multiple case
663 branches. Then inlining it doesn't increase allocation, but it does
664 increase the chance that the constructor won't be allocated at all in
665 the branches that don't use it.
667 Note [Cast then apply]
668 ~~~~~~~~~~~~~~~~~~~~~~
670 myIndex = __inline_me ( (/\a. <blah>) |> co )
671 co :: (forall a. a -> a) ~ (forall a. T a)
672 ... /\a.\x. case ((myIndex a) |> sym co) x of { ... } ...
674 We need to inline myIndex to unravel this; but the actual call (myIndex a) has
675 no value arguments. The ValAppCtxt gives it enough incentive to inline.
677 Note [Inlining in ArgCtxt]
678 ~~~~~~~~~~~~~~~~~~~~~~~~~~
679 The condition (n_vals_wanted > 0) here is very important, because otherwise
680 we end up inlining top-level stuff into useless places; eg
683 This can make a very big difference: it adds 16% to nofib 'integer' allocs,
686 At one stage I replaced this condition by 'True' (leading to the above
687 slow-down). The motivation was test eyeball/inline1.hs; but that seems
690 Note [Lone variables]
691 ~~~~~~~~~~~~~~~~~~~~~
692 The "lone-variable" case is important. I spent ages messing about
693 with unsatisfactory varaints, but this is nice. The idea is that if a
694 variable appears all alone
695 as an arg of lazy fn, or rhs Stop
696 as scrutinee of a case Select
697 as arg of a strict fn ArgOf
699 it is bound to a value
700 then we should not inline it (unless there is some other reason,
701 e.g. is is the sole occurrence). That is what is happening at
702 the use of 'lone_variable' in 'interesting_saturated_call'.
704 Why? At least in the case-scrutinee situation, turning
705 let x = (a,b) in case x of y -> ...
707 let x = (a,b) in case (a,b) of y -> ...
709 let x = (a,b) in let y = (a,b) in ...
710 is bad if the binding for x will remain.
712 Another example: I discovered that strings
713 were getting inlined straight back into applications of 'error'
714 because the latter is strict.
716 f = \x -> ...(error s)...
718 Fundamentally such contexts should not encourage inlining because the
719 context can ``see'' the unfolding of the variable (e.g. case or a
720 RULE) so there's no gain. If the thing is bound to a value.
725 foo = _inline_ (\n. [n])
726 bar = _inline_ (foo 20)
727 baz = \n. case bar of { (m:_) -> m + n }
728 Here we really want to inline 'bar' so that we can inline 'foo'
729 and the whole thing unravels as it should obviously do. This is
730 important: in the NDP project, 'bar' generates a closure data
731 structure rather than a list.
733 * Even a type application or coercion isn't a lone variable.
735 case $fMonadST @ RealWorld of { :DMonad a b c -> c }
736 We had better inline that sucker! The case won't see through it.
738 For now, I'm treating treating a variable applied to types
739 in a *lazy* context "lone". The motivating example was
742 There's no advantage in inlining f here, and perhaps
743 a significant disadvantage. Hence some_val_args in the Stop case
746 computeDiscount :: Int -> [Int] -> Int -> [Bool] -> Int
747 computeDiscount n_vals_wanted arg_discounts result_discount arg_infos
748 -- We multiple the raw discounts (args_discount and result_discount)
749 -- ty opt_UnfoldingKeenessFactor because the former have to do with
750 -- *size* whereas the discounts imply that there's some extra
751 -- *efficiency* to be gained (e.g. beta reductions, case reductions)
754 -- we also discount 1 for each argument passed, because these will
755 -- reduce with the lambdas in the function (we count 1 for a lambda
757 = 1 + -- Discount of 1 because the result replaces the call
758 -- so we count 1 for the function itself
759 length (take n_vals_wanted arg_infos) +
760 -- Discount of 1 for each arg supplied, because the
761 -- result replaces the call
762 round (opt_UF_KeenessFactor *
763 fromIntegral (arg_discount + result_discount))
765 arg_discount = sum (zipWith mk_arg_discount arg_discounts arg_infos)
767 mk_arg_discount discount is_evald | is_evald = discount
771 %************************************************************************
773 The Very Simple Optimiser
775 %************************************************************************
779 simpleOptExpr :: Subst -> CoreExpr -> CoreExpr
780 -- Return an occur-analysed and slightly optimised expression
781 -- The optimisation is very straightforward: just
782 -- inline non-recursive bindings that are used only once,
783 -- or wheere the RHS is trivial
785 simpleOptExpr subst expr
786 = go subst (occurAnalyseExpr expr)
788 go subst (Var v) = lookupIdSubst subst v
789 go subst (App e1 e2) = App (go subst e1) (go subst e2)
790 go subst (Type ty) = Type (substTy subst ty)
791 go _ (Lit lit) = Lit lit
792 go subst (Note note e) = Note note (go subst e)
793 go subst (Cast e co) = Cast (go subst e) (substTy subst co)
794 go subst (Let bind body) = go_bind subst bind body
795 go subst (Lam bndr body) = Lam bndr' (go subst' body)
797 (subst', bndr') = substBndr subst bndr
799 go subst (Case e b ty as) = Case (go subst e) b'
801 (map (go_alt subst') as)
803 (subst', b') = substBndr subst b
806 ----------------------
807 go_alt subst (con, bndrs, rhs) = (con, bndrs', go subst' rhs)
809 (subst', bndrs') = substBndrs subst bndrs
811 ----------------------
812 go_bind subst (Rec prs) body = Let (Rec (bndrs' `zip` rhss'))
815 (bndrs, rhss) = unzip prs
816 (subst', bndrs') = substRecBndrs subst bndrs
817 rhss' = map (go subst') rhss
819 go_bind subst (NonRec b r) body = go_nonrec subst b (go subst r) body
821 ----------------------
822 go_nonrec subst b (Type ty') body
823 | isTyVar b = go (extendTvSubst subst b ty') body
824 -- let a::* = TYPE ty in <body>
825 go_nonrec subst b r' body
826 | isId b -- let x = e in <body>
827 , exprIsTrivial r' || safe_to_inline (idOccInfo b)
828 = go (extendIdSubst subst b r') body
829 go_nonrec subst b r' body
830 = Let (NonRec b' r') (go subst' body)
832 (subst', b') = substBndr subst b
834 ----------------------
835 -- Unconditionally safe to inline
836 safe_to_inline :: OccInfo -> Bool
837 safe_to_inline IAmDead = True
838 safe_to_inline (OneOcc in_lam one_br _) = not in_lam && one_br
839 safe_to_inline (IAmALoopBreaker {}) = False
840 safe_to_inline NoOccInfo = False