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