39740c79387159eafa8d047c1da32654cfaaccf3
[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, -- types
18
19         noUnfolding, mkUnfolding, getUnfoldingTemplate,
20         isEvaldUnfolding, hasUnfolding,
21
22         couldBeSmallEnoughToInline, 
23         certainlySmallEnoughToInline, 
24         okToUnfoldInHiFile,
25
26         calcUnfoldingGuidance,
27
28         callSiteInline, blackListed
29     ) where
30
31 #include "HsVersions.h"
32
33 import CmdLineOpts      ( opt_UF_CreationThreshold,
34                           opt_UF_UseThreshold,
35                           opt_UF_ScrutConDiscount,
36                           opt_UF_FunAppDiscount,
37                           opt_UF_PrimArgDiscount,
38                           opt_UF_KeenessFactor,
39                           opt_UF_CheapOp, opt_UF_DearOp, opt_UF_NoRepLit,
40                           opt_UnfoldCasms, opt_PprStyle_Debug,
41                           opt_D_dump_inlinings
42                         )
43 import CoreSyn
44 import PprCore          ( pprCoreExpr )
45 import OccurAnal        ( occurAnalyseGlobalExpr )
46 import BinderInfo       ( )
47 import CoreUtils        ( coreExprType, exprIsTrivial, mkFormSummary, whnfOrBottom,
48                           FormSummary(..) )
49 import Id               ( Id, idType, idUnique, isId, 
50                           getIdSpecialisation, getInlinePragma, getIdUnfolding
51                         )
52 import VarSet
53 import Const            ( Con(..), isLitLitLit, isWHNFCon )
54 import PrimOp           ( PrimOp(..), primOpIsDupable )
55 import IdInfo           ( ArityInfo(..), InlinePragInfo(..), OccInfo(..) )
56 import TyCon            ( tyConFamilySize )
57 import Type             ( splitAlgTyConApp_maybe, splitFunTy_maybe )
58 import Const            ( isNoRepLit )
59 import Unique           ( Unique, buildIdKey, augmentIdKey, runSTRepIdKey )
60 import Maybes           ( maybeToBool )
61 import Bag
62 import Util             ( isIn, lengthExceeds )
63 import Outputable
64 \end{code}
65
66 %************************************************************************
67 %*                                                                      *
68 \subsection{@Unfolding@ and @UnfoldingGuidance@ types}
69 %*                                                                      *
70 %************************************************************************
71
72 \begin{code}
73 data Unfolding
74   = NoUnfolding
75
76   | OtherCon [Con]              -- It ain't one of these
77                                 -- (OtherCon xs) also indicates that something has been evaluated
78                                 -- and hence there's no point in re-evaluating it.
79                                 -- OtherCon [] is used even for non-data-type values
80                                 -- to indicated evaluated-ness.  Notably:
81                                 --      data C = C !(Int -> Int)
82                                 --      case x of { C f -> ... }
83                                 -- Here, f gets an OtherCon [] unfolding.
84
85   | CoreUnfolding                       -- An unfolding with redundant cached information
86                 FormSummary             -- Tells whether the template is a WHNF or bottom
87                 UnfoldingGuidance       -- Tells about the *size* of the template.
88                 CoreExpr                -- Template; binder-info is correct
89 \end{code}
90
91 \begin{code}
92 noUnfolding = NoUnfolding
93
94 mkUnfolding expr
95   = let
96      -- strictness mangling (depends on there being no CSE)
97      ufg = calcUnfoldingGuidance opt_UF_CreationThreshold expr
98      occ = occurAnalyseGlobalExpr expr
99     in
100     CoreUnfolding (mkFormSummary expr) ufg occ
101
102 getUnfoldingTemplate :: Unfolding -> CoreExpr
103 getUnfoldingTemplate (CoreUnfolding _ _ expr) = expr
104 getUnfoldingTemplate other = panic "getUnfoldingTemplate"
105
106 isEvaldUnfolding :: Unfolding -> Bool
107 isEvaldUnfolding (OtherCon _)                     = True
108 isEvaldUnfolding (CoreUnfolding ValueForm _ expr) = True
109 isEvaldUnfolding other                            = False
110
111 hasUnfolding :: Unfolding -> Bool
112 hasUnfolding NoUnfolding = False
113 hasUnfolding other       = True
114
115 data UnfoldingGuidance
116   = UnfoldNever
117   | UnfoldAlways                -- There is no "original" definition,
118                                 -- so you'd better unfold.  Or: something
119                                 -- so cheap to unfold (e.g., 1#) that
120                                 -- you should do it absolutely always.
121
122   | UnfoldIfGoodArgs    Int     -- and "n" value args
123
124                         [Int]   -- Discount if the argument is evaluated.
125                                 -- (i.e., a simplification will definitely
126                                 -- be possible).  One elt of the list per *value* arg.
127
128                         Int     -- The "size" of the unfolding; to be elaborated
129                                 -- later. ToDo
130
131                         Int     -- Scrutinee discount: the discount to substract if the thing is in
132                                 -- a context (case (thing args) of ...),
133                                 -- (where there are the right number of arguments.)
134 \end{code}
135
136 \begin{code}
137 instance Outputable UnfoldingGuidance where
138     ppr UnfoldAlways    = ptext SLIT("ALWAYS")
139     ppr UnfoldNever     = ptext SLIT("NEVER")
140     ppr (UnfoldIfGoodArgs v cs size discount)
141       = hsep [ptext SLIT("IF_ARGS"), int v,
142                if null cs       -- always print *something*
143                 then char 'X'
144                 else hcat (map (text . show) cs),
145                int size,
146                int discount ]
147 \end{code}
148
149
150 %************************************************************************
151 %*                                                                      *
152 \subsection[calcUnfoldingGuidance]{Calculate ``unfolding guidance'' for an expression}
153 %*                                                                      *
154 %************************************************************************
155
156 \begin{code}
157 calcUnfoldingGuidance
158         :: Int                  -- bomb out if size gets bigger than this
159         -> CoreExpr             -- expression to look at
160         -> UnfoldingGuidance
161 calcUnfoldingGuidance bOMB_OUT_SIZE expr
162   | exprIsTrivial expr          -- Often trivial expressions are never bound
163                                 -- to an expression, but it can happen.  For
164                                 -- example, the Id for a nullary constructor has
165                                 -- a trivial expression as its unfolding, and
166                                 -- we want to make sure that we always unfold it.
167   = UnfoldAlways
168  
169   | otherwise
170   = case collectBinders expr of { (binders, body) ->
171     let
172         val_binders = filter isId binders
173     in
174     case (sizeExpr bOMB_OUT_SIZE val_binders body) of
175
176       TooBig -> UnfoldNever
177
178       SizeIs size cased_args scrut_discount
179         -> UnfoldIfGoodArgs
180                         (length val_binders)
181                         (map discount_for val_binders)
182                         (I# size)
183                         (I# scrut_discount)
184         where        
185             discount_for b 
186                 | num_cases == 0 = 0
187                 | is_fun_ty      = num_cases * opt_UF_FunAppDiscount
188                 | is_data_ty     = num_cases * tyConFamilySize tycon * opt_UF_ScrutConDiscount
189                 | otherwise      = num_cases * opt_UF_PrimArgDiscount
190                 where
191                   num_cases           = foldlBag (\n b' -> if b==b' then n+1 else n) 0 cased_args
192                                         -- Count occurrences of b in cased_args
193                   arg_ty              = idType b
194                   is_fun_ty           = maybeToBool (splitFunTy_maybe arg_ty)
195                   (is_data_ty, tycon) = case (splitAlgTyConApp_maybe (idType b)) of
196                                           Nothing       -> (False, panic "discount")
197                                           Just (tc,_,_) -> (True,  tc)
198         }
199 \end{code}
200
201 \begin{code}
202 sizeExpr :: Int             -- Bomb out if it gets bigger than this
203          -> [Id]            -- Arguments; we're interested in which of these
204                             -- get case'd
205          -> CoreExpr
206          -> ExprSize
207
208 sizeExpr (I# bOMB_OUT_SIZE) args expr
209   = size_up expr
210   where
211     size_up (Type t)          = sizeZero        -- Types cost nothing
212     size_up (Var v)           = sizeOne
213
214     size_up (Note InlineMe _) = sizeTwo         -- The idea is that this is one more
215                                                 -- than the size of the "call" (i.e. 1)
216                                                 -- We want to reply "no" to noSizeIncrease
217                                                 -- for a bare reference (i.e. applied to no args) 
218                                                 -- to an INLINE thing
219
220     size_up (Note _ body)     = size_up body    -- Notes cost nothing
221
222     size_up (App fun (Type t))  = size_up fun
223     size_up (App fun arg)       = size_up_app fun [arg]
224
225     size_up (Con con args) = foldr (addSize . size_up) 
226                                    (size_up_con con args)
227                                    args
228
229     size_up (Lam b e) | isId b    = size_up e `addSizeN` 1
230                       | otherwise = size_up e
231
232     size_up (Let (NonRec binder rhs) body)
233       = nukeScrutDiscount (size_up rhs)         `addSize`
234         size_up body                            `addSizeN`
235         1       -- For the allocation
236
237     size_up (Let (Rec pairs) body)
238       = nukeScrutDiscount rhs_size              `addSize`
239         size_up body                            `addSizeN`
240         length pairs            -- For the allocation
241       where
242         rhs_size = foldr (addSize . size_up . snd) sizeZero pairs
243
244     size_up (Case scrut _ alts)
245       = nukeScrutDiscount (size_up scrut)               `addSize`
246         arg_discount scrut                              `addSize`
247         foldr (addSize . size_up_alt) sizeZero alts     `addSizeN`
248         case (splitAlgTyConApp_maybe (coreExprType scrut)) of
249                 Nothing       -> 1
250                 Just (tc,_,_) -> tyConFamilySize tc
251
252     ------------ 
253     size_up_app (App fun arg) args   = size_up_app fun (arg:args)
254     size_up_app fun           args   = foldr (addSize . size_up) (fun_discount fun) args
255
256         -- A function application with at least one value argument
257         -- so if the function is an argument give it an arg-discount
258         -- Also behave specially if the function is a build
259     fun_discount (Var fun) | idUnique fun == buildIdKey = buildSize
260                            | fun `is_elem` args         = scrutArg fun
261     fun_discount other                                  = sizeZero
262
263     ------------ 
264     size_up_alt (con, bndrs, rhs) = size_up rhs
265             -- Don't charge for args, so that wrappers look cheap
266
267     ------------
268     size_up_con (Literal lit) args | isNoRepLit lit = sizeN opt_UF_NoRepLit
269                                    | otherwise      = sizeOne
270
271     size_up_con (DataCon dc) args = conSizeN (valArgCount args)
272                              
273     size_up_con (PrimOp op) args = foldr addSize (sizeN op_cost) (map arg_discount args)
274                 -- Give an arg-discount if a primop is applies to
275                 -- one of the function's arguments
276       where
277         op_cost | primOpIsDupable op = opt_UF_CheapOp
278                 | otherwise          = opt_UF_DearOp
279
280         -- We want to record if we're case'ing, or applying, an argument
281     arg_discount (Var v) | v `is_elem` args = scrutArg v
282     arg_discount other                      = sizeZero
283
284     ------------
285     is_elem :: Id -> [Id] -> Bool
286     is_elem = isIn "size_up_scrut"
287
288     ------------
289         -- These addSize things have to be here because
290         -- I don't want to give them bOMB_OUT_SIZE as an argument
291
292     addSizeN TooBig          _ = TooBig
293     addSizeN (SizeIs n xs d) (I# m)
294       | n_tot -# d <# bOMB_OUT_SIZE = SizeIs n_tot xs d
295       | otherwise                   = TooBig
296       where
297         n_tot = n +# m
298     
299     addSize TooBig _ = TooBig
300     addSize _ TooBig = TooBig
301     addSize (SizeIs n1 xs d1) (SizeIs n2 ys d2)
302       | (n_tot -# d_tot) <# bOMB_OUT_SIZE = SizeIs n_tot xys d_tot
303       | otherwise                         = TooBig
304       where
305         n_tot = n1 +# n2
306         d_tot = d1 +# d2
307         xys   = xs `unionBags` ys
308 \end{code}
309
310 Code for manipulating sizes
311
312 \begin{code}
313
314 data ExprSize = TooBig
315               | SizeIs Int#     -- Size found
316                        (Bag Id) -- Arguments cased herein
317                        Int#     -- Size to subtract if result is scrutinised 
318                                 -- by a case expression
319
320 sizeZero        = SizeIs 0# emptyBag 0#
321 sizeOne         = SizeIs 1# emptyBag 0#
322 sizeTwo         = SizeIs 2# emptyBag 0#
323 sizeN (I# n)    = SizeIs n  emptyBag 0#
324 conSizeN (I# n) = SizeIs 1# emptyBag (n +# 1#)
325         -- Treat constructors as size 1, that unfoldAlways responsds 'False'
326         -- when asked about 'x' when x is bound to (C 3#).
327         -- This avoids gratuitous 'ticks' when x itself appears as an
328         -- atomic constructor argument.
329
330 buildSize = SizeIs (-2#) emptyBag 4#
331         -- We really want to inline applications of build
332         -- build t (\cn -> e) should cost only the cost of e (because build will be inlined later)
333         -- Indeed, we should add a result_discount becuause build is 
334         -- very like a constructor.  We don't bother to check that the
335         -- build is saturated (it usually is).  The "-2" discounts for the \c n
336         -- The "4" is rather arbitrary.
337                                                 
338 scrutArg v      = SizeIs 0# (unitBag v) 0#
339
340 nukeScrutDiscount (SizeIs n vs d) = SizeIs n vs 0#
341 nukeScrutDiscount TooBig          = TooBig
342 \end{code}
343
344
345 %************************************************************************
346 %*                                                                      *
347 \subsection[considerUnfolding]{Given all the info, do (not) do the unfolding}
348 %*                                                                      *
349 %************************************************************************
350
351 We have very limited information about an unfolding expression: (1)~so
352 many type arguments and so many value arguments expected---for our
353 purposes here, we assume we've got those.  (2)~A ``size'' or ``cost,''
354 a single integer.  (3)~An ``argument info'' vector.  For this, what we
355 have at the moment is a Boolean per argument position that says, ``I
356 will look with great favour on an explicit constructor in this
357 position.'' (4)~The ``discount'' to subtract if the expression
358 is being scrutinised. 
359
360 Assuming we have enough type- and value arguments (if not, we give up
361 immediately), then we see if the ``discounted size'' is below some
362 (semi-arbitrary) threshold.  It works like this: for every argument
363 position where we're looking for a constructor AND WE HAVE ONE in our
364 hands, we get a (again, semi-arbitrary) discount [proportion to the
365 number of constructors in the type being scrutinized].
366
367 If we're in the context of a scrutinee ( \tr{(case <expr > of A .. -> ...;.. )})
368 and the expression in question will evaluate to a constructor, we use
369 the computed discount size *for the result only* rather than
370 computing the argument discounts. Since we know the result of
371 the expression is going to be taken apart, discounting its size
372 is more accurate (see @sizeExpr@ above for how this discount size
373 is computed).
374
375 We use this one to avoid exporting inlinings that we ``couldn't possibly
376 use'' on the other side.  Can be overridden w/ flaggery.
377 Just the same as smallEnoughToInline, except that it has no actual arguments.
378
379 \begin{code}
380 couldBeSmallEnoughToInline :: UnfoldingGuidance -> Bool
381 couldBeSmallEnoughToInline UnfoldNever = False
382 couldBeSmallEnoughToInline other       = True
383
384 certainlySmallEnoughToInline :: UnfoldingGuidance -> Bool
385 certainlySmallEnoughToInline UnfoldNever                   = False
386 certainlySmallEnoughToInline UnfoldAlways                  = True
387 certainlySmallEnoughToInline (UnfoldIfGoodArgs _ _ size _) = size <= opt_UF_UseThreshold
388 \end{code}
389
390 @okToUnfoldInHifile@ is used when emitting unfolding info into an interface
391 file to determine whether an unfolding candidate really should be unfolded.
392 The predicate is needed to prevent @_casm_@s (+ lit-lits) from being emitted
393 into interface files. 
394
395 The reason for inlining expressions containing _casm_s into interface files
396 is that these fragments of C are likely to mention functions/#defines that
397 will be out-of-scope when inlined into another module. This is not an
398 unfixable problem for the user (just need to -#include the approp. header
399 file), but turning it off seems to the simplest thing to do.
400
401 \begin{code}
402 okToUnfoldInHiFile :: CoreExpr -> Bool
403 okToUnfoldInHiFile e = opt_UnfoldCasms || go e
404  where
405     -- Race over an expression looking for CCalls..
406     go (Var _)                = True
407     go (Con (Literal lit) _)  = not (isLitLitLit lit)
408     go (Con (PrimOp op) args) = okToUnfoldPrimOp op && all go args
409     go (Con con args)         = True -- con args are always atomic
410     go (App fun arg)          = go fun && go arg
411     go (Lam _ body)           = go body
412     go (Let binds body)       = and (map go (body :rhssOfBind binds))
413     go (Case scrut bndr alts) = and (map go (scrut:rhssOfAlts alts))
414     go (Note _ body)          = go body
415     go (Type _)               = True
416
417     -- ok to unfold a PrimOp as long as it's not a _casm_
418     okToUnfoldPrimOp (CCallOp _ is_casm _ _) = not is_casm
419     okToUnfoldPrimOp _                       = True
420 \end{code}
421
422
423 %************************************************************************
424 %*                                                                      *
425 \subsection{callSiteInline}
426 %*                                                                      *
427 %************************************************************************
428
429 This is the key function.  It decides whether to inline a variable at a call site
430
431 callSiteInline is used at call sites, so it is a bit more generous.
432 It's a very important function that embodies lots of heuristics.
433 A non-WHNF can be inlined if it doesn't occur inside a lambda,
434 and occurs exactly once or 
435     occurs once in each branch of a case and is small
436
437 If the thing is in WHNF, there's no danger of duplicating work, 
438 so we can inline if it occurs once, or is small
439
440 \begin{code}
441 callSiteInline :: Bool                  -- True <=> the Id is black listed
442                -> Bool                  -- 'inline' note at call site
443                -> Id                    -- The Id
444                -> [CoreExpr]            -- Arguments
445                -> Bool                  -- True <=> continuation is interesting
446                -> Maybe CoreExpr        -- Unfolding, if any
447
448
449 callSiteInline black_listed inline_call id args interesting_cont
450   = case getIdUnfolding id of {
451         NoUnfolding -> Nothing ;
452         OtherCon _  -> Nothing ;
453         CoreUnfolding form guidance unf_template ->
454
455     let
456         result | yes_or_no = Just unf_template
457                | otherwise = Nothing
458
459         inline_prag = getInlinePragma id
460         arg_infos   = map interestingArg val_args
461         val_args    = filter isValArg args
462         whnf        = whnfOrBottom form
463
464         yes_or_no =
465             case inline_prag of
466                 IAmDead           -> pprTrace "callSiteInline: dead" (ppr id) False
467                 IMustNotBeINLINEd -> False
468                 IAmALoopBreaker   -> False
469                 IMustBeINLINEd    -> True       -- Overrides absolutely everything, including the black list
470                 ICanSafelyBeINLINEd in_lam one_br -> consider in_lam    one_br
471                 NoInlinePragInfo                  -> consider InsideLam False
472
473         consider in_lam one_branch 
474           | black_listed = False
475           | inline_call  = True
476           | one_branch  -- Be very keen to inline something if this is its unique occurrence; that
477                         -- gives a good chance of eliminating the original binding for the thing.
478                         -- The only time we hold back is when substituting inside a lambda;
479                         -- then if the context is totally uninteresting (not applied, not scrutinised)
480                         -- there is no point in substituting because it might just increase allocation.
481           = WARN( case in_lam of { NotInsideLam -> True; other -> False },
482                   text "callSiteInline:oneOcc" <+> ppr id )
483                 -- If it has one occurrence, not inside a lambda, PreInlineUnconditionally
484                 -- should have zapped it already
485             whnf && (not (null args) || interesting_cont)
486
487           | otherwise   -- Occurs (textually) more than once, so look at its size
488           = case guidance of
489               UnfoldAlways -> True
490               UnfoldNever  -> False
491               UnfoldIfGoodArgs n_vals_wanted arg_discounts size res_discount
492                 | enough_args && size <= (n_vals_wanted + 1)
493                         -- No size increase
494                         -- Size of call is n_vals_wanted (+1 for the function)
495                 -> case in_lam of
496                         NotInsideLam -> True
497                         InsideLam    -> whnf
498
499                 | not (or arg_infos || really_interesting_cont)
500                         -- If it occurs more than once, there must be something interesting 
501                         -- about some argument, or the result, to make it worth inlining
502                 -> False
503   
504                 | otherwise
505                 -> case in_lam of
506                         NotInsideLam -> small_enough
507                         InsideLam    -> whnf && small_enough
508
509                 where
510                   n_args                  = length arg_infos
511                   enough_args             = n_args >= n_vals_wanted
512                   really_interesting_cont | n_args <  n_vals_wanted = False     -- Too few args
513                                           | n_args == n_vals_wanted = interesting_cont
514                                           | otherwise               = True      -- Extra args
515                         -- This rather elaborate defn for really_interesting_cont is important
516                         -- Consider an I# = INLINE (\x -> I# {x})
517                         -- The unfolding guidance deems it to have size 2, and no arguments.
518                         -- So in an application (I# y) we must take the extra arg 'y' as
519                         -- evidence of an interesting context!
520                         
521                   small_enough = (size - discount) <= opt_UF_UseThreshold
522                   discount     = computeDiscount n_vals_wanted arg_discounts res_discount 
523                                                  arg_infos really_interesting_cont
524
525                                 
526     in    
527 #ifdef DEBUG
528     if opt_D_dump_inlinings then
529         pprTrace "Considering inlining"
530                  (ppr id <+> vcat [text "black listed" <+> ppr black_listed,
531                                    text "inline prag:" <+> ppr inline_prag,
532                                    text "arg infos" <+> ppr arg_infos,
533                                    text "interesting continuation" <+> ppr interesting_cont,
534                                    text "whnf" <+> ppr whnf,
535                                    text "guidance" <+> ppr guidance,
536                                    text "ANSWER =" <+> if yes_or_no then text "YES" else text "NO",
537                                    if yes_or_no then
538                                         text "Unfolding =" <+> pprCoreExpr unf_template
539                                    else empty])
540                   result
541     else
542 #endif
543     result
544     }
545
546 -- An argument is interesting if it has *some* structure
547 -- We are here trying to avoid unfolding a function that
548 -- is applied only to variables that have no unfolding
549 -- (i.e. they are probably lambda bound): f x y z
550 -- There is little point in inlining f here.
551 interestingArg (Type _)          = False
552 interestingArg (App fn (Type _)) = interestingArg fn
553 interestingArg (Var v)           = hasUnfolding (getIdUnfolding v)
554 interestingArg other             = True
555
556
557 computeDiscount :: Int -> [Int] -> Int -> [Bool] -> Bool -> Int
558 computeDiscount n_vals_wanted arg_discounts res_discount arg_infos result_used
559         -- We multiple the raw discounts (args_discount and result_discount)
560         -- ty opt_UnfoldingKeenessFactor because the former have to do with
561         -- *size* whereas the discounts imply that there's some extra 
562         -- *efficiency* to be gained (e.g. beta reductions, case reductions) 
563         -- by inlining.
564
565         -- we also discount 1 for each argument passed, because these will
566         -- reduce with the lambdas in the function (we count 1 for a lambda
567         -- in size_up).
568   = length (take n_vals_wanted arg_infos) +
569                         -- Discount of 1 for each arg supplied, because the 
570                         -- result replaces the call
571     round (opt_UF_KeenessFactor * 
572            fromInt (arg_discount + result_discount))
573   where
574     arg_discount = sum (zipWith mk_arg_discount arg_discounts arg_infos)
575
576     mk_arg_discount discount is_evald | is_evald  = discount
577                                       | otherwise = 0
578
579         -- Don't give a result discount unless there are enough args
580     result_discount | result_used = res_discount        -- Over-applied, or case scrut
581                     | otherwise   = 0
582 \end{code}
583
584
585 %************************************************************************
586 %*                                                                      *
587 \subsection{Black-listing}
588 %*                                                                      *
589 %************************************************************************
590
591 Inlining is controlled by the "Inline phase" number, which is set
592 by the per-simplification-pass '-finline-phase' flag.
593
594 For optimisation we use phase 1,2 and nothing (i.e. no -finline-phase flag)
595 in that order.  The meanings of these are determined by the @blackListed@ function
596 here.
597
598 \begin{code}
599 blackListed :: IdSet            -- Used in transformation rules
600             -> Maybe Int        -- Inline phase
601             -> Id -> Bool       -- True <=> blacklisted
602         
603 -- The blackListed function sees whether a variable should *not* be 
604 -- inlined because of the inline phase we are in.  This is the sole
605 -- place that the inline phase number is looked at.
606
607 -- Phase 0: used for 'no inlinings please'
608 blackListed rule_vars (Just 0)
609   = \v -> True
610
611 -- Phase 1: don't inline any rule-y things or things with specialisations
612 blackListed rule_vars (Just 1)
613   = \v -> let v_uniq = idUnique v
614           in v `elemVarSet` rule_vars
615           || not (isEmptyCoreRules (getIdSpecialisation v))
616           || v_uniq == runSTRepIdKey
617
618 -- Phase 2: allow build/augment to inline, and specialisations
619 blackListed rule_vars (Just 2)
620   = \v -> let v_uniq = idUnique v
621           in (v `elemVarSet` rule_vars && not (v_uniq == buildIdKey || 
622                                                v_uniq == augmentIdKey))
623           || v_uniq == runSTRepIdKey
624
625 -- Otherwise just go for it
626 blackListed rule_vars phase
627   = \v -> False
628 \end{code}
629
630
631 SLPJ 95/04: Why @runST@ must be inlined very late:
632 \begin{verbatim}
633 f x =
634   runST ( \ s -> let
635                     (a, s')  = newArray# 100 [] s
636                     (_, s'') = fill_in_array_or_something a x s'
637                   in
638                   freezeArray# a s'' )
639 \end{verbatim}
640 If we inline @runST@, we'll get:
641 \begin{verbatim}
642 f x = let
643         (a, s')  = newArray# 100 [] realWorld#{-NB-}
644         (_, s'') = fill_in_array_or_something a x s'
645       in
646       freezeArray# a s''
647 \end{verbatim}
648 And now the @newArray#@ binding can be floated to become a CAF, which
649 is totally and utterly wrong:
650 \begin{verbatim}
651 f = let
652     (a, s')  = newArray# 100 [] realWorld#{-NB-} -- YIKES!!!
653     in
654     \ x ->
655         let (_, s'') = fill_in_array_or_something a x s' in
656         freezeArray# a s''
657 \end{verbatim}
658 All calls to @f@ will share a {\em single} array!  
659
660 Yet we do want to inline runST sometime, so we can avoid
661 needless code.  Solution: black list it until the last moment.
662