Avoid hanging on to old unfoldings; fixes #4367 (compiler space regression)
[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, substTyVar )
14 import SimplEnv
15 import SimplUtils
16 import FamInstEnv       ( FamInstEnv )
17 import Id
18 import MkId             ( seqId, realWorldPrimId )
19 import MkCore           ( mkImpossibleExpr )
20 import Var
21 import IdInfo
22 import Name             ( mkSystemVarName, isExternalName )
23 import Coercion
24 import OptCoercion      ( optCoercion )
25 import FamInstEnv       ( topNormaliseType )
26 import DataCon          ( DataCon, dataConWorkId, dataConRepStrictness )
27 import CoreMonad        ( SimplifierSwitch(..), Tick(..) )
28 import CoreSyn
29 import Demand           ( isStrictDmd, splitStrictSig )
30 import PprCore          ( pprParendExpr, pprCoreExpr )
31 import CoreUnfold       ( mkUnfolding, mkCoreUnfolding
32                         , mkInlineUnfolding, mkSimpleUnfolding
33                         , exprIsConApp_maybe, callSiteInline, CallCtxt(..) )
34 import CoreUtils
35 import qualified CoreSubst
36 import CoreArity        ( exprArity )
37 import Rules            ( lookupRule, getRules )
38 import BasicTypes       ( isMarkedStrict, Arity )
39 import CostCentre       ( currentCCS, pushCCisNop )
40 import TysPrim          ( realWorldStatePrimTy )
41 import BasicTypes       ( TopLevelFlag(..), isTopLevel, RecFlag(..) )
42 import MonadUtils       ( foldlM, mapAccumLM )
43 import Maybes           ( orElse )
44 import Data.List        ( mapAccumL )
45 import Outputable
46 import FastString
47 \end{code}
48
49
50 The guts of the simplifier is in this module, but the driver loop for
51 the simplifier is in SimplCore.lhs.
52
53
54 -----------------------------------------
55         *** IMPORTANT NOTE ***
56 -----------------------------------------
57 The simplifier used to guarantee that the output had no shadowing, but
58 it does not do so any more.   (Actually, it never did!)  The reason is
59 documented with simplifyArgs.
60
61
62 -----------------------------------------
63         *** IMPORTANT NOTE ***
64 -----------------------------------------
65 Many parts of the simplifier return a bunch of "floats" as well as an
66 expression. This is wrapped as a datatype SimplUtils.FloatsWith.
67
68 All "floats" are let-binds, not case-binds, but some non-rec lets may
69 be unlifted (with RHS ok-for-speculation).
70
71
72
73 -----------------------------------------
74         ORGANISATION OF FUNCTIONS
75 -----------------------------------------
76 simplTopBinds
77   - simplify all top-level binders
78   - for NonRec, call simplRecOrTopPair
79   - for Rec,    call simplRecBind
80
81
82         ------------------------------
83 simplExpr (applied lambda)      ==> simplNonRecBind
84 simplExpr (Let (NonRec ...) ..) ==> simplNonRecBind
85 simplExpr (Let (Rec ...)    ..) ==> simplify binders; simplRecBind
86
87         ------------------------------
88 simplRecBind    [binders already simplfied]
89   - use simplRecOrTopPair on each pair in turn
90
91 simplRecOrTopPair [binder already simplified]
92   Used for: recursive bindings (top level and nested)
93             top-level non-recursive bindings
94   Returns:
95   - check for PreInlineUnconditionally
96   - simplLazyBind
97
98 simplNonRecBind
99   Used for: non-top-level non-recursive bindings
100             beta reductions (which amount to the same thing)
101   Because it can deal with strict arts, it takes a
102         "thing-inside" and returns an expression
103
104   - check for PreInlineUnconditionally
105   - simplify binder, including its IdInfo
106   - if strict binding
107         simplStrictArg
108         mkAtomicArgs
109         completeNonRecX
110     else
111         simplLazyBind
112         addFloats
113
114 simplNonRecX:   [given a *simplified* RHS, but an *unsimplified* binder]
115   Used for: binding case-binder and constr args in a known-constructor case
116   - check for PreInLineUnconditionally
117   - simplify binder
118   - completeNonRecX
119
120         ------------------------------
121 simplLazyBind:  [binder already simplified, RHS not]
122   Used for: recursive bindings (top level and nested)
123             top-level non-recursive bindings
124             non-top-level, but *lazy* non-recursive bindings
125         [must not be strict or unboxed]
126   Returns floats + an augmented environment, not an expression
127   - substituteIdInfo and add result to in-scope
128         [so that rules are available in rec rhs]
129   - simplify rhs
130   - mkAtomicArgs
131   - float if exposes constructor or PAP
132   - completeBind
133
134
135 completeNonRecX:        [binder and rhs both simplified]
136   - if the the thing needs case binding (unlifted and not ok-for-spec)
137         build a Case
138    else
139         completeBind
140         addFloats
141
142 completeBind:   [given a simplified RHS]
143         [used for both rec and non-rec bindings, top level and not]
144   - try PostInlineUnconditionally
145   - add unfolding [this is the only place we add an unfolding]
146   - add arity
147
148
149
150 Right hand sides and arguments
151 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
152 In many ways we want to treat
153         (a) the right hand side of a let(rec), and
154         (b) a function argument
155 in the same way.  But not always!  In particular, we would
156 like to leave these arguments exactly as they are, so they
157 will match a RULE more easily.
158
159         f (g x, h x)
160         g (+ x)
161
162 It's harder to make the rule match if we ANF-ise the constructor,
163 or eta-expand the PAP:
164
165         f (let { a = g x; b = h x } in (a,b))
166         g (\y. + x y)
167
168 On the other hand if we see the let-defns
169
170         p = (g x, h x)
171         q = + x
172
173 then we *do* want to ANF-ise and eta-expand, so that p and q
174 can be safely inlined.
175
176 Even floating lets out is a bit dubious.  For let RHS's we float lets
177 out if that exposes a value, so that the value can be inlined more vigorously.
178 For example
179
180         r = let x = e in (x,x)
181
182 Here, if we float the let out we'll expose a nice constructor. We did experiments
183 that showed this to be a generally good thing.  But it was a bad thing to float
184 lets out unconditionally, because that meant they got allocated more often.
185
186 For function arguments, there's less reason to expose a constructor (it won't
187 get inlined).  Just possibly it might make a rule match, but I'm pretty skeptical.
188 So for the moment we don't float lets out of function arguments either.
189
190
191 Eta expansion
192 ~~~~~~~~~~~~~~
193 For eta expansion, we want to catch things like
194
195         case e of (a,b) -> \x -> case a of (p,q) -> \y -> r
196
197 If the \x was on the RHS of a let, we'd eta expand to bring the two
198 lambdas together.  And in general that's a good thing to do.  Perhaps
199 we should eta expand wherever we find a (value) lambda?  Then the eta
200 expansion at a let RHS can concentrate solely on the PAP case.
201
202
203 %************************************************************************
204 %*                                                                      *
205 \subsection{Bindings}
206 %*                                                                      *
207 %************************************************************************
208
209 \begin{code}
210 simplTopBinds :: SimplEnv -> [InBind] -> SimplM SimplEnv
211
212 simplTopBinds env0 binds0
213   = do  {       -- Put all the top-level binders into scope at the start
214                 -- so that if a transformation rule has unexpectedly brought
215                 -- anything into scope, then we don't get a complaint about that.
216                 -- It's rather as if the top-level binders were imported.
217         ; env1 <- simplRecBndrs env0 (bindersOfBinds binds0)
218         ; dflags <- getDOptsSmpl
219         ; let dump_flag = dopt Opt_D_verbose_core2core dflags
220         ; env2 <- simpl_binds dump_flag env1 binds0
221         ; freeTick SimplifierDone
222         ; return env2 }
223   where
224         -- We need to track the zapped top-level binders, because
225         -- they should have their fragile IdInfo zapped (notably occurrence info)
226         -- That's why we run down binds and bndrs' simultaneously.
227         --
228         -- The dump-flag emits a trace for each top-level binding, which
229         -- helps to locate the tracing for inlining and rule firing
230     simpl_binds :: Bool -> SimplEnv -> [InBind] -> SimplM SimplEnv
231     simpl_binds _    env []           = return env
232     simpl_binds dump env (bind:binds) = do { env' <- trace_bind dump bind $
233                                                      simpl_bind env bind
234                                            ; simpl_binds dump env' binds }
235
236     trace_bind True  bind = pprTrace "SimplBind" (ppr (bindersOf bind))
237     trace_bind False _    = \x -> x
238
239     simpl_bind env (Rec pairs)  = simplRecBind      env  TopLevel pairs
240     simpl_bind env (NonRec b r) = simplRecOrTopPair env' TopLevel b b' r
241         where
242           (env', b') = addBndrRules env b (lookupRecBndr env b)
243 \end{code}
244
245
246 %************************************************************************
247 %*                                                                      *
248 \subsection{Lazy bindings}
249 %*                                                                      *
250 %************************************************************************
251
252 simplRecBind is used for
253         * recursive bindings only
254
255 \begin{code}
256 simplRecBind :: SimplEnv -> TopLevelFlag
257              -> [(InId, InExpr)]
258              -> SimplM SimplEnv
259 simplRecBind env0 top_lvl pairs0
260   = do  { let (env_with_info, triples) = mapAccumL add_rules env0 pairs0
261         ; env1 <- go (zapFloats env_with_info) triples
262         ; return (env0 `addRecFloats` env1) }
263         -- addFloats adds the floats from env1,
264         -- _and_ updates env0 with the in-scope set from env1
265   where
266     add_rules :: SimplEnv -> (InBndr,InExpr) -> (SimplEnv, (InBndr, OutBndr, InExpr))
267         -- Add the (substituted) rules to the binder
268     add_rules env (bndr, rhs) = (env', (bndr, bndr', rhs))
269         where
270           (env', bndr') = addBndrRules env bndr (lookupRecBndr env bndr)
271
272     go env [] = return env
273
274     go env ((old_bndr, new_bndr, rhs) : pairs)
275         = do { env' <- simplRecOrTopPair env top_lvl old_bndr new_bndr rhs
276              ; go env' pairs }
277 \end{code}
278
279 simplOrTopPair is used for
280         * recursive bindings (whether top level or not)
281         * top-level non-recursive bindings
282
283 It assumes the binder has already been simplified, but not its IdInfo.
284
285 \begin{code}
286 simplRecOrTopPair :: SimplEnv
287                   -> TopLevelFlag
288                   -> InId -> OutBndr -> InExpr  -- Binder and rhs
289                   -> SimplM SimplEnv    -- Returns an env that includes the binding
290
291 simplRecOrTopPair env top_lvl old_bndr new_bndr rhs
292   | preInlineUnconditionally env top_lvl old_bndr rhs   -- Check for unconditional inline
293   = do  { tick (PreInlineUnconditionally old_bndr)
294         ; return (extendIdSubst env old_bndr (mkContEx env rhs)) }
295
296   | otherwise
297   = simplLazyBind env top_lvl Recursive old_bndr new_bndr rhs env
298         -- May not actually be recursive, but it doesn't matter
299 \end{code}
300
301
302 simplLazyBind is used for
303   * [simplRecOrTopPair] recursive bindings (whether top level or not)
304   * [simplRecOrTopPair] top-level non-recursive bindings
305   * [simplNonRecE]      non-top-level *lazy* non-recursive bindings
306
307 Nota bene:
308     1. It assumes that the binder is *already* simplified,
309        and is in scope, and its IdInfo too, except unfolding
310
311     2. It assumes that the binder type is lifted.
312
313     3. It does not check for pre-inline-unconditionallly;
314        that should have been done already.
315
316 \begin{code}
317 simplLazyBind :: SimplEnv
318               -> TopLevelFlag -> RecFlag
319               -> InId -> OutId          -- Binder, both pre-and post simpl
320                                         -- The OutId has IdInfo, except arity, unfolding
321               -> InExpr -> SimplEnv     -- The RHS and its environment
322               -> SimplM SimplEnv
323
324 simplLazyBind env top_lvl is_rec bndr bndr1 rhs rhs_se
325   = -- pprTrace "simplLazyBind" ((ppr bndr <+> ppr bndr1) $$ ppr rhs $$ ppr (seIdSubst rhs_se)) $
326     do  { let   rhs_env     = rhs_se `setInScope` env
327                 (tvs, body) = case collectTyBinders rhs of
328                                 (tvs, body) | not_lam body -> (tvs,body)
329                                             | otherwise    -> ([], rhs)
330                 not_lam (Lam _ _) = False
331                 not_lam _         = True
332                         -- Do not do the "abstract tyyvar" thing if there's
333                         -- a lambda inside, becuase it defeats eta-reduction
334                         --    f = /\a. \x. g a x  
335                         -- should eta-reduce
336
337         ; (body_env, tvs') <- simplBinders rhs_env tvs
338                 -- See Note [Floating and type abstraction] in SimplUtils
339
340         -- Simplify the RHS
341         ; (body_env1, body1) <- simplExprF body_env body mkRhsStop
342         -- ANF-ise a constructor or PAP rhs
343         ; (body_env2, body2) <- prepareRhs top_lvl body_env1 bndr1 body1
344
345         ; (env', rhs')
346             <-  if not (doFloatFromRhs top_lvl is_rec False body2 body_env2)
347                 then                            -- No floating, revert to body1
348                      do { rhs' <- mkLam env tvs' (wrapFloats body_env1 body1)
349                         ; return (env, rhs') }
350
351                 else if null tvs then           -- Simple floating
352                      do { tick LetFloatFromLet
353                         ; return (addFloats env body_env2, body2) }
354
355                 else                            -- Do type-abstraction first
356                      do { tick LetFloatFromLet
357                         ; (poly_binds, body3) <- abstractFloats tvs' body_env2 body2
358                         ; rhs' <- mkLam env tvs' body3
359                         ; env' <- foldlM (addPolyBind top_lvl) env poly_binds
360                         ; return (env', rhs') }
361
362         ; completeBind env' top_lvl bndr bndr1 rhs' }
363 \end{code}
364
365 A specialised variant of simplNonRec used when the RHS is already simplified,
366 notably in knownCon.  It uses case-binding where necessary.
367
368 \begin{code}
369 simplNonRecX :: SimplEnv
370              -> InId            -- Old binder
371              -> OutExpr         -- Simplified RHS
372              -> SimplM SimplEnv
373
374 simplNonRecX env bndr new_rhs
375   | isDeadBinder bndr   -- Not uncommon; e.g. case (a,b) of b { (p,q) -> p }
376   = return env          --               Here b is dead, and we avoid creating
377   | otherwise           --               the binding b = (a,b)
378   = do  { (env', bndr') <- simplBinder env bndr
379         ; completeNonRecX NotTopLevel env' (isStrictId bndr) bndr bndr' new_rhs }
380                 -- simplNonRecX is only used for NotTopLevel things
381
382 completeNonRecX :: TopLevelFlag -> SimplEnv
383                 -> Bool
384                 -> InId                 -- Old binder
385                 -> OutId                -- New binder
386                 -> OutExpr              -- Simplified RHS
387                 -> SimplM SimplEnv
388
389 completeNonRecX top_lvl env is_strict old_bndr new_bndr new_rhs
390   = do  { (env1, rhs1) <- prepareRhs top_lvl (zapFloats env) new_bndr new_rhs
391         ; (env2, rhs2) <- 
392                 if doFloatFromRhs NotTopLevel NonRecursive is_strict rhs1 env1
393                 then do { tick LetFloatFromLet
394                         ; return (addFloats env env1, rhs1) }   -- Add the floats to the main env
395                 else return (env, wrapFloats env1 rhs1)         -- Wrap the floats around the RHS
396         ; completeBind env2 NotTopLevel old_bndr new_bndr rhs2 }
397 \end{code}
398
399 {- No, no, no!  Do not try preInlineUnconditionally in completeNonRecX
400    Doing so risks exponential behaviour, because new_rhs has been simplified once already
401    In the cases described by the folowing commment, postInlineUnconditionally will
402    catch many of the relevant cases.
403         -- This happens; for example, the case_bndr during case of
404         -- known constructor:  case (a,b) of x { (p,q) -> ... }
405         -- Here x isn't mentioned in the RHS, so we don't want to
406         -- create the (dead) let-binding  let x = (a,b) in ...
407         --
408         -- Similarly, single occurrences can be inlined vigourously
409         -- e.g.  case (f x, g y) of (a,b) -> ....
410         -- If a,b occur once we can avoid constructing the let binding for them.
411
412    Furthermore in the case-binding case preInlineUnconditionally risks extra thunks
413         -- Consider     case I# (quotInt# x y) of
414         --                I# v -> let w = J# v in ...
415         -- If we gaily inline (quotInt# x y) for v, we end up building an
416         -- extra thunk:
417         --                let w = J# (quotInt# x y) in ...
418         -- because quotInt# can fail.
419
420   | preInlineUnconditionally env NotTopLevel bndr new_rhs
421   = thing_inside (extendIdSubst env bndr (DoneEx new_rhs))
422 -}
423
424 ----------------------------------
425 prepareRhs takes a putative RHS, checks whether it's a PAP or
426 constructor application and, if so, converts it to ANF, so that the
427 resulting thing can be inlined more easily.  Thus
428         x = (f a, g b)
429 becomes
430         t1 = f a
431         t2 = g b
432         x = (t1,t2)
433
434 We also want to deal well cases like this
435         v = (f e1 `cast` co) e2
436 Here we want to make e1,e2 trivial and get
437         x1 = e1; x2 = e2; v = (f x1 `cast` co) v2
438 That's what the 'go' loop in prepareRhs does
439
440 \begin{code}
441 prepareRhs :: TopLevelFlag -> SimplEnv -> OutId -> OutExpr -> SimplM (SimplEnv, OutExpr)
442 -- Adds new floats to the env iff that allows us to return a good RHS
443 prepareRhs top_lvl env id (Cast rhs co)    -- Note [Float coercions]
444   | (ty1, _ty2) <- coercionKind co       -- Do *not* do this if rhs has an unlifted type
445   , not (isUnLiftedType ty1)            -- see Note [Float coercions (unlifted)]
446   = do  { (env', rhs') <- makeTrivialWithInfo top_lvl env sanitised_info rhs
447         ; return (env', Cast rhs' co) }
448   where
449     sanitised_info = vanillaIdInfo `setStrictnessInfo` strictnessInfo info
450                                    `setDemandInfo`     demandInfo info
451     info = idInfo id
452
453 prepareRhs top_lvl env0 _ rhs0
454   = do  { (_is_exp, env1, rhs1) <- go 0 env0 rhs0
455         ; return (env1, rhs1) }
456   where
457     go n_val_args env (Cast rhs co)
458         = do { (is_exp, env', rhs') <- go n_val_args env rhs
459              ; return (is_exp, env', Cast rhs' co) }
460     go n_val_args env (App fun (Type ty))
461         = do { (is_exp, env', rhs') <- go n_val_args env fun
462              ; return (is_exp, env', App rhs' (Type ty)) }
463     go n_val_args env (App fun arg)
464         = do { (is_exp, env', fun') <- go (n_val_args+1) env fun
465              ; case is_exp of
466                 True -> do { (env'', arg') <- makeTrivial top_lvl env' arg
467                            ; return (True, env'', App fun' arg') }
468                 False -> return (False, env, App fun arg) }
469     go n_val_args env (Var fun)
470         = return (is_exp, env, Var fun)
471         where
472           is_exp = isExpandableApp fun n_val_args   -- The fun a constructor or PAP
473                         -- See Note [CONLIKE pragma] in BasicTypes
474                         -- The definition of is_exp should match that in
475                         -- OccurAnal.occAnalApp
476
477     go _ env other
478         = return (False, env, other)
479 \end{code}
480
481
482 Note [Float coercions]
483 ~~~~~~~~~~~~~~~~~~~~~~
484 When we find the binding
485         x = e `cast` co
486 we'd like to transform it to
487         x' = e
488         x = x `cast` co         -- A trivial binding
489 There's a chance that e will be a constructor application or function, or something
490 like that, so moving the coerion to the usage site may well cancel the coersions
491 and lead to further optimisation.  Example:
492
493      data family T a :: *
494      data instance T Int = T Int
495
496      foo :: Int -> Int -> Int
497      foo m n = ...
498         where
499           x = T m
500           go 0 = 0
501           go n = case x of { T m -> go (n-m) }
502                 -- This case should optimise
503
504 Note [Preserve strictness when floating coercions]
505 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
506 In the Note [Float coercions] transformation, keep the strictness info.
507 Eg
508         f = e `cast` co    -- f has strictness SSL
509 When we transform to
510         f' = e             -- f' also has strictness SSL
511         f = f' `cast` co   -- f still has strictness SSL
512
513 Its not wrong to drop it on the floor, but better to keep it.
514
515 Note [Float coercions (unlifted)]
516 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
517 BUT don't do [Float coercions] if 'e' has an unlifted type.
518 This *can* happen:
519
520      foo :: Int = (error (# Int,Int #) "urk")
521                   `cast` CoUnsafe (# Int,Int #) Int
522
523 If do the makeTrivial thing to the error call, we'll get
524     foo = case error (# Int,Int #) "urk" of v -> v `cast` ...
525 But 'v' isn't in scope!
526
527 These strange casts can happen as a result of case-of-case
528         bar = case (case x of { T -> (# 2,3 #); F -> error "urk" }) of
529                 (# p,q #) -> p+q
530
531
532 \begin{code}
533 makeTrivial :: TopLevelFlag -> SimplEnv -> OutExpr -> SimplM (SimplEnv, OutExpr)
534 -- Binds the expression to a variable, if it's not trivial, returning the variable
535 makeTrivial top_lvl env expr = makeTrivialWithInfo top_lvl env vanillaIdInfo expr
536
537 makeTrivialWithInfo :: TopLevelFlag -> SimplEnv -> IdInfo 
538                     -> OutExpr -> SimplM (SimplEnv, OutExpr)
539 -- Propagate strictness and demand info to the new binder
540 -- Note [Preserve strictness when floating coercions]
541 -- Returned SimplEnv has same substitution as incoming one
542 makeTrivialWithInfo top_lvl env info expr
543   | exprIsTrivial expr                          -- Already trivial
544   || not (bindingOk top_lvl expr expr_ty)       -- Cannot trivialise
545                                                 --   See Note [Cannot trivialise]
546   = return (env, expr)
547   | otherwise           -- See Note [Take care] below
548   = do  { uniq <- getUniqueM
549         ; let name = mkSystemVarName uniq (fsLit "a")
550               var = mkLocalIdWithInfo name expr_ty info
551         ; env'  <- completeNonRecX top_lvl env False var var expr
552         ; expr' <- simplVar env' var
553         ; return (env', expr') }
554         -- The simplVar is needed becase we're constructing a new binding
555         --     a = rhs
556         -- And if rhs is of form (rhs1 |> co), then we might get
557         --     a1 = rhs1
558         --     a = a1 |> co
559         -- and now a's RHS is trivial and can be substituted out, and that
560         -- is what completeNonRecX will do
561         -- To put it another way, it's as if we'd simplified
562         --    let var = e in var
563   where
564     expr_ty = exprType expr
565
566 bindingOk :: TopLevelFlag -> CoreExpr -> Type -> Bool
567 -- True iff we can have a binding of this expression at this level
568 -- Precondition: the type is the type of the expression
569 bindingOk top_lvl _ expr_ty
570   | isTopLevel top_lvl = not (isUnLiftedType expr_ty) 
571   | otherwise          = True
572 \end{code}
573
574 Note [Cannot trivialise]
575 ~~~~~~~~~~~~~~~~~~~~~~~~
576 Consider tih
577    f :: Int -> Addr#
578    
579    foo :: Bar
580    foo = Bar (f 3)
581
582 Then we can't ANF-ise foo, even though we'd like to, because
583 we can't make a top-level binding for the Addr# (f 3). And if
584 so we don't want to turn it into
585    foo = let x = f 3 in Bar x
586 because we'll just end up inlining x back, and that makes the
587 simplifier loop.  Better not to ANF-ise it at all.
588
589 A case in point is literal strings (a MachStr is not regarded as
590 trivial):
591
592    foo = Ptr "blob"#
593
594 We don't want to ANF-ise this.
595
596 %************************************************************************
597 %*                                                                      *
598 \subsection{Completing a lazy binding}
599 %*                                                                      *
600 %************************************************************************
601
602 completeBind
603   * deals only with Ids, not TyVars
604   * takes an already-simplified binder and RHS
605   * is used for both recursive and non-recursive bindings
606   * is used for both top-level and non-top-level bindings
607
608 It does the following:
609   - tries discarding a dead binding
610   - tries PostInlineUnconditionally
611   - add unfolding [this is the only place we add an unfolding]
612   - add arity
613
614 It does *not* attempt to do let-to-case.  Why?  Because it is used for
615   - top-level bindings (when let-to-case is impossible)
616   - many situations where the "rhs" is known to be a WHNF
617                 (so let-to-case is inappropriate).
618
619 Nor does it do the atomic-argument thing
620
621 \begin{code}
622 completeBind :: SimplEnv
623              -> TopLevelFlag            -- Flag stuck into unfolding
624              -> InId                    -- Old binder
625              -> OutId -> OutExpr        -- New binder and RHS
626              -> SimplM SimplEnv
627 -- completeBind may choose to do its work
628 --      * by extending the substitution (e.g. let x = y in ...)
629 --      * or by adding to the floats in the envt
630
631 completeBind env top_lvl old_bndr new_bndr new_rhs
632   = do  { let old_info = idInfo old_bndr
633               old_unf  = unfoldingInfo old_info
634               occ_info = occInfo old_info
635
636         ; new_unfolding <- simplUnfolding env top_lvl old_bndr occ_info new_rhs old_unf
637
638         ; if postInlineUnconditionally env top_lvl new_bndr occ_info new_rhs new_unfolding
639                         -- Inline and discard the binding
640           then do  { tick (PostInlineUnconditionally old_bndr)
641                    ; -- pprTrace "postInlineUnconditionally" (ppr old_bndr <+> equals <+> ppr new_rhs) $
642                      return (extendIdSubst env old_bndr (DoneEx new_rhs)) }
643                 -- Use the substitution to make quite, quite sure that the
644                 -- substitution will happen, since we are going to discard the binding
645
646           else return (addNonRecWithUnf env new_bndr new_rhs new_unfolding) }
647
648 ------------------------------
649 addPolyBind :: TopLevelFlag -> SimplEnv -> OutBind -> SimplM SimplEnv
650 -- Add a new binding to the environment, complete with its unfolding
651 -- but *do not* do postInlineUnconditionally, because we have already
652 -- processed some of the scope of the binding
653 -- We still want the unfolding though.  Consider
654 --      let 
655 --            x = /\a. let y = ... in Just y
656 --      in body
657 -- Then we float the y-binding out (via abstractFloats and addPolyBind)
658 -- but 'x' may well then be inlined in 'body' in which case we'd like the 
659 -- opportunity to inline 'y' too.
660
661 addPolyBind top_lvl env (NonRec poly_id rhs)
662   = do  { unfolding <- simplUnfolding env top_lvl poly_id NoOccInfo rhs noUnfolding
663                         -- Assumes that poly_id did not have an INLINE prag
664                         -- which is perhaps wrong.  ToDo: think about this
665         ; return (addNonRecWithUnf env poly_id rhs unfolding) }
666
667 addPolyBind _ env bind@(Rec _) = return (extendFloats env bind)
668                 -- Hack: letrecs are more awkward, so we extend "by steam"
669                 -- without adding unfoldings etc.  At worst this leads to
670                 -- more simplifier iterations
671
672 ------------------------------
673 addNonRecWithUnf :: SimplEnv
674                  -> OutId -> OutExpr    -- New binder and RHS
675                  -> Unfolding           -- New unfolding
676                  -> SimplEnv
677 addNonRecWithUnf env new_bndr new_rhs new_unfolding
678   = let new_arity = exprArity new_rhs
679         old_arity = idArity new_bndr
680         info1 = idInfo new_bndr `setArityInfo` new_arity
681         
682               -- Unfolding info: Note [Setting the new unfolding]
683         info2 = info1 `setUnfoldingInfo` new_unfolding
684
685         -- Demand info: Note [Setting the demand info]
686         info3 | isEvaldUnfolding new_unfolding = zapDemandInfo info2 `orElse` info2
687               | otherwise                      = info2
688
689         final_id = new_bndr `setIdInfo` info3
690         dmd_arity = length $ fst $ splitStrictSig $ idStrictness new_bndr
691     in
692     ASSERT( isId new_bndr )
693     WARN( new_arity < old_arity || new_arity < dmd_arity, 
694           (ptext (sLit "Arity decrease:") <+> (ppr final_id <+> ppr old_arity
695                 <+> ppr new_arity <+> ppr dmd_arity) $$ ppr new_rhs) )
696         -- Note [Arity decrease]
697
698     final_id `seq`   -- This seq forces the Id, and hence its IdInfo,
699                      -- and hence any inner substitutions
700             -- pprTrace "Binding" (ppr final_id <+> ppr unfolding) $
701     addNonRec env final_id new_rhs
702                 -- The addNonRec adds it to the in-scope set too
703
704 ------------------------------
705 simplUnfolding :: SimplEnv-> TopLevelFlag
706                -> Id
707                -> OccInfo -> OutExpr
708                -> Unfolding -> SimplM Unfolding
709 -- Note [Setting the new unfolding]
710 simplUnfolding env _ _ _ _ (DFunUnfolding ar con ops)
711   = return (DFunUnfolding ar con ops')
712   where
713     ops' = map (substExpr (text "simplUnfolding") env) ops
714
715 simplUnfolding env top_lvl id _ _ 
716     (CoreUnfolding { uf_tmpl = expr, uf_arity = arity
717                    , uf_src = src, uf_guidance = guide })
718   | isStableSource src
719   = do { expr' <- simplExpr rule_env expr
720        ; let src' = CoreSubst.substUnfoldingSource (mkCoreSubst (text "inline-unf") env) src
721              is_top_lvl = isTopLevel top_lvl
722        ; case guide of
723            UnfIfGoodArgs{} ->
724               -- We need to force bottoming, or the new unfolding holds
725               -- on to the old unfolding (which is part of the id).
726               let bottoming = isBottomingId id
727               in bottoming `seq` return (mkUnfolding src' is_top_lvl bottoming expr')
728                 -- If the guidance is UnfIfGoodArgs, this is an INLINABLE
729                 -- unfolding, and we need to make sure the guidance is kept up
730                 -- to date with respect to any changes in the unfolding.
731            _other -> 
732               return (mkCoreUnfolding src' is_top_lvl expr' arity guide)
733                 -- See Note [Top-level flag on inline rules] in CoreUnfold
734        }
735   where
736     act      = idInlineActivation id
737     rule_env = updMode (updModeForInlineRules act) env
738                -- See Note [Simplifying inside InlineRules] in SimplUtils
739
740 simplUnfolding _ top_lvl id _occ_info new_rhs _
741   = -- We need to force bottoming, or the new unfolding holds
742     -- on to the old unfolding (which is part of the id).
743     let bottoming = isBottomingId id
744     in bottoming `seq` return (mkUnfolding InlineRhs (isTopLevel top_lvl) bottoming new_rhs)
745   -- We make an  unfolding *even for loop-breakers*.
746   -- Reason: (a) It might be useful to know that they are WHNF
747   --         (b) In TidyPgm we currently assume that, if we want to
748   --             expose the unfolding then indeed we *have* an unfolding
749   --             to expose.  (We could instead use the RHS, but currently
750   --             we don't.)  The simple thing is always to have one.
751 \end{code}
752
753 Note [Arity decrease]
754 ~~~~~~~~~~~~~~~~~~~~~
755 Generally speaking the arity of a binding should not decrease.  But it *can* 
756 legitimately happen becuase of RULES.  Eg
757         f = g Int
758 where g has arity 2, will have arity 2.  But if there's a rewrite rule
759         g Int --> h
760 where h has arity 1, then f's arity will decrease.  Here's a real-life example,
761 which is in the output of Specialise:
762
763      Rec {
764         $dm {Arity 2} = \d.\x. op d
765         {-# RULES forall d. $dm Int d = $s$dm #-}
766         
767         dInt = MkD .... opInt ...
768         opInt {Arity 1} = $dm dInt
769
770         $s$dm {Arity 0} = \x. op dInt }
771
772 Here opInt has arity 1; but when we apply the rule its arity drops to 0.
773 That's why Specialise goes to a little trouble to pin the right arity
774 on specialised functions too.
775
776 Note [Setting the new unfolding]
777 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
778 * If there's an INLINE pragma, we simplify the RHS gently.  Maybe we
779   should do nothing at all, but simplifying gently might get rid of 
780   more crap.
781
782 * If not, we make an unfolding from the new RHS.  But *only* for
783   non-loop-breakers. Making loop breakers not have an unfolding at all
784   means that we can avoid tests in exprIsConApp, for example.  This is
785   important: if exprIsConApp says 'yes' for a recursive thing, then we
786   can get into an infinite loop
787
788 If there's an InlineRule on a loop breaker, we hang on to the inlining.
789 It's pretty dodgy, but the user did say 'INLINE'.  May need to revisit
790 this choice.
791
792 Note [Setting the demand info]
793 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
794 If the unfolding is a value, the demand info may
795 go pear-shaped, so we nuke it.  Example:
796      let x = (a,b) in
797      case x of (p,q) -> h p q x
798 Here x is certainly demanded. But after we've nuked
799 the case, we'll get just
800      let x = (a,b) in h a b x
801 and now x is not demanded (I'm assuming h is lazy)
802 This really happens.  Similarly
803      let f = \x -> e in ...f..f...
804 After inlining f at some of its call sites the original binding may
805 (for example) be no longer strictly demanded.
806 The solution here is a bit ad hoc...
807
808
809 %************************************************************************
810 %*                                                                      *
811 \subsection[Simplify-simplExpr]{The main function: simplExpr}
812 %*                                                                      *
813 %************************************************************************
814
815 The reason for this OutExprStuff stuff is that we want to float *after*
816 simplifying a RHS, not before.  If we do so naively we get quadratic
817 behaviour as things float out.
818
819 To see why it's important to do it after, consider this (real) example:
820
821         let t = f x
822         in fst t
823 ==>
824         let t = let a = e1
825                     b = e2
826                 in (a,b)
827         in fst t
828 ==>
829         let a = e1
830             b = e2
831             t = (a,b)
832         in
833         a       -- Can't inline a this round, cos it appears twice
834 ==>
835         e1
836
837 Each of the ==> steps is a round of simplification.  We'd save a
838 whole round if we float first.  This can cascade.  Consider
839
840         let f = g d
841         in \x -> ...f...
842 ==>
843         let f = let d1 = ..d.. in \y -> e
844         in \x -> ...f...
845 ==>
846         let d1 = ..d..
847         in \x -> ...(\y ->e)...
848
849 Only in this second round can the \y be applied, and it
850 might do the same again.
851
852
853 \begin{code}
854 simplExpr :: SimplEnv -> CoreExpr -> SimplM CoreExpr
855 simplExpr env expr = simplExprC env expr mkBoringStop
856
857 simplExprC :: SimplEnv -> CoreExpr -> SimplCont -> SimplM CoreExpr
858         -- Simplify an expression, given a continuation
859 simplExprC env expr cont
860   = -- pprTrace "simplExprC" (ppr expr $$ ppr cont {- $$ ppr (seIdSubst env) -} $$ ppr (seFloats env) ) $
861     do  { (env', expr') <- simplExprF (zapFloats env) expr cont
862         ; -- pprTrace "simplExprC ret" (ppr expr $$ ppr expr') $
863           -- pprTrace "simplExprC ret3" (ppr (seInScope env')) $
864           -- pprTrace "simplExprC ret4" (ppr (seFloats env')) $
865           return (wrapFloats env' expr') }
866
867 --------------------------------------------------
868 simplExprF :: SimplEnv -> InExpr -> SimplCont
869            -> SimplM (SimplEnv, OutExpr)
870
871 simplExprF env e cont
872   = -- pprTrace "simplExprF" (ppr e $$ ppr cont $$ ppr (seTvSubst env) $$ ppr (seIdSubst env) {- $$ ppr (seFloats env) -} ) $
873     simplExprF' env e cont
874
875 simplExprF' :: SimplEnv -> InExpr -> SimplCont
876             -> SimplM (SimplEnv, OutExpr)
877 simplExprF' env (Var v)        cont = simplVarF env v cont
878 simplExprF' env (Lit lit)      cont = rebuild env (Lit lit) cont
879 simplExprF' env (Note n expr)  cont = simplNote env n expr cont
880 simplExprF' env (Cast body co) cont = simplCast env body co cont
881 simplExprF' env (App fun arg)  cont = simplExprF env fun $
882                                       ApplyTo NoDup arg env cont
883
884 simplExprF' env expr@(Lam _ _) cont
885   = simplLam env (map zap bndrs) body cont
886         -- The main issue here is under-saturated lambdas
887         --   (\x1. \x2. e) arg1
888         -- Here x1 might have "occurs-once" occ-info, because occ-info
889         -- is computed assuming that a group of lambdas is applied
890         -- all at once.  If there are too few args, we must zap the
891         -- occ-info.
892   where
893     n_args   = countArgs cont
894     n_params = length bndrs
895     (bndrs, body) = collectBinders expr
896     zap | n_args >= n_params = \b -> b
897         | otherwise          = \b -> if isTyCoVar b then b
898                                      else zapLamIdInfo b
899         -- NB: we count all the args incl type args
900         -- so we must count all the binders (incl type lambdas)
901
902 simplExprF' env (Type ty) cont
903   = ASSERT( contIsRhsOrArg cont )
904     do  { ty' <- simplCoercion env ty
905         ; rebuild env (Type ty') cont }
906
907 simplExprF' env (Case scrut bndr _ alts) cont
908   | not (switchIsOn (getSwitchChecker env) NoCaseOfCase)
909   =     -- Simplify the scrutinee with a Select continuation
910     simplExprF env scrut (Select NoDup bndr alts env cont)
911
912   | otherwise
913   =     -- If case-of-case is off, simply simplify the case expression
914         -- in a vanilla Stop context, and rebuild the result around it
915     do  { case_expr' <- simplExprC env scrut
916                              (Select NoDup bndr alts env mkBoringStop)
917         ; rebuild env case_expr' cont }
918
919 simplExprF' env (Let (Rec pairs) body) cont
920   = do  { env' <- simplRecBndrs env (map fst pairs)
921                 -- NB: bndrs' don't have unfoldings or rules
922                 -- We add them as we go down
923
924         ; env'' <- simplRecBind env' NotTopLevel pairs
925         ; simplExprF env'' body cont }
926
927 simplExprF' env (Let (NonRec bndr rhs) body) cont
928   = simplNonRecE env bndr (rhs, env) ([], body) cont
929
930 ---------------------------------
931 simplType :: SimplEnv -> InType -> SimplM OutType
932         -- Kept monadic just so we can do the seqType
933 simplType env ty
934   = -- pprTrace "simplType" (ppr ty $$ ppr (seTvSubst env)) $
935     seqType new_ty `seq` return new_ty
936   where
937     new_ty = substTy env ty
938
939 ---------------------------------
940 simplCoercion :: SimplEnv -> InType -> SimplM OutType
941 -- The InType isn't *necessarily* a coercion, but it might be
942 -- (in a type application, say) and optCoercion is a no-op on types
943 simplCoercion env co
944   = seqType new_co `seq` return new_co
945   where 
946     new_co = optCoercion (getTvSubst env) co
947 \end{code}
948
949
950 %************************************************************************
951 %*                                                                      *
952 \subsection{The main rebuilder}
953 %*                                                                      *
954 %************************************************************************
955
956 \begin{code}
957 rebuild :: SimplEnv -> OutExpr -> SimplCont -> SimplM (SimplEnv, OutExpr)
958 -- At this point the substitution in the SimplEnv should be irrelevant
959 -- only the in-scope set and floats should matter
960 rebuild env expr cont0
961   = -- pprTrace "rebuild" (ppr expr $$ ppr cont0 $$ ppr (seFloats env)) $
962     case cont0 of
963       Stop {}                      -> return (env, expr)
964       CoerceIt co cont             -> rebuild env (mkCoerce co expr) cont
965       Select _ bndr alts se cont   -> rebuildCase (se `setFloats` env) expr bndr alts cont
966       StrictArg info _ cont        -> rebuildCall env (info `addArgTo` expr) cont
967       StrictBind b bs body se cont -> do { env' <- simplNonRecX (se `setFloats` env) b expr
968                                          ; simplLam env' bs body cont }
969       ApplyTo dup_flag arg se cont -- See Note [Avoid redundant simplification]
970         | isSimplified dup_flag    -> rebuild env (App expr arg) cont
971         | otherwise                -> do { arg' <- simplExpr (se `setInScope` env) arg
972                                          ; rebuild env (App expr arg') cont }
973 \end{code}
974
975
976 %************************************************************************
977 %*                                                                      *
978 \subsection{Lambdas}
979 %*                                                                      *
980 %************************************************************************
981
982 \begin{code}
983 simplCast :: SimplEnv -> InExpr -> Coercion -> SimplCont
984           -> SimplM (SimplEnv, OutExpr)
985 simplCast env body co0 cont0
986   = do  { co1 <- simplCoercion env co0
987         ; simplExprF env body (addCoerce co1 cont0) }
988   where
989        addCoerce co cont = add_coerce co (coercionKind co) cont
990
991        add_coerce _co (s1, k1) cont     -- co :: ty~ty
992          | s1 `coreEqType` k1 = cont    -- is a no-op
993
994        add_coerce co1 (s1, _k2) (CoerceIt co2 cont)
995          | (_l1, t1) <- coercionKind co2
996                 --      e |> (g1 :: S1~L) |> (g2 :: L~T1)
997                 -- ==>
998                 --      e,                       if S1=T1
999                 --      e |> (g1 . g2 :: S1~T1)  otherwise
1000                 --
1001                 -- For example, in the initial form of a worker
1002                 -- we may find  (coerce T (coerce S (\x.e))) y
1003                 -- and we'd like it to simplify to e[y/x] in one round
1004                 -- of simplification
1005          , s1 `coreEqType` t1  = cont            -- The coerces cancel out
1006          | otherwise           = CoerceIt (mkTransCoercion co1 co2) cont
1007
1008        add_coerce co (s1s2, _t1t2) (ApplyTo dup (Type arg_ty) arg_se cont)
1009                 -- (f |> g) ty  --->   (f ty) |> (g @ ty)
1010                 -- This implements the PushT and PushC rules from the paper
1011          | Just (tyvar,_) <- splitForAllTy_maybe s1s2
1012          = let 
1013              (new_arg_ty, new_cast)
1014                | isCoVar tyvar = (new_arg_co, mkCselRCoercion co)       -- PushC rule
1015                | otherwise     = (ty',        mkInstCoercion co ty')    -- PushT rule
1016            in 
1017            ApplyTo dup (Type new_arg_ty) (zapSubstEnv arg_se) (addCoerce new_cast cont)
1018          where
1019            ty' = substTy (arg_se `setInScope` env) arg_ty
1020            new_arg_co = mkCsel1Coercion co  `mkTransCoercion`
1021                               ty'           `mkTransCoercion`
1022                         mkSymCoercion (mkCsel2Coercion co)
1023
1024        add_coerce co (s1s2, _t1t2) (ApplyTo dup arg arg_se cont)
1025          | not (isTypeArg arg)  -- This implements the Push rule from the paper
1026          , isFunTy s1s2   -- t1t2 must be a function type, becuase it's applied
1027                 --      (e |> (g :: s1s2 ~ t1->t2)) f
1028                 -- ===>
1029                 --      (e (f |> (arg g :: t1~s1))
1030                 --      |> (res g :: s2->t2)
1031                 --
1032                 -- t1t2 must be a function type, t1->t2, because it's applied
1033                 -- to something but s1s2 might conceivably not be
1034                 --
1035                 -- When we build the ApplyTo we can't mix the out-types
1036                 -- with the InExpr in the argument, so we simply substitute
1037                 -- to make it all consistent.  It's a bit messy.
1038                 -- But it isn't a common case.
1039                 --
1040                 -- Example of use: Trac #995
1041          = ApplyTo dup new_arg (zapSubstEnv arg_se) (addCoerce co2 cont)
1042          where
1043            -- we split coercion t1->t2 ~ s1->s2 into t1 ~ s1 and
1044            -- t2 ~ s2 with left and right on the curried form:
1045            --    (->) t1 t2 ~ (->) s1 s2
1046            [co1, co2] = decomposeCo 2 co
1047            new_arg    = mkCoerce (mkSymCoercion co1) arg'
1048            arg'       = substExpr (text "move-cast") (arg_se `setInScope` env) arg
1049
1050        add_coerce co _ cont = CoerceIt co cont
1051 \end{code}
1052
1053
1054 %************************************************************************
1055 %*                                                                      *
1056 \subsection{Lambdas}
1057 %*                                                                      *
1058 %************************************************************************
1059
1060 \begin{code}
1061 simplLam :: SimplEnv -> [InId] -> InExpr -> SimplCont
1062          -> SimplM (SimplEnv, OutExpr)
1063
1064 simplLam env [] body cont = simplExprF env body cont
1065
1066         -- Beta reduction
1067 simplLam env (bndr:bndrs) body (ApplyTo _ arg arg_se cont)
1068   = do  { tick (BetaReduction bndr)
1069         ; simplNonRecE env bndr (arg, arg_se) (bndrs, body) cont }
1070
1071         -- Not enough args, so there are real lambdas left to put in the result
1072 simplLam env bndrs body cont
1073   = do  { (env', bndrs') <- simplLamBndrs env bndrs
1074         ; body' <- simplExpr env' body
1075         ; new_lam <- mkLam env' bndrs' body'
1076         ; rebuild env' new_lam cont }
1077
1078 ------------------
1079 simplNonRecE :: SimplEnv
1080              -> InBndr                  -- The binder
1081              -> (InExpr, SimplEnv)      -- Rhs of binding (or arg of lambda)
1082              -> ([InBndr], InExpr)      -- Body of the let/lambda
1083                                         --      \xs.e
1084              -> SimplCont
1085              -> SimplM (SimplEnv, OutExpr)
1086
1087 -- simplNonRecE is used for
1088 --  * non-top-level non-recursive lets in expressions
1089 --  * beta reduction
1090 --
1091 -- It deals with strict bindings, via the StrictBind continuation,
1092 -- which may abort the whole process
1093 --
1094 -- The "body" of the binding comes as a pair of ([InId],InExpr)
1095 -- representing a lambda; so we recurse back to simplLam
1096 -- Why?  Because of the binder-occ-info-zapping done before
1097 --       the call to simplLam in simplExprF (Lam ...)
1098
1099         -- First deal with type applications and type lets
1100         --   (/\a. e) (Type ty)   and   (let a = Type ty in e)
1101 simplNonRecE env bndr (Type ty_arg, rhs_se) (bndrs, body) cont
1102   = ASSERT( isTyCoVar bndr )
1103     do  { ty_arg' <- simplType (rhs_se `setInScope` env) ty_arg
1104         ; simplLam (extendTvSubst env bndr ty_arg') bndrs body cont }
1105
1106 simplNonRecE env bndr (rhs, rhs_se) (bndrs, body) cont
1107   | preInlineUnconditionally env NotTopLevel bndr rhs
1108   = do  { tick (PreInlineUnconditionally bndr)
1109         ; -- pprTrace "preInlineUncond" (ppr bndr <+> ppr rhs) $
1110           simplLam (extendIdSubst env bndr (mkContEx rhs_se rhs)) bndrs body cont }
1111
1112   | isStrictId bndr
1113   = do  { simplExprF (rhs_se `setFloats` env) rhs
1114                      (StrictBind bndr bndrs body env cont) }
1115
1116   | otherwise
1117   = ASSERT( not (isTyCoVar bndr) )
1118     do  { (env1, bndr1) <- simplNonRecBndr env bndr
1119         ; let (env2, bndr2) = addBndrRules env1 bndr bndr1
1120         ; env3 <- simplLazyBind env2 NotTopLevel NonRecursive bndr bndr2 rhs rhs_se
1121         ; simplLam env3 bndrs body cont }
1122 \end{code}
1123
1124
1125 %************************************************************************
1126 %*                                                                      *
1127 \subsection{Notes}
1128 %*                                                                      *
1129 %************************************************************************
1130
1131 \begin{code}
1132 -- Hack alert: we only distinguish subsumed cost centre stacks for the
1133 -- purposes of inlining.  All other CCCSs are mapped to currentCCS.
1134 simplNote :: SimplEnv -> Note -> CoreExpr -> SimplCont
1135           -> SimplM (SimplEnv, OutExpr)
1136 simplNote env (SCC cc) e cont
1137   | pushCCisNop cc (getEnclosingCC env)  -- scc "f" (...(scc "f" e)...) 
1138   = simplExprF env e cont                -- ==>  scc "f" (...e...)
1139   | otherwise
1140   = do  { e' <- simplExpr (setEnclosingCC env currentCCS) e
1141         ; rebuild env (mkSCC cc e') cont }
1142
1143 simplNote env (CoreNote s) e cont
1144   = do { e' <- simplExpr env e
1145        ; rebuild env (Note (CoreNote s) e') cont }
1146 \end{code}
1147
1148
1149 %************************************************************************
1150 %*                                                                      *
1151                      Variables
1152 %*                                                                      *
1153 %************************************************************************
1154
1155 \begin{code}
1156 simplVar :: SimplEnv -> InVar -> SimplM OutExpr
1157 -- Look up an InVar in the environment
1158 simplVar env var
1159   | isTyCoVar var 
1160   = return (Type (substTyVar env var))
1161   | otherwise
1162   = case substId env var of
1163         DoneId var1      -> return (Var var1)
1164         DoneEx e         -> return e
1165         ContEx tvs ids e -> simplExpr (setSubstEnv env tvs ids) e
1166
1167 simplVarF :: SimplEnv -> InId -> SimplCont -> SimplM (SimplEnv, OutExpr)
1168 simplVarF env var cont
1169   = case substId env var of
1170         DoneEx e         -> simplExprF (zapSubstEnv env) e cont
1171         ContEx tvs ids e -> simplExprF (setSubstEnv env tvs ids) e cont
1172         DoneId var1      -> completeCall env var1 cont
1173                 -- Note [zapSubstEnv]
1174                 -- The template is already simplified, so don't re-substitute.
1175                 -- This is VITAL.  Consider
1176                 --      let x = e in
1177                 --      let y = \z -> ...x... in
1178                 --      \ x -> ...y...
1179                 -- We'll clone the inner \x, adding x->x' in the id_subst
1180                 -- Then when we inline y, we must *not* replace x by x' in
1181                 -- the inlined copy!!
1182
1183 ---------------------------------------------------------
1184 --      Dealing with a call site
1185
1186 completeCall :: SimplEnv -> Id -> SimplCont -> SimplM (SimplEnv, OutExpr)
1187 completeCall env var cont
1188   = do  {   ------------- Try inlining ----------------
1189           dflags <- getDOptsSmpl
1190         ; let  (lone_variable, arg_infos, call_cont) = contArgs cont
1191                 -- The args are OutExprs, obtained by *lazily* substituting
1192                 -- in the args found in cont.  These args are only examined
1193                 -- to limited depth (unless a rule fires).  But we must do
1194                 -- the substitution; rule matching on un-simplified args would
1195                 -- be bogus
1196
1197                n_val_args = length arg_infos
1198                interesting_cont = interestingCallContext call_cont
1199                unfolding    = activeUnfolding env var
1200                maybe_inline = callSiteInline dflags var unfolding
1201                                              lone_variable arg_infos interesting_cont
1202         ; case maybe_inline of {
1203             Just expr      -- There is an inlining!
1204               ->  do { tick (UnfoldingDone var)
1205                      ; trace_inline dflags expr cont $
1206                        simplExprF (zapSubstEnv env) expr cont }
1207
1208             ; Nothing -> do               -- No inlining!
1209
1210         { rule_base <- getSimplRules
1211         ; let info = mkArgInfo var (getRules rule_base var) n_val_args call_cont
1212         ; rebuildCall env info cont
1213     }}}
1214   where
1215     trace_inline dflags unfolding cont stuff
1216       | not (dopt Opt_D_dump_inlinings dflags) = stuff
1217       | not (dopt Opt_D_verbose_core2core dflags) 
1218       = if isExternalName (idName var) then 
1219           pprTrace "Inlining done:" (ppr var) stuff
1220         else stuff
1221       | otherwise
1222       = pprTrace ("Inlining done: " ++ showSDoc (ppr var))
1223            (vcat [text "Inlined fn: " <+> nest 2 (ppr unfolding),
1224                   text "Cont:  " <+> ppr cont])
1225            stuff
1226
1227 rebuildCall :: SimplEnv
1228             -> ArgInfo
1229             -> SimplCont
1230             -> SimplM (SimplEnv, OutExpr)
1231 rebuildCall env (ArgInfo { ai_fun = fun, ai_args = rev_args, ai_strs = [] }) cont
1232   -- When we run out of strictness args, it means
1233   -- that the call is definitely bottom; see SimplUtils.mkArgInfo
1234   -- Then we want to discard the entire strict continuation.  E.g.
1235   --    * case (error "hello") of { ... }
1236   --    * (error "Hello") arg
1237   --    * f (error "Hello") where f is strict
1238   --    etc
1239   -- Then, especially in the first of these cases, we'd like to discard
1240   -- the continuation, leaving just the bottoming expression.  But the
1241   -- type might not be right, so we may have to add a coerce.
1242   | not (contIsTrivial cont)     -- Only do this if there is a non-trivial
1243   = return (env, mk_coerce res)  -- contination to discard, else we do it
1244   where                          -- again and again!
1245     res     = mkApps (Var fun) (reverse rev_args)
1246     res_ty  = exprType res
1247     cont_ty = contResultType env res_ty cont
1248     co      = mkUnsafeCoercion res_ty cont_ty
1249     mk_coerce expr | cont_ty `coreEqType` res_ty = expr
1250                    | otherwise = mkCoerce co expr
1251
1252 rebuildCall env info (ApplyTo _ (Type arg_ty) se cont)
1253   = do  { ty' <- simplCoercion (se `setInScope` env) arg_ty
1254         ; rebuildCall env (info `addArgTo` Type ty') cont }
1255
1256 rebuildCall env info@(ArgInfo { ai_encl = encl_rules
1257                               , ai_strs = str:strs, ai_discs = disc:discs })
1258             (ApplyTo dup_flag arg arg_se cont)
1259   | isSimplified dup_flag     -- See Note [Avoid redundant simplification]
1260   = rebuildCall env (addArgTo info' arg) cont
1261
1262   | str                 -- Strict argument
1263   = -- pprTrace "Strict Arg" (ppr arg $$ ppr (seIdSubst env) $$ ppr (seInScope env)) $
1264     simplExprF (arg_se `setFloats` env) arg
1265                (StrictArg info' cci cont)
1266                 -- Note [Shadowing]
1267
1268   | otherwise                           -- Lazy argument
1269         -- DO NOT float anything outside, hence simplExprC
1270         -- There is no benefit (unlike in a let-binding), and we'd
1271         -- have to be very careful about bogus strictness through
1272         -- floating a demanded let.
1273   = do  { arg' <- simplExprC (arg_se `setInScope` env) arg
1274                              (mkLazyArgStop cci)
1275         ; rebuildCall env (addArgTo info' arg') cont }
1276   where
1277     info' = info { ai_strs = strs, ai_discs = discs }
1278     cci | encl_rules || disc > 0 = ArgCtxt encl_rules  -- Be keener here
1279         | otherwise              = BoringCtxt          -- Nothing interesting
1280
1281 rebuildCall env (ArgInfo { ai_fun = fun, ai_args = rev_args, ai_rules = rules }) cont
1282   = do {  -- We've accumulated a simplified call in <fun,rev_args> 
1283           -- so try rewrite rules; see Note [RULEs apply to simplified arguments]
1284           -- See also Note [Rules for recursive functions]
1285         ; let args = reverse rev_args
1286               env' = zapSubstEnv env
1287         ; mb_rule <- tryRules env rules fun args cont
1288         ; case mb_rule of {
1289              Just (n_args, rule_rhs) -> simplExprF env' rule_rhs $
1290                                         pushSimplifiedArgs env' (drop n_args args) cont ;
1291                  -- n_args says how many args the rule consumed
1292            ; Nothing -> rebuild env (mkApps (Var fun) args) cont      -- No rules
1293     } }
1294 \end{code}
1295
1296 Note [RULES apply to simplified arguments]
1297 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1298 It's very desirable to try RULES once the arguments have been simplified, because
1299 doing so ensures that rule cascades work in one pass.  Consider
1300    {-# RULES g (h x) = k x
1301              f (k x) = x #-}
1302    ...f (g (h x))...
1303 Then we want to rewrite (g (h x)) to (k x) and only then try f's rules. If
1304 we match f's rules against the un-simplified RHS, it won't match.  This 
1305 makes a particularly big difference when superclass selectors are involved:
1306         op ($p1 ($p2 (df d)))
1307 We want all this to unravel in one sweeep.
1308
1309 Note [Avoid redundant simplification]
1310 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1311 Because RULES apply to simplified arguments, there's a danger of repeatedly
1312 simplifying already-simplified arguments.  An important example is that of
1313             (>>=) d e1 e2
1314 Here e1, e2 are simplified before the rule is applied, but don't really
1315 participate in the rule firing. So we mark them as Simplified to avoid
1316 re-simplifying them.
1317
1318 Note [Shadowing]
1319 ~~~~~~~~~~~~~~~~
1320 This part of the simplifier may break the no-shadowing invariant
1321 Consider
1322         f (...(\a -> e)...) (case y of (a,b) -> e')
1323 where f is strict in its second arg
1324 If we simplify the innermost one first we get (...(\a -> e)...)
1325 Simplifying the second arg makes us float the case out, so we end up with
1326         case y of (a,b) -> f (...(\a -> e)...) e'
1327 So the output does not have the no-shadowing invariant.  However, there is
1328 no danger of getting name-capture, because when the first arg was simplified
1329 we used an in-scope set that at least mentioned all the variables free in its
1330 static environment, and that is enough.
1331
1332 We can't just do innermost first, or we'd end up with a dual problem:
1333         case x of (a,b) -> f e (...(\a -> e')...)
1334
1335 I spent hours trying to recover the no-shadowing invariant, but I just could
1336 not think of an elegant way to do it.  The simplifier is already knee-deep in
1337 continuations.  We have to keep the right in-scope set around; AND we have
1338 to get the effect that finding (error "foo") in a strict arg position will
1339 discard the entire application and replace it with (error "foo").  Getting
1340 all this at once is TOO HARD!
1341
1342
1343 %************************************************************************
1344 %*                                                                      *
1345                 Rewrite rules
1346 %*                                                                      *
1347 %************************************************************************
1348
1349 \begin{code}
1350 tryRules :: SimplEnv -> [CoreRule]
1351          -> Id -> [OutExpr] -> SimplCont 
1352          -> SimplM (Maybe (Arity, CoreExpr))         -- The arity is the number of
1353                                                      -- args consumed by the rule
1354 tryRules env rules fn args call_cont
1355   | null rules
1356   = return Nothing
1357   | otherwise
1358   = do { dflags <- getDOptsSmpl
1359        ; case activeRule dflags env of {
1360            Nothing     -> return Nothing  ; -- No rules apply
1361            Just act_fn -> 
1362          case lookupRule act_fn (activeUnfInRule env) (getInScope env) fn args rules of {
1363            Nothing               -> return Nothing ;   -- No rule matches
1364            Just (rule, rule_rhs) ->
1365
1366              do { tick (RuleFired (ru_name rule))
1367                 ; trace_dump dflags rule rule_rhs $
1368                   return (Just (ruleArity rule, rule_rhs)) }}}}
1369   where
1370     trace_dump dflags rule rule_rhs stuff
1371       | not (dopt Opt_D_dump_rule_firings dflags) = stuff
1372       | not (dopt Opt_D_verbose_core2core dflags) 
1373
1374       = pprTrace "Rule fired:" (ftext (ru_name rule)) stuff
1375       | otherwise
1376       = pprTrace "Rule fired"
1377            (vcat [text "Rule:" <+> ftext (ru_name rule),
1378                   text "Before:" <+> ppr fn <+> sep (map pprParendExpr args),
1379                   text "After: " <+> pprCoreExpr rule_rhs,
1380                   text "Cont:  " <+> ppr call_cont])
1381            stuff
1382 \end{code}
1383
1384 Note [Rules for recursive functions]
1385 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1386 You might think that we shouldn't apply rules for a loop breaker:
1387 doing so might give rise to an infinite loop, because a RULE is
1388 rather like an extra equation for the function:
1389      RULE:           f (g x) y = x+y
1390      Eqn:            f a     y = a-y
1391
1392 But it's too drastic to disable rules for loop breakers.
1393 Even the foldr/build rule would be disabled, because foldr
1394 is recursive, and hence a loop breaker:
1395      foldr k z (build g) = g k z
1396 So it's up to the programmer: rules can cause divergence
1397
1398
1399 %************************************************************************
1400 %*                                                                      *
1401                 Rebuilding a cse expression
1402 %*                                                                      *
1403 %************************************************************************
1404
1405 Note [Case elimination]
1406 ~~~~~~~~~~~~~~~~~~~~~~~
1407 The case-elimination transformation discards redundant case expressions.
1408 Start with a simple situation:
1409
1410         case x# of      ===>   e[x#/y#]
1411           y# -> e
1412
1413 (when x#, y# are of primitive type, of course).  We can't (in general)
1414 do this for algebraic cases, because we might turn bottom into
1415 non-bottom!
1416
1417 The code in SimplUtils.prepareAlts has the effect of generalise this
1418 idea to look for a case where we're scrutinising a variable, and we
1419 know that only the default case can match.  For example:
1420
1421         case x of
1422           0#      -> ...
1423           DEFAULT -> ...(case x of
1424                          0#      -> ...
1425                          DEFAULT -> ...) ...
1426
1427 Here the inner case is first trimmed to have only one alternative, the
1428 DEFAULT, after which it's an instance of the previous case.  This
1429 really only shows up in eliminating error-checking code.
1430
1431 We also make sure that we deal with this very common case:
1432
1433         case e of
1434           x -> ...x...
1435
1436 Here we are using the case as a strict let; if x is used only once
1437 then we want to inline it.  We have to be careful that this doesn't
1438 make the program terminate when it would have diverged before, so we
1439 check that
1440         - e is already evaluated (it may so if e is a variable)
1441         - x is used strictly, or
1442
1443 Lastly, the code in SimplUtils.mkCase combines identical RHSs.  So
1444
1445         case e of       ===> case e of DEFAULT -> r
1446            True  -> r
1447            False -> r
1448
1449 Now again the case may be elminated by the CaseElim transformation.
1450
1451
1452 Further notes about case elimination
1453 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1454 Consider:       test :: Integer -> IO ()
1455                 test = print
1456
1457 Turns out that this compiles to:
1458     Print.test
1459       = \ eta :: Integer
1460           eta1 :: State# RealWorld ->
1461           case PrelNum.< eta PrelNum.zeroInteger of wild { __DEFAULT ->
1462           case hPutStr stdout
1463                  (PrelNum.jtos eta ($w[] @ Char))
1464                  eta1
1465           of wild1 { (# new_s, a4 #) -> PrelIO.lvl23 new_s  }}
1466
1467 Notice the strange '<' which has no effect at all. This is a funny one.
1468 It started like this:
1469
1470 f x y = if x < 0 then jtos x
1471           else if y==0 then "" else jtos x
1472
1473 At a particular call site we have (f v 1).  So we inline to get
1474
1475         if v < 0 then jtos x
1476         else if 1==0 then "" else jtos x
1477
1478 Now simplify the 1==0 conditional:
1479
1480         if v<0 then jtos v else jtos v
1481
1482 Now common-up the two branches of the case:
1483
1484         case (v<0) of DEFAULT -> jtos v
1485
1486 Why don't we drop the case?  Because it's strict in v.  It's technically
1487 wrong to drop even unnecessary evaluations, and in practice they
1488 may be a result of 'seq' so we *definitely* don't want to drop those.
1489 I don't really know how to improve this situation.
1490
1491 \begin{code}
1492 ---------------------------------------------------------
1493 --      Eliminate the case if possible
1494
1495 rebuildCase, reallyRebuildCase
1496    :: SimplEnv
1497    -> OutExpr          -- Scrutinee
1498    -> InId             -- Case binder
1499    -> [InAlt]          -- Alternatives (inceasing order)
1500    -> SimplCont
1501    -> SimplM (SimplEnv, OutExpr)
1502
1503 --------------------------------------------------
1504 --      1. Eliminate the case if there's a known constructor
1505 --------------------------------------------------
1506
1507 rebuildCase env scrut case_bndr alts cont
1508   | Lit lit <- scrut    -- No need for same treatment as constructors
1509                         -- because literals are inlined more vigorously
1510   = do  { tick (KnownBranch case_bndr)
1511         ; case findAlt (LitAlt lit) alts of
1512             Nothing           -> missingAlt env case_bndr alts cont
1513             Just (_, bs, rhs) -> simple_rhs bs rhs }
1514
1515   | Just (con, ty_args, other_args) <- exprIsConApp_maybe (activeUnfInRule env) scrut
1516         -- Works when the scrutinee is a variable with a known unfolding
1517         -- as well as when it's an explicit constructor application
1518   = do  { tick (KnownBranch case_bndr)
1519         ; case findAlt (DataAlt con) alts of
1520             Nothing  -> missingAlt env case_bndr alts cont
1521             Just (DEFAULT, bs, rhs) -> simple_rhs bs rhs
1522             Just (_, bs, rhs)       -> knownCon env scrut con ty_args other_args 
1523                                                 case_bndr bs rhs cont
1524         }
1525   where
1526     simple_rhs bs rhs = ASSERT( null bs ) 
1527                         do { env' <- simplNonRecX env case_bndr scrut
1528                            ; simplExprF env' rhs cont }
1529
1530
1531 --------------------------------------------------
1532 --      2. Eliminate the case if scrutinee is evaluated
1533 --------------------------------------------------
1534
1535 rebuildCase env scrut case_bndr [(_, bndrs, rhs)] cont
1536   -- See if we can get rid of the case altogether
1537   -- See Note [Case elimination] 
1538   -- mkCase made sure that if all the alternatives are equal,
1539   -- then there is now only one (DEFAULT) rhs
1540  | all isDeadBinder bndrs       -- bndrs are [InId]
1541
1542         -- Check that the scrutinee can be let-bound instead of case-bound
1543  , exprOkForSpeculation scrut
1544                 -- OK not to evaluate it
1545                 -- This includes things like (==# a# b#)::Bool
1546                 -- so that we simplify
1547                 --      case ==# a# b# of { True -> x; False -> x }
1548                 -- to just
1549                 --      x
1550                 -- This particular example shows up in default methods for
1551                 -- comparision operations (e.g. in (>=) for Int.Int32)
1552         || exprIsHNF scrut                      -- It's already evaluated
1553         || var_demanded_later scrut             -- It'll be demanded later
1554
1555 --      || not opt_SimplPedanticBottoms)        -- Or we don't care!
1556 --      We used to allow improving termination by discarding cases, unless -fpedantic-bottoms was on,
1557 --      but that breaks badly for the dataToTag# primop, which relies on a case to evaluate
1558 --      its argument:  case x of { y -> dataToTag# y }
1559 --      Here we must *not* discard the case, because dataToTag# just fetches the tag from
1560 --      the info pointer.  So we'll be pedantic all the time, and see if that gives any
1561 --      other problems
1562 --      Also we don't want to discard 'seq's
1563   = do  { tick (CaseElim case_bndr)
1564         ; env' <- simplNonRecX env case_bndr scrut
1565         ; simplExprF env' rhs cont }
1566   where
1567         -- The case binder is going to be evaluated later,
1568         -- and the scrutinee is a simple variable
1569     var_demanded_later (Var v) = isStrictDmd (idDemandInfo case_bndr)
1570                                  && not (isTickBoxOp v)
1571                                     -- ugly hack; covering this case is what
1572                                     -- exprOkForSpeculation was intended for.
1573     var_demanded_later _       = False
1574
1575 --------------------------------------------------
1576 --      3. Try seq rules; see Note [User-defined RULES for seq] in MkId
1577 --------------------------------------------------
1578
1579 rebuildCase env scrut case_bndr alts@[(_, bndrs, rhs)] cont
1580   | all isDeadBinder (case_bndr : bndrs)  -- So this is just 'seq'
1581   = do { let rhs' = substExpr (text "rebuild-case") env rhs
1582              out_args = [Type (substTy env (idType case_bndr)), 
1583                          Type (exprType rhs'), scrut, rhs']
1584                       -- Lazily evaluated, so we don't do most of this
1585
1586        ; rule_base <- getSimplRules
1587        ; mb_rule <- tryRules env (getRules rule_base seqId) seqId out_args cont
1588        ; case mb_rule of 
1589            Just (n_args, res) -> simplExprF (zapSubstEnv env) 
1590                                             (mkApps res (drop n_args out_args))
1591                                             cont
1592            Nothing -> reallyRebuildCase env scrut case_bndr alts cont }
1593
1594 rebuildCase env scrut case_bndr alts cont
1595   = reallyRebuildCase env scrut case_bndr alts cont
1596
1597 --------------------------------------------------
1598 --      3. Catch-all case
1599 --------------------------------------------------
1600
1601 reallyRebuildCase env scrut case_bndr alts cont
1602   = do  {       -- Prepare the continuation;
1603                 -- The new subst_env is in place
1604           (env', dup_cont, nodup_cont) <- prepareCaseCont env alts cont
1605
1606         -- Simplify the alternatives
1607         ; (scrut', case_bndr', alts') <- simplAlts env' scrut case_bndr alts dup_cont
1608
1609         -- Check for empty alternatives
1610         ; if null alts' then missingAlt env case_bndr alts cont
1611           else do
1612         { dflags <- getDOptsSmpl
1613         ; case_expr <- mkCase dflags scrut' case_bndr' alts'
1614
1615         -- Notice that rebuild gets the in-scope set from env', not alt_env
1616         -- (which in any case is only build in simplAlts)
1617         -- The case binder *not* scope over the whole returned case-expression
1618         ; rebuild env' case_expr nodup_cont } }
1619 \end{code}
1620
1621 simplCaseBinder checks whether the scrutinee is a variable, v.  If so,
1622 try to eliminate uses of v in the RHSs in favour of case_bndr; that
1623 way, there's a chance that v will now only be used once, and hence
1624 inlined.
1625
1626 Historical note: we use to do the "case binder swap" in the Simplifier
1627 so there were additional complications if the scrutinee was a variable.
1628 Now the binder-swap stuff is done in the occurrence analyer; see
1629 OccurAnal Note [Binder swap].
1630
1631 Note [zapOccInfo]
1632 ~~~~~~~~~~~~~~~~~
1633 If the case binder is not dead, then neither are the pattern bound
1634 variables:  
1635         case <any> of x { (a,b) ->
1636         case x of { (p,q) -> p } }
1637 Here (a,b) both look dead, but come alive after the inner case is eliminated.
1638 The point is that we bring into the envt a binding
1639         let x = (a,b)
1640 after the outer case, and that makes (a,b) alive.  At least we do unless
1641 the case binder is guaranteed dead.
1642
1643 In practice, the scrutinee is almost always a variable, so we pretty
1644 much always zap the OccInfo of the binders.  It doesn't matter much though.
1645
1646
1647 Note [Case of cast]
1648 ~~~~~~~~~~~~~~~~~~~
1649 Consider        case (v `cast` co) of x { I# y ->
1650                 ... (case (v `cast` co) of {...}) ...
1651 We'd like to eliminate the inner case.  We can get this neatly by
1652 arranging that inside the outer case we add the unfolding
1653         v |-> x `cast` (sym co)
1654 to v.  Then we should inline v at the inner case, cancel the casts, and away we go
1655
1656 Note [Improving seq]
1657 ~~~~~~~~~~~~~~~~~~~
1658 Consider
1659         type family F :: * -> *
1660         type instance F Int = Int
1661
1662         ... case e of x { DEFAULT -> rhs } ...
1663
1664 where x::F Int.  Then we'd like to rewrite (F Int) to Int, getting
1665
1666         case e `cast` co of x'::Int
1667            I# x# -> let x = x' `cast` sym co
1668                     in rhs
1669
1670 so that 'rhs' can take advantage of the form of x'.  
1671
1672 Notice that Note [Case of cast] may then apply to the result. 
1673
1674 Nota Bene: We only do the [Improving seq] transformation if the 
1675 case binder 'x' is actually used in the rhs; that is, if the case 
1676 is *not* a *pure* seq.  
1677   a) There is no point in adding the cast to a pure seq.
1678   b) There is a good reason not to: doing so would interfere 
1679      with seq rules (Note [Built-in RULES for seq] in MkId).
1680      In particular, this [Improving seq] thing *adds* a cast
1681      while [Built-in RULES for seq] *removes* one, so they
1682      just flip-flop.
1683
1684 You might worry about 
1685    case v of x { __DEFAULT ->
1686       ... case (v `cast` co) of y { I# -> ... }}
1687 This is a pure seq (since x is unused), so [Improving seq] won't happen.
1688 But it's ok: the simplifier will replace 'v' by 'x' in the rhs to get
1689    case v of x { __DEFAULT ->
1690       ... case (x `cast` co) of y { I# -> ... }}
1691 Now the outer case is not a pure seq, so [Improving seq] will happen,
1692 and then the inner case will disappear.
1693
1694 The need for [Improving seq] showed up in Roman's experiments.  Example:
1695   foo :: F Int -> Int -> Int
1696   foo t n = t `seq` bar n
1697      where
1698        bar 0 = 0
1699        bar n = bar (n - case t of TI i -> i)
1700 Here we'd like to avoid repeated evaluating t inside the loop, by
1701 taking advantage of the `seq`.
1702
1703 At one point I did transformation in LiberateCase, but it's more
1704 robust here.  (Otherwise, there's a danger that we'll simply drop the
1705 'seq' altogether, before LiberateCase gets to see it.)
1706
1707 \begin{code}
1708 simplAlts :: SimplEnv
1709           -> OutExpr
1710           -> InId                       -- Case binder
1711           -> [InAlt]                    -- Non-empty
1712           -> SimplCont
1713           -> SimplM (OutExpr, OutId, [OutAlt])  -- Includes the continuation
1714 -- Like simplExpr, this just returns the simplified alternatives;
1715 -- it does not return an environment
1716
1717 simplAlts env scrut case_bndr alts cont'
1718   = -- pprTrace "simplAlts" (ppr alts $$ ppr (seTvSubst env)) $
1719     do  { let env0 = zapFloats env
1720
1721         ; (env1, case_bndr1) <- simplBinder env0 case_bndr
1722
1723         ; fam_envs <- getFamEnvs
1724         ; (alt_env', scrut', case_bndr') <- improveSeq fam_envs env1 scrut 
1725                                                        case_bndr case_bndr1 alts
1726
1727         ; (imposs_deflt_cons, in_alts) <- prepareAlts scrut' case_bndr' alts
1728
1729         ; alts' <- mapM (simplAlt alt_env' imposs_deflt_cons case_bndr' cont') in_alts
1730         ; return (scrut', case_bndr', alts') }
1731
1732
1733 ------------------------------------
1734 improveSeq :: (FamInstEnv, FamInstEnv) -> SimplEnv
1735            -> OutExpr -> InId -> OutId -> [InAlt]
1736            -> SimplM (SimplEnv, OutExpr, OutId)
1737 -- Note [Improving seq]
1738 improveSeq fam_envs env scrut case_bndr case_bndr1 [(DEFAULT,_,_)]
1739   | not (isDeadBinder case_bndr)        -- Not a pure seq!  See the Note!
1740   , Just (co, ty2) <- topNormaliseType fam_envs (idType case_bndr1)
1741   = do { case_bndr2 <- newId (fsLit "nt") ty2
1742         ; let rhs  = DoneEx (Var case_bndr2 `Cast` mkSymCoercion co)
1743               env2 = extendIdSubst env case_bndr rhs
1744         ; return (env2, scrut `Cast` co, case_bndr2) }
1745
1746 improveSeq _ env scrut _ case_bndr1 _
1747   = return (env, scrut, case_bndr1)
1748
1749
1750 ------------------------------------
1751 simplAlt :: SimplEnv
1752          -> [AltCon]    -- These constructors can't be present when
1753                         -- matching the DEFAULT alternative
1754          -> OutId       -- The case binder
1755          -> SimplCont
1756          -> InAlt
1757          -> SimplM OutAlt
1758
1759 simplAlt env imposs_deflt_cons case_bndr' cont' (DEFAULT, bndrs, rhs)
1760   = ASSERT( null bndrs )
1761     do  { let env' = addBinderOtherCon env case_bndr' imposs_deflt_cons
1762                 -- Record the constructors that the case-binder *can't* be.
1763         ; rhs' <- simplExprC env' rhs cont'
1764         ; return (DEFAULT, [], rhs') }
1765
1766 simplAlt env _ case_bndr' cont' (LitAlt lit, bndrs, rhs)
1767   = ASSERT( null bndrs )
1768     do  { let env' = addBinderUnfolding env case_bndr' (Lit lit)
1769         ; rhs' <- simplExprC env' rhs cont'
1770         ; return (LitAlt lit, [], rhs') }
1771
1772 simplAlt env _ case_bndr' cont' (DataAlt con, vs, rhs)
1773   = do  {       -- Deal with the pattern-bound variables
1774                 -- Mark the ones that are in ! positions in the
1775                 -- data constructor as certainly-evaluated.
1776                 -- NB: simplLamBinders preserves this eval info
1777           let vs_with_evals = add_evals (dataConRepStrictness con)
1778         ; (env', vs') <- simplLamBndrs env vs_with_evals
1779
1780                 -- Bind the case-binder to (con args)
1781         ; let inst_tys' = tyConAppArgs (idType case_bndr')
1782               con_args  = map Type inst_tys' ++ varsToCoreExprs vs'
1783               env''     = addBinderUnfolding env' case_bndr'
1784                                              (mkConApp con con_args)
1785
1786         ; rhs' <- simplExprC env'' rhs cont'
1787         ; return (DataAlt con, vs', rhs') }
1788   where
1789         -- add_evals records the evaluated-ness of the bound variables of
1790         -- a case pattern.  This is *important*.  Consider
1791         --      data T = T !Int !Int
1792         --
1793         --      case x of { T a b -> T (a+1) b }
1794         --
1795         -- We really must record that b is already evaluated so that we don't
1796         -- go and re-evaluate it when constructing the result.
1797         -- See Note [Data-con worker strictness] in MkId.lhs
1798     add_evals the_strs
1799         = go vs the_strs
1800         where
1801           go [] [] = []
1802           go (v:vs') strs | isTyCoVar v = v : go vs' strs
1803           go (v:vs') (str:strs)
1804             | isMarkedStrict str = evald_v  : go vs' strs
1805             | otherwise          = zapped_v : go vs' strs
1806             where
1807               zapped_v = zap_occ_info v
1808               evald_v  = zapped_v `setIdUnfolding` evaldUnfolding
1809           go _ _ = pprPanic "cat_evals" (ppr con $$ ppr vs $$ ppr the_strs)
1810
1811         -- See Note [zapOccInfo]
1812         -- zap_occ_info: if the case binder is alive, then we add the unfolding
1813         --      case_bndr = C vs
1814         -- to the envt; so vs are now very much alive
1815         -- Note [Aug06] I can't see why this actually matters, but it's neater
1816         --        case e of t { (a,b) -> ...(case t of (p,q) -> p)... }
1817         --   ==>  case e of t { (a,b) -> ...(a)... }
1818         -- Look, Ma, a is alive now.
1819     zap_occ_info = zapCasePatIdOcc case_bndr'
1820
1821 addBinderUnfolding :: SimplEnv -> Id -> CoreExpr -> SimplEnv
1822 addBinderUnfolding env bndr rhs
1823   = modifyInScope env (bndr `setIdUnfolding` mkSimpleUnfolding rhs)
1824
1825 addBinderOtherCon :: SimplEnv -> Id -> [AltCon] -> SimplEnv
1826 addBinderOtherCon env bndr cons
1827   = modifyInScope env (bndr `setIdUnfolding` mkOtherCon cons)
1828
1829 zapCasePatIdOcc :: Id -> Id -> Id
1830 -- Consider  case e of b { (a,b) -> ... }
1831 -- Then if we bind b to (a,b) in "...", and b is not dead,
1832 -- then we must zap the deadness info on a,b
1833 zapCasePatIdOcc case_bndr
1834   | isDeadBinder case_bndr = \ pat_id -> pat_id
1835   | otherwise              = \ pat_id -> zapIdOccInfo pat_id
1836 \end{code}
1837
1838
1839 %************************************************************************
1840 %*                                                                      *
1841 \subsection{Known constructor}
1842 %*                                                                      *
1843 %************************************************************************
1844
1845 We are a bit careful with occurrence info.  Here's an example
1846
1847         (\x* -> case x of (a*, b) -> f a) (h v, e)
1848
1849 where the * means "occurs once".  This effectively becomes
1850         case (h v, e) of (a*, b) -> f a)
1851 and then
1852         let a* = h v; b = e in f a
1853 and then
1854         f (h v)
1855
1856 All this should happen in one sweep.
1857
1858 \begin{code}
1859 knownCon :: SimplEnv            
1860          -> OutExpr                             -- The scrutinee
1861          -> DataCon -> [OutType] -> [OutExpr]   -- The scrutinee (in pieces)
1862          -> InId -> [InBndr] -> InExpr          -- The alternative
1863          -> SimplCont
1864          -> SimplM (SimplEnv, OutExpr)
1865
1866 knownCon env scrut dc dc_ty_args dc_args bndr bs rhs cont
1867   = do  { env'  <- bind_args env bs dc_args
1868         ; env'' <- bind_case_bndr env'
1869         ; simplExprF env'' rhs cont }
1870   where
1871     zap_occ = zapCasePatIdOcc bndr    -- bndr is an InId
1872
1873                   -- Ugh!
1874     bind_args env' [] _  = return env'
1875
1876     bind_args env' (b:bs') (Type ty : args)
1877       = ASSERT( isTyCoVar b )
1878         bind_args (extendTvSubst env' b ty) bs' args
1879
1880     bind_args env' (b:bs') (arg : args)
1881       = ASSERT( isId b )
1882         do { let b' = zap_occ b
1883              -- Note that the binder might be "dead", because it doesn't
1884              -- occur in the RHS; and simplNonRecX may therefore discard
1885              -- it via postInlineUnconditionally.
1886              -- Nevertheless we must keep it if the case-binder is alive,
1887              -- because it may be used in the con_app.  See Note [zapOccInfo]
1888            ; env'' <- simplNonRecX env' b' arg
1889            ; bind_args env'' bs' args }
1890
1891     bind_args _ _ _ =
1892       pprPanic "bind_args" $ ppr dc $$ ppr bs $$ ppr dc_args $$
1893                              text "scrut:" <+> ppr scrut
1894
1895        -- It's useful to bind bndr to scrut, rather than to a fresh
1896        -- binding      x = Con arg1 .. argn
1897        -- because very often the scrut is a variable, so we avoid
1898        -- creating, and then subsequently eliminating, a let-binding
1899        -- BUT, if scrut is a not a variable, we must be careful
1900        -- about duplicating the arg redexes; in that case, make
1901        -- a new con-app from the args
1902     bind_case_bndr env
1903       | isDeadBinder bndr   = return env
1904       | exprIsTrivial scrut = return (extendIdSubst env bndr (DoneEx scrut))
1905       | otherwise           = do { dc_args <- mapM (simplVar env) bs
1906                                          -- dc_ty_args are aready OutTypes, 
1907                                          -- but bs are InBndrs
1908                                  ; let con_app = Var (dataConWorkId dc) 
1909                                                  `mkTyApps` dc_ty_args      
1910                                                  `mkApps`   dc_args
1911                                  ; simplNonRecX env bndr con_app }
1912   
1913 -------------------
1914 missingAlt :: SimplEnv -> Id -> [InAlt] -> SimplCont -> SimplM (SimplEnv, OutExpr)
1915                 -- This isn't strictly an error, although it is unusual. 
1916                 -- It's possible that the simplifer might "see" that 
1917                 -- an inner case has no accessible alternatives before 
1918                 -- it "sees" that the entire branch of an outer case is 
1919                 -- inaccessible.  So we simply put an error case here instead.
1920 missingAlt env case_bndr alts cont
1921   = WARN( True, ptext (sLit "missingAlt") <+> ppr case_bndr )
1922     return (env, mkImpossibleExpr res_ty)
1923   where
1924     res_ty = contResultType env (substTy env (coreAltsType alts)) cont
1925 \end{code}
1926
1927
1928 %************************************************************************
1929 %*                                                                      *
1930 \subsection{Duplicating continuations}
1931 %*                                                                      *
1932 %************************************************************************
1933
1934 \begin{code}
1935 prepareCaseCont :: SimplEnv
1936                 -> [InAlt] -> SimplCont
1937                 -> SimplM (SimplEnv, SimplCont,SimplCont)
1938                         -- Return a duplicatable continuation, a non-duplicable part
1939                         -- plus some extra bindings (that scope over the entire
1940                         -- continunation)
1941
1942         -- No need to make it duplicatable if there's only one alternative
1943 prepareCaseCont env [_] cont = return (env, cont, mkBoringStop)
1944 prepareCaseCont env _   cont = mkDupableCont env cont
1945 \end{code}
1946
1947 \begin{code}
1948 mkDupableCont :: SimplEnv -> SimplCont
1949               -> SimplM (SimplEnv, SimplCont, SimplCont)
1950
1951 mkDupableCont env cont
1952   | contIsDupable cont
1953   = return (env, cont, mkBoringStop)
1954
1955 mkDupableCont _   (Stop {}) = panic "mkDupableCont"     -- Handled by previous eqn
1956
1957 mkDupableCont env (CoerceIt ty cont)
1958   = do  { (env', dup, nodup) <- mkDupableCont env cont
1959         ; return (env', CoerceIt ty dup, nodup) }
1960
1961 mkDupableCont env cont@(StrictBind {})
1962   =  return (env, mkBoringStop, cont)
1963         -- See Note [Duplicating StrictBind]
1964
1965 mkDupableCont env (StrictArg info cci cont)
1966         -- See Note [Duplicating StrictArg]
1967   = do { (env', dup, nodup) <- mkDupableCont env cont
1968        ; (env'', args')     <- mapAccumLM (makeTrivial NotTopLevel) env' (ai_args info)
1969        ; return (env'', StrictArg (info { ai_args = args' }) cci dup, nodup) }
1970
1971 mkDupableCont env (ApplyTo _ arg se cont)
1972   =     -- e.g.         [...hole...] (...arg...)
1973         --      ==>
1974         --              let a = ...arg...
1975         --              in [...hole...] a
1976     do  { (env', dup_cont, nodup_cont) <- mkDupableCont env cont
1977         ; arg' <- simplExpr (se `setInScope` env') arg
1978         ; (env'', arg'') <- makeTrivial NotTopLevel env' arg'
1979         ; let app_cont = ApplyTo OkToDup arg'' (zapSubstEnv env'') dup_cont
1980         ; return (env'', app_cont, nodup_cont) }
1981
1982 mkDupableCont env cont@(Select _ case_bndr [(_, bs, _rhs)] _ _)
1983 --  See Note [Single-alternative case]
1984 --  | not (exprIsDupable rhs && contIsDupable case_cont)
1985 --  | not (isDeadBinder case_bndr)
1986   | all isDeadBinder bs  -- InIds
1987     && not (isUnLiftedType (idType case_bndr))
1988     -- Note [Single-alternative-unlifted]
1989   = return (env, mkBoringStop, cont)
1990
1991 mkDupableCont env (Select _ case_bndr alts se cont)
1992   =     -- e.g.         (case [...hole...] of { pi -> ei })
1993         --      ===>
1994         --              let ji = \xij -> ei
1995         --              in case [...hole...] of { pi -> ji xij }
1996     do  { tick (CaseOfCase case_bndr)
1997         ; (env', dup_cont, nodup_cont) <- mkDupableCont env cont
1998                 -- NB: call mkDupableCont here, *not* prepareCaseCont
1999                 -- We must make a duplicable continuation, whereas prepareCaseCont
2000                 -- doesn't when there is a single case branch
2001
2002         ; let alt_env = se `setInScope` env'
2003         ; (alt_env', case_bndr') <- simplBinder alt_env case_bndr
2004         ; alts' <- mapM (simplAlt alt_env' [] case_bndr' dup_cont) alts
2005         -- Safe to say that there are no handled-cons for the DEFAULT case
2006                 -- NB: simplBinder does not zap deadness occ-info, so
2007                 -- a dead case_bndr' will still advertise its deadness
2008                 -- This is really important because in
2009                 --      case e of b { (# p,q #) -> ... }
2010                 -- b is always dead, and indeed we are not allowed to bind b to (# p,q #),
2011                 -- which might happen if e was an explicit unboxed pair and b wasn't marked dead.
2012                 -- In the new alts we build, we have the new case binder, so it must retain
2013                 -- its deadness.
2014         -- NB: we don't use alt_env further; it has the substEnv for
2015         --     the alternatives, and we don't want that
2016
2017         ; (env'', alts'') <- mkDupableAlts env' case_bndr' alts'
2018         ; return (env'',  -- Note [Duplicated env]
2019                   Select OkToDup case_bndr' alts'' (zapSubstEnv env'') mkBoringStop,
2020                   nodup_cont) }
2021
2022
2023 mkDupableAlts :: SimplEnv -> OutId -> [InAlt]
2024               -> SimplM (SimplEnv, [InAlt])
2025 -- Absorbs the continuation into the new alternatives
2026
2027 mkDupableAlts env case_bndr' the_alts
2028   = go env the_alts
2029   where
2030     go env0 [] = return (env0, [])
2031     go env0 (alt:alts)
2032         = do { (env1, alt') <- mkDupableAlt env0 case_bndr' alt
2033              ; (env2, alts') <- go env1 alts
2034              ; return (env2, alt' : alts' ) }
2035
2036 mkDupableAlt :: SimplEnv -> OutId -> (AltCon, [CoreBndr], CoreExpr)
2037               -> SimplM (SimplEnv, (AltCon, [CoreBndr], CoreExpr))
2038 mkDupableAlt env case_bndr (con, bndrs', rhs')
2039   | exprIsDupable rhs'  -- Note [Small alternative rhs]
2040   = return (env, (con, bndrs', rhs'))
2041   | otherwise
2042   = do  { let rhs_ty'  = exprType rhs'
2043               scrut_ty = idType case_bndr
2044               case_bndr_w_unf   
2045                 = case con of 
2046                       DEFAULT    -> case_bndr                                   
2047                       DataAlt dc -> setIdUnfolding case_bndr unf
2048                           where
2049                                  -- See Note [Case binders and join points]
2050                              unf = mkInlineUnfolding Nothing rhs
2051                              rhs = mkConApp dc (map Type (tyConAppArgs scrut_ty)
2052                                                 ++ varsToCoreExprs bndrs')
2053
2054                       LitAlt {} -> WARN( True, ptext (sLit "mkDupableAlt")
2055                                                 <+> ppr case_bndr <+> ppr con )
2056                                    case_bndr
2057                            -- The case binder is alive but trivial, so why has 
2058                            -- it not been substituted away?
2059
2060               used_bndrs' | isDeadBinder case_bndr = filter abstract_over bndrs'
2061                           | otherwise              = bndrs' ++ [case_bndr_w_unf]
2062               
2063               abstract_over bndr
2064                   | isTyCoVar bndr = True -- Abstract over all type variables just in case
2065                   | otherwise    = not (isDeadBinder bndr)
2066                         -- The deadness info on the new Ids is preserved by simplBinders
2067
2068         ; (final_bndrs', final_args)    -- Note [Join point abstraction]
2069                 <- if (any isId used_bndrs')
2070                    then return (used_bndrs', varsToCoreExprs used_bndrs')
2071                     else do { rw_id <- newId (fsLit "w") realWorldStatePrimTy
2072                             ; return ([rw_id], [Var realWorldPrimId]) }
2073
2074         ; join_bndr <- newId (fsLit "$j") (mkPiTypes final_bndrs' rhs_ty')
2075                 -- Note [Funky mkPiTypes]
2076
2077         ; let   -- We make the lambdas into one-shot-lambdas.  The
2078                 -- join point is sure to be applied at most once, and doing so
2079                 -- prevents the body of the join point being floated out by
2080                 -- the full laziness pass
2081                 really_final_bndrs     = map one_shot final_bndrs'
2082                 one_shot v | isId v    = setOneShotLambda v
2083                            | otherwise = v
2084                 join_rhs  = mkLams really_final_bndrs rhs'
2085                 join_call = mkApps (Var join_bndr) final_args
2086
2087         ; env' <- addPolyBind NotTopLevel env (NonRec join_bndr join_rhs)
2088         ; return (env', (con, bndrs', join_call)) }
2089                 -- See Note [Duplicated env]
2090 \end{code}
2091
2092 Note [Case binders and join points]
2093 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2094 Consider this 
2095    case (case .. ) of c {
2096      I# c# -> ....c....
2097
2098 If we make a join point with c but not c# we get
2099   $j = \c -> ....c....
2100
2101 But if later inlining scrutines the c, thus
2102
2103   $j = \c -> ... case c of { I# y -> ... } ...
2104
2105 we won't see that 'c' has already been scrutinised.  This actually
2106 happens in the 'tabulate' function in wave4main, and makes a significant
2107 difference to allocation.
2108
2109 An alternative plan is this:
2110
2111    $j = \c# -> let c = I# c# in ...c....
2112
2113 but that is bad if 'c' is *not* later scrutinised.  
2114
2115 So instead we do both: we pass 'c' and 'c#' , and record in c's inlining
2116 (an InlineRule) that it's really I# c#, thus
2117    
2118    $j = \c# -> \c[=I# c#] -> ...c....
2119
2120 Absence analysis may later discard 'c'.
2121
2122 NB: take great care when doing strictness analysis; 
2123     see Note [Lamba-bound unfoldings] in DmdAnal.
2124
2125 Also note that we can still end up passing stuff that isn't used.  Before
2126 strictness analysis we have
2127    let $j x y c{=(x,y)} = (h c, ...)
2128    in ...
2129 After strictness analysis we see that h is strict, we end up with
2130    let $j x y c{=(x,y)} = ($wh x y, ...)
2131 and c is unused.
2132    
2133 Note [Duplicated env]
2134 ~~~~~~~~~~~~~~~~~~~~~
2135 Some of the alternatives are simplified, but have not been turned into a join point
2136 So they *must* have an zapped subst-env.  So we can't use completeNonRecX to
2137 bind the join point, because it might to do PostInlineUnconditionally, and
2138 we'd lose that when zapping the subst-env.  We could have a per-alt subst-env,
2139 but zapping it (as we do in mkDupableCont, the Select case) is safe, and
2140 at worst delays the join-point inlining.
2141
2142 Note [Small alternative rhs]
2143 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2144 It is worth checking for a small RHS because otherwise we
2145 get extra let bindings that may cause an extra iteration of the simplifier to
2146 inline back in place.  Quite often the rhs is just a variable or constructor.
2147 The Ord instance of Maybe in PrelMaybe.lhs, for example, took several extra
2148 iterations because the version with the let bindings looked big, and so wasn't
2149 inlined, but after the join points had been inlined it looked smaller, and so
2150 was inlined.
2151
2152 NB: we have to check the size of rhs', not rhs.
2153 Duplicating a small InAlt might invalidate occurrence information
2154 However, if it *is* dupable, we return the *un* simplified alternative,
2155 because otherwise we'd need to pair it up with an empty subst-env....
2156 but we only have one env shared between all the alts.
2157 (Remember we must zap the subst-env before re-simplifying something).
2158 Rather than do this we simply agree to re-simplify the original (small) thing later.
2159
2160 Note [Funky mkPiTypes]
2161 ~~~~~~~~~~~~~~~~~~~~~~
2162 Notice the funky mkPiTypes.  If the contructor has existentials
2163 it's possible that the join point will be abstracted over
2164 type varaibles as well as term variables.
2165  Example:  Suppose we have
2166         data T = forall t.  C [t]
2167  Then faced with
2168         case (case e of ...) of
2169             C t xs::[t] -> rhs
2170  We get the join point
2171         let j :: forall t. [t] -> ...
2172             j = /\t \xs::[t] -> rhs
2173         in
2174         case (case e of ...) of
2175             C t xs::[t] -> j t xs
2176
2177 Note [Join point abstaction]
2178 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2179 If we try to lift a primitive-typed something out
2180 for let-binding-purposes, we will *caseify* it (!),
2181 with potentially-disastrous strictness results.  So
2182 instead we turn it into a function: \v -> e
2183 where v::State# RealWorld#.  The value passed to this function
2184 is realworld#, which generates (almost) no code.
2185
2186 There's a slight infelicity here: we pass the overall
2187 case_bndr to all the join points if it's used in *any* RHS,
2188 because we don't know its usage in each RHS separately
2189
2190 We used to say "&& isUnLiftedType rhs_ty'" here, but now
2191 we make the join point into a function whenever used_bndrs'
2192 is empty.  This makes the join-point more CPR friendly.
2193 Consider:       let j = if .. then I# 3 else I# 4
2194                 in case .. of { A -> j; B -> j; C -> ... }
2195
2196 Now CPR doesn't w/w j because it's a thunk, so
2197 that means that the enclosing function can't w/w either,
2198 which is a lose.  Here's the example that happened in practice:
2199         kgmod :: Int -> Int -> Int
2200         kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
2201                     then 78
2202                     else 5
2203
2204 I have seen a case alternative like this:
2205         True -> \v -> ...
2206 It's a bit silly to add the realWorld dummy arg in this case, making
2207         $j = \s v -> ...
2208            True -> $j s
2209 (the \v alone is enough to make CPR happy) but I think it's rare
2210
2211 Note [Duplicating StrictArg]
2212 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2213 The original plan had (where E is a big argument)
2214 e.g.    f E [..hole..]
2215         ==>     let $j = \a -> f E a
2216                 in $j [..hole..]
2217
2218 But this is terrible! Here's an example:
2219         && E (case x of { T -> F; F -> T })
2220 Now, && is strict so we end up simplifying the case with
2221 an ArgOf continuation.  If we let-bind it, we get
2222         let $j = \v -> && E v
2223         in simplExpr (case x of { T -> F; F -> T })
2224                      (ArgOf (\r -> $j r)
2225 And after simplifying more we get
2226         let $j = \v -> && E v
2227         in case x of { T -> $j F; F -> $j T }
2228 Which is a Very Bad Thing
2229
2230 What we do now is this
2231         f E [..hole..]
2232         ==>     let a = E
2233                 in f a [..hole..]
2234 Now if the thing in the hole is a case expression (which is when
2235 we'll call mkDupableCont), we'll push the function call into the
2236 branches, which is what we want.  Now RULES for f may fire, and
2237 call-pattern specialisation.  Here's an example from Trac #3116
2238      go (n+1) (case l of
2239                  1  -> bs'
2240                  _  -> Chunk p fpc (o+1) (l-1) bs')
2241 If we can push the call for 'go' inside the case, we get
2242 call-pattern specialisation for 'go', which is *crucial* for 
2243 this program.
2244
2245 Here is the (&&) example: 
2246         && E (case x of { T -> F; F -> T })
2247   ==>   let a = E in 
2248         case x of { T -> && a F; F -> && a T }
2249 Much better!
2250
2251 Notice that 
2252   * Arguments to f *after* the strict one are handled by 
2253     the ApplyTo case of mkDupableCont.  Eg
2254         f [..hole..] E
2255
2256   * We can only do the let-binding of E because the function
2257     part of a StrictArg continuation is an explicit syntax
2258     tree.  In earlier versions we represented it as a function
2259     (CoreExpr -> CoreEpxr) which we couldn't take apart.
2260
2261 Do *not* duplicate StrictBind and StritArg continuations.  We gain
2262 nothing by propagating them into the expressions, and we do lose a
2263 lot.  
2264
2265 The desire not to duplicate is the entire reason that
2266 mkDupableCont returns a pair of continuations.
2267
2268 Note [Duplicating StrictBind]
2269 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2270 Unlike StrictArg, there doesn't seem anything to gain from
2271 duplicating a StrictBind continuation, so we don't.
2272
2273 The desire not to duplicate is the entire reason that
2274 mkDupableCont returns a pair of continuations.
2275
2276
2277 Note [Single-alternative cases]
2278 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2279 This case is just like the ArgOf case.  Here's an example:
2280         data T a = MkT !a
2281         ...(MkT (abs x))...
2282 Then we get
2283         case (case x of I# x' ->
2284               case x' <# 0# of
2285                 True  -> I# (negate# x')
2286                 False -> I# x') of y {
2287           DEFAULT -> MkT y
2288 Because the (case x) has only one alternative, we'll transform to
2289         case x of I# x' ->
2290         case (case x' <# 0# of
2291                 True  -> I# (negate# x')
2292                 False -> I# x') of y {
2293           DEFAULT -> MkT y
2294 But now we do *NOT* want to make a join point etc, giving
2295         case x of I# x' ->
2296         let $j = \y -> MkT y
2297         in case x' <# 0# of
2298                 True  -> $j (I# (negate# x'))
2299                 False -> $j (I# x')
2300 In this case the $j will inline again, but suppose there was a big
2301 strict computation enclosing the orginal call to MkT.  Then, it won't
2302 "see" the MkT any more, because it's big and won't get duplicated.
2303 And, what is worse, nothing was gained by the case-of-case transform.
2304
2305 So, in circumstances like these, we don't want to build join points
2306 and push the outer case into the branches of the inner one. Instead,
2307 don't duplicate the continuation. 
2308
2309 When should we use this strategy?  We should not use it on *every*
2310 single-alternative case:
2311   e.g.  case (case ....) of (a,b) -> (# a,b #)
2312 Here we must push the outer case into the inner one!
2313 Other choices:
2314
2315    * Match [(DEFAULT,_,_)], but in the common case of Int,
2316      the alternative-filling-in code turned the outer case into
2317                 case (...) of y { I# _ -> MkT y }
2318
2319    * Match on single alternative plus (not (isDeadBinder case_bndr))
2320      Rationale: pushing the case inwards won't eliminate the construction.
2321      But there's a risk of
2322                 case (...) of y { (a,b) -> let z=(a,b) in ... }
2323      Now y looks dead, but it'll come alive again.  Still, this
2324      seems like the best option at the moment.
2325
2326    * Match on single alternative plus (all (isDeadBinder bndrs))
2327      Rationale: this is essentially  seq.
2328
2329    * Match when the rhs is *not* duplicable, and hence would lead to a
2330      join point.  This catches the disaster-case above.  We can test
2331      the *un-simplified* rhs, which is fine.  It might get bigger or
2332      smaller after simplification; if it gets smaller, this case might
2333      fire next time round.  NB also that we must test contIsDupable
2334      case_cont *too, because case_cont might be big!
2335
2336      HOWEVER: I found that this version doesn't work well, because
2337      we can get         let x = case (...) of { small } in ...case x...
2338      When x is inlined into its full context, we find that it was a bad
2339      idea to have pushed the outer case inside the (...) case.
2340
2341 Note [Single-alternative-unlifted]
2342 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2343 Here's another single-alternative where we really want to do case-of-case:
2344
2345 data Mk1 = Mk1 Int#
2346 data Mk1 = Mk2 Int#
2347
2348 M1.f =
2349     \r [x_s74 y_s6X]
2350         case
2351             case y_s6X of tpl_s7m {
2352               M1.Mk1 ipv_s70 -> ipv_s70;
2353               M1.Mk2 ipv_s72 -> ipv_s72;
2354             }
2355         of
2356         wild_s7c
2357         { __DEFAULT ->
2358               case
2359                   case x_s74 of tpl_s7n {
2360                     M1.Mk1 ipv_s77 -> ipv_s77;
2361                     M1.Mk2 ipv_s79 -> ipv_s79;
2362                   }
2363               of
2364               wild1_s7b
2365               { __DEFAULT -> ==# [wild1_s7b wild_s7c];
2366               };
2367         };
2368
2369 So the outer case is doing *nothing at all*, other than serving as a
2370 join-point.  In this case we really want to do case-of-case and decide
2371 whether to use a real join point or just duplicate the continuation.
2372
2373 Hence: check whether the case binder's type is unlifted, because then
2374 the outer case is *not* a seq.