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