Wibble
[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 IdInfo
18 import Coercion
19 import TcGadt           ( dataConCanMatch )
20 import DataCon          ( dataConTyCon, dataConRepStrictness )
21 import TyCon            ( tyConArity, isAlgTyCon, isNewTyCon, tyConDataCons_maybe )
22 import CoreSyn
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 List             ( nub )
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                           (isStrictBndr 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 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 \begin{code}
412 prepareRhs :: SimplEnv -> OutExpr -> SimplM (SimplEnv, OutExpr)
413 -- Adds new floats to the env iff that allows us to return a good RHS
414
415 prepareRhs env (Cast rhs co)    -- Note [Float coercions]
416   = do  { (env', rhs') <- makeTrivial env rhs
417         ; return (env', Cast rhs' co) }
418
419 prepareRhs env rhs
420   | (Var fun, args) <- collectArgs rhs          -- It's an application
421   , let n_args = valArgCount args       
422   , n_args > 0                                  -- ...but not a trivial one     
423   , isDataConWorkId fun || n_args < idArity fun -- ...and it's a constructor or PAP
424   = go env (Var fun) args
425   where
426     go env fun []           = return (env, fun)
427     go env fun (arg : args) = do { (env', arg') <- makeTrivial env arg
428                                  ; go env' (App fun arg') args }
429
430 prepareRhs env rhs              -- The default case
431   = return (env, rhs)
432 \end{code}
433
434 Note [Float coercions]
435 ~~~~~~~~~~~~~~~~~~~~~~
436 When we find the binding
437         x = e `cast` co
438 we'd like to transform it to
439         x' = e
440         x = x `cast` co         -- A trivial binding
441 There's a chance that e will be a constructor application or function, or something
442 like that, so moving the coerion to the usage site may well cancel the coersions
443 and lead to further optimisation.  Example:
444
445      data family T a :: *
446      data instance T Int = T Int
447
448      foo :: Int -> Int -> Int
449      foo m n = ...
450         where
451           x = T m
452           go 0 = 0
453           go n = case x of { T m -> go (n-m) }
454                 -- This case should optimise
455
456
457 \begin{code}
458 makeTrivial :: SimplEnv -> OutExpr -> SimplM (SimplEnv, OutExpr)
459 -- Binds the expression to a variable, if it's not trivial, returning the variable
460 makeTrivial env expr
461   | exprIsTrivial expr
462   = return (env, expr)
463   | otherwise           -- See Note [Take care] below
464   = do  { var <- newId FSLIT("a") (exprType expr)
465         ; env <- completeNonRecX env NotTopLevel NonRecursive 
466                                  False var var expr
467         ; return (env, substExpr env (Var var)) }
468 \end{code}
469
470
471 %************************************************************************
472 %*                                                                      *
473 \subsection{Completing a lazy binding}
474 %*                                                                      *
475 %************************************************************************
476
477 completeBind
478   * deals only with Ids, not TyVars
479   * takes an already-simplified binder and RHS
480   * is used for both recursive and non-recursive bindings
481   * is used for both top-level and non-top-level bindings
482
483 It does the following:
484   - tries discarding a dead binding
485   - tries PostInlineUnconditionally
486   - add unfolding [this is the only place we add an unfolding]
487   - add arity
488
489 It does *not* attempt to do let-to-case.  Why?  Because it is used for
490   - top-level bindings (when let-to-case is impossible) 
491   - many situations where the "rhs" is known to be a WHNF
492                 (so let-to-case is inappropriate).
493
494 Nor does it do the atomic-argument thing
495
496 \begin{code}
497 completeBind :: SimplEnv
498              -> TopLevelFlag            -- Flag stuck into unfolding
499              -> InId                    -- Old binder
500              -> OutId -> OutExpr        -- New binder and RHS
501              -> SimplM SimplEnv
502 -- completeBind may choose to do its work 
503 --      * by extending the substitution (e.g. let x = y in ...)
504 --      * or by adding to the floats in the envt
505
506 completeBind env top_lvl old_bndr new_bndr new_rhs
507   | postInlineUnconditionally env top_lvl new_bndr occ_info new_rhs unfolding
508                 -- Inline and discard the binding
509   = do  { tick (PostInlineUnconditionally old_bndr)
510         ; -- pprTrace "postInlineUnconditionally" (ppr old_bndr <+> ppr new_bndr <+> ppr new_rhs) $
511           return (extendIdSubst env old_bndr (DoneEx new_rhs)) }
512         -- Use the substitution to make quite, quite sure that the
513         -- substitution will happen, since we are going to discard the binding
514
515   |  otherwise
516   = let
517         --      Arity info
518         new_bndr_info = idInfo new_bndr `setArityInfo` exprArity new_rhs
519
520         --      Unfolding info
521         -- Add the unfolding *only* for non-loop-breakers
522         -- Making loop breakers not have an unfolding at all 
523         -- means that we can avoid tests in exprIsConApp, for example.
524         -- This is important: if exprIsConApp says 'yes' for a recursive
525         -- thing, then we can get into an infinite loop
526
527         --      Demand info
528         -- If the unfolding is a value, the demand info may
529         -- go pear-shaped, so we nuke it.  Example:
530         --      let x = (a,b) in
531         --      case x of (p,q) -> h p q x
532         -- Here x is certainly demanded. But after we've nuked
533         -- the case, we'll get just
534         --      let x = (a,b) in h a b x
535         -- and now x is not demanded (I'm assuming h is lazy)
536         -- This really happens.  Similarly
537         --      let f = \x -> e in ...f..f...
538         -- After inlining f at some of its call sites the original binding may
539         -- (for example) be no longer strictly demanded.
540         -- The solution here is a bit ad hoc...
541         info_w_unf = new_bndr_info `setUnfoldingInfo` unfolding
542         final_info | loop_breaker               = new_bndr_info
543                    | isEvaldUnfolding unfolding = zapDemandInfo info_w_unf `orElse` info_w_unf
544                    | otherwise                  = info_w_unf
545
546         final_id = new_bndr `setIdInfo` final_info
547     in
548                 -- These seqs forces the Id, and hence its IdInfo,
549                 -- and hence any inner substitutions
550     final_id                                    `seq`
551     -- pprTrace "Binding" (ppr final_id <+> ppr unfolding) $
552     return (addNonRec env final_id new_rhs)
553   where 
554     unfolding    = mkUnfolding (isTopLevel top_lvl) new_rhs
555     loop_breaker = isNonRuleLoopBreaker occ_info
556     old_info     = idInfo old_bndr
557     occ_info     = occInfo old_info
558 \end{code}
559
560
561
562 %************************************************************************
563 %*                                                                      *
564 \subsection[Simplify-simplExpr]{The main function: simplExpr}
565 %*                                                                      *
566 %************************************************************************
567
568 The reason for this OutExprStuff stuff is that we want to float *after*
569 simplifying a RHS, not before.  If we do so naively we get quadratic
570 behaviour as things float out.
571
572 To see why it's important to do it after, consider this (real) example:
573
574         let t = f x
575         in fst t
576 ==>
577         let t = let a = e1
578                     b = e2
579                 in (a,b)
580         in fst t
581 ==>
582         let a = e1
583             b = e2
584             t = (a,b)
585         in
586         a       -- Can't inline a this round, cos it appears twice
587 ==>
588         e1
589
590 Each of the ==> steps is a round of simplification.  We'd save a
591 whole round if we float first.  This can cascade.  Consider
592
593         let f = g d
594         in \x -> ...f...
595 ==>
596         let f = let d1 = ..d.. in \y -> e
597         in \x -> ...f...
598 ==>
599         let d1 = ..d..
600         in \x -> ...(\y ->e)...
601
602 Only in this second round can the \y be applied, and it 
603 might do the same again.
604
605
606 \begin{code}
607 simplExpr :: SimplEnv -> CoreExpr -> SimplM CoreExpr
608 simplExpr env expr = simplExprC env expr (mkBoringStop expr_ty')
609                    where
610                      expr_ty' = substTy env (exprType expr)
611         -- The type in the Stop continuation, expr_ty', is usually not used
612         -- It's only needed when discarding continuations after finding
613         -- a function that returns bottom.
614         -- Hence the lazy substitution
615
616
617 simplExprC :: SimplEnv -> CoreExpr -> SimplCont -> SimplM CoreExpr
618         -- Simplify an expression, given a continuation
619 simplExprC env expr cont 
620   = -- pprTrace "simplExprC" (ppr expr $$ ppr cont {- $$ ppr (seIdSubst env) -} $$ ppr (seFloats env) ) $
621     do  { (env', expr') <- simplExprF (zapFloats env) expr cont
622         ; -- pprTrace "simplExprC ret" (ppr expr $$ ppr expr') $
623           -- pprTrace "simplExprC ret3" (ppr (seInScope env')) $
624           -- pprTrace "simplExprC ret4" (ppr (seFloats env')) $
625           return (wrapFloats env' expr') }
626
627 --------------------------------------------------
628 simplExprF :: SimplEnv -> InExpr -> SimplCont
629            -> SimplM (SimplEnv, OutExpr)
630
631 simplExprF env e cont 
632   = -- pprTrace "simplExprF" (ppr e $$ ppr cont $$ ppr (seTvSubst env) $$ ppr (seIdSubst env) {- $$ ppr (seFloats env) -} ) $
633     simplExprF' env e cont
634                                      
635 simplExprF' env (Var v)        cont = simplVar env v cont
636 simplExprF' env (Lit lit)      cont = rebuild env (Lit lit) cont
637 simplExprF' env (Note n expr)  cont = simplNote env n expr cont
638 simplExprF' env (Cast body co) cont = simplCast env body co cont
639 simplExprF' env (App fun arg)  cont = simplExprF env fun $
640                                       ApplyTo NoDup arg env cont
641
642 simplExprF' env expr@(Lam _ _) cont 
643   = simplLam env (map zap bndrs) body cont
644         -- The main issue here is under-saturated lambdas
645         --   (\x1. \x2. e) arg1
646         -- Here x1 might have "occurs-once" occ-info, because occ-info
647         -- is computed assuming that a group of lambdas is applied
648         -- all at once.  If there are too few args, we must zap the 
649         -- occ-info.
650   where
651     n_args   = countArgs cont
652     n_params = length bndrs
653     (bndrs, body) = collectBinders expr
654     zap | n_args >= n_params = \b -> b  
655         | otherwise          = \b -> if isTyVar b then b
656                                      else zapLamIdInfo b
657         -- NB: we count all the args incl type args
658         -- so we must count all the binders (incl type lambdas)
659
660 simplExprF' env (Type ty) cont
661   = ASSERT( contIsRhsOrArg cont )
662     do  { ty' <- simplType env ty
663         ; rebuild env (Type ty') cont }
664
665 simplExprF' env (Case scrut bndr case_ty alts) cont
666   | not (switchIsOn (getSwitchChecker env) NoCaseOfCase)
667   =     -- Simplify the scrutinee with a Select continuation
668     simplExprF env scrut (Select NoDup bndr alts env cont)
669
670   | otherwise
671   =     -- If case-of-case is off, simply simplify the case expression
672         -- in a vanilla Stop context, and rebuild the result around it
673     do  { case_expr' <- simplExprC env scrut case_cont
674         ; rebuild env case_expr' cont }
675   where
676     case_cont = Select NoDup bndr alts env (mkBoringStop case_ty')
677     case_ty'  = substTy env case_ty     -- c.f. defn of simplExpr
678
679 simplExprF' env (Let (Rec pairs) body) cont
680   = do  { env <- simplRecBndrs env (map fst pairs)
681                 -- NB: bndrs' don't have unfoldings or rules
682                 -- We add them as we go down
683
684         ; env <- simplRecBind env NotTopLevel pairs
685         ; simplExprF env body cont }
686
687 simplExprF' env (Let (NonRec bndr rhs) body) cont
688   = simplNonRecE env bndr (rhs, env) ([], body) cont
689
690 ---------------------------------
691 simplType :: SimplEnv -> InType -> SimplM OutType
692         -- Kept monadic just so we can do the seqType
693 simplType env ty
694   = -- pprTrace "simplType" (ppr ty $$ ppr (seTvSubst env)) $
695     seqType new_ty   `seq`   returnSmpl new_ty
696   where
697     new_ty = substTy env ty
698 \end{code}
699
700
701 %************************************************************************
702 %*                                                                      *
703 \subsection{The main rebuilder}
704 %*                                                                      *
705 %************************************************************************
706
707 \begin{code}
708 rebuild :: SimplEnv -> OutExpr -> SimplCont -> SimplM (SimplEnv, OutExpr)
709 -- At this point the substitution in the SimplEnv should be irrelevant
710 -- only the in-scope set and floats should matter
711 rebuild env expr cont
712   = -- pprTrace "rebuild" (ppr expr $$ ppr cont $$ ppr (seFloats env)) $
713     case cont of
714       Stop {}                      -> return (env, expr)
715       CoerceIt co cont             -> rebuild env (mkCoerce co expr) cont
716       Select _ bndr alts se cont   -> rebuildCase (se `setFloats` env) expr bndr alts cont
717       StrictArg fun ty info cont   -> rebuildCall env (fun `App` expr) (funResultTy ty) info cont
718       StrictBind b bs body se cont -> do { env' <- simplNonRecX (se `setFloats` env) b expr
719                                          ; simplLam env' bs body cont }
720       ApplyTo _ arg se cont        -> do { arg' <- simplExpr (se `setInScope` env) arg
721                                          ; rebuild env (App expr arg') cont }
722 \end{code}
723
724
725 %************************************************************************
726 %*                                                                      *
727 \subsection{Lambdas}
728 %*                                                                      *
729 %************************************************************************
730
731 \begin{code}
732 simplCast :: SimplEnv -> InExpr -> Coercion -> SimplCont
733           -> SimplM (SimplEnv, OutExpr)
734 simplCast env body co cont
735   = do  { co' <- simplType env co
736         ; simplExprF env body (addCoerce co' cont) }
737   where
738        addCoerce co cont = add_coerce co (coercionKind co) cont
739
740        add_coerce co (s1, k1) cont      -- co :: ty~ty
741          | s1 `coreEqType` k1 = cont    -- is a no-op
742
743        add_coerce co1 (s1, k2) (CoerceIt co2 cont)
744          | (l1, t1) <- coercionKind co2
745                 --      coerce T1 S1 (coerce S1 K1 e)
746                 -- ==>
747                 --      e,                      if T1=K1
748                 --      coerce T1 K1 e,         otherwise
749                 --
750                 -- For example, in the initial form of a worker
751                 -- we may find  (coerce T (coerce S (\x.e))) y
752                 -- and we'd like it to simplify to e[y/x] in one round 
753                 -- of simplification
754          , s1 `coreEqType` t1  = cont            -- The coerces cancel out  
755          | otherwise           = CoerceIt (mkTransCoercion co1 co2) cont
756     
757        add_coerce co (s1s2, t1t2) (ApplyTo dup arg arg_se cont)
758          | not (isTypeArg arg)  -- This whole case only works for value args
759                                 -- Could upgrade to have equiv thing for type apps too  
760          , isFunTy s1s2   -- t1t2 must be a function type, becuase it's applied
761                 -- co : s1s2 :=: t1t2
762                 --      (coerce (T1->T2) (S1->S2) F) E
763                 -- ===> 
764                 --      coerce T2 S2 (F (coerce S1 T1 E))
765                 --
766                 -- t1t2 must be a function type, T1->T2, because it's applied
767                 -- to something but s1s2 might conceivably not be
768                 --
769                 -- When we build the ApplyTo we can't mix the out-types
770                 -- with the InExpr in the argument, so we simply substitute
771                 -- to make it all consistent.  It's a bit messy.
772                 -- But it isn't a common case.
773                 --
774                 -- Example of use: Trac #995
775          = ApplyTo dup new_arg (zapSubstEnv env) (addCoerce co2 cont)
776          where
777            -- we split coercion t1->t2 :=: s1->s2 into t1 :=: s1 and 
778            -- t2 :=: s2 with left and right on the curried form: 
779            --    (->) t1 t2 :=: (->) s1 s2
780            [co1, co2] = decomposeCo 2 co
781            new_arg    = mkCoerce (mkSymCoercion co1) arg'
782            arg'       = substExpr arg_se arg
783
784        add_coerce co _ cont = CoerceIt co cont
785 \end{code}
786
787
788 %************************************************************************
789 %*                                                                      *
790 \subsection{Lambdas}
791 %*                                                                      *
792 %************************************************************************
793
794 \begin{code}
795 simplLam :: SimplEnv -> [InId] -> InExpr -> SimplCont
796          -> SimplM (SimplEnv, OutExpr)
797
798 simplLam env [] body cont = simplExprF env body cont
799
800         -- Type-beta reduction
801 simplLam env (bndr:bndrs) body (ApplyTo _ (Type ty_arg) arg_se cont)
802   = ASSERT( isTyVar bndr )
803     do  { tick (BetaReduction bndr)
804         ; ty_arg' <- simplType (arg_se `setInScope` env) ty_arg
805         ; simplLam (extendTvSubst env bndr ty_arg') bndrs body cont }
806
807         -- Ordinary beta reduction
808 simplLam env (bndr:bndrs) body (ApplyTo _ arg arg_se cont)
809   = do  { tick (BetaReduction bndr)     
810         ; simplNonRecE env bndr (arg, arg_se) (bndrs, body) cont }
811
812         -- Not enough args, so there are real lambdas left to put in the result
813 simplLam env bndrs body cont
814   = do  { (env, bndrs') <- simplLamBndrs env bndrs
815         ; body' <- simplExpr env body
816         ; new_lam <- mkLam bndrs' body'
817         ; rebuild env new_lam cont }
818
819 ------------------
820 simplNonRecE :: SimplEnv 
821              -> InId                    -- The binder
822              -> (InExpr, SimplEnv)      -- Rhs of binding (or arg of lambda)
823              -> ([InId], InExpr)        -- Body of the let/lambda
824                                         --      \xs.e
825              -> SimplCont
826              -> SimplM (SimplEnv, OutExpr)
827
828 -- simplNonRecE is used for
829 --  * non-top-level non-recursive lets in expressions
830 --  * beta reduction
831 --
832 -- It deals with strict bindings, via the StrictBind continuation,
833 -- which may abort the whole process
834 --
835 -- The "body" of the binding comes as a pair of ([InId],InExpr)
836 -- representing a lambda; so we recurse back to simplLam
837 -- Why?  Because of the binder-occ-info-zapping done before 
838 --       the call to simplLam in simplExprF (Lam ...)
839
840 simplNonRecE env bndr (rhs, rhs_se) (bndrs, body) cont
841   | preInlineUnconditionally env NotTopLevel bndr rhs
842   = do  { tick (PreInlineUnconditionally bndr)
843         ; simplLam (extendIdSubst env bndr (mkContEx rhs_se rhs)) bndrs body cont }
844
845   | isStrictBndr bndr
846   = do  { simplExprF (rhs_se `setFloats` env) rhs 
847                      (StrictBind bndr bndrs body env cont) }
848
849   | otherwise
850   = do  { (env, bndr') <- simplBinder env bndr
851         ; env <- simplLazyBind env NotTopLevel NonRecursive bndr bndr' rhs rhs_se
852         ; simplLam env bndrs body cont }
853 \end{code}
854
855
856 %************************************************************************
857 %*                                                                      *
858 \subsection{Notes}
859 %*                                                                      *
860 %************************************************************************
861
862 \begin{code}
863 -- Hack alert: we only distinguish subsumed cost centre stacks for the 
864 -- purposes of inlining.  All other CCCSs are mapped to currentCCS.
865 simplNote env (SCC cc) e cont
866   = do  { e' <- simplExpr (setEnclosingCC env currentCCS) e
867         ; rebuild env (mkSCC cc e') cont }
868
869 -- See notes with SimplMonad.inlineMode
870 simplNote env InlineMe e cont
871   | contIsRhsOrArg cont         -- Totally boring continuation; see notes above
872   = do  {                       -- Don't inline inside an INLINE expression
873           e' <- simplExpr (setMode inlineMode env) e
874         ; rebuild env (mkInlineMe e') cont }
875
876   | otherwise   -- Dissolve the InlineMe note if there's
877                 -- an interesting context of any kind to combine with
878                 -- (even a type application -- anything except Stop)
879   = simplExprF env e cont
880
881 simplNote env (CoreNote s) e cont
882   = simplExpr env e    `thenSmpl` \ e' ->
883     rebuild env (Note (CoreNote s) e') cont
884 \end{code}
885
886
887 %************************************************************************
888 %*                                                                      *
889 \subsection{Dealing with calls}
890 %*                                                                      *
891 %************************************************************************
892
893 \begin{code}
894 simplVar env var cont
895   = case substId env var of
896         DoneEx e         -> simplExprF (zapSubstEnv env) e cont
897         ContEx tvs ids e -> simplExprF (setSubstEnv env tvs ids) e cont
898         DoneId var1      -> completeCall (zapSubstEnv env) var1 cont
899                 -- Note [zapSubstEnv]
900                 -- The template is already simplified, so don't re-substitute.
901                 -- This is VITAL.  Consider
902                 --      let x = e in
903                 --      let y = \z -> ...x... in
904                 --      \ x -> ...y...
905                 -- We'll clone the inner \x, adding x->x' in the id_subst
906                 -- Then when we inline y, we must *not* replace x by x' in
907                 -- the inlined copy!!
908
909 ---------------------------------------------------------
910 --      Dealing with a call site
911
912 completeCall env var cont
913   = do  { dflags <- getDOptsSmpl
914         ; let   (args,call_cont) = contArgs cont
915                 -- The args are OutExprs, obtained by *lazily* substituting
916                 -- in the args found in cont.  These args are only examined
917                 -- to limited depth (unless a rule fires).  But we must do
918                 -- the substitution; rule matching on un-simplified args would
919                 -- be bogus
920
921         ------------- First try rules ----------------
922         -- Do this before trying inlining.  Some functions have 
923         -- rules *and* are strict; in this case, we don't want to 
924         -- inline the wrapper of the non-specialised thing; better
925         -- to call the specialised thing instead.
926         --
927         -- We used to use the black-listing mechanism to ensure that inlining of 
928         -- the wrapper didn't occur for things that have specialisations till a 
929         -- later phase, so but now we just try RULES first
930         --
931         -- You might think that we shouldn't apply rules for a loop breaker: 
932         -- doing so might give rise to an infinite loop, because a RULE is
933         -- rather like an extra equation for the function:
934         --      RULE:           f (g x) y = x+y
935         --      Eqn:            f a     y = a-y
936         --
937         -- But it's too drastic to disable rules for loop breakers.  
938         -- Even the foldr/build rule would be disabled, because foldr 
939         -- is recursive, and hence a loop breaker:
940         --      foldr k z (build g) = g k z
941         -- So it's up to the programmer: rules can cause divergence
942         ; let   in_scope   = getInScope env
943                 rules      = getRules env
944                 maybe_rule = case activeRule env of
945                                 Nothing     -> Nothing  -- No rules apply
946                                 Just act_fn -> lookupRule act_fn in_scope 
947                                                           rules var args 
948         ; case maybe_rule of {
949             Just (rule, rule_rhs) -> 
950                 tick (RuleFired (ru_name rule))                 `thenSmpl_`
951                 (if dopt Opt_D_dump_rule_firings dflags then
952                    pprTrace "Rule fired" (vcat [
953                         text "Rule:" <+> ftext (ru_name rule),
954                         text "Before:" <+> ppr var <+> sep (map pprParendExpr args),
955                         text "After: " <+> pprCoreExpr rule_rhs,
956                         text "Cont:  " <+> ppr call_cont])
957                  else
958                         id)             $
959                 simplExprF env rule_rhs (dropArgs (ruleArity rule) cont)
960                 -- The ruleArity says how many args the rule consumed
961         
962           ; Nothing -> do       -- No rules
963
964         ------------- Next try inlining ----------------
965         { let   arg_infos = [interestingArg arg | arg <- args, isValArg arg]
966                 n_val_args = length arg_infos
967                 interesting_cont = interestingCallContext (notNull args)
968                                                           (notNull arg_infos)
969                                                           call_cont
970                 active_inline = activeInline env var
971                 maybe_inline  = callSiteInline dflags active_inline
972                                        var arg_infos interesting_cont
973         ; case maybe_inline of {
974             Just unfolding      -- There is an inlining!
975               ->  do { tick (UnfoldingDone var)
976                      ; (if dopt Opt_D_dump_inlinings dflags then
977                            pprTrace "Inlining done" (vcat [
978                                 text "Before:" <+> ppr var <+> sep (map pprParendExpr args),
979                                 text "Inlined fn: " <+> nest 2 (ppr unfolding),
980                                 text "Cont:  " <+> ppr call_cont])
981                          else
982                                 id)
983                        simplExprF env unfolding cont }
984
985             ; Nothing ->                -- No inlining!
986
987         ------------- No inlining! ----------------
988         -- Next, look for rules or specialisations that match
989         --
990         rebuildCall env (Var var) (idType var) 
991                     (mkArgInfo var n_val_args call_cont) cont
992     }}}}
993
994 rebuildCall :: SimplEnv
995             -> OutExpr -> OutType       -- Function and its type
996             -> (Bool, [Bool])           -- See SimplUtils.mkArgInfo
997             -> SimplCont
998             -> SimplM (SimplEnv, OutExpr)
999 rebuildCall env fun fun_ty (has_rules, []) cont
1000   -- When we run out of strictness args, it means
1001   -- that the call is definitely bottom; see SimplUtils.mkArgInfo
1002   -- Then we want to discard the entire strict continuation.  E.g.
1003   --    * case (error "hello") of { ... }
1004   --    * (error "Hello") arg
1005   --    * f (error "Hello") where f is strict
1006   --    etc
1007   -- Then, especially in the first of these cases, we'd like to discard
1008   -- the continuation, leaving just the bottoming expression.  But the
1009   -- type might not be right, so we may have to add a coerce.
1010   | not (contIsTrivial cont)     -- Only do thia if there is a non-trivial
1011   = return (env, mk_coerce fun)  -- contination to discard, else we do it
1012   where                          -- again and again!
1013     cont_ty = contResultType cont
1014     co      = mkUnsafeCoercion fun_ty cont_ty
1015     mk_coerce expr | cont_ty `coreEqType` fun_ty = fun
1016                    | otherwise = mkCoerce co fun
1017
1018 rebuildCall env fun fun_ty info (ApplyTo _ (Type arg_ty) se cont)
1019   = do  { ty' <- simplType (se `setInScope` env) arg_ty
1020         ; rebuildCall env (fun `App` Type ty') (applyTy fun_ty ty') info cont }
1021
1022 rebuildCall env fun fun_ty (has_rules, str:strs) (ApplyTo _ arg arg_se cont)
1023   | str || isStrictType arg_ty          -- Strict argument
1024   = -- pprTrace "Strict Arg" (ppr arg $$ ppr (seIdSubst env) $$ ppr (seInScope env)) $
1025     simplExprF (arg_se `setFloats` env) arg
1026                (StrictArg fun fun_ty (has_rules, strs) cont)
1027                 -- Note [Shadowing]
1028
1029   | otherwise                           -- Lazy argument
1030         -- DO NOT float anything outside, hence simplExprC
1031         -- There is no benefit (unlike in a let-binding), and we'd
1032         -- have to be very careful about bogus strictness through 
1033         -- floating a demanded let.
1034   = do  { arg' <- simplExprC (arg_se `setInScope` env) arg
1035                              (mkLazyArgStop arg_ty has_rules)
1036         ; rebuildCall env (fun `App` arg') res_ty (has_rules, strs) cont }
1037   where
1038     (arg_ty, res_ty) = splitFunTy fun_ty
1039
1040 rebuildCall env fun fun_ty info cont
1041   = rebuild env fun cont
1042 \end{code}
1043
1044 Note [Shadowing]
1045 ~~~~~~~~~~~~~~~~
1046 This part of the simplifier may break the no-shadowing invariant
1047 Consider
1048         f (...(\a -> e)...) (case y of (a,b) -> e')
1049 where f is strict in its second arg
1050 If we simplify the innermost one first we get (...(\a -> e)...)
1051 Simplifying the second arg makes us float the case out, so we end up with
1052         case y of (a,b) -> f (...(\a -> e)...) e'
1053 So the output does not have the no-shadowing invariant.  However, there is
1054 no danger of getting name-capture, because when the first arg was simplified
1055 we used an in-scope set that at least mentioned all the variables free in its
1056 static environment, and that is enough.
1057
1058 We can't just do innermost first, or we'd end up with a dual problem:
1059         case x of (a,b) -> f e (...(\a -> e')...)
1060
1061 I spent hours trying to recover the no-shadowing invariant, but I just could
1062 not think of an elegant way to do it.  The simplifier is already knee-deep in
1063 continuations.  We have to keep the right in-scope set around; AND we have
1064 to get the effect that finding (error "foo") in a strict arg position will
1065 discard the entire application and replace it with (error "foo").  Getting
1066 all this at once is TOO HARD!
1067
1068 %************************************************************************
1069 %*                                                                      *
1070                 Rebuilding a cse expression
1071 %*                                                                      *
1072 %************************************************************************
1073
1074 Blob of helper functions for the "case-of-something-else" situation.
1075
1076 \begin{code}
1077 ---------------------------------------------------------
1078 --      Eliminate the case if possible
1079
1080 rebuildCase :: SimplEnv
1081             -> OutExpr          -- Scrutinee
1082             -> InId             -- Case binder
1083             -> [InAlt]          -- Alternatives (inceasing order)
1084             -> SimplCont
1085             -> SimplM (SimplEnv, OutExpr)
1086
1087 rebuildCase env scrut case_bndr alts cont
1088   | Just (con,args) <- exprIsConApp_maybe scrut 
1089         -- Works when the scrutinee is a variable with a known unfolding
1090         -- as well as when it's an explicit constructor application
1091   = knownCon env scrut (DataAlt con) args case_bndr alts cont
1092
1093   | Lit lit <- scrut    -- No need for same treatment as constructors
1094                         -- because literals are inlined more vigorously
1095   = knownCon env scrut (LitAlt lit) [] case_bndr alts cont
1096
1097   | otherwise
1098   = do  {       -- Prepare the continuation;
1099                 -- The new subst_env is in place
1100           (env, dup_cont, nodup_cont) <- prepareCaseCont env alts cont
1101
1102         -- Simplify the alternatives
1103         ; (case_bndr', alts') <- simplAlts env scrut case_bndr alts dup_cont
1104         ; let res_ty' = contResultType dup_cont
1105         ; case_expr <- mkCase scrut case_bndr' res_ty' alts'
1106
1107         -- Notice that rebuildDone returns the in-scope set from env, not alt_env
1108         -- The case binder *not* scope over the whole returned case-expression
1109         ; rebuild env case_expr nodup_cont }
1110 \end{code}
1111
1112 simplCaseBinder checks whether the scrutinee is a variable, v.  If so,
1113 try to eliminate uses of v in the RHSs in favour of case_bndr; that
1114 way, there's a chance that v will now only be used once, and hence
1115 inlined.
1116
1117 Note [no-case-of-case]
1118 ~~~~~~~~~~~~~~~~~~~~~~
1119 There is a time we *don't* want to do that, namely when
1120 -fno-case-of-case is on.  This happens in the first simplifier pass,
1121 and enhances full laziness.  Here's the bad case:
1122         f = \ y -> ...(case x of I# v -> ...(case x of ...) ... )
1123 If we eliminate the inner case, we trap it inside the I# v -> arm,
1124 which might prevent some full laziness happening.  I've seen this
1125 in action in spectral/cichelli/Prog.hs:
1126          [(m,n) | m <- [1..max], n <- [1..max]]
1127 Hence the check for NoCaseOfCase.
1128
1129 Note [Suppressing the case binder-swap]
1130 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1131 There is another situation when it might make sense to suppress the
1132 case-expression binde-swap. If we have
1133
1134     case x of w1 { DEFAULT -> case x of w2 { A -> e1; B -> e2 }
1135                    ...other cases .... }
1136
1137 We'll perform the binder-swap for the outer case, giving
1138
1139     case x of w1 { DEFAULT -> case w1 of w2 { A -> e1; B -> e2 } 
1140                    ...other cases .... }
1141
1142 But there is no point in doing it for the inner case, because w1 can't
1143 be inlined anyway.  Furthermore, doing the case-swapping involves
1144 zapping w2's occurrence info (see paragraphs that follow), and that
1145 forces us to bind w2 when doing case merging.  So we get
1146
1147     case x of w1 { A -> let w2 = w1 in e1
1148                    B -> let w2 = w1 in e2
1149                    ...other cases .... }
1150
1151 This is plain silly in the common case where w2 is dead.
1152
1153 Even so, I can't see a good way to implement this idea.  I tried
1154 not doing the binder-swap if the scrutinee was already evaluated
1155 but that failed big-time:
1156
1157         data T = MkT !Int
1158
1159         case v of w  { MkT x ->
1160         case x of x1 { I# y1 ->
1161         case x of x2 { I# y2 -> ...
1162
1163 Notice that because MkT is strict, x is marked "evaluated".  But to
1164 eliminate the last case, we must either make sure that x (as well as
1165 x1) has unfolding MkT y1.  THe straightforward thing to do is to do
1166 the binder-swap.  So this whole note is a no-op.
1167
1168 Note [zapOccInfo]
1169 ~~~~~~~~~~~~~~~~~
1170 If we replace the scrutinee, v, by tbe case binder, then we have to nuke
1171 any occurrence info (eg IAmDead) in the case binder, because the
1172 case-binder now effectively occurs whenever v does.  AND we have to do
1173 the same for the pattern-bound variables!  Example:
1174
1175         (case x of { (a,b) -> a }) (case x of { (p,q) -> q })
1176
1177 Here, b and p are dead.  But when we move the argment inside the first
1178 case RHS, and eliminate the second case, we get
1179
1180         case x of { (a,b) -> a b }
1181
1182 Urk! b is alive!  Reason: the scrutinee was a variable, and case elimination
1183 happened.  
1184
1185 Indeed, this can happen anytime the case binder isn't dead:
1186         case <any> of x { (a,b) -> 
1187         case x of { (p,q) -> p } }
1188 Here (a,b) both look dead, but come alive after the inner case is eliminated.
1189 The point is that we bring into the envt a binding
1190         let x = (a,b) 
1191 after the outer case, and that makes (a,b) alive.  At least we do unless
1192 the case binder is guaranteed dead.
1193
1194 Note [Case of cast]
1195 ~~~~~~~~~~~~~~~~~~~
1196 Consider        case (v `cast` co) of x { I# ->
1197                 ... (case (v `cast` co) of {...}) ...
1198 We'd like to eliminate the inner case.  We can get this neatly by 
1199 arranging that inside the outer case we add the unfolding
1200         v |-> x `cast` (sym co)
1201 to v.  Then we should inline v at the inner case, cancel the casts, and away we go
1202         
1203 \begin{code}
1204 simplCaseBinder :: SimplEnv -> OutExpr -> InId -> SimplM (SimplEnv, OutId)
1205 simplCaseBinder env scrut case_bndr
1206   | switchIsOn (getSwitchChecker env) NoCaseOfCase
1207         -- See Note [no-case-of-case]
1208   = do  { (env, case_bndr') <- simplBinder env case_bndr
1209         ; return (env, case_bndr') }
1210
1211 simplCaseBinder env (Var v) case_bndr
1212 -- Failed try [see Note 2 above]
1213 --     not (isEvaldUnfolding (idUnfolding v))
1214   = do  { (env, case_bndr') <- simplBinder env (zapOccInfo case_bndr)
1215         ; return (modifyInScope env v case_bndr', case_bndr') }
1216         -- We could extend the substitution instead, but it would be
1217         -- a hack because then the substitution wouldn't be idempotent
1218         -- any more (v is an OutId).  And this does just as well.
1219             
1220 simplCaseBinder env (Cast (Var v) co) case_bndr         -- Note [Case of cast]
1221   = do  { (env, case_bndr') <- simplBinder env (zapOccInfo case_bndr)
1222         ; let rhs = Cast (Var case_bndr') (mkSymCoercion co)
1223         ; return (addBinderUnfolding env v rhs, case_bndr') }
1224
1225 simplCaseBinder env other_scrut case_bndr 
1226   = do  { (env, case_bndr') <- simplBinder env case_bndr
1227         ; return (env, case_bndr') }
1228
1229 zapOccInfo :: InId -> InId      -- See Note [zapOccInfo]
1230 zapOccInfo b = b `setIdOccInfo` NoOccInfo
1231 \end{code}
1232
1233
1234 simplAlts does two things:
1235
1236 1.  Eliminate alternatives that cannot match, including the
1237     DEFAULT alternative.
1238
1239 2.  If the DEFAULT alternative can match only one possible constructor,
1240     then make that constructor explicit.
1241     e.g.
1242         case e of x { DEFAULT -> rhs }
1243      ===>
1244         case e of x { (a,b) -> rhs }
1245     where the type is a single constructor type.  This gives better code
1246     when rhs also scrutinises x or e.
1247
1248 Here "cannot match" includes knowledge from GADTs
1249
1250 It's a good idea do do this stuff before simplifying the alternatives, to
1251 avoid simplifying alternatives we know can't happen, and to come up with
1252 the list of constructors that are handled, to put into the IdInfo of the
1253 case binder, for use when simplifying the alternatives.
1254
1255 Eliminating the default alternative in (1) isn't so obvious, but it can
1256 happen:
1257
1258 data Colour = Red | Green | Blue
1259
1260 f x = case x of
1261         Red -> ..
1262         Green -> ..
1263         DEFAULT -> h x
1264
1265 h y = case y of
1266         Blue -> ..
1267         DEFAULT -> [ case y of ... ]
1268
1269 If we inline h into f, the default case of the inlined h can't happen.
1270 If we don't notice this, we may end up filtering out *all* the cases
1271 of the inner case y, which give us nowhere to go!
1272
1273
1274 \begin{code}
1275 simplAlts :: SimplEnv 
1276           -> OutExpr
1277           -> InId                       -- Case binder
1278           -> [InAlt] -> SimplCont
1279           -> SimplM (OutId, [OutAlt])   -- Includes the continuation
1280 -- Like simplExpr, this just returns the simplified alternatives;
1281 -- it not return an environment
1282
1283 simplAlts env scrut case_bndr alts cont'
1284   = -- pprTrace "simplAlts" (ppr alts $$ ppr (seIdSubst env)) $
1285     do  { let alt_env = zapFloats env
1286         ; (alt_env, case_bndr') <- simplCaseBinder alt_env scrut case_bndr
1287
1288         ; default_alts <- prepareDefault alt_env case_bndr' imposs_deflt_cons cont' maybe_deflt
1289
1290         ; let inst_tys = tyConAppArgs (idType case_bndr')
1291               trimmed_alts = filter (is_possible inst_tys) alts_wo_default
1292               in_alts      = mergeAlts default_alts trimmed_alts
1293                 -- We need the mergeAlts in case the new default_alt 
1294                 -- has turned into a constructor alternative.
1295
1296         ; alts' <- mapM (simplAlt alt_env imposs_cons case_bndr' cont') in_alts
1297         ; return (case_bndr', alts') }
1298   where
1299     (alts_wo_default, maybe_deflt) = findDefault alts
1300     imposs_cons = case scrut of
1301                     Var v -> otherCons (idUnfolding v)
1302                     other -> []
1303
1304         -- "imposs_deflt_cons" are handled either by the context, 
1305         -- OR by a branch in this case expression. (Don't include DEFAULT!!)
1306     imposs_deflt_cons = nub (imposs_cons ++ [con | (con,_,_) <- alts_wo_default])
1307
1308     is_possible :: [Type] -> CoreAlt -> Bool
1309     is_possible tys (con, _, _) | con `elem` imposs_cons = False
1310     is_possible tys (DataAlt con, _, _) = dataConCanMatch tys con
1311     is_possible tys alt                 = True
1312
1313 ------------------------------------
1314 prepareDefault :: SimplEnv
1315                -> OutId         -- Case binder; need just for its type. Note that as an
1316                                 --   OutId, it has maximum information; this is important.
1317                                 --   Test simpl013 is an example
1318              -> [AltCon]        -- These cons can't happen when matching the default
1319              -> SimplCont
1320              -> Maybe InExpr
1321              -> SimplM [InAlt]  -- One branch or none; still unsimplified
1322                                 -- We use a list because it's what mergeAlts expects
1323
1324 prepareDefault env case_bndr' imposs_cons cont Nothing
1325   = return []   -- No default branch
1326
1327 prepareDefault env case_bndr' imposs_cons cont (Just rhs)
1328   |     -- This branch handles the case where we are 
1329         -- scrutinisng an algebraic data type
1330     Just (tycon, inst_tys) <- splitTyConApp_maybe (idType case_bndr'),
1331     isAlgTyCon tycon,           -- It's a data type, tuple, or unboxed tuples.  
1332     not (isNewTyCon tycon),     -- We can have a newtype, if we are just doing an eval:
1333                                 --      case x of { DEFAULT -> e }
1334                                 -- and we don't want to fill in a default for them!
1335     Just all_cons <- tyConDataCons_maybe tycon,
1336     not (null all_cons),        -- This is a tricky corner case.  If the data type has no constructors,
1337                                 -- which GHC allows, then the case expression will have at most a default
1338                                 -- alternative.  We don't want to eliminate that alternative, because the
1339                                 -- invariant is that there's always one alternative.  It's more convenient
1340                                 -- to leave     
1341                                 --      case x of { DEFAULT -> e }     
1342                                 -- as it is, rather than transform it to
1343                                 --      error "case cant match"
1344                                 -- which would be quite legitmate.  But it's a really obscure corner, and
1345                                 -- not worth wasting code on.
1346
1347     let imposs_data_cons = [con | DataAlt con <- imposs_cons]   -- We now know it's a data type 
1348         is_possible con  = not (con `elem` imposs_data_cons)
1349                            && dataConCanMatch inst_tys con
1350   = case filter is_possible all_cons of
1351         []    -> return []      -- Eliminate the default alternative
1352                                 -- altogether if it can't match
1353
1354         [con] ->        -- It matches exactly one constructor, so fill it in
1355                  do { tick (FillInCaseDefault case_bndr')
1356                     ; us <- getUniquesSmpl
1357                     ; let (ex_tvs, co_tvs, arg_ids) =
1358                               dataConRepInstPat us con inst_tys
1359                     ; return [(DataAlt con, ex_tvs ++ co_tvs ++ arg_ids, rhs)] }
1360
1361         two_or_more -> return [(DEFAULT, [], rhs)]
1362
1363   | otherwise 
1364   = return [(DEFAULT, [], rhs)]
1365
1366 ------------------------------------
1367 simplAlt :: SimplEnv
1368          -> [AltCon]    -- These constructors can't be present when
1369                         -- matching this alternative
1370          -> OutId       -- The case binder
1371          -> SimplCont
1372          -> InAlt
1373          -> SimplM (OutAlt)
1374
1375 -- Simplify an alternative, returning the type refinement for the 
1376 -- alternative, if the alternative does any refinement at all
1377
1378 simplAlt env handled_cons case_bndr' cont' (DEFAULT, bndrs, rhs)
1379   = ASSERT( null bndrs )
1380     do  { let env' = addBinderOtherCon env case_bndr' handled_cons
1381                 -- Record the constructors that the case-binder *can't* be.
1382         ; rhs' <- simplExprC env' rhs cont'
1383         ; return (DEFAULT, [], rhs') }
1384
1385 simplAlt env handled_cons case_bndr' cont' (LitAlt lit, bndrs, rhs)
1386   = ASSERT( null bndrs )
1387     do  { let env' = addBinderUnfolding env case_bndr' (Lit lit)
1388         ; rhs' <- simplExprC env' rhs cont'
1389         ; return (LitAlt lit, [], rhs') }
1390
1391 simplAlt env handled_cons case_bndr' cont' (DataAlt con, vs, rhs)
1392   = do  {       -- Deal with the pattern-bound variables
1393                 -- Mark the ones that are in ! positions in the data constructor
1394                 -- as certainly-evaluated.
1395                 -- NB: it happens that simplBinders does *not* erase the OtherCon
1396                 --     form of unfolding, so it's ok to add this info before 
1397                 --     doing simplBinders
1398           (env, vs') <- simplBinders env (add_evals con vs)
1399
1400                 -- Bind the case-binder to (con args)
1401         ; let inst_tys' = tyConAppArgs (idType case_bndr')
1402               con_args  = map Type inst_tys' ++ varsToCoreExprs vs' 
1403               env'      = addBinderUnfolding env case_bndr' (mkConApp con con_args)
1404
1405         ; rhs' <- simplExprC env' rhs cont'
1406         ; return (DataAlt con, vs', rhs') }
1407   where
1408         -- add_evals records the evaluated-ness of the bound variables of
1409         -- a case pattern.  This is *important*.  Consider
1410         --      data T = T !Int !Int
1411         --
1412         --      case x of { T a b -> T (a+1) b }
1413         --
1414         -- We really must record that b is already evaluated so that we don't
1415         -- go and re-evaluate it when constructing the result.
1416         -- See Note [Data-con worker strictness] in MkId.lhs
1417     add_evals dc vs = cat_evals dc vs (dataConRepStrictness dc)
1418
1419     cat_evals dc vs strs
1420         = go vs strs
1421         where
1422           go [] [] = []
1423           go (v:vs) strs | isTyVar v = v : go vs strs
1424           go (v:vs) (str:strs)
1425             | isMarkedStrict str = evald_v  : go vs strs
1426             | otherwise          = zapped_v : go vs strs
1427             where
1428               zapped_v = zap_occ_info v
1429               evald_v  = zapped_v `setIdUnfolding` evaldUnfolding
1430           go _ _ = pprPanic "cat_evals" (ppr dc $$ ppr vs $$ ppr strs)
1431
1432         -- If the case binder is alive, then we add the unfolding
1433         --      case_bndr = C vs
1434         -- to the envt; so vs are now very much alive
1435         -- Note [Aug06] I can't see why this actually matters
1436     zap_occ_info | isDeadBinder case_bndr' = \id -> id
1437                  | otherwise               = zapOccInfo
1438
1439 addBinderUnfolding :: SimplEnv -> Id -> CoreExpr -> SimplEnv
1440 addBinderUnfolding env bndr rhs
1441   = modifyInScope env bndr (bndr `setIdUnfolding` mkUnfolding False rhs)
1442
1443 addBinderOtherCon :: SimplEnv -> Id -> [AltCon] -> SimplEnv
1444 addBinderOtherCon env bndr cons
1445   = modifyInScope env bndr (bndr `setIdUnfolding` mkOtherCon cons)
1446 \end{code}
1447
1448
1449 %************************************************************************
1450 %*                                                                      *
1451 \subsection{Known constructor}
1452 %*                                                                      *
1453 %************************************************************************
1454
1455 We are a bit careful with occurrence info.  Here's an example
1456
1457         (\x* -> case x of (a*, b) -> f a) (h v, e)
1458
1459 where the * means "occurs once".  This effectively becomes
1460         case (h v, e) of (a*, b) -> f a)
1461 and then
1462         let a* = h v; b = e in f a
1463 and then
1464         f (h v)
1465
1466 All this should happen in one sweep.
1467
1468 \begin{code}
1469 knownCon :: SimplEnv -> OutExpr -> AltCon -> [OutExpr]
1470          -> InId -> [InAlt] -> SimplCont
1471          -> SimplM (SimplEnv, OutExpr)
1472
1473 knownCon env scrut con args bndr alts cont
1474   = do  { tick (KnownBranch bndr)
1475         ; knownAlt env scrut args bndr (findAlt con alts) cont }
1476
1477 knownAlt env scrut args bndr (DEFAULT, bs, rhs) cont
1478   = ASSERT( null bs )
1479     do  { env <- simplNonRecX env bndr scrut
1480                 -- This might give rise to a binding with non-atomic args
1481                 -- like x = Node (f x) (g x)
1482                 -- but simplNonRecX will atomic-ify it
1483         ; simplExprF env rhs cont }
1484
1485 knownAlt env scrut args bndr (LitAlt lit, bs, rhs) cont
1486   = ASSERT( null bs )
1487     do  { env <- simplNonRecX env bndr scrut
1488         ; simplExprF env rhs cont }
1489
1490 knownAlt env scrut args bndr (DataAlt dc, bs, rhs) cont
1491   = do  { let dead_bndr  = isDeadBinder bndr
1492               n_drop_tys = tyConArity (dataConTyCon dc)
1493         ; env <- bind_args env dead_bndr bs (drop n_drop_tys args)
1494         ; let
1495                 -- It's useful to bind bndr to scrut, rather than to a fresh
1496                 -- binding      x = Con arg1 .. argn
1497                 -- because very often the scrut is a variable, so we avoid
1498                 -- creating, and then subsequently eliminating, a let-binding
1499                 -- BUT, if scrut is a not a variable, we must be careful
1500                 -- about duplicating the arg redexes; in that case, make
1501                 -- a new con-app from the args
1502                 bndr_rhs  = case scrut of
1503                                 Var v -> scrut
1504                                 other -> con_app
1505                 con_app = mkConApp dc (take n_drop_tys args ++ con_args)
1506                 con_args = [substExpr env (varToCoreExpr b) | b <- bs]
1507                                 -- args are aready OutExprs, but bs are InIds
1508
1509         ; env <- simplNonRecX env bndr bndr_rhs
1510         ; -- pprTrace "knownCon2" (ppr bs $$ ppr rhs $$ ppr (seIdSubst env)) $
1511           simplExprF env rhs cont }
1512
1513 -- Ugh!
1514 bind_args env dead_bndr [] _  = return env
1515
1516 bind_args env dead_bndr (b:bs) (Type ty : args)
1517   = ASSERT( isTyVar b )
1518     bind_args (extendTvSubst env b ty) dead_bndr bs args
1519     
1520 bind_args env dead_bndr (b:bs) (arg : args)
1521   = ASSERT( isId b )
1522     do  { let b' = if dead_bndr then b else zapOccInfo b
1523                 -- Note that the binder might be "dead", because it doesn't occur 
1524                 -- in the RHS; and simplNonRecX may therefore discard it via postInlineUnconditionally
1525                 -- Nevertheless we must keep it if the case-binder is alive, because it may
1526                 -- be used in the con_app.  See Note [zapOccInfo]
1527         ; env <- simplNonRecX env b' arg
1528         ; bind_args env dead_bndr bs args }
1529
1530 bind_args _ _ _ _ = panic "bind_args"
1531 \end{code}
1532
1533
1534 %************************************************************************
1535 %*                                                                      *
1536 \subsection{Duplicating continuations}
1537 %*                                                                      *
1538 %************************************************************************
1539
1540 \begin{code}
1541 prepareCaseCont :: SimplEnv
1542                 -> [InAlt] -> SimplCont
1543                 -> SimplM (SimplEnv, SimplCont,SimplCont)
1544                         -- Return a duplicatable continuation, a non-duplicable part 
1545                         -- plus some extra bindings (that scope over the entire
1546                         -- continunation)
1547
1548         -- No need to make it duplicatable if there's only one alternative
1549 prepareCaseCont env [alt] cont = return (env, cont, mkBoringStop (contResultType cont))
1550 prepareCaseCont env alts  cont = mkDupableCont env cont
1551 \end{code}
1552
1553 \begin{code}
1554 mkDupableCont :: SimplEnv -> SimplCont 
1555               -> SimplM (SimplEnv, SimplCont, SimplCont)
1556
1557 mkDupableCont env cont
1558   | contIsDupable cont
1559   = returnSmpl (env, cont, mkBoringStop (contResultType cont))
1560
1561 mkDupableCont env (Stop {}) = panic "mkDupableCont"     -- Handled by previous eqn
1562
1563 mkDupableCont env (CoerceIt ty cont)
1564   = do  { (env, dup, nodup) <- mkDupableCont env cont
1565         ; return (env, CoerceIt ty dup, nodup) }
1566
1567 mkDupableCont env cont@(StrictBind bndr _ _ se _)
1568   =  return (env, mkBoringStop (substTy se (idType bndr)), cont)
1569         -- See Note [Duplicating strict continuations]
1570
1571 mkDupableCont env cont@(StrictArg _ fun_ty _ _)
1572   =  return (env, mkBoringStop (funArgTy fun_ty), cont)
1573         -- See Note [Duplicating strict continuations]
1574
1575 mkDupableCont env (ApplyTo _ arg se cont)
1576   =     -- e.g.         [...hole...] (...arg...)
1577         --      ==>
1578         --              let a = ...arg... 
1579         --              in [...hole...] a
1580     do  { (env, dup_cont, nodup_cont) <- mkDupableCont env cont
1581         ; arg <- simplExpr (se `setInScope` env) arg
1582         ; (env, arg) <- makeTrivial env arg
1583         ; let app_cont = ApplyTo OkToDup arg (zapSubstEnv env) dup_cont
1584         ; return (env, app_cont, nodup_cont) }
1585
1586 mkDupableCont env cont@(Select _ case_bndr [(_,bs,rhs)] se case_cont)
1587 --  See Note [Single-alternative case]
1588 --  | not (exprIsDupable rhs && contIsDupable case_cont)
1589 --  | not (isDeadBinder case_bndr)
1590   | all isDeadBinder bs
1591   = return (env, mkBoringStop scrut_ty, cont)
1592   where
1593     scrut_ty = substTy se (idType case_bndr)
1594
1595 mkDupableCont env (Select _ case_bndr alts se cont)
1596   =     -- e.g.         (case [...hole...] of { pi -> ei })
1597         --      ===>
1598         --              let ji = \xij -> ei 
1599         --              in case [...hole...] of { pi -> ji xij }
1600     do  { tick (CaseOfCase case_bndr)
1601         ; (env, dup_cont, nodup_cont) <- mkDupableCont env cont
1602                 -- NB: call mkDupableCont here, *not* prepareCaseCont
1603                 -- We must make a duplicable continuation, whereas prepareCaseCont
1604                 -- doesn't when there is a single case branch
1605
1606         ; let alt_env = se `setInScope` env 
1607         ; (alt_env, case_bndr') <- simplBinder alt_env case_bndr
1608         ; alts' <- mapM (simplAlt alt_env [] case_bndr' dup_cont) alts
1609         -- Safe to say that there are no handled-cons for the DEFAULT case
1610                 -- NB: simplBinder does not zap deadness occ-info, so
1611                 -- a dead case_bndr' will still advertise its deadness
1612                 -- This is really important because in
1613                 --      case e of b { (# a,b #) -> ... }
1614                 -- b is always dead, and indeed we are not allowed to bind b to (# a,b #),
1615                 -- which might happen if e was an explicit unboxed pair and b wasn't marked dead.
1616                 -- In the new alts we build, we have the new case binder, so it must retain
1617                 -- its deadness.
1618         -- NB: we don't use alt_env further; it has the substEnv for
1619         --     the alternatives, and we don't want that
1620
1621         ; (env, alts') <- mkDupableAlts env case_bndr' alts'
1622         ; return (env,  -- Note [Duplicated env]
1623                   Select OkToDup case_bndr' alts' (zapSubstEnv env)
1624                          (mkBoringStop (contResultType dup_cont)),
1625                   nodup_cont) }
1626
1627
1628 mkDupableAlts :: SimplEnv -> OutId -> [InAlt]
1629               -> SimplM (SimplEnv, [InAlt])
1630 -- Absorbs the continuation into the new alternatives
1631
1632 mkDupableAlts env case_bndr' alts
1633   = go env alts
1634   where
1635     go env [] = return (env, [])
1636     go env (alt:alts)
1637         = do { (env, alt') <- mkDupableAlt env case_bndr' alt
1638      ; (env, alts') <- go env alts
1639              ; return (env, alt' : alts' ) }
1640                                         
1641 mkDupableAlt env case_bndr' (con, bndrs', rhs')
1642   | exprIsDupable rhs'  -- Note [Small alternative rhs]
1643   = return (env, (con, bndrs', rhs'))
1644   | otherwise
1645   = do  { let rhs_ty'     = exprType rhs'
1646               used_bndrs' = filter abstract_over (case_bndr' : bndrs')
1647               abstract_over bndr 
1648                   | isTyVar bndr = True -- Abstract over all type variables just in case
1649                   | otherwise    = not (isDeadBinder bndr)
1650                         -- The deadness info on the new Ids is preserved by simplBinders
1651
1652         ; (final_bndrs', final_args)    -- Note [Join point abstraction]
1653                 <- if (any isId used_bndrs')
1654                    then return (used_bndrs', varsToCoreExprs used_bndrs')
1655                     else do { rw_id <- newId FSLIT("w") realWorldStatePrimTy
1656                             ; return ([rw_id], [Var realWorldPrimId]) }
1657              
1658         ; join_bndr <- newId FSLIT("$j") (mkPiTypes final_bndrs' rhs_ty')
1659                 -- Note [Funky mkPiTypes]
1660         
1661         ; let   -- We make the lambdas into one-shot-lambdas.  The
1662                 -- join point is sure to be applied at most once, and doing so
1663                 -- prevents the body of the join point being floated out by
1664                 -- the full laziness pass
1665                 really_final_bndrs     = map one_shot final_bndrs'
1666                 one_shot v | isId v    = setOneShotLambda v
1667                            | otherwise = v
1668                 join_rhs  = mkLams really_final_bndrs rhs'
1669                 join_call = mkApps (Var join_bndr) final_args
1670
1671         ; return (addNonRec env join_bndr join_rhs, (con, bndrs', join_call)) }
1672                 -- See Note [Duplicated env]
1673 \end{code}
1674
1675 Note [Duplicated env]
1676 ~~~~~~~~~~~~~~~~~~~~~
1677 Some of the alternatives are simplified, but have not been turned into a join point
1678 So they *must* have an zapped subst-env.  So we can't use completeNonRecX to
1679 bind the join point, because it might to do PostInlineUnconditionally, and
1680 we'd lose that when zapping the subst-env.  We could have a per-alt subst-env,
1681 but zapping it (as we do in mkDupableCont, the Select case) is safe, and
1682 at worst delays the join-point inlining.
1683
1684 Note [Small alterantive rhs]
1685 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1686 It is worth checking for a small RHS because otherwise we
1687 get extra let bindings that may cause an extra iteration of the simplifier to
1688 inline back in place.  Quite often the rhs is just a variable or constructor.
1689 The Ord instance of Maybe in PrelMaybe.lhs, for example, took several extra
1690 iterations because the version with the let bindings looked big, and so wasn't
1691 inlined, but after the join points had been inlined it looked smaller, and so
1692 was inlined.
1693
1694 NB: we have to check the size of rhs', not rhs. 
1695 Duplicating a small InAlt might invalidate occurrence information
1696 However, if it *is* dupable, we return the *un* simplified alternative,
1697 because otherwise we'd need to pair it up with an empty subst-env....
1698 but we only have one env shared between all the alts.
1699 (Remember we must zap the subst-env before re-simplifying something).
1700 Rather than do this we simply agree to re-simplify the original (small) thing later.
1701
1702 Note [Funky mkPiTypes]
1703 ~~~~~~~~~~~~~~~~~~~~~~
1704 Notice the funky mkPiTypes.  If the contructor has existentials
1705 it's possible that the join point will be abstracted over
1706 type varaibles as well as term variables.
1707  Example:  Suppose we have
1708         data T = forall t.  C [t]
1709  Then faced with
1710         case (case e of ...) of
1711             C t xs::[t] -> rhs
1712  We get the join point
1713         let j :: forall t. [t] -> ...
1714             j = /\t \xs::[t] -> rhs
1715         in
1716         case (case e of ...) of
1717             C t xs::[t] -> j t xs
1718
1719 Note [Join point abstaction]
1720 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1721 If we try to lift a primitive-typed something out
1722 for let-binding-purposes, we will *caseify* it (!),
1723 with potentially-disastrous strictness results.  So
1724 instead we turn it into a function: \v -> e
1725 where v::State# RealWorld#.  The value passed to this function
1726 is realworld#, which generates (almost) no code.
1727
1728 There's a slight infelicity here: we pass the overall 
1729 case_bndr to all the join points if it's used in *any* RHS,
1730 because we don't know its usage in each RHS separately
1731
1732 We used to say "&& isUnLiftedType rhs_ty'" here, but now
1733 we make the join point into a function whenever used_bndrs'
1734 is empty.  This makes the join-point more CPR friendly. 
1735 Consider:       let j = if .. then I# 3 else I# 4
1736                 in case .. of { A -> j; B -> j; C -> ... }
1737
1738 Now CPR doesn't w/w j because it's a thunk, so
1739 that means that the enclosing function can't w/w either,
1740 which is a lose.  Here's the example that happened in practice:
1741         kgmod :: Int -> Int -> Int
1742         kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
1743                     then 78
1744                     else 5
1745
1746 I have seen a case alternative like this:
1747         True -> \v -> ...
1748 It's a bit silly to add the realWorld dummy arg in this case, making
1749         $j = \s v -> ...
1750            True -> $j s
1751 (the \v alone is enough to make CPR happy) but I think it's rare
1752
1753 Note [Duplicating strict continuations]
1754 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1755 Do *not* duplicate StrictBind and StritArg continuations.  We gain
1756 nothing by propagating them into the expressions, and we do lose a
1757 lot.  Here's an example:
1758         && (case x of { T -> F; F -> T }) E
1759 Now, && is strict so we end up simplifying the case with
1760 an ArgOf continuation.  If we let-bind it, we get
1761
1762         let $j = \v -> && v E
1763         in simplExpr (case x of { T -> F; F -> T })
1764                      (ArgOf (\r -> $j r)
1765 And after simplifying more we get
1766
1767         let $j = \v -> && v E
1768         in case x of { T -> $j F; F -> $j T }
1769 Which is a Very Bad Thing
1770
1771 The desire not to duplicate is the entire reason that
1772 mkDupableCont returns a pair of continuations.
1773
1774 The original plan had:
1775 e.g.    (...strict-fn...) [...hole...]
1776         ==>
1777                 let $j = \a -> ...strict-fn...
1778                 in $j [...hole...]
1779
1780 Note [Single-alternative cases]
1781 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1782 This case is just like the ArgOf case.  Here's an example:
1783         data T a = MkT !a
1784         ...(MkT (abs x))...
1785 Then we get
1786         case (case x of I# x' -> 
1787               case x' <# 0# of
1788                 True  -> I# (negate# x')
1789                 False -> I# x') of y {
1790           DEFAULT -> MkT y
1791 Because the (case x) has only one alternative, we'll transform to
1792         case x of I# x' ->
1793         case (case x' <# 0# of
1794                 True  -> I# (negate# x')
1795                 False -> I# x') of y {
1796           DEFAULT -> MkT y
1797 But now we do *NOT* want to make a join point etc, giving 
1798         case x of I# x' ->
1799         let $j = \y -> MkT y
1800         in case x' <# 0# of
1801                 True  -> $j (I# (negate# x'))
1802                 False -> $j (I# x')
1803 In this case the $j will inline again, but suppose there was a big
1804 strict computation enclosing the orginal call to MkT.  Then, it won't
1805 "see" the MkT any more, because it's big and won't get duplicated.
1806 And, what is worse, nothing was gained by the case-of-case transform.
1807
1808 When should use this case of mkDupableCont?  
1809 However, matching on *any* single-alternative case is a *disaster*;
1810   e.g.  case (case ....) of (a,b) -> (# a,b #)
1811   We must push the outer case into the inner one!
1812 Other choices:
1813
1814    * Match [(DEFAULT,_,_)], but in the common case of Int, 
1815      the alternative-filling-in code turned the outer case into
1816                 case (...) of y { I# _ -> MkT y }
1817
1818    * Match on single alternative plus (not (isDeadBinder case_bndr))
1819      Rationale: pushing the case inwards won't eliminate the construction.
1820      But there's a risk of
1821                 case (...) of y { (a,b) -> let z=(a,b) in ... }
1822      Now y looks dead, but it'll come alive again.  Still, this
1823      seems like the best option at the moment.
1824
1825    * Match on single alternative plus (all (isDeadBinder bndrs))
1826      Rationale: this is essentially  seq.
1827
1828    * Match when the rhs is *not* duplicable, and hence would lead to a
1829      join point.  This catches the disaster-case above.  We can test
1830      the *un-simplified* rhs, which is fine.  It might get bigger or
1831      smaller after simplification; if it gets smaller, this case might
1832      fire next time round.  NB also that we must test contIsDupable
1833      case_cont *btoo, because case_cont might be big!
1834
1835      HOWEVER: I found that this version doesn't work well, because
1836      we can get         let x = case (...) of { small } in ...case x...
1837      When x is inlined into its full context, we find that it was a bad
1838      idea to have pushed the outer case inside the (...) case.
1839