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