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