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