[project @ 2000-10-23 09:03:26 by simonpj]
[ghc-hetmet.git] / ghc / compiler / coreSyn / CoreUnfold.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1994-1998
3 %
4 \section[CoreUnfold]{Core-syntax unfoldings}
5
6 Unfoldings (which can travel across module boundaries) are in Core
7 syntax (namely @CoreExpr@s).
8
9 The type @Unfolding@ sits ``above'' simply-Core-expressions
10 unfoldings, capturing ``higher-level'' things we know about a binding,
11 usually things that the simplifier found out (e.g., ``it's a
12 literal'').  In the corner of a @CoreUnfolding@ unfolding, you will
13 find, unsurprisingly, a Core expression.
14
15 \begin{code}
16 module CoreUnfold (
17         Unfolding, UnfoldingGuidance,   -- Abstract types
18
19         noUnfolding, mkTopUnfolding, mkUnfolding, mkCompulsoryUnfolding, seqUnfolding,
20         mkOtherCon, otherCons,
21         unfoldingTemplate, maybeUnfoldingTemplate,
22         isEvaldUnfolding, isValueUnfolding, isCheapUnfolding, isCompulsoryUnfolding,
23         hasUnfolding, hasSomeUnfolding,
24
25         couldBeSmallEnoughToInline, 
26         certainlyWillInline, 
27         okToUnfoldInHiFile,
28
29         callSiteInline, blackListed
30     ) where
31
32 #include "HsVersions.h"
33
34 import CmdLineOpts      ( opt_UF_CreationThreshold,
35                           opt_UF_UseThreshold,
36                           opt_UF_FunAppDiscount,
37                           opt_UF_KeenessFactor,
38                           opt_UF_DearOp, opt_UnfoldCasms,
39                           DynFlags, DynFlag(..), dopt
40                         )
41 import CoreSyn
42 import PprCore          ( pprCoreExpr )
43 import OccurAnal        ( occurAnalyseGlobalExpr )
44 import CoreUtils        ( exprIsValue, exprIsCheap, exprIsTrivial )
45 import Id               ( Id, idType, idFlavour, isId,
46                           idSpecialisation, idInlinePragma, idUnfolding,
47                           isPrimOpId_maybe
48                         )
49 import VarSet
50 import Literal          ( isLitLitLit, litIsDupable )
51 import PrimOp           ( PrimOp(..), primOpIsDupable, primOpOutOfLine, ccallIsCasm )
52 import IdInfo           ( InlinePragInfo(..), OccInfo(..), IdFlavour(..),
53                           isNeverInlinePrag
54                         )
55 import Type             ( isUnLiftedType )
56 import PrelNames        ( hasKey, buildIdKey, augmentIdKey )
57 import Bag
58 import FastTypes
59 import Outputable
60
61 #if __GLASGOW_HASKELL__ >= 404
62 import GlaExts          ( fromInt )
63 #endif
64 \end{code}
65
66
67 %************************************************************************
68 %*                                                                      *
69 \subsection{Making unfoldings}
70 %*                                                                      *
71 %************************************************************************
72
73 \begin{code}
74 mkTopUnfolding expr = mkUnfolding True {- Top level -} expr
75
76 mkUnfolding top_lvl expr
77   = CoreUnfolding (occurAnalyseGlobalExpr expr)
78                   top_lvl
79                   (exprIsValue expr)
80                         -- Already evaluated
81
82                   (exprIsCheap expr)
83                         -- OK to inline inside a lambda
84
85                   (calcUnfoldingGuidance opt_UF_CreationThreshold expr)
86         -- Sometimes during simplification, there's a large let-bound thing     
87         -- which has been substituted, and so is now dead; so 'expr' contains
88         -- two copies of the thing while the occurrence-analysed expression doesn't
89         -- Nevertheless, we don't occ-analyse before computing the size because the
90         -- size computation bales out after a while, whereas occurrence analysis does not.
91         --
92         -- This can occasionally mean that the guidance is very pessimistic;
93         -- it gets fixed up next round
94
95 mkCompulsoryUnfolding expr      -- Used for things that absolutely must be unfolded
96   = CompulsoryUnfolding (occurAnalyseGlobalExpr 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 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         | inline     -> 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 inline 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 :: Int             -- 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 t)          = sizeZero        -- Types cost nothing
189     size_up (Var v)           = sizeOne
190
191     size_up (Note _ body)     = size_up body    -- Notes cost nothing
192
193     size_up (App fun (Type t))  = size_up fun
194     size_up (App fun arg)     = size_up_app fun [arg]
195
196     size_up (Lit lit) | litIsDupable lit = sizeOne
197                       | otherwise        = sizeN opt_UF_DearOp  -- For lack of anything better
198
199     size_up (Lam b e) | isId b    = lamScrutDiscount (size_up e `addSizeN` 1)
200                       | otherwise = size_up e
201
202     size_up (Let (NonRec binder rhs) body)
203       = nukeScrutDiscount (size_up rhs)         `addSize`
204         size_up body                            `addSizeN`
205         (if isUnLiftedType (idType binder) then 0 else 1)
206                 -- For the allocation
207                 -- If the binder has an unlifted type there is no allocation
208
209     size_up (Let (Rec pairs) body)
210       = nukeScrutDiscount rhs_size              `addSize`
211         size_up body                            `addSizeN`
212         length pairs            -- For the allocation
213       where
214         rhs_size = foldr (addSize . size_up . snd) sizeZero pairs
215
216     size_up (Case (Var v) _ alts) 
217         | v `elem` top_args             -- We are scrutinising an argument variable
218         = 
219 {-      I'm nuking this special case; BUT see the comment with case alternatives.
220
221         (a) It's too eager.  We don't want to inline a wrapper into a
222             context with no benefit.  
223             E.g.  \ x. f (x+x)          o point in inlining (+) here!
224
225         (b) It's ineffective. Once g's wrapper is inlined, its case-expressions 
226             aren't scrutinising arguments any more
227
228             case alts of
229
230                 [alt] -> size_up_alt alt `addSize` SizeIs 0# (unitBag (v, 1)) 0#
231                 -- We want to make wrapper-style evaluation look cheap, so that
232                 -- when we inline a wrapper it doesn't make call site (much) bigger
233                 -- Otherwise we get nasty phase ordering stuff: 
234                 --      f x = g x x
235                 --      h y = ...(f e)...
236                 -- If we inline g's wrapper, f looks big, and doesn't get inlined
237                 -- into h; if we inline f first, while it looks small, then g's 
238                 -- wrapper will get inlined later anyway.  To avoid this nasty
239                 -- ordering difference, we make (case a of (x,y) -> ...), 
240                 -- *where a is one of the arguments* look free.
241
242                 other -> 
243 -}
244                          alts_size (foldr addSize sizeOne alt_sizes)    -- The 1 is for the scrutinee
245                                    (foldr1 maxSize alt_sizes)
246
247                 -- Good to inline if an arg is scrutinised, because
248                 -- that may eliminate allocation in the caller
249                 -- And it eliminates the case itself
250
251         where
252           alt_sizes = map size_up_alt alts
253
254                 -- alts_size tries to compute a good discount for
255                 -- the case when we are scrutinising an argument variable
256           alts_size (SizeIs tot tot_disc tot_scrut)             -- Size of all alternatives
257                     (SizeIs max max_disc max_scrut)             -- Size of biggest alternative
258                 = SizeIs tot (unitBag (v, iBox (_ILIT 1 +# tot -# max)) `unionBags` max_disc) max_scrut
259                         -- If the variable is known, we produce a discount that
260                         -- will take us back to 'max', the size of rh largest alternative
261                         -- The 1+ is a little discount for reduced allocation in the caller
262           alts_size tot_size _ = tot_size
263
264
265     size_up (Case e _ alts) = nukeScrutDiscount (size_up e) `addSize` 
266                               foldr (addSize . size_up_alt) sizeZero alts
267                 -- We don't charge for the case itself
268                 -- It's a strict thing, and the price of the call
269                 -- is paid by scrut.  Also consider
270                 --      case f x of DEFAULT -> e
271                 -- This is just ';'!  Don't charge for it.
272
273     ------------ 
274     size_up_app (App fun arg) args   
275         | isTypeArg arg              = size_up_app fun args
276         | otherwise                  = size_up_app fun (arg:args)
277     size_up_app fun           args   = foldr (addSize . nukeScrutDiscount . size_up) 
278                                              (size_up_fun fun args)
279                                              args
280
281         -- A function application with at least one value argument
282         -- so if the function is an argument give it an arg-discount
283         --
284         -- Also behave specially if the function is a build
285         --
286         -- Also if the function is a constant Id (constr or primop)
287         -- compute discounts specially
288     size_up_fun (Var fun) args
289       | fun `hasKey` buildIdKey   = buildSize
290       | fun `hasKey` augmentIdKey = augmentSize
291       | otherwise 
292       = case idFlavour fun of
293           DataConId dc -> conSizeN (valArgCount args)
294
295           PrimOpId op  -> primOpSize op (valArgCount args)
296                           -- foldr addSize (primOpSize op) (map arg_discount args)
297                           -- At one time I tried giving an arg-discount if a primop 
298                           -- is applied to one of the function's arguments, but it's
299                           -- not good.  At the moment, any unlifted-type arg gets a
300                           -- 'True' for 'yes I'm evald', so we collect the discount even
301                           -- if we know nothing about it.  And just having it in a primop
302                           -- doesn't help at all if we don't know something more.
303
304           other        -> fun_discount fun `addSizeN` 
305                           (1 + length (filter (not . exprIsTrivial) args))
306                                 -- The 1+ is for the function itself
307                                 -- Add 1 for each non-trivial arg;
308                                 -- the allocation cost, as in let(rec)
309                                 -- Slight hack here: for constructors the args are almost always
310                                 --      trivial; and for primops they are almost always prim typed
311                                 --      We should really only count for non-prim-typed args in the
312                                 --      general case, but that seems too much like hard work
313
314     size_up_fun other args = size_up other
315
316     ------------ 
317     size_up_alt (con, bndrs, rhs) = size_up rhs
318         -- Don't charge for args, so that wrappers look cheap
319         -- (See comments about wrappers with Case)
320
321     ------------
322         -- We want to record if we're case'ing, or applying, an argument
323     fun_discount v | v `elem` top_args = SizeIs 0# (unitBag (v, opt_UF_FunAppDiscount)) 0#
324     fun_discount other                 = sizeZero
325
326     ------------
327         -- These addSize things have to be here because
328         -- I don't want to give them bOMB_OUT_SIZE as an argument
329
330     addSizeN TooBig          _      = TooBig
331     addSizeN (SizeIs n xs d) m
332       | n_tot ># (iUnbox bOMB_OUT_SIZE) = TooBig
333       | otherwise                   = SizeIs n_tot xs d
334       where
335         n_tot = n +# iUnbox m
336     
337     addSize TooBig _ = TooBig
338     addSize _ TooBig = TooBig
339     addSize (SizeIs n1 xs d1) (SizeIs n2 ys d2)
340       | n_tot ># (iUnbox bOMB_OUT_SIZE) = TooBig
341       | otherwise              = SizeIs n_tot xys d_tot
342       where
343         n_tot = n1 +# n2
344         d_tot = d1 +# d2
345         xys   = xs `unionBags` ys
346 \end{code}
347
348 Code for manipulating sizes
349
350 \begin{code}
351
352 data ExprSize = TooBig
353               | SizeIs FastInt          -- Size found
354                        (Bag (Id,Int))   -- Arguments cased herein, and discount for each such
355                        FastInt          -- Size to subtract if result is scrutinised 
356                                         -- by a case expression
357
358
359 maxSize TooBig         _                                  = TooBig
360 maxSize _              TooBig                             = TooBig
361 maxSize s1@(SizeIs n1 _ _) s2@(SizeIs n2 _ _) | n1 ># n2  = s1
362                                               | otherwise = s2
363
364 sizeZero        = SizeIs (_ILIT 0) emptyBag (_ILIT 0)
365 sizeOne         = SizeIs (_ILIT 1) emptyBag (_ILIT 0)
366 sizeTwo         = SizeIs (_ILIT 2) emptyBag (_ILIT 0)
367 sizeN n         = SizeIs (iUnbox n) emptyBag (_ILIT 0)
368 conSizeN n      = SizeIs (_ILIT 1) emptyBag (iUnbox n +# _ILIT 1)
369         -- Treat constructors as size 1; we are keen to expose them
370         -- (and we charge separately for their args).  We can't treat
371         -- them as size zero, else we find that (iBox x) has size 1,
372         -- which is the same as a lone variable; and hence 'v' will 
373         -- always be replaced by (iBox x), where v is bound to iBox x.
374
375 primOpSize op n_args
376  | not (primOpIsDupable op) = sizeN opt_UF_DearOp
377  | not (primOpOutOfLine op) = sizeZero                  -- These are good to inline
378  | otherwise                = sizeOne
379
380 buildSize = SizeIs (-2#) emptyBag 4#
381         -- We really want to inline applications of build
382         -- build t (\cn -> e) should cost only the cost of e (because build will be inlined later)
383         -- Indeed, we should add a result_discount becuause build is 
384         -- very like a constructor.  We don't bother to check that the
385         -- build is saturated (it usually is).  The "-2" discounts for the \c n, 
386         -- The "4" is rather arbitrary.
387
388 augmentSize = SizeIs (-2#) emptyBag 4#
389         -- Ditto (augment t (\cn -> e) ys) should cost only the cost of
390         -- e plus ys. The -2 accounts for the \cn 
391                                                 
392 nukeScrutDiscount (SizeIs n vs d) = SizeIs n vs 0#
393 nukeScrutDiscount TooBig          = TooBig
394
395 -- When we return a lambda, give a discount if it's used (applied)
396 lamScrutDiscount  (SizeIs n vs d) = case opt_UF_FunAppDiscount of { d -> SizeIs n vs (iUnbox d) }
397 lamScrutDiscount TooBig           = TooBig
398 \end{code}
399
400
401 %************************************************************************
402 %*                                                                      *
403 \subsection[considerUnfolding]{Given all the info, do (not) do the unfolding}
404 %*                                                                      *
405 %************************************************************************
406
407 We have very limited information about an unfolding expression: (1)~so
408 many type arguments and so many value arguments expected---for our
409 purposes here, we assume we've got those.  (2)~A ``size'' or ``cost,''
410 a single integer.  (3)~An ``argument info'' vector.  For this, what we
411 have at the moment is a Boolean per argument position that says, ``I
412 will look with great favour on an explicit constructor in this
413 position.'' (4)~The ``discount'' to subtract if the expression
414 is being scrutinised. 
415
416 Assuming we have enough type- and value arguments (if not, we give up
417 immediately), then we see if the ``discounted size'' is below some
418 (semi-arbitrary) threshold.  It works like this: for every argument
419 position where we're looking for a constructor AND WE HAVE ONE in our
420 hands, we get a (again, semi-arbitrary) discount [proportion to the
421 number of constructors in the type being scrutinized].
422
423 If we're in the context of a scrutinee ( \tr{(case <expr > of A .. -> ...;.. )})
424 and the expression in question will evaluate to a constructor, we use
425 the computed discount size *for the result only* rather than
426 computing the argument discounts. Since we know the result of
427 the expression is going to be taken apart, discounting its size
428 is more accurate (see @sizeExpr@ above for how this discount size
429 is computed).
430
431 We use this one to avoid exporting inlinings that we ``couldn't possibly
432 use'' on the other side.  Can be overridden w/ flaggery.
433 Just the same as smallEnoughToInline, except that it has no actual arguments.
434
435 \begin{code}
436 couldBeSmallEnoughToInline :: Int -> CoreExpr -> Bool
437 couldBeSmallEnoughToInline threshold rhs = case calcUnfoldingGuidance threshold rhs of
438                                                 UnfoldNever -> False
439                                                 other       -> True
440
441 certainlyWillInline :: Id -> Bool
442         -- Sees if the Id is pretty certain to inline   
443 certainlyWillInline v
444   = case idUnfolding v of
445
446         CoreUnfolding _ _ is_value _ g@(UnfoldIfGoodArgs n_vals _ size _)
447            ->    is_value 
448               && size - (n_vals +1) <= opt_UF_UseThreshold
449
450         other -> False
451 \end{code}
452
453 @okToUnfoldInHifile@ is used when emitting unfolding info into an interface
454 file to determine whether an unfolding candidate really should be unfolded.
455 The predicate is needed to prevent @_casm_@s (+ lit-lits) from being emitted
456 into interface files. 
457
458 The reason for inlining expressions containing _casm_s into interface files
459 is that these fragments of C are likely to mention functions/#defines that
460 will be out-of-scope when inlined into another module. This is not an
461 unfixable problem for the user (just need to -#include the approp. header
462 file), but turning it off seems to the simplest thing to do.
463
464 \begin{code}
465 okToUnfoldInHiFile :: CoreExpr -> Bool
466 okToUnfoldInHiFile e = opt_UnfoldCasms || go e
467  where
468     -- Race over an expression looking for CCalls..
469     go (Var v)                = case isPrimOpId_maybe v of
470                                   Just op -> okToUnfoldPrimOp op
471                                   Nothing -> True
472     go (Lit lit)              = not (isLitLitLit lit)
473     go (App fun arg)          = go fun && go arg
474     go (Lam _ body)           = go body
475     go (Let binds body)       = and (map go (body :rhssOfBind binds))
476     go (Case scrut bndr alts) = and (map go (scrut:rhssOfAlts alts)) &&
477                                 not (any isLitLitLit [ lit | (LitAlt lit, _, _) <- alts ])
478     go (Note _ body)          = go body
479     go (Type _)               = True
480
481     -- ok to unfold a PrimOp as long as it's not a _casm_
482     okToUnfoldPrimOp (CCallOp ccall) = not (ccallIsCasm ccall)
483     okToUnfoldPrimOp _               = True
484 \end{code}
485
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 is black listed
512                -> Bool                  -- 'inline' note at call site
513                -> OccInfo
514                -> Id                    -- The Id
515                -> [Bool]                -- One for each value arg; True if it is interesting
516                -> Bool                  -- True <=> continuation is interesting
517                -> Maybe CoreExpr        -- Unfolding, if any
518
519
520 callSiteInline dflags black_listed inline_call occ id arg_infos interesting_cont
521   = case idUnfolding id of {
522         NoUnfolding -> Nothing ;
523         OtherCon cs -> Nothing ;
524         CompulsoryUnfolding unf_template | black_listed -> Nothing 
525                                          | otherwise    -> Just unf_template ;
526                 -- Constructors have compulsory unfoldings, but
527                 -- may have rules, in which case they are 
528                 -- black listed till later
529         CoreUnfolding unf_template is_top is_value is_cheap guidance ->
530
531     let
532         result | yes_or_no = Just unf_template
533                | otherwise = Nothing
534
535         n_val_args  = length arg_infos
536
537         yes_or_no 
538           | black_listed = False
539           | otherwise    = case occ of
540                                 IAmDead              -> pprTrace "callSiteInline: dead" (ppr id) False
541                                 IAmALoopBreaker      -> False
542                                 OneOcc in_lam one_br -> (not in_lam || is_cheap) && consider_safe in_lam True  one_br
543                                 NoOccInfo            -> is_cheap                 && consider_safe True   False False
544
545         consider_safe in_lam once once_in_one_branch
546                 -- consider_safe decides whether it's a good idea to inline something,
547                 -- given that there's no work-duplication issue (the caller checks that).
548                 -- once_in_one_branch = True means there's a unique textual occurrence
549           | inline_call  = True
550
551           | once_in_one_branch
552                 -- Be very keen to inline something if this is its unique occurrence:
553                 --
554                 --   a) Inlining gives a good chance of eliminating the original 
555                 --      binding (and hence the allocation) for the thing.  
556                 --      (Provided it's not a top level binding, in which case the 
557                 --       allocation costs nothing.)
558                 --
559                 --   b) Inlining a function that is called only once exposes the 
560                 --      body function to the call site.
561                 --
562                 -- The only time we hold back is when substituting inside a lambda;
563                 -- then if the context is totally uninteresting (not applied, not scrutinised)
564                 -- there is no point in substituting because it might just increase allocation,
565                 -- by allocating the function itself many times
566                 --
567                 -- Note: there used to be a '&& not top_level' in the guard above,
568                 --       but that stopped us inlining top-level functions used only once,
569                 --       which is stupid
570           = not in_lam || not (null arg_infos) || interesting_cont
571
572           | otherwise
573           = case guidance of
574               UnfoldNever  -> False ;
575               UnfoldIfGoodArgs n_vals_wanted arg_discounts size res_discount
576
577                   | enough_args && size <= (n_vals_wanted + 1)
578                         -- No size increase
579                         -- Size of call is n_vals_wanted (+1 for the function)
580                   -> True
581
582                   | otherwise
583                   -> some_benefit && small_enough
584
585                   where
586                     some_benefit = or arg_infos || really_interesting_cont || 
587                                    (not is_top && (once || (n_vals_wanted > 0 && enough_args)))
588                         -- If it occurs more than once, there must be something interesting 
589                         -- about some argument, or the result context, to make it worth inlining
590                         --
591                         -- If a function has a nested defn we also record some-benefit,
592                         -- on the grounds that we are often able to eliminate the binding,
593                         -- and hence the allocation, for the function altogether; this is good
594                         -- for join points.  But this only makes sense for *functions*;
595                         -- inlining a constructor doesn't help allocation unless the result is
596                         -- scrutinised.  UNLESS the constructor occurs just once, albeit possibly
597                         -- in multiple case branches.  Then inlining it doesn't increase allocation,
598                         -- but it does increase the chance that the constructor won't be allocated at all
599                         -- in the branches that don't use it.
600             
601                     enough_args           = n_val_args >= n_vals_wanted
602                     really_interesting_cont | n_val_args <  n_vals_wanted = False       -- Too few args
603                                             | n_val_args == n_vals_wanted = interesting_cont
604                                             | otherwise                   = True        -- Extra args
605                         -- really_interesting_cont tells if the result of the
606                         -- call is in an interesting context.
607
608                     small_enough = (size - discount) <= opt_UF_UseThreshold
609                     discount     = computeDiscount n_vals_wanted arg_discounts res_discount 
610                                                  arg_infos really_interesting_cont
611                 
612     in    
613 #ifdef DEBUG
614     if dopt Opt_D_dump_inlinings dflags then
615         pprTrace "Considering inlining"
616                  (ppr id <+> vcat [text "black listed:" <+> ppr black_listed,
617                                    text "occ info:" <+> ppr occ,
618                                    text "arg infos" <+> ppr arg_infos,
619                                    text "interesting continuation" <+> ppr interesting_cont,
620                                    text "is value:" <+> ppr is_value,
621                                    text "is cheap:" <+> ppr is_cheap,
622                                    text "guidance" <+> ppr guidance,
623                                    text "ANSWER =" <+> if yes_or_no then text "YES" else text "NO",
624                                    if yes_or_no then
625                                         text "Unfolding =" <+> pprCoreExpr unf_template
626                                    else empty])
627                   result
628     else
629 #endif
630     result
631     }
632
633 computeDiscount :: Int -> [Int] -> Int -> [Bool] -> Bool -> Int
634 computeDiscount n_vals_wanted arg_discounts res_discount arg_infos result_used
635         -- We multiple the raw discounts (args_discount and result_discount)
636         -- ty opt_UnfoldingKeenessFactor because the former have to do with
637         -- *size* whereas the discounts imply that there's some extra 
638         -- *efficiency* to be gained (e.g. beta reductions, case reductions) 
639         -- by inlining.
640
641         -- we also discount 1 for each argument passed, because these will
642         -- reduce with the lambdas in the function (we count 1 for a lambda
643         -- in size_up).
644   = 1 +                 -- Discount of 1 because the result replaces the call
645                         -- so we count 1 for the function itself
646     length (take n_vals_wanted arg_infos) +
647                         -- Discount of 1 for each arg supplied, because the 
648                         -- result replaces the call
649     round (opt_UF_KeenessFactor * 
650            fromInt (arg_discount + result_discount))
651   where
652     arg_discount = sum (zipWith mk_arg_discount arg_discounts arg_infos)
653
654     mk_arg_discount discount is_evald | is_evald  = discount
655                                       | otherwise = 0
656
657         -- Don't give a result discount unless there are enough args
658     result_discount | result_used = res_discount        -- Over-applied, or case scrut
659                     | otherwise   = 0
660 \end{code}
661
662
663 %************************************************************************
664 %*                                                                      *
665 \subsection{Black-listing}
666 %*                                                                      *
667 %************************************************************************
668
669 Inlining is controlled by the "Inline phase" number, which is set
670 by the per-simplification-pass '-finline-phase' flag.
671
672 For optimisation we use phase 1,2 and nothing (i.e. no -finline-phase flag)
673 in that order.  The meanings of these are determined by the @blackListed@ function
674 here.
675
676 The final simplification doesn't have a phase number.
677
678 Pragmas
679 ~~~~~~~
680         Pragma          Black list if
681
682 (least black listing, most inlining)
683         INLINE n foo    phase is Just p *and* p<n *and* foo appears on LHS of rule
684         INLINE foo      phase is Just p *and*           foo appears on LHS of rule
685         NOINLINE n foo  phase is Just p *and* (p<n *or* foo appears on LHS of rule)
686         NOINLINE foo    always
687 (most black listing, least inlining)
688
689 \begin{code}
690 blackListed :: IdSet            -- Used in transformation rules
691             -> Maybe Int        -- Inline phase
692             -> Id -> Bool       -- True <=> blacklisted
693         
694 -- The blackListed function sees whether a variable should *not* be 
695 -- inlined because of the inline phase we are in.  This is the sole
696 -- place that the inline phase number is looked at.
697
698 blackListed rule_vars Nothing           -- Last phase
699   = \v -> isNeverInlinePrag (idInlinePragma v)
700
701 blackListed rule_vars (Just phase)
702   = \v -> normal_case rule_vars phase v
703
704 normal_case rule_vars phase v 
705   = case idInlinePragma v of
706         NoInlinePragInfo -> has_rules
707
708         IMustNotBeINLINEd from_INLINE Nothing
709           | from_INLINE -> has_rules    -- Black list until final phase
710           | otherwise   -> True         -- Always blacklisted
711
712         IMustNotBeINLINEd from_INLINE (Just threshold)
713           | from_INLINE -> (phase < threshold && has_rules)
714           | otherwise   -> (phase < threshold || has_rules)
715   where
716     has_rules =  v `elemVarSet` rule_vars
717               || not (isEmptyCoreRules (idSpecialisation v))
718 \end{code}
719
720
721 SLPJ 95/04: Why @runST@ must be inlined very late:
722 \begin{verbatim}
723 f x =
724   runST ( \ s -> let
725                     (a, s')  = newArray# 100 [] s
726                     (_, s'') = fill_in_array_or_something a x s'
727                   in
728                   freezeArray# a s'' )
729 \end{verbatim}
730 If we inline @runST@, we'll get:
731 \begin{verbatim}
732 f x = let
733         (a, s')  = newArray# 100 [] realWorld#{-NB-}
734         (_, s'') = fill_in_array_or_something a x s'
735       in
736       freezeArray# a s''
737 \end{verbatim}
738 And now the @newArray#@ binding can be floated to become a CAF, which
739 is totally and utterly wrong:
740 \begin{verbatim}
741 f = let
742     (a, s')  = newArray# 100 [] realWorld#{-NB-} -- YIKES!!!
743     in
744     \ x ->
745         let (_, s'') = fill_in_array_or_something a x s' in
746         freezeArray# a s''
747 \end{verbatim}
748 All calls to @f@ will share a {\em single} array!  
749
750 Yet we do want to inline runST sometime, so we can avoid
751 needless code.  Solution: black list it until the last moment.
752