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