Tweak sizing heurstics for case expressions (see comments).
[ghc-hetmet.git] / compiler / coreSyn / CoreUnfold.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The AQUA Project, Glasgow University, 1994-1998
4 %
5
6 Core-syntax unfoldings
7
8 Unfoldings (which can travel across module boundaries) are in Core
9 syntax (namely @CoreExpr@s).
10
11 The type @Unfolding@ sits ``above'' simply-Core-expressions
12 unfoldings, capturing ``higher-level'' things we know about a binding,
13 usually things that the simplifier found out (e.g., ``it's a
14 literal'').  In the corner of a @CoreUnfolding@ unfolding, you will
15 find, unsurprisingly, a Core expression.
16
17 \begin{code}
18 module CoreUnfold (
19         Unfolding, UnfoldingGuidance,   -- Abstract types
20
21         noUnfolding, mkImplicitUnfolding, 
22         mkUnfolding, mkCoreUnfolding,
23         mkTopUnfolding, mkSimpleUnfolding,
24         mkInlineUnfolding, mkInlinableUnfolding, mkWwInlineRule,
25         mkCompulsoryUnfolding, mkDFunUnfolding,
26
27         interestingArg, ArgSummary(..),
28
29         couldBeSmallEnoughToInline, inlineBoringOk,
30         certainlyWillInline, smallEnoughToInline,
31
32         callSiteInline, CallCtxt(..), 
33
34         exprIsConApp_maybe
35
36     ) where
37
38 #include "HsVersions.h"
39
40 import StaticFlags
41 import DynFlags
42 import CoreSyn
43 import PprCore          ()      -- Instances
44 import TcType           ( tcSplitDFunTy )
45 import OccurAnal        ( occurAnalyseExpr )
46 import CoreSubst hiding( substTy )
47 import CoreFVs         ( exprFreeVars )
48 import CoreArity       ( manifestArity, exprBotStrictness_maybe )
49 import CoreUtils
50 import Id
51 import DataCon
52 import TyCon
53 import Literal
54 import PrimOp
55 import IdInfo
56 import BasicTypes       ( Arity )
57 import Type
58 import Coercion
59 import PrelNames
60 import VarEnv           ( mkInScopeSet )
61 import Bag
62 import Util
63 import Pair
64 import FastTypes
65 import FastString
66 import Outputable
67 import ForeignCall
68
69 import Data.Maybe
70 \end{code}
71
72
73 %************************************************************************
74 %*                                                                      *
75 \subsection{Making unfoldings}
76 %*                                                                      *
77 %************************************************************************
78
79 \begin{code}
80 mkTopUnfolding :: Bool -> CoreExpr -> Unfolding
81 mkTopUnfolding = mkUnfolding InlineRhs True {- Top level -}
82
83 mkImplicitUnfolding :: CoreExpr -> Unfolding
84 -- For implicit Ids, do a tiny bit of optimising first
85 mkImplicitUnfolding expr = mkTopUnfolding False (simpleOptExpr expr) 
86
87 -- Note [Top-level flag on inline rules]
88 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
89 -- Slight hack: note that mk_inline_rules conservatively sets the
90 -- top-level flag to True.  It gets set more accurately by the simplifier
91 -- Simplify.simplUnfolding.
92
93 mkSimpleUnfolding :: CoreExpr -> Unfolding
94 mkSimpleUnfolding = mkUnfolding InlineRhs False False
95
96 mkDFunUnfolding :: Type -> [DFunArg CoreExpr] -> Unfolding
97 mkDFunUnfolding dfun_ty ops 
98   = DFunUnfolding dfun_nargs data_con ops
99   where
100     (tvs, n_theta, cls, _) = tcSplitDFunTy dfun_ty
101     dfun_nargs = length tvs + n_theta
102     data_con   = classDataCon cls
103
104 mkWwInlineRule :: Id -> CoreExpr -> Arity -> Unfolding
105 mkWwInlineRule id expr arity
106   = mkCoreUnfolding (InlineWrapper id) True
107                    (simpleOptExpr expr) arity
108                    (UnfWhen unSaturatedOk boringCxtNotOk)
109
110 mkCompulsoryUnfolding :: CoreExpr -> Unfolding
111 mkCompulsoryUnfolding expr         -- Used for things that absolutely must be unfolded
112   = mkCoreUnfolding InlineCompulsory True
113                     (simpleOptExpr expr) 0    -- Arity of unfolding doesn't matter
114                     (UnfWhen unSaturatedOk boringCxtOk)
115
116 mkInlineUnfolding :: Maybe Arity -> CoreExpr -> Unfolding
117 mkInlineUnfolding mb_arity expr 
118   = mkCoreUnfolding InlineStable
119                     True         -- Note [Top-level flag on inline rules]
120                     expr' arity 
121                     (UnfWhen unsat_ok boring_ok)
122   where
123     expr' = simpleOptExpr expr
124     (unsat_ok, arity) = case mb_arity of
125                           Nothing -> (unSaturatedOk, manifestArity expr')
126                           Just ar -> (needSaturated, ar)
127               
128     boring_ok = inlineBoringOk expr'
129
130 mkInlinableUnfolding :: CoreExpr -> Unfolding
131 mkInlinableUnfolding expr
132   = mkUnfolding InlineStable True is_bot expr'
133   where
134     expr' = simpleOptExpr expr
135     is_bot = isJust (exprBotStrictness_maybe expr')
136 \end{code}
137
138 Internal functions
139
140 \begin{code}
141 mkCoreUnfolding :: UnfoldingSource -> Bool -> CoreExpr
142                 -> Arity -> UnfoldingGuidance -> Unfolding
143 -- Occurrence-analyses the expression before capturing it
144 mkCoreUnfolding src top_lvl expr arity guidance 
145   = CoreUnfolding { uf_tmpl       = occurAnalyseExpr expr,
146                     uf_src        = src,
147                     uf_arity      = arity,
148                     uf_is_top     = top_lvl,
149                     uf_is_value   = exprIsHNF        expr,
150                     uf_is_conlike = exprIsConLike    expr,
151                     uf_is_cheap   = exprIsCheap      expr,
152                     uf_expandable = exprIsExpandable expr,
153                     uf_guidance   = guidance }
154
155 mkUnfolding :: UnfoldingSource -> Bool -> Bool -> CoreExpr -> Unfolding
156 -- Calculates unfolding guidance
157 -- Occurrence-analyses the expression before capturing it
158 mkUnfolding src top_lvl is_bottoming expr
159   | top_lvl && is_bottoming
160   , not (exprIsTrivial expr)
161   = NoUnfolding    -- See Note [Do not inline top-level bottoming functions]
162   | otherwise
163   = CoreUnfolding { uf_tmpl       = occurAnalyseExpr expr,
164                     uf_src        = src,
165                     uf_arity      = arity,
166                     uf_is_top     = top_lvl,
167                     uf_is_value   = exprIsHNF        expr,
168                     uf_is_conlike = exprIsConLike    expr,
169                     uf_expandable = exprIsExpandable expr,
170                     uf_is_cheap   = is_cheap,
171                     uf_guidance   = guidance }
172   where
173     is_cheap = exprIsCheap expr
174     (arity, guidance) = calcUnfoldingGuidance is_cheap
175                                               opt_UF_CreationThreshold expr
176         -- Sometimes during simplification, there's a large let-bound thing     
177         -- which has been substituted, and so is now dead; so 'expr' contains
178         -- two copies of the thing while the occurrence-analysed expression doesn't
179         -- Nevertheless, we *don't* occ-analyse before computing the size because the
180         -- size computation bales out after a while, whereas occurrence analysis does not.
181         --
182         -- This can occasionally mean that the guidance is very pessimistic;
183         -- it gets fixed up next round.  And it should be rare, because large
184         -- let-bound things that are dead are usually caught by preInlineUnconditionally
185 \end{code}
186
187 %************************************************************************
188 %*                                                                      *
189 \subsection{The UnfoldingGuidance type}
190 %*                                                                      *
191 %************************************************************************
192
193 \begin{code}
194 inlineBoringOk :: CoreExpr -> Bool
195 -- See Note [INLINE for small functions]
196 -- True => the result of inlining the expression is 
197 --         no bigger than the expression itself
198 --     eg      (\x y -> f y x)
199 -- This is a quick and dirty version. It doesn't attempt
200 -- to deal with  (\x y z -> x (y z))
201 -- The really important one is (x `cast` c)
202 inlineBoringOk e
203   = go 0 e
204   where
205     go :: Int -> CoreExpr -> Bool
206     go credit (Lam x e) | isId x           = go (credit+1) e
207                         | otherwise        = go credit e
208     go credit (App f (Type {}))            = go credit f
209     go credit (App f a) | credit > 0  
210                         , exprIsTrivial a  = go (credit-1) f
211     go credit (Note _ e)                   = go credit e     
212     go credit (Cast e _)                   = go credit e
213     go _      (Var {})                     = boringCxtOk
214     go _      _                            = boringCxtNotOk
215
216 calcUnfoldingGuidance
217         :: Bool         -- True <=> the rhs is cheap, or we want to treat it
218                         --          as cheap (INLINE things)     
219         -> Int          -- Bomb out if size gets bigger than this
220         -> CoreExpr     -- Expression to look at
221         -> (Arity, UnfoldingGuidance)
222 calcUnfoldingGuidance expr_is_cheap bOMB_OUT_SIZE expr
223   = case collectBinders expr of { (bndrs, body) ->
224     let
225         val_bndrs   = filter isId bndrs
226         n_val_bndrs = length val_bndrs
227
228         guidance 
229           = case (sizeExpr (iUnbox bOMB_OUT_SIZE) val_bndrs body) of
230               TooBig -> UnfNever
231               SizeIs size cased_bndrs scrut_discount
232                 | uncondInline n_val_bndrs (iBox size)
233                 , expr_is_cheap
234                 -> UnfWhen unSaturatedOk boringCxtOk   -- Note [INLINE for small functions]
235                 | otherwise
236                 -> UnfIfGoodArgs { ug_args  = map (discount cased_bndrs) val_bndrs
237                                  , ug_size  = iBox size
238                                  , ug_res   = iBox scrut_discount }
239
240         discount cbs bndr
241            = foldlBag (\acc (b',n) -> if bndr==b' then acc+n else acc) 
242                       0 cbs
243     in
244     (n_val_bndrs, guidance) }
245 \end{code}
246
247 Note [Computing the size of an expression]
248 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
249 The basic idea of sizeExpr is obvious enough: count nodes.  But getting the
250 heuristics right has taken a long time.  Here's the basic strategy:
251
252     * Variables, literals: 0
253       (Exception for string literals, see litSize.)
254
255     * Function applications (f e1 .. en): 1 + #value args
256
257     * Constructor applications: 1, regardless of #args
258
259     * Let(rec): 1 + size of components
260
261     * Note, cast: 0
262
263 Examples
264
265   Size  Term
266   --------------
267     0     42#
268     0     x
269     0     True
270     2     f x
271     1     Just x
272     4     f (g x)
273
274 Notice that 'x' counts 0, while (f x) counts 2.  That's deliberate: there's
275 a function call to account for.  Notice also that constructor applications 
276 are very cheap, because exposing them to a caller is so valuable.
277
278
279 Note [Do not inline top-level bottoming functions]
280 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
281 The FloatOut pass has gone to some trouble to float out calls to 'error' 
282 and similar friends.  See Note [Bottoming floats] in SetLevels.
283 Do not re-inline them!  But we *do* still inline if they are very small
284 (the uncondInline stuff).
285
286
287 Note [INLINE for small functions]
288 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
289 Consider        {-# INLINE f #-}
290                 f x = Just x
291                 g y = f y
292 Then f's RHS is no larger than its LHS, so we should inline it into
293 even the most boring context.  In general, f the function is
294 sufficiently small that its body is as small as the call itself, the
295 inline unconditionally, regardless of how boring the context is.
296
297 Things to note:
298
299  * We inline *unconditionally* if inlined thing is smaller (using sizeExpr)
300    than the thing it's replacing.  Notice that
301       (f x) --> (g 3)             -- YES, unconditionally
302       (f x) --> x : []            -- YES, *even though* there are two
303                                   --      arguments to the cons
304       x     --> g 3               -- NO
305       x     --> Just v            -- NO
306
307   It's very important not to unconditionally replace a variable by
308   a non-atomic term.
309
310 * We do this even if the thing isn't saturated, else we end up with the
311   silly situation that
312      f x y = x
313      ...map (f 3)...
314   doesn't inline.  Even in a boring context, inlining without being
315   saturated will give a lambda instead of a PAP, and will be more
316   efficient at runtime.
317
318 * However, when the function's arity > 0, we do insist that it 
319   has at least one value argument at the call site.  Otherwise we find this:
320        f = /\a \x:a. x
321        d = /\b. MkD (f b)
322   If we inline f here we get
323        d = /\b. MkD (\x:b. x)
324   and then prepareRhs floats out the argument, abstracting the type
325   variables, so we end up with the original again!
326
327
328 \begin{code}
329 uncondInline :: Arity -> Int -> Bool
330 -- Inline unconditionally if there no size increase
331 -- Size of call is arity (+1 for the function)
332 -- See Note [INLINE for small functions]
333 uncondInline arity size 
334   | arity == 0 = size == 0
335   | otherwise  = size <= arity + 1
336 \end{code}
337
338
339 \begin{code}
340 sizeExpr :: FastInt         -- Bomb out if it gets bigger than this
341          -> [Id]            -- Arguments; we're interested in which of these
342                             -- get case'd
343          -> CoreExpr
344          -> ExprSize
345
346 -- Note [Computing the size of an expression]
347
348 sizeExpr bOMB_OUT_SIZE top_args expr
349   = size_up expr
350   where
351     size_up (Cast e _) = size_up e
352     size_up (Note _ e) = size_up e
353     size_up (Type _)   = sizeZero           -- Types cost nothing
354     size_up (Coercion _) = sizeZero
355     size_up (Lit lit)  = sizeN (litSize lit)
356     size_up (Var f)    = size_up_call f []  -- Make sure we get constructor
357                                             -- discounts even on nullary constructors
358
359     size_up (App fun (Type _)) = size_up fun
360     size_up (App fun (Coercion _)) = size_up fun
361     size_up (App fun arg)      = size_up arg  `addSizeNSD`
362                                  size_up_app fun [arg]
363
364     size_up (Lam b e) | isId b    = lamScrutDiscount (size_up e `addSizeN` 1)
365                       | otherwise = size_up e
366
367     size_up (Let (NonRec binder rhs) body)
368       = size_up rhs             `addSizeNSD`
369         size_up body            `addSizeN`
370         (if isUnLiftedType (idType binder) then 0 else 1)
371                 -- For the allocation
372                 -- If the binder has an unlifted type there is no allocation
373
374     size_up (Let (Rec pairs) body)
375       = foldr (addSizeNSD . size_up . snd) 
376               (size_up body `addSizeN` length pairs)    -- (length pairs) for the allocation
377               pairs
378
379     size_up (Case (Var v) _ _ alts) 
380         | v `elem` top_args             -- We are scrutinising an argument variable
381         = alts_size (foldr1 addAltSize alt_sizes)
382                     (foldr1 maxSize alt_sizes)
383                 -- Good to inline if an arg is scrutinised, because
384                 -- that may eliminate allocation in the caller
385                 -- And it eliminates the case itself
386         where
387           alt_sizes = map size_up_alt alts
388
389                 -- alts_size tries to compute a good discount for
390                 -- the case when we are scrutinising an argument variable
391           alts_size (SizeIs tot tot_disc tot_scrut)  -- Size of all alternatives
392                     (SizeIs max _        _)          -- Size of biggest alternative
393                 = SizeIs tot (unitBag (v, iBox (_ILIT(2) +# tot -# max)) `unionBags` tot_disc) tot_scrut
394                         -- If the variable is known, we produce a discount that
395                         -- will take us back to 'max', the size of the largest alternative
396                         -- The 1+ is a little discount for reduced allocation in the caller
397                         --
398                         -- Notice though, that we return tot_disc, the total discount from 
399                         -- all branches.  I think that's right.
400
401           alts_size tot_size _ = tot_size
402
403     size_up (Case e b _ alts) = size_up e  `addSizeNSD`
404                                 foldr (addAltSize . size_up_alt) case_size alts
405       where
406           case_size
407            | is_inline_scrut e, not (lengthExceeds alts 1)  = sizeN (-1)
408            | otherwise = sizeZero
409                 -- Normally we don't charge for the case itself, but
410                 -- we charge one per alternative (see size_up_alt,
411                 -- below) to account for the cost of the info table
412                 -- and comparisons.
413                 --
414                 -- However, in certain cases (see is_inline_scrut
415                 -- below), no code is generated for the case unless
416                 -- there are multiple alts.  In these cases we
417                 -- subtract one, making the first alt free.
418                 -- e.g. case x# +# y# of _ -> ...   should cost 1
419                 --      case touch# x# of _ -> ...  should cost 0
420                 -- (see #4978)
421                 --
422                 -- I would like to not have the "not (lengthExceeds alts 1)"
423                 -- condition above, but without that some programs got worse
424                 -- (spectral/hartel/event and spectral/para).  I don't fully
425                 -- understand why. (SDM 24/5/11)
426
427                 -- unboxed variables, inline primops and unsafe foreign calls
428                 -- are all "inline" things:
429           is_inline_scrut (Var v) = isUnLiftedType (idType v)
430           is_inline_scrut scrut
431               | (Var f, _) <- collectArgs scrut
432                 = case idDetails f of
433                     FCallId fc  -> not (isSafeForeignCall fc)
434                     PrimOpId op -> not (primOpOutOfLine op)
435                     _other      -> False
436               | otherwise
437                 = False
438
439     ------------ 
440     -- size_up_app is used when there's ONE OR MORE value args
441     size_up_app (App fun arg) args 
442         | isTyCoArg arg            = size_up_app fun args
443         | otherwise                = size_up arg  `addSizeNSD`
444                                      size_up_app fun (arg:args)
445     size_up_app (Var fun)     args = size_up_call fun args
446     size_up_app other         args = size_up other `addSizeN` length args
447
448     ------------ 
449     size_up_call :: Id -> [CoreExpr] -> ExprSize
450     size_up_call fun val_args
451        = case idDetails fun of
452            FCallId _        -> sizeN opt_UF_DearOp
453            DataConWorkId dc -> conSize    dc (length val_args)
454            PrimOpId op      -> primOpSize op (length val_args)
455            ClassOpId _      -> classOpSize top_args val_args
456            _                -> funSize top_args fun (length val_args)
457
458     ------------ 
459     size_up_alt (_con, _bndrs, rhs) = size_up rhs `addSizeN` 1
460         -- Don't charge for args, so that wrappers look cheap
461         -- (See comments about wrappers with Case)
462         --
463         -- IMPORATANT: *do* charge 1 for the alternative, else we 
464         -- find that giant case nests are treated as practically free
465         -- A good example is Foreign.C.Error.errrnoToIOError
466
467     ------------
468         -- These addSize things have to be here because
469         -- I don't want to give them bOMB_OUT_SIZE as an argument
470     addSizeN TooBig          _  = TooBig
471     addSizeN (SizeIs n xs d) m  = mkSizeIs bOMB_OUT_SIZE (n +# iUnbox m) xs d
472     
473         -- addAltSize is used to add the sizes of case alternatives
474     addAltSize TooBig            _      = TooBig
475     addAltSize _                 TooBig = TooBig
476     addAltSize (SizeIs n1 xs d1) (SizeIs n2 ys d2) 
477         = mkSizeIs bOMB_OUT_SIZE (n1 +# n2) 
478                                  (xs `unionBags` ys) 
479                                  (d1 +# d2)   -- Note [addAltSize result discounts]
480
481         -- This variant ignores the result discount from its LEFT argument
482         -- It's used when the second argument isn't part of the result
483     addSizeNSD TooBig            _      = TooBig
484     addSizeNSD _                 TooBig = TooBig
485     addSizeNSD (SizeIs n1 xs _) (SizeIs n2 ys d2) 
486         = mkSizeIs bOMB_OUT_SIZE (n1 +# n2) 
487                                  (xs `unionBags` ys) 
488                                  d2  -- Ignore d1
489 \end{code}
490
491 \begin{code}
492 -- | Finds a nominal size of a string literal.
493 litSize :: Literal -> Int
494 -- Used by CoreUnfold.sizeExpr
495 litSize (MachStr str) = 1 + ((lengthFS str + 3) `div` 4)
496         -- If size could be 0 then @f "x"@ might be too small
497         -- [Sept03: make literal strings a bit bigger to avoid fruitless 
498         --  duplication of little strings]
499 litSize _other = 0    -- Must match size of nullary constructors
500                       -- Key point: if  x |-> 4, then x must inline unconditionally
501                       --            (eg via case binding)
502
503 classOpSize :: [Id] -> [CoreExpr] -> ExprSize
504 -- See Note [Conlike is interesting]
505 classOpSize _ [] 
506   = sizeZero
507 classOpSize top_args (arg1 : other_args)
508   = SizeIs (iUnbox size) arg_discount (_ILIT(0))
509   where
510     size = 2 + length other_args
511     -- If the class op is scrutinising a lambda bound dictionary then
512     -- give it a discount, to encourage the inlining of this function
513     -- The actual discount is rather arbitrarily chosen
514     arg_discount = case arg1 of
515                      Var dict | dict `elem` top_args 
516                               -> unitBag (dict, opt_UF_DictDiscount)
517                      _other   -> emptyBag
518                      
519 funSize :: [Id] -> Id -> Int -> ExprSize
520 -- Size for functions that are not constructors or primops
521 -- Note [Function applications]
522 funSize top_args fun n_val_args
523   | fun `hasKey` buildIdKey   = buildSize
524   | fun `hasKey` augmentIdKey = augmentSize
525   | otherwise = SizeIs (iUnbox size) arg_discount (iUnbox res_discount)
526   where
527     some_val_args = n_val_args > 0
528
529     arg_discount | some_val_args && fun `elem` top_args
530                  = unitBag (fun, opt_UF_FunAppDiscount)
531                  | otherwise = emptyBag
532         -- If the function is an argument and is applied
533         -- to some values, give it an arg-discount
534
535     res_discount | idArity fun > n_val_args = opt_UF_FunAppDiscount
536                  | otherwise                = 0
537         -- If the function is partially applied, show a result discount
538
539     size | some_val_args = 1 + n_val_args
540          | otherwise     = 0
541         -- The 1+ is for the function itself
542         -- Add 1 for each non-trivial arg;
543         -- the allocation cost, as in let(rec)
544   
545
546 conSize :: DataCon -> Int -> ExprSize
547 conSize dc n_val_args
548   | n_val_args == 0 = SizeIs (_ILIT(0)) emptyBag (_ILIT(1))     -- Like variables
549
550 -- See Note [Constructor size]
551   | isUnboxedTupleCon dc = SizeIs (_ILIT(0)) emptyBag (iUnbox n_val_args +# _ILIT(1))
552
553 -- See Note [Unboxed tuple result discount]
554 --  | isUnboxedTupleCon dc = SizeIs (_ILIT(0)) emptyBag (_ILIT(0))
555
556 -- See Note [Constructor size]
557   | otherwise = SizeIs (_ILIT(1)) emptyBag (iUnbox n_val_args +# _ILIT(1))
558 \end{code}
559
560 Note [Constructor size]
561 ~~~~~~~~~~~~~~~~~~~~~~~
562 Treat a constructors application as size 1, regardless of how many
563 arguments it has; we are keen to expose them (and we charge separately
564 for their args).  We can't treat them as size zero, else we find that
565 (Just x) has size 0, which is the same as a lone variable; and hence
566 'v' will always be replaced by (Just x), where v is bound to Just x.
567
568 However, unboxed tuples count as size zero. I found occasions where we had 
569         f x y z = case op# x y z of { s -> (# s, () #) }
570 and f wasn't getting inlined.
571
572 Note [Unboxed tuple result discount]
573 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
574 I tried giving unboxed tuples a *result discount* of zero (see the
575 commented-out line).  Why?  When returned as a result they do not
576 allocate, so maybe we don't want to charge so much for them If you
577 have a non-zero discount here, we find that workers often get inlined
578 back into wrappers, because it look like
579     f x = case $wf x of (# a,b #) -> (a,b)
580 and we are keener because of the case.  However while this change
581 shrank binary sizes by 0.5% it also made spectral/boyer allocate 5%
582 more. All other changes were very small. So it's not a big deal but I
583 didn't adopt the idea.
584
585 \begin{code}
586 primOpSize :: PrimOp -> Int -> ExprSize
587 primOpSize op n_val_args
588  | not (primOpIsDupable op) = sizeN opt_UF_DearOp
589  | not (primOpOutOfLine op) = sizeN 1
590         -- Be very keen to inline simple primops.
591         -- We give a discount of 1 for each arg so that (op# x y z) costs 2.
592         -- We can't make it cost 1, else we'll inline let v = (op# x y z) 
593         -- at every use of v, which is excessive.
594         --
595         -- A good example is:
596         --      let x = +# p q in C {x}
597         -- Even though x get's an occurrence of 'many', its RHS looks cheap,
598         -- and there's a good chance it'll get inlined back into C's RHS. Urgh!
599
600  | otherwise = sizeN n_val_args
601
602
603 buildSize :: ExprSize
604 buildSize = SizeIs (_ILIT(0)) emptyBag (_ILIT(4))
605         -- We really want to inline applications of build
606         -- build t (\cn -> e) should cost only the cost of e (because build will be inlined later)
607         -- Indeed, we should add a result_discount becuause build is 
608         -- very like a constructor.  We don't bother to check that the
609         -- build is saturated (it usually is).  The "-2" discounts for the \c n, 
610         -- The "4" is rather arbitrary.
611
612 augmentSize :: ExprSize
613 augmentSize = SizeIs (_ILIT(0)) emptyBag (_ILIT(4))
614         -- Ditto (augment t (\cn -> e) ys) should cost only the cost of
615         -- e plus ys. The -2 accounts for the \cn 
616
617 -- When we return a lambda, give a discount if it's used (applied)
618 lamScrutDiscount :: ExprSize -> ExprSize
619 lamScrutDiscount (SizeIs n vs _) = SizeIs n vs (iUnbox opt_UF_FunAppDiscount)
620 lamScrutDiscount TooBig          = TooBig
621 \end{code}
622
623 Note [addAltSize result discounts]
624 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
625 When adding the size of alternatives, we *add* the result discounts
626 too, rather than take the *maximum*.  For a multi-branch case, this
627 gives a discount for each branch that returns a constructor, making us
628 keener to inline.  I did try using 'max' instead, but it makes nofib 
629 'rewrite' and 'puzzle' allocate significantly more, and didn't make
630 binary sizes shrink significantly either.
631
632 Note [Discounts and thresholds]
633 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
634 Constants for discounts and thesholds are defined in main/StaticFlags,
635 all of form opt_UF_xxxx.   They are:
636
637 opt_UF_CreationThreshold (45)
638      At a definition site, if the unfolding is bigger than this, we
639      may discard it altogether
640
641 opt_UF_UseThreshold (6)
642      At a call site, if the unfolding, less discounts, is smaller than
643      this, then it's small enough inline
644
645 opt_UF_KeennessFactor (1.5)
646      Factor by which the discounts are multiplied before 
647      subtracting from size
648
649 opt_UF_DictDiscount (1)
650      The discount for each occurrence of a dictionary argument
651      as an argument of a class method.  Should be pretty small
652      else big functions may get inlined
653
654 opt_UF_FunAppDiscount (6)
655      Discount for a function argument that is applied.  Quite
656      large, because if we inline we avoid the higher-order call.
657
658 opt_UF_DearOp (4)
659      The size of a foreign call or not-dupable PrimOp
660
661
662 Note [Function applications]
663 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
664 In a function application (f a b)
665
666   - If 'f' is an argument to the function being analysed, 
667     and there's at least one value arg, record a FunAppDiscount for f
668
669   - If the application if a PAP (arity > 2 in this example)
670     record a *result* discount (because inlining
671     with "extra" args in the call may mean that we now 
672     get a saturated application)
673
674 Code for manipulating sizes
675
676 \begin{code}
677 data ExprSize = TooBig
678               | SizeIs FastInt          -- Size found
679                        (Bag (Id,Int))   -- Arguments cased herein, and discount for each such
680                        FastInt          -- Size to subtract if result is scrutinised 
681                                         -- by a case expression
682
683 instance Outputable ExprSize where
684   ppr TooBig         = ptext (sLit "TooBig")
685   ppr (SizeIs a _ c) = brackets (int (iBox a) <+> int (iBox c))
686
687 -- subtract the discount before deciding whether to bale out. eg. we
688 -- want to inline a large constructor application into a selector:
689 --      tup = (a_1, ..., a_99)
690 --      x = case tup of ...
691 --
692 mkSizeIs :: FastInt -> FastInt -> Bag (Id, Int) -> FastInt -> ExprSize
693 mkSizeIs max n xs d | (n -# d) ># max = TooBig
694                     | otherwise       = SizeIs n xs d
695  
696 maxSize :: ExprSize -> ExprSize -> ExprSize
697 maxSize TooBig         _                                  = TooBig
698 maxSize _              TooBig                             = TooBig
699 maxSize s1@(SizeIs n1 _ _) s2@(SizeIs n2 _ _) | n1 ># n2  = s1
700                                               | otherwise = s2
701
702 sizeZero :: ExprSize
703 sizeN :: Int -> ExprSize
704
705 sizeZero = SizeIs (_ILIT(0))  emptyBag (_ILIT(0))
706 sizeN n  = SizeIs (iUnbox n) emptyBag (_ILIT(0))
707 \end{code}
708
709
710 %************************************************************************
711 %*                                                                      *
712 \subsection[considerUnfolding]{Given all the info, do (not) do the unfolding}
713 %*                                                                      *
714 %************************************************************************
715
716 We use 'couldBeSmallEnoughToInline' to avoid exporting inlinings that
717 we ``couldn't possibly use'' on the other side.  Can be overridden w/
718 flaggery.  Just the same as smallEnoughToInline, except that it has no
719 actual arguments.
720
721 \begin{code}
722 couldBeSmallEnoughToInline :: Int -> CoreExpr -> Bool
723 couldBeSmallEnoughToInline threshold rhs 
724   = case sizeExpr (iUnbox threshold) [] body of
725        TooBig -> False
726        _      -> True
727   where
728     (_, body) = collectBinders rhs
729
730 ----------------
731 smallEnoughToInline :: Unfolding -> Bool
732 smallEnoughToInline (CoreUnfolding {uf_guidance = UnfIfGoodArgs {ug_size = size}})
733   = size <= opt_UF_UseThreshold
734 smallEnoughToInline _
735   = False
736
737 ----------------
738 certainlyWillInline :: Unfolding -> Bool
739   -- Sees if the unfolding is pretty certain to inline  
740 certainlyWillInline (CoreUnfolding { uf_is_cheap = is_cheap, uf_arity = n_vals, uf_guidance = guidance })
741   = case guidance of
742       UnfNever      -> False
743       UnfWhen {}    -> True
744       UnfIfGoodArgs { ug_size = size} 
745                     -> is_cheap && size - (n_vals +1) <= opt_UF_UseThreshold
746
747 certainlyWillInline _
748   = False
749 \end{code}
750
751 %************************************************************************
752 %*                                                                      *
753 \subsection{callSiteInline}
754 %*                                                                      *
755 %************************************************************************
756
757 This is the key function.  It decides whether to inline a variable at a call site
758
759 callSiteInline is used at call sites, so it is a bit more generous.
760 It's a very important function that embodies lots of heuristics.
761 A non-WHNF can be inlined if it doesn't occur inside a lambda,
762 and occurs exactly once or 
763     occurs once in each branch of a case and is small
764
765 If the thing is in WHNF, there's no danger of duplicating work, 
766 so we can inline if it occurs once, or is small
767
768 NOTE: we don't want to inline top-level functions that always diverge.
769 It just makes the code bigger.  Tt turns out that the convenient way to prevent
770 them inlining is to give them a NOINLINE pragma, which we do in 
771 StrictAnal.addStrictnessInfoToTopId
772
773 \begin{code}
774 callSiteInline :: DynFlags
775                -> Id                    -- The Id
776                -> Bool                  -- True <=> unfolding is active
777                -> Bool                  -- True if there are are no arguments at all (incl type args)
778                -> [ArgSummary]          -- One for each value arg; True if it is interesting
779                -> CallCtxt              -- True <=> continuation is interesting
780                -> Maybe CoreExpr        -- Unfolding, if any
781
782 instance Outputable ArgSummary where
783   ppr TrivArg    = ptext (sLit "TrivArg")
784   ppr NonTrivArg = ptext (sLit "NonTrivArg")
785   ppr ValueArg   = ptext (sLit "ValueArg")
786
787 data CallCtxt = BoringCtxt
788
789               | ArgCtxt         -- We are somewhere in the argument of a function
790                         Bool    -- True  <=> we're somewhere in the RHS of function with rules
791                                 -- False <=> we *are* the argument of a function with non-zero
792                                 --           arg discount
793                                 --        OR 
794                                 --           we *are* the RHS of a let  Note [RHS of lets]
795                                 -- In both cases, be a little keener to inline
796
797               | ValAppCtxt      -- We're applied to at least one value arg
798                                 -- This arises when we have ((f x |> co) y)
799                                 -- Then the (f x) has argument 'x' but in a ValAppCtxt
800
801               | CaseCtxt        -- We're the scrutinee of a case
802                                 -- that decomposes its scrutinee
803
804 instance Outputable CallCtxt where
805   ppr BoringCtxt      = ptext (sLit "BoringCtxt")
806   ppr (ArgCtxt rules) = ptext (sLit "ArgCtxt") <+> ppr rules
807   ppr CaseCtxt        = ptext (sLit "CaseCtxt")
808   ppr ValAppCtxt      = ptext (sLit "ValAppCtxt")
809
810 callSiteInline dflags id active_unfolding lone_variable arg_infos cont_info
811   = case idUnfolding id of 
812       -- idUnfolding checks for loop-breakers, returning NoUnfolding
813       -- Things with an INLINE pragma may have an unfolding *and* 
814       -- be a loop breaker  (maybe the knot is not yet untied)
815         CoreUnfolding { uf_tmpl = unf_template, uf_is_top = is_top 
816                       , uf_is_cheap = is_cheap, uf_arity = uf_arity
817                       , uf_guidance = guidance, uf_expandable = is_exp }
818           | active_unfolding -> tryUnfolding dflags id lone_variable 
819                                     arg_infos cont_info unf_template is_top 
820                                     is_cheap is_exp uf_arity guidance
821           | otherwise    -> Nothing
822         NoUnfolding      -> Nothing 
823         OtherCon {}      -> Nothing 
824         DFunUnfolding {} -> Nothing     -- Never unfold a DFun
825
826 tryUnfolding :: DynFlags -> Id -> Bool -> [ArgSummary] -> CallCtxt
827              -> CoreExpr -> Bool -> Bool -> Bool -> Arity -> UnfoldingGuidance
828              -> Maybe CoreExpr  
829 tryUnfolding dflags id lone_variable 
830              arg_infos cont_info unf_template is_top 
831              is_cheap is_exp uf_arity guidance
832                         -- uf_arity will typically be equal to (idArity id), 
833                         -- but may be less for InlineRules
834  | dopt Opt_D_dump_inlinings dflags && dopt Opt_D_verbose_core2core dflags
835  = pprTrace ("Considering inlining: " ++ showSDoc (ppr id))
836                  (vcat [text "arg infos" <+> ppr arg_infos,
837                         text "uf arity" <+> ppr uf_arity,
838                         text "interesting continuation" <+> ppr cont_info,
839                         text "some_benefit" <+> ppr some_benefit,
840                         text "is exp:" <+> ppr is_exp,
841                         text "is cheap:" <+> ppr is_cheap,
842                         text "guidance" <+> ppr guidance,
843                         extra_doc,
844                         text "ANSWER =" <+> if yes_or_no then text "YES" else text "NO"])
845                  result
846   | otherwise  = result
847
848   where
849     n_val_args = length arg_infos
850     saturated  = n_val_args >= uf_arity
851
852     result | yes_or_no = Just unf_template
853            | otherwise = Nothing
854
855     interesting_args = any nonTriv arg_infos 
856         -- NB: (any nonTriv arg_infos) looks at the
857         -- over-saturated args too which is "wrong"; 
858         -- but if over-saturated we inline anyway.
859
860            -- some_benefit is used when the RHS is small enough
861            -- and the call has enough (or too many) value
862            -- arguments (ie n_val_args >= arity). But there must
863            -- be *something* interesting about some argument, or the
864            -- result context, to make it worth inlining
865     some_benefit 
866        | not saturated = interesting_args       -- Under-saturated
867                                         -- Note [Unsaturated applications]
868        | n_val_args > uf_arity = True   -- Over-saturated
869        | otherwise = interesting_args   -- Saturated
870                   || interesting_saturated_call 
871
872     interesting_saturated_call 
873       = case cont_info of
874           BoringCtxt -> not is_top && uf_arity > 0        -- Note [Nested functions]
875           CaseCtxt   -> not (lone_variable && is_cheap)   -- Note [Lone variables]
876           ArgCtxt {} -> uf_arity > 0                      -- Note [Inlining in ArgCtxt]
877           ValAppCtxt -> True                              -- Note [Cast then apply]
878
879     (yes_or_no, extra_doc)
880       = case guidance of
881           UnfNever -> (False, empty)
882
883           UnfWhen unsat_ok boring_ok 
884              -> (enough_args && (boring_ok || some_benefit), empty )
885              where      -- See Note [INLINE for small functions]
886                enough_args = saturated || (unsat_ok && n_val_args > 0)
887
888           UnfIfGoodArgs { ug_args = arg_discounts, ug_res = res_discount, ug_size = size }
889              -> ( is_cheap && some_benefit && small_enough
890                 , (text "discounted size =" <+> int discounted_size) )
891              where
892                discounted_size = size - discount
893                small_enough = discounted_size <= opt_UF_UseThreshold
894                discount = computeDiscount uf_arity arg_discounts 
895                                           res_discount arg_infos cont_info
896 \end{code}
897
898 Note [RHS of lets]
899 ~~~~~~~~~~~~~~~~~~
900 Be a tiny bit keener to inline in the RHS of a let, because that might
901 lead to good thing later
902      f y = (y,y,y)
903      g y = let x = f y in ...(case x of (a,b,c) -> ...) ...
904 We'd inline 'f' if the call was in a case context, and it kind-of-is,
905 only we can't see it.  So we treat the RHS of a let as not-totally-boring.
906     
907 Note [Unsaturated applications]
908 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
909 When a call is not saturated, we *still* inline if one of the
910 arguments has interesting structure.  That's sometimes very important.
911 A good example is the Ord instance for Bool in Base:
912
913  Rec {
914     $fOrdBool =GHC.Classes.D:Ord
915                  @ Bool
916                  ...
917                  $cmin_ajX
918
919     $cmin_ajX [Occ=LoopBreaker] :: Bool -> Bool -> Bool
920     $cmin_ajX = GHC.Classes.$dmmin @ Bool $fOrdBool
921   }
922
923 But the defn of GHC.Classes.$dmmin is:
924
925   $dmmin :: forall a. GHC.Classes.Ord a => a -> a -> a
926     {- Arity: 3, HasNoCafRefs, Strictness: SLL,
927        Unfolding: (\ @ a $dOrd :: GHC.Classes.Ord a x :: a y :: a ->
928                    case @ a GHC.Classes.<= @ a $dOrd x y of wild {
929                      GHC.Types.False -> y GHC.Types.True -> x }) -}
930
931 We *really* want to inline $dmmin, even though it has arity 3, in
932 order to unravel the recursion.
933
934
935 Note [Things to watch]
936 ~~~~~~~~~~~~~~~~~~~~~~
937 *   { y = I# 3; x = y `cast` co; ...case (x `cast` co) of ... }
938     Assume x is exported, so not inlined unconditionally.
939     Then we want x to inline unconditionally; no reason for it 
940     not to, and doing so avoids an indirection.
941
942 *   { x = I# 3; ....f x.... }
943     Make sure that x does not inline unconditionally!  
944     Lest we get extra allocation.
945
946 Note [Inlining an InlineRule]
947 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
948 An InlineRules is used for
949   (a) programmer INLINE pragmas
950   (b) inlinings from worker/wrapper
951
952 For (a) the RHS may be large, and our contract is that we *only* inline
953 when the function is applied to all the arguments on the LHS of the
954 source-code defn.  (The uf_arity in the rule.)
955
956 However for worker/wrapper it may be worth inlining even if the 
957 arity is not satisfied (as we do in the CoreUnfolding case) so we don't
958 require saturation.
959
960
961 Note [Nested functions]
962 ~~~~~~~~~~~~~~~~~~~~~~~
963 If a function has a nested defn we also record some-benefit, on the
964 grounds that we are often able to eliminate the binding, and hence the
965 allocation, for the function altogether; this is good for join points.
966 But this only makes sense for *functions*; inlining a constructor
967 doesn't help allocation unless the result is scrutinised.  UNLESS the
968 constructor occurs just once, albeit possibly in multiple case
969 branches.  Then inlining it doesn't increase allocation, but it does
970 increase the chance that the constructor won't be allocated at all in
971 the branches that don't use it.
972
973 Note [Cast then apply]
974 ~~~~~~~~~~~~~~~~~~~~~~
975 Consider
976    myIndex = __inline_me ( (/\a. <blah>) |> co )
977    co :: (forall a. a -> a) ~ (forall a. T a)
978      ... /\a.\x. case ((myIndex a) |> sym co) x of { ... } ...
979
980 We need to inline myIndex to unravel this; but the actual call (myIndex a) has
981 no value arguments.  The ValAppCtxt gives it enough incentive to inline.
982
983 Note [Inlining in ArgCtxt]
984 ~~~~~~~~~~~~~~~~~~~~~~~~~~
985 The condition (arity > 0) here is very important, because otherwise
986 we end up inlining top-level stuff into useless places; eg
987    x = I# 3#
988    f = \y.  g x
989 This can make a very big difference: it adds 16% to nofib 'integer' allocs,
990 and 20% to 'power'.
991
992 At one stage I replaced this condition by 'True' (leading to the above 
993 slow-down).  The motivation was test eyeball/inline1.hs; but that seems
994 to work ok now.
995
996 NOTE: arguably, we should inline in ArgCtxt only if the result of the
997 call is at least CONLIKE.  At least for the cases where we use ArgCtxt
998 for the RHS of a 'let', we only profit from the inlining if we get a 
999 CONLIKE thing (modulo lets).
1000
1001 Note [Lone variables]   See also Note [Interaction of exprIsCheap and lone variables]
1002 ~~~~~~~~~~~~~~~~~~~~~   which appears below
1003 The "lone-variable" case is important.  I spent ages messing about
1004 with unsatisfactory varaints, but this is nice.  The idea is that if a
1005 variable appears all alone
1006
1007         as an arg of lazy fn, or rhs    BoringCtxt
1008         as scrutinee of a case          CaseCtxt
1009         as arg of a fn                  ArgCtxt
1010 AND
1011         it is bound to a cheap expression
1012
1013 then we should not inline it (unless there is some other reason,
1014 e.g. is is the sole occurrence).  That is what is happening at 
1015 the use of 'lone_variable' in 'interesting_saturated_call'.
1016
1017 Why?  At least in the case-scrutinee situation, turning
1018         let x = (a,b) in case x of y -> ...
1019 into
1020         let x = (a,b) in case (a,b) of y -> ...
1021 and thence to 
1022         let x = (a,b) in let y = (a,b) in ...
1023 is bad if the binding for x will remain.
1024
1025 Another example: I discovered that strings
1026 were getting inlined straight back into applications of 'error'
1027 because the latter is strict.
1028         s = "foo"
1029         f = \x -> ...(error s)...
1030
1031 Fundamentally such contexts should not encourage inlining because the
1032 context can ``see'' the unfolding of the variable (e.g. case or a
1033 RULE) so there's no gain.  If the thing is bound to a value.
1034
1035 However, watch out:
1036
1037  * Consider this:
1038         foo = _inline_ (\n. [n])
1039         bar = _inline_ (foo 20)
1040         baz = \n. case bar of { (m:_) -> m + n }
1041    Here we really want to inline 'bar' so that we can inline 'foo'
1042    and the whole thing unravels as it should obviously do.  This is 
1043    important: in the NDP project, 'bar' generates a closure data
1044    structure rather than a list. 
1045
1046    So the non-inlining of lone_variables should only apply if the
1047    unfolding is regarded as cheap; because that is when exprIsConApp_maybe
1048    looks through the unfolding.  Hence the "&& is_cheap" in the
1049    InlineRule branch.
1050
1051  * Even a type application or coercion isn't a lone variable.
1052    Consider
1053         case $fMonadST @ RealWorld of { :DMonad a b c -> c }
1054    We had better inline that sucker!  The case won't see through it.
1055
1056    For now, I'm treating treating a variable applied to types 
1057    in a *lazy* context "lone". The motivating example was
1058         f = /\a. \x. BIG
1059         g = /\a. \y.  h (f a)
1060    There's no advantage in inlining f here, and perhaps
1061    a significant disadvantage.  Hence some_val_args in the Stop case
1062
1063 Note [Interaction of exprIsCheap and lone variables]
1064 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1065 The lone-variable test says "don't inline if a case expression
1066 scrutines a lone variable whose unfolding is cheap".  It's very 
1067 important that, under these circumstances, exprIsConApp_maybe
1068 can spot a constructor application. So, for example, we don't
1069 consider
1070         let x = e in (x,x)
1071 to be cheap, and that's good because exprIsConApp_maybe doesn't
1072 think that expression is a constructor application.
1073
1074 I used to test is_value rather than is_cheap, which was utterly
1075 wrong, because the above expression responds True to exprIsHNF.
1076
1077 This kind of thing can occur if you have
1078
1079         {-# INLINE foo #-}
1080         foo = let x = e in (x,x)
1081
1082 which Roman did.
1083
1084 \begin{code}
1085 computeDiscount :: Int -> [Int] -> Int -> [ArgSummary] -> CallCtxt -> Int
1086 computeDiscount n_vals_wanted arg_discounts res_discount arg_infos cont_info
1087         -- We multiple the raw discounts (args_discount and result_discount)
1088         -- ty opt_UnfoldingKeenessFactor because the former have to do with
1089         --  *size* whereas the discounts imply that there's some extra 
1090         --  *efficiency* to be gained (e.g. beta reductions, case reductions) 
1091         -- by inlining.
1092
1093   = 1           -- Discount of 1 because the result replaces the call
1094                 -- so we count 1 for the function itself
1095
1096     + length (take n_vals_wanted arg_infos)
1097                -- Discount of (un-scaled) 1 for each arg supplied, 
1098                -- because the result replaces the call
1099
1100     + round (opt_UF_KeenessFactor * 
1101              fromIntegral (arg_discount + res_discount'))
1102   where
1103     arg_discount = sum (zipWith mk_arg_discount arg_discounts arg_infos)
1104
1105     mk_arg_discount _        TrivArg    = 0 
1106     mk_arg_discount _        NonTrivArg = 1   
1107     mk_arg_discount discount ValueArg   = discount 
1108
1109     res_discount' = case cont_info of
1110                         BoringCtxt  -> 0
1111                         CaseCtxt    -> res_discount
1112                         _other      -> 4 `min` res_discount
1113                 -- res_discount can be very large when a function returns
1114                 -- constructors; but we only want to invoke that large discount
1115                 -- when there's a case continuation.
1116                 -- Otherwise we, rather arbitrarily, threshold it.  Yuk.
1117                 -- But we want to aovid inlining large functions that return 
1118                 -- constructors into contexts that are simply "interesting"
1119 \end{code}
1120
1121 %************************************************************************
1122 %*                                                                      *
1123         Interesting arguments
1124 %*                                                                      *
1125 %************************************************************************
1126
1127 Note [Interesting arguments]
1128 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1129 An argument is interesting if it deserves a discount for unfoldings
1130 with a discount in that argument position.  The idea is to avoid
1131 unfolding a function that is applied only to variables that have no
1132 unfolding (i.e. they are probably lambda bound): f x y z There is
1133 little point in inlining f here.
1134
1135 Generally, *values* (like (C a b) and (\x.e)) deserve discounts.  But
1136 we must look through lets, eg (let x = e in C a b), because the let will
1137 float, exposing the value, if we inline.  That makes it different to
1138 exprIsHNF.
1139
1140 Before 2009 we said it was interesting if the argument had *any* structure
1141 at all; i.e. (hasSomeUnfolding v).  But does too much inlining; see Trac #3016.
1142
1143 But we don't regard (f x y) as interesting, unless f is unsaturated.
1144 If it's saturated and f hasn't inlined, then it's probably not going
1145 to now!
1146
1147 Note [Conlike is interesting]
1148 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1149 Consider
1150         f d = ...((*) d x y)...
1151         ... f (df d')...
1152 where df is con-like. Then we'd really like to inline 'f' so that the
1153 rule for (*) (df d) can fire.  To do this 
1154   a) we give a discount for being an argument of a class-op (eg (*) d)
1155   b) we say that a con-like argument (eg (df d)) is interesting
1156
1157 \begin{code}
1158 data ArgSummary = TrivArg       -- Nothing interesting
1159                 | NonTrivArg    -- Arg has structure
1160                 | ValueArg      -- Arg is a con-app or PAP
1161                                 -- ..or con-like. Note [Conlike is interesting]
1162
1163 interestingArg :: CoreExpr -> ArgSummary
1164 -- See Note [Interesting arguments]
1165 interestingArg e = go e 0
1166   where
1167     -- n is # value args to which the expression is applied
1168     go (Lit {}) _          = ValueArg
1169     go (Var v)  n
1170        | isConLikeId v     = ValueArg   -- Experimenting with 'conlike' rather that
1171                                         --    data constructors here
1172        | idArity v > n     = ValueArg   -- Catches (eg) primops with arity but no unfolding
1173        | n > 0             = NonTrivArg -- Saturated or unknown call
1174        | conlike_unfolding = ValueArg   -- n==0; look for an interesting unfolding
1175                                         -- See Note [Conlike is interesting]
1176        | otherwise         = TrivArg    -- n==0, no useful unfolding
1177        where
1178          conlike_unfolding = isConLikeUnfolding (idUnfolding v)
1179
1180     go (Type _)          _ = TrivArg
1181     go (Coercion _)      _ = TrivArg
1182     go (App fn (Type _)) n = go fn n
1183     go (App fn (Coercion _)) n = go fn n
1184     go (App fn _)        n = go fn (n+1)
1185     go (Note _ a)        n = go a n
1186     go (Cast e _)        n = go e n
1187     go (Lam v e)         n 
1188        | isTyVar v         = go e n
1189        | n>0               = go e (n-1)
1190        | otherwise         = ValueArg
1191     go (Let _ e)         n = case go e n of { ValueArg -> ValueArg; _ -> NonTrivArg }
1192     go (Case {})         _ = NonTrivArg
1193
1194 nonTriv ::  ArgSummary -> Bool
1195 nonTriv TrivArg = False
1196 nonTriv _       = True
1197 \end{code}
1198
1199 %************************************************************************
1200 %*                                                                      *
1201          exprIsConApp_maybe
1202 %*                                                                      *
1203 %************************************************************************
1204
1205 Note [exprIsConApp_maybe]
1206 ~~~~~~~~~~~~~~~~~~~~~~~~~
1207 exprIsConApp_maybe is a very important function.  There are two principal
1208 uses:
1209   * case e of { .... }
1210   * cls_op e, where cls_op is a class operation
1211
1212 In both cases you want to know if e is of form (C e1..en) where C is
1213 a data constructor.
1214
1215 However e might not *look* as if 
1216
1217 \begin{code}
1218 -- | Returns @Just (dc, [t1..tk], [x1..xn])@ if the argument expression is 
1219 -- a *saturated* constructor application of the form @dc t1..tk x1 .. xn@,
1220 -- where t1..tk are the *universally-qantified* type args of 'dc'
1221 exprIsConApp_maybe :: IdUnfoldingFun -> CoreExpr -> Maybe (DataCon, [Type], [CoreExpr])
1222
1223 exprIsConApp_maybe id_unf (Note note expr)
1224   | notSccNote note
1225   = exprIsConApp_maybe id_unf expr
1226         -- We ignore all notes except SCCs.  For example,
1227         --      case _scc_ "foo" (C a b) of
1228         --                      C a b -> e
1229         -- should not be optimised away, because we'll lose the
1230         -- entry count on 'foo'; see Trac #4414
1231
1232 exprIsConApp_maybe id_unf (Cast expr co)
1233   =     -- Here we do the KPush reduction rule as described in the FC paper
1234         -- The transformation applies iff we have
1235         --      (C e1 ... en) `cast` co
1236         -- where co :: (T t1 .. tn) ~ to_ty
1237         -- The left-hand one must be a T, because exprIsConApp returned True
1238         -- but the right-hand one might not be.  (Though it usually will.)
1239
1240     case exprIsConApp_maybe id_unf expr of {
1241         Nothing                          -> Nothing ;
1242         Just (dc, _dc_univ_args, dc_args) -> 
1243
1244     let Pair _from_ty to_ty = coercionKind co
1245         dc_tc = dataConTyCon dc
1246     in
1247     case splitTyConApp_maybe to_ty of {
1248         Nothing -> Nothing ;
1249         Just (to_tc, to_tc_arg_tys) 
1250                 | dc_tc /= to_tc -> Nothing
1251                 -- These two Nothing cases are possible; we might see 
1252                 --      (C x y) `cast` (g :: T a ~ S [a]),
1253                 -- where S is a type function.  In fact, exprIsConApp
1254                 -- will probably not be called in such circumstances,
1255                 -- but there't nothing wrong with it 
1256
1257                 | otherwise  ->
1258     let
1259         tc_arity       = tyConArity dc_tc
1260         dc_univ_tyvars = dataConUnivTyVars dc
1261         dc_ex_tyvars   = dataConExTyVars dc
1262         arg_tys        = dataConRepArgTys dc
1263
1264         (ex_args, val_args) = splitAtList dc_ex_tyvars dc_args
1265
1266         -- Make the "theta" from Fig 3 of the paper
1267         gammas = decomposeCo tc_arity co
1268         theta  = zipOpenCvSubst (dc_univ_tyvars ++ dc_ex_tyvars)
1269                                 (gammas         ++ map mkReflCo (stripTypeArgs ex_args))
1270
1271           -- Cast the value arguments (which include dictionaries)
1272         new_val_args = zipWith cast_arg arg_tys val_args
1273         cast_arg arg_ty arg = mkCoerce (liftCoSubst theta arg_ty) arg
1274     in
1275 #ifdef DEBUG
1276     let dump_doc = vcat [ppr dc,      ppr dc_univ_tyvars, ppr dc_ex_tyvars,
1277                          ppr arg_tys, ppr dc_args,        ppr _dc_univ_args,
1278                          ppr ex_args, ppr val_args]
1279     in
1280     ASSERT2( eqType _from_ty (mkTyConApp dc_tc _dc_univ_args), dump_doc )
1281     ASSERT2( all isTypeArg ex_args, dump_doc )
1282     ASSERT2( equalLength val_args arg_tys, dump_doc )
1283 #endif
1284
1285     Just (dc, to_tc_arg_tys, ex_args ++ new_val_args)
1286     }}
1287
1288 exprIsConApp_maybe id_unf expr 
1289   = analyse expr [] 
1290   where
1291     analyse (App fun arg) args = analyse fun (arg:args)
1292     analyse fun@(Lam {})  args = beta fun [] args 
1293
1294     analyse (Var fun) args
1295         | Just con <- isDataConWorkId_maybe fun
1296         , count isValArg args == idArity fun
1297         , let (univ_ty_args, rest_args) = splitAtList (dataConUnivTyVars con) args
1298         = Just (con, stripTypeArgs univ_ty_args, rest_args)
1299
1300         -- Look through dictionary functions; see Note [Unfolding DFuns]
1301         | DFunUnfolding dfun_nargs con ops <- unfolding
1302         , let sat = length args == dfun_nargs    -- See Note [DFun arity check]
1303           in if sat then True else 
1304              pprTrace "Unsaturated dfun" (ppr fun <+> int dfun_nargs $$ ppr args) False   
1305         , let (dfun_tvs, _n_theta, _cls, dfun_res_tys) = tcSplitDFunTy (idType fun)
1306               subst    = zipOpenTvSubst dfun_tvs (stripTypeArgs (takeList dfun_tvs args))
1307               mk_arg (DFunConstArg e) = e
1308               mk_arg (DFunLamArg i)   = args !! i
1309               mk_arg (DFunPolyArg e)  = mkApps e args
1310         = Just (con, substTys subst dfun_res_tys, map mk_arg ops)
1311
1312         -- Look through unfoldings, but only cheap ones, because
1313         -- we are effectively duplicating the unfolding
1314         | Just rhs <- expandUnfolding_maybe unfolding
1315         = -- pprTrace "expanding" (ppr fun $$ ppr rhs) $
1316           analyse rhs args
1317         where
1318           unfolding = id_unf fun
1319
1320     analyse _ _ = Nothing
1321
1322     -----------
1323     beta (Lam v body) pairs (arg : args) 
1324         | isTyCoArg arg
1325         = beta body ((v,arg):pairs) args 
1326
1327     beta (Lam {}) _ _    -- Un-saturated, or not a type lambda
1328         = Nothing
1329
1330     beta fun pairs args
1331         = analyse (substExpr (text "subst-expr-is-con-app") subst fun) args
1332         where
1333           subst = mkOpenSubst (mkInScopeSet (exprFreeVars fun)) pairs
1334           -- doc = vcat [ppr fun, ppr expr, ppr pairs, ppr args]
1335
1336 stripTypeArgs :: [CoreExpr] -> [Type]
1337 stripTypeArgs args = ASSERT2( all isTypeArg args, ppr args )
1338                      [ty | Type ty <- args]
1339   -- We really do want isTypeArg here, not isTyCoArg!
1340 \end{code}
1341
1342 Note [Unfolding DFuns]
1343 ~~~~~~~~~~~~~~~~~~~~~~
1344 DFuns look like
1345
1346   df :: forall a b. (Eq a, Eq b) -> Eq (a,b)
1347   df a b d_a d_b = MkEqD (a,b) ($c1 a b d_a d_b)
1348                                ($c2 a b d_a d_b)
1349
1350 So to split it up we just need to apply the ops $c1, $c2 etc
1351 to the very same args as the dfun.  It takes a little more work
1352 to compute the type arguments to the dictionary constructor.
1353
1354 Note [DFun arity check]
1355 ~~~~~~~~~~~~~~~~~~~~~~~
1356 Here we check that the total number of supplied arguments (inclding 
1357 type args) matches what the dfun is expecting.  This may be *less*
1358 than the ordinary arity of the dfun: see Note [DFun unfoldings] in CoreSyn