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