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