Don't import FastString in HsVersions.h
[ghc-hetmet.git] / compiler / coreSyn / CoreUnfold.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The AQUA Project, Glasgow University, 1994-1998
4 %
5
6 Core-syntax unfoldings
7
8 Unfoldings (which can travel across module boundaries) are in Core
9 syntax (namely @CoreExpr@s).
10
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.
16
17 \begin{code}
18 module CoreUnfold (
19         Unfolding, UnfoldingGuidance,   -- Abstract types
20
21         noUnfolding, mkTopUnfolding, mkUnfolding, mkCompulsoryUnfolding, seqUnfolding,
22         evaldUnfolding, mkOtherCon, otherCons,
23         unfoldingTemplate, maybeUnfoldingTemplate,
24         isEvaldUnfolding, isValueUnfolding, isCheapUnfolding, isCompulsoryUnfolding,
25         hasUnfolding, hasSomeUnfolding, neverUnfold,
26
27         couldBeSmallEnoughToInline, 
28         certainlyWillInline, smallEnoughToInline,
29
30         callSiteInline, CallCtxt(..)
31
32     ) where
33
34 #include "HsVersions.h"
35
36 import StaticFlags
37 import DynFlags
38 import CoreSyn
39 import PprCore          ()      -- Instances
40 import OccurAnal
41 import CoreUtils
42 import Id
43 import DataCon
44 import Literal
45 import PrimOp
46 import IdInfo
47 import Type
48 import PrelNames
49 import Bag
50 import FastTypes
51 import FastString
52 import Outputable
53
54 \end{code}
55
56
57 %************************************************************************
58 %*                                                                      *
59 \subsection{Making unfoldings}
60 %*                                                                      *
61 %************************************************************************
62
63 \begin{code}
64 mkTopUnfolding :: CoreExpr -> Unfolding
65 mkTopUnfolding expr = mkUnfolding True {- Top level -} expr
66
67 mkUnfolding :: Bool -> CoreExpr -> Unfolding
68 mkUnfolding top_lvl expr
69   = CoreUnfolding (occurAnalyseExpr expr)
70                   top_lvl
71
72                   (exprIsHNF expr)
73                         -- Already evaluated
74
75                   (exprIsCheap expr)
76                         -- OK to inline inside a lambda
77
78                   (calcUnfoldingGuidance opt_UF_CreationThreshold expr)
79         -- Sometimes during simplification, there's a large let-bound thing     
80         -- which has been substituted, and so is now dead; so 'expr' contains
81         -- two copies of the thing while the occurrence-analysed expression doesn't
82         -- Nevertheless, we don't occ-analyse before computing the size because the
83         -- size computation bales out after a while, whereas occurrence analysis does not.
84         --
85         -- This can occasionally mean that the guidance is very pessimistic;
86         -- it gets fixed up next round
87
88 instance Outputable Unfolding where
89   ppr NoUnfolding = ptext SLIT("No unfolding")
90   ppr (OtherCon cs) = ptext SLIT("OtherCon") <+> ppr cs
91   ppr (CompulsoryUnfolding e) = ptext SLIT("Compulsory") <+> ppr e
92   ppr (CoreUnfolding e top hnf cheap g) 
93         = ptext SLIT("Unf") <+> sep [ppr top <+> ppr hnf <+> ppr cheap <+> ppr g, 
94                                      ppr e]
95
96 mkCompulsoryUnfolding :: CoreExpr -> Unfolding
97 mkCompulsoryUnfolding expr      -- Used for things that absolutely must be unfolded
98   = CompulsoryUnfolding (occurAnalyseExpr expr)
99 \end{code}
100
101
102 %************************************************************************
103 %*                                                                      *
104 \subsection{The UnfoldingGuidance type}
105 %*                                                                      *
106 %************************************************************************
107
108 \begin{code}
109 instance Outputable UnfoldingGuidance where
110     ppr UnfoldNever     = ptext SLIT("NEVER")
111     ppr (UnfoldIfGoodArgs v cs size discount)
112       = hsep [ ptext SLIT("IF_ARGS"), int v,
113                brackets (hsep (map int cs)),
114                int size,
115                int discount ]
116 \end{code}
117
118
119 \begin{code}
120 calcUnfoldingGuidance
121         :: Int                  -- bomb out if size gets bigger than this
122         -> CoreExpr             -- expression to look at
123         -> UnfoldingGuidance
124 calcUnfoldingGuidance bOMB_OUT_SIZE expr
125   = case collect_val_bndrs expr of { (inline, val_binders, body) ->
126     let
127         n_val_binders = length val_binders
128
129         max_inline_size = n_val_binders+2
130         -- The idea is that if there is an INLINE pragma (inline is True)
131         -- and there's a big body, we give a size of n_val_binders+2.  This
132         -- This is just enough to fail the no-size-increase test in callSiteInline,
133         --   so that INLINE things don't get inlined into entirely boring contexts,
134         --   but no more.
135
136     in
137     case (sizeExpr (iUnbox bOMB_OUT_SIZE) val_binders body) of
138
139       TooBig 
140         | not inline -> UnfoldNever
141                 -- A big function with an INLINE pragma must
142                 -- have an UnfoldIfGoodArgs guidance
143         | otherwise  -> UnfoldIfGoodArgs n_val_binders
144                                          (map (const 0) val_binders)
145                                          max_inline_size 0
146
147       SizeIs size cased_args scrut_discount
148         -> UnfoldIfGoodArgs
149                         n_val_binders
150                         (map discount_for val_binders)
151                         final_size
152                         (iBox scrut_discount)
153         where        
154             boxed_size    = iBox size
155
156             final_size | inline     = boxed_size `min` max_inline_size
157                        | otherwise  = boxed_size
158
159                 -- Sometimes an INLINE thing is smaller than n_val_binders+2.
160                 -- A particular case in point is a constructor, which has size 1.
161                 -- We want to inline this regardless, hence the `min`
162
163             discount_for b = foldlBag (\acc (b',n) -> if b==b' then acc+n else acc) 
164                                       0 cased_args
165         }
166   where
167     collect_val_bndrs e = go False [] e
168         -- We need to be a bit careful about how we collect the
169         -- value binders.  In ptic, if we see 
170         --      __inline_me (\x y -> e)
171         -- We want to say "2 value binders".  Why?  So that 
172         -- we take account of information given for the arguments
173
174     go _      rev_vbs (Note InlineMe e)     = go True   rev_vbs     e
175     go inline rev_vbs (Lam b e) | isId b    = go inline (b:rev_vbs) e
176                                 | otherwise = go inline rev_vbs     e
177     go inline rev_vbs e                     = (inline, reverse rev_vbs, e)
178 \end{code}
179
180 \begin{code}
181 sizeExpr :: FastInt         -- Bomb out if it gets bigger than this
182          -> [Id]            -- Arguments; we're interested in which of these
183                             -- get case'd
184          -> CoreExpr
185          -> ExprSize
186
187 sizeExpr bOMB_OUT_SIZE top_args expr
188   = size_up expr
189   where
190     size_up (Type _)           = sizeZero        -- Types cost nothing
191     size_up (Var _)            = sizeOne
192
193     size_up (Note InlineMe _)  = sizeOne         -- Inline notes make it look very small
194         -- This can be important.  If you have an instance decl like this:
195         --      instance Foo a => Foo [a] where
196         --         {-# INLINE op1, op2 #-}
197         --         op1 = ...
198         --         op2 = ...
199         -- then we'll get a dfun which is a pair of two INLINE lambdas
200
201     size_up (Note _      body) = size_up body  -- Other notes cost nothing
202     
203     size_up (Cast e _)         = size_up e
204
205     size_up (App fun (Type _)) = size_up fun
206     size_up (App fun arg)      = size_up_app fun [arg]
207
208     size_up (Lit lit)          = sizeN (litSize lit)
209
210     size_up (Lam b e) | isId b    = lamScrutDiscount (size_up e `addSizeN` 1)
211                       | otherwise = size_up e
212
213     size_up (Let (NonRec binder rhs) body)
214       = nukeScrutDiscount (size_up rhs)         `addSize`
215         size_up body                            `addSizeN`
216         (if isUnLiftedType (idType binder) then 0 else 1)
217                 -- For the allocation
218                 -- If the binder has an unlifted type there is no allocation
219
220     size_up (Let (Rec pairs) body)
221       = nukeScrutDiscount rhs_size              `addSize`
222         size_up body                            `addSizeN`
223         length pairs            -- For the allocation
224       where
225         rhs_size = foldr (addSize . size_up . snd) sizeZero pairs
226
227     size_up (Case (Var v) _ _ alts) 
228         | v `elem` top_args             -- We are scrutinising an argument variable
229         = 
230 {-      I'm nuking this special case; BUT see the comment with case alternatives.
231
232         (a) It's too eager.  We don't want to inline a wrapper into a
233             context with no benefit.  
234             E.g.  \ x. f (x+x)          no point in inlining (+) here!
235
236         (b) It's ineffective. Once g's wrapper is inlined, its case-expressions 
237             aren't scrutinising arguments any more
238
239             case alts of
240
241                 [alt] -> size_up_alt alt `addSize` SizeIs (_ILIT(0)) (unitBag (v, 1)) (_ILIT(0))
242                 -- We want to make wrapper-style evaluation look cheap, so that
243                 -- when we inline a wrapper it doesn't make call site (much) bigger
244                 -- Otherwise we get nasty phase ordering stuff: 
245                 --      f x = g x x
246                 --      h y = ...(f e)...
247                 -- If we inline g's wrapper, f looks big, and doesn't get inlined
248                 -- into h; if we inline f first, while it looks small, then g's 
249                 -- wrapper will get inlined later anyway.  To avoid this nasty
250                 -- ordering difference, we make (case a of (x,y) -> ...), 
251                 --  *where a is one of the arguments* look free.
252
253                 other -> 
254 -}
255                          alts_size (foldr addSize sizeOne alt_sizes)    -- The 1 is for the scrutinee
256                                    (foldr1 maxSize alt_sizes)
257
258                 -- Good to inline if an arg is scrutinised, because
259                 -- that may eliminate allocation in the caller
260                 -- And it eliminates the case itself
261
262         where
263           alt_sizes = map size_up_alt alts
264
265                 -- alts_size tries to compute a good discount for
266                 -- the case when we are scrutinising an argument variable
267           alts_size (SizeIs tot _tot_disc _tot_scrut)           -- Size of all alternatives
268                     (SizeIs max  max_disc  max_scrut)           -- Size of biggest alternative
269                 = SizeIs tot (unitBag (v, iBox (_ILIT(1) +# tot -# max)) `unionBags` max_disc) max_scrut
270                         -- If the variable is known, we produce a discount that
271                         -- will take us back to 'max', the size of rh largest alternative
272                         -- The 1+ is a little discount for reduced allocation in the caller
273           alts_size tot_size _ = tot_size
274
275     size_up (Case e _ _ alts) = nukeScrutDiscount (size_up e) `addSize` 
276                                  foldr (addSize . size_up_alt) sizeZero alts
277                 -- We don't charge for the case itself
278                 -- It's a strict thing, and the price of the call
279                 -- is paid by scrut.  Also consider
280                 --      case f x of DEFAULT -> e
281                 -- This is just ';'!  Don't charge for it.
282
283     ------------ 
284     size_up_app (App fun arg) args   
285         | isTypeArg arg              = size_up_app fun args
286         | otherwise                  = size_up_app fun (arg:args)
287     size_up_app fun           args   = foldr (addSize . nukeScrutDiscount . size_up) 
288                                              (size_up_fun fun args)
289                                              args
290
291         -- A function application with at least one value argument
292         -- so if the function is an argument give it an arg-discount
293         --
294         -- Also behave specially if the function is a build
295         --
296         -- Also if the function is a constant Id (constr or primop)
297         -- compute discounts specially
298     size_up_fun (Var fun) args
299       | fun `hasKey` buildIdKey   = buildSize
300       | fun `hasKey` augmentIdKey = augmentSize
301       | otherwise 
302       = case globalIdDetails fun of
303           DataConWorkId dc -> conSizeN dc (valArgCount args)
304
305           FCallId _    -> sizeN opt_UF_DearOp
306           PrimOpId op  -> primOpSize op (valArgCount args)
307                           -- foldr addSize (primOpSize op) (map arg_discount args)
308                           -- At one time I tried giving an arg-discount if a primop 
309                           -- is applied to one of the function's arguments, but it's
310                           -- not good.  At the moment, any unlifted-type arg gets a
311                           -- 'True' for 'yes I'm evald', so we collect the discount even
312                           -- if we know nothing about it.  And just having it in a primop
313                           -- doesn't help at all if we don't know something more.
314
315           _            -> fun_discount fun `addSizeN`
316                           (1 + length (filter (not . exprIsTrivial) args))
317                                 -- The 1+ is for the function itself
318                                 -- Add 1 for each non-trivial arg;
319                                 -- the allocation cost, as in let(rec)
320                                 -- Slight hack here: for constructors the args are almost always
321                                 --      trivial; and for primops they are almost always prim typed
322                                 --      We should really only count for non-prim-typed args in the
323                                 --      general case, but that seems too much like hard work
324
325     size_up_fun other _ = size_up other
326
327     ------------ 
328     size_up_alt (_con, _bndrs, rhs) = size_up rhs
329         -- Don't charge for args, so that wrappers look cheap
330         -- (See comments about wrappers with Case)
331
332     ------------
333         -- We want to record if we're case'ing, or applying, an argument
334     fun_discount v | v `elem` top_args = SizeIs (_ILIT(0)) (unitBag (v, opt_UF_FunAppDiscount)) (_ILIT(0))
335     fun_discount _                     = sizeZero
336
337     ------------
338         -- These addSize things have to be here because
339         -- I don't want to give them bOMB_OUT_SIZE as an argument
340
341     addSizeN TooBig          _  = TooBig
342     addSizeN (SizeIs n xs d) m  = mkSizeIs bOMB_OUT_SIZE (n +# iUnbox m) xs d
343     
344     addSize TooBig            _                 = TooBig
345     addSize _                 TooBig            = TooBig
346     addSize (SizeIs n1 xs d1) (SizeIs n2 ys d2) 
347         = mkSizeIs bOMB_OUT_SIZE (n1 +# n2) (xs `unionBags` ys) (d1 +# d2)
348 \end{code}
349
350 Code for manipulating sizes
351
352 \begin{code}
353 data ExprSize = TooBig
354               | SizeIs FastInt          -- Size found
355                        (Bag (Id,Int))   -- Arguments cased herein, and discount for each such
356                        FastInt          -- Size to subtract if result is scrutinised 
357                                         -- by a case expression
358
359 -- subtract the discount before deciding whether to bale out. eg. we
360 -- want to inline a large constructor application into a selector:
361 --      tup = (a_1, ..., a_99)
362 --      x = case tup of ...
363 --
364 mkSizeIs :: FastInt -> FastInt -> Bag (Id, Int) -> FastInt -> ExprSize
365 mkSizeIs max n xs d | (n -# d) ># max = TooBig
366                     | otherwise       = SizeIs n xs d
367  
368 maxSize :: ExprSize -> ExprSize -> ExprSize
369 maxSize TooBig         _                                  = TooBig
370 maxSize _              TooBig                             = TooBig
371 maxSize s1@(SizeIs n1 _ _) s2@(SizeIs n2 _ _) | n1 ># n2  = s1
372                                               | otherwise = s2
373
374 sizeZero, sizeOne :: ExprSize
375 sizeN :: Int -> ExprSize
376 conSizeN :: DataCon ->Int -> ExprSize
377
378 sizeZero        = SizeIs (_ILIT(0))  emptyBag (_ILIT(0))
379 sizeOne         = SizeIs (_ILIT(1))  emptyBag (_ILIT(0))
380 sizeN n         = SizeIs (iUnbox n) emptyBag (_ILIT(0))
381 conSizeN dc n   
382   | isUnboxedTupleCon dc = SizeIs (_ILIT(0)) emptyBag (iUnbox n +# _ILIT(1))
383   | otherwise            = SizeIs (_ILIT(1)) emptyBag (iUnbox n +# _ILIT(1))
384         -- Treat constructors as size 1; we are keen to expose them
385         -- (and we charge separately for their args).  We can't treat
386         -- them as size zero, else we find that (iBox x) has size 1,
387         -- which is the same as a lone variable; and hence 'v' will 
388         -- always be replaced by (iBox x), where v is bound to iBox x.
389         --
390         -- However, unboxed tuples count as size zero
391         -- I found occasions where we had 
392         --      f x y z = case op# x y z of { s -> (# s, () #) }
393         -- and f wasn't getting inlined
394
395 primOpSize :: PrimOp -> Int -> ExprSize
396 primOpSize op n_args
397  | not (primOpIsDupable op) = sizeN opt_UF_DearOp
398  | not (primOpOutOfLine op) = sizeN (2 - n_args)
399         -- Be very keen to inline simple primops.
400         -- We give a discount of 1 for each arg so that (op# x y z) costs 2.
401         -- We can't make it cost 1, else we'll inline let v = (op# x y z) 
402         -- at every use of v, which is excessive.
403         --
404         -- A good example is:
405         --      let x = +# p q in C {x}
406         -- Even though x get's an occurrence of 'many', its RHS looks cheap,
407         -- and there's a good chance it'll get inlined back into C's RHS. Urgh!
408  | otherwise                = sizeOne
409
410 buildSize :: ExprSize
411 buildSize = SizeIs (_ILIT(-2)) emptyBag (_ILIT(4))
412         -- We really want to inline applications of build
413         -- build t (\cn -> e) should cost only the cost of e (because build will be inlined later)
414         -- Indeed, we should add a result_discount becuause build is 
415         -- very like a constructor.  We don't bother to check that the
416         -- build is saturated (it usually is).  The "-2" discounts for the \c n, 
417         -- The "4" is rather arbitrary.
418
419 augmentSize :: ExprSize
420 augmentSize = SizeIs (_ILIT(-2)) emptyBag (_ILIT(4))
421         -- Ditto (augment t (\cn -> e) ys) should cost only the cost of
422         -- e plus ys. The -2 accounts for the \cn 
423
424 nukeScrutDiscount :: ExprSize -> ExprSize
425 nukeScrutDiscount (SizeIs n vs _) = SizeIs n vs (_ILIT(0))
426 nukeScrutDiscount TooBig          = TooBig
427
428 -- When we return a lambda, give a discount if it's used (applied)
429 lamScrutDiscount :: ExprSize -> ExprSize
430 lamScrutDiscount (SizeIs n vs _) = case opt_UF_FunAppDiscount of { d -> SizeIs n vs (iUnbox d) }
431 lamScrutDiscount TooBig          = TooBig
432 \end{code}
433
434
435 %************************************************************************
436 %*                                                                      *
437 \subsection[considerUnfolding]{Given all the info, do (not) do the unfolding}
438 %*                                                                      *
439 %************************************************************************
440
441 We have very limited information about an unfolding expression: (1)~so
442 many type arguments and so many value arguments expected---for our
443 purposes here, we assume we've got those.  (2)~A ``size'' or ``cost,''
444 a single integer.  (3)~An ``argument info'' vector.  For this, what we
445 have at the moment is a Boolean per argument position that says, ``I
446 will look with great favour on an explicit constructor in this
447 position.'' (4)~The ``discount'' to subtract if the expression
448 is being scrutinised. 
449
450 Assuming we have enough type- and value arguments (if not, we give up
451 immediately), then we see if the ``discounted size'' is below some
452 (semi-arbitrary) threshold.  It works like this: for every argument
453 position where we're looking for a constructor AND WE HAVE ONE in our
454 hands, we get a (again, semi-arbitrary) discount [proportion to the
455 number of constructors in the type being scrutinized].
456
457 If we're in the context of a scrutinee ( \tr{(case <expr > of A .. -> ...;.. )})
458 and the expression in question will evaluate to a constructor, we use
459 the computed discount size *for the result only* rather than
460 computing the argument discounts. Since we know the result of
461 the expression is going to be taken apart, discounting its size
462 is more accurate (see @sizeExpr@ above for how this discount size
463 is computed).
464
465 We use this one to avoid exporting inlinings that we ``couldn't possibly
466 use'' on the other side.  Can be overridden w/ flaggery.
467 Just the same as smallEnoughToInline, except that it has no actual arguments.
468
469 \begin{code}
470 couldBeSmallEnoughToInline :: Int -> CoreExpr -> Bool
471 couldBeSmallEnoughToInline threshold rhs = case calcUnfoldingGuidance threshold rhs of
472                                                 UnfoldNever -> False
473                                                 _           -> True
474
475 certainlyWillInline :: Unfolding -> Bool
476   -- Sees if the unfolding is pretty certain to inline  
477 certainlyWillInline (CoreUnfolding _ _ _ is_cheap (UnfoldIfGoodArgs n_vals _ size _))
478   = is_cheap && size - (n_vals +1) <= opt_UF_UseThreshold
479 certainlyWillInline _
480   = False
481
482 smallEnoughToInline :: Unfolding -> Bool
483 smallEnoughToInline (CoreUnfolding _ _ _ _ (UnfoldIfGoodArgs _ _ size _))
484   = size <= opt_UF_UseThreshold
485 smallEnoughToInline _
486   = False
487 \end{code}
488
489 %************************************************************************
490 %*                                                                      *
491 \subsection{callSiteInline}
492 %*                                                                      *
493 %************************************************************************
494
495 This is the key function.  It decides whether to inline a variable at a call site
496
497 callSiteInline is used at call sites, so it is a bit more generous.
498 It's a very important function that embodies lots of heuristics.
499 A non-WHNF can be inlined if it doesn't occur inside a lambda,
500 and occurs exactly once or 
501     occurs once in each branch of a case and is small
502
503 If the thing is in WHNF, there's no danger of duplicating work, 
504 so we can inline if it occurs once, or is small
505
506 NOTE: we don't want to inline top-level functions that always diverge.
507 It just makes the code bigger.  Tt turns out that the convenient way to prevent
508 them inlining is to give them a NOINLINE pragma, which we do in 
509 StrictAnal.addStrictnessInfoToTopId
510
511 \begin{code}
512 callSiteInline :: DynFlags
513                -> Bool                  -- True <=> the Id can be inlined
514                -> Id                    -- The Id
515                -> Bool                  -- True if there are are no arguments at all (incl type args)
516                -> [Bool]                -- One for each value arg; True if it is interesting
517                -> CallCtxt              -- True <=> continuation is interesting
518                -> Maybe CoreExpr        -- Unfolding, if any
519
520
521 data CallCtxt = BoringCtxt
522
523               | ArgCtxt Bool    -- We're somewhere in the RHS of function with rules
524                                 --      => be keener to inline
525                         Int     -- We *are* the argument of a function with this arg discount
526                                 --      => be keener to inline
527                 -- INVARIANT: ArgCtxt False 0 ==> BoringCtxt
528
529               | CaseCtxt        -- We're the scrutinee of a case
530                                 -- that decomposes its scrutinee
531
532 instance Outputable CallCtxt where
533   ppr BoringCtxt    = ptext SLIT("BoringCtxt")
534   ppr (ArgCtxt _ _) = ptext SLIT("ArgCtxt")
535   ppr CaseCtxt      = ptext SLIT("CaseCtxt")
536
537 callSiteInline dflags active_inline id lone_variable arg_infos cont_info
538   = case idUnfolding id of {
539         NoUnfolding -> Nothing ;
540         OtherCon _  -> Nothing ;
541
542         CompulsoryUnfolding unf_template -> Just unf_template ;
543                 -- CompulsoryUnfolding => there is no top-level binding
544                 -- for these things, so we must inline it.
545                 -- Only a couple of primop-like things have 
546                 -- compulsory unfoldings (see MkId.lhs).
547                 -- We don't allow them to be inactive
548
549         CoreUnfolding unf_template is_top is_value is_cheap guidance ->
550
551     let
552         result | yes_or_no = Just unf_template
553                | otherwise = Nothing
554
555         n_val_args  = length arg_infos
556
557         yes_or_no = active_inline && is_cheap && consider_safe
558                 -- We consider even the once-in-one-branch
559                 -- occurrences, because they won't all have been
560                 -- caught by preInlineUnconditionally.  In particular,
561                 -- if the occurrence is once inside a lambda, and the
562                 -- rhs is cheap but not a manifest lambda, then
563                 -- pre-inline will not have inlined it for fear of
564                 -- invalidating the occurrence info in the rhs.
565
566         consider_safe
567                 -- consider_safe decides whether it's a good idea to
568                 -- inline something, given that there's no
569                 -- work-duplication issue (the caller checks that).
570           = case guidance of
571               UnfoldNever  -> False
572               UnfoldIfGoodArgs n_vals_wanted arg_discounts size res_discount
573                   | enough_args && size <= (n_vals_wanted + 1)
574                         -- Inline unconditionally if there no size increase
575                         -- Size of call is n_vals_wanted (+1 for the function)
576                   -> True
577
578                   | otherwise
579                   -> some_benefit && small_enough
580
581                   where
582                     enough_args = n_val_args >= n_vals_wanted
583
584                     some_benefit = or arg_infos || really_interesting_cont
585                                 -- There must be something interesting
586                                 -- about some argument, or the result
587                                 -- context, to make it worth inlining
588
589                     really_interesting_cont 
590                         | n_val_args <  n_vals_wanted = False   -- Too few args
591                         | n_val_args == n_vals_wanted = interesting_saturated_call
592                         | otherwise                   = True    -- Extra args
593                         -- really_interesting_cont tells if the result of the
594                         -- call is in an interesting context.
595
596                     interesting_saturated_call 
597                         = case cont_info of
598                             BoringCtxt -> not is_top && n_vals_wanted > 0       -- Note [Nested functions] 
599                             CaseCtxt   -> not lone_variable || not is_value     -- Note [Lone variables]
600                             ArgCtxt {} -> True
601                                 -- Was: n_vals_wanted > 0; but see test eyeball/inline1.hs
602
603                     small_enough = (size - discount) <= opt_UF_UseThreshold
604                     discount = computeDiscount n_vals_wanted arg_discounts 
605                                                res_discount' arg_infos
606                     res_discount' = case cont_info of
607                                         BoringCtxt  -> 0
608                                         CaseCtxt    -> res_discount
609                                         ArgCtxt _ _ -> 4 `min` res_discount
610                         -- res_discount can be very large when a function returns
611                         -- construtors; but we only want to invoke that large discount
612                         -- when there's a case continuation.
613                         -- Otherwise we, rather arbitrarily, threshold it.  Yuk.
614                         -- But we want to aovid inlining large functions that return 
615                         -- constructors into contexts that are simply "interesting"
616                 
617     in    
618     if dopt Opt_D_dump_inlinings dflags then
619         pprTrace "Considering inlining"
620                  (ppr id <+> vcat [text "active:" <+> ppr active_inline,
621                                    text "arg infos" <+> ppr arg_infos,
622                                    text "interesting continuation" <+> ppr cont_info,
623                                    text "is value:" <+> ppr is_value,
624                                    text "is cheap:" <+> ppr is_cheap,
625                                    text "guidance" <+> ppr guidance,
626                                    text "ANSWER =" <+> if yes_or_no then text "YES" else text "NO"])
627                   result
628     else
629     result
630     }
631 \end{code}
632
633 Note [Nested functions]
634 ~~~~~~~~~~~~~~~~~~~~~~~
635 If a function has a nested defn we also record some-benefit, on the
636 grounds that we are often able to eliminate the binding, and hence the
637 allocation, for the function altogether; this is good for join points.
638 But this only makes sense for *functions*; inlining a constructor
639 doesn't help allocation unless the result is scrutinised.  UNLESS the
640 constructor occurs just once, albeit possibly in multiple case
641 branches.  Then inlining it doesn't increase allocation, but it does
642 increase the chance that the constructor won't be allocated at all in
643 the branches that don't use it.
644
645 Note [Lone variables]
646 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
647 The "lone-variable" case is important.  I spent ages messing about
648 with unsatisfactory varaints, but this is nice.  The idea is that if a
649 variable appears all alone
650         as an arg of lazy fn, or rhs    Stop
651         as scrutinee of a case          Select
652         as arg of a strict fn           ArgOf
653 AND
654         it is bound to a value
655 then we should not inline it (unless there is some other reason,
656 e.g. is is the sole occurrence).  That is what is happening at 
657 the use of 'lone_variable' in 'interesting_saturated_call'.
658
659 Why?  At least in the case-scrutinee situation, turning
660         let x = (a,b) in case x of y -> ...
661 into
662         let x = (a,b) in case (a,b) of y -> ...
663 and thence to 
664         let x = (a,b) in let y = (a,b) in ...
665 is bad if the binding for x will remain.
666
667 Another example: I discovered that strings
668 were getting inlined straight back into applications of 'error'
669 because the latter is strict.
670         s = "foo"
671         f = \x -> ...(error s)...
672
673 Fundamentally such contexts should not encourage inlining because the
674 context can ``see'' the unfolding of the variable (e.g. case or a
675 RULE) so there's no gain.  If the thing is bound to a value.
676
677 However, watch out:
678
679  * Consider this:
680         foo = _inline_ (\n. [n])
681         bar = _inline_ (foo 20)
682         baz = \n. case bar of { (m:_) -> m + n }
683    Here we really want to inline 'bar' so that we can inline 'foo'
684    and the whole thing unravels as it should obviously do.  This is 
685    important: in the NDP project, 'bar' generates a closure data
686    structure rather than a list. 
687
688  * Even a type application or coercion isn't a lone variable.
689    Consider
690         case $fMonadST @ RealWorld of { :DMonad a b c -> c }
691    We had better inline that sucker!  The case won't see through it.
692
693    For now, I'm treating treating a variable applied to types 
694    in a *lazy* context "lone". The motivating example was
695         f = /\a. \x. BIG
696         g = /\a. \y.  h (f a)
697    There's no advantage in inlining f here, and perhaps
698    a significant disadvantage.  Hence some_val_args in the Stop case
699
700 \begin{code}
701 computeDiscount :: Int -> [Int] -> Int -> [Bool] -> Int
702 computeDiscount n_vals_wanted arg_discounts result_discount arg_infos
703         -- We multiple the raw discounts (args_discount and result_discount)
704         -- ty opt_UnfoldingKeenessFactor because the former have to do with
705         --  *size* whereas the discounts imply that there's some extra 
706         --  *efficiency* to be gained (e.g. beta reductions, case reductions) 
707         -- by inlining.
708
709         -- we also discount 1 for each argument passed, because these will
710         -- reduce with the lambdas in the function (we count 1 for a lambda
711         -- in size_up).
712   = 1 +                 -- Discount of 1 because the result replaces the call
713                         -- so we count 1 for the function itself
714     length (take n_vals_wanted arg_infos) +
715                         -- Discount of 1 for each arg supplied, because the 
716                         -- result replaces the call
717     round (opt_UF_KeenessFactor * 
718            fromIntegral (arg_discount + result_discount))
719   where
720     arg_discount = sum (zipWith mk_arg_discount arg_discounts arg_infos)
721
722     mk_arg_discount discount is_evald | is_evald  = discount
723                                       | otherwise = 0
724 \end{code}