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