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