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