Stopping tick boxes for being removed round calls to error.
[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                                  && not (isTickBoxOp v) 
1169                                     -- ugly hack; covering this case is what 
1170                                     -- exprOkForSpeculation was intended for.
1171     var_demanded_later other   = False
1172
1173
1174 --------------------------------------------------
1175 --      3. Catch-all case
1176 --------------------------------------------------
1177
1178 rebuildCase env scrut case_bndr alts cont
1179   = do  {       -- Prepare the continuation;
1180                 -- The new subst_env is in place
1181           (env, dup_cont, nodup_cont) <- prepareCaseCont env alts cont
1182
1183         -- Simplify the alternatives
1184         ; (case_bndr', alts') <- simplAlts env scrut case_bndr alts dup_cont
1185         ; let res_ty' = contResultType dup_cont
1186         ; case_expr <- mkCase scrut case_bndr' res_ty' alts'
1187
1188         -- Notice that rebuildDone returns the in-scope set from env, not alt_env
1189         -- The case binder *not* scope over the whole returned case-expression
1190         ; rebuild env case_expr nodup_cont }
1191 \end{code}
1192
1193 simplCaseBinder checks whether the scrutinee is a variable, v.  If so,
1194 try to eliminate uses of v in the RHSs in favour of case_bndr; that
1195 way, there's a chance that v will now only be used once, and hence
1196 inlined.
1197
1198 Note [no-case-of-case]
1199 ~~~~~~~~~~~~~~~~~~~~~~
1200 There is a time we *don't* want to do that, namely when
1201 -fno-case-of-case is on.  This happens in the first simplifier pass,
1202 and enhances full laziness.  Here's the bad case:
1203         f = \ y -> ...(case x of I# v -> ...(case x of ...) ... )
1204 If we eliminate the inner case, we trap it inside the I# v -> arm,
1205 which might prevent some full laziness happening.  I've seen this
1206 in action in spectral/cichelli/Prog.hs:
1207          [(m,n) | m <- [1..max], n <- [1..max]]
1208 Hence the check for NoCaseOfCase.
1209
1210 Note [Suppressing the case binder-swap]
1211 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1212 There is another situation when it might make sense to suppress the
1213 case-expression binde-swap. If we have
1214
1215     case x of w1 { DEFAULT -> case x of w2 { A -> e1; B -> e2 }
1216                    ...other cases .... }
1217
1218 We'll perform the binder-swap for the outer case, giving
1219
1220     case x of w1 { DEFAULT -> case w1 of w2 { A -> e1; B -> e2 } 
1221                    ...other cases .... }
1222
1223 But there is no point in doing it for the inner case, because w1 can't
1224 be inlined anyway.  Furthermore, doing the case-swapping involves
1225 zapping w2's occurrence info (see paragraphs that follow), and that
1226 forces us to bind w2 when doing case merging.  So we get
1227
1228     case x of w1 { A -> let w2 = w1 in e1
1229                    B -> let w2 = w1 in e2
1230                    ...other cases .... }
1231
1232 This is plain silly in the common case where w2 is dead.
1233
1234 Even so, I can't see a good way to implement this idea.  I tried
1235 not doing the binder-swap if the scrutinee was already evaluated
1236 but that failed big-time:
1237
1238         data T = MkT !Int
1239
1240         case v of w  { MkT x ->
1241         case x of x1 { I# y1 ->
1242         case x of x2 { I# y2 -> ...
1243
1244 Notice that because MkT is strict, x is marked "evaluated".  But to
1245 eliminate the last case, we must either make sure that x (as well as
1246 x1) has unfolding MkT y1.  THe straightforward thing to do is to do
1247 the binder-swap.  So this whole note is a no-op.
1248
1249 Note [zapOccInfo]
1250 ~~~~~~~~~~~~~~~~~
1251 If we replace the scrutinee, v, by tbe case binder, then we have to nuke
1252 any occurrence info (eg IAmDead) in the case binder, because the
1253 case-binder now effectively occurs whenever v does.  AND we have to do
1254 the same for the pattern-bound variables!  Example:
1255
1256         (case x of { (a,b) -> a }) (case x of { (p,q) -> q })
1257
1258 Here, b and p are dead.  But when we move the argment inside the first
1259 case RHS, and eliminate the second case, we get
1260
1261         case x of { (a,b) -> a b }
1262
1263 Urk! b is alive!  Reason: the scrutinee was a variable, and case elimination
1264 happened.  
1265
1266 Indeed, this can happen anytime the case binder isn't dead:
1267         case <any> of x { (a,b) -> 
1268         case x of { (p,q) -> p } }
1269 Here (a,b) both look dead, but come alive after the inner case is eliminated.
1270 The point is that we bring into the envt a binding
1271         let x = (a,b) 
1272 after the outer case, and that makes (a,b) alive.  At least we do unless
1273 the case binder is guaranteed dead.
1274
1275 Note [Case of cast]
1276 ~~~~~~~~~~~~~~~~~~~
1277 Consider        case (v `cast` co) of x { I# ->
1278                 ... (case (v `cast` co) of {...}) ...
1279 We'd like to eliminate the inner case.  We can get this neatly by 
1280 arranging that inside the outer case we add the unfolding
1281         v |-> x `cast` (sym co)
1282 to v.  Then we should inline v at the inner case, cancel the casts, and away we go
1283         
1284
1285 Note [Case elimination]
1286 ~~~~~~~~~~~~~~~~~~~~~~~
1287 The case-elimination transformation discards redundant case expressions.
1288 Start with a simple situation:
1289
1290         case x# of      ===>   e[x#/y#]
1291           y# -> e
1292
1293 (when x#, y# are of primitive type, of course).  We can't (in general)
1294 do this for algebraic cases, because we might turn bottom into
1295 non-bottom!
1296
1297 The code in SimplUtils.prepareAlts has the effect of generalise this
1298 idea to look for a case where we're scrutinising a variable, and we
1299 know that only the default case can match.  For example:
1300
1301         case x of
1302           0#      -> ...
1303           DEFAULT -> ...(case x of
1304                          0#      -> ...
1305                          DEFAULT -> ...) ...
1306
1307 Here the inner case is first trimmed to have only one alternative, the
1308 DEFAULT, after which it's an instance of the previous case.  This
1309 really only shows up in eliminating error-checking code.
1310
1311 We also make sure that we deal with this very common case:
1312
1313         case e of 
1314           x -> ...x...
1315
1316 Here we are using the case as a strict let; if x is used only once
1317 then we want to inline it.  We have to be careful that this doesn't 
1318 make the program terminate when it would have diverged before, so we
1319 check that 
1320         - e is already evaluated (it may so if e is a variable)
1321         - x is used strictly, or
1322
1323 Lastly, the code in SimplUtils.mkCase combines identical RHSs.  So
1324
1325         case e of       ===> case e of DEFAULT -> r
1326            True  -> r
1327            False -> r
1328
1329 Now again the case may be elminated by the CaseElim transformation.
1330
1331
1332 Further notes about case elimination
1333 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1334 Consider:       test :: Integer -> IO ()
1335                 test = print
1336
1337 Turns out that this compiles to:
1338     Print.test
1339       = \ eta :: Integer
1340           eta1 :: State# RealWorld ->
1341           case PrelNum.< eta PrelNum.zeroInteger of wild { __DEFAULT ->
1342           case hPutStr stdout
1343                  (PrelNum.jtos eta ($w[] @ Char))
1344                  eta1
1345           of wild1 { (# new_s, a4 #) -> PrelIO.lvl23 new_s  }}
1346
1347 Notice the strange '<' which has no effect at all. This is a funny one.  
1348 It started like this:
1349
1350 f x y = if x < 0 then jtos x
1351           else if y==0 then "" else jtos x
1352
1353 At a particular call site we have (f v 1).  So we inline to get
1354
1355         if v < 0 then jtos x 
1356         else if 1==0 then "" else jtos x
1357
1358 Now simplify the 1==0 conditional:
1359
1360         if v<0 then jtos v else jtos v
1361
1362 Now common-up the two branches of the case:
1363
1364         case (v<0) of DEFAULT -> jtos v
1365
1366 Why don't we drop the case?  Because it's strict in v.  It's technically
1367 wrong to drop even unnecessary evaluations, and in practice they
1368 may be a result of 'seq' so we *definitely* don't want to drop those.
1369 I don't really know how to improve this situation.
1370
1371
1372 \begin{code}
1373 simplCaseBinder :: SimplEnv -> OutExpr -> InId -> SimplM (SimplEnv, OutId)
1374 simplCaseBinder env scrut case_bndr
1375   | switchIsOn (getSwitchChecker env) NoCaseOfCase
1376         -- See Note [no-case-of-case]
1377   = do  { (env, case_bndr') <- simplBinder env case_bndr
1378         ; return (env, case_bndr') }
1379
1380 simplCaseBinder env (Var v) case_bndr
1381 -- Failed try [see Note 2 above]
1382 --     not (isEvaldUnfolding (idUnfolding v))
1383   = do  { (env, case_bndr') <- simplBinder env (zapOccInfo case_bndr)
1384         ; return (modifyInScope env v case_bndr', case_bndr') }
1385         -- We could extend the substitution instead, but it would be
1386         -- a hack because then the substitution wouldn't be idempotent
1387         -- any more (v is an OutId).  And this does just as well.
1388             
1389 simplCaseBinder env (Cast (Var v) co) case_bndr         -- Note [Case of cast]
1390   = do  { (env, case_bndr') <- simplBinder env (zapOccInfo case_bndr)
1391         ; let rhs = Cast (Var case_bndr') (mkSymCoercion co)
1392         ; return (addBinderUnfolding env v rhs, case_bndr') }
1393
1394 simplCaseBinder env other_scrut case_bndr 
1395   = do  { (env, case_bndr') <- simplBinder env case_bndr
1396         ; return (env, case_bndr') }
1397
1398 zapOccInfo :: InId -> InId      -- See Note [zapOccInfo]
1399 zapOccInfo b = b `setIdOccInfo` NoOccInfo
1400 \end{code}
1401
1402
1403 simplAlts does two things:
1404
1405 1.  Eliminate alternatives that cannot match, including the
1406     DEFAULT alternative.
1407
1408 2.  If the DEFAULT alternative can match only one possible constructor,
1409     then make that constructor explicit.
1410     e.g.
1411         case e of x { DEFAULT -> rhs }
1412      ===>
1413         case e of x { (a,b) -> rhs }
1414     where the type is a single constructor type.  This gives better code
1415     when rhs also scrutinises x or e.
1416
1417 Here "cannot match" includes knowledge from GADTs
1418
1419 It's a good idea do do this stuff before simplifying the alternatives, to
1420 avoid simplifying alternatives we know can't happen, and to come up with
1421 the list of constructors that are handled, to put into the IdInfo of the
1422 case binder, for use when simplifying the alternatives.
1423
1424 Eliminating the default alternative in (1) isn't so obvious, but it can
1425 happen:
1426
1427 data Colour = Red | Green | Blue
1428
1429 f x = case x of
1430         Red -> ..
1431         Green -> ..
1432         DEFAULT -> h x
1433
1434 h y = case y of
1435         Blue -> ..
1436         DEFAULT -> [ case y of ... ]
1437
1438 If we inline h into f, the default case of the inlined h can't happen.
1439 If we don't notice this, we may end up filtering out *all* the cases
1440 of the inner case y, which give us nowhere to go!
1441
1442
1443 \begin{code}
1444 simplAlts :: SimplEnv 
1445           -> OutExpr
1446           -> InId                       -- Case binder
1447           -> [InAlt] -> SimplCont
1448           -> SimplM (OutId, [OutAlt])   -- Includes the continuation
1449 -- Like simplExpr, this just returns the simplified alternatives;
1450 -- it not return an environment
1451
1452 simplAlts env scrut case_bndr alts cont'
1453   = -- pprTrace "simplAlts" (ppr alts $$ ppr (seIdSubst env)) $
1454     do  { let alt_env = zapFloats env
1455         ; (alt_env, case_bndr') <- simplCaseBinder alt_env scrut case_bndr
1456
1457         ; (imposs_deflt_cons, in_alts) <- prepareAlts scrut case_bndr' alts
1458
1459         ; alts' <- mapM (simplAlt alt_env imposs_deflt_cons case_bndr' cont') in_alts
1460         ; return (case_bndr', alts') }
1461
1462 ------------------------------------
1463 simplAlt :: SimplEnv
1464          -> [AltCon]    -- These constructors can't be present when
1465                         -- matching the DEFAULT alternative
1466          -> OutId       -- The case binder
1467          -> SimplCont
1468          -> InAlt
1469          -> SimplM OutAlt
1470
1471 simplAlt env imposs_deflt_cons case_bndr' cont' (DEFAULT, bndrs, rhs)
1472   = ASSERT( null bndrs )
1473     do  { let env' = addBinderOtherCon env case_bndr' imposs_deflt_cons
1474                 -- Record the constructors that the case-binder *can't* be.
1475         ; rhs' <- simplExprC env' rhs cont'
1476         ; return (DEFAULT, [], rhs') }
1477
1478 simplAlt env imposs_deflt_cons case_bndr' cont' (LitAlt lit, bndrs, rhs)
1479   = ASSERT( null bndrs )
1480     do  { let env' = addBinderUnfolding env case_bndr' (Lit lit)
1481         ; rhs' <- simplExprC env' rhs cont'
1482         ; return (LitAlt lit, [], rhs') }
1483
1484 simplAlt env imposs_deflt_cons case_bndr' cont' (DataAlt con, vs, rhs)
1485   = do  {       -- Deal with the pattern-bound variables
1486           (env, vs') <- simplBinders env (add_evals con vs)
1487
1488                 -- Mark the ones that are in ! positions in the
1489                 -- data constructor as certainly-evaluated.
1490         ; let vs'' = add_evals con vs'
1491
1492                 -- Bind the case-binder to (con args)
1493         ; let inst_tys' = tyConAppArgs (idType case_bndr')
1494               con_args  = map Type inst_tys' ++ varsToCoreExprs vs'' 
1495               env'      = addBinderUnfolding env case_bndr' (mkConApp con con_args)
1496
1497         ; rhs' <- simplExprC env' rhs cont'
1498         ; return (DataAlt con, vs'', rhs') }
1499   where
1500         -- add_evals records the evaluated-ness of the bound variables of
1501         -- a case pattern.  This is *important*.  Consider
1502         --      data T = T !Int !Int
1503         --
1504         --      case x of { T a b -> T (a+1) b }
1505         --
1506         -- We really must record that b is already evaluated so that we don't
1507         -- go and re-evaluate it when constructing the result.
1508         -- See Note [Data-con worker strictness] in MkId.lhs
1509     add_evals dc vs = cat_evals dc vs (dataConRepStrictness dc)
1510
1511     cat_evals dc vs strs
1512         = go vs strs
1513         where
1514           go [] [] = []
1515           go (v:vs) strs | isTyVar v = v : go vs strs
1516           go (v:vs) (str:strs)
1517             | isMarkedStrict str = evald_v  : go vs strs
1518             | otherwise          = zapped_v : go vs strs
1519             where
1520               zapped_v = zap_occ_info v
1521               evald_v  = zapped_v `setIdUnfolding` evaldUnfolding
1522           go _ _ = pprPanic "cat_evals" (ppr dc $$ ppr vs $$ ppr strs)
1523
1524         -- If the case binder is alive, then we add the unfolding
1525         --      case_bndr = C vs
1526         -- to the envt; so vs are now very much alive
1527         -- Note [Aug06] I can't see why this actually matters
1528     zap_occ_info | isDeadBinder case_bndr' = \id -> id
1529                  | otherwise               = zapOccInfo
1530
1531 addBinderUnfolding :: SimplEnv -> Id -> CoreExpr -> SimplEnv
1532 addBinderUnfolding env bndr rhs
1533   = modifyInScope env bndr (bndr `setIdUnfolding` mkUnfolding False rhs)
1534
1535 addBinderOtherCon :: SimplEnv -> Id -> [AltCon] -> SimplEnv
1536 addBinderOtherCon env bndr cons
1537   = modifyInScope env bndr (bndr `setIdUnfolding` mkOtherCon cons)
1538 \end{code}
1539
1540
1541 %************************************************************************
1542 %*                                                                      *
1543 \subsection{Known constructor}
1544 %*                                                                      *
1545 %************************************************************************
1546
1547 We are a bit careful with occurrence info.  Here's an example
1548
1549         (\x* -> case x of (a*, b) -> f a) (h v, e)
1550
1551 where the * means "occurs once".  This effectively becomes
1552         case (h v, e) of (a*, b) -> f a)
1553 and then
1554         let a* = h v; b = e in f a
1555 and then
1556         f (h v)
1557
1558 All this should happen in one sweep.
1559
1560 \begin{code}
1561 knownCon :: SimplEnv -> OutExpr -> AltCon -> [OutExpr]
1562          -> InId -> [InAlt] -> SimplCont
1563          -> SimplM (SimplEnv, OutExpr)
1564
1565 knownCon env scrut con args bndr alts cont
1566   = do  { tick (KnownBranch bndr)
1567         ; knownAlt env scrut args bndr (findAlt con alts) cont }
1568
1569 knownAlt env scrut args bndr (DEFAULT, bs, rhs) cont
1570   = ASSERT( null bs )
1571     do  { env <- simplNonRecX env bndr scrut
1572                 -- This might give rise to a binding with non-atomic args
1573                 -- like x = Node (f x) (g x)
1574                 -- but simplNonRecX will atomic-ify it
1575         ; simplExprF env rhs cont }
1576
1577 knownAlt env scrut args bndr (LitAlt lit, bs, rhs) cont
1578   = ASSERT( null bs )
1579     do  { env <- simplNonRecX env bndr scrut
1580         ; simplExprF env rhs cont }
1581
1582 knownAlt env scrut args bndr (DataAlt dc, bs, rhs) cont
1583   = do  { let dead_bndr  = isDeadBinder bndr    -- bndr is an InId
1584               n_drop_tys = length (dataConUnivTyVars dc)
1585         ; env <- bind_args env dead_bndr bs (drop n_drop_tys args)
1586         ; let
1587                 -- It's useful to bind bndr to scrut, rather than to a fresh
1588                 -- binding      x = Con arg1 .. argn
1589                 -- because very often the scrut is a variable, so we avoid
1590                 -- creating, and then subsequently eliminating, a let-binding
1591                 -- BUT, if scrut is a not a variable, we must be careful
1592                 -- about duplicating the arg redexes; in that case, make
1593                 -- a new con-app from the args
1594                 bndr_rhs  = case scrut of
1595                                 Var v -> scrut
1596                                 other -> con_app
1597                 con_app = mkConApp dc (take n_drop_tys args ++ con_args)
1598                 con_args = [substExpr env (varToCoreExpr b) | b <- bs]
1599                                 -- args are aready OutExprs, but bs are InIds
1600
1601         ; env <- simplNonRecX env bndr bndr_rhs
1602         ; -- pprTrace "knownCon2" (ppr bs $$ ppr rhs $$ ppr (seIdSubst env)) $
1603           simplExprF env rhs cont }
1604
1605 -- Ugh!
1606 bind_args env dead_bndr [] _  = return env
1607
1608 bind_args env dead_bndr (b:bs) (Type ty : args)
1609   = ASSERT( isTyVar b )
1610     bind_args (extendTvSubst env b ty) dead_bndr bs args
1611     
1612 bind_args env dead_bndr (b:bs) (arg : args)
1613   = ASSERT( isId b )
1614     do  { let b' = if dead_bndr then b else zapOccInfo b
1615                 -- Note that the binder might be "dead", because it doesn't occur 
1616                 -- in the RHS; and simplNonRecX may therefore discard it via postInlineUnconditionally
1617                 -- Nevertheless we must keep it if the case-binder is alive, because it may
1618                 -- be used in the con_app.  See Note [zapOccInfo]
1619         ; env <- simplNonRecX env b' arg
1620         ; bind_args env dead_bndr bs args }
1621
1622 bind_args _ _ _ _ = panic "bind_args"
1623 \end{code}
1624
1625
1626 %************************************************************************
1627 %*                                                                      *
1628 \subsection{Duplicating continuations}
1629 %*                                                                      *
1630 %************************************************************************
1631
1632 \begin{code}
1633 prepareCaseCont :: SimplEnv
1634                 -> [InAlt] -> SimplCont
1635                 -> SimplM (SimplEnv, SimplCont,SimplCont)
1636                         -- Return a duplicatable continuation, a non-duplicable part 
1637                         -- plus some extra bindings (that scope over the entire
1638                         -- continunation)
1639
1640         -- No need to make it duplicatable if there's only one alternative
1641 prepareCaseCont env [alt] cont = return (env, cont, mkBoringStop (contResultType cont))
1642 prepareCaseCont env alts  cont = mkDupableCont env cont
1643 \end{code}
1644
1645 \begin{code}
1646 mkDupableCont :: SimplEnv -> SimplCont 
1647               -> SimplM (SimplEnv, SimplCont, SimplCont)
1648
1649 mkDupableCont env cont
1650   | contIsDupable cont
1651   = returnSmpl (env, cont, mkBoringStop (contResultType cont))
1652
1653 mkDupableCont env (Stop {}) = panic "mkDupableCont"     -- Handled by previous eqn
1654
1655 mkDupableCont env (CoerceIt ty cont)
1656   = do  { (env, dup, nodup) <- mkDupableCont env cont
1657         ; return (env, CoerceIt ty dup, nodup) }
1658
1659 mkDupableCont env cont@(StrictBind bndr _ _ se _)
1660   =  return (env, mkBoringStop (substTy se (idType bndr)), cont)
1661         -- See Note [Duplicating strict continuations]
1662
1663 mkDupableCont env cont@(StrictArg _ fun_ty _ _)
1664   =  return (env, mkBoringStop (funArgTy fun_ty), cont)
1665         -- See Note [Duplicating strict continuations]
1666
1667 mkDupableCont env (ApplyTo _ arg se cont)
1668   =     -- e.g.         [...hole...] (...arg...)
1669         --      ==>
1670         --              let a = ...arg... 
1671         --              in [...hole...] a
1672     do  { (env, dup_cont, nodup_cont) <- mkDupableCont env cont
1673         ; arg <- simplExpr (se `setInScope` env) arg
1674         ; (env, arg) <- makeTrivial env arg
1675         ; let app_cont = ApplyTo OkToDup arg (zapSubstEnv env) dup_cont
1676         ; return (env, app_cont, nodup_cont) }
1677
1678 mkDupableCont env cont@(Select _ case_bndr [(_,bs,rhs)] se case_cont)
1679 --  See Note [Single-alternative case]
1680 --  | not (exprIsDupable rhs && contIsDupable case_cont)
1681 --  | not (isDeadBinder case_bndr)
1682   | all isDeadBinder bs         -- InIds
1683   = return (env, mkBoringStop scrut_ty, cont)
1684   where
1685     scrut_ty = substTy se (idType case_bndr)
1686
1687 mkDupableCont env (Select _ case_bndr alts se cont)
1688   =     -- e.g.         (case [...hole...] of { pi -> ei })
1689         --      ===>
1690         --              let ji = \xij -> ei 
1691         --              in case [...hole...] of { pi -> ji xij }
1692     do  { tick (CaseOfCase case_bndr)
1693         ; (env, dup_cont, nodup_cont) <- mkDupableCont env cont
1694                 -- NB: call mkDupableCont here, *not* prepareCaseCont
1695                 -- We must make a duplicable continuation, whereas prepareCaseCont
1696                 -- doesn't when there is a single case branch
1697
1698         ; let alt_env = se `setInScope` env 
1699         ; (alt_env, case_bndr') <- simplBinder alt_env case_bndr
1700         ; alts' <- mapM (simplAlt alt_env [] case_bndr' dup_cont) alts
1701         -- Safe to say that there are no handled-cons for the DEFAULT case
1702                 -- NB: simplBinder does not zap deadness occ-info, so
1703                 -- a dead case_bndr' will still advertise its deadness
1704                 -- This is really important because in
1705                 --      case e of b { (# p,q #) -> ... }
1706                 -- b is always dead, and indeed we are not allowed to bind b to (# p,q #),
1707                 -- which might happen if e was an explicit unboxed pair and b wasn't marked dead.
1708                 -- In the new alts we build, we have the new case binder, so it must retain
1709                 -- its deadness.
1710         -- NB: we don't use alt_env further; it has the substEnv for
1711         --     the alternatives, and we don't want that
1712
1713         ; (env, alts') <- mkDupableAlts env case_bndr' alts'
1714         ; return (env,  -- Note [Duplicated env]
1715                   Select OkToDup case_bndr' alts' (zapSubstEnv env)
1716                          (mkBoringStop (contResultType dup_cont)),
1717                   nodup_cont) }
1718
1719
1720 mkDupableAlts :: SimplEnv -> OutId -> [InAlt]
1721               -> SimplM (SimplEnv, [InAlt])
1722 -- Absorbs the continuation into the new alternatives
1723
1724 mkDupableAlts env case_bndr' alts
1725   = go env alts
1726   where
1727     go env [] = return (env, [])
1728     go env (alt:alts)
1729         = do { (env, alt') <- mkDupableAlt env case_bndr' alt
1730      ; (env, alts') <- go env alts
1731              ; return (env, alt' : alts' ) }
1732                                         
1733 mkDupableAlt env case_bndr' (con, bndrs', rhs')
1734   | exprIsDupable rhs'  -- Note [Small alternative rhs]
1735   = return (env, (con, bndrs', rhs'))
1736   | otherwise
1737   = do  { let rhs_ty'     = exprType rhs'
1738               used_bndrs' = filter abstract_over (case_bndr' : bndrs')
1739               abstract_over bndr 
1740                   | isTyVar bndr = True -- Abstract over all type variables just in case
1741                   | otherwise    = not (isDeadBinder bndr)
1742                         -- The deadness info on the new Ids is preserved by simplBinders
1743
1744         ; (final_bndrs', final_args)    -- Note [Join point abstraction]
1745                 <- if (any isId used_bndrs')
1746                    then return (used_bndrs', varsToCoreExprs used_bndrs')
1747                     else do { rw_id <- newId FSLIT("w") realWorldStatePrimTy
1748                             ; return ([rw_id], [Var realWorldPrimId]) }
1749              
1750         ; join_bndr <- newId FSLIT("$j") (mkPiTypes final_bndrs' rhs_ty')
1751                 -- Note [Funky mkPiTypes]
1752         
1753         ; let   -- We make the lambdas into one-shot-lambdas.  The
1754                 -- join point is sure to be applied at most once, and doing so
1755                 -- prevents the body of the join point being floated out by
1756                 -- the full laziness pass
1757                 really_final_bndrs     = map one_shot final_bndrs'
1758                 one_shot v | isId v    = setOneShotLambda v
1759                            | otherwise = v
1760                 join_rhs  = mkLams really_final_bndrs rhs'
1761                 join_call = mkApps (Var join_bndr) final_args
1762
1763         ; return (addNonRec env join_bndr join_rhs, (con, bndrs', join_call)) }
1764                 -- See Note [Duplicated env]
1765 \end{code}
1766
1767 Note [Duplicated env]
1768 ~~~~~~~~~~~~~~~~~~~~~
1769 Some of the alternatives are simplified, but have not been turned into a join point
1770 So they *must* have an zapped subst-env.  So we can't use completeNonRecX to
1771 bind the join point, because it might to do PostInlineUnconditionally, and
1772 we'd lose that when zapping the subst-env.  We could have a per-alt subst-env,
1773 but zapping it (as we do in mkDupableCont, the Select case) is safe, and
1774 at worst delays the join-point inlining.
1775
1776 Note [Small alterantive rhs]
1777 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1778 It is worth checking for a small RHS because otherwise we
1779 get extra let bindings that may cause an extra iteration of the simplifier to
1780 inline back in place.  Quite often the rhs is just a variable or constructor.
1781 The Ord instance of Maybe in PrelMaybe.lhs, for example, took several extra
1782 iterations because the version with the let bindings looked big, and so wasn't
1783 inlined, but after the join points had been inlined it looked smaller, and so
1784 was inlined.
1785
1786 NB: we have to check the size of rhs', not rhs. 
1787 Duplicating a small InAlt might invalidate occurrence information
1788 However, if it *is* dupable, we return the *un* simplified alternative,
1789 because otherwise we'd need to pair it up with an empty subst-env....
1790 but we only have one env shared between all the alts.
1791 (Remember we must zap the subst-env before re-simplifying something).
1792 Rather than do this we simply agree to re-simplify the original (small) thing later.
1793
1794 Note [Funky mkPiTypes]
1795 ~~~~~~~~~~~~~~~~~~~~~~
1796 Notice the funky mkPiTypes.  If the contructor has existentials
1797 it's possible that the join point will be abstracted over
1798 type varaibles as well as term variables.
1799  Example:  Suppose we have
1800         data T = forall t.  C [t]
1801  Then faced with
1802         case (case e of ...) of
1803             C t xs::[t] -> rhs
1804  We get the join point
1805         let j :: forall t. [t] -> ...
1806             j = /\t \xs::[t] -> rhs
1807         in
1808         case (case e of ...) of
1809             C t xs::[t] -> j t xs
1810
1811 Note [Join point abstaction]
1812 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1813 If we try to lift a primitive-typed something out
1814 for let-binding-purposes, we will *caseify* it (!),
1815 with potentially-disastrous strictness results.  So
1816 instead we turn it into a function: \v -> e
1817 where v::State# RealWorld#.  The value passed to this function
1818 is realworld#, which generates (almost) no code.
1819
1820 There's a slight infelicity here: we pass the overall 
1821 case_bndr to all the join points if it's used in *any* RHS,
1822 because we don't know its usage in each RHS separately
1823
1824 We used to say "&& isUnLiftedType rhs_ty'" here, but now
1825 we make the join point into a function whenever used_bndrs'
1826 is empty.  This makes the join-point more CPR friendly. 
1827 Consider:       let j = if .. then I# 3 else I# 4
1828                 in case .. of { A -> j; B -> j; C -> ... }
1829
1830 Now CPR doesn't w/w j because it's a thunk, so
1831 that means that the enclosing function can't w/w either,
1832 which is a lose.  Here's the example that happened in practice:
1833         kgmod :: Int -> Int -> Int
1834         kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
1835                     then 78
1836                     else 5
1837
1838 I have seen a case alternative like this:
1839         True -> \v -> ...
1840 It's a bit silly to add the realWorld dummy arg in this case, making
1841         $j = \s v -> ...
1842            True -> $j s
1843 (the \v alone is enough to make CPR happy) but I think it's rare
1844
1845 Note [Duplicating strict continuations]
1846 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1847 Do *not* duplicate StrictBind and StritArg continuations.  We gain
1848 nothing by propagating them into the expressions, and we do lose a
1849 lot.  Here's an example:
1850         && (case x of { T -> F; F -> T }) E
1851 Now, && is strict so we end up simplifying the case with
1852 an ArgOf continuation.  If we let-bind it, we get
1853
1854         let $j = \v -> && v E
1855         in simplExpr (case x of { T -> F; F -> T })
1856                      (ArgOf (\r -> $j r)
1857 And after simplifying more we get
1858
1859         let $j = \v -> && v E
1860         in case x of { T -> $j F; F -> $j T }
1861 Which is a Very Bad Thing
1862
1863 The desire not to duplicate is the entire reason that
1864 mkDupableCont returns a pair of continuations.
1865
1866 The original plan had:
1867 e.g.    (...strict-fn...) [...hole...]
1868         ==>
1869                 let $j = \a -> ...strict-fn...
1870                 in $j [...hole...]
1871
1872 Note [Single-alternative cases]
1873 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1874 This case is just like the ArgOf case.  Here's an example:
1875         data T a = MkT !a
1876         ...(MkT (abs x))...
1877 Then we get
1878         case (case x of I# x' -> 
1879               case x' <# 0# of
1880                 True  -> I# (negate# x')
1881                 False -> I# x') of y {
1882           DEFAULT -> MkT y
1883 Because the (case x) has only one alternative, we'll transform to
1884         case x of I# x' ->
1885         case (case x' <# 0# of
1886                 True  -> I# (negate# x')
1887                 False -> I# x') of y {
1888           DEFAULT -> MkT y
1889 But now we do *NOT* want to make a join point etc, giving 
1890         case x of I# x' ->
1891         let $j = \y -> MkT y
1892         in case x' <# 0# of
1893                 True  -> $j (I# (negate# x'))
1894                 False -> $j (I# x')
1895 In this case the $j will inline again, but suppose there was a big
1896 strict computation enclosing the orginal call to MkT.  Then, it won't
1897 "see" the MkT any more, because it's big and won't get duplicated.
1898 And, what is worse, nothing was gained by the case-of-case transform.
1899
1900 When should use this case of mkDupableCont?  
1901 However, matching on *any* single-alternative case is a *disaster*;
1902   e.g.  case (case ....) of (a,b) -> (# a,b #)
1903   We must push the outer case into the inner one!
1904 Other choices:
1905
1906    * Match [(DEFAULT,_,_)], but in the common case of Int, 
1907      the alternative-filling-in code turned the outer case into
1908                 case (...) of y { I# _ -> MkT y }
1909
1910    * Match on single alternative plus (not (isDeadBinder case_bndr))
1911      Rationale: pushing the case inwards won't eliminate the construction.
1912      But there's a risk of
1913                 case (...) of y { (a,b) -> let z=(a,b) in ... }
1914      Now y looks dead, but it'll come alive again.  Still, this
1915      seems like the best option at the moment.
1916
1917    * Match on single alternative plus (all (isDeadBinder bndrs))
1918      Rationale: this is essentially  seq.
1919
1920    * Match when the rhs is *not* duplicable, and hence would lead to a
1921      join point.  This catches the disaster-case above.  We can test
1922      the *un-simplified* rhs, which is fine.  It might get bigger or
1923      smaller after simplification; if it gets smaller, this case might
1924      fire next time round.  NB also that we must test contIsDupable
1925      case_cont *btoo, because case_cont might be big!
1926
1927      HOWEVER: I found that this version doesn't work well, because
1928      we can get         let x = case (...) of { small } in ...case x...
1929      When x is inlined into its full context, we find that it was a bad
1930      idea to have pushed the outer case inside the (...) case.
1931