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