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