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