[project @ 1999-11-01 17:09:54 by simonpj]
[ghc-hetmet.git] / ghc / compiler / simplCore / SetLevels.lhs
index 1c068f0..2ff4754 100644 (file)
@@ -1,13 +1,33 @@
 %
-% (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
+% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
 %
 \section{SetLevels}
 
-We attach binding levels to Core bindings, in preparation for floating
-outwards (@FloatOut@).
+               ***************************
+                       Overview
+               ***************************
 
-We also let-ify many applications (notably case scrutinees), so they
-will have a fighting chance of being floated sensible.
+* We attach binding levels to Core bindings, in preparation for floating
+  outwards (@FloatOut@).
+
+* We also let-ify many expressions (notably case scrutinees), so they
+  will have a fighting chance of being floated sensible.
+
+* We clone the binders of any floatable let-binding, so that when it is
+  floated out it will be unique.  (This used to be done by the simplifier
+  but the latter now only ensures that there's no shadowing.)
+  NOTE: Very tiresomely, we must apply this substitution to
+       the rules stored inside a variable too.
+
+  We do *not* clone top-level bindings, because some of them must not change,
+  but we *do* clone bindings that are heading for the top level
+
+* In the expression
+       case x of wild { p -> ...wild... }
+  we substitute x for wild in the RHS of the case alternatives:
+       case x of wild { p -> ...x... }
+  This means that a sub-expression involving x is not "trapped" inside the RHS.
+  And it's not inconvenient because we already have a substitution.
 
 \begin{code}
 module SetLevels (
@@ -20,35 +40,29 @@ module SetLevels (
 
 #include "HsVersions.h"
 
-import AnnCoreSyn
 import CoreSyn
 
-import CoreUtils       ( coreExprType )
-import CoreUnfold      ( FormSummary, whnfOrBottom, mkFormSummary )
-import FreeVars                -- all of it
-import Id              ( idType, mkSysLocal, 
-                         nullIdEnv, addOneToIdEnv, growIdEnvList,
-                         unionManyIdSets, minusIdSet, mkIdSet,
-                         idSetToList, Id,
-                         lookupIdEnv, IdEnv
+import CoreUtils       ( coreExprType, exprIsTrivial, exprIsBottom )
+import CoreFVs         -- all of it
+import Id              ( Id, idType, mkSysLocal, isOneShotLambda, modifyIdInfo, 
+                         getIdSpecialisation, getIdWorkerInfo
                        )
-import SrcLoc          ( noSrcLoc )
-import Type            ( isUnpointedType, mkTyVarTys, mkForAllTys, tyVarsOfTypes, Type )
-import TyVar           ( emptyTyVarEnv, addToTyVarEnv,
-                         growTyVarEnvList, lookupTyVarEnv,
-                         tyVarSetToList, 
-                         TyVarEnv, TyVar,
-                         unionManyTyVarSets, unionTyVarSets
-                       )
-import UniqSupply      ( thenUs, returnUs, mapUs, mapAndUnzipUs,
-                         mapAndUnzip3Us, getUnique, UniqSM,
-                         UniqSupply
-                       )
-import BasicTypes      ( Unused )
-import Util            ( mapAccumL, zipWithEqual, zipEqual, panic, assertPanic )
+import IdInfo          ( workerExists )
+import Var             ( IdOrTyVar, Var, TyVar, setVarUnique )
+import VarEnv
+import Subst
+import VarSet
+import Name            ( getOccName )
+import OccName         ( occNameUserString )
+import Type            ( isUnLiftedType, mkTyVarTy, mkForAllTys, Type )
+import BasicTypes      ( TopLevelFlag(..) )
+import VarSet
+import VarEnv
+import UniqSupply
+import Maybes          ( maybeToBool )
+import Util            ( zipWithEqual, zipEqual )
 import Outputable
-
-isLeakFreeType x y = False -- safe option; ToDo
+import List            ( nub )
 \end{code}
 
 %************************************************************************
@@ -58,18 +72,18 @@ isLeakFreeType x y = False -- safe option; ToDo
 %************************************************************************
 
 \begin{code}
-data Level
-  = Top                -- Means *really* the top level.
-  | Level   Int        -- Level number of enclosing lambdas
-           Int -- Number of big-lambda and/or case expressions between
-               -- here and the nearest enclosing lambda
+data Level = Level Int -- Level number of enclosing lambdas
+                  Int  -- Number of big-lambda and/or case expressions between
+                       -- here and the nearest enclosing lambda
 \end{code}
 
 The {\em level number} on a (type-)lambda-bound variable is the
-nesting depth of the (type-)lambda which binds it.  On an expression,
-it's the maximum level number of its free (type-)variables.  On a
-let(rec)-bound variable, it's the level of its RHS.  On a case-bound
-variable, it's the number of enclosing lambdas.
+nesting depth of the (type-)lambda which binds it.  The outermost lambda
+has level 1, so (Level 0 0) means that the variable is bound outside any lambda.
+
+On an expression, it's the maximum level number of its free
+(type-)variables.  On a let(rec)-bound variable, it's the level of its
+RHS.  On a case-bound variable, it's the number of enclosing lambdas.
 
 Top-level variables: level~0.  Those bound on the RHS of a top-level
 definition but ``before'' a lambda; e.g., the \tr{x} in (levels shown
@@ -79,68 +93,44 @@ a_0 = let  b_? = ...  in
           x_1 = ... b ... in ...
 \end{verbatim}
 
-Level 0 0 will make something get floated to a top-level "equals",
-@Top@ makes it go right to the top.
-
 The main function @lvlExpr@ carries a ``context level'' (@ctxt_lvl@).
 That's meant to be the level number of the enclosing binder in the
 final (floated) program.  If the level number of a sub-expression is
 less than that of the context, then it might be worth let-binding the
 sub-expression so that it will indeed float. This context level starts
-at @Level 0 0@; it is never @Top@.
+at @Level 0 0@.
 
 \begin{code}
-type LevelledExpr  = GenCoreExpr    (Id, Level) Id Unused
-type LevelledArg   = GenCoreArg                        Id Unused
-type LevelledBind  = GenCoreBinding (Id, Level) Id Unused
-
-type LevelEnvs = (IdEnv    Level, -- bind Ids to levels
-                 TyVarEnv Level) -- bind type variables to levels
+type LevelledExpr  = TaggedExpr Level
+type LevelledArg   = TaggedArg Level
+type LevelledBind  = TaggedBind Level
 
-tOP_LEVEL = Top
+tOP_LEVEL = Level 0 0
 
 incMajorLvl :: Level -> Level
-incMajorLvl Top                        = Level 1 0
 incMajorLvl (Level major minor) = Level (major+1) 0
 
 incMinorLvl :: Level -> Level
-incMinorLvl Top                        = Level 0 1
 incMinorLvl (Level major minor) = Level major (minor+1)
 
 maxLvl :: Level -> Level -> Level
-maxLvl Top l2 = l2
-maxLvl l1 Top = l1
 maxLvl l1@(Level maj1 min1) l2@(Level maj2 min2)
   | (maj1 > maj2) || (maj1 == maj2 && min1 > min2) = l1
   | otherwise                                     = l2
 
 ltLvl :: Level -> Level -> Bool
-ltLvl l1               Top               = False
-ltLvl Top              (Level _ _)       = True
 ltLvl (Level maj1 min1) (Level maj2 min2)
   = (maj1 < maj2) || (maj1 == maj2 && min1 < min2)
 
 ltMajLvl :: Level -> Level -> Bool
     -- Tells if one level belongs to a difft *lambda* level to another
-ltMajLvl l1            Top            = False
-ltMajLvl Top           (Level 0 _)    = False
-ltMajLvl Top           (Level _ _)    = True
 ltMajLvl (Level maj1 _) (Level maj2 _) = maj1 < maj2
 
 isTopLvl :: Level -> Bool
-isTopLvl Top   = True
-isTopLvl other = False
-
-isTopMajLvl :: Level -> Bool -- Tells if it's the top *lambda* level
-isTopMajLvl Top                  = True
-isTopMajLvl (Level maj _) = maj == 0
-
-unTopify :: Level -> Level
-unTopify Top = Level 0 0
-unTopify lvl = lvl
+isTopLvl (Level 0 0) = True
+isTopLvl other       = False
 
 instance Outputable Level where
-  ppr Top            = ptext SLIT("<Top>")
   ppr (Level maj min) = hcat [ char '<', int maj, char ',', int min, char '>' ]
 \end{code}
 
@@ -151,71 +141,30 @@ instance Outputable Level where
 %************************************************************************
 
 \begin{code}
-setLevels :: [CoreBinding]
+setLevels :: [CoreBind]
          -> UniqSupply
          -> [LevelledBind]
 
 setLevels binds us
-  = do_them binds us
+  = initLvl us (do_them binds)
   where
     -- "do_them"'s main business is to thread the monad along
     -- It gives each top binding the same empty envt, because
     -- things unbound in the envt have level number zero implicitly
-    do_them :: [CoreBinding] -> LvlM [LevelledBind]
+    do_them :: [CoreBind] -> LvlM [LevelledBind]
 
     do_them [] = returnLvl []
     do_them (b:bs)
       = lvlTopBind b   `thenLvl` \ (lvld_bind, _) ->
-       do_them bs       `thenLvl` \ lvld_binds ->
-       returnLvl (lvld_bind ++ lvld_binds)
-
-initial_envs = (nullIdEnv, emptyTyVarEnv)
+       do_them bs      `thenLvl` \ lvld_binds ->
+       returnLvl (lvld_bind : lvld_binds)
 
 lvlTopBind (NonRec binder rhs)
-  = lvlBind (Level 0 0) initial_envs (AnnNonRec binder (freeVars rhs))
+  = lvlBind TopLevel tOP_LEVEL initialEnv (AnnNonRec binder (freeVars rhs))
                                        -- Rhs can have no free vars!
 
 lvlTopBind (Rec pairs)
-  = lvlBind (Level 0 0) initial_envs (AnnRec [(b,freeVars rhs) | (b,rhs) <- pairs])
-\end{code}
-
-%************************************************************************
-%*                                                                     *
-\subsection{Bindings}
-%*                                                                     *
-%************************************************************************
-
-The binding stuff works for top level too.
-
-\begin{code}
-type CoreBindingWithFVs = AnnCoreBinding Id Id Unused FVInfo
-
-lvlBind :: Level
-       -> LevelEnvs
-       -> CoreBindingWithFVs
-       -> LvlM ([LevelledBind], LevelEnvs)
-
-lvlBind ctxt_lvl envs@(venv, tenv) (AnnNonRec name rhs)
-  = setFloatLevel True {- Already let-bound -}
-       ctxt_lvl envs rhs ty    `thenLvl` \ (final_lvl, rhs') ->
-    let
-       new_envs = (addOneToIdEnv venv name final_lvl, tenv)
-    in
-    returnLvl ([NonRec (name, final_lvl) rhs'], new_envs)
-  where
-    ty = idType name
-
-
-lvlBind ctxt_lvl envs@(venv, tenv) (AnnRec pairs)
-  = decideRecFloatLevel ctxt_lvl envs binders rhss
-                               `thenLvl` \ (final_lvl, extra_binds, rhss') ->
-    let
-       binders_w_lvls = binders `zip` repeat final_lvl
-       new_envs       = (growIdEnvList venv binders_w_lvls, tenv)
-    in
-    returnLvl (extra_binds ++ [Rec (zipEqual "lvlBind" binders_w_lvls rhss')], new_envs)
-  where
-    (binders,rhss) = unzip pairs
+  = lvlBind TopLevel tOP_LEVEL initialEnv (AnnRec [(b,freeVars rhs) | (b,rhs) <- pairs])
 \end{code}
 
 %************************************************************************
@@ -226,15 +175,13 @@ lvlBind ctxt_lvl envs@(venv, tenv) (AnnRec pairs)
 
 \begin{code}
 lvlExpr :: Level               -- ctxt_lvl: Level of enclosing expression
-       -> LevelEnvs            -- Level of in-scope names/tyvars
+       -> LevelEnv             -- Level of in-scope names/tyvars
        -> CoreExprWithFVs      -- input expression
        -> LvlM LevelledExpr    -- Result expression
 \end{code}
 
 The @ctxt_lvl@ is, roughly, the level of the innermost enclosing
-binder.
-
-Here's an example
+binder.  Here's an example
 
        v = \x -> ...\y -> let r = case (..x..) of
                                        ..x..
@@ -249,22 +196,26 @@ don't want @lvlExpr@ to turn the scrutinee of the @case@ into an MFE
 If there were another lambda in @r@'s rhs, it would get level-2 as well.
 
 \begin{code}
-lvlExpr _ _ (_, AnnVar v)       = returnLvl (Var v)
-lvlExpr _ _ (_, AnnLit l)       = returnLvl (Lit l)
-lvlExpr _ _ (_, AnnCon con args) = returnLvl (Con con args)
-lvlExpr _ _ (_, AnnPrim op args) = returnLvl (Prim op args)
+lvlExpr _ _ (_, AnnType ty) = returnLvl (Type ty)
+lvlExpr _ env (_, AnnVar v) = returnLvl (lookupVar env v)
 
-lvlExpr ctxt_lvl envs@(venv, tenv) (_, AnnApp fun arg)
-  = lvlExpr ctxt_lvl envs fun          `thenLvl` \ fun' ->
-    returnLvl (App fun' arg)
+lvlExpr ctxt_lvl env (_, AnnCon con args)
+  = mapLvl (lvlExpr ctxt_lvl env) args `thenLvl` \ args' ->
+    returnLvl (Con con args')
 
-lvlExpr ctxt_lvl envs (_, AnnSCC cc expr)
-  = lvlExpr ctxt_lvl envs expr                 `thenLvl` \ expr' ->
-    returnLvl (SCC cc expr')
+lvlExpr ctxt_lvl env (_, AnnApp fun arg)
+  = lvlExpr ctxt_lvl env fun           `thenLvl` \ fun' ->
+    lvlMFE  False ctxt_lvl env arg     `thenLvl` \ arg' ->
+    returnLvl (App fun' arg')
 
-lvlExpr ctxt_lvl envs (_, AnnCoerce c ty expr)
-  = lvlExpr ctxt_lvl envs expr                 `thenLvl` \ expr' ->
-    returnLvl (Coerce c ty expr')
+lvlExpr ctxt_lvl env (_, AnnNote InlineMe expr)
+       -- Don't float anything out of an InlineMe
+  = lvlExpr tOP_LEVEL env expr                 `thenLvl` \ expr' ->
+    returnLvl (Note InlineMe expr')
+
+lvlExpr ctxt_lvl env (_, AnnNote note expr)
+  = lvlExpr ctxt_lvl env expr          `thenLvl` \ expr' ->
+    returnLvl (Note note expr')
 
 -- We don't split adjacent lambdas.  That is, given
 --     \x y -> (x+1,y)
@@ -273,502 +224,362 @@ lvlExpr ctxt_lvl envs (_, AnnCoerce c ty expr)
 -- Why not?  Because partial applications are fairly rare, and splitting
 -- lambdas makes them more expensive.
 
-lvlExpr ctxt_lvl envs@(venv, tenv) (_, AnnLam (ValBinder arg) rhs)
-  = lvlMFE incd_lvl (new_venv, tenv) body `thenLvl` \ body' ->
-    returnLvl (foldr (Lam . ValBinder) body' lvld_args)
-  where
-    incd_lvl     = incMajorLvl ctxt_lvl
-    (args, body) = annCollectValBinders rhs
-    lvld_args    = [(a,incd_lvl) | a <- (arg:args)]
-    new_venv     = growIdEnvList venv lvld_args
-
--- We don't need to play such tricks for type lambdas, because
--- they don't get annotated
-
-lvlExpr ctxt_lvl (venv, tenv) (_, AnnLam (TyBinder tyvar) body)
-  = lvlExpr incd_lvl (venv, new_tenv) body     `thenLvl` \ body' ->
-    returnLvl (Lam (TyBinder tyvar) body')
+lvlExpr ctxt_lvl env expr@(_, AnnLam bndr rhs)
+  = go (incMinorLvl ctxt_lvl) env False {- Havn't bumped major level in this group -} expr
+  where 
+    go lvl env bumped_major (_, AnnLam bndr body)
+      = go new_lvl new_env new_bumped_major body       `thenLvl` \ new_body ->
+       returnLvl (Lam lvld_bndr new_body)
+      where
+       -- Go to the next major level if this is a value binder,
+       -- and we havn't already gone to the next level (one jump per group)
+       -- and it isn't a one-shot lambda
+       (new_lvl, new_bumped_major)     
+         | isId bndr && 
+           not bumped_major && 
+           not (isOneShotLambda bndr) = (incMajorLvl ctxt_lvl, True)
+         | otherwise                  = (lvl,                 bumped_major)
+       new_env   = extendLvlEnv env [lvld_bndr]
+       lvld_bndr = (bndr, new_lvl)
+
+       -- Ignore notes, because we don't want to split
+       -- a lambda like this (\x -> coerce t (\s -> ...))
+       -- This happens quite a bit in state-transformer programs
+    go lvl env bumped_major (_, AnnNote note body)
+      = go lvl env bumped_major body                   `thenLvl` \ new_body ->
+       returnLvl (Note note new_body)
+
+    go lvl env bumped_major body
+      = lvlMFE True lvl env body
+
+
+lvlExpr ctxt_lvl env (_, AnnLet bind body)
+  = lvlBind NotTopLevel ctxt_lvl env bind      `thenLvl` \ (bind', new_env) ->
+    lvlExpr ctxt_lvl new_env body              `thenLvl` \ body' ->
+    returnLvl (Let bind' body')
+
+lvlExpr ctxt_lvl env (_, AnnCase expr case_bndr alts)
+  = lvlMFE True ctxt_lvl env expr      `thenLvl` \ expr' ->
+    let
+       alts_env = extendCaseBndrLvlEnv env expr' case_bndr incd_lvl
+    in
+    mapLvl (lvl_alt alts_env) alts     `thenLvl` \ alts' ->
+    returnLvl (Case expr' (case_bndr, incd_lvl) alts')
   where
-    incd_lvl = incMinorLvl ctxt_lvl
-    new_tenv = addToTyVarEnv tenv tyvar incd_lvl
-
-lvlExpr ctxt_lvl envs (_, AnnLet bind body)
-  = lvlBind ctxt_lvl envs bind         `thenLvl` \ (binds', new_envs) ->
-    lvlExpr ctxt_lvl new_envs body     `thenLvl` \ body' ->
-    returnLvl (foldr Let body' binds') -- mkCoLet* requires Core...
-
-lvlExpr ctxt_lvl envs@(venv, tenv) (_, AnnCase expr alts)
-  = lvlMFE ctxt_lvl envs expr  `thenLvl` \ expr' ->
-    lvl_alts alts              `thenLvl` \ alts' ->
-    returnLvl (Case expr' alts')
-    where
       expr_type = coreExprType (deAnnotate expr)
       incd_lvl  = incMinorLvl ctxt_lvl
 
-      lvl_alts (AnnAlgAlts alts deflt)
-       = mapLvl lvl_alt alts   `thenLvl` \ alts' ->
-         lvl_deflt deflt       `thenLvl` \ deflt' ->
-         returnLvl (AlgAlts alts' deflt')
+      lvl_alt alts_env (con, bs, rhs)
+       = lvlMFE True incd_lvl new_env rhs      `thenLvl` \ rhs' ->
+         returnLvl (con, bs', rhs')
        where
-         lvl_alt (con, bs, e)
-           = let
-                 bs'  = [ (b, incd_lvl) | b <- bs ]
-                 new_envs = (growIdEnvList venv bs', tenv)
-             in
-             lvlMFE incd_lvl new_envs e        `thenLvl` \ e' ->
-             returnLvl (con, bs', e')
-
-      lvl_alts (AnnPrimAlts alts deflt)
-       = mapLvl lvl_alt alts   `thenLvl` \ alts' ->
-         lvl_deflt deflt       `thenLvl` \ deflt' ->
-         returnLvl (PrimAlts alts' deflt')
-       where
-         lvl_alt (lit, e)
-           = lvlMFE incd_lvl envs e `thenLvl` \ e' ->
-             returnLvl (lit, e')
-
-      lvl_deflt AnnNoDefault = returnLvl NoDefault
-
-      lvl_deflt (AnnBindDefault b expr)
-       = let
-             new_envs = (addOneToIdEnv venv b incd_lvl, tenv)
-         in
-         lvlMFE incd_lvl new_envs expr `thenLvl` \ expr' ->
-         returnLvl (BindDefault (b, incd_lvl) expr')
+         bs'     = [ (b, incd_lvl) | b <- bs ]
+         new_env = extendLvlEnv alts_env bs'
 \end{code}
 
 @lvlMFE@ is just like @lvlExpr@, except that it might let-bind
 the expression, so that it can itself be floated.
 
 \begin{code}
-lvlMFE ::  Level               -- Level of innermost enclosing lambda/tylam
-       -> LevelEnvs            -- Level of in-scope names/tyvars
+lvlMFE ::  Bool                        -- True <=> strict context [body of case or let]
+       -> Level                -- Level of innermost enclosing lambda/tylam
+       -> LevelEnv             -- Level of in-scope names/tyvars
        -> CoreExprWithFVs      -- input expression
        -> LvlM LevelledExpr    -- Result expression
 
-lvlMFE ctxt_lvl envs@(venv,_) ann_expr
-  | isUnpointedType ty -- Can't let-bind it
-  = lvlExpr ctxt_lvl envs ann_expr
-
-  | otherwise          -- Not primitive type so could be let-bound
-  = setFloatLevel False {- Not already let-bound -}
-       ctxt_lvl envs ann_expr ty       `thenLvl` \ (final_lvl, expr') ->
-    returnLvl expr'
+lvlMFE strict_ctxt ctxt_lvl env (_, AnnType ty)
+  = returnLvl (Type ty)
+
+lvlMFE strict_ctxt ctxt_lvl env ann_expr@(fvs, _)
+  |  isUnLiftedType ty                         -- Can't let-bind it
+  || not (dest_lvl `ltMajLvl` ctxt_lvl)                -- Does not escape a value lambda
+       -- A decision to float entails let-binding this thing, and we only do 
+       -- that if we'll escape a value lambda.  I considered doing it if it
+       -- would make the thing go to top level, but I found things like
+       --      concat = /\ a -> foldr ..a.. (++) []
+       -- was getting turned into
+       --      concat = /\ a -> lvl a
+       --      lvl    = /\ a -> foldr ..a.. (++) []
+       -- which is pretty stupid.  So for now at least, I don't let-bind things
+       -- simply because they could go to top level.
+  || exprIsTrivial expr                                -- Is trivial
+  || (strict_ctxt && exprIsBottom expr)                -- Strict context and is bottom
+  =    -- Don't float it out
+    lvlExpr ctxt_lvl env ann_expr
+
+  | otherwise  -- Float it out!
+  = lvlExpr expr_lvl expr_env ann_expr         `thenLvl` \ expr' ->
+    newLvlVar "lvl" (mkForAllTys tyvars ty)    `thenLvl` \ var ->
+    returnLvl (Let (NonRec (var,dest_lvl) (mkLams tyvars_w_lvls expr')) 
+                  (mkTyVarApps var tyvars))
   where
-    ty = coreExprType (deAnnotate ann_expr)
+    expr     = deAnnotate ann_expr
+    ty       = coreExprType expr
+    dest_lvl = destLevel env fvs
+    (tyvars, tyvars_w_lvls, expr_lvl) = abstractTyVars dest_lvl env fvs
+    expr_env = extendLvlEnv env tyvars_w_lvls
 \end{code}
 
 
 %************************************************************************
 %*                                                                     *
-\subsection{Deciding floatability}
+\subsection{Bindings}
 %*                                                                     *
 %************************************************************************
 
-@setFloatLevel@ is used for let-bound right-hand-sides, or for MFEs which
-are being created as let-bindings
-
-Decision tree:
-Let Bound?
-  YES. -> (a) try abstracting type variables.
-       If we abstract type variables it will go further, that is, past more
-       lambdas. same as asking if the level number given by the free
-       variables is less than the level number given by free variables
-       and type variables together.
-       Abstract offending type variables, e.g.
-       change f ty a b
-       to let v = /\ty' -> f ty' a b
-         in v ty
-       so that v' is not stopped by the level number of ty
-       tag the original let with its level number
-       (from its variables and type variables)
-  NO.  is a WHNF?
-        YES. -> No point in let binding to float a WHNF.
-                Pin (leave) expression here.
-        NO. -> Will float past a lambda?
-               (check using free variables only, not type variables)
-                 YES. -> do the same as (a) above.
-                 NO. -> No point in let binding if it is not going anywhere
-                        Pin (leave) expression here.
+The binding stuff works for top level too.
 
 \begin{code}
-setFloatLevel :: Bool                  -- True <=> the expression is already let-bound
-                                       -- False <=> it's a possible MFE
-             -> Level                  -- of context
-             -> LevelEnvs
-
-             -> CoreExprWithFVs        -- Original rhs
-             -> Type           -- Type of rhs
-
-             -> LvlM (Level,           -- Level to attribute to this let-binding
-                      LevelledExpr)    -- Final rhs
-
-setFloatLevel alreadyLetBound ctxt_lvl envs@(venv, tenv)
-             expr@(FVInfo fvs tfvs might_leak, _) ty
--- Invariant: ctxt_lvl is never = Top
--- Beautiful ASSERT, dudes (WDP 95/04)...
-
--- Now deal with (by not floating) trivial non-let-bound expressions
--- which just aren't worth let-binding in order to float.  We always
--- choose to float even trivial let-bound things because it doesn't do
--- any harm, and not floating it may pin something important.  For
--- example
---
---     x = let v = []
---             w = 1:v
---         in ...
---
--- Here, if we don't float v we won't float w, which is Bad News.
--- If this gives any problems we could restrict the idea to things destined
--- for top level.
-
-  | not alreadyLetBound
-    && (manifestly_whnf || not will_float_past_lambda)
-  =   -- Pin whnf non-let-bound expressions,
-      -- or ones which aren't going anywhere useful
-    lvlExpr ctxt_lvl envs expr        `thenLvl` \ expr' ->
-    returnLvl (ctxt_lvl, expr')
-
-  | alreadyLetBound && not worth_type_abstraction
-  =   -- Process the expression with a new ctxt_lvl, obtained from
-      -- the free vars of the expression itself
-    lvlExpr (unTopify expr_lvl) envs expr `thenLvl` \ expr' ->
-    returnLvl (maybe_unTopify expr_lvl, expr')
-
-  | otherwise -- This will create a let anyway, even if there is no
-             -- type variable to abstract, so we try to abstract anyway
-  = abstractWrtTyVars offending_tyvars ty envs lvl_after_ty_abstr expr
-                                             `thenLvl` \ final_expr ->
-    returnLvl (expr_lvl, final_expr)
-      -- OLD LIE: The body of the let, just a type application, isn't worth floating
-      --          so pin it with ctxt_lvl
-      -- The truth: better to give it expr_lvl in case it is pinning
-      -- something non-trivial which depends on it.
-  where
-    fv_list = idSetToList    fvs
-    tv_list = tyVarSetToList tfvs
-    expr_lvl = ids_only_lvl `maxLvl` tyvars_only_lvl
-    ids_only_lvl    = foldr (maxLvl . idLevel venv)    tOP_LEVEL fv_list
-    tyvars_only_lvl = foldr (maxLvl . tyvarLevel tenv) tOP_LEVEL tv_list
-    lvl_after_ty_abstr = ids_only_lvl --`maxLvl` non_offending_tyvars_lvl
-
-    will_float_past_lambda =   -- Will escape lambda if let-bound
-                           ids_only_lvl `ltMajLvl` ctxt_lvl
-
-    worth_type_abstraction = -- Will escape (more) lambda(s)/type lambda(s)
-                            -- if type abstracted
-      (ids_only_lvl `ltLvl` tyvars_only_lvl)
-      && not (is_trivial de_ann_expr) -- avoids abstracting trivial type applications
-
-    de_ann_expr = deAnnotate expr
-
-    is_trivial (App e a)
-      | notValArg a    = is_trivial e
-    is_trivial (Var _)  = True
-    is_trivial _        = False
-
-    offending_tyvars = filter offending tv_list
-    --non_offending_tyvars = filter (not . offending) tv_list
-    --non_offending_tyvars_lvl = foldr (maxLvl . tyvarLevel tenv) tOP_LEVEL non_offending_tyvars
-
-    offending tyvar = ids_only_lvl `ltLvl` tyvarLevel tenv tyvar
-
-    manifestly_whnf = whnfOrBottom (mkFormSummary de_ann_expr)
-
-    maybe_unTopify Top | not (canFloatToTop (ty, expr)) = Level 0 0
-    maybe_unTopify lvl                                  = lvl
-       {- ToDo [Andre]: the line above (maybe) should be Level 1 0,
-       -- so that the let will not go past the *last* lambda if it can
-       -- generate a space leak. If it is already in major level 0
-       -- It won't do any harm to give it a Level 1 0.
-       -- we should do the same test not only for things with level Top,
-       -- but also for anything that gets a major level 0.
-          the problem is that
-          f = \a -> let x = [1..1000]
-                    in zip a x
-          ==>
-          f = let x = [1..1000]
-              in \a -> zip a x
-          is just as bad as floating x to the top level.
-          Notice it would be OK in cases like
-          f = \a -> let x = [1..1000]
-                        y = length x
-                    in a + y
-          ==>
-          f = let x = [1..1000]
-                  y = length x
-              in \a -> a + y
-          as x will be gc'd after y is updated.
-          [We did not hit any problems with the above (Level 0 0) code
-           in nofib benchmark]
-       -}
-\end{code}
-
-Abstract wrt tyvars, by making it just as if we had seen
-
-     let v = /\a1..an. E
-     in v a1 ... an
-
-instead of simply E. The idea is that v can be freely floated, since it
-has no free type variables. Of course, if E has no free type
-variables, then we just return E.
+lvlBind :: TopLevelFlag                -- Used solely to decide whether to clone
+       -> Level                -- Context level; might be Top even for bindings nested in the RHS
+                               -- of a top level binding
+       -> LevelEnv
+       -> CoreBindWithFVs
+       -> LvlM (LevelledBind, LevelEnv)
+
+lvlBind top_lvl ctxt_lvl env (AnnNonRec bndr rhs@(rhs_fvs,_))
+  | null tyvars
+  =    -- No type abstraction; clone existing binder
+    lvlExpr rhs_lvl rhs_env rhs                        `thenLvl` \ rhs' ->
+    cloneVar top_lvl env bndr dest_lvl         `thenLvl` \ (env', bndr') ->
+    returnLvl (NonRec (bndr', dest_lvl) rhs', env') 
 
-\begin{code}
-abstractWrtTyVars offending_tyvars ty (venv,tenv) lvl expr
-  = lvlExpr incd_lvl new_envs expr     `thenLvl` \ expr' ->
-    newLvlVar poly_ty                  `thenLvl` \ poly_var ->
+  | otherwise
+  = -- Yes, type abstraction; create a new binder, extend substitution, etc
+    WARN( workerExists (getIdWorkerInfo bndr)
+         || not (isEmptyCoreRules (getIdSpecialisation bndr)),
+         text "lvlBind: discarding info on" <+> ppr bndr )
+       
+    lvl_poly_rhs tyvars_w_lvls rhs_lvl rhs_env rhs     `thenLvl` \ rhs' ->
+    new_poly_bndr tyvars bndr                          `thenLvl` \ bndr' ->
     let
-       poly_var_rhs     = mkTyLam offending_tyvars expr'
-       poly_var_binding = NonRec (poly_var, lvl) poly_var_rhs
-       poly_var_app     = mkTyApp (Var poly_var) (mkTyVarTys offending_tyvars)
-       final_expr       = Let poly_var_binding poly_var_app -- mkCoLet* requires Core
+       env' = extendPolyLvlEnv env dest_lvl tyvars [(bndr, bndr')]
     in
-    returnLvl final_expr
-  where
-    poly_ty = mkForAllTys offending_tyvars ty
+    returnLvl (NonRec (bndr', dest_lvl) rhs', env')
 
-       -- These defns are just like those in the TyLam case of lvlExpr
-    (incd_lvl, tyvar_lvls) = mapAccumL next (unTopify lvl) offending_tyvars
+  where
+    bind_fvs = rhs_fvs `unionVarSet` idFreeVars bndr
 
-    next lvl tyvar = (lvl1, (tyvar,lvl1))
-                    where lvl1 = incMinorLvl lvl
+    dest_lvl | isUnLiftedType (idType bndr) = destLevel env bind_fvs `maxLvl` Level 1 0
+            | otherwise                    = destLevel env bind_fvs
+       -- Hack alert!  We do have some unlifted bindings, for cheap primops, and 
+       -- it is ok to float them out; but not to the top level.  If they would otherwise
+       -- go to the top level, we pin them inside the topmost lambda
 
-    new_tenv = growTyVarEnvList tenv tyvar_lvls
-    new_envs = (venv, new_tenv)
+    (tyvars, tyvars_w_lvls, rhs_lvl) = abstractTyVars dest_lvl env bind_fvs
+    rhs_env = extendLvlEnv env tyvars_w_lvls
 \end{code}
 
-Recursive definitions.  We want to transform
-
-       letrec
-          x1 = e1
-          ...
-          xn = en
-       in
-       body
-
-to
-
-       letrec
-          x1' = /\ ab -> let D' in e1
-          ...
-          xn' = /\ ab -> let D' in en
-       in
-       let D in body
-
-where ab are the tyvars pinning the defn further in than it
-need be, and D  is a bunch of simple type applications:
-
-               x1_cl = x1' ab
-               ...
-               xn_cl = xn' ab
-
-The "_cl" indicates that in D, the level numbers on the xi are the context level
-number; type applications aren't worth floating.  The D' decls are
-similar:
-
-               x1_ll = x1' ab
-               ...
-               xn_ll = xn' ab
-
-but differ in their level numbers; here the ab are the newly-introduced
-type lambdas.
 
 \begin{code}
-decideRecFloatLevel ctxt_lvl envs@(venv, tenv) ids rhss
-  | isTopMajLvl ids_only_lvl   &&              -- Destination = top
-    not (all canFloatToTop (zipEqual "decideRec" tys rhss)) -- Some can't float to top
-  =    -- Pin it here
-    let
-       ids_w_lvls = ids `zip` repeat ctxt_lvl
-       new_envs   = (growIdEnvList venv ids_w_lvls, tenv)
-    in
-    mapLvl (lvlExpr ctxt_lvl new_envs) rhss    `thenLvl` \ rhss' ->
-    returnLvl (ctxt_lvl, [], rhss')
-
-{- OMITTED; see comments above near isWorthFloatingExpr
-
-  | not (any (isWorthFloating True . deAnnotate) rhss)
-  =    -- Pin it here
-    mapLvl (lvlExpr ctxt_lvl envs) rhss        `thenLvl` \ rhss' ->
-    returnLvl (ctxt_lvl, [], rhss')
-
--}
-
-  | ids_only_lvl `ltLvl` tyvars_only_lvl
-  =    -- Abstract wrt tyvars;
-       -- offending_tyvars is definitely non-empty
-       -- (I love the ASSERT to check this...  WDP 95/02)
-    let
-       -- These defns are just like those in the TyLam case of lvlExpr
-       (incd_lvl, tyvar_lvls) = mapAccumL next (unTopify ids_only_lvl) offending_tyvars
-
-       next lvl tyvar = (lvl1, (tyvar,lvl1))
-                    where lvl1 = incMinorLvl lvl
+lvlBind top_lvl ctxt_lvl env (AnnRec pairs)
+  | null tyvars
+  = cloneVars top_lvl env bndrs dest_lvl       `thenLvl` \ (new_env, new_bndrs) ->
+    mapLvl (lvlExpr rhs_lvl new_env) rhss      `thenLvl` \ new_rhss ->
+    returnLvl (Rec ((new_bndrs `zip` repeat dest_lvl) `zip` new_rhss), new_env)
 
-       ids_w_incd_lvl = [(id,incd_lvl) | id <- ids]
-       new_tenv              = growTyVarEnvList tenv tyvar_lvls
-       new_venv              = growIdEnvList    venv ids_w_incd_lvl
-       new_envs              = (new_venv, new_tenv)
-    in
-    mapLvl (lvlExpr incd_lvl new_envs) rhss    `thenLvl` \ rhss' ->
-    mapLvl newLvlVar poly_tys                  `thenLvl` \ poly_vars ->
+  | otherwise
+  = mapLvl (new_poly_bndr tyvars) bndrs                `thenLvl` \ new_bndrs ->
     let
-       ids_w_poly_vars = zipEqual "decideRec2" ids poly_vars
+       new_env = extendPolyLvlEnv env dest_lvl tyvars (bndrs `zip` new_bndrs)
+       rhs_env = extendLvlEnv new_env tyvars_w_lvls
+   in
+    mapLvl (lvl_poly_rhs tyvars_w_lvls rhs_lvl rhs_env) rhss   `thenLvl` \ new_rhss ->
+    returnLvl (Rec ((new_bndrs `zip` repeat dest_lvl) `zip` new_rhss), new_env)
 
-               -- The "d_rhss" are the right-hand sides of "D" and "D'"
-               -- in the documentation above
-       d_rhss = [ mkTyApp (Var poly_var) offending_tyvar_tys | poly_var <- poly_vars]
+  where
+    (bndrs,rhss) = unzip pairs
 
-               -- "local_binds" are "D'" in the documentation above
-       local_binds = zipWithEqual "SetLevels" NonRec ids_w_incd_lvl d_rhss
+       -- Finding the free vars of the binding group is annoying
+    bind_fvs       = (unionVarSets [ idFreeVars bndr `unionVarSet` rhs_fvs
+                                   | (bndr, (rhs_fvs,_)) <- pairs])
+                     `minusVarSet`
+                     mkVarSet bndrs
 
-       poly_var_rhss = [ mkTyLam offending_tyvars (foldr Let rhs' local_binds)
-                       | rhs' <- rhss' -- mkCoLet* requires Core...
-                       ]
+    dest_lvl       = destLevel env bind_fvs
 
-       poly_binds  = zipEqual "poly_binds" [(poly_var, ids_only_lvl) | poly_var <- poly_vars] 
-                                           poly_var_rhss
+    (tyvars, tyvars_w_lvls, rhs_lvl) = abstractTyVars dest_lvl env bind_fvs
 
-    in
-    returnLvl (ctxt_lvl, [Rec poly_binds], d_rhss)
-       -- The new right-hand sides, just a type application, aren't worth floating
-       -- so pin it with ctxt_lvl
+----------------------------------------------------
+-- Three help functons Stuff for the type-abstraction case
 
-  | otherwise
-  =    -- Let it float freely
-    let
-       ids_w_lvls = ids `zip` repeat expr_lvl
-       new_envs   = (growIdEnvList venv ids_w_lvls, tenv)
-    in
-    mapLvl (lvlExpr (unTopify expr_lvl) new_envs) rhss `thenLvl` \ rhss' ->
-    returnLvl (expr_lvl, [], rhss')
+new_poly_bndr tyvars bndr 
+  = newLvlVar ("poly_" ++ occNameUserString (getOccName bndr))
+             (mkForAllTys tyvars (idType bndr))
 
-  where
-    tys  = map idType ids
-
-    fvs  = unionManyIdSets [freeVarsOf   rhs | rhs <- rhss] `minusIdSet` mkIdSet ids
-    tfvs = unionManyTyVarSets [freeTyVarsOf rhs | rhs <- rhss]
-          `unionTyVarSets`
-          tyVarsOfTypes tys
-       -- Why the "tyVarsOfTypes" part?  Consider this:
-       --      /\a -> letrec x::a = x in E
-       -- Now, there are no explicit free type variables in the RHS of x,
-       -- but nevertheless "a" is free in its definition.  So we add in
-       -- the free tyvars of the types of the binders.
-       -- This actually happened in the defn of errorIO in IOBase.lhs:
-       --      errorIO (ST io) = case (errorIO# io) of
-       --                          _ -> bottom
-       --                        where
-       --                          bottom = bottom -- Never evaluated
-       -- I don't think this can every happen for non-recursive bindings.
-
-    fv_list = idSetToList fvs
-    tv_list = tyVarSetToList tfvs
-
-    ids_only_lvl    = foldr (maxLvl . idLevel venv)    tOP_LEVEL fv_list
-    tyvars_only_lvl = foldr (maxLvl . tyvarLevel tenv) tOP_LEVEL tv_list
-    expr_lvl       = ids_only_lvl `maxLvl` tyvars_only_lvl
-
-    offending_tyvars
-       | ids_only_lvl `ltLvl` tyvars_only_lvl = filter offending tv_list
-       | otherwise                            = []
-
-    offending_tyvar_tys = mkTyVarTys offending_tyvars
-    poly_tys = map (mkForAllTys offending_tyvars) tys
-
-    offending tyvar = ids_only_lvl `ltLvl` tyvarLevel tenv tyvar
+lvl_poly_rhs tyvars_w_lvls rhs_lvl rhs_env rhs
+ = lvlExpr rhs_lvl rhs_env rhs `thenLvl` \ rhs' ->
+   returnLvl (mkLams tyvars_w_lvls rhs')
 \end{code}
 
 
-\begin{code}
-{- ******** OMITTED NOW
-
-isWorthFloating :: Bool                -- True <=> already let-bound
-               -> CoreExpr     -- The expression
-               -> Bool
+%************************************************************************
+%*                                                                     *
+\subsection{Deciding floatability}
+%*                                                                     *
+%************************************************************************
 
-isWorthFloating alreadyLetBound expr
+\begin{code}
+abstractTyVars :: Level -> LevelEnv -> VarSet
+              -> ([TyVar], [(TyVar,Level)], Level)
+       -- Find the tyvars whose level is higher than the supplied level
+       -- There should be no Ids with this property
+abstractTyVars lvl env fvs
+  | null tyvars = ([], [], lvl)                -- Don't increment level
 
-  | alreadyLetBound = isWorthFloatingExpr expr
+  | otherwise
+  = ASSERT( not (any bad fv_list) )
+    (tyvars, tyvars_w_lvls, incd_lvl)
+  where
+    bad v   = isId v && lvl `ltLvl` varLevel env v
+    fv_list = varSetElems fvs
+    tyvars  = nub [tv | v <- fv_list, tv <- tvs_of v, abstract_tv tv]
 
-  | otherwise       =  -- No point in adding a fresh let-binding for a WHNF, because
-                       -- floating it isn't beneficial enough.
-                     isWorthFloatingExpr expr &&
-                     not (whnfOrBottom expr)
-********** -}
+       -- If f is free in the exression, and f maps to poly_f a b c in the
+       -- current substitution, then we must report a b c as candidate type
+       -- variables
+    tvs_of v | isId v    = lookupTyVars env v
+            | otherwise = [v]
 
-isWorthFloatingExpr :: CoreExpr -> Bool
+    abstract_tv var | isId var  = False
+                   | otherwise = lvl `ltLvl` varLevel env var
 
-isWorthFloatingExpr (Var v)    = False
-isWorthFloatingExpr (Lit lit)  = False
-isWorthFloatingExpr (App e arg)
-  | notValArg arg              = isWorthFloatingExpr e
-isWorthFloatingExpr (Con con as)
-  | all notValArg as           = False -- Just a type application
-isWorthFloatingExpr _          = True
+       -- These defns are just like those in the TyLam case of lvlExpr
+    incd_lvl      = incMinorLvl lvl
+    tyvars_w_lvls = [(tv,incd_lvl) | tv <- tyvars]
 
-canFloatToTop :: (Type, CoreExprWithFVs) -> Bool
 
-canFloatToTop (ty, (FVInfo _ _ (LeakFree _), expr)) = True
-canFloatToTop (ty, (FVInfo _ _ MightLeak,    expr)) = isLeakFreeType [] ty
+  -- Destintion level is the max Id level of the expression
+  -- (We'll abstract the type variables, if any.)
+destLevel :: LevelEnv -> VarSet -> Level
+destLevel env fvs = foldVarSet (maxIdLvl env) tOP_LEVEL fvs
 
-valSuggestsLeakFree expr = whnfOrBottom expr
+maxIdLvl :: LevelEnv -> IdOrTyVar -> Level -> Level
+maxIdLvl (lvl_env,_,_) var lvl | isTyVar var = lvl
+                              | otherwise   = case lookupVarEnv lvl_env var of
+                                                 Just lvl' -> maxLvl lvl' lvl
+                                                 Nothing   -> lvl 
 \end{code}
 
 
-
 %************************************************************************
 %*                                                                     *
-\subsection{Help functions}
+\subsection{Free-To-Level Monad}
 %*                                                                     *
 %************************************************************************
 
 \begin{code}
-idLevel :: IdEnv Level -> Id -> Level
-idLevel venv v
-  = case lookupIdEnv venv v of
-      Just level -> level
-      Nothing    -> tOP_LEVEL
+type LevelEnv = (VarEnv Level, SubstEnv, IdEnv ([TyVar], LevelledExpr))
+       -- We clone let-bound variables so that they are still
+       -- distinct when floated out; hence the SubstEnv/IdEnv.
+       -- We also use these envs when making a variable polymorphic
+       -- because we want to float it out past a big lambda.
+       --
+       -- The two Envs always implement the same mapping, but the
+       -- SubstEnv maps to CoreExpr and the IdEnv to LevelledExpr
+       -- Since the range is always a variable or type application,
+       -- there is never any difference between the two, but sadly
+       -- the types differ.  The SubstEnv is used when substituting in
+       -- a variable's IdInfo; the IdEnv when we find a Var.
+       --
+       -- In addition the IdEnv records a list of tyvars free in the
+       -- type application, just so we don't have to call freeVars on
+       -- the type application repeatedly.
+       --
+       -- The domain of the both envs is *pre-cloned* Ids, though
+
+initialEnv :: LevelEnv
+initialEnv = (emptyVarEnv, emptySubstEnv, emptyVarEnv)
+
+extendLvlEnv :: LevelEnv -> [(Var,Level)] -> LevelEnv
+       -- Used when *not* cloning
+extendLvlEnv (lvl_env, subst_env, id_env) prs
+  = (foldl add lvl_env prs, subst_env, id_env)
+  where
+    add env (v,l) = extendVarEnv env v l
+
+-- extendCaseBndrLvlEnv adds the mapping case-bndr->scrut-var if it can
+extendCaseBndrLvlEnv (lvl_env, subst_env, id_env) scrut case_bndr lvl
+  = case scrut of
+       Var v -> (new_lvl_env, extendSubstEnv subst_env case_bndr (DoneEx (Var v)), 
+                              extendVarEnv   id_env    case_bndr ([], scrut))
+       other -> (new_lvl_env, subst_env, id_env)
+  where
+    new_lvl_env = extendVarEnv lvl_env case_bndr lvl
 
-tyvarLevel :: TyVarEnv Level -> TyVar -> Level
-tyvarLevel tenv tyvar
-  = case lookupTyVarEnv tenv tyvar of
+extendPolyLvlEnv (lvl_env, subst_env, id_env) dest_lvl tyvars bndr_pairs
+  = (foldl add_lvl lvl_env bndr_pairs,
+     foldl add_subst subst_env bndr_pairs,
+     foldl add_id    id_env    bndr_pairs)
+  where
+     add_lvl   env (v,_ ) = extendVarEnv   env v dest_lvl
+     add_subst env (v,v') = extendSubstEnv env v (DoneEx (mkTyVarApps v' tyvars))
+     add_id    env (v,v') = extendVarEnv   env v (tyvars, mkTyVarApps v' tyvars)
+
+varLevel :: LevelEnv -> IdOrTyVar -> Level
+varLevel (lvl_env, _, _) v
+  = case lookupVarEnv lvl_env v of
       Just level -> level
       Nothing    -> tOP_LEVEL
-\end{code}
 
-\begin{code}
-annCollectValBinders (_, (AnnLam (ValBinder arg) rhs))
-  = (arg:args, body) 
-  where
-    (args, body) = annCollectValBinders rhs
+lookupVar :: LevelEnv -> Id -> LevelledExpr
+lookupVar (_, _, id_env) v = case lookupVarEnv id_env v of
+                              Just (_, expr) -> expr
+                              other          -> Var v
 
-annCollectValBinders body
-  = ([], body)
+lookupTyVars :: LevelEnv -> Id -> [TyVar]
+lookupTyVars (_, _, id_env) v = case lookupVarEnv id_env v of
+                                 Just (tyvars, _) -> tyvars
+                                 Nothing          -> []
 \end{code}
 
-%************************************************************************
-%*                                                                     *
-\subsection{Free-To-Level Monad}
-%*                                                                     *
-%************************************************************************
-
 \begin{code}
 type LvlM result = UniqSM result
 
+initLvl                = initUs_
 thenLvl                = thenUs
 returnLvl      = returnUs
 mapLvl         = mapUs
-mapAndUnzipLvl  = mapAndUnzipUs
-mapAndUnzip3Lvl = mapAndUnzip3Us
 \end{code}
 
-We create a let-binding for `interesting' (non-utterly-trivial)
-applications, to give them a fighting chance of being floated.
-
 \begin{code}
-newLvlVar :: Type -> LvlM Id
+newLvlVar :: String -> Type -> LvlM Id
+newLvlVar str ty = getUniqueUs `thenLvl` \ uniq ->
+                  returnUs (mkSysLocal (_PK_ str) uniq ty)
+
+-- The deeply tiresome thing is that we have to apply the substitution
+-- to the rules inside each Id.  Grr.  But it matters.
+
+cloneVar :: TopLevelFlag -> LevelEnv -> Id -> Level -> LvlM (LevelEnv, Id)
+cloneVar TopLevel env v lvl
+  = returnUs (env, v)  -- Don't clone top level things
+cloneVar NotTopLevel (lvl_env, subst_env, id_env) v lvl
+  = getUniqueUs        `thenLvl` \ uniq ->
+    let
+      subst     = mkSubst emptyVarSet subst_env
+      v'        = setVarUnique v uniq
+      v''       = modifyIdInfo (\info -> substIdInfo subst info info) v'
+      subst_env' = extendSubstEnv subst_env v (DoneEx (Var v''))
+      id_env'    = extendVarEnv   id_env v ([], Var v'')
+      lvl_env'   = extendVarEnv   lvl_env v lvl
+    in
+    returnUs ((lvl_env', subst_env', id_env'), v'')
+
+cloneVars :: TopLevelFlag -> LevelEnv -> [Id] -> Level -> LvlM (LevelEnv, [Id])
+cloneVars TopLevel env vs lvl 
+  = returnUs (env, vs) -- Don't clone top level things
+cloneVars NotTopLevel (lvl_env, subst_env, id_env) vs lvl
+  = getUniquesUs (length vs)   `thenLvl` \ uniqs ->
+    let
+      subst     = mkSubst emptyVarSet subst_env'
+      vs'       = zipWith setVarUnique vs uniqs
+      vs''      = map (modifyIdInfo (\info -> substIdInfo subst info info)) vs'
+      subst_env' = extendSubstEnvList subst_env vs [DoneEx (Var v'') | v'' <- vs'']
+      id_env'    = extendVarEnvList id_env (vs `zip` [([], Var v') | v' <- vs''])
+      lvl_env'   = extendVarEnvList lvl_env (vs `zip` repeat lvl)
+    in
+    returnUs ((lvl_env', subst_env', id_env'), vs'')
 
-newLvlVar ty us
-  = mkSysLocal SLIT("lvl") (getUnique us) ty noSrcLoc
+mkTyVarApps var tyvars = foldl (\e tv -> App e (Type (mkTyVarTy tv))) 
+                              (Var var) tyvars
 \end{code}