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