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