Allow inlining in "SimplGentle" mode
[ghc-hetmet.git] / compiler / simplCore / Simplify.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1993-1998
3 %
4 \section[Simplify]{The main module of the simplifier}
5
6 \begin{code}
7 module Simplify ( simplTopBinds, simplExpr ) where
8
9 #include "HsVersions.h"
10
11 import DynFlags
12 import SimplMonad
13 import Type hiding      ( substTy, extendTvSubst )
14 import SimplEnv
15 import SimplUtils
16 import FamInstEnv       ( FamInstEnv )
17 import Id
18 import MkId             ( mkImpossibleExpr, seqId )
19 import Var
20 import IdInfo
21 import Coercion
22 import FamInstEnv       ( topNormaliseType )
23 import DataCon          ( DataCon, dataConWorkId, dataConRepStrictness )
24 import CoreSyn
25 import NewDemand        ( isStrictDmd, splitStrictSig )
26 import PprCore          ( pprParendExpr, pprCoreExpr )
27 import CoreUnfold       ( mkUnfolding, mkCoreUnfolding, mkInlineRule, 
28                           exprIsConApp_maybe, callSiteInline, CallCtxt(..) )
29 import CoreUtils
30 import qualified CoreSubst
31 import CoreArity        ( exprArity )
32 import Rules            ( lookupRule, getRules )
33 import BasicTypes       ( isMarkedStrict, Arity )
34 import CostCentre       ( currentCCS, pushCCisNop )
35 import TysPrim          ( realWorldStatePrimTy )
36 import PrelInfo         ( realWorldPrimId )
37 import BasicTypes       ( TopLevelFlag(..), isTopLevel,
38                           RecFlag(..), isNonRuleLoopBreaker )
39 import MonadUtils       ( foldlM )
40 import Maybes           ( orElse )
41 import Data.List        ( mapAccumL )
42 import Outputable
43 import FastString
44 \end{code}
45
46
47 The guts of the simplifier is in this module, but the driver loop for
48 the simplifier is in SimplCore.lhs.
49
50
51 -----------------------------------------
52         *** IMPORTANT NOTE ***
53 -----------------------------------------
54 The simplifier used to guarantee that the output had no shadowing, but
55 it does not do so any more.   (Actually, it never did!)  The reason is
56 documented with simplifyArgs.
57
58
59 -----------------------------------------
60         *** IMPORTANT NOTE ***
61 -----------------------------------------
62 Many parts of the simplifier return a bunch of "floats" as well as an
63 expression. This is wrapped as a datatype SimplUtils.FloatsWith.
64
65 All "floats" are let-binds, not case-binds, but some non-rec lets may
66 be unlifted (with RHS ok-for-speculation).
67
68
69
70 -----------------------------------------
71         ORGANISATION OF FUNCTIONS
72 -----------------------------------------
73 simplTopBinds
74   - simplify all top-level binders
75   - for NonRec, call simplRecOrTopPair
76   - for Rec,    call simplRecBind
77
78
79         ------------------------------
80 simplExpr (applied lambda)      ==> simplNonRecBind
81 simplExpr (Let (NonRec ...) ..) ==> simplNonRecBind
82 simplExpr (Let (Rec ...)    ..) ==> simplify binders; simplRecBind
83
84         ------------------------------
85 simplRecBind    [binders already simplfied]
86   - use simplRecOrTopPair on each pair in turn
87
88 simplRecOrTopPair [binder already simplified]
89   Used for: recursive bindings (top level and nested)
90             top-level non-recursive bindings
91   Returns:
92   - check for PreInlineUnconditionally
93   - simplLazyBind
94
95 simplNonRecBind
96   Used for: non-top-level non-recursive bindings
97             beta reductions (which amount to the same thing)
98   Because it can deal with strict arts, it takes a
99         "thing-inside" and returns an expression
100
101   - check for PreInlineUnconditionally
102   - simplify binder, including its IdInfo
103   - if strict binding
104         simplStrictArg
105         mkAtomicArgs
106         completeNonRecX
107     else
108         simplLazyBind
109         addFloats
110
111 simplNonRecX:   [given a *simplified* RHS, but an *unsimplified* binder]
112   Used for: binding case-binder and constr args in a known-constructor case
113   - check for PreInLineUnconditionally
114   - simplify binder
115   - completeNonRecX
116
117         ------------------------------
118 simplLazyBind:  [binder already simplified, RHS not]
119   Used for: recursive bindings (top level and nested)
120             top-level non-recursive bindings
121             non-top-level, but *lazy* non-recursive bindings
122         [must not be strict or unboxed]
123   Returns floats + an augmented environment, not an expression
124   - substituteIdInfo and add result to in-scope
125         [so that rules are available in rec rhs]
126   - simplify rhs
127   - mkAtomicArgs
128   - float if exposes constructor or PAP
129   - completeBind
130
131
132 completeNonRecX:        [binder and rhs both simplified]
133   - if the the thing needs case binding (unlifted and not ok-for-spec)
134         build a Case
135    else
136         completeBind
137         addFloats
138
139 completeBind:   [given a simplified RHS]
140         [used for both rec and non-rec bindings, top level and not]
141   - try PostInlineUnconditionally
142   - add unfolding [this is the only place we add an unfolding]
143   - add arity
144
145
146
147 Right hand sides and arguments
148 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
149 In many ways we want to treat
150         (a) the right hand side of a let(rec), and
151         (b) a function argument
152 in the same way.  But not always!  In particular, we would
153 like to leave these arguments exactly as they are, so they
154 will match a RULE more easily.
155
156         f (g x, h x)
157         g (+ x)
158
159 It's harder to make the rule match if we ANF-ise the constructor,
160 or eta-expand the PAP:
161
162         f (let { a = g x; b = h x } in (a,b))
163         g (\y. + x y)
164
165 On the other hand if we see the let-defns
166
167         p = (g x, h x)
168         q = + x
169
170 then we *do* want to ANF-ise and eta-expand, so that p and q
171 can be safely inlined.
172
173 Even floating lets out is a bit dubious.  For let RHS's we float lets
174 out if that exposes a value, so that the value can be inlined more vigorously.
175 For example
176
177         r = let x = e in (x,x)
178
179 Here, if we float the let out we'll expose a nice constructor. We did experiments
180 that showed this to be a generally good thing.  But it was a bad thing to float
181 lets out unconditionally, because that meant they got allocated more often.
182
183 For function arguments, there's less reason to expose a constructor (it won't
184 get inlined).  Just possibly it might make a rule match, but I'm pretty skeptical.
185 So for the moment we don't float lets out of function arguments either.
186
187
188 Eta expansion
189 ~~~~~~~~~~~~~~
190 For eta expansion, we want to catch things like
191
192         case e of (a,b) -> \x -> case a of (p,q) -> \y -> r
193
194 If the \x was on the RHS of a let, we'd eta expand to bring the two
195 lambdas together.  And in general that's a good thing to do.  Perhaps
196 we should eta expand wherever we find a (value) lambda?  Then the eta
197 expansion at a let RHS can concentrate solely on the PAP case.
198
199
200 %************************************************************************
201 %*                                                                      *
202 \subsection{Bindings}
203 %*                                                                      *
204 %************************************************************************
205
206 \begin{code}
207 simplTopBinds :: SimplEnv -> [InBind] -> SimplM SimplEnv
208
209 simplTopBinds env0 binds0
210   = do  {       -- Put all the top-level binders into scope at the start
211                 -- so that if a transformation rule has unexpectedly brought
212                 -- anything into scope, then we don't get a complaint about that.
213                 -- It's rather as if the top-level binders were imported.
214         ; env1 <- simplRecBndrs env0 (bindersOfBinds binds0)
215         ; dflags <- getDOptsSmpl
216         ; let dump_flag = dopt Opt_D_dump_inlinings dflags ||
217                           dopt Opt_D_dump_rule_firings dflags
218         ; env2 <- simpl_binds dump_flag env1 binds0
219         ; freeTick SimplifierDone
220         ; return env2 }
221   where
222         -- We need to track the zapped top-level binders, because
223         -- they should have their fragile IdInfo zapped (notably occurrence info)
224         -- That's why we run down binds and bndrs' simultaneously.
225         --
226         -- The dump-flag emits a trace for each top-level binding, which
227         -- helps to locate the tracing for inlining and rule firing
228     simpl_binds :: Bool -> SimplEnv -> [InBind] -> SimplM SimplEnv
229     simpl_binds _    env []           = return env
230     simpl_binds dump env (bind:binds) = do { env' <- trace_bind dump bind $
231                                                      simpl_bind env bind
232                                            ; simpl_binds dump env' binds }
233
234     trace_bind True  bind = pprTrace "SimplBind" (ppr (bindersOf bind))
235     trace_bind False _    = \x -> x
236
237     simpl_bind env (Rec pairs)  = simplRecBind      env  TopLevel pairs
238     simpl_bind env (NonRec b r) = simplRecOrTopPair env' TopLevel b b' r
239         where
240           (env', b') = addBndrRules env b (lookupRecBndr env b)
241 \end{code}
242
243
244 %************************************************************************
245 %*                                                                      *
246 \subsection{Lazy bindings}
247 %*                                                                      *
248 %************************************************************************
249
250 simplRecBind is used for
251         * recursive bindings only
252
253 \begin{code}
254 simplRecBind :: SimplEnv -> TopLevelFlag
255              -> [(InId, InExpr)]
256              -> SimplM SimplEnv
257 simplRecBind env0 top_lvl pairs0
258   = do  { let (env_with_info, triples) = mapAccumL add_rules env0 pairs0
259         ; env1 <- go (zapFloats env_with_info) triples
260         ; return (env0 `addRecFloats` env1) }
261         -- addFloats adds the floats from env1,
262         -- _and_ updates env0 with the in-scope set from env1
263   where
264     add_rules :: SimplEnv -> (InBndr,InExpr) -> (SimplEnv, (InBndr, OutBndr, InExpr))
265         -- Add the (substituted) rules to the binder
266     add_rules env (bndr, rhs) = (env', (bndr, bndr', rhs))
267         where
268           (env', bndr') = addBndrRules env bndr (lookupRecBndr env bndr)
269
270     go env [] = return env
271
272     go env ((old_bndr, new_bndr, rhs) : pairs)
273         = do { env' <- simplRecOrTopPair env top_lvl old_bndr new_bndr rhs
274              ; go env' pairs }
275 \end{code}
276
277 simplOrTopPair is used for
278         * recursive bindings (whether top level or not)
279         * top-level non-recursive bindings
280
281 It assumes the binder has already been simplified, but not its IdInfo.
282
283 \begin{code}
284 simplRecOrTopPair :: SimplEnv
285                   -> TopLevelFlag
286                   -> InId -> OutBndr -> InExpr  -- Binder and rhs
287                   -> SimplM SimplEnv    -- Returns an env that includes the binding
288
289 simplRecOrTopPair env top_lvl old_bndr new_bndr rhs
290   | preInlineUnconditionally env top_lvl old_bndr rhs   -- Check for unconditional inline
291   = do  { tick (PreInlineUnconditionally old_bndr)
292         ; return (extendIdSubst env old_bndr (mkContEx env rhs)) }
293
294   | otherwise
295   = simplLazyBind env top_lvl Recursive old_bndr new_bndr rhs env
296         -- May not actually be recursive, but it doesn't matter
297 \end{code}
298
299
300 simplLazyBind is used for
301   * [simplRecOrTopPair] recursive bindings (whether top level or not)
302   * [simplRecOrTopPair] top-level non-recursive bindings
303   * [simplNonRecE]      non-top-level *lazy* non-recursive bindings
304
305 Nota bene:
306     1. It assumes that the binder is *already* simplified,
307        and is in scope, and its IdInfo too, except unfolding
308
309     2. It assumes that the binder type is lifted.
310
311     3. It does not check for pre-inline-unconditionallly;
312        that should have been done already.
313
314 \begin{code}
315 simplLazyBind :: SimplEnv
316               -> TopLevelFlag -> RecFlag
317               -> InId -> OutId          -- Binder, both pre-and post simpl
318                                         -- The OutId has IdInfo, except arity, unfolding
319               -> InExpr -> SimplEnv     -- The RHS and its environment
320               -> SimplM SimplEnv
321
322 simplLazyBind env top_lvl is_rec bndr bndr1 rhs rhs_se
323   = do  { let   rhs_env     = rhs_se `setInScope` env
324                 (tvs, body) = case collectTyBinders rhs of
325                                 (tvs, body) | not_lam body -> (tvs,body)
326                                             | otherwise    -> ([], rhs)
327                 not_lam (Lam _ _) = False
328                 not_lam _         = True
329                         -- Do not do the "abstract tyyvar" thing if there's
330                         -- a lambda inside, becuase it defeats eta-reduction
331                         --    f = /\a. \x. g a x  
332                         -- should eta-reduce
333
334         ; (body_env, tvs') <- simplBinders rhs_env tvs
335                 -- See Note [Floating and type abstraction] in SimplUtils
336
337         -- Simplify the RHS
338         ; (body_env1, body1) <- simplExprF body_env body mkRhsStop
339         -- ANF-ise a constructor or PAP rhs
340         ; (body_env2, body2) <- prepareRhs body_env1 body1
341
342         ; (env', rhs')
343             <-  if not (doFloatFromRhs top_lvl is_rec False body2 body_env2)
344                 then                            -- No floating, just wrap up!
345                      do { rhs' <- mkLam env tvs' (wrapFloats body_env2 body2)
346                         ; return (env, rhs') }
347
348                 else if null tvs then           -- Simple floating
349                      do { tick LetFloatFromLet
350                         ; return (addFloats env body_env2, body2) }
351
352                 else                            -- Do type-abstraction first
353                      do { tick LetFloatFromLet
354                         ; (poly_binds, body3) <- abstractFloats tvs' body_env2 body2
355                         ; rhs' <- mkLam env tvs' body3
356                         ; env' <- foldlM (addPolyBind top_lvl) env poly_binds
357                         ; return (env', rhs') }
358
359         ; completeBind env' top_lvl bndr bndr1 rhs' }
360 \end{code}
361
362 A specialised variant of simplNonRec used when the RHS is already simplified,
363 notably in knownCon.  It uses case-binding where necessary.
364
365 \begin{code}
366 simplNonRecX :: SimplEnv
367              -> InId            -- Old binder
368              -> OutExpr         -- Simplified RHS
369              -> SimplM SimplEnv
370
371 simplNonRecX env bndr new_rhs
372   | isDeadBinder bndr   -- Not uncommon; e.g. case (a,b) of b { (p,q) -> p }
373   = return env          --               Here b is dead, and we avoid creating
374   | otherwise           --               the binding b = (a,b)
375   = do  { (env', bndr') <- simplBinder env bndr
376         ; completeNonRecX env' (isStrictId bndr) bndr bndr' new_rhs }
377
378 completeNonRecX :: SimplEnv
379                 -> Bool
380                 -> InId                 -- Old binder
381                 -> OutId                -- New binder
382                 -> OutExpr              -- Simplified RHS
383                 -> SimplM SimplEnv
384
385 completeNonRecX env is_strict old_bndr new_bndr new_rhs
386   = do  { (env1, rhs1) <- prepareRhs (zapFloats env) new_rhs
387         ; (env2, rhs2) <-
388                 if doFloatFromRhs NotTopLevel NonRecursive is_strict rhs1 env1
389                 then do { tick LetFloatFromLet
390                         ; return (addFloats env env1, rhs1) }   -- Add the floats to the main env
391                 else return (env, wrapFloats env1 rhs1)         -- Wrap the floats around the RHS
392         ; completeBind env2 NotTopLevel old_bndr new_bndr rhs2 }
393 \end{code}
394
395 {- No, no, no!  Do not try preInlineUnconditionally in completeNonRecX
396    Doing so risks exponential behaviour, because new_rhs has been simplified once already
397    In the cases described by the folowing commment, postInlineUnconditionally will
398    catch many of the relevant cases.
399         -- This happens; for example, the case_bndr during case of
400         -- known constructor:  case (a,b) of x { (p,q) -> ... }
401         -- Here x isn't mentioned in the RHS, so we don't want to
402         -- create the (dead) let-binding  let x = (a,b) in ...
403         --
404         -- Similarly, single occurrences can be inlined vigourously
405         -- e.g.  case (f x, g y) of (a,b) -> ....
406         -- If a,b occur once we can avoid constructing the let binding for them.
407
408    Furthermore in the case-binding case preInlineUnconditionally risks extra thunks
409         -- Consider     case I# (quotInt# x y) of
410         --                I# v -> let w = J# v in ...
411         -- If we gaily inline (quotInt# x y) for v, we end up building an
412         -- extra thunk:
413         --                let w = J# (quotInt# x y) in ...
414         -- because quotInt# can fail.
415
416   | preInlineUnconditionally env NotTopLevel bndr new_rhs
417   = thing_inside (extendIdSubst env bndr (DoneEx new_rhs))
418 -}
419
420 ----------------------------------
421 prepareRhs takes a putative RHS, checks whether it's a PAP or
422 constructor application and, if so, converts it to ANF, so that the
423 resulting thing can be inlined more easily.  Thus
424         x = (f a, g b)
425 becomes
426         t1 = f a
427         t2 = g b
428         x = (t1,t2)
429
430 We also want to deal well cases like this
431         v = (f e1 `cast` co) e2
432 Here we want to make e1,e2 trivial and get
433         x1 = e1; x2 = e2; v = (f x1 `cast` co) v2
434 That's what the 'go' loop in prepareRhs does
435
436 \begin{code}
437 prepareRhs :: SimplEnv -> OutExpr -> SimplM (SimplEnv, OutExpr)
438 -- Adds new floats to the env iff that allows us to return a good RHS
439 prepareRhs env (Cast rhs co)    -- Note [Float coercions]
440   | (ty1, _ty2) <- coercionKind co       -- Do *not* do this if rhs has an unlifted type
441   , not (isUnLiftedType ty1)            -- see Note [Float coercions (unlifted)]
442   = do  { (env', rhs') <- makeTrivial env rhs
443         ; return (env', Cast rhs' co) }
444
445 prepareRhs env0 rhs0
446   = do  { (_is_val, env1, rhs1) <- go 0 env0 rhs0
447         ; return (env1, rhs1) }
448   where
449     go n_val_args env (Cast rhs co)
450         = do { (is_val, env', rhs') <- go n_val_args env rhs
451              ; return (is_val, env', Cast rhs' co) }
452     go n_val_args env (App fun (Type ty))
453         = do { (is_val, env', rhs') <- go n_val_args env fun
454              ; return (is_val, env', App rhs' (Type ty)) }
455     go n_val_args env (App fun arg)
456         = do { (is_val, env', fun') <- go (n_val_args+1) env fun
457              ; case is_val of
458                 True -> do { (env'', arg') <- makeTrivial env' arg
459                            ; return (True, env'', App fun' arg') }
460                 False -> return (False, env, App fun arg) }
461     go n_val_args env (Var fun)
462         = return (is_val, env, Var fun)
463         where
464           is_val = n_val_args > 0       -- There is at least one arg
465                                         -- ...and the fun a constructor or PAP
466                  && (isConLikeId fun || n_val_args < idArity fun)
467                                    -- See Note [CONLIKE pragma] in BasicTypes
468     go _ env other
469         = return (False, env, other)
470 \end{code}
471
472
473 Note [Float coercions]
474 ~~~~~~~~~~~~~~~~~~~~~~
475 When we find the binding
476         x = e `cast` co
477 we'd like to transform it to
478         x' = e
479         x = x `cast` co         -- A trivial binding
480 There's a chance that e will be a constructor application or function, or something
481 like that, so moving the coerion to the usage site may well cancel the coersions
482 and lead to further optimisation.  Example:
483
484      data family T a :: *
485      data instance T Int = T Int
486
487      foo :: Int -> Int -> Int
488      foo m n = ...
489         where
490           x = T m
491           go 0 = 0
492           go n = case x of { T m -> go (n-m) }
493                 -- This case should optimise
494
495 Note [Float coercions (unlifted)]
496 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
497 BUT don't do [Float coercions] if 'e' has an unlifted type.
498 This *can* happen:
499
500      foo :: Int = (error (# Int,Int #) "urk")
501                   `cast` CoUnsafe (# Int,Int #) Int
502
503 If do the makeTrivial thing to the error call, we'll get
504     foo = case error (# Int,Int #) "urk" of v -> v `cast` ...
505 But 'v' isn't in scope!
506
507 These strange casts can happen as a result of case-of-case
508         bar = case (case x of { T -> (# 2,3 #); F -> error "urk" }) of
509                 (# p,q #) -> p+q
510
511
512 \begin{code}
513 makeTrivial :: SimplEnv -> OutExpr -> SimplM (SimplEnv, OutExpr)
514 -- Binds the expression to a variable, if it's not trivial, returning the variable
515 makeTrivial env expr
516   | exprIsTrivial expr
517   = return (env, expr)
518   | otherwise           -- See Note [Take care] below
519   = do  { var <- newId (fsLit "a") (exprType expr)
520         ; env' <- completeNonRecX env False var var expr
521 --        pprTrace "makeTrivial" (vcat [ppr var <+> ppr (exprArity (substExpr env' (Var var)))
522 --                                     , ppr expr
523 --                                     , ppr (substExpr env' (Var var))
524 --                                     , ppr (idArity (fromJust (lookupInScope (seInScope env') var))) ]) $
525         ; return (env', substExpr env' (Var var)) }
526         -- The substitution is needed becase we're constructing a new binding
527         --     a = rhs
528         -- And if rhs is of form (rhs1 |> co), then we might get
529         --     a1 = rhs1
530         --     a = a1 |> co
531         -- and now a's RHS is trivial and can be substituted out, and that
532         -- is what completeNonRecX will do
533 \end{code}
534
535
536 %************************************************************************
537 %*                                                                      *
538 \subsection{Completing a lazy binding}
539 %*                                                                      *
540 %************************************************************************
541
542 completeBind
543   * deals only with Ids, not TyVars
544   * takes an already-simplified binder and RHS
545   * is used for both recursive and non-recursive bindings
546   * is used for both top-level and non-top-level bindings
547
548 It does the following:
549   - tries discarding a dead binding
550   - tries PostInlineUnconditionally
551   - add unfolding [this is the only place we add an unfolding]
552   - add arity
553
554 It does *not* attempt to do let-to-case.  Why?  Because it is used for
555   - top-level bindings (when let-to-case is impossible)
556   - many situations where the "rhs" is known to be a WHNF
557                 (so let-to-case is inappropriate).
558
559 Nor does it do the atomic-argument thing
560
561 \begin{code}
562 completeBind :: SimplEnv
563              -> TopLevelFlag            -- Flag stuck into unfolding
564              -> InId                    -- Old binder
565              -> OutId -> OutExpr        -- New binder and RHS
566              -> SimplM SimplEnv
567 -- completeBind may choose to do its work
568 --      * by extending the substitution (e.g. let x = y in ...)
569 --      * or by adding to the floats in the envt
570
571 completeBind env top_lvl old_bndr new_bndr new_rhs
572   = do  { let old_info = idInfo old_bndr
573               old_unf  = unfoldingInfo old_info
574               occ_info = occInfo old_info
575
576         ; new_unfolding <- simplUnfolding env top_lvl old_bndr occ_info new_rhs old_unf
577
578         ; if postInlineUnconditionally env top_lvl new_bndr occ_info new_rhs new_unfolding
579                         -- Inline and discard the binding
580           then do  { tick (PostInlineUnconditionally old_bndr)
581                     ; return (extendIdSubst env old_bndr (DoneEx new_rhs)) }
582                 -- Use the substitution to make quite, quite sure that the
583                 -- substitution will happen, since we are going to discard the binding
584
585           else return (addNonRecWithUnf env new_bndr new_rhs new_unfolding) }
586
587 ------------------------------
588 addPolyBind :: TopLevelFlag -> SimplEnv -> OutBind -> SimplM SimplEnv
589 -- Add a new binding to the environment, complete with its unfolding
590 -- but *do not* do postInlineUnconditionally, because we have already
591 -- processed some of the scope of the binding
592 -- We still want the unfolding though.  Consider
593 --      let 
594 --            x = /\a. let y = ... in Just y
595 --      in body
596 -- Then we float the y-binding out (via abstractFloats and addPolyBind)
597 -- but 'x' may well then be inlined in 'body' in which case we'd like the 
598 -- opportunity to inline 'y' too.
599
600 addPolyBind top_lvl env (NonRec poly_id rhs)
601   = do  { unfolding <- simplUnfolding env top_lvl poly_id NoOccInfo rhs noUnfolding
602                         -- Assumes that poly_id did not have an INLINE prag
603                         -- which is perhaps wrong.  ToDo: think about this
604         ; return (addNonRecWithUnf env poly_id rhs unfolding) }
605
606 addPolyBind _ env bind@(Rec _) = return (extendFloats env bind)
607                 -- Hack: letrecs are more awkward, so we extend "by steam"
608                 -- without adding unfoldings etc.  At worst this leads to
609                 -- more simplifier iterations
610
611 ------------------------------
612 addNonRecWithUnf :: SimplEnv
613                  -> OutId -> OutExpr    -- New binder and RHS
614                  -> Unfolding           -- New unfolding
615                  -> SimplEnv
616 addNonRecWithUnf env new_bndr new_rhs new_unfolding
617   = let new_arity = exprArity new_rhs
618         old_arity = idArity new_bndr
619         info1 = idInfo new_bndr `setArityInfo` new_arity
620         
621               -- Unfolding info: Note [Setting the new unfolding]
622         info2 = info1 `setUnfoldingInfo` new_unfolding
623
624         -- Demand info: Note [Setting the demand info]
625         info3 | isEvaldUnfolding new_unfolding = zapDemandInfo info2 `orElse` info2
626               | otherwise                      = info2
627
628         final_id = new_bndr `setIdInfo` info3
629         dmd_arity = length $ fst $ splitStrictSig $ idNewStrictness new_bndr
630     in
631     ASSERT( isId new_bndr )
632     WARN( new_arity < old_arity || new_arity < dmd_arity, 
633           (ptext (sLit "Arity decrease:") <+> ppr final_id <+> ppr old_arity
634                 <+> ppr new_arity <+> ppr dmd_arity) )
635         -- Note [Arity decrease]
636
637     final_id `seq`   -- This seq forces the Id, and hence its IdInfo,
638                      -- and hence any inner substitutions
639             -- pprTrace "Binding" (ppr final_id <+> ppr unfolding) $
640     addNonRec env final_id new_rhs
641                 -- The addNonRec adds it to the in-scope set too
642
643 ------------------------------
644 simplUnfolding :: SimplEnv-> TopLevelFlag
645                -> Id    -- Debug output only
646                -> OccInfo -> OutExpr
647                -> Unfolding -> SimplM Unfolding
648 -- Note [Setting the new unfolding]
649 simplUnfolding env _ _ _ _ (DFunUnfolding con ops)
650   = return (DFunUnfolding con ops')
651   where
652     ops' = map (CoreSubst.substExpr (mkCoreSubst env)) ops
653
654 simplUnfolding env top_lvl _ _ _ 
655     (CoreUnfolding { uf_tmpl = expr, uf_arity = arity
656                    , uf_guidance = guide@(InlineRule {}) })
657   = do { expr' <- simplExpr (setMode simplGentlyForInlineRules env) expr
658                -- See Note [Simplifying gently inside InlineRules] in SimplUtils
659        ; let mb_wkr' = CoreSubst.substInlineRuleInfo (mkCoreSubst env) (ir_info guide)
660        ; return (mkCoreUnfolding (isTopLevel top_lvl) expr' arity 
661                                  (guide { ir_info = mb_wkr' })) }
662                 -- See Note [Top-level flag on inline rules] in CoreUnfold
663
664 simplUnfolding _ top_lvl _ occ_info new_rhs _
665   | omit_unfolding = return NoUnfolding 
666   | otherwise      = return (mkUnfolding (isTopLevel top_lvl) new_rhs)
667   where
668     omit_unfolding = isNonRuleLoopBreaker occ_info
669 \end{code}
670
671 Note [Arity decrease]
672 ~~~~~~~~~~~~~~~~~~~~~
673 Generally speaking the arity of a binding should not decrease.  But it *can* 
674 legitimately happen becuase of RULES.  Eg
675         f = g Int
676 where g has arity 2, will have arity 2.  But if there's a rewrite rule
677         g Int --> h
678 where h has arity 1, then f's arity will decrease.  Here's a real-life example,
679 which is in the output of Specialise:
680
681      Rec {
682         $dm {Arity 2} = \d.\x. op d
683         {-# RULES forall d. $dm Int d = $s$dm #-}
684         
685         dInt = MkD .... opInt ...
686         opInt {Arity 1} = $dm dInt
687
688         $s$dm {Arity 0} = \x. op dInt }
689
690 Here opInt has arity 1; but when we apply the rule its arity drops to 0.
691 That's why Specialise goes to a little trouble to pin the right arity
692 on specialised functions too.
693
694 Note [Setting the new unfolding]
695 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
696 * If there's an INLINE pragma, we simplify the RHS gently.  Maybe we
697   should do nothing at all, but simplifying gently might get rid of 
698   more crap.
699
700 * If not, we make an unfolding from the new RHS.  But *only* for
701   non-loop-breakers. Making loop breakers not have an unfolding at all
702   means that we can avoid tests in exprIsConApp, for example.  This is
703   important: if exprIsConApp says 'yes' for a recursive thing, then we
704   can get into an infinite loop
705
706 If there's an InlineRule on a loop breaker, we hang on to the inlining.
707 It's pretty dodgy, but the user did say 'INLINE'.  May need to revisit
708 this choice.
709
710 Note [Setting the demand info]
711 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
712 If the unfolding is a value, the demand info may
713 go pear-shaped, so we nuke it.  Example:
714      let x = (a,b) in
715      case x of (p,q) -> h p q x
716 Here x is certainly demanded. But after we've nuked
717 the case, we'll get just
718      let x = (a,b) in h a b x
719 and now x is not demanded (I'm assuming h is lazy)
720 This really happens.  Similarly
721      let f = \x -> e in ...f..f...
722 After inlining f at some of its call sites the original binding may
723 (for example) be no longer strictly demanded.
724 The solution here is a bit ad hoc...
725
726
727 %************************************************************************
728 %*                                                                      *
729 \subsection[Simplify-simplExpr]{The main function: simplExpr}
730 %*                                                                      *
731 %************************************************************************
732
733 The reason for this OutExprStuff stuff is that we want to float *after*
734 simplifying a RHS, not before.  If we do so naively we get quadratic
735 behaviour as things float out.
736
737 To see why it's important to do it after, consider this (real) example:
738
739         let t = f x
740         in fst t
741 ==>
742         let t = let a = e1
743                     b = e2
744                 in (a,b)
745         in fst t
746 ==>
747         let a = e1
748             b = e2
749             t = (a,b)
750         in
751         a       -- Can't inline a this round, cos it appears twice
752 ==>
753         e1
754
755 Each of the ==> steps is a round of simplification.  We'd save a
756 whole round if we float first.  This can cascade.  Consider
757
758         let f = g d
759         in \x -> ...f...
760 ==>
761         let f = let d1 = ..d.. in \y -> e
762         in \x -> ...f...
763 ==>
764         let d1 = ..d..
765         in \x -> ...(\y ->e)...
766
767 Only in this second round can the \y be applied, and it
768 might do the same again.
769
770
771 \begin{code}
772 simplExpr :: SimplEnv -> CoreExpr -> SimplM CoreExpr
773 simplExpr env expr = simplExprC env expr mkBoringStop
774
775 simplExprC :: SimplEnv -> CoreExpr -> SimplCont -> SimplM CoreExpr
776         -- Simplify an expression, given a continuation
777 simplExprC env expr cont
778   = -- pprTrace "simplExprC" (ppr expr $$ ppr cont {- $$ ppr (seIdSubst env) -} $$ ppr (seFloats env) ) $
779     do  { (env', expr') <- simplExprF (zapFloats env) expr cont
780         ; -- pprTrace "simplExprC ret" (ppr expr $$ ppr expr') $
781           -- pprTrace "simplExprC ret3" (ppr (seInScope env')) $
782           -- pprTrace "simplExprC ret4" (ppr (seFloats env')) $
783           return (wrapFloats env' expr') }
784
785 --------------------------------------------------
786 simplExprF :: SimplEnv -> InExpr -> SimplCont
787            -> SimplM (SimplEnv, OutExpr)
788
789 simplExprF env e cont
790   = -- pprTrace "simplExprF" (ppr e $$ ppr cont $$ ppr (seTvSubst env) $$ ppr (seIdSubst env) {- $$ ppr (seFloats env) -} ) $
791     simplExprF' env e cont
792
793 simplExprF' :: SimplEnv -> InExpr -> SimplCont
794             -> SimplM (SimplEnv, OutExpr)
795 simplExprF' env (Var v)        cont = simplVar env v cont
796 simplExprF' env (Lit lit)      cont = rebuild env (Lit lit) cont
797 simplExprF' env (Note n expr)  cont = simplNote env n expr cont
798 simplExprF' env (Cast body co) cont = simplCast env body co cont
799 simplExprF' env (App fun arg)  cont = simplExprF env fun $
800                                       ApplyTo NoDup arg env cont
801
802 simplExprF' env expr@(Lam _ _) cont
803   = simplLam env (map zap bndrs) body cont
804         -- The main issue here is under-saturated lambdas
805         --   (\x1. \x2. e) arg1
806         -- Here x1 might have "occurs-once" occ-info, because occ-info
807         -- is computed assuming that a group of lambdas is applied
808         -- all at once.  If there are too few args, we must zap the
809         -- occ-info.
810   where
811     n_args   = countArgs cont
812     n_params = length bndrs
813     (bndrs, body) = collectBinders expr
814     zap | n_args >= n_params = \b -> b
815         | otherwise          = \b -> if isTyVar b then b
816                                      else zapLamIdInfo b
817         -- NB: we count all the args incl type args
818         -- so we must count all the binders (incl type lambdas)
819
820 simplExprF' env (Type ty) cont
821   = ASSERT( contIsRhsOrArg cont )
822     do  { ty' <- simplCoercion env ty
823         ; rebuild env (Type ty') cont }
824
825 simplExprF' env (Case scrut bndr _ alts) cont
826   | not (switchIsOn (getSwitchChecker env) NoCaseOfCase)
827   =     -- Simplify the scrutinee with a Select continuation
828     simplExprF env scrut (Select NoDup bndr alts env cont)
829
830   | otherwise
831   =     -- If case-of-case is off, simply simplify the case expression
832         -- in a vanilla Stop context, and rebuild the result around it
833     do  { case_expr' <- simplExprC env scrut case_cont
834         ; rebuild env case_expr' cont }
835   where
836     case_cont = Select NoDup bndr alts env mkBoringStop
837
838 simplExprF' env (Let (Rec pairs) body) cont
839   = do  { env' <- simplRecBndrs env (map fst pairs)
840                 -- NB: bndrs' don't have unfoldings or rules
841                 -- We add them as we go down
842
843         ; env'' <- simplRecBind env' NotTopLevel pairs
844         ; simplExprF env'' body cont }
845
846 simplExprF' env (Let (NonRec bndr rhs) body) cont
847   = simplNonRecE env bndr (rhs, env) ([], body) cont
848
849 ---------------------------------
850 simplType :: SimplEnv -> InType -> SimplM OutType
851         -- Kept monadic just so we can do the seqType
852 simplType env ty
853   = -- pprTrace "simplType" (ppr ty $$ ppr (seTvSubst env)) $
854     seqType new_ty   `seq`   return new_ty
855   where
856     new_ty = substTy env ty
857
858 ---------------------------------
859 simplCoercion :: SimplEnv -> InType -> SimplM OutType
860 -- The InType isn't *necessarily* a coercion, but it might be
861 -- (in a type application, say) and optCoercion is a no-op on types
862 simplCoercion env co
863   = do { co' <- simplType env co
864        ; return (optCoercion co') }
865 \end{code}
866
867
868 %************************************************************************
869 %*                                                                      *
870 \subsection{The main rebuilder}
871 %*                                                                      *
872 %************************************************************************
873
874 \begin{code}
875 rebuild :: SimplEnv -> OutExpr -> SimplCont -> SimplM (SimplEnv, OutExpr)
876 -- At this point the substitution in the SimplEnv should be irrelevant
877 -- only the in-scope set and floats should matter
878 rebuild env expr cont0
879   = -- pprTrace "rebuild" (ppr expr $$ ppr cont0 $$ ppr (seFloats env)) $
880     case cont0 of
881       Stop {}                      -> return (env, expr)
882       CoerceIt co cont             -> rebuild env (mkCoerce co expr) cont
883       Select _ bndr alts se cont   -> rebuildCase (se `setFloats` env) expr bndr alts cont
884       StrictArg fun _ info cont    -> rebuildCall env (fun `App` expr) info cont
885       StrictBind b bs body se cont -> do { env' <- simplNonRecX (se `setFloats` env) b expr
886                                          ; simplLam env' bs body cont }
887       ApplyTo _ arg se cont        -> do { arg' <- simplExpr (se `setInScope` env) arg
888                                          ; rebuild env (App expr arg') cont }
889 \end{code}
890
891
892 %************************************************************************
893 %*                                                                      *
894 \subsection{Lambdas}
895 %*                                                                      *
896 %************************************************************************
897
898 \begin{code}
899 simplCast :: SimplEnv -> InExpr -> Coercion -> SimplCont
900           -> SimplM (SimplEnv, OutExpr)
901 simplCast env body co0 cont0
902   = do  { co1 <- simplCoercion env co0
903         ; simplExprF env body (addCoerce co1 cont0) }
904   where
905        addCoerce co cont = add_coerce co (coercionKind co) cont
906
907        add_coerce _co (s1, k1) cont     -- co :: ty~ty
908          | s1 `coreEqType` k1 = cont    -- is a no-op
909
910        add_coerce co1 (s1, _k2) (CoerceIt co2 cont)
911          | (_l1, t1) <- coercionKind co2
912                 --      e |> (g1 :: S1~L) |> (g2 :: L~T1)
913                 -- ==>
914                 --      e,                       if S1=T1
915                 --      e |> (g1 . g2 :: S1~T1)  otherwise
916                 --
917                 -- For example, in the initial form of a worker
918                 -- we may find  (coerce T (coerce S (\x.e))) y
919                 -- and we'd like it to simplify to e[y/x] in one round
920                 -- of simplification
921          , s1 `coreEqType` t1  = cont            -- The coerces cancel out
922          | otherwise           = CoerceIt (mkTransCoercion co1 co2) cont
923
924        add_coerce co (s1s2, _t1t2) (ApplyTo dup (Type arg_ty) arg_se cont)
925                 -- (f |> g) ty  --->   (f ty) |> (g @ ty)
926                 -- This implements the PushT rule from the paper
927          | Just (tyvar,_) <- splitForAllTy_maybe s1s2
928          , not (isCoVar tyvar)
929          = ApplyTo dup (Type ty') (zapSubstEnv env) (addCoerce (mkInstCoercion co ty') cont)
930          where
931            ty' = substTy (arg_se `setInScope` env) arg_ty
932
933         -- ToDo: the PushC rule is not implemented at all
934
935        add_coerce co (s1s2, _t1t2) (ApplyTo dup arg arg_se cont)
936          | not (isTypeArg arg)  -- This implements the Push rule from the paper
937          , isFunTy s1s2   -- t1t2 must be a function type, becuase it's applied
938                 --      (e |> (g :: s1s2 ~ t1->t2)) f
939                 -- ===>
940                 --      (e (f |> (arg g :: t1~s1))
941                 --      |> (res g :: s2->t2)
942                 --
943                 -- t1t2 must be a function type, t1->t2, because it's applied
944                 -- to something but s1s2 might conceivably not be
945                 --
946                 -- When we build the ApplyTo we can't mix the out-types
947                 -- with the InExpr in the argument, so we simply substitute
948                 -- to make it all consistent.  It's a bit messy.
949                 -- But it isn't a common case.
950                 --
951                 -- Example of use: Trac #995
952          = ApplyTo dup new_arg (zapSubstEnv env) (addCoerce co2 cont)
953          where
954            -- we split coercion t1->t2 ~ s1->s2 into t1 ~ s1 and
955            -- t2 ~ s2 with left and right on the curried form:
956            --    (->) t1 t2 ~ (->) s1 s2
957            [co1, co2] = decomposeCo 2 co
958            new_arg    = mkCoerce (mkSymCoercion co1) arg'
959            arg'       = substExpr (arg_se `setInScope` env) arg
960
961        add_coerce co _ cont = CoerceIt co cont
962 \end{code}
963
964
965 %************************************************************************
966 %*                                                                      *
967 \subsection{Lambdas}
968 %*                                                                      *
969 %************************************************************************
970
971 \begin{code}
972 simplLam :: SimplEnv -> [InId] -> InExpr -> SimplCont
973          -> SimplM (SimplEnv, OutExpr)
974
975 simplLam env [] body cont = simplExprF env body cont
976
977         -- Beta reduction
978 simplLam env (bndr:bndrs) body (ApplyTo _ arg arg_se cont)
979   = do  { tick (BetaReduction bndr)
980         ; simplNonRecE env bndr (arg, arg_se) (bndrs, body) cont }
981
982         -- Not enough args, so there are real lambdas left to put in the result
983 simplLam env bndrs body cont
984   = do  { (env', bndrs') <- simplLamBndrs env bndrs
985         ; body' <- simplExpr env' body
986         ; new_lam <- mkLam env' bndrs' body'
987         ; rebuild env' new_lam cont }
988
989 ------------------
990 simplNonRecE :: SimplEnv
991              -> InBndr                  -- The binder
992              -> (InExpr, SimplEnv)      -- Rhs of binding (or arg of lambda)
993              -> ([InBndr], InExpr)      -- Body of the let/lambda
994                                         --      \xs.e
995              -> SimplCont
996              -> SimplM (SimplEnv, OutExpr)
997
998 -- simplNonRecE is used for
999 --  * non-top-level non-recursive lets in expressions
1000 --  * beta reduction
1001 --
1002 -- It deals with strict bindings, via the StrictBind continuation,
1003 -- which may abort the whole process
1004 --
1005 -- The "body" of the binding comes as a pair of ([InId],InExpr)
1006 -- representing a lambda; so we recurse back to simplLam
1007 -- Why?  Because of the binder-occ-info-zapping done before
1008 --       the call to simplLam in simplExprF (Lam ...)
1009
1010         -- First deal with type applications and type lets
1011         --   (/\a. e) (Type ty)   and   (let a = Type ty in e)
1012 simplNonRecE env bndr (Type ty_arg, rhs_se) (bndrs, body) cont
1013   = ASSERT( isTyVar bndr )
1014     do  { ty_arg' <- simplType (rhs_se `setInScope` env) ty_arg
1015         ; simplLam (extendTvSubst env bndr ty_arg') bndrs body cont }
1016
1017 simplNonRecE env bndr (rhs, rhs_se) (bndrs, body) cont
1018   | preInlineUnconditionally env NotTopLevel bndr rhs
1019   = do  { tick (PreInlineUnconditionally bndr)
1020         ; simplLam (extendIdSubst env bndr (mkContEx rhs_se rhs)) bndrs body cont }
1021
1022   | isStrictId bndr
1023   = do  { simplExprF (rhs_se `setFloats` env) rhs
1024                      (StrictBind bndr bndrs body env cont) }
1025
1026   | otherwise
1027   = ASSERT( not (isTyVar bndr) )
1028     do  { (env1, bndr1) <- simplNonRecBndr env bndr
1029         ; let (env2, bndr2) = addBndrRules env1 bndr bndr1
1030         ; env3 <- simplLazyBind env2 NotTopLevel NonRecursive bndr bndr2 rhs rhs_se
1031         ; simplLam env3 bndrs body cont }
1032 \end{code}
1033
1034
1035 %************************************************************************
1036 %*                                                                      *
1037 \subsection{Notes}
1038 %*                                                                      *
1039 %************************************************************************
1040
1041 \begin{code}
1042 -- Hack alert: we only distinguish subsumed cost centre stacks for the
1043 -- purposes of inlining.  All other CCCSs are mapped to currentCCS.
1044 simplNote :: SimplEnv -> Note -> CoreExpr -> SimplCont
1045           -> SimplM (SimplEnv, OutExpr)
1046 simplNote env (SCC cc) e cont
1047   | pushCCisNop cc (getEnclosingCC env)  -- scc "f" (...(scc "f" e)...) 
1048   = simplExprF env e cont                -- ==>  scc "f" (...e...)
1049   | otherwise
1050   = do  { e' <- simplExpr (setEnclosingCC env currentCCS) e
1051         ; rebuild env (mkSCC cc e') cont }
1052
1053 simplNote env (CoreNote s) e cont
1054   = do { e' <- simplExpr env e
1055        ; rebuild env (Note (CoreNote s) e') cont }
1056 \end{code}
1057
1058
1059 %************************************************************************
1060 %*                                                                      *
1061 \subsection{Dealing with calls}
1062 %*                                                                      *
1063 %************************************************************************
1064
1065 \begin{code}
1066 simplVar :: SimplEnv -> Id -> SimplCont -> SimplM (SimplEnv, OutExpr)
1067 simplVar env var cont
1068   = case substId env var of
1069         DoneEx e         -> simplExprF (zapSubstEnv env) e cont
1070         ContEx tvs ids e -> simplExprF (setSubstEnv env tvs ids) e cont
1071         DoneId var1      -> completeCall (zapSubstEnv env) var1 cont
1072                 -- Note [zapSubstEnv]
1073                 -- The template is already simplified, so don't re-substitute.
1074                 -- This is VITAL.  Consider
1075                 --      let x = e in
1076                 --      let y = \z -> ...x... in
1077                 --      \ x -> ...y...
1078                 -- We'll clone the inner \x, adding x->x' in the id_subst
1079                 -- Then when we inline y, we must *not* replace x by x' in
1080                 -- the inlined copy!!
1081
1082 ---------------------------------------------------------
1083 --      Dealing with a call site
1084
1085 completeCall :: SimplEnv -> Id -> SimplCont -> SimplM (SimplEnv, OutExpr)
1086 completeCall env var cont
1087   = do  { let   (args,call_cont) = contArgs cont
1088                 -- The args are OutExprs, obtained by *lazily* substituting
1089                 -- in the args found in cont.  These args are only examined
1090                 -- to limited depth (unless a rule fires).  But we must do
1091                 -- the substitution; rule matching on un-simplified args would
1092                 -- be bogus
1093
1094         ------------- First try rules ----------------
1095         -- Do this before trying inlining.  Some functions have
1096         -- rules *and* are strict; in this case, we don't want to
1097         -- inline the wrapper of the non-specialised thing; better
1098         -- to call the specialised thing instead.
1099         --
1100         -- We used to use the black-listing mechanism to ensure that inlining of
1101         -- the wrapper didn't occur for things that have specialisations till a
1102         -- later phase, so but now we just try RULES first
1103         -- 
1104         -- See also Note [Rules for recursive functions]
1105         ; rule_base <- getSimplRules
1106         ; let rules = getRules rule_base var
1107         ; mb_rule <- tryRules env var rules args call_cont
1108         ; case mb_rule of {
1109              Just (n_args, rule_rhs) -> simplExprF env rule_rhs (dropArgs n_args cont) ;
1110                  -- The ruleArity says how many args the rule consumed
1111            ; Nothing -> do       -- No rules
1112
1113
1114         ------------- Next try inlining ----------------
1115         { dflags <- getDOptsSmpl
1116         ; let   arg_infos = [interestingArg arg | arg <- args, isValArg arg]
1117                 n_val_args = length arg_infos
1118                 interesting_cont = interestingCallContext call_cont
1119                 active_inline = activeInline env var
1120                 maybe_inline  = callSiteInline dflags active_inline var
1121                                                (null args) arg_infos interesting_cont
1122         ; case maybe_inline of {
1123             Just unfolding      -- There is an inlining!
1124               ->  do { tick (UnfoldingDone var)
1125                      ; (if dopt Opt_D_dump_inlinings dflags then
1126                            pprTrace ("Inlining done: " ++ showSDoc (ppr var)) (vcat [
1127                                 text "Before:" <+> ppr var <+> sep (map pprParendExpr args),
1128                                 text "Inlined fn: " <+> nest 2 (ppr unfolding),
1129                                 text "Cont:  " <+> ppr call_cont])
1130                          else
1131                                 id)
1132                        simplExprF env unfolding cont }
1133
1134             ; Nothing ->                -- No inlining!
1135
1136         ------------- No inlining! ----------------
1137         -- Next, look for rules or specialisations that match
1138         --
1139         rebuildCall env (Var var)
1140                     (mkArgInfo var rules n_val_args call_cont) 
1141                     cont
1142     }}}}
1143
1144 rebuildCall :: SimplEnv
1145             -> OutExpr       -- Function 
1146             -> ArgInfo
1147             -> SimplCont
1148             -> SimplM (SimplEnv, OutExpr)
1149 rebuildCall env fun (ArgInfo { ai_strs = [] }) cont
1150   -- When we run out of strictness args, it means
1151   -- that the call is definitely bottom; see SimplUtils.mkArgInfo
1152   -- Then we want to discard the entire strict continuation.  E.g.
1153   --    * case (error "hello") of { ... }
1154   --    * (error "Hello") arg
1155   --    * f (error "Hello") where f is strict
1156   --    etc
1157   -- Then, especially in the first of these cases, we'd like to discard
1158   -- the continuation, leaving just the bottoming expression.  But the
1159   -- type might not be right, so we may have to add a coerce.
1160   | not (contIsTrivial cont)     -- Only do this if there is a non-trivial
1161   = return (env, mk_coerce fun)  -- contination to discard, else we do it
1162   where                          -- again and again!
1163     fun_ty  = exprType fun
1164     cont_ty = contResultType env fun_ty cont
1165     co      = mkUnsafeCoercion fun_ty cont_ty
1166     mk_coerce expr | cont_ty `coreEqType` fun_ty = expr
1167                    | otherwise = mkCoerce co expr
1168
1169 rebuildCall env fun info (ApplyTo _ (Type arg_ty) se cont)
1170   = do  { ty' <- simplCoercion (se `setInScope` env) arg_ty
1171         ; rebuildCall env (fun `App` Type ty') info cont }
1172
1173 rebuildCall env fun 
1174            (ArgInfo { ai_rules = has_rules, ai_strs = str:strs, ai_discs = disc:discs })
1175            (ApplyTo _ arg arg_se cont)
1176   | str                 -- Strict argument
1177   = -- pprTrace "Strict Arg" (ppr arg $$ ppr (seIdSubst env) $$ ppr (seInScope env)) $
1178     simplExprF (arg_se `setFloats` env) arg
1179                (StrictArg fun cci arg_info' cont)
1180                 -- Note [Shadowing]
1181
1182   | otherwise                           -- Lazy argument
1183         -- DO NOT float anything outside, hence simplExprC
1184         -- There is no benefit (unlike in a let-binding), and we'd
1185         -- have to be very careful about bogus strictness through
1186         -- floating a demanded let.
1187   = do  { arg' <- simplExprC (arg_se `setInScope` env) arg
1188                              (mkLazyArgStop cci)
1189         ; rebuildCall env (fun `App` arg') arg_info' cont }
1190   where
1191     arg_info' = ArgInfo { ai_rules = has_rules, ai_strs = strs, ai_discs = discs }
1192     cci | has_rules || disc > 0 = ArgCtxt has_rules  -- Be keener here
1193         | otherwise             = BoringCtxt         -- Nothing interesting
1194
1195 rebuildCall env fun _ cont
1196   = rebuild env fun cont
1197 \end{code}
1198
1199 Note [Shadowing]
1200 ~~~~~~~~~~~~~~~~
1201 This part of the simplifier may break the no-shadowing invariant
1202 Consider
1203         f (...(\a -> e)...) (case y of (a,b) -> e')
1204 where f is strict in its second arg
1205 If we simplify the innermost one first we get (...(\a -> e)...)
1206 Simplifying the second arg makes us float the case out, so we end up with
1207         case y of (a,b) -> f (...(\a -> e)...) e'
1208 So the output does not have the no-shadowing invariant.  However, there is
1209 no danger of getting name-capture, because when the first arg was simplified
1210 we used an in-scope set that at least mentioned all the variables free in its
1211 static environment, and that is enough.
1212
1213 We can't just do innermost first, or we'd end up with a dual problem:
1214         case x of (a,b) -> f e (...(\a -> e')...)
1215
1216 I spent hours trying to recover the no-shadowing invariant, but I just could
1217 not think of an elegant way to do it.  The simplifier is already knee-deep in
1218 continuations.  We have to keep the right in-scope set around; AND we have
1219 to get the effect that finding (error "foo") in a strict arg position will
1220 discard the entire application and replace it with (error "foo").  Getting
1221 all this at once is TOO HARD!
1222
1223
1224 %************************************************************************
1225 %*                                                                      *
1226                 Rewrite rules
1227 %*                                                                      *
1228 %************************************************************************
1229
1230 \begin{code}
1231 tryRules :: SimplEnv
1232          -> Id -> [CoreRule] -> [OutExpr] -> SimplCont 
1233          -> SimplM (Maybe (Arity, CoreExpr))         -- The arity is the number of
1234                                                      -- args consumed by the rule
1235 tryRules env fn rules args call_cont
1236   | null rules
1237   = return Nothing
1238   | otherwise
1239   = do { dflags <- getDOptsSmpl
1240        ; case activeRule dflags env of {
1241            Nothing     -> return Nothing  ; -- No rules apply
1242            Just act_fn -> 
1243
1244          case lookupRule act_fn (getInScope env) fn args rules of {
1245            Nothing               -> return Nothing ;   -- No rule matches
1246            Just (rule, rule_rhs) ->
1247
1248              do { tick (RuleFired (ru_name rule))
1249                 ; (if dopt Opt_D_dump_rule_firings dflags then
1250                      pprTrace "Rule fired" (vcat [
1251                         text "Rule:" <+> ftext (ru_name rule),
1252                         text "Before:" <+> ppr fn <+> sep (map pprParendExpr args),
1253                         text "After: " <+> pprCoreExpr rule_rhs,
1254                         text "Cont:  " <+> ppr call_cont])
1255                    else
1256                         id)             $
1257                    return (Just (ruleArity rule, rule_rhs)) }}}}
1258 \end{code}
1259
1260 Note [Rules for recursive functions]
1261 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1262 You might think that we shouldn't apply rules for a loop breaker:
1263 doing so might give rise to an infinite loop, because a RULE is
1264 rather like an extra equation for the function:
1265      RULE:           f (g x) y = x+y
1266      Eqn:            f a     y = a-y
1267
1268 But it's too drastic to disable rules for loop breakers.
1269 Even the foldr/build rule would be disabled, because foldr
1270 is recursive, and hence a loop breaker:
1271      foldr k z (build g) = g k z
1272 So it's up to the programmer: rules can cause divergence
1273
1274
1275 %************************************************************************
1276 %*                                                                      *
1277                 Rebuilding a cse expression
1278 %*                                                                      *
1279 %************************************************************************
1280
1281 Note [Case elimination]
1282 ~~~~~~~~~~~~~~~~~~~~~~~
1283 The case-elimination transformation discards redundant case expressions.
1284 Start with a simple situation:
1285
1286         case x# of      ===>   e[x#/y#]
1287           y# -> e
1288
1289 (when x#, y# are of primitive type, of course).  We can't (in general)
1290 do this for algebraic cases, because we might turn bottom into
1291 non-bottom!
1292
1293 The code in SimplUtils.prepareAlts has the effect of generalise this
1294 idea to look for a case where we're scrutinising a variable, and we
1295 know that only the default case can match.  For example:
1296
1297         case x of
1298           0#      -> ...
1299           DEFAULT -> ...(case x of
1300                          0#      -> ...
1301                          DEFAULT -> ...) ...
1302
1303 Here the inner case is first trimmed to have only one alternative, the
1304 DEFAULT, after which it's an instance of the previous case.  This
1305 really only shows up in eliminating error-checking code.
1306
1307 We also make sure that we deal with this very common case:
1308
1309         case e of
1310           x -> ...x...
1311
1312 Here we are using the case as a strict let; if x is used only once
1313 then we want to inline it.  We have to be careful that this doesn't
1314 make the program terminate when it would have diverged before, so we
1315 check that
1316         - e is already evaluated (it may so if e is a variable)
1317         - x is used strictly, or
1318
1319 Lastly, the code in SimplUtils.mkCase combines identical RHSs.  So
1320
1321         case e of       ===> case e of DEFAULT -> r
1322            True  -> r
1323            False -> r
1324
1325 Now again the case may be elminated by the CaseElim transformation.
1326
1327
1328 Further notes about case elimination
1329 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1330 Consider:       test :: Integer -> IO ()
1331                 test = print
1332
1333 Turns out that this compiles to:
1334     Print.test
1335       = \ eta :: Integer
1336           eta1 :: State# RealWorld ->
1337           case PrelNum.< eta PrelNum.zeroInteger of wild { __DEFAULT ->
1338           case hPutStr stdout
1339                  (PrelNum.jtos eta ($w[] @ Char))
1340                  eta1
1341           of wild1 { (# new_s, a4 #) -> PrelIO.lvl23 new_s  }}
1342
1343 Notice the strange '<' which has no effect at all. This is a funny one.
1344 It started like this:
1345
1346 f x y = if x < 0 then jtos x
1347           else if y==0 then "" else jtos x
1348
1349 At a particular call site we have (f v 1).  So we inline to get
1350
1351         if v < 0 then jtos x
1352         else if 1==0 then "" else jtos x
1353
1354 Now simplify the 1==0 conditional:
1355
1356         if v<0 then jtos v else jtos v
1357
1358 Now common-up the two branches of the case:
1359
1360         case (v<0) of DEFAULT -> jtos v
1361
1362 Why don't we drop the case?  Because it's strict in v.  It's technically
1363 wrong to drop even unnecessary evaluations, and in practice they
1364 may be a result of 'seq' so we *definitely* don't want to drop those.
1365 I don't really know how to improve this situation.
1366
1367 \begin{code}
1368 ---------------------------------------------------------
1369 --      Eliminate the case if possible
1370
1371 rebuildCase, reallyRebuildCase
1372    :: SimplEnv
1373    -> OutExpr          -- Scrutinee
1374    -> InId             -- Case binder
1375    -> [InAlt]          -- Alternatives (inceasing order)
1376    -> SimplCont
1377    -> SimplM (SimplEnv, OutExpr)
1378
1379 --------------------------------------------------
1380 --      1. Eliminate the case if there's a known constructor
1381 --------------------------------------------------
1382
1383 rebuildCase env scrut case_bndr alts cont
1384   | Lit lit <- scrut    -- No need for same treatment as constructors
1385                         -- because literals are inlined more vigorously
1386   = do  { tick (KnownBranch case_bndr)
1387         ; case findAlt (LitAlt lit) alts of
1388             Nothing           -> missingAlt env case_bndr alts cont
1389             Just (_, bs, rhs) -> simple_rhs bs rhs }
1390
1391   | Just (con, ty_args, other_args) <- exprIsConApp_maybe scrut
1392         -- Works when the scrutinee is a variable with a known unfolding
1393         -- as well as when it's an explicit constructor application
1394   = do  { tick (KnownBranch case_bndr)
1395         ; case findAlt (DataAlt con) alts of
1396             Nothing  -> missingAlt env case_bndr alts cont
1397             Just (DEFAULT, bs, rhs) -> simple_rhs bs rhs
1398             Just (_, bs, rhs)       -> knownCon env scrut con ty_args other_args 
1399                                                 case_bndr bs rhs cont
1400         }
1401   where
1402     simple_rhs bs rhs = ASSERT( null bs ) 
1403                         do { env' <- simplNonRecX env case_bndr scrut
1404                            ; simplExprF env' rhs cont }
1405
1406
1407 --------------------------------------------------
1408 --      2. Eliminate the case if scrutinee is evaluated
1409 --------------------------------------------------
1410
1411 rebuildCase env scrut case_bndr [(_, bndrs, rhs)] cont
1412   -- See if we can get rid of the case altogether
1413   -- See Note [Case eliminiation] 
1414   -- mkCase made sure that if all the alternatives are equal,
1415   -- then there is now only one (DEFAULT) rhs
1416  | all isDeadBinder bndrs       -- bndrs are [InId]
1417
1418         -- Check that the scrutinee can be let-bound instead of case-bound
1419  , exprOkForSpeculation scrut
1420                 -- OK not to evaluate it
1421                 -- This includes things like (==# a# b#)::Bool
1422                 -- so that we simplify
1423                 --      case ==# a# b# of { True -> x; False -> x }
1424                 -- to just
1425                 --      x
1426                 -- This particular example shows up in default methods for
1427                 -- comparision operations (e.g. in (>=) for Int.Int32)
1428         || exprIsHNF scrut                      -- It's already evaluated
1429         || var_demanded_later scrut             -- It'll be demanded later
1430
1431 --      || not opt_SimplPedanticBottoms)        -- Or we don't care!
1432 --      We used to allow improving termination by discarding cases, unless -fpedantic-bottoms was on,
1433 --      but that breaks badly for the dataToTag# primop, which relies on a case to evaluate
1434 --      its argument:  case x of { y -> dataToTag# y }
1435 --      Here we must *not* discard the case, because dataToTag# just fetches the tag from
1436 --      the info pointer.  So we'll be pedantic all the time, and see if that gives any
1437 --      other problems
1438 --      Also we don't want to discard 'seq's
1439   = do  { tick (CaseElim case_bndr)
1440         ; env' <- simplNonRecX env case_bndr scrut
1441         ; simplExprF env' rhs cont }
1442   where
1443         -- The case binder is going to be evaluated later,
1444         -- and the scrutinee is a simple variable
1445     var_demanded_later (Var v) = isStrictDmd (idNewDemandInfo case_bndr)
1446                                  && not (isTickBoxOp v)
1447                                     -- ugly hack; covering this case is what
1448                                     -- exprOkForSpeculation was intended for.
1449     var_demanded_later _       = False
1450
1451 rebuildCase env scrut case_bndr alts@[(_, bndrs, rhs)] cont
1452   | all isDeadBinder (case_bndr : bndrs)  -- So this is just 'seq'
1453   =     -- For this case, see Note [User-defined RULES for seq] in MkId
1454     do { let rhs' = substExpr env rhs
1455              out_args = [Type (substTy env (idType case_bndr)), 
1456                          Type (exprType rhs'), scrut, rhs']
1457                       -- Lazily evaluated, so we don't do most of this
1458
1459        ; rule_base <- getSimplRules
1460        ; let rules = getRules rule_base seqId
1461        ; mb_rule <- tryRules env seqId rules out_args cont
1462        ; case mb_rule of 
1463            Just (n_args, res) -> simplExprF (zapSubstEnv env) 
1464                                             (mkApps res (drop n_args out_args))
1465                                             cont
1466            Nothing -> reallyRebuildCase env scrut case_bndr alts cont }
1467
1468 rebuildCase env scrut case_bndr alts cont
1469   = reallyRebuildCase env scrut case_bndr alts cont
1470
1471 --------------------------------------------------
1472 --      3. Catch-all case
1473 --------------------------------------------------
1474
1475 reallyRebuildCase env scrut case_bndr alts cont
1476   = do  {       -- Prepare the continuation;
1477                 -- The new subst_env is in place
1478           (env', dup_cont, nodup_cont) <- prepareCaseCont env alts cont
1479
1480         -- Simplify the alternatives
1481         ; (scrut', case_bndr', alts') <- simplAlts env' scrut case_bndr alts dup_cont
1482
1483         -- Check for empty alternatives
1484         ; if null alts' then missingAlt env case_bndr alts cont
1485           else do
1486         { case_expr <- mkCase scrut' case_bndr' alts'
1487
1488         -- Notice that rebuild gets the in-scope set from env, not alt_env
1489         -- The case binder *not* scope over the whole returned case-expression
1490         ; rebuild env' case_expr nodup_cont } }
1491 \end{code}
1492
1493 simplCaseBinder checks whether the scrutinee is a variable, v.  If so,
1494 try to eliminate uses of v in the RHSs in favour of case_bndr; that
1495 way, there's a chance that v will now only be used once, and hence
1496 inlined.
1497
1498 Historical note: we use to do the "case binder swap" in the Simplifier
1499 so there were additional complications if the scrutinee was a variable.
1500 Now the binder-swap stuff is done in the occurrence analyer; see
1501 OccurAnal Note [Binder swap].
1502
1503 Note [zapOccInfo]
1504 ~~~~~~~~~~~~~~~~~
1505 If the case binder is not dead, then neither are the pattern bound
1506 variables:  
1507         case <any> of x { (a,b) ->
1508         case x of { (p,q) -> p } }
1509 Here (a,b) both look dead, but come alive after the inner case is eliminated.
1510 The point is that we bring into the envt a binding
1511         let x = (a,b)
1512 after the outer case, and that makes (a,b) alive.  At least we do unless
1513 the case binder is guaranteed dead.
1514
1515 In practice, the scrutinee is almost always a variable, so we pretty
1516 much always zap the OccInfo of the binders.  It doesn't matter much though.
1517
1518
1519 Note [Case of cast]
1520 ~~~~~~~~~~~~~~~~~~~
1521 Consider        case (v `cast` co) of x { I# y ->
1522                 ... (case (v `cast` co) of {...}) ...
1523 We'd like to eliminate the inner case.  We can get this neatly by
1524 arranging that inside the outer case we add the unfolding
1525         v |-> x `cast` (sym co)
1526 to v.  Then we should inline v at the inner case, cancel the casts, and away we go
1527
1528 Note [Improving seq]
1529 ~~~~~~~~~~~~~~~~~~~
1530 Consider
1531         type family F :: * -> *
1532         type instance F Int = Int
1533
1534         ... case e of x { DEFAULT -> rhs } ...
1535
1536 where x::F Int.  Then we'd like to rewrite (F Int) to Int, getting
1537
1538         case e `cast` co of x'::Int
1539            I# x# -> let x = x' `cast` sym co
1540                     in rhs
1541
1542 so that 'rhs' can take advantage of the form of x'.  
1543
1544 Notice that Note [Case of cast] may then apply to the result. 
1545
1546 Nota Bene: We only do the [Improving seq] transformation if the 
1547 case binder 'x' is actually used in the rhs; that is, if the case 
1548 is *not* a *pure* seq.  
1549   a) There is no point in adding the cast to a pure seq.
1550   b) There is a good reason not to: doing so would interfere 
1551      with seq rules (Note [Built-in RULES for seq] in MkId).
1552      In particular, this [Improving seq] thing *adds* a cast
1553      while [Built-in RULES for seq] *removes* one, so they
1554      just flip-flop.
1555
1556 You might worry about 
1557    case v of x { __DEFAULT ->
1558       ... case (v `cast` co) of y { I# -> ... }}
1559 This is a pure seq (since x is unused), so [Improving seq] won't happen.
1560 But it's ok: the simplifier will replace 'v' by 'x' in the rhs to get
1561    case v of x { __DEFAULT ->
1562       ... case (x `cast` co) of y { I# -> ... }}
1563 Now the outer case is not a pure seq, so [Improving seq] will happen,
1564 and then the inner case will disappear.
1565
1566 The need for [Improving seq] showed up in Roman's experiments.  Example:
1567   foo :: F Int -> Int -> Int
1568   foo t n = t `seq` bar n
1569      where
1570        bar 0 = 0
1571        bar n = bar (n - case t of TI i -> i)
1572 Here we'd like to avoid repeated evaluating t inside the loop, by
1573 taking advantage of the `seq`.
1574
1575 At one point I did transformation in LiberateCase, but it's more
1576 robust here.  (Otherwise, there's a danger that we'll simply drop the
1577 'seq' altogether, before LiberateCase gets to see it.)
1578
1579
1580 \begin{code}
1581 improveSeq :: (FamInstEnv, FamInstEnv) -> SimplEnv
1582            -> OutExpr -> InId -> OutId -> [InAlt]
1583            -> SimplM (SimplEnv, OutExpr, OutId)
1584 -- Note [Improving seq]
1585 improveSeq fam_envs env scrut case_bndr case_bndr1 [(DEFAULT,_,_)]
1586   | not (isDeadBinder case_bndr)        -- Not a pure seq!  See the Note!
1587   , Just (co, ty2) <- topNormaliseType fam_envs (idType case_bndr1)
1588   = do { case_bndr2 <- newId (fsLit "nt") ty2
1589         ; let rhs  = DoneEx (Var case_bndr2 `Cast` mkSymCoercion co)
1590               env2 = extendIdSubst env case_bndr rhs
1591         ; return (env2, scrut `Cast` co, case_bndr2) }
1592
1593 improveSeq _ env scrut _ case_bndr1 _
1594   = return (env, scrut, case_bndr1)
1595
1596 {-
1597     improve_case_bndr env scrut case_bndr
1598         -- See Note [no-case-of-case]
1599         --  | switchIsOn (getSwitchChecker env) NoCaseOfCase
1600         --  = (env, case_bndr)
1601
1602         | otherwise     -- Failed try; see Note [Suppressing the case binder-swap]
1603                         --     not (isEvaldUnfolding (idUnfolding v))
1604         = case scrut of
1605             Var v -> (modifyInScope env1 v case_bndr', case_bndr')
1606                 -- Note about using modifyInScope for v here
1607                 -- We could extend the substitution instead, but it would be
1608                 -- a hack because then the substitution wouldn't be idempotent
1609                 -- any more (v is an OutId).  And this does just as well.
1610
1611             Cast (Var v) co -> (addBinderUnfolding env1 v rhs, case_bndr')
1612                             where
1613                                 rhs = Cast (Var case_bndr') (mkSymCoercion co)
1614
1615             _ -> (env, case_bndr)
1616         where
1617           case_bndr' = zapIdOccInfo case_bndr
1618           env1       = modifyInScope env case_bndr case_bndr'
1619 -}
1620 \end{code}
1621
1622
1623 simplAlts does two things:
1624
1625 1.  Eliminate alternatives that cannot match, including the
1626     DEFAULT alternative.
1627
1628 2.  If the DEFAULT alternative can match only one possible constructor,
1629     then make that constructor explicit.
1630     e.g.
1631         case e of x { DEFAULT -> rhs }
1632      ===>
1633         case e of x { (a,b) -> rhs }
1634     where the type is a single constructor type.  This gives better code
1635     when rhs also scrutinises x or e.
1636
1637 Here "cannot match" includes knowledge from GADTs
1638
1639 It's a good idea do do this stuff before simplifying the alternatives, to
1640 avoid simplifying alternatives we know can't happen, and to come up with
1641 the list of constructors that are handled, to put into the IdInfo of the
1642 case binder, for use when simplifying the alternatives.
1643
1644 Eliminating the default alternative in (1) isn't so obvious, but it can
1645 happen:
1646
1647 data Colour = Red | Green | Blue
1648
1649 f x = case x of
1650         Red -> ..
1651         Green -> ..
1652         DEFAULT -> h x
1653
1654 h y = case y of
1655         Blue -> ..
1656         DEFAULT -> [ case y of ... ]
1657
1658 If we inline h into f, the default case of the inlined h can't happen.
1659 If we don't notice this, we may end up filtering out *all* the cases
1660 of the inner case y, which give us nowhere to go!
1661
1662
1663 \begin{code}
1664 simplAlts :: SimplEnv
1665           -> OutExpr
1666           -> InId                       -- Case binder
1667           -> [InAlt]                    -- Non-empty
1668           -> SimplCont
1669           -> SimplM (OutExpr, OutId, [OutAlt])  -- Includes the continuation
1670 -- Like simplExpr, this just returns the simplified alternatives;
1671 -- it not return an environment
1672
1673 simplAlts env scrut case_bndr alts cont'
1674   = -- pprTrace "simplAlts" (ppr alts $$ ppr (seIdSubst env)) $
1675     do  { let env0 = zapFloats env
1676
1677         ; (env1, case_bndr1) <- simplBinder env0 case_bndr
1678
1679         ; fam_envs <- getFamEnvs
1680         ; (alt_env', scrut', case_bndr') <- improveSeq fam_envs env1 scrut 
1681                                                        case_bndr case_bndr1 alts
1682
1683         ; (imposs_deflt_cons, in_alts) <- prepareAlts alt_env' scrut' case_bndr' alts
1684
1685         ; alts' <- mapM (simplAlt alt_env' imposs_deflt_cons case_bndr' cont') in_alts
1686         ; return (scrut', case_bndr', alts') }
1687
1688 ------------------------------------
1689 simplAlt :: SimplEnv
1690          -> [AltCon]    -- These constructors can't be present when
1691                         -- matching the DEFAULT alternative
1692          -> OutId       -- The case binder
1693          -> SimplCont
1694          -> InAlt
1695          -> SimplM OutAlt
1696
1697 simplAlt env imposs_deflt_cons case_bndr' cont' (DEFAULT, bndrs, rhs)
1698   = ASSERT( null bndrs )
1699     do  { let env' = addBinderOtherCon env case_bndr' imposs_deflt_cons
1700                 -- Record the constructors that the case-binder *can't* be.
1701         ; rhs' <- simplExprC env' rhs cont'
1702         ; return (DEFAULT, [], rhs') }
1703
1704 simplAlt env _ case_bndr' cont' (LitAlt lit, bndrs, rhs)
1705   = ASSERT( null bndrs )
1706     do  { let env' = addBinderUnfolding env case_bndr' (Lit lit)
1707         ; rhs' <- simplExprC env' rhs cont'
1708         ; return (LitAlt lit, [], rhs') }
1709
1710 simplAlt env _ case_bndr' cont' (DataAlt con, vs, rhs)
1711   = do  {       -- Deal with the pattern-bound variables
1712                 -- Mark the ones that are in ! positions in the
1713                 -- data constructor as certainly-evaluated.
1714                 -- NB: simplLamBinders preserves this eval info
1715           let vs_with_evals = add_evals (dataConRepStrictness con)
1716         ; (env', vs') <- simplLamBndrs env vs_with_evals
1717
1718                 -- Bind the case-binder to (con args)
1719         ; let inst_tys' = tyConAppArgs (idType case_bndr')
1720               con_args  = map Type inst_tys' ++ varsToCoreExprs vs'
1721               env''     = addBinderUnfolding env' case_bndr'
1722                                              (mkConApp con con_args)
1723
1724         ; rhs' <- simplExprC env'' rhs cont'
1725         ; return (DataAlt con, vs', rhs') }
1726   where
1727         -- add_evals records the evaluated-ness of the bound variables of
1728         -- a case pattern.  This is *important*.  Consider
1729         --      data T = T !Int !Int
1730         --
1731         --      case x of { T a b -> T (a+1) b }
1732         --
1733         -- We really must record that b is already evaluated so that we don't
1734         -- go and re-evaluate it when constructing the result.
1735         -- See Note [Data-con worker strictness] in MkId.lhs
1736     add_evals the_strs
1737         = go vs the_strs
1738         where
1739           go [] [] = []
1740           go (v:vs') strs | isTyVar v = v : go vs' strs
1741           go (v:vs') (str:strs)
1742             | isMarkedStrict str = evald_v  : go vs' strs
1743             | otherwise          = zapped_v : go vs' strs
1744             where
1745               zapped_v = zap_occ_info v
1746               evald_v  = zapped_v `setIdUnfolding` evaldUnfolding
1747           go _ _ = pprPanic "cat_evals" (ppr con $$ ppr vs $$ ppr the_strs)
1748
1749         -- See Note [zapOccInfo]
1750         -- zap_occ_info: if the case binder is alive, then we add the unfolding
1751         --      case_bndr = C vs
1752         -- to the envt; so vs are now very much alive
1753         -- Note [Aug06] I can't see why this actually matters, but it's neater
1754         --        case e of t { (a,b) -> ...(case t of (p,q) -> p)... }
1755         --   ==>  case e of t { (a,b) -> ...(a)... }
1756         -- Look, Ma, a is alive now.
1757     zap_occ_info = zapCasePatIdOcc case_bndr'
1758
1759 addBinderUnfolding :: SimplEnv -> Id -> CoreExpr -> SimplEnv
1760 addBinderUnfolding env bndr rhs
1761   = modifyInScope env (bndr `setIdUnfolding` mkUnfolding False rhs)
1762
1763 addBinderOtherCon :: SimplEnv -> Id -> [AltCon] -> SimplEnv
1764 addBinderOtherCon env bndr cons
1765   = modifyInScope env (bndr `setIdUnfolding` mkOtherCon cons)
1766
1767 zapCasePatIdOcc :: Id -> Id -> Id
1768 -- Consider  case e of b { (a,b) -> ... }
1769 -- Then if we bind b to (a,b) in "...", and b is not dead,
1770 -- then we must zap the deadness info on a,b
1771 zapCasePatIdOcc case_bndr
1772   | isDeadBinder case_bndr = \ pat_id -> pat_id
1773   | otherwise              = \ pat_id -> zapIdOccInfo pat_id
1774 \end{code}
1775
1776
1777 %************************************************************************
1778 %*                                                                      *
1779 \subsection{Known constructor}
1780 %*                                                                      *
1781 %************************************************************************
1782
1783 We are a bit careful with occurrence info.  Here's an example
1784
1785         (\x* -> case x of (a*, b) -> f a) (h v, e)
1786
1787 where the * means "occurs once".  This effectively becomes
1788         case (h v, e) of (a*, b) -> f a)
1789 and then
1790         let a* = h v; b = e in f a
1791 and then
1792         f (h v)
1793
1794 All this should happen in one sweep.
1795
1796 \begin{code}
1797 knownCon :: SimplEnv            
1798          -> OutExpr                             -- The scrutinee
1799          -> DataCon -> [OutType] -> [OutExpr]   -- The scrutinee (in pieces)
1800          -> InId -> [InBndr] -> InExpr          -- The alternative
1801          -> SimplCont
1802          -> SimplM (SimplEnv, OutExpr)
1803
1804 knownCon env scrut dc dc_ty_args dc_args bndr bs rhs cont
1805   = do  { env' <- bind_args env bs dc_args
1806         ; let
1807                 -- It's useful to bind bndr to scrut, rather than to a fresh
1808                 -- binding      x = Con arg1 .. argn
1809                 -- because very often the scrut is a variable, so we avoid
1810                 -- creating, and then subsequently eliminating, a let-binding
1811                 -- BUT, if scrut is a not a variable, we must be careful
1812                 -- about duplicating the arg redexes; in that case, make
1813                 -- a new con-app from the args
1814                 bndr_rhs | exprIsTrivial scrut = scrut
1815                          | otherwise           = con_app
1816                 con_app = Var (dataConWorkId dc) 
1817                           `mkTyApps` dc_ty_args
1818                           `mkApps`   [substExpr env' (varToCoreExpr b) | b <- bs]
1819                          -- dc_ty_args are aready OutTypes, but bs are InBndrs
1820
1821         ; env'' <- simplNonRecX env' bndr bndr_rhs
1822         ; simplExprF env'' rhs cont }
1823   where
1824     zap_occ = zapCasePatIdOcc bndr    -- bndr is an InId
1825
1826                   -- Ugh!
1827     bind_args env' [] _  = return env'
1828
1829     bind_args env' (b:bs') (Type ty : args)
1830       = ASSERT( isTyVar b )
1831         bind_args (extendTvSubst env' b ty) bs' args
1832
1833     bind_args env' (b:bs') (arg : args)
1834       = ASSERT( isId b )
1835         do { let b' = zap_occ b
1836              -- Note that the binder might be "dead", because it doesn't
1837              -- occur in the RHS; and simplNonRecX may therefore discard
1838              -- it via postInlineUnconditionally.
1839              -- Nevertheless we must keep it if the case-binder is alive,
1840              -- because it may be used in the con_app.  See Note [zapOccInfo]
1841            ; env'' <- simplNonRecX env' b' arg
1842            ; bind_args env'' bs' args }
1843
1844     bind_args _ _ _ =
1845       pprPanic "bind_args" $ ppr dc $$ ppr bs $$ ppr dc_args $$
1846                              text "scrut:" <+> ppr scrut
1847
1848 -------------------
1849 missingAlt :: SimplEnv -> Id -> [InAlt] -> SimplCont -> SimplM (SimplEnv, OutExpr)
1850                 -- This isn't strictly an error, although it is unusual. 
1851                 -- It's possible that the simplifer might "see" that 
1852                 -- an inner case has no accessible alternatives before 
1853                 -- it "sees" that the entire branch of an outer case is 
1854                 -- inaccessible.  So we simply put an error case here instead.
1855 missingAlt env case_bndr alts cont
1856   = WARN( True, ptext (sLit "missingAlt") <+> ppr case_bndr )
1857     return (env, mkImpossibleExpr res_ty)
1858   where
1859     res_ty = contResultType env (substTy env (coreAltsType alts)) cont
1860 \end{code}
1861
1862
1863 %************************************************************************
1864 %*                                                                      *
1865 \subsection{Duplicating continuations}
1866 %*                                                                      *
1867 %************************************************************************
1868
1869 \begin{code}
1870 prepareCaseCont :: SimplEnv
1871                 -> [InAlt] -> SimplCont
1872                 -> SimplM (SimplEnv, SimplCont,SimplCont)
1873                         -- Return a duplicatable continuation, a non-duplicable part
1874                         -- plus some extra bindings (that scope over the entire
1875                         -- continunation)
1876
1877         -- No need to make it duplicatable if there's only one alternative
1878 prepareCaseCont env [_] cont = return (env, cont, mkBoringStop)
1879 prepareCaseCont env _   cont = mkDupableCont env cont
1880 \end{code}
1881
1882 \begin{code}
1883 mkDupableCont :: SimplEnv -> SimplCont
1884               -> SimplM (SimplEnv, SimplCont, SimplCont)
1885
1886 mkDupableCont env cont
1887   | contIsDupable cont
1888   = return (env, cont, mkBoringStop)
1889
1890 mkDupableCont _   (Stop {}) = panic "mkDupableCont"     -- Handled by previous eqn
1891
1892 mkDupableCont env (CoerceIt ty cont)
1893   = do  { (env', dup, nodup) <- mkDupableCont env cont
1894         ; return (env', CoerceIt ty dup, nodup) }
1895
1896 mkDupableCont env cont@(StrictBind {})
1897   =  return (env, mkBoringStop, cont)
1898         -- See Note [Duplicating StrictBind]
1899
1900 mkDupableCont env (StrictArg fun cci ai cont)
1901         -- See Note [Duplicating StrictArg]
1902   = do { (env', dup, nodup) <- mkDupableCont env cont
1903        ; (env'', fun') <- mk_dupable_call env' fun
1904        ; return (env'', StrictArg fun' cci ai dup, nodup) }
1905   where
1906     mk_dupable_call env (Var v)       = return (env, Var v)
1907     mk_dupable_call env (App fun arg) = do { (env', fun') <- mk_dupable_call env fun
1908                                            ; (env'', arg') <- makeTrivial env' arg
1909                                            ; return (env'', fun' `App` arg') }
1910     mk_dupable_call _ other = pprPanic "mk_dupable_call" (ppr other)
1911         -- The invariant of StrictArg is that the first arg is always an App chain
1912
1913 mkDupableCont env (ApplyTo _ arg se cont)
1914   =     -- e.g.         [...hole...] (...arg...)
1915         --      ==>
1916         --              let a = ...arg...
1917         --              in [...hole...] a
1918     do  { (env', dup_cont, nodup_cont) <- mkDupableCont env cont
1919         ; arg' <- simplExpr (se `setInScope` env') arg
1920         ; (env'', arg'') <- makeTrivial env' arg'
1921         ; let app_cont = ApplyTo OkToDup arg'' (zapSubstEnv env'') dup_cont
1922         ; return (env'', app_cont, nodup_cont) }
1923
1924 mkDupableCont env cont@(Select _ case_bndr [(_, bs, _rhs)] _ _)
1925 --  See Note [Single-alternative case]
1926 --  | not (exprIsDupable rhs && contIsDupable case_cont)
1927 --  | not (isDeadBinder case_bndr)
1928   | all isDeadBinder bs  -- InIds
1929     && not (isUnLiftedType (idType case_bndr))
1930     -- Note [Single-alternative-unlifted]
1931   = return (env, mkBoringStop, cont)
1932
1933 mkDupableCont env (Select _ case_bndr alts se cont)
1934   =     -- e.g.         (case [...hole...] of { pi -> ei })
1935         --      ===>
1936         --              let ji = \xij -> ei
1937         --              in case [...hole...] of { pi -> ji xij }
1938     do  { tick (CaseOfCase case_bndr)
1939         ; (env', dup_cont, nodup_cont) <- mkDupableCont env cont
1940                 -- NB: call mkDupableCont here, *not* prepareCaseCont
1941                 -- We must make a duplicable continuation, whereas prepareCaseCont
1942                 -- doesn't when there is a single case branch
1943
1944         ; let alt_env = se `setInScope` env'
1945         ; (alt_env', case_bndr') <- simplBinder alt_env case_bndr
1946         ; alts' <- mapM (simplAlt alt_env' [] case_bndr' dup_cont) alts
1947         -- Safe to say that there are no handled-cons for the DEFAULT case
1948                 -- NB: simplBinder does not zap deadness occ-info, so
1949                 -- a dead case_bndr' will still advertise its deadness
1950                 -- This is really important because in
1951                 --      case e of b { (# p,q #) -> ... }
1952                 -- b is always dead, and indeed we are not allowed to bind b to (# p,q #),
1953                 -- which might happen if e was an explicit unboxed pair and b wasn't marked dead.
1954                 -- In the new alts we build, we have the new case binder, so it must retain
1955                 -- its deadness.
1956         -- NB: we don't use alt_env further; it has the substEnv for
1957         --     the alternatives, and we don't want that
1958
1959         ; (env'', alts'') <- mkDupableAlts env' case_bndr' alts'
1960         ; return (env'',  -- Note [Duplicated env]
1961                   Select OkToDup case_bndr' alts'' (zapSubstEnv env'') mkBoringStop,
1962                   nodup_cont) }
1963
1964
1965 mkDupableAlts :: SimplEnv -> OutId -> [InAlt]
1966               -> SimplM (SimplEnv, [InAlt])
1967 -- Absorbs the continuation into the new alternatives
1968
1969 mkDupableAlts env case_bndr' the_alts
1970   = go env the_alts
1971   where
1972     go env0 [] = return (env0, [])
1973     go env0 (alt:alts)
1974         = do { (env1, alt') <- mkDupableAlt env0 case_bndr' alt
1975              ; (env2, alts') <- go env1 alts
1976              ; return (env2, alt' : alts' ) }
1977
1978 mkDupableAlt :: SimplEnv -> OutId -> (AltCon, [CoreBndr], CoreExpr)
1979               -> SimplM (SimplEnv, (AltCon, [CoreBndr], CoreExpr))
1980 mkDupableAlt env case_bndr (con, bndrs', rhs')
1981   | exprIsDupable rhs'  -- Note [Small alternative rhs]
1982   = return (env, (con, bndrs', rhs'))
1983   | otherwise
1984   = do  { let rhs_ty'  = exprType rhs'
1985               scrut_ty = idType case_bndr
1986               case_bndr_w_unf   
1987                 = case con of 
1988                       DEFAULT    -> case_bndr                                   
1989                       DataAlt dc -> setIdUnfolding case_bndr unf
1990                           where
1991                                  -- See Note [Case binders and join points]
1992                              unf = mkInlineRule InlSat rhs 0
1993                              rhs = mkConApp dc (map Type (tyConAppArgs scrut_ty)
1994                                                 ++ varsToCoreExprs bndrs')
1995
1996                       LitAlt {} -> WARN( True, ptext (sLit "mkDupableAlt")
1997                                                 <+> ppr case_bndr <+> ppr con )
1998                                    case_bndr
1999                            -- The case binder is alive but trivial, so why has 
2000                            -- it not been substituted away?
2001
2002               used_bndrs' | isDeadBinder case_bndr = filter abstract_over bndrs'
2003                           | otherwise              = bndrs' ++ [case_bndr_w_unf]
2004               
2005               abstract_over bndr
2006                   | isTyVar bndr = True -- Abstract over all type variables just in case
2007                   | otherwise    = not (isDeadBinder bndr)
2008                         -- The deadness info on the new Ids is preserved by simplBinders
2009
2010         ; (final_bndrs', final_args)    -- Note [Join point abstraction]
2011                 <- if (any isId used_bndrs')
2012                    then return (used_bndrs', varsToCoreExprs used_bndrs')
2013                     else do { rw_id <- newId (fsLit "w") realWorldStatePrimTy
2014                             ; return ([rw_id], [Var realWorldPrimId]) }
2015
2016         ; join_bndr <- newId (fsLit "$j") (mkPiTypes final_bndrs' rhs_ty')
2017                 -- Note [Funky mkPiTypes]
2018
2019         ; let   -- We make the lambdas into one-shot-lambdas.  The
2020                 -- join point is sure to be applied at most once, and doing so
2021                 -- prevents the body of the join point being floated out by
2022                 -- the full laziness pass
2023                 really_final_bndrs     = map one_shot final_bndrs'
2024                 one_shot v | isId v    = setOneShotLambda v
2025                            | otherwise = v
2026                 join_rhs  = mkLams really_final_bndrs rhs'
2027                 join_call = mkApps (Var join_bndr) final_args
2028
2029         ; env' <- addPolyBind NotTopLevel env (NonRec join_bndr join_rhs)
2030         ; return (env', (con, bndrs', join_call)) }
2031                 -- See Note [Duplicated env]
2032 \end{code}
2033
2034 Note [Case binders and join points]
2035 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2036 Consider this 
2037    case (case .. ) of c {
2038      I# c# -> ....c....
2039
2040 If we make a join point with c but not c# we get
2041   $j = \c -> ....c....
2042
2043 But if later inlining scrutines the c, thus
2044
2045   $j = \c -> ... case c of { I# y -> ... } ...
2046
2047 we won't see that 'c' has already been scrutinised.  This actually
2048 happens in the 'tabulate' function in wave4main, and makes a significant
2049 difference to allocation.
2050
2051 An alternative plan is this:
2052
2053    $j = \c# -> let c = I# c# in ...c....
2054
2055 but that is bad if 'c' is *not* later scrutinised.  
2056
2057 So instead we do both: we pass 'c' and 'c#' , and record in c's inlining
2058 that it's really I# c#, thus
2059    
2060    $j = \c# -> \c[=I# c#] -> ...c....
2061
2062 Absence analysis may later discard 'c'.
2063
2064    
2065 Note [Duplicated env]
2066 ~~~~~~~~~~~~~~~~~~~~~
2067 Some of the alternatives are simplified, but have not been turned into a join point
2068 So they *must* have an zapped subst-env.  So we can't use completeNonRecX to
2069 bind the join point, because it might to do PostInlineUnconditionally, and
2070 we'd lose that when zapping the subst-env.  We could have a per-alt subst-env,
2071 but zapping it (as we do in mkDupableCont, the Select case) is safe, and
2072 at worst delays the join-point inlining.
2073
2074 Note [Small alternative rhs]
2075 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2076 It is worth checking for a small RHS because otherwise we
2077 get extra let bindings that may cause an extra iteration of the simplifier to
2078 inline back in place.  Quite often the rhs is just a variable or constructor.
2079 The Ord instance of Maybe in PrelMaybe.lhs, for example, took several extra
2080 iterations because the version with the let bindings looked big, and so wasn't
2081 inlined, but after the join points had been inlined it looked smaller, and so
2082 was inlined.
2083
2084 NB: we have to check the size of rhs', not rhs.
2085 Duplicating a small InAlt might invalidate occurrence information
2086 However, if it *is* dupable, we return the *un* simplified alternative,
2087 because otherwise we'd need to pair it up with an empty subst-env....
2088 but we only have one env shared between all the alts.
2089 (Remember we must zap the subst-env before re-simplifying something).
2090 Rather than do this we simply agree to re-simplify the original (small) thing later.
2091
2092 Note [Funky mkPiTypes]
2093 ~~~~~~~~~~~~~~~~~~~~~~
2094 Notice the funky mkPiTypes.  If the contructor has existentials
2095 it's possible that the join point will be abstracted over
2096 type varaibles as well as term variables.
2097  Example:  Suppose we have
2098         data T = forall t.  C [t]
2099  Then faced with
2100         case (case e of ...) of
2101             C t xs::[t] -> rhs
2102  We get the join point
2103         let j :: forall t. [t] -> ...
2104             j = /\t \xs::[t] -> rhs
2105         in
2106         case (case e of ...) of
2107             C t xs::[t] -> j t xs
2108
2109 Note [Join point abstaction]
2110 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2111 If we try to lift a primitive-typed something out
2112 for let-binding-purposes, we will *caseify* it (!),
2113 with potentially-disastrous strictness results.  So
2114 instead we turn it into a function: \v -> e
2115 where v::State# RealWorld#.  The value passed to this function
2116 is realworld#, which generates (almost) no code.
2117
2118 There's a slight infelicity here: we pass the overall
2119 case_bndr to all the join points if it's used in *any* RHS,
2120 because we don't know its usage in each RHS separately
2121
2122 We used to say "&& isUnLiftedType rhs_ty'" here, but now
2123 we make the join point into a function whenever used_bndrs'
2124 is empty.  This makes the join-point more CPR friendly.
2125 Consider:       let j = if .. then I# 3 else I# 4
2126                 in case .. of { A -> j; B -> j; C -> ... }
2127
2128 Now CPR doesn't w/w j because it's a thunk, so
2129 that means that the enclosing function can't w/w either,
2130 which is a lose.  Here's the example that happened in practice:
2131         kgmod :: Int -> Int -> Int
2132         kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
2133                     then 78
2134                     else 5
2135
2136 I have seen a case alternative like this:
2137         True -> \v -> ...
2138 It's a bit silly to add the realWorld dummy arg in this case, making
2139         $j = \s v -> ...
2140            True -> $j s
2141 (the \v alone is enough to make CPR happy) but I think it's rare
2142
2143 Note [Duplicating StrictArg]
2144 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2145 The original plan had (where E is a big argument)
2146 e.g.    f E [..hole..]
2147         ==>     let $j = \a -> f E a
2148                 in $j [..hole..]
2149
2150 But this is terrible! Here's an example:
2151         && E (case x of { T -> F; F -> T })
2152 Now, && is strict so we end up simplifying the case with
2153 an ArgOf continuation.  If we let-bind it, we get
2154         let $j = \v -> && E v
2155         in simplExpr (case x of { T -> F; F -> T })
2156                      (ArgOf (\r -> $j r)
2157 And after simplifying more we get
2158         let $j = \v -> && E v
2159         in case x of { T -> $j F; F -> $j T }
2160 Which is a Very Bad Thing
2161
2162 What we do now is this
2163         f E [..hole..]
2164         ==>     let a = E
2165                 in f a [..hole..]
2166 Now if the thing in the hole is a case expression (which is when
2167 we'll call mkDupableCont), we'll push the function call into the
2168 branches, which is what we want.  Now RULES for f may fire, and
2169 call-pattern specialisation.  Here's an example from Trac #3116
2170      go (n+1) (case l of
2171                  1  -> bs'
2172                  _  -> Chunk p fpc (o+1) (l-1) bs')
2173 If we can push the call for 'go' inside the case, we get
2174 call-pattern specialisation for 'go', which is *crucial* for 
2175 this program.
2176
2177 Here is the (&&) example: 
2178         && E (case x of { T -> F; F -> T })
2179   ==>   let a = E in 
2180         case x of { T -> && a F; F -> && a T }
2181 Much better!
2182
2183 Notice that 
2184   * Arguments to f *after* the strict one are handled by 
2185     the ApplyTo case of mkDupableCont.  Eg
2186         f [..hole..] E
2187
2188   * We can only do the let-binding of E because the function
2189     part of a StrictArg continuation is an explicit syntax
2190     tree.  In earlier versions we represented it as a function
2191     (CoreExpr -> CoreEpxr) which we couldn't take apart.
2192
2193 Do *not* duplicate StrictBind and StritArg continuations.  We gain
2194 nothing by propagating them into the expressions, and we do lose a
2195 lot.  
2196
2197 The desire not to duplicate is the entire reason that
2198 mkDupableCont returns a pair of continuations.
2199
2200 Note [Duplicating StrictBind]
2201 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2202 Unlike StrictArg, there doesn't seem anything to gain from
2203 duplicating a StrictBind continuation, so we don't.
2204
2205 The desire not to duplicate is the entire reason that
2206 mkDupableCont returns a pair of continuations.
2207
2208
2209 Note [Single-alternative cases]
2210 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2211 This case is just like the ArgOf case.  Here's an example:
2212         data T a = MkT !a
2213         ...(MkT (abs x))...
2214 Then we get
2215         case (case x of I# x' ->
2216               case x' <# 0# of
2217                 True  -> I# (negate# x')
2218                 False -> I# x') of y {
2219           DEFAULT -> MkT y
2220 Because the (case x) has only one alternative, we'll transform to
2221         case x of I# x' ->
2222         case (case x' <# 0# of
2223                 True  -> I# (negate# x')
2224                 False -> I# x') of y {
2225           DEFAULT -> MkT y
2226 But now we do *NOT* want to make a join point etc, giving
2227         case x of I# x' ->
2228         let $j = \y -> MkT y
2229         in case x' <# 0# of
2230                 True  -> $j (I# (negate# x'))
2231                 False -> $j (I# x')
2232 In this case the $j will inline again, but suppose there was a big
2233 strict computation enclosing the orginal call to MkT.  Then, it won't
2234 "see" the MkT any more, because it's big and won't get duplicated.
2235 And, what is worse, nothing was gained by the case-of-case transform.
2236
2237 When should use this case of mkDupableCont?
2238 However, matching on *any* single-alternative case is a *disaster*;
2239   e.g.  case (case ....) of (a,b) -> (# a,b #)
2240   We must push the outer case into the inner one!
2241 Other choices:
2242
2243    * Match [(DEFAULT,_,_)], but in the common case of Int,
2244      the alternative-filling-in code turned the outer case into
2245                 case (...) of y { I# _ -> MkT y }
2246
2247    * Match on single alternative plus (not (isDeadBinder case_bndr))
2248      Rationale: pushing the case inwards won't eliminate the construction.
2249      But there's a risk of
2250                 case (...) of y { (a,b) -> let z=(a,b) in ... }
2251      Now y looks dead, but it'll come alive again.  Still, this
2252      seems like the best option at the moment.
2253
2254    * Match on single alternative plus (all (isDeadBinder bndrs))
2255      Rationale: this is essentially  seq.
2256
2257    * Match when the rhs is *not* duplicable, and hence would lead to a
2258      join point.  This catches the disaster-case above.  We can test
2259      the *un-simplified* rhs, which is fine.  It might get bigger or
2260      smaller after simplification; if it gets smaller, this case might
2261      fire next time round.  NB also that we must test contIsDupable
2262      case_cont *btoo, because case_cont might be big!
2263
2264      HOWEVER: I found that this version doesn't work well, because
2265      we can get         let x = case (...) of { small } in ...case x...
2266      When x is inlined into its full context, we find that it was a bad
2267      idea to have pushed the outer case inside the (...) case.
2268
2269 Note [Single-alternative-unlifted]
2270 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2271 Here's another single-alternative where we really want to do case-of-case:
2272
2273 data Mk1 = Mk1 Int#
2274 data Mk1 = Mk2 Int#
2275
2276 M1.f =
2277     \r [x_s74 y_s6X]
2278         case
2279             case y_s6X of tpl_s7m {
2280               M1.Mk1 ipv_s70 -> ipv_s70;
2281               M1.Mk2 ipv_s72 -> ipv_s72;
2282             }
2283         of
2284         wild_s7c
2285         { __DEFAULT ->
2286               case
2287                   case x_s74 of tpl_s7n {
2288                     M1.Mk1 ipv_s77 -> ipv_s77;
2289                     M1.Mk2 ipv_s79 -> ipv_s79;
2290                   }
2291               of
2292               wild1_s7b
2293               { __DEFAULT -> ==# [wild1_s7b wild_s7c];
2294               };
2295         };
2296
2297 So the outer case is doing *nothing at all*, other than serving as a
2298 join-point.  In this case we really want to do case-of-case and decide
2299 whether to use a real join point or just duplicate the continuation.
2300
2301 Hence: check whether the case binder's type is unlifted, because then
2302 the outer case is *not* a seq.