[project @ 2001-02-26 15:42:24 by simonpj]
[ghc-hetmet.git] / ghc / compiler / simplCore / Simplify.lhs
index 9d44435..131b56c 100644 (file)
 %
-% (c) The AQUA Project, Glasgow University, 1993-1996
+% (c) The AQUA Project, Glasgow University, 1993-1998
 %
 \section[Simplify]{The main module of the simplifier}
 
 \begin{code}
-#include "HsVersions.h"
-
-module Simplify ( simplTopBinds, simplExpr, simplBind ) where
+module Simplify ( simplTopBinds, simplExpr ) where
 
-IMP_Ubiq(){-uitous-}
-IMPORT_DELOOPER(SmplLoop)              -- paranoia checking
-IMPORT_1_3(List(partition))
+#include "HsVersions.h"
 
-import BinderInfo
-import CmdLineOpts     ( SimplifierSwitch(..) )
-import ConFold         ( completePrim )
-import CoreUnfold      ( Unfolding, SimpleUnfolding, mkFormSummary, FormSummary(..) )
-import CostCentre      ( isSccCountCostCentre, cmpCostCentre )
+import CmdLineOpts     ( switchIsOn, opt_SimplDoEtaReduction,
+                         opt_SimplNoPreInlining, 
+                         dopt, DynFlag(Opt_D_dump_inlinings),
+                         SimplifierSwitch(..)
+                       )
+import SimplMonad
+import SimplUtils      ( mkCase, tryRhsTyLam, tryEtaExpansion,
+                         simplBinder, simplBinders, simplIds, 
+                         SimplCont(..), DupFlag(..), mkStop, mkRhsStop,
+                         contResultType, discardInline, countArgs, contIsDupable,
+                         getContArgs, interestingCallContext, interestingArg, isStrictType
+                       )
+import Var             ( mkSysTyVar, tyVarKind )
+import VarEnv
+import Id              ( Id, idType, idInfo, isDataConId, hasNoBinding,
+                         idUnfolding, setIdUnfolding, isExportedId, isDeadBinder,
+                         idDemandInfo, setIdInfo,
+                         idOccInfo, setIdOccInfo, 
+                         zapLamIdInfo, setOneShotLambda, 
+                       )
+import IdInfo          ( OccInfo(..), isDeadOcc, isLoopBreaker,
+                         setArityInfo, 
+                         setUnfoldingInfo, atLeastArity,
+                         occInfo
+                       )
+import Demand          ( isStrict )
+import DataCon         ( dataConNumInstArgs, dataConRepStrictness,
+                         dataConSig, dataConArgTys
+                       )
 import CoreSyn
-import CoreUtils       ( coreExprType, nonErrorRHSs, maybeErrorApp,
-                         unTagBinders, squashableDictishCcExpr
+import PprCore         ( pprParendExpr, pprCoreExpr )
+import CoreFVs         ( mustHaveLocalBinding )
+import CoreUnfold      ( mkOtherCon, mkUnfolding, otherCons,
+                         callSiteInline
                        )
-import Id              ( idType, idWantsToBeINLINEd, addIdArity, 
-                         getIdDemandInfo, addIdDemandInfo,
-                         GenId{-instance NamedThing-}
+import CoreUtils       ( cheapEqExpr, exprIsDupable, exprIsTrivial, 
+                         exprIsConApp_maybe, mkPiType, findAlt, findDefault,
+                         exprType, coreAltsType, exprIsValue, 
+                         exprOkForSpeculation, exprArity, exprIsCheap,
+                         mkCoerce, mkSCC, mkInlineMe, mkAltExpr
                        )
-import Name            ( isExported )
-import IdInfo          ( willBeDemanded, noDemandInfo, DemandInfo, ArityInfo(..),
-                         atLeastArity, unknownArity )
-import Literal         ( isNoRepLit )
-import Maybes          ( maybeToBool )
---import Name          ( isExported )
-import PprStyle                ( PprStyle(..) )
-import PprType         ( GenType{-instance Outputable-} )
-import Pretty          ( ppAbove )
-import PrimOp          ( primOpOkForSpeculation, PrimOp(..) )
-import SimplCase       ( simplCase, bindLargeRhs )
-import SimplEnv
-import SimplMonad
-import SimplVar                ( completeVar )
-import SimplUtils
-import Type            ( mkTyVarTy, mkTyVarTys, mkAppTy,
-                         splitFunTy, getFunTy_maybe, eqTy
+import Rules           ( lookupRule )
+import CostCentre      ( currentCCS )
+import Type            ( mkTyVarTys, isUnLiftedType, seqType,
+                         mkFunTy, splitTyConApp_maybe, tyConAppArgs,
+                         funResultTy
                        )
-import TysWiredIn      ( realWorldStateTy )
-import Util            ( isSingleton, zipEqual, zipWithEqual, panic, pprPanic, assertPanic )
+import Subst           ( mkSubst, substTy, 
+                         isInScope, lookupIdSubst, substIdInfo
+                       )
+import TyCon           ( isDataTyCon, tyConDataConsIfAvailable )
+import TysPrim         ( realWorldStatePrimTy )
+import PrelInfo                ( realWorldPrimId )
+import OrdList
+import Maybes          ( maybeToBool )
+import Util            ( zipWithEqual )
+import Outputable
 \end{code}
 
-The controlling flags, and what they do
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-passes:
-------
--fsimplify             = run the simplifier
--ffloat-inwards                = runs the float lets inwards pass
--ffloat                        = runs the full laziness pass
-                         (ToDo: rename to -ffull-laziness)
--fupdate-analysis      = runs update analyser
--fstrictness           = runs strictness analyser
--fsaturate-apps                = saturates applications (eta expansion)
-
-options:
--------
--ffloat-past-lambda    = OK to do full laziness.
-                         (ToDo: remove, as the full laziness pass is
-                                useless without this flag, therefore
-                                it is unnecessary. Just -ffull-laziness
-                                should be kept.)
-
--ffloat-lets-ok                = OK to float lets out of lets if the enclosing
-                         let is strict or if the floating will expose
-                         a WHNF [simplifier].
-
--ffloat-primops-ok     = OK to float out of lets cases whose scrutinee
-                         is a primop that cannot fail [simplifier].
-
--fcode-duplication-ok  = allows the previous option to work on cases with
-                         multiple branches [simplifier].
-
--flet-to-case          = does let-to-case transformation [simplifier].
-
--fcase-of-case         = does case of case transformation [simplifier].
-
--fpedantic-bottoms     = does not allow:
-                            case x of y -> e  ===>  e[x/y]
-                         (which may turn bottom into non-bottom)
-
-
-                       NOTES ON INLINING
-                       ~~~~~~~~~~~~~~~~~
-
-Inlining is one of the delicate aspects of the simplifier.  By
-``inlining'' we mean replacing an occurrence of a variable ``x'' by
-the RHS of x's definition.  Thus
-
-       let x = e in ...x...    ===>   let x = e in ...e...
-
-We have two mechanisms for inlining:
-
-1.  Unconditional.  The occurrence analyser has pinned an (OneOcc
-FunOcc NoDupDanger NotInsideSCC n) flag on the variable, saying ``it's
-certainly safe to inline this variable, and to drop its binding''.
-(...Umm... if n <= 1; if n > 1, it is still safe, provided you are
-happy to be duplicating code...) When it encounters such a beast, the
-simplifer binds the variable to its RHS (in the id_env) and continues.
-It doesn't even look at the RHS at that stage.  It also drops the
-binding altogether.
-
-2.  Conditional.  In all other situations, the simplifer simplifies
-the RHS anyway, and keeps the new binding.  It also binds the new
-(cloned) variable to a ``suitable'' Unfolding in the UnfoldEnv.
-
-Here, ``suitable'' might mean NoUnfolding (if the occurrence
-info is ManyOcc and the RHS is not a manifest HNF, or UnfoldAlways (if
-the variable has an INLINE pragma on it).  The idea is that anything
-in the UnfoldEnv is safe to use, but also has an enclosing binding if
-you decide not to use it.
-
-Head normal forms
-~~~~~~~~~~~~~~~~~
-We *never* put a non-HNF unfolding in the UnfoldEnv except in the
-INLINE-pragma case.
-
-At one time I thought it would be OK to put non-HNF unfoldings in for
-variables which occur only once [if they got inlined at that
-occurrence the RHS of the binding would become dead, so no duplication
-would occur].   But consider:
-@
-       let x = <expensive>
-           f = \y -> ...y...y...y...
-       in f x
-@
-Now, it seems that @x@ appears only once, but even so it is NOT safe
-to put @x@ in the UnfoldEnv, because @f@ will be inlined, and will
-duplicate the references to @x@.
-
-Because of this, the "unconditional-inline" mechanism above is the
-only way in which non-HNFs can get inlined.
-
-INLINE pragmas
-~~~~~~~~~~~~~~
-
-When a variable has an INLINE pragma on it --- which includes wrappers
-produced by the strictness analyser --- we treat it rather carefully.
-
-For a start, we are careful not to substitute into its RHS, because
-that might make it BIG, and the user said "inline exactly this", not
-"inline whatever you get after inlining other stuff inside me".  For
-example
-
-       let f = BIG
-       in {-# INLINE y #-} y = f 3
-       in ...y...y...
-
-Here we don't want to substitute BIG for the (single) occurrence of f,
-because then we'd duplicate BIG when we inline'd y.  (Exception:
-things in the UnfoldEnv with UnfoldAlways flags, which originated in
-other INLINE pragmas.)
 
-So, we clean out the UnfoldEnv of all SimpleUnfolding inlinings before
-going into such an RHS.
+The guts of the simplifier is in this module, but the driver
+loop for the simplifier is in SimplCore.lhs.
+
+
+-----------------------------------------
+       *** IMPORTANT NOTE ***
+-----------------------------------------
+The simplifier used to guarantee that the output had no shadowing, but
+it does not do so any more.   (Actually, it never did!)  The reason is
+documented with simplifyArgs.
 
-What about imports?  They don't really matter much because we only
-inline relatively small things via imports.
 
-We augment the the UnfoldEnv with UnfoldAlways guidance if there's an
-INLINE pragma.  We also do this for the RHSs of recursive decls,
-before looking at the recursive decls. That way we achieve the effect
-of inlining a wrapper in the body of its worker, in the case of a
-mutually-recursive worker/wrapper split.
 
 
 %************************************************************************
 %*                                                                     *
-\subsection[Simplify-simplExpr]{The main function: simplExpr}
+\subsection{Bindings}
 %*                                                                     *
 %************************************************************************
 
-At the top level things are a little different.
-
-  * No cloning (not allowed for exported Ids, unnecessary for the others)
-
-  * No floating.   Case floating is obviously out.  Let floating is
-       theoretically OK, but dangerous because of space leaks.
-       The long-distance let-floater lifts these lets.
-
 \begin{code}
-simplTopBinds :: SimplEnv -> [InBinding] -> SmplM [OutBinding]
-
-simplTopBinds env [] = returnSmpl []
-
--- Dead code is now discarded by the occurrence analyser,
-
-simplTopBinds env (NonRec binder@(in_id,occ_info) rhs : binds)
-  =    -- No cloning necessary at top level
-       -- Process the binding
-    simplRhsExpr env binder rhs                                `thenSmpl` \ (rhs',arity) ->
-    completeNonRec env binder (in_id `withArity` arity) rhs'   `thenSmpl` \ (new_env, binds1') ->
-
-       -- Process the other bindings
-    simplTopBinds new_env binds        `thenSmpl` \ binds2' ->
-
-       -- Glue together and return ...
-    returnSmpl (binds1' ++ binds2')
-
-simplTopBinds env (Rec pairs : binds)
-  = simplRecursiveGroup env ids pairs  `thenSmpl` \ (bind', new_env) ->
-
-       -- Process the other bindings
-    simplTopBinds new_env binds                `thenSmpl` \ binds' ->
+simplTopBinds :: [InBind] -> SimplM [OutBind]
+
+simplTopBinds binds
+  =    -- Put all the top-level binders into scope at the start
+       -- so that if a transformation rule has unexpectedly brought
+       -- anything into scope, then we don't get a complaint about that.
+       -- It's rather as if the top-level binders were imported.
+    simplIds (bindersOfBinds binds)    $ \ bndrs' -> 
+    simpl_binds binds bndrs'           `thenSmpl` \ (binds', _) ->
+    freeTick SimplifierDone            `thenSmpl_`
+    returnSmpl (fromOL binds')
+  where
 
-       -- Glue together and return
-    returnSmpl (bind' : binds')
+       -- We need to track the zapped top-level binders, because
+       -- they should have their fragile IdInfo zapped (notably occurrence info)
+    simpl_binds []                       bs     = ASSERT( null bs ) returnSmpl (nilOL, panic "simplTopBinds corner")
+    simpl_binds (NonRec bndr rhs : binds) (b:bs) = simplLazyBind True bndr  b rhs      (simpl_binds binds bs)
+    simpl_binds (Rec pairs       : binds) bs     = simplRecBind  True pairs (take n bs) (simpl_binds binds (drop n bs))
+                                                where 
+                                                  n = length pairs
+
+simplRecBind :: Bool -> [(InId, InExpr)] -> [OutId]
+            -> SimplM (OutStuff a) -> SimplM (OutStuff a)
+simplRecBind top_lvl pairs bndrs' thing_inside
+  = go pairs bndrs'            `thenSmpl` \ (binds', (_, (binds'', res))) ->
+    returnSmpl (unitOL (Rec (flattenBinds (fromOL binds'))) `appOL` binds'', res)
   where
-    ids = [id | (binder@(id,_), rhs) <- pairs] -- No cloning necessary at top level
+    go [] _ = thing_inside     `thenSmpl` \ stuff ->
+             returnOutStuff stuff
+       
+    go ((bndr, rhs) : pairs) (bndr' : bndrs')
+       = simplLazyBind top_lvl bndr bndr' rhs (go pairs bndrs')
+               -- Don't float unboxed bindings out,
+               -- because we can't "rec" them
 \end{code}
 
+
 %************************************************************************
 %*                                                                     *
 \subsection[Simplify-simplExpr]{The main function: simplExpr}
 %*                                                                     *
 %************************************************************************
 
+The reason for this OutExprStuff stuff is that we want to float *after*
+simplifying a RHS, not before.  If we do so naively we get quadratic
+behaviour as things float out.
 
-\begin{code}
-simplExpr :: SimplEnv
-         -> InExpr -> [OutArg]
-         -> SmplM OutExpr
-\end{code}
+To see why it's important to do it after, consider this (real) example:
 
-The expression returned has the same meaning as the input expression
-applied to the specified arguments.
+       let t = f x
+       in fst t
+==>
+       let t = let a = e1
+                   b = e2
+               in (a,b)
+       in fst t
+==>
+       let a = e1
+           b = e2
+           t = (a,b)
+       in
+       a       -- Can't inline a this round, cos it appears twice
+==>
+       e1
 
+Each of the ==> steps is a round of simplification.  We'd save a
+whole round if we float first.  This can cascade.  Consider
 
-Variables
-~~~~~~~~~
-Check if there's a macro-expansion, and if so rattle on.  Otherwise do
-the more sophisticated stuff.
+       let f = g d
+       in \x -> ...f...
+==>
+       let f = let d1 = ..d.. in \y -> e
+       in \x -> ...f...
+==>
+       let d1 = ..d..
+       in \x -> ...(\y ->e)...
 
-\begin{code}
-simplExpr env (Var v) args
-  = case (lookupId env v) of
-      LitArg lit               -- A boring old literal
-       -> ASSERT( null args )
-          returnSmpl (Lit lit)
-
-      VarArg var       -- More interesting!  An id!
-       -> completeVar env var args
-                               -- Either Id is in the local envt, or it's a global.
-                               -- In either case we don't need to apply the type
-                               -- environment to it.
-\end{code}
+Only in this second round can the \y be applied, and it 
+might do the same again.
 
-Literals
-~~~~~~~~
 
 \begin{code}
-simplExpr env (Lit l) [] = returnSmpl (Lit l)
-#ifdef DEBUG
-simplExpr env (Lit l) _  = panic "simplExpr:Lit with argument"
-#endif
+simplExpr :: CoreExpr -> SimplM CoreExpr
+simplExpr expr = getSubst      `thenSmpl` \ subst ->
+                simplExprC expr (mkStop (substTy subst (exprType expr)))
+       -- The type in the Stop continuation is usually not used
+       -- It's only needed when discarding continuations after finding
+       -- a function that returns bottom.
+       -- Hence the lazy substitution
+
+simplExprC :: CoreExpr -> SimplCont -> SimplM CoreExpr
+       -- Simplify an expression, given a continuation
+
+simplExprC expr cont = simplExprF expr cont    `thenSmpl` \ (floats, (_, body)) ->
+                      returnSmpl (wrapFloats floats body)
+
+simplExprF :: InExpr -> SimplCont -> SimplM OutExprStuff
+       -- Simplify an expression, returning floated binds
+
+simplExprF (Var v) cont
+  = simplVar v cont
+
+simplExprF (Lit lit) (Select _ bndr alts se cont)
+  = knownCon (Lit lit) (LitAlt lit) [] bndr alts se cont
+
+simplExprF (Lit lit) cont
+  = rebuild (Lit lit) cont
+
+simplExprF (App fun arg) cont
+  = getSubstEnv                `thenSmpl` \ se ->
+    simplExprF fun (ApplyTo NoDup arg se cont)
+
+simplExprF (Case scrut bndr alts) cont
+  = getSubstEnv                        `thenSmpl` \ subst_env ->
+    getSwitchChecker           `thenSmpl` \ chkr ->
+    if not (switchIsOn chkr NoCaseOfCase) then
+       -- Simplify the scrutinee with a Select continuation
+       simplExprF scrut (Select NoDup bndr alts subst_env cont)
+
+    else
+       -- If case-of-case is off, simply simplify the case expression
+       -- in a vanilla Stop context, and rebuild the result around it
+       simplExprC scrut (Select NoDup bndr alts subst_env 
+                                (mkStop (contResultType cont)))        `thenSmpl` \ case_expr' ->
+       rebuild case_expr' cont
+
+
+simplExprF (Let (Rec pairs) body) cont
+  = simplIds (map fst pairs)           $ \ bndrs' -> 
+       -- NB: bndrs' don't have unfoldings or spec-envs
+       -- We add them as we go down, using simplPrags
+
+    simplRecBind False pairs bndrs' (simplExprF body cont)
+
+simplExprF expr@(Lam _ _) cont = simplLam expr cont
+
+simplExprF (Type ty) cont
+  = ASSERT( case cont of { Stop _ _ -> True; ArgOf _ _ _ -> True; other -> False } )
+    simplType ty       `thenSmpl` \ ty' ->
+    rebuild (Type ty') cont
+
+-- Comments about the Coerce case
+-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+-- It's worth checking for a coerce in the continuation,
+-- in case we can cancel them.  For example, in the initial form of a worker
+-- we may find         (coerce T (coerce S (\x.e))) y
+-- and we'd like it to simplify to e[y/x] in one round of simplification
+
+simplExprF (Note (Coerce to from) e) (CoerceIt outer_to cont)
+  = simplType from             `thenSmpl` \ from' ->
+    if outer_to == from' then
+       -- The coerces cancel out
+       simplExprF e cont
+    else
+       -- They don't cancel, but the inner one is redundant
+       simplExprF e (CoerceIt outer_to cont)
+
+simplExprF (Note (Coerce to from) e) cont
+  = simplType to               `thenSmpl` \ to' ->
+    simplExprF e (CoerceIt to' cont)
+
+-- hack: we only distinguish subsumed cost centre stacks for the purposes of
+-- inlining.  All other CCCSs are mapped to currentCCS.
+simplExprF (Note (SCC cc) e) cont
+  = setEnclosingCC currentCCS $
+    simplExpr e        `thenSmpl` \ e ->
+    rebuild (mkSCC cc e) cont
+
+simplExprF (Note InlineCall e) cont
+  = simplExprF e (InlinePlease cont)
+
+--      Comments about the InlineMe case 
+--      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+-- Don't inline in the RHS of something that has an
+-- inline pragma.  But be careful that the InScopeEnv that
+-- we return does still have inlinings on!
+-- 
+-- It really is important to switch off inlinings.  This function
+-- may be inlinined in other modules, so we don't want to remove
+-- (by inlining) calls to functions that have specialisations, or
+-- that may have transformation rules in an importing scope.
+-- E.g.        {-# INLINE f #-}
+--             f x = ...g...
+-- and suppose that g is strict *and* has specialisations.
+-- If we inline g's wrapper, we deny f the chance of getting
+-- the specialised version of g when f is inlined at some call site
+-- (perhaps in some other module).
+
+-- It's also important not to inline a worker back into a wrapper.
+-- A wrapper looks like
+--     wraper = inline_me (\x -> ...worker... )
+-- Normally, the inline_me prevents the worker getting inlined into
+-- the wrapper (initially, the worker's only call site!).  But,
+-- if the wrapper is sure to be called, the strictness analyser will
+-- mark it 'demanded', so when the RHS is simplified, it'll get an ArgOf
+-- continuation.  That's why the keep_inline predicate returns True for
+-- ArgOf continuations.  It shouldn't do any harm not to dissolve the
+-- inline-me note under these circumstances
+
+simplExprF (Note InlineMe e) cont
+  | keep_inline cont           -- Totally boring continuation
+  =                            -- Don't inline inside an INLINE expression
+    setBlackList noInlineBlackList (simplExpr e)       `thenSmpl` \ e' ->
+    rebuild (mkInlineMe e') cont
+
+  | otherwise          -- Dissolve the InlineMe note if there's
+               -- an interesting context of any kind to combine with
+               -- (even a type application -- anything except Stop)
+  = simplExprF e cont
+  where
+    keep_inline (Stop _ _)    = True           -- See notes above
+    keep_inline (ArgOf _ _ _) = True           -- about this predicate
+    keep_inline other        = False
+
+-- A non-recursive let is dealt with by simplBeta
+simplExprF (Let (NonRec bndr rhs) body) cont
+  = getSubstEnv                        `thenSmpl` \ se ->
+    simplBeta bndr rhs se (contResultType cont)        $
+    simplExprF body cont
 \end{code}
 
-Primitive applications are simple.
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
-NB: Prim expects an empty argument list! (Because it should be
-saturated and not higher-order. ADR)
+---------------------------------
 
 \begin{code}
-simplExpr env (Prim op prim_args) args
-  = ASSERT (null args)
-    let
-       prim_args' = [simplArg env prim_arg | prim_arg <- prim_args]
-       op'        = simpl_op op
-    in
-    completePrim env op' prim_args'
+simplLam fun cont
+  = go fun cont
   where
-    -- PrimOps just need any types in them renamed.
-
-    simpl_op (CCallOp label is_asm may_gc arg_tys result_ty)
-      = let
-           arg_tys'    = map (simplTy env) arg_tys
-           result_ty'  = simplTy env result_ty
-       in
-       CCallOp label is_asm may_gc arg_tys' result_ty'
+    zap_it  = mkLamBndrZapper fun cont
+    cont_ty = contResultType cont
+
+       -- Type-beta reduction
+    go (Lam bndr body) (ApplyTo _ (Type ty_arg) arg_se body_cont)
+      =        ASSERT( isTyVar bndr )
+       tick (BetaReduction bndr)       `thenSmpl_`
+       simplTyArg ty_arg arg_se        `thenSmpl` \ ty_arg' ->
+       extendSubst bndr (DoneTy ty_arg')
+       (go body body_cont)
+
+       -- Ordinary beta reduction
+    go (Lam bndr body) cont@(ApplyTo _ arg arg_se body_cont)
+      = tick (BetaReduction bndr)                      `thenSmpl_`
+       simplBeta zapped_bndr arg arg_se cont_ty
+       (go body body_cont)
+      where
+       zapped_bndr = zap_it bndr
+
+       -- Not enough args
+    go lam@(Lam _ _) cont = completeLam [] lam cont
+
+       -- Exactly enough args
+    go expr cont = simplExprF expr cont
+
+-- completeLam deals with the case where a lambda doesn't have an ApplyTo
+-- continuation, so there are real lambdas left to put in the result
+
+-- We try for eta reduction here, but *only* if we get all the 
+-- way to an exprIsTrivial expression.    
+-- We don't want to remove extra lambdas unless we are going 
+-- to avoid allocating this thing altogether
+
+completeLam rev_bndrs (Lam bndr body) cont
+  = simplBinder bndr                   $ \ bndr' ->
+    completeLam (bndr':rev_bndrs) body cont
+
+completeLam rev_bndrs body cont
+  = simplExpr body                     `thenSmpl` \ body' ->
+    case try_eta body' of
+       Just etad_lam -> tick (EtaReduction (head rev_bndrs))   `thenSmpl_`
+                        rebuild etad_lam cont
+
+       Nothing       -> rebuild (foldl (flip Lam) body' rev_bndrs) cont
+  where
+       -- We don't use CoreUtils.etaReduce, because we can be more
+       -- efficient here:
+       --  (a) we already have the binders,
+       --  (b) we can do the triviality test before computing the free vars
+       --      [in fact I take the simple path and look for just a variable]
+       --  (c) we don't want to eta-reduce a data con worker or primop
+       --      because we only have to eta-expand them later when we saturate
+    try_eta body | not opt_SimplDoEtaReduction = Nothing
+                | otherwise                   = go rev_bndrs body
+
+    go (b : bs) (App fun arg) | ok_arg b arg = go bs fun       -- Loop round
+    go []       body          | ok_body body = Just body       -- Success!
+    go _        _                           = Nothing          -- Failure!
+
+    ok_body (Var v) = not (v `elem` rev_bndrs) && not (hasNoBinding v)
+    ok_body other   = False
+    ok_arg b arg    = varToCoreExpr b `cheapEqExpr` arg
+
+mkLamBndrZapper :: CoreExpr    -- Function
+               -> SimplCont    -- The context
+               -> Id -> Id     -- Use this to zap the binders
+mkLamBndrZapper fun cont
+  | n_args >= n_params fun = \b -> b           -- Enough args
+  | otherwise             = \b -> zapLamIdInfo b
+  where
+       -- NB: we count all the args incl type args
+       -- so we must count all the binders (incl type lambdas)
+    n_args = countArgs cont
 
-    simpl_op other_op = other_op
+    n_params (Note _ e) = n_params e
+    n_params (Lam b e)  = 1 + n_params e
+    n_params other     = 0::Int
 \end{code}
 
-Constructor applications
-~~~~~~~~~~~~~~~~~~~~~~~~
-Nothing to try here.  We only reuse constructors when they appear as the
-rhs of a let binding (see completeLetBinding).
 
+---------------------------------
 \begin{code}
-simplExpr env (Con con con_args) args
-  = ASSERT( null args )
-    returnSmpl (Con con [simplArg env con_arg | con_arg <- con_args])
+simplType :: InType -> SimplM OutType
+simplType ty
+  = getSubst   `thenSmpl` \ subst ->
+    let
+       new_ty = substTy subst ty
+    in
+    seqType new_ty `seq`  
+    returnSmpl new_ty
 \end{code}
 
 
-Applications are easy too:
-~~~~~~~~~~~~~~~~~~~~~~~~~~
-Just stuff 'em in the arg stack
-
-\begin{code}
-simplExpr env (App fun arg) args
-  = simplExpr env fun (simplArg env arg : args)
-\end{code}
+%************************************************************************
+%*                                                                     *
+\subsection{Binding}
+%*                                                                     *
+%************************************************************************
 
-Type lambdas
-~~~~~~~~~~~~
+@simplBeta@ is used for non-recursive lets in expressions, 
+as well as true beta reduction.
 
-We only eta-reduce a type lambda if all type arguments in the body can
-be eta-reduced. This requires us to collect up all tyvar parameters so
-we can pass them all to @mkTyLamTryingEta@.
+Very similar to @simplLazyBind@, but not quite the same.
 
 \begin{code}
-simplExpr env (Lam (TyBinder tyvar) body) (TyArg ty : args)
-  = -- ASSERT(not (isPrimType ty))
-    tick TyBetaReduction       `thenSmpl_`
-    simplExpr (extendTyEnv env tyvar ty) body args
-
-simplExpr env tylam@(Lam (TyBinder tyvar) body) []
-  = do_tylambdas env [] tylam
-  where
-    do_tylambdas env tyvars' (Lam (TyBinder tyvar) body)
-      =          -- Clone the type variable
-       cloneTyVarSmpl tyvar            `thenSmpl` \ tyvar' ->
-       let
-           new_env = extendTyEnv env tyvar (mkTyVarTy tyvar')
-       in
-       do_tylambdas new_env (tyvar':tyvars') body
-
-    do_tylambdas env tyvars' body
-      =        simplExpr env body []           `thenSmpl` \ body' ->
-       returnSmpl (
-          (if switchIsSet env SimplDoEtaReduction
-          then mkTyLamTryingEta
-          else mkTyLam) (reverse tyvars')  body'
-       )
-
+simplBeta :: InId                      -- Binder
+         -> InExpr -> SubstEnv         -- Arg, with its subst-env
+         -> OutType                    -- Type of thing computed by the context
+         -> SimplM OutExprStuff        -- The body
+         -> SimplM OutExprStuff
 #ifdef DEBUG
-simplExpr env (Lam (TyBinder _) _) (_ : _)
-  = panic "simplExpr:TyLam with non-TyArg"
+simplBeta bndr rhs rhs_se cont_ty thing_inside
+  | isTyVar bndr
+  = pprPanic "simplBeta" (ppr bndr <+> ppr rhs)
 #endif
-\end{code}
 
+simplBeta bndr rhs rhs_se cont_ty thing_inside
+  | preInlineUnconditionally False {- not black listed -} bndr
+  = tick (PreInlineUnconditionally bndr)               `thenSmpl_`
+    extendSubst bndr (ContEx rhs_se rhs) thing_inside
 
-Ordinary lambdas
-~~~~~~~~~~~~~~~~
-
-There's a complication with lambdas that aren't saturated.
-Suppose we have:
-
-       (\x. \y. ...x...)
-
-If we did nothing, x is used inside the \y, so would be marked
-as dangerous to dup.  But in the common case where the abstraction
-is applied to two arguments this is over-pessimistic.
-So instead we don't take account of the \y when dealing with x's usage;
-instead, the simplifier is careful when partially applying lambdas.
+  | otherwise
+  =    -- Simplify the RHS
+    simplBinder bndr                                   $ \ bndr' ->
+    let
+       bndr_ty'  = idType bndr'
+       is_strict = isStrict (idDemandInfo bndr) || isStrictType bndr_ty'
+    in
+    simplValArg bndr_ty' is_strict rhs rhs_se cont_ty  $ \ rhs' ->
 
-\begin{code}
-simplExpr env expr@(Lam (ValBinder binder) body) orig_args
-  = go 0 env expr orig_args
-  where
-    go n env (Lam (ValBinder binder) body) (val_arg : args)
-      | isValArg val_arg               -- The lambda has an argument
-      = tick BetaReduction     `thenSmpl_`
-        go (n+1) (extendIdEnvWithAtom env binder val_arg) body args
-
-    go n env expr@(Lam (ValBinder binder) body) args
-       -- The lambda is un-saturated, so we must zap the occurrence info
-       -- on the arguments we've already beta-reduced into the body of the lambda
-      = ASSERT( null args )    -- Value lambda must match value argument!
-        let
-           new_env = markDangerousOccs env (take n orig_args)
-        in
-        simplValLam new_env expr 0 {- Guaranteed applied to at least 0 args! -}
-                               `thenSmpl` \ (expr', arity) ->
-       returnSmpl expr'
-
-    go n env non_val_lam_expr args             -- The lambda had enough arguments
-      = simplExpr env non_val_lam_expr args
+       -- Now complete the binding and simplify the body
+    if needsCaseBinding bndr_ty' rhs' then
+       addCaseBind bndr' rhs' thing_inside
+    else
+       completeBinding bndr bndr' False False rhs' thing_inside
 \end{code}
 
 
-Let expressions
-~~~~~~~~~~~~~~~
-
 \begin{code}
-simplExpr env (Let bind body) args
-  = simplBind env bind (\env -> simplExpr env body args)
-                      (computeResultType env body args)
-\end{code}
-
-Case expressions
-~~~~~~~~~~~~~~~~
+simplTyArg :: InType -> SubstEnv -> SimplM OutType
+simplTyArg ty_arg se
+  = getInScope         `thenSmpl` \ in_scope ->
+    let
+       ty_arg' = substTy (mkSubst in_scope se) ty_arg
+    in
+    seqType ty_arg'    `seq`
+    returnSmpl ty_arg'
+
+simplValArg :: OutType         -- rhs_ty: Type of arg; used only occasionally
+           -> Bool             -- True <=> evaluate eagerly
+           -> InExpr -> SubstEnv
+           -> OutType          -- cont_ty: Type of thing computed by the context
+           -> (OutExpr -> SimplM OutExprStuff) 
+                               -- Takes an expression of type rhs_ty, 
+                               -- returns an expression of type cont_ty
+           -> SimplM OutExprStuff      -- An expression of type cont_ty
+
+simplValArg arg_ty is_strict arg arg_se cont_ty thing_inside
+  | is_strict
+  = getEnv                             `thenSmpl` \ env ->
+    setSubstEnv arg_se                                 $
+    simplExprF arg (ArgOf NoDup cont_ty        $ \ rhs' ->
+    setAllExceptInScope env                    $
+    thing_inside rhs')
 
-\begin{code}
-simplExpr env expr@(Case scrut alts) args
-  = simplCase env scrut alts (\env rhs -> simplExpr env rhs args)
-                            (computeResultType env expr args)
+  | otherwise
+  = simplRhs False {- Not top level -} 
+            True {- OK to float unboxed -}
+            arg_ty arg arg_se 
+            thing_inside
 \end{code}
 
 
-Coercions
-~~~~~~~~~
-\begin{code}
-simplExpr env (Coerce coercion ty body) args
-  = simplCoerce env coercion ty body args 
-\end{code}
-
+completeBinding
+       - deals only with Ids, not TyVars
+       - take an already-simplified RHS
 
-Set-cost-centre
-~~~~~~~~~~~~~~~
+It does *not* attempt to do let-to-case.  Why?  Because they are used for
 
-1) Eliminating nested sccs ...
-We must be careful to maintain the scc counts ...
+       - top-level bindings
+               (when let-to-case is impossible) 
 
-\begin{code}
-simplExpr env (SCC cc1 (SCC cc2 expr)) args
-  | not (isSccCountCostCentre cc2) && case cmpCostCentre cc1 cc2 of { EQ_ -> True; _ -> False }
-       -- eliminate inner scc if no call counts and same cc as outer
-  = simplExpr env (SCC cc1 expr) args
-
-  | not (isSccCountCostCentre cc2) && not (isSccCountCostCentre cc1)
-       -- eliminate outer scc if no call counts associated with either ccs
-  = simplExpr env (SCC cc2 expr) args
-\end{code}
+       - many situations where the "rhs" is known to be a WHNF
+               (so let-to-case is inappropriate).
 
-2) Moving sccs inside lambdas ...
-  
 \begin{code}
-simplExpr env (SCC cc (Lam binder@(ValBinder _) body)) args
-  | not (isSccCountCostCentre cc)
-       -- move scc inside lambda only if no call counts
-  = simplExpr env (Lam binder (SCC cc body)) args
-
-simplExpr env (SCC cc (Lam binder body)) args
-       -- always ok to move scc inside type/usage lambda
-  = simplExpr env (Lam binder (SCC cc body)) args
-\end{code}
-
-3) Eliminating dict sccs ...
+completeBinding :: InId                -- Binder
+               -> OutId                -- New binder
+               -> Bool                 -- True <=> top level
+               -> Bool                 -- True <=> black-listed; don't inline
+               -> OutExpr              -- Simplified RHS
+               -> SimplM (OutStuff a)  -- Thing inside
+               -> SimplM (OutStuff a)
+
+completeBinding old_bndr new_bndr top_lvl black_listed new_rhs thing_inside
+  |  isDeadOcc occ_info        -- This happens; for example, the case_bndr during case of
+                               -- known constructor:  case (a,b) of x { (p,q) -> ... }
+                               -- Here x isn't mentioned in the RHS, so we don't want to
+                               -- create the (dead) let-binding  let x = (a,b) in ...
+  =  thing_inside
+
+  | trivial_rhs && not must_keep_binding
+       -- We're looking at a binding with a trivial RHS, so
+       -- perhaps we can discard it altogether!
+       --
+       -- NB: a loop breaker has must_keep_binding = True
+       -- and non-loop-breakers only have *forward* references
+       -- Hence, it's safe to discard the binding
+       --      
+       -- NOTE: This isn't our last opportunity to inline.
+       -- We're at the binding site right now, and
+       -- we'll get another opportunity when we get to the ocurrence(s)
+
+       -- Note that we do this unconditional inlining only for trival RHSs.
+       -- Don't inline even WHNFs inside lambdas; doing so may
+       -- simply increase allocation when the function is called
+       -- This isn't the last chance; see NOTE above.
+       --
+       -- NB: Even inline pragmas (e.g. IMustBeINLINEd) are ignored here
+       -- Why?  Because we don't even want to inline them into the
+       -- RHS of constructor arguments. See NOTE above
+       --
+       -- NB: Even NOINLINEis ignored here: if the rhs is trivial
+       -- it's best to inline it anyway.  We often get a=E; b=a
+       -- from desugaring, with both a and b marked NOINLINE.
+  =            -- Drop the binding
+    extendSubst old_bndr (DoneEx new_rhs)      $
+               -- Use the substitution to make quite, quite sure that the substitution
+               -- will happen, since we are going to discard the binding
+    tick (PostInlineUnconditionally old_bndr)  `thenSmpl_`
+    thing_inside
+
+  | Note coercion@(Coerce _ inner_ty) inner_rhs <- new_rhs,
+    not trivial_rhs && not (isUnLiftedType inner_ty)
+       -- x = coerce t e  ==>  c = e; x = inline_me (coerce t c)
+       -- Now x can get inlined, which moves the coercion
+       -- to the usage site.  This is a bit like worker/wrapper stuff,
+       -- but it's useful to do it very promptly, so that
+       --      x = coerce T (I# 3)
+       -- get's w/wd to
+       --      c = I# 3
+       --      x = coerce T c
+       -- This in turn means that
+       --      case (coerce Int x) of ...
+       -- will inline x.  
+       -- Also the full-blown w/w thing isn't set up for non-functions
+       --
+       -- The (not (isUnLiftedType inner_ty)) avoids the nasty case of
+       --      x::Int = coerce Int Int# (foo y)
+       -- ==>
+       --      v::Int# = foo y
+       --      x::Int  = coerce Int Int# v
+       -- which would be bogus because then v will be evaluated strictly.
+       -- How can this arise?  Via 
+       --      x::Int = case (foo y) of { ... }
+       -- followed by case elimination.
+       --
+       -- The inline_me note is so that the simplifier doesn't 
+       -- just substitute c back inside x's rhs!  (Typically, x will
+       -- get substituted away, but not if it's exported.)
+  = newId SLIT("c") inner_ty                                   $ \ c_id ->
+    completeBinding c_id c_id top_lvl False inner_rhs          $
+    completeBinding old_bndr new_bndr top_lvl black_listed
+                   (Note InlineMe (Note coercion (Var c_id)))  $
+    thing_inside
+
+  |  otherwise
+  = getSubst                   `thenSmpl` \ subst ->
+    let
+               -- We make new IdInfo for the new binder by starting from the old binder, 
+               -- doing appropriate substitutions.
+               -- Then we add arity and unfolding info to get the new binder
+       new_bndr_info = substIdInfo subst old_info (idInfo new_bndr)
+                       `setArityInfo` arity_info
+
+               -- Add the unfolding *only* for non-loop-breakers
+               -- Making loop breakers not have an unfolding at all 
+               -- means that we can avoid tests in exprIsConApp, for example.
+               -- This is important: if exprIsConApp says 'yes' for a recursive
+               -- thing, then we can get into an infinite loop
+        info_w_unf | loop_breaker = new_bndr_info
+                  | otherwise    = new_bndr_info `setUnfoldingInfo` mkUnfolding top_lvl new_rhs
+
+       final_id = new_bndr `setIdInfo` info_w_unf
+    in
+               -- These seqs forces the Id, and hence its IdInfo,
+               -- and hence any inner substitutions
+    final_id                           `seq`
+    addLetBind (NonRec final_id new_rhs)       $
+    modifyInScope new_bndr final_id thing_inside
 
-\begin{code}
-simplExpr env (SCC cc expr) args
-  | squashableDictishCcExpr cc expr
-       -- eliminate dict cc if trivial dict expression
-  = simplExpr env expr args
-\end{code}
+  where
+    old_info          = idInfo old_bndr
+    occ_info          = occInfo old_info
+    loop_breaker      = isLoopBreaker occ_info
+    trivial_rhs              = exprIsTrivial new_rhs
+    must_keep_binding = black_listed || loop_breaker || isExportedId old_bndr
+    arity_info       = atLeastArity (exprArity new_rhs)
+\end{code}    
 
-4) Moving arguments inside the body of an scc ...
-This moves the cost of doing the application inside the scc
-(which may include the cost of extracting methods etc)
 
-\begin{code}
-simplExpr env (SCC cost_centre body) args
-  = let
-       new_env = setEnclosingCC env cost_centre
-    in
-    simplExpr new_env body args                `thenSmpl` \ body' ->
-    returnSmpl (SCC cost_centre body')
-\end{code}
 
 %************************************************************************
 %*                                                                     *
-\subsection{Simplify RHS of a Let/Letrec}
+\subsection{simplLazyBind}
 %*                                                                     *
 %************************************************************************
 
-simplRhsExpr does arity-expansion.  That is, given:
+simplLazyBind basically just simplifies the RHS of a let(rec).
+It does two important optimisations though:
+
+       * It floats let(rec)s out of the RHS, even if they
+         are hidden by big lambdas
+
+       * It does eta expansion
 
-       * a right hand side /\ tyvars -> \a1 ... an -> e
-       * the information (stored in BinderInfo) that the function will always
-         be applied to at least k arguments
+\begin{code}
+simplLazyBind :: Bool                  -- True <=> top level
+             -> InId -> OutId
+             -> InExpr                 -- The RHS
+             -> SimplM (OutStuff a)    -- The body of the binding
+             -> SimplM (OutStuff a)
+-- When called, the subst env is correct for the entire let-binding
+-- and hence right for the RHS.
+-- Also the binder has already been simplified, and hence is in scope
+
+simplLazyBind top_lvl bndr bndr' rhs thing_inside
+  = getBlackList               `thenSmpl` \ black_list_fn ->
+    let
+       black_listed = black_list_fn bndr
+    in
 
-it transforms the rhs to
+    if preInlineUnconditionally black_listed bndr then
+       -- Inline unconditionally
+       tick (PreInlineUnconditionally bndr)    `thenSmpl_`
+       getSubstEnv                             `thenSmpl` \ rhs_se ->
+       (extendSubst bndr (ContEx rhs_se rhs) thing_inside)
+    else
+
+       -- Simplify the RHS
+    getSubstEnv                                        `thenSmpl` \ rhs_se ->
+    simplRhs top_lvl False {- Not ok to float unboxed (conservative) -}
+            (idType bndr')
+            rhs rhs_se                                 $ \ rhs' ->
+
+       -- Now compete the binding and simplify the body
+    completeBinding bndr bndr' top_lvl black_listed rhs' thing_inside
+\end{code}
 
-       /\tyvars -> \a1 ... an b(n+1) ... bk -> (e b(n+1) ... bk)
 
-This is a Very Good Thing!
 
 \begin{code}
-simplRhsExpr
-       :: SimplEnv
-       -> InBinder
-       -> InExpr
-       -> SmplM (OutExpr, ArityInfo)
-
-simplRhsExpr env binder@(id,occ_info) rhs
-  | dont_eta_expand rhs
-  = simplExpr rhs_env rhs []   `thenSmpl` \ rhs' ->
-    returnSmpl (rhs', unknownArity)
-
-  | otherwise  -- Have a go at eta expansion
-  =    -- Deal with the big lambda part
-    ASSERT( null uvars )       -- For now
-
-    mapSmpl cloneTyVarSmpl tyvars                      `thenSmpl` \ tyvars' ->
+simplRhs :: Bool               -- True <=> Top level
+        -> Bool                -- True <=> OK to float unboxed (speculative) bindings
+                               --          False for (a) recursive and (b) top-level bindings
+        -> OutType             -- Type of RHS; used only occasionally
+        -> InExpr -> SubstEnv
+        -> (OutExpr -> SimplM (OutStuff a))
+        -> SimplM (OutStuff a)
+simplRhs top_lvl float_ubx rhs_ty rhs rhs_se thing_inside
+  =    -- Simplify it
+    setSubstEnv rhs_se (simplExprF rhs (mkRhsStop rhs_ty))     `thenSmpl` \ (floats1, (rhs_in_scope, rhs1)) ->
     let
-       lam_env  = extendTyEnvList rhs_env (zipEqual "simplRhsExpr" tyvars (mkTyVarTys tyvars'))
+       (floats2, rhs2) = splitFloats float_ubx floats1 rhs1
     in
-       -- Deal with the little lambda part
-       -- Note that we call simplLam even if there are no binders,
-       -- in case it can do arity expansion.
-    simplValLam lam_env body (getBinderInfoArity occ_info)     `thenSmpl` \ (lambda', arity) ->
-
-       -- Put it back together
-    returnSmpl (
-       (if switchIsSet env SimplDoEtaReduction
-       then mkTyLamTryingEta
-       else mkTyLam) tyvars' lambda',
-      arity
-    )
+               -- There's a subtlety here.  There may be a binding (x* = e) in the
+               -- floats, where the '*' means 'will be demanded'.  So is it safe
+               -- to float it out?  Answer no, but it won't matter because
+               -- we only float if arg' is a WHNF,
+               -- and so there can't be any 'will be demanded' bindings in the floats.
+               -- Hence the assert
+    WARN( any demanded_float (fromOL floats2), ppr (fromOL floats2) )
+
+       --                      Transform the RHS
+       -- It's important that we do eta expansion on function *arguments* (which are
+       -- simplified with simplRhs), as well as let-bound right-hand sides.  
+       -- Otherwise we find that things like
+       --      f (\x -> case x of I# x' -> coerce T (\ y -> ...))
+       -- get right through to the code generator as two separate lambdas, 
+       -- which is a Bad Thing
+    tryRhsTyLam rhs2           `thenSmpl` \ (floats3, rhs3) ->
+    tryEtaExpansion rhs3 rhs_ty        `thenSmpl` \ (floats4, rhs4) ->
+
+       -- Float lets if (a) we're at the top level
+       -- or            (b) the resulting RHS is one we'd like to expose
+    if (top_lvl || exprIsCheap rhs4) then
+       (if (isNilOL floats2 && null floats3 && null floats4) then
+               returnSmpl ()
+        else
+               tick LetFloatFromLet)                   `thenSmpl_`
+
+       addFloats floats2 rhs_in_scope  $
+       addAuxiliaryBinds floats3       $
+       addAuxiliaryBinds floats4       $
+       thing_inside rhs4
+    else       
+               -- Don't do the float
+       thing_inside (wrapFloats floats1 rhs1)
+
+demanded_float (NonRec b r) = isStrict (idDemandInfo b) && not (isUnLiftedType (idType b))
+               -- Unlifted-type (cheap-eagerness) lets may well have a demanded flag on them
+demanded_float (Rec _)     = False
+
+-- If float_ubx is true we float all the bindings, otherwise
+-- we just float until we come across an unlifted one.
+-- Remember that the unlifted bindings in the floats are all for
+-- guaranteed-terminating non-exception-raising unlifted things,
+-- which we are happy to do speculatively.  However, we may still
+-- not be able to float them out, because the context
+-- is either a Rec group, or the top level, neither of which
+-- can tolerate them.
+splitFloats float_ubx floats rhs
+  | float_ubx = (floats, rhs)          -- Float them all
+  | otherwise = go (fromOL floats)
   where
+    go []                  = (nilOL, rhs)
+    go (f:fs) | must_stay f = (nilOL, mkLets (f:fs) rhs)
+             | otherwise   = case go fs of
+                                  (out, rhs') -> (f `consOL` out, rhs')
 
-    rhs_env |  -- not (switchIsSet env IgnoreINLINEPragma) &&
-               -- No!  Don't ever inline in a INLINE thing's rhs, because
-               -- doing so will inline a worker straight back into its wrapper!
-             idWantsToBeINLINEd id
-           = switchOffInlining env
-           | otherwise 
-            = env
-
-       -- Switch off all inlining in the RHS of things that have an INLINE pragma.
-       -- They are going to be inlined wherever they are used, and then all the
-       -- inlining will take effect.  Meanwhile, there isn't
-       -- much point in doing anything to the as-yet-un-INLINEd rhs.
-       -- It's very important to switch off inlining!  Consider:
-       --
-       -- let f = \pq -> BIG
-       -- in
-       -- let g = \y -> f y y
-       --     {-# INLINE g #-}
-       -- in ...g...g...g...g...g...
-       --
-       -- Now, if that's the ONLY occurrence of f, it will be inlined inside g,
-       -- and thence copied multiple times when g is inlined.
-
-       -- Andy disagrees! Example:
-       --      all xs = foldr (&&) True xs
-       --      any p = all . map p  {-# INLINE any #-}
-       --
-       -- Problem: any won't get deforested, and so if it's exported and
-       -- the importer doesn't use the inlining, (eg passes it as an arg)
-       -- then we won't get deforestation at all.
-       -- We havn't solved this problem yet!
-
-    (uvars, tyvars, body) = collectUsageAndTyBinders rhs
-
-       -- dont_eta_expand prevents eta expansion in silly situations.
-       -- For example, consider the defn
-       --      x = y
-       -- It would be silly to eta expand the "y", because it would just
-       -- get eta-reduced back to y.  Furthermore, if this was a top level defn,
-       -- and x was exported, then the defn won't be eliminated, so this
-       -- silly expand/reduce cycle will happen every time, which makes the
-       -- simplifier loop!.
-       -- The solution is to not even try eta expansion unless the rhs looks
-       -- non-trivial.
-    dont_eta_expand (Lit _)     = True
-    dont_eta_expand (Var _)     = True
-    dont_eta_expand (Con _ _)   = True
-    dont_eta_expand (App f a)
-      | notValArg    a         = dont_eta_expand f
-    dont_eta_expand (Lam x b)
-      | notValBinder x         = dont_eta_expand b
-    dont_eta_expand _          = False
+    must_stay (Rec prs)    = False     -- No unlifted bindings in here
+    must_stay (NonRec b r) = isUnLiftedType (idType b)
 \end{code}
 
 
+
 %************************************************************************
 %*                                                                     *
-\subsection{Simplify a lambda abstraction}
+\subsection{Variables}
 %*                                                                     *
 %************************************************************************
 
-Simplify (\binders -> body) trying eta expansion and reduction, given that
-the abstraction will always be applied to at least min_no_of_args.
-
 \begin{code}
-simplValLam env expr min_no_of_args
-  | not (switchIsSet env SimplDoLambdaEtaExpansion) || -- Bale out if eta expansion off
+simplVar var cont
+  = getSubst           `thenSmpl` \ subst ->
+    case lookupIdSubst subst var of
+       DoneEx e        -> zapSubstEnv (simplExprF e cont)
+       ContEx env1 e   -> setSubstEnv env1 (simplExprF e cont)
+       DoneId var1 occ -> WARN( not (isInScope var1 subst) && mustHaveLocalBinding var1,
+                                text "simplVar:" <+> ppr var )
+                          zapSubstEnv (completeCall var1 occ cont)
+               -- The template is already simplified, so don't re-substitute.
+               -- This is VITAL.  Consider
+               --      let x = e in
+               --      let y = \z -> ...x... in
+               --      \ x -> ...y...
+               -- We'll clone the inner \x, adding x->x' in the id_subst
+               -- Then when we inline y, we must *not* replace x by x' in
+               -- the inlined copy!!
+
+---------------------------------------------------------
+--     Dealing with a call
+
+completeCall var occ_info cont
+  = getBlackList               `thenSmpl` \ black_list_fn ->
+    getInScope                 `thenSmpl` \ in_scope ->
+    getContArgs var cont       `thenSmpl` \ (args, call_cont, inline_call) ->
+    getDOptsSmpl               `thenSmpl` \ dflags ->
+    let
+       black_listed       = black_list_fn var
+       arg_infos          = [ interestingArg in_scope arg subst 
+                            | (arg, subst, _) <- args, isValArg arg]
 
--- We used to disable eta expansion for thunks, but I don't see why.
---    null binders                                 ||  -- or it's a thunk
+       interesting_cont = interestingCallContext (not (null args)) 
+                                                 (not (null arg_infos))
+                                                 call_cont
 
-    null potential_extra_binder_tys                ||  -- or ain't a function
-    no_of_extra_binders <= 0                           -- or no extra binders needed
-  = cloneIds env binders               `thenSmpl` \ binders' ->
-    let
-       new_env = extendIdEnvWithClones env binders binders'
+       inline_cont | inline_call = discardInline cont
+                   | otherwise   = cont
+
+       maybe_inline = callSiteInline dflags black_listed inline_call occ_info
+                                     var arg_infos interesting_cont
     in
-    simplExpr new_env body []          `thenSmpl` \ body' ->
-    returnSmpl (
-      (if switchIsSet new_env SimplDoEtaReduction
-       then mkValLamTryingEta
-       else mkValLam) binders' body',
-      atLeastArity no_of_binders
-    )
+       -- First, look for an inlining
+    case maybe_inline of {
+       Just unfolding          -- There is an inlining!
+         ->  tick (UnfoldingDone var)          `thenSmpl_`
+             simplExprF unfolding inline_cont
+
+       ;
+       Nothing ->              -- No inlining!
+
 
-  | otherwise                          -- Eta expansion possible
-  = tick EtaExpansion                  `thenSmpl_`
-    cloneIds env binders               `thenSmpl` \ binders' ->
+    simplifyArgs (isDataConId var) args (contResultType call_cont)  $ \ args' ->
+
+       -- Next, look for rules or specialisations that match
+       --
+       -- It's important to simplify the args first, because the rule-matcher
+       -- doesn't do substitution as it goes.  We don't want to use subst_args
+       -- (defined in the 'where') because that throws away useful occurrence info,
+       -- and perhaps-very-important specialisations.
+       --
+       -- Some functions have specialisations *and* are strict; in this case,
+       -- we don't want to inline the wrapper of the non-specialised thing; better
+       -- to call the specialised thing instead.
+       -- But the black-listing mechanism means that inlining of the wrapper
+       -- won't occur for things that have specialisations till a later phase, so
+       -- it's ok to try for inlining first.
+       --
+       -- You might think that we shouldn't apply rules for a loop breaker: 
+       -- doing so might give rise to an infinite loop, because a RULE is
+       -- rather like an extra equation for the function:
+       --      RULE:           f (g x) y = x+y
+       --      Eqn:            f a     y = a-y
+       --
+       -- But it's too drastic to disable rules for loop breakers.  
+       -- Even the foldr/build rule would be disabled, because foldr 
+       -- is recursive, and hence a loop breaker:
+       --      foldr k z (build g) = g k z
+       -- So it's up to the programmer: rules can cause divergence
+
+    getSwitchChecker   `thenSmpl` \ chkr ->
     let
-       new_env = extendIdEnvWithClones env binders binders'
+       maybe_rule | switchIsOn chkr DontApplyRules = Nothing
+                  | otherwise                      = lookupRule in_scope var args' 
     in
-    newIds extra_binder_tys                            `thenSmpl` \ extra_binders' ->
-    simplExpr new_env body (map VarArg extra_binders') `thenSmpl` \ body' ->
-    returnSmpl (
-      (if switchIsSet new_env SimplDoEtaReduction
-       then mkValLamTryingEta
-       else mkValLam) (binders' ++ extra_binders') body',
-      atLeastArity (no_of_binders + no_of_extra_binders)
-    )
+    case maybe_rule of {
+       Just (rule_name, rule_rhs) -> 
+               tick (RuleFired rule_name)                      `thenSmpl_`
+#ifdef DEBUG
+               (if dopt Opt_D_dump_inlinings dflags then
+                  pprTrace "Rule fired" (vcat [
+                       text "Rule:" <+> ptext rule_name,
+                       text "Before:" <+> ppr var <+> sep (map pprParendExpr args'),
+                       text "After: " <+> pprCoreExpr rule_rhs])
+                else
+                       id)             $
+#endif
+               simplExprF rule_rhs call_cont ;
+       
+       Nothing ->              -- No rules
+
+       -- Done
+    rebuild (mkApps (Var var) args') call_cont
+    }}
+
+
+---------------------------------------------------------
+--     Simplifying the arguments of a call
+
+simplifyArgs :: Bool                           -- It's a data constructor
+            -> [(InExpr, SubstEnv, Bool)]      -- Details of the arguments
+            -> OutType                         -- Type of the continuation
+            -> ([OutExpr] -> SimplM OutExprStuff)
+            -> SimplM OutExprStuff
+
+-- Simplify the arguments to a call.
+-- This part of the simplifier may break the no-shadowing invariant
+-- Consider
+--     f (...(\a -> e)...) (case y of (a,b) -> e')
+-- where f is strict in its second arg
+-- If we simplify the innermost one first we get (...(\a -> e)...)
+-- Simplifying the second arg makes us float the case out, so we end up with
+--     case y of (a,b) -> f (...(\a -> e)...) e'
+-- So the output does not have the no-shadowing invariant.  However, there is
+-- no danger of getting name-capture, because when the first arg was simplified
+-- we used an in-scope set that at least mentioned all the variables free in its
+-- static environment, and that is enough.
+--
+-- We can't just do innermost first, or we'd end up with a dual problem:
+--     case x of (a,b) -> f e (...(\a -> e')...)
+--
+-- I spent hours trying to recover the no-shadowing invariant, but I just could
+-- not think of an elegant way to do it.  The simplifier is already knee-deep in
+-- continuations.  We have to keep the right in-scope set around; AND we have
+-- to get the effect that finding (error "foo") in a strict arg position will
+-- discard the entire application and replace it with (error "foo").  Getting
+-- all this at once is TOO HARD!
+
+simplifyArgs is_data_con args cont_ty thing_inside
+  | not is_data_con
+  = go args thing_inside
+
+  | otherwise  -- It's a data constructor, so we want 
+               -- to switch off inlining in the arguments
+               -- If we don't do this, consider:
+               --      let x = +# p q in C {x}
+               -- Even though x get's an occurrence of 'many', its RHS looks cheap,
+               -- and there's a good chance it'll get inlined back into C's RHS. Urgh!
+  = getBlackList                               `thenSmpl` \ old_bl ->
+    setBlackList noInlineBlackList             $
+    go args                                    $ \ args' ->
+    setBlackList old_bl                                $
+    thing_inside args'
 
   where
-    (binders,body) = collectValBinders expr
-    no_of_binders  = length binders
-    (potential_extra_binder_tys, res_ty)
-       = splitFunTy (simplTy env (coreExprType (unTagBinders body)))
-       -- Note: it's possible that simplValLam will be applied to something
-       -- with a forall type.  Eg when being applied to the rhs of
-       --              let x = wurble
-       -- where wurble has a forall-type, but no big lambdas at the top.
-       -- We could be clever an insert new big lambdas, but we don't bother.
-
-    extra_binder_tys = take no_of_extra_binders potential_extra_binder_tys
-
-    no_of_extra_binders =      -- First, use the info about how many args it's
-                               -- always applied to in its scope; but ignore this
-                               -- if it's a thunk!  To see why we ignore it for thunks,
-                               -- consider     let f = lookup env key in (f 1, f 2)
-                               -- We'd better not eta expand f just because it is 
-                               -- always applied!
-                          (if null binders
-                           then 0 
-                           else min_no_of_args - no_of_binders)
-
-                               -- Next, try seeing if there's a lambda hidden inside
-                               -- something cheap
-                          `max`
-                          etaExpandCount body
-
-                               -- Finally, see if it's a state transformer, in which
-                               -- case we eta-expand on principle! This can waste work,
-                               -- but usually doesn't
-                          `max`
-                          case potential_extra_binder_tys of
-                               [ty] | ty `eqTy` realWorldStateTy -> 1
-                               other                             -> 0
-\end{code}
+    go []        thing_inside = thing_inside []
+    go (arg:args) thing_inside = simplifyArg is_data_con arg cont_ty   $ \ arg' ->
+                                go args                                $ \ args' ->
+                                thing_inside (arg':args')
 
+simplifyArg is_data_con (Type ty_arg, se, _) cont_ty thing_inside
+  = simplTyArg ty_arg se       `thenSmpl` \ new_ty_arg ->
+    thing_inside (Type new_ty_arg)
+
+simplifyArg is_data_con (val_arg, se, is_strict) cont_ty thing_inside
+  = getInScope         `thenSmpl` \ in_scope ->
+    let
+       arg_ty = substTy (mkSubst in_scope se) (exprType val_arg)
+    in
+    if not is_data_con then
+       -- An ordinary function
+       simplValArg arg_ty is_strict val_arg se cont_ty thing_inside
+    else
+       -- A data constructor
+       -- simplifyArgs has already switched off inlining, so 
+       -- all we have to do here is to let-bind any non-trivial argument
+
+       -- It's not always the case that new_arg will be trivial
+       -- Consider             f x
+       -- where, in one pass, f gets substituted by a constructor,
+       -- but x gets substituted by an expression (assume this is the
+       -- unique occurrence of x).  It doesn't really matter -- it'll get
+       -- fixed up next pass.  And it happens for dictionary construction,
+       -- which mentions the wrapper constructor to start with.
+       simplValArg arg_ty is_strict val_arg se cont_ty         $ \ arg' ->
+       
+       if exprIsTrivial arg' then
+            thing_inside arg'
+       else
+       newId SLIT("a") (exprType arg')         $ \ arg_id ->
+       addNonRecBind arg_id arg'               $
+       thing_inside (Var arg_id)
+\end{code}                
 
 
 %************************************************************************
 %*                                                                     *
-\subsection[Simplify-coerce]{Coerce expressions}
+\subsection{Decisions about inlining}
 %*                                                                     *
 %************************************************************************
 
-\begin{code}
--- (coerce (case s of p -> r)) args ==> case s of p -> (coerce r) args
-simplCoerce env coercion ty expr@(Case scrut alts) args
-  = simplCase env scrut alts (\env rhs -> simplCoerce env coercion ty rhs args)
-                            (computeResultType env expr args)
-
--- (coerce (let defns in b)) args  ==> let defns' in (coerce b) args
-simplCoerce env coercion ty (Let bind body) args
-  = simplBind env bind (\env -> simplCoerce env coercion ty body args)
-                      (computeResultType env body args)
-
--- Default case
-simplCoerce env coercion ty expr args
-  = simplExpr env expr []      `thenSmpl` \ expr' ->
-    returnSmpl (mkGenApp (mkCoerce coercion (simplTy env ty) expr') args)
-  where
+NB: At one time I tried not pre/post-inlining top-level things,
+even if they occur exactly once.  Reason: 
+       (a) some might appear as a function argument, so we simply
+               replace static allocation with dynamic allocation:
+                  l = <...>
+                  x = f l
+       becomes
+                  x = f <...>
 
-       -- Try cancellation; we do this "on the way up" because
-       -- I think that's where it'll bite best
-    mkCoerce (CoerceOut con1) ty1 (Coerce (CoerceIn  con2) ty2 body) | con1 == con2 = body
-    mkCoerce coercion ty  body = Coerce coercion ty body
-\end{code}
+       (b) some top level things might be black listed
 
+HOWEVER, I found that some useful foldr/build fusion was lost (most
+notably in spectral/hartel/parstof) because the foldr didn't see the build.
 
-%************************************************************************
-%*                                                                     *
-\subsection[Simplify-let]{Let-expressions}
-%*                                                                     *
-%************************************************************************
+Doing the dynamic allocation isn't a big deal, in fact, but losing the
+fusion can be.
 
 \begin{code}
-simplBind :: SimplEnv
-         -> InBinding
-         -> (SimplEnv -> SmplM OutExpr)
-         -> OutType
-         -> SmplM OutExpr
+preInlineUnconditionally :: Bool {- Black listed -} -> InId -> Bool
+       -- Examines a bndr to see if it is used just once in a 
+       -- completely safe way, so that it is safe to discard the binding
+       -- inline its RHS at the (unique) usage site, REGARDLESS of how
+       -- big the RHS might be.  If this is the case we don't simplify
+       -- the RHS first, but just inline it un-simplified.
+       --
+       -- This is much better than first simplifying a perhaps-huge RHS
+       -- and then inlining and re-simplifying it.
+       --
+       -- NB: we don't even look at the RHS to see if it's trivial
+       -- We might have
+       --                      x = y
+       -- where x is used many times, but this is the unique occurrence
+       -- of y.  We should NOT inline x at all its uses, because then
+       -- we'd do the same for y -- aargh!  So we must base this
+       -- pre-rhs-simplification decision solely on x's occurrences, not
+       -- on its rhs.
+       -- 
+       -- Evne RHSs labelled InlineMe aren't caught here, because
+       -- there might be no benefit from inlining at the call site.
+
+preInlineUnconditionally black_listed bndr
+  | black_listed || opt_SimplNoPreInlining = False
+  | otherwise = case idOccInfo bndr of
+                 OneOcc in_lam once -> not in_lam && once
+                       -- Not inside a lambda, one occurrence ==> safe!
+                 other              -> False
 \end{code}
 
-When floating cases out of lets, remember this:
 
-       let x* = case e of alts
-       in <small expr>
 
-where x* is sure to be demanded or e is a cheap operation that cannot
-fail, e.g. unboxed addition.  Here we should be prepared to duplicate
-<small expr>.  A good example:
+%************************************************************************
+%*                                                                     *
+\subsection{The main rebuilder}
+%*                                                                     *
+%************************************************************************
 
-       let x* = case y of
-                  p1 -> build e1
-                  p2 -> build e2
-       in
-       foldr c n x*
-==>
-       case y of
-         p1 -> foldr c n (build e1)
-         p2 -> foldr c n (build e2)
+\begin{code}
+-------------------------------------------------------------------
+-- Finish rebuilding
+rebuild_done expr = returnOutStuff expr
 
-NEW: We use the same machinery that we use for case-of-case to
-*always* do case floating from let, that is we let bind and abstract
-the original let body, and let the occurrence analyser later decide
-whether the new let should be inlined or not. The example above
-becomes:
+---------------------------------------------------------
+rebuild :: OutExpr -> SimplCont -> SimplM OutExprStuff
 
-==>
-      let join_body x' = foldr c n x'
-       in case y of
-       p1 -> let x* = build e1
-               in join_body x*
-       p2 -> let x* = build e2
-               in join_body x*
+--     Stop continuation
+rebuild expr (Stop _ _) = rebuild_done expr
 
-note that join_body is a let-no-escape.
-In this particular example join_body will later be inlined,
-achieving the same effect.
-ToDo: check this is OK with andy
+--     ArgOf continuation
+rebuild expr (ArgOf _ _ cont_fn) = cont_fn expr
 
+--     ApplyTo continuation
+rebuild expr cont@(ApplyTo _ arg se cont')
+  = setSubstEnv se (simplExpr arg)     `thenSmpl` \ arg' ->
+    rebuild (App expr arg') cont'
 
+--     Coerce continuation
+rebuild expr (CoerceIt to_ty cont)
+  = rebuild (mkCoerce to_ty (exprType expr) expr) cont
 
-\begin{code}
--- Dead code is now discarded by the occurrence analyser,
+--     Inline continuation
+rebuild expr (InlinePlease cont)
+  = rebuild (Note InlineCall expr) cont
 
-simplBind env (NonRec binder@(id,occ_info) rhs) body_c body_ty
-  | idWantsToBeINLINEd id
-  = complete_bind env rhs      -- Don't messa bout with floating or let-to-case on
-                               -- INLINE things
-  | otherwise
-  = simpl_bind env rhs
-  where
-    -- Try let-to-case; see notes below about let-to-case
-    simpl_bind env rhs | will_be_demanded &&
-                        try_let_to_case &&
-                        type_ok_for_let_to_case rhs_ty &&
-                        not rhs_is_whnf        -- note: WHNF, but not bottom,  (comment below)
-      = tick Let2Case                          `thenSmpl_`
-        mkIdentityAlts rhs_ty                  `thenSmpl` \ id_alts ->
-        simplCase env rhs id_alts (\env rhs -> complete_bind env rhs) body_ty
-               -- NB: it's tidier to call complete_bind not simpl_bind, else
-               -- we nearly end up in a loop.  Consider:
-               --      let x = rhs in b
-               -- ==>  case rhs of (p,q) -> let x=(p,q) in b
-               -- This effectively what the above simplCase call does.
-               -- Now, the inner let is a let-to-case target again!  Actually, since
-               -- the RHS is in WHNF it won't happen, but it's a close thing!
-
-    -- Try let-from-let
-    simpl_bind env (Let bind rhs) | let_floating_ok
-      = tick LetFloatFromLet                    `thenSmpl_`
-       simplBind env (fix_up_demandedness will_be_demanded bind)
-                     (\env -> simpl_bind env rhs) body_ty
-
-    -- Try case-from-let; this deals with a strict let of error too
-    simpl_bind env (Case scrut alts) | will_be_demanded || 
-                                      (float_primops && is_cheap_prim_app scrut)
-      = tick CaseFloatFromLet                          `thenSmpl_`
-
-       -- First, bind large let-body if necessary
-       if ok_to_dup || isSingleton (nonErrorRHSs alts)
-       then
-           simplCase env scrut alts (\env rhs -> simpl_bind env rhs) body_ty
-       else
-           bindLargeRhs env [binder] body_ty body_c    `thenSmpl` \ (extra_binding, new_body) ->
-           let
-               body_c' = \env -> simplExpr env new_body []
-               case_c  = \env rhs -> simplBind env (NonRec binder rhs) body_c' body_ty
-           in
-           simplCase env scrut alts case_c body_ty     `thenSmpl` \ case_expr ->
-           returnSmpl (Let extra_binding case_expr)
-
-    -- None of the above; simplify rhs and tidy up
-    simpl_bind env rhs = complete_bind env rhs
-    complete_bind env rhs
-      = simplRhsExpr env binder rhs            `thenSmpl` \ (rhs',arity) ->
-       cloneId env binder                      `thenSmpl` \ new_id ->
-       completeNonRec env binder 
-               (new_id `withArity` arity) rhs' `thenSmpl` \ (new_env, binds) ->
-        body_c new_env                         `thenSmpl` \ body' ->
-        returnSmpl (mkCoLetsAny binds body')
-
-
-       -- All this stuff is computed at the start of the simpl_bind loop
-    float_lets               = switchIsSet env SimplFloatLetsExposingWHNF
-    float_primops            = switchIsSet env SimplOkToFloatPrimOps
-    ok_to_dup                = switchIsSet env SimplOkToDupCode
-    always_float_let_from_let = switchIsSet env SimplAlwaysFloatLetsFromLets
-    try_let_to_case           = switchIsSet env SimplLetToCase
-    no_float                 = switchIsSet env SimplNoLetFromStrictLet
-
-    will_be_demanded = willBeDemanded (getIdDemandInfo id)
-    rhs_ty          = idType id
-
-    rhs_is_whnf = case mkFormSummary rhs of
-                       VarForm -> True
-                       ValueForm -> True
-                       other -> False
-
-    let_floating_ok  = (will_be_demanded && not no_float) ||
-                      always_float_let_from_let ||
-                      floatExposesHNF float_lets float_primops ok_to_dup rhs
+rebuild scrut (Select _ bndr alts se cont)
+  = rebuild_case scrut bndr alts se cont
 \end{code}
 
-Let to case
-~~~~~~~~~~~
-It's important to try let-to-case before floating. Consider
-
-       let a*::Int = case v of {p1->e1; p2->e2}
-       in b
-
-(The * means that a is sure to be demanded.)
-If we do case-floating first we get this:
+Case elimination [see the code above]
+~~~~~~~~~~~~~~~~
+Start with a simple situation:
+
+       case x# of      ===>   e[x#/y#]
+         y# -> e
+
+(when x#, y# are of primitive type, of course).  We can't (in general)
+do this for algebraic cases, because we might turn bottom into
+non-bottom!
+
+Actually, we generalise this idea to look for a case where we're
+scrutinising a variable, and we know that only the default case can
+match.  For example:
+\begin{verbatim}
+       case x of
+         0#    -> ...
+         other -> ...(case x of
+                        0#    -> ...
+                        other -> ...) ...
+\end{code}
+Here the inner case can be eliminated.  This really only shows up in
+eliminating error-checking code.
 
-       let k = \a* -> b
-       in case v of
-               p1-> let a*=e1 in k a
-               p2-> let a*=e2 in k a
+We also make sure that we deal with this very common case:
 
-Now watch what happens if we do let-to-case first:
+       case e of 
+         x -> ...x...
 
-       case (case v of {p1->e1; p2->e2}) of
-         Int a# -> let a*=I# a# in b
-===>
-       let k = \a# -> let a*=I# a# in b
-       in case v of
-               p1 -> case e1 of I# a# -> k a#
-               p1 -> case e1 of I# a# -> k a#
+Here we are using the case as a strict let; if x is used only once
+then we want to inline it.  We have to be careful that this doesn't 
+make the program terminate when it would have diverged before, so we
+check that 
+       - x is used strictly, or
+       - e is already evaluated (it may so if e is a variable)
 
-The latter is clearly better.  (Remember the reboxing let-decl for a
-is likely to go away, because after all b is strict in a.)
+Lastly, we generalise the transformation to handle this:
 
-We do not do let to case for WHNFs, e.g.
+       case e of       ===> r
+          True  -> r
+          False -> r
 
-         let x = a:b in ...
-         =/=>
-         case a:b of x in ...
+We only do this for very cheaply compared r's (constructors, literals
+and variables).  If pedantic bottoms is on, we only do it when the
+scrutinee is a PrimOp which can't fail.
 
-as this is less efficient.  but we don't mind doing let-to-case for
-"bottom", as that will allow us to remove more dead code, if anything:
+We do it *here*, looking at un-simplified alternatives, because we
+have to check that r doesn't mention the variables bound by the
+pattern in each alternative, so the binder-info is rather useful.
 
-         let x = error in ...
-         ===>
-         case error  of x -> ...
-         ===>
-         error
+So the case-elimination algorithm is:
 
-Notice that let to case occurs only if x is used strictly in its body
-(obviously).
+       1. Eliminate alternatives which can't match
 
+       2. Check whether all the remaining alternatives
+               (a) do not mention in their rhs any of the variables bound in their pattern
+          and  (b) have equal rhss
 
-Letrec expressions
-~~~~~~~~~~~~~~~~~~
+       3. Check we can safely ditch the case:
+                  * PedanticBottoms is off,
+               or * the scrutinee is an already-evaluated variable
+               or * the scrutinee is a primop which is ok for speculation
+                       -- ie we want to preserve divide-by-zero errors, and
+                       -- calls to error itself!
 
-Simplify each RHS, float any let(recs) from the RHSs (if let-floating is
-on and it'll expose a HNF), and bang the whole resulting mess together
-into a huge letrec.
+               or * [Prim cases] the scrutinee is a primitive variable
 
-1. Any "macros" should be expanded.  The main application of this
-macro-expansion is:
+               or * [Alg cases] the scrutinee is a variable and
+                    either * the rhs is the same variable
+                       (eg case x of C a b -> x  ===>   x)
+                    or     * there is only one alternative, the default alternative,
+                               and the binder is used strictly in its scope.
+                               [NB this is helped by the "use default binder where
+                                possible" transformation; see below.]
 
-       letrec
-               f = ....g...
-               g = ....f...
-       in
-       ....f...
 
-Here we would like the single call to g to be inlined.
+If so, then we can replace the case with one of the rhss.
 
-We can spot this easily, because g will be tagged as having just one
-occurrence.  The "inlineUnconditionally" predicate is just what we want.
 
-A worry: could this lead to non-termination?  For example:
+Blob of helper functions for the "case-of-something-else" situation.
 
-       letrec
-               f = ...g...
-               g = ...f...
-               h = ...h...
-       in
-       ..h..
+\begin{code}
+---------------------------------------------------------
+--     Eliminate the case if possible
 
-Here, f and g call each other (just once) and neither is used elsewhere.
-But it's OK:
+rebuild_case scrut bndr alts se cont
+  | maybeToBool maybe_con_app
+  = knownCon scrut (DataAlt con) args bndr alts se cont
 
-* the occurrence analyser will drop any (sub)-group that isn't used at
-  all.
+  | canEliminateCase scrut bndr alts
+  = tick (CaseElim bndr)                       `thenSmpl_` (
+    setSubstEnv se                             $                       
+    simplBinder bndr                           $ \ bndr' ->
+       -- Remember to bind the case binder!
+    completeBinding bndr bndr' False False scrut       $
+    simplExprF (head (rhssOfAlts alts)) cont)
 
-* If the group is used outside itself (ie in the "in" part), then there
-  can't be a cyle.
+  | otherwise
+  = complete_case scrut bndr alts se cont
 
-** IMPORTANT: check that NewOccAnal has the property that a group of
-   bindings like the above has f&g dropped.! ***
+  where
+    maybe_con_app    = exprIsConApp_maybe scrut
+    Just (con, args) = maybe_con_app
+
+       -- See if we can get rid of the case altogether
+       -- See the extensive notes on case-elimination above
+canEliminateCase scrut bndr alts
+  =    -- Check that the RHSs are all the same, and
+       -- don't use the binders in the alternatives
+       -- This test succeeds rapidly in the common case of
+       -- a single DEFAULT alternative
+    all (cheapEqExpr rhs1) other_rhss && all binders_unused alts
+
+       -- Check that the scrutinee can be let-bound instead of case-bound
+    && (   exprOkForSpeculation scrut
+               -- OK not to evaluate it
+               -- This includes things like (==# a# b#)::Bool
+               -- so that we simplify 
+               --      case ==# a# b# of { True -> x; False -> x }
+               -- to just
+               --      x
+               -- This particular example shows up in default methods for
+               -- comparision operations (e.g. in (>=) for Int.Int32)
+       || exprIsValue scrut                    -- It's already evaluated
+       || var_demanded_later scrut             -- It'll be demanded later
+
+--      || not opt_SimplPedanticBottoms)       -- Or we don't care!
+--     We used to allow improving termination by discarding cases, unless -fpedantic-bottoms was on,
+--     but that breaks badly for the dataToTag# primop, which relies on a case to evaluate
+--     its argument:  case x of { y -> dataToTag# y }
+--     Here we must *not* discard the case, because dataToTag# just fetches the tag from
+--     the info pointer.  So we'll be pedantic all the time, and see if that gives any
+--     other problems
+       )
 
+  where
+    (rhs1:other_rhss)           = rhssOfAlts alts
+    binders_unused (_, bndrs, _) = all isDeadBinder bndrs
 
-2. We'd also like to pull out any top-level let(rec)s from the
-rhs of the defns:
+    var_demanded_later (Var v) = isStrict (idDemandInfo bndr)  -- It's going to be evaluated later
+    var_demanded_later other   = False
 
-       letrec
-               f = let h = ... in \x -> ....h...f...h...
-       in
-       ...f...
-====>
-       letrec
-               h = ...
-               f = \x -> ....h...f...h...
-       in
-       ...f...
 
-But floating cases is less easy?  (Don't for now; ToDo?)
+---------------------------------------------------------
+--     Case of something else
 
+complete_case scrut case_bndr alts se cont
+  =    -- Prepare case alternatives
+    prepareCaseAlts case_bndr (splitTyConApp_maybe (idType case_bndr))
+                   impossible_cons alts                `thenSmpl` \ better_alts ->
+    
+       -- Set the new subst-env in place (before dealing with the case binder)
+    setSubstEnv se                             $
 
-3.  We'd like to arrange that the RHSs "know" about members of the
-group that are bound to constructors.  For example:
-
-    let rec
-       d.Eq      = (==,/=)
-       f a b c d = case d.Eq of (h,_) -> let x = (a,b); y = (c,d) in not (h x y)
-       /= a b    = unpack tuple a, unpack tuple b, call f
-    in d.Eq
+       -- Deal with the case binder, and prepare the continuation;
+       -- The new subst_env is in place
+    prepareCaseCont better_alts cont           $ \ cont' ->
+       
 
-here, by knowing about d.Eq in f's rhs, one could get rid of
-the case (and break out the recursion completely).
-[This occurred with more aggressive inlining threshold (4),
-nofib/spectral/knights]
+       -- Deal with variable scrutinee
+    (  
+        getSwitchChecker                               `thenSmpl` \ chkr ->
+       simplCaseBinder (switchIsOn chkr NoCaseOfCase)
+                       scrut case_bndr                 $ \ case_bndr' zap_occ_info ->
 
-How to do it?
-       1: we simplify constructor rhss first.
-       2: we record the "known constructors" in the environment
-       3: we simplify the other rhss, with the knowledge about the constructors
+       -- Deal with the case alternatives
+       simplAlts zap_occ_info impossible_cons
+                 case_bndr' better_alts cont'  `thenSmpl` \ alts' ->
 
+       mkCase scrut case_bndr' alts'
+    )                                          `thenSmpl` \ case_expr ->
 
+       -- Notice that the simplBinder, prepareCaseCont, etc, do *not* scope
+       -- over the rebuild_done; rebuild_done returns the in-scope set, and
+       -- that should not include these chaps!
+    rebuild_done case_expr     
+  where
+    impossible_cons = case scrut of
+                           Var v -> otherCons (idUnfolding v)
+                           other -> []
+
+
+knownCon :: OutExpr -> AltCon -> [OutExpr]
+        -> InId -> [InAlt] -> SubstEnv -> SimplCont
+        -> SimplM OutExprStuff
+
+knownCon expr con args bndr alts se cont
+  =    -- Arguments should be atomic;
+       -- yell if not
+    WARN( not (all exprIsTrivial args), 
+         text "knownCon" <+> ppr expr )
+    tick (KnownBranch bndr)    `thenSmpl_`
+    setSubstEnv se             (
+    simplBinder bndr           $ \ bndr' ->
+    completeBinding bndr bndr' False False expr $
+       -- Don't use completeBeta here.  The expr might be
+       -- an unboxed literal, like 3, or a variable
+       -- whose unfolding is an unboxed literal... and
+       -- completeBeta will just construct another case
+                                       -- expression!
+    case findAlt con alts of
+       (DEFAULT, bs, rhs)     -> ASSERT( null bs )
+                                 simplExprF rhs cont
+
+       (LitAlt lit, bs, rhs) ->  ASSERT( null bs )
+                                 simplExprF rhs cont
+
+       (DataAlt dc, bs, rhs)  -> ASSERT( length bs == length real_args )
+                                 extendSubstList bs (map mk real_args) $
+                                 simplExprF rhs cont
+                              where
+                                 real_args    = drop (dataConNumInstArgs dc) args
+                                 mk (Type ty) = DoneTy ty
+                                 mk other     = DoneEx other
+    )
+\end{code}
 
 \begin{code}
-simplBind env (Rec pairs) body_c body_ty
-  =    -- Do floating, if necessary
-    let
-        floated_pairs | do_floating = float_pairs pairs
-                     | otherwise   = pairs
+prepareCaseCont :: [InAlt] -> SimplCont
+               -> (SimplCont -> SimplM (OutStuff a))
+               -> SimplM (OutStuff a)
+       -- Polymorphic recursion here!
+
+prepareCaseCont [alt] cont thing_inside = thing_inside cont
+prepareCaseCont alts  cont thing_inside = simplType (coreAltsType alts)                `thenSmpl` \ alts_ty ->
+                                         mkDupableCont alts_ty cont thing_inside
+       -- At one time I passed in the un-simplified type, and simplified
+       -- it only if we needed to construct a join binder, but that    
+       -- didn't work because we have to decompse function types
+       -- (using funResultTy) in mkDupableCont.
+\end{code}
 
-       ticks         | do_floating = length floated_pairs - length pairs
-                     | otherwise   = 0
+simplCaseBinder checks whether the scrutinee is a variable, v.  If so,
+try to eliminate uses of v in the RHSs in favour of case_bndr; that
+way, there's a chance that v will now only be used once, and hence
+inlined.
 
-       binders       = map fst floated_pairs
-    in
-    tickN LetFloatFromLet ticks                `thenSmpl_` 
-               -- It's important to increment the tick counts if we
-               -- do any floating.  A situation where this turns out
-               -- to be important is this:
-               -- Float in produces:
-               --      letrec  x = let y = Ey in Ex
-               --      in B
-               -- Now floating gives this:
-               --      letrec x = Ex
-               --             y = Ey
-               --      in B
-               --- We now want to iterate once more in case Ey doesn't
-               -- mention x, in which case the y binding can be pulled
-               -- out as an enclosing let(rec), which in turn gives
-               -- the strictness analyser more chance.
-
-    cloneIds env binders                       `thenSmpl` \ ids' ->
-    let
-       env_w_clones = extendIdEnvWithClones env binders ids'
-    in
-    simplRecursiveGroup env_w_clones ids' floated_pairs        `thenSmpl` \ (binding, new_env) ->
+There is a time we *don't* want to do that, namely when
+-fno-case-of-case is on.  This happens in the first simplifier pass,
+and enhances full laziness.  Here's the bad case:
+       f = \ y -> ...(case x of I# v -> ...(case x of ...) ... )
+If we eliminate the inner case, we trap it inside the I# v -> arm,
+which might prevent some full laziness happening.  I've seen this
+in action in spectral/cichelli/Prog.hs:
+        [(m,n) | m <- [1..max], n <- [1..max]]
+Hence the no_case_of_case argument
 
-    body_c new_env                             `thenSmpl` \ body' ->
 
-    returnSmpl (Let binding body')
+If we do this, then we have to nuke any occurrence info (eg IAmDead)
+in the case binder, because the case-binder now effectively occurs
+whenever v does.  AND we have to do the same for the pattern-bound
+variables!  Example:
 
-  where
-    ------------ Floating stuff -------------------
+       (case x of { (a,b) -> a }) (case x of { (p,q) -> q })
 
-    float_lets               = switchIsSet env SimplFloatLetsExposingWHNF
-    always_float_let_from_let = switchIsSet env SimplAlwaysFloatLetsFromLets
-    do_floating              = float_lets || always_float_let_from_let
+Here, b and p are dead.  But when we move the argment inside the first
+case RHS, and eliminate the second case, we get
 
-    float_pairs pairs = concat (map float_pair pairs)
+       case x or { (a,b) -> a b }
 
-    float_pair (binder, rhs)
-       | always_float_let_from_let ||
-         floatExposesHNF True False False rhs
-       = (binder,rhs') : pairs'
+Urk! b is alive!  Reason: the scrutinee was a variable, and case elimination
+happened.  Hence the zap_occ_info function returned by simplCaseBinder
 
-       | otherwise
-       = [(binder,rhs)]
-       where
-         (pairs', rhs') = do_float rhs
-
-       -- Float just pulls out any top-level let(rec) bindings
-    do_float :: InExpr -> ([(InBinder,InExpr)], InExpr)
-    do_float (Let (Rec pairs) body)     = (float_pairs pairs    ++ pairs', body')
-                                           where
-                                             (pairs', body') = do_float body
-    do_float (Let (NonRec id rhs) body) = (float_pair (id,rhs) ++ pairs', body')
-                                           where
-                                             (pairs', body') = do_float body
-    do_float other                         = ([], other)
-
-
--- The env passed to simplRecursiveGroup already has 
--- bindings that clone the variables of the group.
-simplRecursiveGroup env new_ids pairs 
-  =    -- Add unfoldings to the new_ids corresponding to their RHS
-    let
-       binders        = map fst pairs
-       occs            = map snd binders
-       new_ids_w_pairs = zipEqual "simplRecGp" new_ids pairs
-       rhs_env         = foldl extendEnvForRecBinding 
-                              env new_ids_w_pairs
-    in
+\begin{code}
+simplCaseBinder no_case_of_case (Var v) case_bndr thing_inside
+  | not no_case_of_case
+  = simplBinder (zap case_bndr)                                        $ \ case_bndr' ->
+    modifyInScope v case_bndr'                                 $
+       -- We could extend the substitution instead, but it would be
+       -- a hack because then the substitution wouldn't be idempotent
+       -- any more (v is an OutId).  And this just just as well.
+    thing_inside case_bndr' zap
+  where
+    zap b = b `setIdOccInfo` NoOccInfo
+           
+simplCaseBinder add_eval_info other_scrut case_bndr thing_inside
+  = simplBinder case_bndr              $ \ case_bndr' ->
+    thing_inside case_bndr' (\ bndr -> bndr)   -- NoOp on bndr
+\end{code}
 
-    mapSmpl (\(binder,rhs) -> simplRhsExpr rhs_env binder rhs) pairs   `thenSmpl` \ new_rhss_w_arities ->
+prepareCaseAlts does two things:
 
-    let
-       new_pairs = zipWithEqual "simplRecGp" mk_new_pair new_ids new_rhss_w_arities
-       mk_new_pair id (rhs,arity) = (id `withArity` arity, rhs)
-               -- NB: the new arity isn't used when processing its own
-               -- right hand sides, nor in the subsequent code
-               -- The latter is something of a pity, and not hard to fix; but
-               -- the info will percolate on the next iteration anyway
-
-{-     THE NEXT FEW LINES ARE PLAIN WRONG
-       occs_w_new_pairs = zipEqual "simplRecGp" occs new_pairs
-       new_env         = foldl add_binding env occs_w_new_pairs
-
-       add_binding env (occ_info,(new_id,new_rhs)) 
-         = extendEnvGivenBinding env occ_info new_id new_rhs
-
-Here's why it's wrong: consider
-       let f x = ...f x'...
-       in
-       f 3
+1.  Remove impossible alternatives
 
-If the RHS is small we'll inline f in the body of the let, then
-again, then again...URK
--}
-    in
-    returnSmpl (Rec new_pairs, rhs_env)
-\end{code}
+2.  If the DEFAULT alternative can match only one possible constructor,
+    then make that constructor explicit.
+    e.g.
+       case e of x { DEFAULT -> rhs }
+     ===>
+       case e of x { (a,b) -> rhs }
+    where the type is a single constructor type.  This gives better code
+    when rhs also scrutinises x or e.
 
+\begin{code}
+prepareCaseAlts bndr (Just (tycon, inst_tys)) scrut_cons alts
+  | isDataTyCon tycon
+  = case (findDefault filtered_alts, missing_cons) of
+
+       ((alts_no_deflt, Just rhs), [data_con])         -- Just one missing constructor!
+               -> tick (FillInCaseDefault bndr)        `thenSmpl_`
+                  let
+                       (_,_,ex_tyvars,_,_,_) = dataConSig data_con
+                  in
+                  getUniquesSmpl (length ex_tyvars)                            `thenSmpl` \ tv_uniqs ->
+                  let
+                       ex_tyvars' = zipWithEqual "simpl_alt" mk tv_uniqs ex_tyvars
+                       mk uniq tv = mkSysTyVar uniq (tyVarKind tv)
+                       arg_tys    = dataConArgTys data_con
+                                                  (inst_tys ++ mkTyVarTys ex_tyvars')
+                  in
+                  newIds SLIT("a") arg_tys             $ \ bndrs ->
+                  returnSmpl ((DataAlt data_con, ex_tyvars' ++ bndrs, rhs) : alts_no_deflt)
+
+       other -> returnSmpl filtered_alts
+  where
+       -- Filter out alternatives that can't possibly match
+    filtered_alts = case scrut_cons of
+                       []    -> alts
+                       other -> [alt | alt@(con,_,_) <- alts, not (con `elem` scrut_cons)]
 
-@completeLet@ looks at the simplified post-floating RHS of the
-let-expression, and decides what to do.  There's one interesting
-aspect to this, namely constructor reuse.  Consider
-@
-       f = \x -> case x of
-                   (y:ys) -> y:ys
-                   []     -> ...
-@
-Is it a good idea to replace the rhs @y:ys@ with @x@?  This depends a
-bit on the compiler technology, but in general I believe not. For
-example, here's some code from a real program:
-@
-const.Int.max.wrk{-s2516-} =
-    \ upk.s3297#  upk.s3298# ->
-       let {
-         a.s3299 :: Int
-         _N_ {-# U(P) #-}
-         a.s3299 = I#! upk.s3297#
-       } in
-         case (const.Int._tagCmp.wrk{-s2513-} upk.s3297# upk.s3298#) of {
-           _LT -> I#! upk.s3298#
-           _EQ -> a.s3299
-           _GT -> a.s3299
-         }
-@
-The a.s3299 really isn't doing much good.  We'd be better off inlining
-it.  (Actually, let-no-escapery means it isn't as bad as it looks.)
-
-So the current strategy is to inline all known-form constructors, and
-only do the reverse (turn a constructor application back into a
-variable) when we find a let-expression:
-@
-       let x = C a1 .. an
-       in
-       ... (let y = C a1 .. an in ...) ...
-@
-where it is always good to ditch the binding for y, and replace y by
-x.  That's just what completeLetBinding does.
+    missing_cons = [data_con | data_con <- tyConDataConsIfAvailable tycon, 
+                              not (data_con `elem` handled_data_cons)]
+    handled_data_cons = [data_con | DataAlt data_con         <- scrut_cons] ++
+                       [data_con | (DataAlt data_con, _, _) <- filtered_alts]
 
+-- The default case
+prepareCaseAlts _ _ scrut_cons alts
+  = returnSmpl alts                    -- Functions
 
-\begin{code}
-       -- We want to ensure that all let-bound Coerces have 
-       -- atomic bodies, so they can freely be inlined.
-completeNonRec env binder new_id (Coerce coercion ty rhs)
-  | not (is_atomic rhs)
-  = newId (coreExprType rhs)                           `thenSmpl` \ inner_id ->
-    completeNonRec env 
-                  (inner_id, dangerousArgOcc) inner_id rhs `thenSmpl` \ (env1, binds1) ->
-       -- Dangerous occ because, like constructor args,
-       -- it can be duplicated easily
-    let
-       atomic_rhs = case lookupId env1 inner_id of
-                       LitArg l -> Lit l
-                       VarArg v -> Var v
-    in
-    completeNonRec env1 binder new_id
-                  (Coerce coercion ty atomic_rhs)      `thenSmpl` \ (env2, binds2) ->
 
-    returnSmpl (env2, binds1 ++ binds2)
+----------------------
+simplAlts zap_occ_info scrut_cons case_bndr' alts cont'
+  = mapSmpl simpl_alt alts
   where
-    is_atomic (Var v) = True
-    is_atomic (Lit l) = not (isNoRepLit l)
-    is_atomic other   = False
-       
-       -- Atomic right-hand sides.
-       -- We used to have a "tick AtomicRhs" in here, but it causes more trouble
-       -- than it's worth.  For a top-level binding a = b, where a is exported,
-       -- we can't drop the binding, so we get repeated AtomicRhs ticks
-completeNonRec env binder new_id rhs@(Var v)
-  = returnSmpl (extendIdEnvWithAtom env binder (VarArg v), [NonRec new_id rhs])
-
-completeNonRec env binder new_id rhs@(Lit lit)
-  | not (isNoRepLit lit)
-  = returnSmpl (extendIdEnvWithAtom env binder (LitArg lit), [NonRec new_id rhs])
-
-       -- Right hand sides that are constructors
-       --      let v = C args
-       --      in
-       --- ...(let w = C same-args in ...)...
-       -- Then use v instead of w.      This may save
-       -- re-constructing an existing constructor.
-completeNonRec env binder new_id rhs@(Con con con_args)
-  | switchIsSet env SimplReuseCon && 
-    maybeToBool maybe_existing_con &&
-    not (isExported new_id)            -- Don't bother for exported things
-                                       -- because we won't be able to drop
-                                       -- its binding.
-  = tick ConReused             `thenSmpl_`
-    returnSmpl (extendIdEnvWithAtom env binder (VarArg it), [NonRec new_id rhs])
-  where
-    maybe_existing_con = lookForConstructor env con con_args
-    Just it           = maybe_existing_con
-
-       -- Default case
-completeNonRec env binder@(id,occ_info) new_id rhs
- = returnSmpl (new_env, [NonRec new_id rhs])
- where
-   env1    = extendIdEnvWithClone env binder new_id
-   new_env = extendEnvGivenBinding env1 occ_info new_id rhs
-\end{code}
-
-%************************************************************************
-%*                                                                     *
-\subsection[Simplify-atoms]{Simplifying atoms}
-%*                                                                     *
-%************************************************************************
+    inst_tys' = tyConAppArgs (idType case_bndr')
+
+       -- handled_cons is all the constructors that are dealt
+       -- with, either by being impossible, or by there being an alternative
+    handled_cons = scrut_cons ++ [con | (con,_,_) <- alts, con /= DEFAULT]
+
+    simpl_alt (DEFAULT, _, rhs)
+       =       -- In the default case we record the constructors that the
+               -- case-binder *can't* be.
+               -- We take advantage of any OtherCon info in the case scrutinee
+         modifyInScope case_bndr' (case_bndr' `setIdUnfolding` mkOtherCon handled_cons)        $ 
+         simplExprC rhs cont'                                                  `thenSmpl` \ rhs' ->
+         returnSmpl (DEFAULT, [], rhs')
+
+    simpl_alt (con, vs, rhs)
+       =       -- Deal with the pattern-bound variables
+               -- Mark the ones that are in ! positions in the data constructor
+               -- as certainly-evaluated.
+               -- NB: it happens that simplBinders does *not* erase the OtherCon
+               --     form of unfolding, so it's ok to add this info before 
+               --     doing simplBinders
+         simplBinders (add_evals con vs)                                       $ \ vs' ->
+
+               -- Bind the case-binder to (con args)
+         let
+               unfolding = mkUnfolding False (mkAltExpr con vs' inst_tys')
+         in
+         modifyInScope case_bndr' (case_bndr' `setIdUnfolding` unfolding)      $
+         simplExprC rhs cont'          `thenSmpl` \ rhs' ->
+         returnSmpl (con, vs', rhs')
+
+
+       -- add_evals records the evaluated-ness of the bound variables of
+       -- a case pattern.  This is *important*.  Consider
+       --      data T = T !Int !Int
+       --
+       --      case x of { T a b -> T (a+1) b }
+       --
+       -- We really must record that b is already evaluated so that we don't
+       -- go and re-evaluate it when constructing the result.
 
-\begin{code}
-simplArg :: SimplEnv -> InArg -> OutArg
+    add_evals (DataAlt dc) vs = cat_evals vs (dataConRepStrictness dc)
+    add_evals other_con    vs = vs
 
-simplArg env (LitArg lit) = LitArg lit
-simplArg env (TyArg  ty)  = TyArg  (simplTy env ty)
-simplArg env (VarArg id)  = lookupId env id
+    cat_evals [] [] = []
+    cat_evals (v:vs) (str:strs)
+       | isTyVar v    = v                                   : cat_evals vs (str:strs)
+       | isStrict str = (v' `setIdUnfolding` mkOtherCon []) : cat_evals vs strs
+       | otherwise    = v'                                  : cat_evals vs strs
+       where
+         v' = zap_occ_info v
 \end{code}
 
+
 %************************************************************************
 %*                                                                     *
-\subsection[Simplify-quickies]{Some local help functions}
+\subsection{Duplicating continuations}
 %*                                                                     *
 %************************************************************************
 
-
 \begin{code}
--- fix_up_demandedness switches off the willBeDemanded Info field
--- for bindings floated out of a non-demanded let
-fix_up_demandedness True {- Will be demanded -} bind
-   = bind      -- Simple; no change to demand info needed
-fix_up_demandedness False {- May not be demanded -} (NonRec binder rhs)
-   = NonRec (un_demandify binder) rhs
-fix_up_demandedness False {- May not be demanded -} (Rec pairs)
-   = Rec [(un_demandify binder, rhs) | (binder,rhs) <- pairs]
-
-un_demandify (id, occ_info) = (id `addIdDemandInfo` noDemandInfo, occ_info)
-
-is_cheap_prim_app (Prim op _) = primOpOkForSpeculation op
-is_cheap_prim_app other              = False
-
-computeResultType :: SimplEnv -> InExpr -> [OutArg] -> OutType
-computeResultType env expr args
-  = go expr_ty' args
-  where
-    expr_ty  = coreExprType (unTagBinders expr)
-    expr_ty' = simplTy env expr_ty
-
-    go ty [] = ty
-    go ty (TyArg ty_arg : args) = go (mkAppTy ty ty_arg) args
-    go ty (a:args) | isValArg a = case (getFunTy_maybe ty) of
-                                   Just (_, res_ty) -> go res_ty args
-                                   Nothing          -> panic "computeResultType"
+mkDupableCont :: OutType               -- Type of the thing to be given to the continuation
+             -> SimplCont 
+             -> (SimplCont -> SimplM (OutStuff a))
+             -> SimplM (OutStuff a)
+mkDupableCont ty cont thing_inside 
+  | contIsDupable cont
+  = thing_inside cont
+
+mkDupableCont _ (CoerceIt ty cont) thing_inside
+  = mkDupableCont ty cont              $ \ cont' ->
+    thing_inside (CoerceIt ty cont')
+
+mkDupableCont ty (InlinePlease cont) thing_inside
+  = mkDupableCont ty cont              $ \ cont' ->
+    thing_inside (InlinePlease cont')
+
+mkDupableCont join_arg_ty (ArgOf _ cont_ty cont_fn) thing_inside
+  =    -- Build the RHS of the join point
+    newId SLIT("a") join_arg_ty                                ( \ arg_id ->
+       cont_fn (Var arg_id)                            `thenSmpl` \ (floats, (_, rhs)) ->
+       returnSmpl (Lam (setOneShotLambda arg_id) (wrapFloats floats rhs))
+    )                                                  `thenSmpl` \ join_rhs ->
+   
+       -- Build the join Id and continuation
+       -- We give it a "$j" name just so that for later amusement
+       -- we can identify any join points that don't end up as let-no-escapes
+       -- [NOTE: the type used to be exprType join_rhs, but this seems more elegant.]
+    newId SLIT("$j") (mkFunTy join_arg_ty cont_ty)     $ \ join_id ->
+    let
+       new_cont = ArgOf OkToDup cont_ty
+                        (\arg' -> rebuild_done (App (Var join_id) arg'))
+    in
 
-var `withArity` UnknownArity = var
-var `withArity` arity       = var `addIdArity` arity
+    tick (CaseOfCase join_id)                                          `thenSmpl_`
+       -- Want to tick here so that we go round again,
+       -- and maybe copy or inline the code;
+       -- not strictly CaseOf Case
+    addLetBind (NonRec join_id join_rhs)       $
+    thing_inside new_cont
+
+mkDupableCont ty (ApplyTo _ arg se cont) thing_inside
+  = mkDupableCont (funResultTy ty) cont                $ \ cont' ->
+    setSubstEnv se (simplExpr arg)                     `thenSmpl` \ arg' ->
+    if exprIsDupable arg' then
+       thing_inside (ApplyTo OkToDup arg' emptySubstEnv cont')
+    else
+    newId SLIT("a") (exprType arg')                    $ \ bndr ->
+
+    tick (CaseOfCase bndr)                             `thenSmpl_`
+       -- Want to tick here so that we go round again,
+       -- and maybe copy or inline the code;
+       -- not strictly CaseOf Case
+
+     addLetBind (NonRec bndr arg')             $
+       -- But what if the arg should be case-bound?  We can't use
+       -- addNonRecBind here because its type is too specific.
+       -- This has been this way for a long time, so I'll leave it,
+       -- but I can't convince myself that it's right.
+
+     thing_inside (ApplyTo OkToDup (Var bndr) emptySubstEnv cont')
+
+
+mkDupableCont ty (Select _ case_bndr alts se cont) thing_inside
+  = tick (CaseOfCase case_bndr)                                                `thenSmpl_`
+    setSubstEnv se (
+       simplBinder case_bndr                                           $ \ case_bndr' ->
+       prepareCaseCont alts cont                                       $ \ cont' ->
+       mkDupableAlts case_bndr case_bndr' cont' alts                   $ \ alts' ->
+       returnOutStuff alts'
+    )                                  `thenSmpl` \ (alt_binds, (in_scope, alts')) ->
+
+    addFloats alt_binds in_scope               $
+
+       -- NB that the new alternatives, alts', are still InAlts, using the original
+       -- binders.  That means we can keep the case_bndr intact. This is important
+       -- because another case-of-case might strike, and so we want to keep the
+       -- info that the case_bndr is dead (if it is, which is often the case).
+       -- This is VITAL when the type of case_bndr is an unboxed pair (often the
+       -- case in I/O rich code.  We aren't allowed a lambda bound
+       -- arg of unboxed tuple type, and indeed such a case_bndr is always dead
+    thing_inside (Select OkToDup case_bndr alts' se (mkStop (contResultType cont)))
+
+mkDupableAlts :: InId -> OutId -> SimplCont -> [InAlt] 
+            -> ([InAlt] -> SimplM (OutStuff a))
+            -> SimplM (OutStuff a)
+mkDupableAlts case_bndr case_bndr' cont [] thing_inside
+  = thing_inside []
+mkDupableAlts case_bndr case_bndr' cont (alt:alts) thing_inside
+  = mkDupableAlt  case_bndr case_bndr' cont alt                $ \ alt' -> 
+    mkDupableAlts case_bndr case_bndr' cont alts       $ \ alts' ->
+    thing_inside (alt' : alts')
+
+mkDupableAlt case_bndr case_bndr' cont alt@(con, bndrs, rhs) thing_inside
+  = simplBinders bndrs                                 $ \ bndrs' ->
+    simplExprC rhs cont                                        `thenSmpl` \ rhs' ->
+
+    if (case cont of { Stop _ _ -> exprIsDupable rhs'; other -> False}) then
+       -- It is worth checking for a small RHS because otherwise we
+       -- get extra let bindings that may cause an extra iteration of the simplifier to
+       -- inline back in place.  Quite often the rhs is just a variable or constructor.
+       -- The Ord instance of Maybe in PrelMaybe.lhs, for example, took several extra
+       -- iterations because the version with the let bindings looked big, and so wasn't
+       -- inlined, but after the join points had been inlined it looked smaller, and so
+       -- was inlined.
+       --
+       -- But since the continuation is absorbed into the rhs, we only do this
+       -- for a Stop continuation.
+       --
+       -- NB: we have to check the size of rhs', not rhs. 
+       -- Duplicating a small InAlt might invalidate occurrence information
+       -- However, if it *is* dupable, we return the *un* simplified alternative,
+       -- because otherwise we'd need to pair it up with an empty subst-env.
+       -- (Remember we must zap the subst-env before re-simplifying something).
+       -- Rather than do this we simply agree to re-simplify the original (small) thing later.
+       thing_inside alt
+
+    else
+    let
+       rhs_ty' = exprType rhs'
+        (used_bndrs, used_bndrs')
+          = unzip [pr | pr@(bndr,bndr') <- zip (case_bndr  : bndrs)
+                                               (case_bndr' : bndrs'),
+                        not (isDeadBinder bndr)]
+               -- The new binders have lost their occurrence info,
+               -- so we have to extract it from the old ones
+    in
+    ( if null used_bndrs' 
+       -- If we try to lift a primitive-typed something out
+       -- for let-binding-purposes, we will *caseify* it (!),
+       -- with potentially-disastrous strictness results.  So
+       -- instead we turn it into a function: \v -> e
+       -- where v::State# RealWorld#.  The value passed to this function
+       -- is realworld#, which generates (almost) no code.
+
+       -- There's a slight infelicity here: we pass the overall 
+       -- case_bndr to all the join points if it's used in *any* RHS,
+       -- because we don't know its usage in each RHS separately
+
+       -- We used to say "&& isUnLiftedType rhs_ty'" here, but now
+       -- we make the join point into a function whenever used_bndrs'
+       -- is empty.  This makes the join-point more CPR friendly. 
+       -- Consider:    let j = if .. then I# 3 else I# 4
+       --              in case .. of { A -> j; B -> j; C -> ... }
+       --
+       -- Now CPR should not w/w j because it's a thunk, so
+       -- that means that the enclosing function can't w/w either,
+       -- which is a lose.  Here's the example that happened in practice:
+       --      kgmod :: Int -> Int -> Int
+       --      kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
+       --                  then 78
+       --                  else 5
+
+       then newId SLIT("w") realWorldStatePrimTy  $ \ rw_id ->
+            returnSmpl ([rw_id], [Var realWorldPrimId])
+       else 
+            returnSmpl (used_bndrs', map varToCoreExpr used_bndrs)
+    )
+       `thenSmpl` \ (final_bndrs', final_args) ->
+
+       -- See comment about "$j" name above
+    newId SLIT("$j") (foldr mkPiType rhs_ty' final_bndrs')     $ \ join_bndr ->
+       -- Notice the funky mkPiType.  If the contructor has existentials
+       -- it's possible that the join point will be abstracted over
+       -- type varaibles as well as term variables.
+       --  Example:  Suppose we have
+       --      data T = forall t.  C [t]
+       --  Then faced with
+       --      case (case e of ...) of
+       --          C t xs::[t] -> rhs
+       --  We get the join point
+       --      let j :: forall t. [t] -> ...
+       --          j = /\t \xs::[t] -> rhs
+       --      in
+       --      case (case e of ...) of
+       --          C t xs::[t] -> j t xs
+
+    let 
+       -- We make the lambdas into one-shot-lambdas.  The
+       -- join point is sure to be applied at most once, and doing so
+       -- prevents the body of the join point being floated out by
+       -- the full laziness pass
+       really_final_bndrs = map one_shot final_bndrs'
+       one_shot v | isId v    = setOneShotLambda v
+                  | otherwise = v
+    in
+    addLetBind (NonRec join_bndr (mkLams really_final_bndrs rhs'))     $
+    thing_inside (con, bndrs, mkApps (Var join_bndr) final_args)
 \end{code}
-