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