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