The Big INLINE Patch: totally reorganise way that INLINE pragmas work
[ghc-hetmet.git] / compiler / simplCore / SimplUtils.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1993-1998
3 %
4 \section[SimplUtils]{The simplifier utilities}
5
6 \begin{code}
7 module SimplUtils (
8         -- Rebuilding
9         mkLam, mkCase, prepareAlts, bindCaseBndr,
10
11         -- Inlining,
12         preInlineUnconditionally, postInlineUnconditionally, 
13         activeInline, activeRule, 
14
15         -- The continuation type
16         SimplCont(..), DupFlag(..), ArgInfo(..),
17         contIsDupable, contResultType, contIsTrivial, contArgs, dropArgs, 
18         countValArgs, countArgs, 
19         mkBoringStop, mkLazyArgStop, contIsRhsOrArg,
20         interestingCallContext, 
21
22         interestingArg, mkArgInfo,
23         
24         abstractFloats
25     ) where
26
27 #include "HsVersions.h"
28
29 import SimplEnv
30 import DynFlags
31 import StaticFlags
32 import CoreSyn
33 import qualified CoreSubst
34 import PprCore
35 import CoreFVs
36 import CoreUtils
37 import CoreArity        ( etaExpand, exprEtaExpandArity )
38 import CoreUnfold
39 import Name
40 import Id
41 import Var      ( isCoVar )
42 import NewDemand
43 import SimplMonad
44 import Type     hiding( substTy )
45 import Coercion ( coercionKind )
46 import TyCon
47 import Unify    ( dataConCannotMatch )
48 import VarSet
49 import BasicTypes
50 import Util
51 import MonadUtils
52 import Outputable
53 import FastString
54
55 import Data.List
56 \end{code}
57
58
59 %************************************************************************
60 %*                                                                      *
61                 The SimplCont type
62 %*                                                                      *
63 %************************************************************************
64
65 A SimplCont allows the simplifier to traverse the expression in a 
66 zipper-like fashion.  The SimplCont represents the rest of the expression,
67 "above" the point of interest.
68
69 You can also think of a SimplCont as an "evaluation context", using
70 that term in the way it is used for operational semantics. This is the
71 way I usually think of it, For example you'll often see a syntax for
72 evaluation context looking like
73         C ::= []  |  C e   |  case C of alts  |  C `cast` co
74 That's the kind of thing we are doing here, and I use that syntax in
75 the comments.
76
77
78 Key points:
79   * A SimplCont describes a *strict* context (just like 
80     evaluation contexts do).  E.g. Just [] is not a SimplCont
81
82   * A SimplCont describes a context that *does not* bind
83     any variables.  E.g. \x. [] is not a SimplCont
84
85 \begin{code}
86 data SimplCont  
87   = Stop                -- An empty context, or hole, []     
88         CallCtxt        -- True <=> There is something interesting about
89                         --          the context, and hence the inliner
90                         --          should be a bit keener (see interestingCallContext)
91                         -- Specifically:
92                         --     This is an argument of a function that has RULES
93                         --     Inlining the call might allow the rule to fire
94
95   | CoerceIt            -- C `cast` co
96         OutCoercion             -- The coercion simplified
97         SimplCont
98
99   | ApplyTo             -- C arg
100         DupFlag 
101         InExpr SimplEnv         -- The argument and its static env
102         SimplCont
103
104   | Select              -- case C of alts
105         DupFlag 
106         InId [InAlt] SimplEnv   -- The case binder, alts, and subst-env
107         SimplCont
108
109   -- The two strict forms have no DupFlag, because we never duplicate them
110   | StrictBind          -- (\x* \xs. e) C
111         InId [InBndr]           -- let x* = [] in e     
112         InExpr SimplEnv         --      is a special case 
113         SimplCont       
114
115   | StrictArg           -- e C
116         OutExpr                 -- e; *always* of form (Var v `App1` e1 .. `App` en)
117         CallCtxt                -- Whether *this* argument position is interesting
118         ArgInfo                 -- Whether the function at the head of e has rules, etc
119         SimplCont               --     plus strictness flags for *further* args
120
121 data ArgInfo 
122   = ArgInfo {
123         ai_rules :: Bool,       -- Function has rules (recursively)
124                                 --      => be keener to inline in all args
125         ai_strs :: [Bool],      -- Strictness of arguments
126                                 --   Usually infinite, but if it is finite it guarantees
127                                 --   that the function diverges after being given
128                                 --   that number of args
129         ai_discs :: [Int]       -- Discounts for arguments; non-zero => be keener to inline
130                                 --   Always infinite
131     }
132
133 instance Outputable SimplCont where
134   ppr (Stop interesting)             = ptext (sLit "Stop") <> brackets (ppr interesting)
135   ppr (ApplyTo dup arg _ cont)       = ((ptext (sLit "ApplyTo") <+> ppr dup <+> pprParendExpr arg)
136                                           {-  $$ nest 2 (pprSimplEnv se) -}) $$ ppr cont
137   ppr (StrictBind b _ _ _ cont)      = (ptext (sLit "StrictBind") <+> ppr b) $$ ppr cont
138   ppr (StrictArg f _ _ cont)         = (ptext (sLit "StrictArg") <+> ppr f) $$ ppr cont
139   ppr (Select dup bndr alts _ cont)  = (ptext (sLit "Select") <+> ppr dup <+> ppr bndr) $$ 
140                                        (nest 4 (ppr alts)) $$ ppr cont 
141   ppr (CoerceIt co cont)             = (ptext (sLit "CoerceIt") <+> ppr co) $$ ppr cont
142
143 data DupFlag = OkToDup | NoDup
144
145 instance Outputable DupFlag where
146   ppr OkToDup = ptext (sLit "ok")
147   ppr NoDup   = ptext (sLit "nodup")
148
149
150
151 -------------------
152 mkBoringStop :: SimplCont
153 mkBoringStop = Stop BoringCtxt
154
155 mkLazyArgStop :: CallCtxt -> SimplCont
156 mkLazyArgStop cci = Stop cci
157
158 -------------------
159 contIsRhsOrArg :: SimplCont -> Bool
160 contIsRhsOrArg (Stop {})       = True
161 contIsRhsOrArg (StrictBind {}) = True
162 contIsRhsOrArg (StrictArg {})  = True
163 contIsRhsOrArg _               = False
164
165 -------------------
166 contIsDupable :: SimplCont -> Bool
167 contIsDupable (Stop {})                  = True
168 contIsDupable (ApplyTo  OkToDup _ _ _)   = True
169 contIsDupable (Select   OkToDup _ _ _ _) = True
170 contIsDupable (CoerceIt _ cont)          = contIsDupable cont
171 contIsDupable _                          = False
172
173 -------------------
174 contIsTrivial :: SimplCont -> Bool
175 contIsTrivial (Stop {})                   = True
176 contIsTrivial (ApplyTo _ (Type _) _ cont) = contIsTrivial cont
177 contIsTrivial (CoerceIt _ cont)           = contIsTrivial cont
178 contIsTrivial _                           = False
179
180 -------------------
181 contResultType :: SimplEnv -> OutType -> SimplCont -> OutType
182 contResultType env ty cont
183   = go cont ty
184   where
185     subst_ty se ty = substTy (se `setInScope` env) ty
186
187     go (Stop {})                      ty = ty
188     go (CoerceIt co cont)             _  = go cont (snd (coercionKind co))
189     go (StrictBind _ bs body se cont) _  = go cont (subst_ty se (exprType (mkLams bs body)))
190     go (StrictArg fn _ _ cont)        _  = go cont (funResultTy (exprType fn))
191     go (Select _ _ alts se cont)      _  = go cont (subst_ty se (coreAltsType alts))
192     go (ApplyTo _ arg se cont)        ty = go cont (apply_to_arg ty arg se)
193
194     apply_to_arg ty (Type ty_arg) se = applyTy ty (subst_ty se ty_arg)
195     apply_to_arg ty _             _  = funResultTy ty
196
197 -------------------
198 countValArgs :: SimplCont -> Int
199 countValArgs (ApplyTo _ (Type _) _ cont) = countValArgs cont
200 countValArgs (ApplyTo _ _        _ cont) = 1 + countValArgs cont
201 countValArgs _                           = 0
202
203 countArgs :: SimplCont -> Int
204 countArgs (ApplyTo _ _ _ cont) = 1 + countArgs cont
205 countArgs _                    = 0
206
207 contArgs :: SimplCont -> ([OutExpr], SimplCont)
208 -- Uses substitution to turn each arg into an OutExpr
209 contArgs cont = go [] cont
210   where
211     go args (ApplyTo _ arg se cont) = go (substExpr se arg : args) cont
212     go args cont                    = (reverse args, cont)
213
214 dropArgs :: Int -> SimplCont -> SimplCont
215 dropArgs 0 cont = cont
216 dropArgs n (ApplyTo _ _ _ cont) = dropArgs (n-1) cont
217 dropArgs n other                = pprPanic "dropArgs" (ppr n <+> ppr other)
218 \end{code}
219
220
221 Note [Interesting call context]
222 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
223 We want to avoid inlining an expression where there can't possibly be
224 any gain, such as in an argument position.  Hence, if the continuation
225 is interesting (eg. a case scrutinee, application etc.) then we
226 inline, otherwise we don't.  
227
228 Previously some_benefit used to return True only if the variable was
229 applied to some value arguments.  This didn't work:
230
231         let x = _coerce_ (T Int) Int (I# 3) in
232         case _coerce_ Int (T Int) x of
233                 I# y -> ....
234
235 we want to inline x, but can't see that it's a constructor in a case
236 scrutinee position, and some_benefit is False.
237
238 Another example:
239
240 dMonadST = _/\_ t -> :Monad (g1 _@_ t, g2 _@_ t, g3 _@_ t)
241
242 ....  case dMonadST _@_ x0 of (a,b,c) -> ....
243
244 we'd really like to inline dMonadST here, but we *don't* want to
245 inline if the case expression is just
246
247         case x of y { DEFAULT -> ... }
248
249 since we can just eliminate this case instead (x is in WHNF).  Similar
250 applies when x is bound to a lambda expression.  Hence
251 contIsInteresting looks for case expressions with just a single
252 default case.
253
254
255 \begin{code}
256 interestingCallContext :: SimplCont -> CallCtxt
257 -- See Note [Interesting call context]
258 interestingCallContext cont
259   = interesting cont
260   where
261     interesting (Select _ bndr _ _ _)
262         | isDeadBinder bndr = CaseCtxt
263         | otherwise         = ArgCtxt False 2   -- If the binder is used, this
264                                                 -- is like a strict let
265                 
266     interesting (ApplyTo _ arg _ cont)
267         | isTypeArg arg = interesting cont
268         | otherwise     = ValAppCtxt    -- Can happen if we have (f Int |> co) y
269                                         -- If f has an INLINE prag we need to give it some
270                                         -- motivation to inline. See Note [Cast then apply]
271                                         -- in CoreUnfold
272
273     interesting (StrictArg _ cci _ _)   = cci
274     interesting (StrictBind {})         = BoringCtxt
275     interesting (Stop cci)              = cci
276     interesting (CoerceIt _ cont)       = interesting cont
277         -- If this call is the arg of a strict function, the context
278         -- is a bit interesting.  If we inline here, we may get useful
279         -- evaluation information to avoid repeated evals: e.g.
280         --      x + (y * z)
281         -- Here the contIsInteresting makes the '*' keener to inline,
282         -- which in turn exposes a constructor which makes the '+' inline.
283         -- Assuming that +,* aren't small enough to inline regardless.
284         --
285         -- It's also very important to inline in a strict context for things
286         -- like
287         --              foldr k z (f x)
288         -- Here, the context of (f x) is strict, and if f's unfolding is
289         -- a build it's *great* to inline it here.  So we must ensure that
290         -- the context for (f x) is not totally uninteresting.
291
292
293 -------------------
294 mkArgInfo :: Id
295           -> [CoreRule] -- Rules for function
296           -> Int        -- Number of value args
297           -> SimplCont  -- Context of the call
298           -> ArgInfo
299
300 mkArgInfo fun rules n_val_args call_cont
301   | n_val_args < idArity fun            -- Note [Unsaturated functions]
302   = ArgInfo { ai_rules = False
303             , ai_strs = vanilla_stricts 
304             , ai_discs = vanilla_discounts }
305   | otherwise
306   = ArgInfo { ai_rules = interestingArgContext rules call_cont
307             , ai_strs  = add_type_str (idType fun) arg_stricts
308             , ai_discs = arg_discounts }
309   where
310     vanilla_discounts, arg_discounts :: [Int]
311     vanilla_discounts = repeat 0
312     arg_discounts = case idUnfolding fun of
313                         CoreUnfolding {uf_guidance = UnfoldIfGoodArgs {ug_args = discounts}}
314                               -> discounts ++ vanilla_discounts
315                         _     -> vanilla_discounts
316
317     vanilla_stricts, arg_stricts :: [Bool]
318     vanilla_stricts  = repeat False
319
320     arg_stricts
321       = case splitStrictSig (idNewStrictness fun) of
322           (demands, result_info)
323                 | not (demands `lengthExceeds` n_val_args)
324                 ->      -- Enough args, use the strictness given.
325                         -- For bottoming functions we used to pretend that the arg
326                         -- is lazy, so that we don't treat the arg as an
327                         -- interesting context.  This avoids substituting
328                         -- top-level bindings for (say) strings into 
329                         -- calls to error.  But now we are more careful about
330                         -- inlining lone variables, so its ok (see SimplUtils.analyseCont)
331                    if isBotRes result_info then
332                         map isStrictDmd demands         -- Finite => result is bottom
333                    else
334                         map isStrictDmd demands ++ vanilla_stricts
335                | otherwise
336                -> WARN( True, text "More demands than arity" <+> ppr fun <+> ppr (idArity fun) 
337                                 <+> ppr n_val_args <+> ppr demands ) 
338                    vanilla_stricts      -- Not enough args, or no strictness
339
340     add_type_str :: Type -> [Bool] -> [Bool]
341     -- If the function arg types are strict, record that in the 'strictness bits'
342     -- No need to instantiate because unboxed types (which dominate the strict
343     -- types) can't instantiate type variables.
344     -- add_type_str is done repeatedly (for each call); might be better 
345     -- once-for-all in the function
346     -- But beware primops/datacons with no strictness
347     add_type_str _ [] = []
348     add_type_str fun_ty strs            -- Look through foralls
349         | Just (_, fun_ty') <- splitForAllTy_maybe fun_ty       -- Includes coercions
350         = add_type_str fun_ty' strs
351     add_type_str fun_ty (str:strs)      -- Add strict-type info
352         | Just (arg_ty, fun_ty') <- splitFunTy_maybe fun_ty
353         = (str || isStrictType arg_ty) : add_type_str fun_ty' strs
354     add_type_str _ strs
355         = strs
356
357 {- Note [Unsaturated functions]
358   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
359 Consider (test eyeball/inline4)
360         x = a:as
361         y = f x
362 where f has arity 2.  Then we do not want to inline 'x', because
363 it'll just be floated out again.  Even if f has lots of discounts
364 on its first argument -- it must be saturated for these to kick in
365 -}
366
367 interestingArgContext :: [CoreRule] -> SimplCont -> Bool
368 -- If the argument has form (f x y), where x,y are boring,
369 -- and f is marked INLINE, then we don't want to inline f.
370 -- But if the context of the argument is
371 --      g (f x y) 
372 -- where g has rules, then we *do* want to inline f, in case it
373 -- exposes a rule that might fire.  Similarly, if the context is
374 --      h (g (f x x))
375 -- where h has rules, then we do want to inline f; hence the
376 -- call_cont argument to interestingArgContext
377 --
378 -- The ai-rules flag makes this happen; if it's
379 -- set, the inliner gets just enough keener to inline f 
380 -- regardless of how boring f's arguments are, if it's marked INLINE
381 --
382 -- The alternative would be to *always* inline an INLINE function,
383 -- regardless of how boring its context is; but that seems overkill
384 -- For example, it'd mean that wrapper functions were always inlined
385 interestingArgContext rules call_cont
386   = notNull rules || enclosing_fn_has_rules
387   where
388     enclosing_fn_has_rules = go call_cont
389
390     go (Select {})           = False
391     go (ApplyTo {})          = False
392     go (StrictArg _ cci _ _) = interesting cci
393     go (StrictBind {})       = False    -- ??
394     go (CoerceIt _ c)        = go c
395     go (Stop cci)            = interesting cci
396
397     interesting (ArgCtxt rules _) = rules
398     interesting _                 = False
399 \end{code}
400
401
402
403 %************************************************************************
404 %*                                                                      *
405 \subsection{Decisions about inlining}
406 %*                                                                      *
407 %************************************************************************
408
409 Inlining is controlled partly by the SimplifierMode switch.  This has two
410 settings:
411
412         SimplGently     (a) Simplifying before specialiser/full laziness
413                         (b) Simplifiying inside INLINE pragma
414                         (c) Simplifying the LHS of a rule
415                         (d) Simplifying a GHCi expression or Template 
416                                 Haskell splice
417
418         SimplPhase n _   Used at all other times
419
420 The key thing about SimplGently is that it does no call-site inlining.
421 Before full laziness we must be careful not to inline wrappers,
422 because doing so inhibits floating
423     e.g. ...(case f x of ...)...
424     ==> ...(case (case x of I# x# -> fw x#) of ...)...
425     ==> ...(case x of I# x# -> case fw x# of ...)...
426 and now the redex (f x) isn't floatable any more.
427
428 The no-inlining thing is also important for Template Haskell.  You might be 
429 compiling in one-shot mode with -O2; but when TH compiles a splice before
430 running it, we don't want to use -O2.  Indeed, we don't want to inline
431 anything, because the byte-code interpreter might get confused about 
432 unboxed tuples and suchlike.
433
434 INLINE pragmas
435 ~~~~~~~~~~~~~~
436 We don't simplify inside InlineRules (which come from INLINE pragmas).
437 It really is important to switch off inlinings inside such
438 expressions.  Consider the following example 
439
440         let f = \pq -> BIG
441         in
442         let g = \y -> f y y
443             {-# INLINE g #-}
444         in ...g...g...g...g...g...
445
446 Now, if that's the ONLY occurrence of f, it will be inlined inside g,
447 and thence copied multiple times when g is inlined.
448
449
450 This function may be inlinined in other modules, so we
451 don't want to remove (by inlining) calls to functions that have
452 specialisations, or that may have transformation rules in an importing
453 scope.
454
455 E.g.    {-# INLINE f #-}
456                 f x = ...g...
457
458 and suppose that g is strict *and* has specialisations.  If we inline
459 g's wrapper, we deny f the chance of getting the specialised version
460 of g when f is inlined at some call site (perhaps in some other
461 module).
462
463 It's also important not to inline a worker back into a wrapper.
464 A wrapper looks like
465         wraper = inline_me (\x -> ...worker... )
466 Normally, the inline_me prevents the worker getting inlined into
467 the wrapper (initially, the worker's only call site!).  But,
468 if the wrapper is sure to be called, the strictness analyser will
469 mark it 'demanded', so when the RHS is simplified, it'll get an ArgOf
470 continuation.  That's why the keep_inline predicate returns True for
471 ArgOf continuations.  It shouldn't do any harm not to dissolve the
472 inline-me note under these circumstances.
473
474 Note that the result is that we do very little simplification
475 inside an InlineMe.  
476
477         all xs = foldr (&&) True xs
478         any p = all . map p  {-# INLINE any #-}
479
480 Problem: any won't get deforested, and so if it's exported and the
481 importer doesn't use the inlining, (eg passes it as an arg) then we
482 won't get deforestation at all.  We havn't solved this problem yet!
483
484
485 preInlineUnconditionally
486 ~~~~~~~~~~~~~~~~~~~~~~~~
487 @preInlineUnconditionally@ examines a bndr to see if it is used just
488 once in a completely safe way, so that it is safe to discard the
489 binding inline its RHS at the (unique) usage site, REGARDLESS of how
490 big the RHS might be.  If this is the case we don't simplify the RHS
491 first, but just inline it un-simplified.
492
493 This is much better than first simplifying a perhaps-huge RHS and then
494 inlining and re-simplifying it.  Indeed, it can be at least quadratically
495 better.  Consider
496
497         x1 = e1
498         x2 = e2[x1]
499         x3 = e3[x2]
500         ...etc...
501         xN = eN[xN-1]
502
503 We may end up simplifying e1 N times, e2 N-1 times, e3 N-3 times etc.
504 This can happen with cascades of functions too:
505
506         f1 = \x1.e1
507         f2 = \xs.e2[f1]
508         f3 = \xs.e3[f3]
509         ...etc...
510
511 THE MAIN INVARIANT is this:
512
513         ----  preInlineUnconditionally invariant -----
514    IF preInlineUnconditionally chooses to inline x = <rhs>
515    THEN doing the inlining should not change the occurrence
516         info for the free vars of <rhs>
517         ----------------------------------------------
518
519 For example, it's tempting to look at trivial binding like
520         x = y
521 and inline it unconditionally.  But suppose x is used many times,
522 but this is the unique occurrence of y.  Then inlining x would change
523 y's occurrence info, which breaks the invariant.  It matters: y
524 might have a BIG rhs, which will now be dup'd at every occurrenc of x.
525
526
527 Even RHSs labelled InlineMe aren't caught here, because there might be
528 no benefit from inlining at the call site.
529
530 [Sept 01] Don't unconditionally inline a top-level thing, because that
531 can simply make a static thing into something built dynamically.  E.g.
532         x = (a,b)
533         main = \s -> h x
534
535 [Remember that we treat \s as a one-shot lambda.]  No point in
536 inlining x unless there is something interesting about the call site.
537
538 But watch out: if you aren't careful, some useful foldr/build fusion
539 can be lost (most notably in spectral/hartel/parstof) because the
540 foldr didn't see the build.  Doing the dynamic allocation isn't a big
541 deal, in fact, but losing the fusion can be.  But the right thing here
542 seems to be to do a callSiteInline based on the fact that there is
543 something interesting about the call site (it's strict).  Hmm.  That
544 seems a bit fragile.
545
546 Conclusion: inline top level things gaily until Phase 0 (the last
547 phase), at which point don't.
548
549 \begin{code}
550 preInlineUnconditionally :: SimplEnv -> TopLevelFlag -> InId -> InExpr -> Bool
551 preInlineUnconditionally env top_lvl bndr rhs
552   | not active             = False
553   | opt_SimplNoPreInlining = False
554   | otherwise = case idOccInfo bndr of
555                   IAmDead                    -> True    -- Happens in ((\x.1) v)
556                   OneOcc in_lam True int_cxt -> try_once in_lam int_cxt
557                   _                          -> False
558   where
559     phase = getMode env
560     active = case phase of
561                    SimplGently    -> isEarlyActive act
562                    SimplPhase n _ -> isActive n act
563     act = idInlineActivation bndr
564
565     try_once in_lam int_cxt     -- There's one textual occurrence
566         | not in_lam = isNotTopLevel top_lvl || early_phase
567         | otherwise  = int_cxt && canInlineInLam rhs
568
569 -- Be very careful before inlining inside a lambda, becuase (a) we must not 
570 -- invalidate occurrence information, and (b) we want to avoid pushing a
571 -- single allocation (here) into multiple allocations (inside lambda).  
572 -- Inlining a *function* with a single *saturated* call would be ok, mind you.
573 --      || (if is_cheap && not (canInlineInLam rhs) then pprTrace "preinline" (ppr bndr <+> ppr rhs) ok else ok)
574 --      where 
575 --              is_cheap = exprIsCheap rhs
576 --              ok = is_cheap && int_cxt
577
578         --      int_cxt         The context isn't totally boring
579         -- E.g. let f = \ab.BIG in \y. map f xs
580         --      Don't want to substitute for f, because then we allocate
581         --      its closure every time the \y is called
582         -- But: let f = \ab.BIG in \y. map (f y) xs
583         --      Now we do want to substitute for f, even though it's not 
584         --      saturated, because we're going to allocate a closure for 
585         --      (f y) every time round the loop anyhow.
586
587         -- canInlineInLam => free vars of rhs are (Once in_lam) or Many,
588         -- so substituting rhs inside a lambda doesn't change the occ info.
589         -- Sadly, not quite the same as exprIsHNF.
590     canInlineInLam (Lit _)              = True
591     canInlineInLam (Lam b e)            = isRuntimeVar b || canInlineInLam e
592     canInlineInLam (Note _ e)           = canInlineInLam e
593     canInlineInLam _                    = False
594
595     early_phase = case phase of
596                         SimplPhase 0 _ -> False
597                         _              -> True
598 -- If we don't have this early_phase test, consider
599 --      x = length [1,2,3]
600 -- The full laziness pass carefully floats all the cons cells to
601 -- top level, and preInlineUnconditionally floats them all back in.
602 -- Result is (a) static allocation replaced by dynamic allocation
603 --           (b) many simplifier iterations because this tickles
604 --               a related problem; only one inlining per pass
605 -- 
606 -- On the other hand, I have seen cases where top-level fusion is
607 -- lost if we don't inline top level thing (e.g. string constants)
608 -- Hence the test for phase zero (which is the phase for all the final
609 -- simplifications).  Until phase zero we take no special notice of
610 -- top level things, but then we become more leery about inlining
611 -- them.  
612
613 \end{code}
614
615 postInlineUnconditionally
616 ~~~~~~~~~~~~~~~~~~~~~~~~~
617 @postInlineUnconditionally@ decides whether to unconditionally inline
618 a thing based on the form of its RHS; in particular if it has a
619 trivial RHS.  If so, we can inline and discard the binding altogether.
620
621 NB: a loop breaker has must_keep_binding = True and non-loop-breakers
622 only have *forward* references Hence, it's safe to discard the binding
623         
624 NOTE: This isn't our last opportunity to inline.  We're at the binding
625 site right now, and we'll get another opportunity when we get to the
626 ocurrence(s)
627
628 Note that we do this unconditional inlining only for trival RHSs.
629 Don't inline even WHNFs inside lambdas; doing so may simply increase
630 allocation when the function is called. This isn't the last chance; see
631 NOTE above.
632
633 NB: Even inline pragmas (e.g. IMustBeINLINEd) are ignored here Why?
634 Because we don't even want to inline them into the RHS of constructor
635 arguments. See NOTE above
636
637 NB: At one time even NOINLINE was ignored here: if the rhs is trivial
638 it's best to inline it anyway.  We often get a=E; b=a from desugaring,
639 with both a and b marked NOINLINE.  But that seems incompatible with
640 our new view that inlining is like a RULE, so I'm sticking to the 'active'
641 story for now.
642
643 \begin{code}
644 postInlineUnconditionally 
645     :: SimplEnv -> TopLevelFlag
646     -> OutId            -- The binder (an InId would be fine too)
647     -> OccInfo          -- From the InId
648     -> OutExpr
649     -> Unfolding
650     -> Bool
651 postInlineUnconditionally env top_lvl bndr occ_info rhs unfolding
652   | not active             = False
653   | isLoopBreaker occ_info = False      -- If it's a loop-breaker of any kind, don't inline
654                                         -- because it might be referred to "earlier"
655   | isExportedId bndr      = False
656   | isInlineRule unfolding = False      -- Note [InlineRule and postInlineUnconditionally]
657   | exprIsTrivial rhs      = True
658   | otherwise
659   = case occ_info of
660         -- The point of examining occ_info here is that for *non-values* 
661         -- that occur outside a lambda, the call-site inliner won't have
662         -- a chance (becuase it doesn't know that the thing
663         -- only occurs once).   The pre-inliner won't have gotten
664         -- it either, if the thing occurs in more than one branch
665         -- So the main target is things like
666         --      let x = f y in
667         --      case v of
668         --         True  -> case x of ...
669         --         False -> case x of ...
670         -- I'm not sure how important this is in practice
671       OneOcc in_lam _one_br int_cxt     -- OneOcc => no code-duplication issue
672         ->     smallEnoughToInline unfolding    -- Small enough to dup
673                         -- ToDo: consider discount on smallEnoughToInline if int_cxt is true
674                         --
675                         -- NB: Do NOT inline arbitrarily big things, even if one_br is True
676                         -- Reason: doing so risks exponential behaviour.  We simplify a big
677                         --         expression, inline it, and simplify it again.  But if the
678                         --         very same thing happens in the big expression, we get 
679                         --         exponential cost!
680                         -- PRINCIPLE: when we've already simplified an expression once, 
681                         -- make sure that we only inline it if it's reasonably small.
682
683            &&  ((isNotTopLevel top_lvl && not in_lam) || 
684                         -- But outside a lambda, we want to be reasonably aggressive
685                         -- about inlining into multiple branches of case
686                         -- e.g. let x = <non-value> 
687                         --      in case y of { C1 -> ..x..; C2 -> ..x..; C3 -> ... } 
688                         -- Inlining can be a big win if C3 is the hot-spot, even if
689                         -- the uses in C1, C2 are not 'interesting'
690                         -- An example that gets worse if you add int_cxt here is 'clausify'
691
692                 (isCheapUnfolding unfolding && int_cxt))
693                         -- isCheap => acceptable work duplication; in_lam may be true
694                         -- int_cxt to prevent us inlining inside a lambda without some 
695                         -- good reason.  See the notes on int_cxt in preInlineUnconditionally
696
697       IAmDead -> True   -- This happens; for example, the case_bndr during case of
698                         -- known constructor:  case (a,b) of x { (p,q) -> ... }
699                         -- Here x isn't mentioned in the RHS, so we don't want to
700                         -- create the (dead) let-binding  let x = (a,b) in ...
701
702       _ -> False
703
704 -- Here's an example that we don't handle well:
705 --      let f = if b then Left (\x.BIG) else Right (\y.BIG)
706 --      in \y. ....case f of {...} ....
707 -- Here f is used just once, and duplicating the case work is fine (exprIsCheap).
708 -- But
709 --  - We can't preInlineUnconditionally because that woud invalidate
710 --    the occ info for b.
711 --  - We can't postInlineUnconditionally because the RHS is big, and
712 --    that risks exponential behaviour
713 --  - We can't call-site inline, because the rhs is big
714 -- Alas!
715
716   where
717     active = case getMode env of
718                    SimplGently    -> isAlwaysActive act
719                    SimplPhase n _ -> isActive n act
720     act = idInlineActivation bndr
721
722 activeInline :: SimplEnv -> OutId -> Bool
723 activeInline env id
724   = case getMode env of
725       SimplGently -> False
726         -- No inlining at all when doing gentle stuff,
727         -- except for local things that occur once (pre/postInlineUnconditionally)
728         -- The reason is that too little clean-up happens if you 
729         -- don't inline use-once things.   Also a bit of inlining is *good* for
730         -- full laziness; it can expose constant sub-expressions.
731         -- Example in spectral/mandel/Mandel.hs, where the mandelset 
732         -- function gets a useful let-float if you inline windowToViewport
733
734         -- NB: we used to have a second exception, for data con wrappers.
735         -- On the grounds that we use gentle mode for rule LHSs, and 
736         -- they match better when data con wrappers are inlined.
737         -- But that only really applies to the trivial wrappers (like (:)),
738         -- and they are now constructed as Compulsory unfoldings (in MkId)
739         -- so they'll happen anyway.
740
741       SimplPhase n _ -> isActive n act
742   where
743     act = idInlineActivation id
744
745 activeRule :: DynFlags -> SimplEnv -> Maybe (Activation -> Bool)
746 -- Nothing => No rules at all
747 activeRule dflags env
748   | not (dopt Opt_EnableRewriteRules dflags)
749   = Nothing     -- Rewriting is off
750   | otherwise
751   = case getMode env of
752         SimplGently    -> Just isAlwaysActive
753                         -- Used to be Nothing (no rules in gentle mode)
754                         -- Main motivation for changing is that I wanted
755                         --      lift String ===> ...
756                         -- to work in Template Haskell when simplifying
757                         -- splices, so we get simpler code for literal strings
758         SimplPhase n _ -> Just (isActive n)
759 \end{code}
760
761 Note [InlineRule and postInlineUnconditionally]
762 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
763 Do not do postInlineUnconditionally if the Id has an InlineRule, otherwise
764 we lose the unfolding.  Example
765
766      -- f has InlineRule with rhs (e |> co)
767      --   where 'e' is big
768      f = e |> co
769
770 Then there's a danger we'll optimise to
771
772      f' = e
773      f = f' |> co
774
775 and now postInlineUnconditionally, losing the InlineRule on f.  Now f'
776 won't inline because 'e' is too big.
777
778
779 %************************************************************************
780 %*                                                                      *
781         Rebuilding a lambda
782 %*                                                                      *
783 %************************************************************************
784
785 \begin{code}
786 mkLam :: SimplEnv -> [OutBndr] -> OutExpr -> SimplM OutExpr
787 -- mkLam tries three things
788 --      a) eta reduction, if that gives a trivial expression
789 --      b) eta expansion [only if there are some value lambdas]
790
791 mkLam _b [] body 
792   = return body
793 mkLam env bndrs body
794   = do  { dflags <- getDOptsSmpl
795         ; mkLam' dflags bndrs body }
796   where
797     mkLam' :: DynFlags -> [OutBndr] -> OutExpr -> SimplM OutExpr
798     mkLam' dflags bndrs (Cast body co)
799       | not (any bad bndrs)
800         -- Note [Casts and lambdas]
801       = do { lam <- mkLam' dflags bndrs body
802            ; return (mkCoerce (mkPiTypes bndrs co) lam) }
803       where
804         co_vars  = tyVarsOfType co
805         bad bndr = isCoVar bndr && bndr `elemVarSet` co_vars      
806
807     mkLam' dflags bndrs body
808       | dopt Opt_DoEtaReduction dflags,
809         Just etad_lam <- tryEtaReduce bndrs body
810       = do { tick (EtaReduction (head bndrs))
811            ; return etad_lam }
812
813       | dopt Opt_DoLambdaEtaExpansion dflags,
814         not (inGentleMode env),       -- In gentle mode don't eta-expansion
815         any isRuntimeVar bndrs        -- because it can clutter up the code
816                                       -- with casts etc that may not be removed
817       = do { let body' = tryEtaExpansion dflags body
818            ; return (mkLams bndrs body') }
819    
820       | otherwise 
821       = return (mkLams bndrs body)
822 \end{code}
823
824 Note [Casts and lambdas]
825 ~~~~~~~~~~~~~~~~~~~~~~~~
826 Consider 
827         (\x. (\y. e) `cast` g1) `cast` g2
828 There is a danger here that the two lambdas look separated, and the 
829 full laziness pass might float an expression to between the two.
830
831 So this equation in mkLam' floats the g1 out, thus:
832         (\x. e `cast` g1)  -->  (\x.e) `cast` (tx -> g1)
833 where x:tx.
834
835 In general, this floats casts outside lambdas, where (I hope) they
836 might meet and cancel with some other cast:
837         \x. e `cast` co   ===>   (\x. e) `cast` (tx -> co)
838         /\a. e `cast` co  ===>   (/\a. e) `cast` (/\a. co)
839         /\g. e `cast` co  ===>   (/\g. e) `cast` (/\g. co)
840                           (if not (g `in` co))
841
842 Notice that it works regardless of 'e'.  Originally it worked only
843 if 'e' was itself a lambda, but in some cases that resulted in 
844 fruitless iteration in the simplifier.  A good example was when
845 compiling Text.ParserCombinators.ReadPrec, where we had a definition 
846 like    (\x. Get `cast` g)
847 where Get is a constructor with nonzero arity.  Then mkLam eta-expanded
848 the Get, and the next iteration eta-reduced it, and then eta-expanded 
849 it again.
850
851 Note also the side condition for the case of coercion binders.
852 It does not make sense to transform
853         /\g. e `cast` g  ==>  (/\g.e) `cast` (/\g.g)
854 because the latter is not well-kinded.
855
856 --      c) floating lets out through big lambdas 
857 --              [only if all tyvar lambdas, and only if this lambda
858 --               is the RHS of a let]
859
860 {-      Sept 01: I'm experimenting with getting the
861         full laziness pass to float out past big lambdsa
862  | all isTyVar bndrs,   -- Only for big lambdas
863    contIsRhs cont       -- Only try the rhs type-lambda floating
864                         -- if this is indeed a right-hand side; otherwise
865                         -- we end up floating the thing out, only for float-in
866                         -- to float it right back in again!
867  = do (floats, body') <- tryRhsTyLam env bndrs body
868       return (floats, mkLams bndrs body')
869 -}
870
871
872 %************************************************************************
873 %*                                                                      *
874                 Eta reduction
875 %*                                                                      *
876 %************************************************************************
877
878 Note [Eta reduction conditions]
879 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
880 We try for eta reduction here, but *only* if we get all the way to an
881 trivial expression.  We don't want to remove extra lambdas unless we
882 are going to avoid allocating this thing altogether.
883
884 There are some particularly delicate points here:
885
886 * Eta reduction is not valid in general:  
887         \x. bot  /=  bot
888   This matters, partly for old-fashioned correctness reasons but,
889   worse, getting it wrong can yield a seg fault. Consider
890         f = \x.f x
891         h y = case (case y of { True -> f `seq` True; False -> False }) of
892                 True -> ...; False -> ...
893
894   If we (unsoundly) eta-reduce f to get f=f, the strictness analyser
895   says f=bottom, and replaces the (f `seq` True) with just
896   (f `cast` unsafe-co).  BUT, as thing stand, 'f' got arity 1, and it
897   *keeps* arity 1 (perhaps also wrongly).  So CorePrep eta-expands 
898   the definition again, so that it does not termninate after all.
899   Result: seg-fault because the boolean case actually gets a function value.
900   See Trac #1947.
901
902   So it's important to to the right thing.
903
904 * Note [Arity care]: we need to be careful if we just look at f's
905   arity. Currently (Dec07), f's arity is visible in its own RHS (see
906   Note [Arity robustness] in SimplEnv) so we must *not* trust the
907   arity when checking that 'f' is a value.  Otherwise we will
908   eta-reduce
909       f = \x. f x
910   to
911       f = f
912   Which might change a terminiating program (think (f `seq` e)) to a 
913   non-terminating one.  So we check for being a loop breaker first.
914
915   However for GlobalIds we can look at the arity; and for primops we
916   must, since they have no unfolding.  
917
918 * Regardless of whether 'f' is a value, we always want to 
919   reduce (/\a -> f a) to f
920   This came up in a RULE: foldr (build (/\a -> g a))
921   did not match           foldr (build (/\b -> ...something complex...))
922   The type checker can insert these eta-expanded versions,
923   with both type and dictionary lambdas; hence the slightly 
924   ad-hoc isDictId
925
926 * Never *reduce* arity. For example
927       f = \xy. g x y
928   Then if h has arity 1 we don't want to eta-reduce because then
929   f's arity would decrease, and that is bad
930
931 These delicacies are why we don't use exprIsTrivial and exprIsHNF here.
932 Alas.
933
934 \begin{code}
935 tryEtaReduce :: [OutBndr] -> OutExpr -> Maybe OutExpr
936 tryEtaReduce bndrs body 
937   = go (reverse bndrs) body
938   where
939     incoming_arity = count isId bndrs
940
941     go (b : bs) (App fun arg) | ok_arg b arg = go bs fun        -- Loop round
942     go []       fun           | ok_fun fun   = Just fun         -- Success!
943     go _        _                            = Nothing          -- Failure!
944
945         -- Note [Eta reduction conditions]
946     ok_fun (App fun (Type ty)) 
947         | not (any (`elemVarSet` tyVarsOfType ty) bndrs)
948         =  ok_fun fun
949     ok_fun (Var fun_id)
950         =  not (fun_id `elem` bndrs)
951         && (ok_fun_id fun_id || all ok_lam bndrs)
952     ok_fun _fun = False
953
954     ok_fun_id fun = fun_arity fun >= incoming_arity
955
956     fun_arity fun             -- See Note [Arity care]
957        | isLocalId fun && isLoopBreaker (idOccInfo fun) = 0
958        | otherwise = idArity fun              
959
960     ok_lam v = isTyVar v || isDictId v
961
962     ok_arg b arg = varToCoreExpr b `cheapEqExpr` arg
963 \end{code}
964
965
966 %************************************************************************
967 %*                                                                      *
968                 Eta expansion
969 %*                                                                      *
970 %************************************************************************
971
972
973 We go for:
974    f = \x1..xn -> N  ==>   f = \x1..xn y1..ym -> N y1..ym
975                                  (n >= 0)
976
977 where (in both cases) 
978
979         * The xi can include type variables
980
981         * The yi are all value variables
982
983         * N is a NORMAL FORM (i.e. no redexes anywhere)
984           wanting a suitable number of extra args.
985
986 The biggest reason for doing this is for cases like
987
988         f = \x -> case x of
989                     True  -> \y -> e1
990                     False -> \y -> e2
991
992 Here we want to get the lambdas together.  A good exmaple is the nofib
993 program fibheaps, which gets 25% more allocation if you don't do this
994 eta-expansion.
995
996 We may have to sandwich some coerces between the lambdas
997 to make the types work.   exprEtaExpandArity looks through coerces
998 when computing arity; and etaExpand adds the coerces as necessary when
999 actually computing the expansion.
1000
1001 \begin{code}
1002 tryEtaExpansion :: DynFlags -> OutExpr -> OutExpr
1003 -- There is at least one runtime binder in the binders
1004 tryEtaExpansion dflags body
1005   = etaExpand fun_arity body
1006   where
1007     fun_arity = exprEtaExpandArity dflags body
1008 \end{code}
1009
1010
1011 %************************************************************************
1012 %*                                                                      *
1013 \subsection{Floating lets out of big lambdas}
1014 %*                                                                      *
1015 %************************************************************************
1016
1017 Note [Floating and type abstraction]
1018 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1019 Consider this:
1020         x = /\a. C e1 e2
1021 We'd like to float this to 
1022         y1 = /\a. e1
1023         y2 = /\a. e2
1024         x  = /\a. C (y1 a) (y2 a)
1025 for the usual reasons: we want to inline x rather vigorously.
1026
1027 You may think that this kind of thing is rare.  But in some programs it is
1028 common.  For example, if you do closure conversion you might get:
1029
1030         data a :-> b = forall e. (e -> a -> b) :$ e
1031
1032         f_cc :: forall a. a :-> a
1033         f_cc = /\a. (\e. id a) :$ ()
1034
1035 Now we really want to inline that f_cc thing so that the
1036 construction of the closure goes away. 
1037
1038 So I have elaborated simplLazyBind to understand right-hand sides that look
1039 like
1040         /\ a1..an. body
1041
1042 and treat them specially. The real work is done in SimplUtils.abstractFloats,
1043 but there is quite a bit of plumbing in simplLazyBind as well.
1044
1045 The same transformation is good when there are lets in the body:
1046
1047         /\abc -> let(rec) x = e in b
1048    ==>
1049         let(rec) x' = /\abc -> let x = x' a b c in e
1050         in 
1051         /\abc -> let x = x' a b c in b
1052
1053 This is good because it can turn things like:
1054
1055         let f = /\a -> letrec g = ... g ... in g
1056 into
1057         letrec g' = /\a -> ... g' a ...
1058         in
1059         let f = /\ a -> g' a
1060
1061 which is better.  In effect, it means that big lambdas don't impede
1062 let-floating.
1063
1064 This optimisation is CRUCIAL in eliminating the junk introduced by
1065 desugaring mutually recursive definitions.  Don't eliminate it lightly!
1066
1067 [May 1999]  If we do this transformation *regardless* then we can
1068 end up with some pretty silly stuff.  For example, 
1069
1070         let 
1071             st = /\ s -> let { x1=r1 ; x2=r2 } in ...
1072         in ..
1073 becomes
1074         let y1 = /\s -> r1
1075             y2 = /\s -> r2
1076             st = /\s -> ...[y1 s/x1, y2 s/x2]
1077         in ..
1078
1079 Unless the "..." is a WHNF there is really no point in doing this.
1080 Indeed it can make things worse.  Suppose x1 is used strictly,
1081 and is of the form
1082
1083         x1* = case f y of { (a,b) -> e }
1084
1085 If we abstract this wrt the tyvar we then can't do the case inline
1086 as we would normally do.
1087
1088 That's why the whole transformation is part of the same process that
1089 floats let-bindings and constructor arguments out of RHSs.  In particular,
1090 it is guarded by the doFloatFromRhs call in simplLazyBind.
1091
1092
1093 \begin{code}
1094 abstractFloats :: [OutTyVar] -> SimplEnv -> OutExpr -> SimplM ([OutBind], OutExpr)
1095 abstractFloats main_tvs body_env body
1096   = ASSERT( notNull body_floats )
1097     do  { (subst, float_binds) <- mapAccumLM abstract empty_subst body_floats
1098         ; return (float_binds, CoreSubst.substExpr subst body) }
1099   where
1100     main_tv_set = mkVarSet main_tvs
1101     body_floats = getFloats body_env
1102     empty_subst = CoreSubst.mkEmptySubst (seInScope body_env)
1103
1104     abstract :: CoreSubst.Subst -> OutBind -> SimplM (CoreSubst.Subst, OutBind)
1105     abstract subst (NonRec id rhs)
1106       = do { (poly_id, poly_app) <- mk_poly tvs_here id
1107            ; let poly_rhs = mkLams tvs_here rhs'
1108                  subst'   = CoreSubst.extendIdSubst subst id poly_app
1109            ; return (subst', (NonRec poly_id poly_rhs)) }
1110       where
1111         rhs' = CoreSubst.substExpr subst rhs
1112         tvs_here | any isCoVar main_tvs = main_tvs      -- Note [Abstract over coercions]
1113                  | otherwise 
1114                  = varSetElems (main_tv_set `intersectVarSet` exprSomeFreeVars isTyVar rhs')
1115         
1116                 -- Abstract only over the type variables free in the rhs
1117                 -- wrt which the new binding is abstracted.  But the naive
1118                 -- approach of abstract wrt the tyvars free in the Id's type
1119                 -- fails. Consider:
1120                 --      /\ a b -> let t :: (a,b) = (e1, e2)
1121                 --                    x :: a     = fst t
1122                 --                in ...
1123                 -- Here, b isn't free in x's type, but we must nevertheless
1124                 -- abstract wrt b as well, because t's type mentions b.
1125                 -- Since t is floated too, we'd end up with the bogus:
1126                 --      poly_t = /\ a b -> (e1, e2)
1127                 --      poly_x = /\ a   -> fst (poly_t a *b*)
1128                 -- So for now we adopt the even more naive approach of
1129                 -- abstracting wrt *all* the tyvars.  We'll see if that
1130                 -- gives rise to problems.   SLPJ June 98
1131
1132     abstract subst (Rec prs)
1133        = do { (poly_ids, poly_apps) <- mapAndUnzipM (mk_poly tvs_here) ids
1134             ; let subst' = CoreSubst.extendSubstList subst (ids `zip` poly_apps)
1135                   poly_rhss = [mkLams tvs_here (CoreSubst.substExpr subst' rhs) | rhs <- rhss]
1136             ; return (subst', Rec (poly_ids `zip` poly_rhss)) }
1137        where
1138          (ids,rhss) = unzip prs
1139                 -- For a recursive group, it's a bit of a pain to work out the minimal
1140                 -- set of tyvars over which to abstract:
1141                 --      /\ a b c.  let x = ...a... in
1142                 --                 letrec { p = ...x...q...
1143                 --                          q = .....p...b... } in
1144                 --                 ...
1145                 -- Since 'x' is abstracted over 'a', the {p,q} group must be abstracted
1146                 -- over 'a' (because x is replaced by (poly_x a)) as well as 'b'.  
1147                 -- Since it's a pain, we just use the whole set, which is always safe
1148                 -- 
1149                 -- If you ever want to be more selective, remember this bizarre case too:
1150                 --      x::a = x
1151                 -- Here, we must abstract 'x' over 'a'.
1152          tvs_here = main_tvs
1153
1154     mk_poly tvs_here var
1155       = do { uniq <- getUniqueM
1156            ; let  poly_name = setNameUnique (idName var) uniq           -- Keep same name
1157                   poly_ty   = mkForAllTys tvs_here (idType var) -- But new type of course
1158                   poly_id   = transferPolyIdInfo var tvs_here $ -- Note [transferPolyIdInfo] in Id.lhs
1159                               mkLocalId poly_name poly_ty 
1160            ; return (poly_id, mkTyApps (Var poly_id) (mkTyVarTys tvs_here)) }
1161                 -- In the olden days, it was crucial to copy the occInfo of the original var, 
1162                 -- because we were looking at occurrence-analysed but as yet unsimplified code!
1163                 -- In particular, we mustn't lose the loop breakers.  BUT NOW we are looking
1164                 -- at already simplified code, so it doesn't matter
1165                 -- 
1166                 -- It's even right to retain single-occurrence or dead-var info:
1167                 -- Suppose we started with  /\a -> let x = E in B
1168                 -- where x occurs once in B. Then we transform to:
1169                 --      let x' = /\a -> E in /\a -> let x* = x' a in B
1170                 -- where x* has an INLINE prag on it.  Now, once x* is inlined,
1171                 -- the occurrences of x' will be just the occurrences originally
1172                 -- pinned on x.
1173 \end{code}
1174
1175 Note [Abstract over coercions]
1176 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1177 If a coercion variable (g :: a ~ Int) is free in the RHS, then so is the
1178 type variable a.  Rather than sort this mess out, we simply bale out and abstract
1179 wrt all the type variables if any of them are coercion variables.
1180
1181
1182 Historical note: if you use let-bindings instead of a substitution, beware of this:
1183
1184                 -- Suppose we start with:
1185                 --
1186                 --      x = /\ a -> let g = G in E
1187                 --
1188                 -- Then we'll float to get
1189                 --
1190                 --      x = let poly_g = /\ a -> G
1191                 --          in /\ a -> let g = poly_g a in E
1192                 --
1193                 -- But now the occurrence analyser will see just one occurrence
1194                 -- of poly_g, not inside a lambda, so the simplifier will
1195                 -- PreInlineUnconditionally poly_g back into g!  Badk to square 1!
1196                 -- (I used to think that the "don't inline lone occurrences" stuff
1197                 --  would stop this happening, but since it's the *only* occurrence,
1198                 --  PreInlineUnconditionally kicks in first!)
1199                 --
1200                 -- Solution: put an INLINE note on g's RHS, so that poly_g seems
1201                 --           to appear many times.  (NB: mkInlineMe eliminates
1202                 --           such notes on trivial RHSs, so do it manually.)
1203
1204 %************************************************************************
1205 %*                                                                      *
1206                 prepareAlts
1207 %*                                                                      *
1208 %************************************************************************
1209
1210 prepareAlts tries these things:
1211
1212 1.  If several alternatives are identical, merge them into
1213     a single DEFAULT alternative.  I've occasionally seen this 
1214     making a big difference:
1215
1216         case e of               =====>     case e of
1217           C _ -> f x                         D v -> ....v....
1218           D v -> ....v....                   DEFAULT -> f x
1219           DEFAULT -> f x
1220
1221    The point is that we merge common RHSs, at least for the DEFAULT case.
1222    [One could do something more elaborate but I've never seen it needed.]
1223    To avoid an expensive test, we just merge branches equal to the *first*
1224    alternative; this picks up the common cases
1225         a) all branches equal
1226         b) some branches equal to the DEFAULT (which occurs first)
1227
1228 2.  Case merging:
1229        case e of b {             ==>   case e of b {
1230          p1 -> rhs1                      p1 -> rhs1
1231          ...                             ...
1232          pm -> rhsm                      pm -> rhsm
1233          _  -> case b of b' {            pn -> let b'=b in rhsn
1234                      pn -> rhsn          ...
1235                      ...                 po -> let b'=b in rhso
1236                      po -> rhso          _  -> let b'=b in rhsd
1237                      _  -> rhsd
1238        }  
1239     
1240     which merges two cases in one case when -- the default alternative of
1241     the outer case scrutises the same variable as the outer case This
1242     transformation is called Case Merging.  It avoids that the same
1243     variable is scrutinised multiple times.
1244
1245
1246 The case where transformation (1) showed up was like this (lib/std/PrelCError.lhs):
1247
1248         x | p `is` 1 -> e1
1249           | p `is` 2 -> e2
1250         ...etc...
1251
1252 where @is@ was something like
1253         
1254         p `is` n = p /= (-1) && p == n
1255
1256 This gave rise to a horrible sequence of cases
1257
1258         case p of
1259           (-1) -> $j p
1260           1    -> e1
1261           DEFAULT -> $j p
1262
1263 and similarly in cascade for all the join points!
1264
1265 Note [Dead binders]
1266 ~~~~~~~~~~~~~~~~~~~~
1267 We do this *here*, looking at un-simplified alternatives, because we
1268 have to check that r doesn't mention the variables bound by the
1269 pattern in each alternative, so the binder-info is rather useful.
1270
1271 \begin{code}
1272 prepareAlts :: SimplEnv -> OutExpr -> OutId -> [InAlt] -> SimplM ([AltCon], [InAlt])
1273 prepareAlts env scrut case_bndr' alts
1274   = do  { dflags <- getDOptsSmpl
1275         ; alts <- combineIdenticalAlts case_bndr' alts
1276
1277         ; let (alts_wo_default, maybe_deflt) = findDefault alts
1278               alt_cons = [con | (con,_,_) <- alts_wo_default]
1279               imposs_deflt_cons = nub (imposs_cons ++ alt_cons)
1280                 -- "imposs_deflt_cons" are handled 
1281                 --   EITHER by the context, 
1282                 --   OR by a non-DEFAULT branch in this case expression.
1283
1284         ; default_alts <- prepareDefault dflags env case_bndr' mb_tc_app 
1285                                          imposs_deflt_cons maybe_deflt
1286
1287         ; let trimmed_alts = filterOut impossible_alt alts_wo_default
1288               merged_alts = mergeAlts trimmed_alts default_alts
1289                 -- We need the mergeAlts in case the new default_alt 
1290                 -- has turned into a constructor alternative.
1291                 -- The merge keeps the inner DEFAULT at the front, if there is one
1292                 -- and interleaves the alternatives in the right order
1293
1294         ; return (imposs_deflt_cons, merged_alts) }
1295   where
1296     mb_tc_app = splitTyConApp_maybe (idType case_bndr')
1297     Just (_, inst_tys) = mb_tc_app 
1298
1299     imposs_cons = case scrut of
1300                     Var v -> otherCons (idUnfolding v)
1301                     _     -> []
1302
1303     impossible_alt :: CoreAlt -> Bool
1304     impossible_alt (con, _, _) | con `elem` imposs_cons = True
1305     impossible_alt (DataAlt con, _, _) = dataConCannotMatch inst_tys con
1306     impossible_alt _                   = False
1307
1308
1309 --------------------------------------------------
1310 --      1. Merge identical branches
1311 --------------------------------------------------
1312 combineIdenticalAlts :: OutId -> [InAlt] -> SimplM [InAlt]
1313
1314 combineIdenticalAlts case_bndr ((_con1,bndrs1,rhs1) : con_alts)
1315   | all isDeadBinder bndrs1,                    -- Remember the default 
1316     length filtered_alts < length con_alts      -- alternative comes first
1317         -- Also Note [Dead binders]
1318   = do  { tick (AltMerge case_bndr)
1319         ; return ((DEFAULT, [], rhs1) : filtered_alts) }
1320   where
1321     filtered_alts        = filter keep con_alts
1322     keep (_con,bndrs,rhs) = not (all isDeadBinder bndrs && rhs `cheapEqExpr` rhs1)
1323
1324 combineIdenticalAlts _ alts = return alts
1325
1326 -------------------------------------------------------------------------
1327 --                      Prepare the default alternative
1328 -------------------------------------------------------------------------
1329 prepareDefault :: DynFlags
1330                -> SimplEnv
1331                -> OutId         -- Case binder; need just for its type. Note that as an
1332                                 --   OutId, it has maximum information; this is important.
1333                                 --   Test simpl013 is an example
1334                -> Maybe (TyCon, [Type]) -- Type of scrutinee, decomposed
1335                -> [AltCon]      -- These cons can't happen when matching the default
1336                -> Maybe InExpr  -- Rhs
1337                -> SimplM [InAlt]        -- Still unsimplified
1338                                         -- We use a list because it's what mergeAlts expects,
1339                                         -- And becuase case-merging can cause many to show up
1340
1341 ------- Merge nested cases ----------
1342 prepareDefault dflags env outer_bndr _bndr_ty imposs_cons (Just deflt_rhs)
1343   | dopt Opt_CaseMerge dflags
1344   , Case (Var inner_scrut_var) inner_bndr _ inner_alts <- deflt_rhs
1345   , DoneId inner_scrut_var' <- substId env inner_scrut_var
1346         -- Remember, inner_scrut_var is an InId, but outer_bndr is an OutId
1347   , inner_scrut_var' == outer_bndr
1348         -- NB: the substId means that if the outer scrutinee was a 
1349         --     variable, and inner scrutinee is the same variable, 
1350         --     then inner_scrut_var' will be outer_bndr
1351         --     via the magic of simplCaseBinder
1352   = do  { tick (CaseMerge outer_bndr)
1353
1354         ; let munge_rhs rhs = bindCaseBndr inner_bndr (Var outer_bndr) rhs
1355         ; return [(con, args, munge_rhs rhs) | (con, args, rhs) <- inner_alts,
1356                                                not (con `elem` imposs_cons) ]
1357                 -- NB: filter out any imposs_cons.  Example:
1358                 --      case x of 
1359                 --        A -> e1
1360                 --        DEFAULT -> case x of 
1361                 --                      A -> e2
1362                 --                      B -> e3
1363                 -- When we merge, we must ensure that e1 takes 
1364                 -- precedence over e2 as the value for A!  
1365         }
1366         -- Warning: don't call prepareAlts recursively!
1367         -- Firstly, there's no point, because inner alts have already had
1368         -- mkCase applied to them, so they won't have a case in their default
1369         -- Secondly, if you do, you get an infinite loop, because the bindCaseBndr
1370         -- in munge_rhs may put a case into the DEFAULT branch!
1371
1372
1373 --------- Fill in known constructor -----------
1374 prepareDefault _ _ case_bndr (Just (tycon, inst_tys)) imposs_cons (Just deflt_rhs)
1375   |     -- This branch handles the case where we are 
1376         -- scrutinisng an algebraic data type
1377     isAlgTyCon tycon            -- It's a data type, tuple, or unboxed tuples.  
1378   , not (isNewTyCon tycon)      -- We can have a newtype, if we are just doing an eval:
1379                                 --      case x of { DEFAULT -> e }
1380                                 -- and we don't want to fill in a default for them!
1381   , Just all_cons <- tyConDataCons_maybe tycon
1382   , not (null all_cons)         -- This is a tricky corner case.  If the data type has no constructors,
1383                                 -- which GHC allows, then the case expression will have at most a default
1384                                 -- alternative.  We don't want to eliminate that alternative, because the
1385                                 -- invariant is that there's always one alternative.  It's more convenient
1386                                 -- to leave     
1387                                 --      case x of { DEFAULT -> e }     
1388                                 -- as it is, rather than transform it to
1389                                 --      error "case cant match"
1390                                 -- which would be quite legitmate.  But it's a really obscure corner, and
1391                                 -- not worth wasting code on.
1392   , let imposs_data_cons = [con | DataAlt con <- imposs_cons]   -- We now know it's a data type 
1393         impossible con  = con `elem` imposs_data_cons || dataConCannotMatch inst_tys con
1394   = case filterOut impossible all_cons of
1395         []    -> return []      -- Eliminate the default alternative
1396                                 -- altogether if it can't match
1397
1398         [con] ->        -- It matches exactly one constructor, so fill it in
1399                  do { tick (FillInCaseDefault case_bndr)
1400                     ; us <- getUniquesM
1401                     ; let (ex_tvs, co_tvs, arg_ids) =
1402                               dataConRepInstPat us con inst_tys
1403                     ; return [(DataAlt con, ex_tvs ++ co_tvs ++ arg_ids, deflt_rhs)] }
1404
1405         _ -> return [(DEFAULT, [], deflt_rhs)]
1406
1407   | debugIsOn, isAlgTyCon tycon, not (isOpenTyCon tycon), null (tyConDataCons tycon)
1408         -- This can legitimately happen for type families, so don't report that
1409   = pprTrace "prepareDefault" (ppr case_bndr <+> ppr tycon)
1410         $ return [(DEFAULT, [], deflt_rhs)]
1411
1412 --------- Catch-all cases -----------
1413 prepareDefault _dflags _env _case_bndr _bndr_ty _imposs_cons (Just deflt_rhs)
1414   = return [(DEFAULT, [], deflt_rhs)]
1415
1416 prepareDefault _dflags _env _case_bndr _bndr_ty _imposs_cons Nothing
1417   = return []   -- No default branch
1418 \end{code}
1419
1420
1421
1422 =================================================================================
1423
1424 mkCase tries these things
1425
1426 1.  Eliminate the case altogether if possible
1427
1428 2.  Case-identity:
1429
1430         case e of               ===> e
1431                 True  -> True;
1432                 False -> False
1433
1434     and similar friends.
1435
1436
1437 \begin{code}
1438 mkCase :: OutExpr -> OutId -> [OutAlt]  -- Increasing order
1439        -> SimplM OutExpr
1440
1441 --------------------------------------------------
1442 --      2. Identity case
1443 --------------------------------------------------
1444
1445 mkCase scrut case_bndr alts     -- Identity case
1446   | all identity_alt alts
1447   = do tick (CaseIdentity case_bndr)
1448        return (re_cast scrut)
1449   where
1450     identity_alt (con, args, rhs) = check_eq con args (de_cast rhs)
1451
1452     check_eq DEFAULT       _    (Var v)   = v == case_bndr
1453     check_eq (LitAlt lit') _    (Lit lit) = lit == lit'
1454     check_eq (DataAlt con) args rhs       = rhs `cheapEqExpr` mkConApp con (arg_tys ++ varsToCoreExprs args)
1455                                          || rhs `cheapEqExpr` Var case_bndr
1456     check_eq _ _ _ = False
1457
1458     arg_tys = map Type (tyConAppArgs (idType case_bndr))
1459
1460         -- We've seen this:
1461         --      case e of x { _ -> x `cast` c }
1462         -- And we definitely want to eliminate this case, to give
1463         --      e `cast` c
1464         -- So we throw away the cast from the RHS, and reconstruct
1465         -- it at the other end.  All the RHS casts must be the same
1466         -- if (all identity_alt alts) holds.
1467         -- 
1468         -- Don't worry about nested casts, because the simplifier combines them
1469     de_cast (Cast e _) = e
1470     de_cast e          = e
1471
1472     re_cast scrut = case head alts of
1473                         (_,_,Cast _ co) -> Cast scrut co
1474                         _               -> scrut
1475
1476
1477
1478 --------------------------------------------------
1479 --      Catch-all
1480 --------------------------------------------------
1481 mkCase scrut bndr alts = return (Case scrut bndr (coreAltsType alts) alts)
1482 \end{code}
1483
1484
1485 When adding auxiliary bindings for the case binder, it's worth checking if
1486 its dead, because it often is, and occasionally these mkCase transformations
1487 cascade rather nicely.
1488
1489 \begin{code}
1490 bindCaseBndr :: Id -> CoreExpr -> CoreExpr -> CoreExpr
1491 bindCaseBndr bndr rhs body
1492   | isDeadBinder bndr = body
1493   | otherwise         = bindNonRec bndr rhs body
1494 \end{code}