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