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, mkUnfolding, mkCompulsoryUnfolding, seqUnfolding,
22 evaldUnfolding, mkOtherCon, otherCons,
23 unfoldingTemplate, maybeUnfoldingTemplate,
24 isEvaldUnfolding, isValueUnfolding, isCheapUnfolding, isCompulsoryUnfolding,
25 hasUnfolding, hasSomeUnfolding, neverUnfold,
27 couldBeSmallEnoughToInline,
28 certainlyWillInline, smallEnoughToInline,
33 #include "HsVersions.h"
38 import PprCore () -- Instances
52 import GHC.Exts ( Int# )
56 %************************************************************************
58 \subsection{Making unfoldings}
60 %************************************************************************
63 mkTopUnfolding expr = mkUnfolding True {- Top level -} expr
65 mkUnfolding top_lvl expr
66 = CoreUnfolding (occurAnalyseExpr expr)
73 -- OK to inline inside a lambda
75 (calcUnfoldingGuidance opt_UF_CreationThreshold expr)
76 -- Sometimes during simplification, there's a large let-bound thing
77 -- which has been substituted, and so is now dead; so 'expr' contains
78 -- two copies of the thing while the occurrence-analysed expression doesn't
79 -- Nevertheless, we don't occ-analyse before computing the size because the
80 -- size computation bales out after a while, whereas occurrence analysis does not.
82 -- This can occasionally mean that the guidance is very pessimistic;
83 -- it gets fixed up next round
85 instance Outputable Unfolding where
86 ppr NoUnfolding = ptext SLIT("No unfolding")
87 ppr (OtherCon cs) = ptext SLIT("OtherCon") <+> ppr cs
88 ppr (CompulsoryUnfolding e) = ptext SLIT("Compulsory") <+> ppr e
89 ppr (CoreUnfolding e top hnf cheap g)
90 = ptext SLIT("Unf") <+> sep [ppr top <+> ppr hnf <+> ppr cheap <+> ppr g,
93 mkCompulsoryUnfolding expr -- Used for things that absolutely must be unfolded
94 = CompulsoryUnfolding (occurAnalyseExpr expr)
98 %************************************************************************
100 \subsection{The UnfoldingGuidance type}
102 %************************************************************************
105 instance Outputable UnfoldingGuidance where
106 ppr UnfoldNever = ptext SLIT("NEVER")
107 ppr (UnfoldIfGoodArgs v cs size discount)
108 = hsep [ ptext SLIT("IF_ARGS"), int v,
109 brackets (hsep (map int cs)),
116 calcUnfoldingGuidance
117 :: Int -- bomb out if size gets bigger than this
118 -> CoreExpr -- expression to look at
120 calcUnfoldingGuidance bOMB_OUT_SIZE expr
121 = case collect_val_bndrs expr of { (inline, val_binders, body) ->
123 n_val_binders = length val_binders
125 max_inline_size = n_val_binders+2
126 -- The idea is that if there is an INLINE pragma (inline is True)
127 -- and there's a big body, we give a size of n_val_binders+2. This
128 -- This is just enough to fail the no-size-increase test in callSiteInline,
129 -- so that INLINE things don't get inlined into entirely boring contexts,
133 case (sizeExpr (iUnbox bOMB_OUT_SIZE) val_binders body) of
136 | not inline -> UnfoldNever
137 -- A big function with an INLINE pragma must
138 -- have an UnfoldIfGoodArgs guidance
139 | otherwise -> UnfoldIfGoodArgs n_val_binders
140 (map (const 0) val_binders)
143 SizeIs size cased_args scrut_discount
146 (map discount_for val_binders)
148 (iBox scrut_discount)
150 boxed_size = iBox size
152 final_size | inline = boxed_size `min` max_inline_size
153 | otherwise = boxed_size
155 -- Sometimes an INLINE thing is smaller than n_val_binders+2.
156 -- A particular case in point is a constructor, which has size 1.
157 -- We want to inline this regardless, hence the `min`
159 discount_for b = foldlBag (\acc (b',n) -> if b==b' then acc+n else acc)
163 collect_val_bndrs e = go False [] e
164 -- We need to be a bit careful about how we collect the
165 -- value binders. In ptic, if we see
166 -- __inline_me (\x y -> e)
167 -- We want to say "2 value binders". Why? So that
168 -- we take account of information given for the arguments
170 go inline rev_vbs (Note InlineMe e) = go True rev_vbs e
171 go inline rev_vbs (Lam b e) | isId b = go inline (b:rev_vbs) e
172 | otherwise = go inline rev_vbs e
173 go inline rev_vbs e = (inline, reverse rev_vbs, e)
177 sizeExpr :: Int# -- Bomb out if it gets bigger than this
178 -> [Id] -- Arguments; we're interested in which of these
183 sizeExpr bOMB_OUT_SIZE top_args expr
186 size_up (Type t) = sizeZero -- Types cost nothing
187 size_up (Var v) = sizeOne
189 size_up (Note InlineMe body) = sizeOne -- Inline notes make it look very small
190 -- This can be important. If you have an instance decl like this:
191 -- instance Foo a => Foo [a] where
192 -- {-# INLINE op1, op2 #-}
195 -- then we'll get a dfun which is a pair of two INLINE lambdas
197 size_up (Note _ body) = size_up body -- Other notes cost nothing
199 size_up (Cast e _) = size_up e
201 size_up (App fun (Type t)) = size_up fun
202 size_up (App fun arg) = size_up_app fun [arg]
204 size_up (Lit lit) = sizeN (litSize lit)
206 size_up (Lam b e) | isId b = lamScrutDiscount (size_up e `addSizeN` 1)
207 | otherwise = size_up e
209 size_up (Let (NonRec binder rhs) body)
210 = nukeScrutDiscount (size_up rhs) `addSize`
211 size_up body `addSizeN`
212 (if isUnLiftedType (idType binder) then 0 else 1)
213 -- For the allocation
214 -- If the binder has an unlifted type there is no allocation
216 size_up (Let (Rec pairs) body)
217 = nukeScrutDiscount rhs_size `addSize`
218 size_up body `addSizeN`
219 length pairs -- For the allocation
221 rhs_size = foldr (addSize . size_up . snd) sizeZero pairs
223 size_up (Case (Var v) _ _ alts)
224 | v `elem` top_args -- We are scrutinising an argument variable
226 {- I'm nuking this special case; BUT see the comment with case alternatives.
228 (a) It's too eager. We don't want to inline a wrapper into a
229 context with no benefit.
230 E.g. \ x. f (x+x) no point in inlining (+) here!
232 (b) It's ineffective. Once g's wrapper is inlined, its case-expressions
233 aren't scrutinising arguments any more
237 [alt] -> size_up_alt alt `addSize` SizeIs 0# (unitBag (v, 1)) 0#
238 -- We want to make wrapper-style evaluation look cheap, so that
239 -- when we inline a wrapper it doesn't make call site (much) bigger
240 -- Otherwise we get nasty phase ordering stuff:
243 -- If we inline g's wrapper, f looks big, and doesn't get inlined
244 -- into h; if we inline f first, while it looks small, then g's
245 -- wrapper will get inlined later anyway. To avoid this nasty
246 -- ordering difference, we make (case a of (x,y) -> ...),
247 -- *where a is one of the arguments* look free.
251 alts_size (foldr addSize sizeOne alt_sizes) -- The 1 is for the scrutinee
252 (foldr1 maxSize alt_sizes)
254 -- Good to inline if an arg is scrutinised, because
255 -- that may eliminate allocation in the caller
256 -- And it eliminates the case itself
259 alt_sizes = map size_up_alt alts
261 -- alts_size tries to compute a good discount for
262 -- the case when we are scrutinising an argument variable
263 alts_size (SizeIs tot tot_disc tot_scrut) -- Size of all alternatives
264 (SizeIs max max_disc max_scrut) -- Size of biggest alternative
265 = SizeIs tot (unitBag (v, iBox (_ILIT 1 +# tot -# max)) `unionBags` max_disc) max_scrut
266 -- If the variable is known, we produce a discount that
267 -- will take us back to 'max', the size of rh largest alternative
268 -- The 1+ is a little discount for reduced allocation in the caller
269 alts_size tot_size _ = tot_size
271 size_up (Case e _ _ alts) = nukeScrutDiscount (size_up e) `addSize`
272 foldr (addSize . size_up_alt) sizeZero alts
273 -- We don't charge for the case itself
274 -- It's a strict thing, and the price of the call
275 -- is paid by scrut. Also consider
276 -- case f x of DEFAULT -> e
277 -- This is just ';'! Don't charge for it.
280 size_up_app (App fun arg) args
281 | isTypeArg arg = size_up_app fun args
282 | otherwise = size_up_app fun (arg:args)
283 size_up_app fun args = foldr (addSize . nukeScrutDiscount . size_up)
284 (size_up_fun fun args)
287 -- A function application with at least one value argument
288 -- so if the function is an argument give it an arg-discount
290 -- Also behave specially if the function is a build
292 -- Also if the function is a constant Id (constr or primop)
293 -- compute discounts specially
294 size_up_fun (Var fun) args
295 | fun `hasKey` buildIdKey = buildSize
296 | fun `hasKey` augmentIdKey = augmentSize
298 = case globalIdDetails fun of
299 DataConWorkId dc -> conSizeN dc (valArgCount args)
301 FCallId fc -> sizeN opt_UF_DearOp
302 PrimOpId op -> primOpSize op (valArgCount args)
303 -- foldr addSize (primOpSize op) (map arg_discount args)
304 -- At one time I tried giving an arg-discount if a primop
305 -- is applied to one of the function's arguments, but it's
306 -- not good. At the moment, any unlifted-type arg gets a
307 -- 'True' for 'yes I'm evald', so we collect the discount even
308 -- if we know nothing about it. And just having it in a primop
309 -- doesn't help at all if we don't know something more.
311 other -> fun_discount fun `addSizeN`
312 (1 + length (filter (not . exprIsTrivial) args))
313 -- The 1+ is for the function itself
314 -- Add 1 for each non-trivial arg;
315 -- the allocation cost, as in let(rec)
316 -- Slight hack here: for constructors the args are almost always
317 -- trivial; and for primops they are almost always prim typed
318 -- We should really only count for non-prim-typed args in the
319 -- general case, but that seems too much like hard work
321 size_up_fun other args = size_up other
324 size_up_alt (con, bndrs, rhs) = size_up rhs
325 -- Don't charge for args, so that wrappers look cheap
326 -- (See comments about wrappers with Case)
329 -- We want to record if we're case'ing, or applying, an argument
330 fun_discount v | v `elem` top_args = SizeIs 0# (unitBag (v, opt_UF_FunAppDiscount)) 0#
331 fun_discount other = sizeZero
334 -- These addSize things have to be here because
335 -- I don't want to give them bOMB_OUT_SIZE as an argument
337 addSizeN TooBig _ = TooBig
338 addSizeN (SizeIs n xs d) m = mkSizeIs bOMB_OUT_SIZE (n +# iUnbox m) xs d
340 addSize TooBig _ = TooBig
341 addSize _ TooBig = TooBig
342 addSize (SizeIs n1 xs d1) (SizeIs n2 ys d2)
343 = mkSizeIs bOMB_OUT_SIZE (n1 +# n2) (xs `unionBags` ys) (d1 +# d2)
346 Code for manipulating sizes
349 data ExprSize = TooBig
350 | SizeIs FastInt -- Size found
351 (Bag (Id,Int)) -- Arguments cased herein, and discount for each such
352 FastInt -- Size to subtract if result is scrutinised
353 -- by a case expression
355 -- subtract the discount before deciding whether to bale out. eg. we
356 -- want to inline a large constructor application into a selector:
357 -- tup = (a_1, ..., a_99)
358 -- x = case tup of ...
360 mkSizeIs max n xs d | (n -# d) ># max = TooBig
361 | otherwise = SizeIs n xs d
363 maxSize TooBig _ = TooBig
364 maxSize _ TooBig = TooBig
365 maxSize s1@(SizeIs n1 _ _) s2@(SizeIs n2 _ _) | n1 ># n2 = s1
368 sizeZero = SizeIs (_ILIT 0) emptyBag (_ILIT 0)
369 sizeOne = SizeIs (_ILIT 1) emptyBag (_ILIT 0)
370 sizeN n = SizeIs (iUnbox n) emptyBag (_ILIT 0)
372 | isUnboxedTupleCon dc = SizeIs (_ILIT 0) emptyBag (iUnbox n +# _ILIT 1)
373 | otherwise = SizeIs (_ILIT 1) emptyBag (iUnbox n +# _ILIT 1)
374 -- Treat constructors as size 1; we are keen to expose them
375 -- (and we charge separately for their args). We can't treat
376 -- them as size zero, else we find that (iBox x) has size 1,
377 -- which is the same as a lone variable; and hence 'v' will
378 -- always be replaced by (iBox x), where v is bound to iBox x.
380 -- However, unboxed tuples count as size zero
381 -- I found occasions where we had
382 -- f x y z = case op# x y z of { s -> (# s, () #) }
383 -- and f wasn't getting inlined
386 | not (primOpIsDupable op) = sizeN opt_UF_DearOp
387 | not (primOpOutOfLine op) = sizeN (2 - n_args)
388 -- Be very keen to inline simple primops.
389 -- We give a discount of 1 for each arg so that (op# x y z) costs 2.
390 -- We can't make it cost 1, else we'll inline let v = (op# x y z)
391 -- at every use of v, which is excessive.
393 -- A good example is:
394 -- let x = +# p q in C {x}
395 -- Even though x get's an occurrence of 'many', its RHS looks cheap,
396 -- and there's a good chance it'll get inlined back into C's RHS. Urgh!
397 | otherwise = sizeOne
399 buildSize = SizeIs (-2#) emptyBag 4#
400 -- We really want to inline applications of build
401 -- build t (\cn -> e) should cost only the cost of e (because build will be inlined later)
402 -- Indeed, we should add a result_discount becuause build is
403 -- very like a constructor. We don't bother to check that the
404 -- build is saturated (it usually is). The "-2" discounts for the \c n,
405 -- The "4" is rather arbitrary.
407 augmentSize = SizeIs (-2#) emptyBag 4#
408 -- Ditto (augment t (\cn -> e) ys) should cost only the cost of
409 -- e plus ys. The -2 accounts for the \cn
411 nukeScrutDiscount (SizeIs n vs d) = SizeIs n vs 0#
412 nukeScrutDiscount TooBig = TooBig
414 -- When we return a lambda, give a discount if it's used (applied)
415 lamScrutDiscount (SizeIs n vs d) = case opt_UF_FunAppDiscount of { d -> SizeIs n vs (iUnbox d) }
416 lamScrutDiscount TooBig = TooBig
420 %************************************************************************
422 \subsection[considerUnfolding]{Given all the info, do (not) do the unfolding}
424 %************************************************************************
426 We have very limited information about an unfolding expression: (1)~so
427 many type arguments and so many value arguments expected---for our
428 purposes here, we assume we've got those. (2)~A ``size'' or ``cost,''
429 a single integer. (3)~An ``argument info'' vector. For this, what we
430 have at the moment is a Boolean per argument position that says, ``I
431 will look with great favour on an explicit constructor in this
432 position.'' (4)~The ``discount'' to subtract if the expression
433 is being scrutinised.
435 Assuming we have enough type- and value arguments (if not, we give up
436 immediately), then we see if the ``discounted size'' is below some
437 (semi-arbitrary) threshold. It works like this: for every argument
438 position where we're looking for a constructor AND WE HAVE ONE in our
439 hands, we get a (again, semi-arbitrary) discount [proportion to the
440 number of constructors in the type being scrutinized].
442 If we're in the context of a scrutinee ( \tr{(case <expr > of A .. -> ...;.. )})
443 and the expression in question will evaluate to a constructor, we use
444 the computed discount size *for the result only* rather than
445 computing the argument discounts. Since we know the result of
446 the expression is going to be taken apart, discounting its size
447 is more accurate (see @sizeExpr@ above for how this discount size
450 We use this one to avoid exporting inlinings that we ``couldn't possibly
451 use'' on the other side. Can be overridden w/ flaggery.
452 Just the same as smallEnoughToInline, except that it has no actual arguments.
455 couldBeSmallEnoughToInline :: Int -> CoreExpr -> Bool
456 couldBeSmallEnoughToInline threshold rhs = case calcUnfoldingGuidance threshold rhs of
460 certainlyWillInline :: Unfolding -> Bool
461 -- Sees if the unfolding is pretty certain to inline
462 certainlyWillInline (CoreUnfolding _ _ _ is_cheap (UnfoldIfGoodArgs n_vals _ size _))
463 = is_cheap && size - (n_vals +1) <= opt_UF_UseThreshold
464 certainlyWillInline other
467 smallEnoughToInline :: Unfolding -> Bool
468 smallEnoughToInline (CoreUnfolding _ _ _ _ (UnfoldIfGoodArgs _ _ size _))
469 = size <= opt_UF_UseThreshold
470 smallEnoughToInline other
474 %************************************************************************
476 \subsection{callSiteInline}
478 %************************************************************************
480 This is the key function. It decides whether to inline a variable at a call site
482 callSiteInline is used at call sites, so it is a bit more generous.
483 It's a very important function that embodies lots of heuristics.
484 A non-WHNF can be inlined if it doesn't occur inside a lambda,
485 and occurs exactly once or
486 occurs once in each branch of a case and is small
488 If the thing is in WHNF, there's no danger of duplicating work,
489 so we can inline if it occurs once, or is small
491 NOTE: we don't want to inline top-level functions that always diverge.
492 It just makes the code bigger. Tt turns out that the convenient way to prevent
493 them inlining is to give them a NOINLINE pragma, which we do in
494 StrictAnal.addStrictnessInfoToTopId
497 callSiteInline :: DynFlags
498 -> Bool -- True <=> the Id can be inlined
500 -> [Bool] -- One for each value arg; True if it is interesting
501 -> Bool -- True <=> continuation is interesting
502 -> Maybe CoreExpr -- Unfolding, if any
505 callSiteInline dflags active_inline id arg_infos interesting_cont
506 = case idUnfolding id of {
507 NoUnfolding -> Nothing ;
508 OtherCon cs -> Nothing ;
510 CompulsoryUnfolding unf_template -> Just unf_template ;
511 -- CompulsoryUnfolding => there is no top-level binding
512 -- for these things, so we must inline it.
513 -- Only a couple of primop-like things have
514 -- compulsory unfoldings (see MkId.lhs).
515 -- We don't allow them to be inactive
517 CoreUnfolding unf_template is_top is_value is_cheap guidance ->
520 result | yes_or_no = Just unf_template
521 | otherwise = Nothing
523 n_val_args = length arg_infos
526 | not active_inline = False
527 | otherwise = is_cheap && consider_safe False
528 -- We consider even the once-in-one-branch
529 -- occurrences, because they won't all have been
530 -- caught by preInlineUnconditionally. In particular,
531 -- if the occurrence is once inside a lambda, and the
532 -- rhs is cheap but not a manifest lambda, then
533 -- pre-inline will not have inlined it for fear of
534 -- invalidating the occurrence info in the rhs.
537 -- consider_safe decides whether it's a good idea to
538 -- inline something, given that there's no
539 -- work-duplication issue (the caller checks that).
542 UnfoldIfGoodArgs n_vals_wanted arg_discounts size res_discount
544 | enough_args && size <= (n_vals_wanted + 1)
545 -- Inline unconditionally if there no size increase
546 -- Size of call is n_vals_wanted (+1 for the function)
550 -> some_benefit && small_enough
553 some_benefit = or arg_infos || really_interesting_cont ||
554 (not is_top && ({- once || -} (n_vals_wanted > 0 && enough_args)))
555 -- [was (once && not in_lam)]
556 -- If it occurs more than once, there must be
557 -- something interesting about some argument, or the
558 -- result context, to make it worth inlining
560 -- If a function has a nested defn we also record
561 -- some-benefit, on the grounds that we are often able
562 -- to eliminate the binding, and hence the allocation,
563 -- for the function altogether; this is good for join
564 -- points. But this only makes sense for *functions*;
565 -- inlining a constructor doesn't help allocation
566 -- unless the result is scrutinised. UNLESS the
567 -- constructor occurs just once, albeit possibly in
568 -- multiple case branches. Then inlining it doesn't
569 -- increase allocation, but it does increase the
570 -- chance that the constructor won't be allocated at
571 -- all in the branches that don't use it.
573 enough_args = n_val_args >= n_vals_wanted
574 really_interesting_cont | n_val_args < n_vals_wanted = False -- Too few args
575 | n_val_args == n_vals_wanted = interesting_cont
576 | otherwise = True -- Extra args
577 -- really_interesting_cont tells if the result of the
578 -- call is in an interesting context.
580 small_enough = (size - discount) <= opt_UF_UseThreshold
581 discount = computeDiscount n_vals_wanted arg_discounts res_discount
582 arg_infos really_interesting_cont
585 if dopt Opt_D_dump_inlinings dflags then
586 pprTrace "Considering inlining"
587 (ppr id <+> vcat [text "active:" <+> ppr active_inline,
588 text "arg infos" <+> ppr arg_infos,
589 text "interesting continuation" <+> ppr interesting_cont,
590 text "is value:" <+> ppr is_value,
591 text "is cheap:" <+> ppr is_cheap,
592 text "guidance" <+> ppr guidance,
593 text "ANSWER =" <+> if yes_or_no then text "YES" else text "NO"])
599 computeDiscount :: Int -> [Int] -> Int -> [Bool] -> Bool -> Int
600 computeDiscount n_vals_wanted arg_discounts res_discount arg_infos result_used
601 -- We multiple the raw discounts (args_discount and result_discount)
602 -- ty opt_UnfoldingKeenessFactor because the former have to do with
603 -- *size* whereas the discounts imply that there's some extra
604 -- *efficiency* to be gained (e.g. beta reductions, case reductions)
607 -- we also discount 1 for each argument passed, because these will
608 -- reduce with the lambdas in the function (we count 1 for a lambda
610 = 1 + -- Discount of 1 because the result replaces the call
611 -- so we count 1 for the function itself
612 length (take n_vals_wanted arg_infos) +
613 -- Discount of 1 for each arg supplied, because the
614 -- result replaces the call
615 round (opt_UF_KeenessFactor *
616 fromIntegral (arg_discount + result_discount))
618 arg_discount = sum (zipWith mk_arg_discount arg_discounts arg_infos)
620 mk_arg_discount discount is_evald | is_evald = discount
623 -- Don't give a result discount unless there are enough args
624 result_discount | result_used = res_discount -- Over-applied, or case scrut