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