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