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