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