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