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