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