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