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