[project @ 2001-01-05 17:57:07 by rrt]
[ghc-hetmet.git] / ghc / compiler / ghci / ByteCodeGen.lhs
index e1f45cf..a5b10ca 100644 (file)
@@ -23,7 +23,7 @@ import FiniteMap      ( FiniteMap, addListToFM, listToFM, filterFM,
                          addToFM, lookupFM, fmToList, emptyFM, plusFM )
 import CoreSyn
 import PprCore         ( pprCoreExpr, pprCoreAlt )
-import Literal         ( Literal(..) )
+import Literal         ( Literal(..), literalPrimRep )
 import PrimRep         ( PrimRep(..) )
 import CoreFVs         ( freeVars )
 import Type            ( typePrimRep )
@@ -42,22 +42,28 @@ import ClosureInfo  ( mkVirtHeapOffsets )
 import Module          ( ModuleName, moduleName, moduleNameFS )
 import Unique          ( mkPseudoUnique3 )
 import Linker          ( lookupSymbol )
+import FastString      ( FastString(..) )
+
 
 import List            ( intersperse )
 import Monad           ( foldM )
 import ST              ( runST )
 import MArray          ( castSTUArray, 
                          newFloatArray, writeFloatArray,
-                         newDoubleArray,  writeDoubleArray,
+                         newDoubleArray, writeDoubleArray,
                          newIntArray, writeIntArray,
                          newAddrArray, writeAddrArray )
 import Foreign         ( Storable(..), Word8, Word16, Word32, Ptr(..), 
-                         malloc, castPtr, plusPtr )
-import Addr            ( Word, Addr, addrToInt, nullAddr )
+                         malloc, castPtr, plusPtr, mallocBytes )
+import Addr            ( Word, addrToInt, nullAddr, writeCharOffAddr )
 import Bits            ( Bits(..), shiftR )
+import CTypes          ( CInt )
 
-import PrelGHC         ( BCO#, newBCO#, unsafeCoerce#, ByteArray#, Array# )
-import IOExts          ( IORef, fixIO )
+import PrelBase                ( Int(..) )
+import PrelAddr                ( Addr(..) )
+import PrelGHC         ( BCO#, newBCO#, unsafeCoerce#, 
+                         ByteArray#, Array#, addrToHValue# )
+import IOExts          ( IORef, fixIO, unsafePerformIO )
 import ArrayBase       
 import PrelArr         ( Array(..) )
 import PrelIOBase      ( IO(..) )
@@ -132,36 +138,37 @@ linkIModules :: ItblEnv    -- incoming global itbl env; returned updated
             -> ClosureEnv -- incoming global closure env; returned updated
             -> [([UnlinkedBCO], ItblEnv)]
             -> IO ([HValue], ItblEnv, ClosureEnv)
-linkIModules gie gce mods = do
-  let (bcoss, ies) = unzip mods
-      bcos = concat bcoss
-      top_level_binders = map nameOfUnlinkedBCO bcos
-      final_gie = foldr plusFM gie ies
-  
-  (new_bcos, new_gce) <-
-    fixIO (\ ~(new_bcos, new_gce) -> do
-      new_bcos <- linkBCOs final_gie new_gce bcos
-      let new_gce = addListToFM gce (zip top_level_binders new_bcos)
-      return (new_bcos, new_gce))
-
-  return (new_bcos, final_gie, new_gce)
+linkIModules gie gce mods 
+   = do let (bcoss, ies) = unzip mods
+            bcos = concat bcoss
+            final_gie = foldr plusFM gie ies
+        (final_gce, linked_bcos) <- linkSomeBCOs final_gie gce bcos
+        return (linked_bcos, final_gie, final_gce)
 
 
 linkIExpr :: ItblEnv -> ClosureEnv -> UnlinkedBCOExpr
           -> IO HValue           -- IO BCO# really
 linkIExpr ie ce (root_ul_bco, aux_ul_bcos)
-   = do let aux_ul_binders = map nameOfUnlinkedBCO aux_ul_bcos
-        (aux_bcos, aux_ce) 
-           <- fixIO 
-                (\ ~(aux_bcos, new_ce) 
-                 -> do new_bcos <- linkBCOs ie new_ce aux_ul_bcos
-                       let new_ce = addListToFM ce (zip aux_ul_binders new_bcos)
-                       return (new_bcos, new_ce)
-                )
-        [root_bco]
-           <- linkBCOs ie aux_ce [root_ul_bco]
+   = do (aux_ce, _) <- linkSomeBCOs ie ce aux_ul_bcos
+        (_, [root_bco]) <- linkSomeBCOs ie aux_ce [root_ul_bco]
         return root_bco
 
+-- Link a bunch of BCOs and return them + updated closure env.
+linkSomeBCOs :: ItblEnv -> ClosureEnv -> [UnlinkedBCO]
+                -> IO (ClosureEnv, [HValue])
+linkSomeBCOs ie ce_in ul_bcos
+   = do let nms = map nameOfUnlinkedBCO ul_bcos
+        hvals <- fixIO 
+                    ( \ hvs -> let ce_out = addListToFM ce_in (zipLazily nms hvs)
+                               in  mapM (linkBCO ie ce_out) ul_bcos )
+        let ce_out = addListToFM ce_in (zip nms hvals)
+        return (ce_out, hvals)
+     where
+        -- A lazier zip, in which no demand is propagated to the second
+        -- list unless some demand is propagated to the snd of one of the
+        -- result list elems.
+        zipLazily []     ys = []
+        zipLazily (x:xs) ys = (x, head ys) : zipLazily xs (tail ys)
 
 
 data UnlinkedBCO
@@ -244,12 +251,18 @@ data BCInstr
    | TESTEQ_F  Float  LocalLabel
    | TESTLT_D  Double LocalLabel
    | TESTEQ_D  Double LocalLabel
+
+   -- The Int value is a constructor number and therefore
+   -- stored in the insn stream rather than as an offset into
+   -- the literal pool.
    | TESTLT_P  Int    LocalLabel
    | TESTEQ_P  Int    LocalLabel
+
    | CASEFAIL
    -- To Infinity And Beyond
    | ENTER
-   | RETURN    -- unboxed value on TOS.  Use tag to find underlying ret itbl
+   | RETURN    PrimRep
+               -- unboxed value on TOS.  Use tag to find underlying ret itbl
                -- and return as per that.
 
 
@@ -264,7 +277,8 @@ instance Outputable BCInstr where
    ppr (PUSH_TAG n)          = text "PUSH_TAG" <+> int n
    ppr (SLIDE n d)           = text "SLIDE   " <+> int n <+> int d
    ppr (ALLOC sz)            = text "ALLOC   " <+> int sz
-   ppr (MKAP offset sz)      = text "MKAP    " <+> int offset <+> int sz
+   ppr (MKAP offset sz)      = text "MKAP    " <+> int sz <+> text "words," 
+                                               <+> int offset <+> text "stkoff"
    ppr (UNPACK sz)           = text "UNPACK  " <+> int sz
    ppr (UPK_TAG n m k)       = text "UPK_TAG " <+> int n <> text "words" 
                                                <+> int m <> text "conoff"
@@ -281,7 +295,7 @@ instance Outputable BCInstr where
    ppr (TESTEQ_P  i lab)     = text "TESTEQ_P" <+> int i <+> text "__" <> int lab
    ppr CASEFAIL              = text "CASEFAIL"
    ppr ENTER                 = text "ENTER"
-   ppr RETURN                = text "RETURN"
+   ppr (RETURN pk)           = text "RETURN  " <+> ppr pk
 
 instance Outputable a => Outputable (ProtoBCO a) where
    ppr (ProtoBCO name instrs origin)
@@ -322,7 +336,7 @@ type BCEnv = FiniteMap Id Int       -- To find vars on the stack
 -- Create a BCO and do a spot of peephole optimisation on the insns
 -- at the same time.
 mkProtoBCO nm instrs_ordlist origin
-   = ProtoBCO nm (peep (fromOL instrs_ordlist)) origin
+   = ProtoBCO nm (id {-peep-} (fromOL instrs_ordlist)) origin
      where
         peep (PUSH_L off1 : PUSH_L off2 : PUSH_L off3 : rest)
            = PUSH_LLL off1 (off2-1) (off3-2) : peep rest
@@ -339,7 +353,19 @@ mkProtoBCO nm instrs_ordlist origin
 -- variable to which this value was bound, so as to give the
 -- resulting BCO a name.
 schemeR :: (Id, AnnExpr Id VarSet) -> BcM ()
-schemeR (nm, rhs) = schemeR_wrk rhs nm (collect [] rhs)
+schemeR (nm, rhs) 
+{-
+   | trace (showSDoc (
+              (char ' '
+               $$ (ppr.filter (not.isTyVar).varSetElems.fst) rhs
+               $$ pprCoreExpr (deAnnotate rhs)
+               $$ char ' '
+              ))) False
+   = undefined
+-}
+   | otherwise
+   = schemeR_wrk rhs nm (collect [] rhs)
+
 
 collect xs (_, AnnLam x e) 
    = collect (if isTyVar x then xs else (x:xs)) e
@@ -352,7 +378,7 @@ schemeR_wrk original_body nm (args, body)
          szsw_args = map taggedIdSizeW all_args
          szw_args  = sum szsw_args
          p_init    = listToFM (zip all_args (mkStackOffsets 0 szsw_args))
-         argcheck  = if null args then nilOL else unitOL (ARGCHECK szw_args)
+         argcheck  = {-if null args then nilOL else-} unitOL (ARGCHECK szw_args)
      in
      schemeE szw_args 0 p_init body            `thenBc` \ body_code ->
      emitBc (mkProtoBCO (getName nm) (appOL argcheck body_code) (Right original_body))
@@ -372,26 +398,31 @@ schemeE :: Int -> Sequel -> BCEnv -> AnnExpr Id VarSet -> BcM BCInstrList
 schemeE d s p e@(fvs, AnnApp f a) 
    = returnBc (schemeT (should_args_be_tagged e) d s 0 p (fvs, AnnApp f a))
 schemeE d s p e@(fvs, AnnVar v)
-   | isFollowableRep (typePrimRep (idType v))
+   | isFollowableRep v_rep
    = returnBc (schemeT (should_args_be_tagged e) d s 0 p (fvs, AnnVar v))
    | otherwise
    = -- returning an unboxed value.  Heave it on the stack, SLIDE, and RETURN.
      let (push, szw) = pushAtom True d p (AnnVar v)
      in  returnBc (push                        -- value onto stack
                    `snocOL` SLIDE szw (d-s)    -- clear to sequel
-                   `snocOL` RETURN)            -- go
+                   `snocOL` RETURN v_rep)      -- go
+   where
+      v_rep = typePrimRep (idType v)
 
 schemeE d s p (fvs, AnnLit literal)
    = let (push, szw) = pushAtom True d p (AnnLit literal)
+         l_rep = literalPrimRep literal
      in  returnBc (push                        -- value onto stack
                    `snocOL` SLIDE szw (d-s)    -- clear to sequel
-                   `snocOL` RETURN)            -- go
+                   `snocOL` RETURN l_rep)              -- go
 
 schemeE d s p (fvs, AnnLet binds b)
    = let (xs,rhss) = case binds of AnnNonRec x rhs  -> ([x],[rhs])
                                    AnnRec xs_n_rhss -> unzip xs_n_rhss
          n     = length xs
          fvss  = map (filter (not.isTyVar).varSetElems.fst) rhss
+
+         -- Sizes of tagged free vars, + 1 for the fn
          sizes = map (\rhs_fvs -> 1 + sum (map taggedIdSizeW rhs_fvs)) fvss
 
          -- This p', d' defn is safe because all the items being pushed
@@ -461,7 +492,7 @@ schemeE d s p (fvs, AnnCase scrut bndr alts)
              returnBc (my_discr alt, rhs_code)
 
         my_discr (DEFAULT, binds, rhs)  = NoDiscr
-        my_discr (DataAlt dc, binds, rhs) = DiscrP (dataConTag dc)
+        my_discr (DataAlt dc, binds, rhs) = DiscrP (dataConTag dc - fIRST_TAG)
         my_discr (LitAlt l, binds, rhs)
            = case l of MachInt i     -> DiscrI (fromInteger i)
                        MachFloat r   -> DiscrF (fromRational r)
@@ -478,8 +509,9 @@ schemeE d s p (fvs, AnnCase scrut bndr alts)
      mapBc codeAlt alts                                `thenBc` \ alt_stuff ->
      mkMultiBranch maybe_ncons alt_stuff               `thenBc` \ alt_final ->
      let 
+         alt_final_ac = ARGCHECK (taggedIdSizeW bndr) `consOL` alt_final
          alt_bco_name = getName bndr
-         alt_bco      = mkProtoBCO alt_bco_name alt_final (Left alts)
+         alt_bco      = mkProtoBCO alt_bco_name alt_final_ac (Left alts)
      in
      schemeE (d + ret_frame_sizeW) 
              (d + ret_frame_sizeW) p scrut             `thenBc` \ scrut_code ->
@@ -516,7 +548,9 @@ schemeT enTag d s narg_words p (_, AnnApp f a)
 schemeT enTag d s narg_words p (_, AnnVar f)
    | Just con <- isDataConId_maybe f
    = ASSERT(enTag == False)
-     PACK con narg_words `consOL` (mkSLIDE 1 (d-s-1) `snocOL` ENTER)
+     --trace ("schemeT: d = " ++ show d ++ ", s = " ++ show s ++ ", naw = " ++ show narg_words) (
+     PACK con narg_words `consOL` (mkSLIDE 1 (d - narg_words - s) `snocOL` ENTER)
+     --)
    | otherwise
    = ASSERT(enTag == True)
      let (push, arg_words) = pushAtom True d p (AnnVar f)
@@ -601,7 +635,10 @@ pushAtom tagged d p (AnnVar v)
                  Just d_v -> (toOL (nOfThem nwords (PUSH_L (d-d_v+sz_t-2))), sz_t)
                  Nothing  -> ASSERT(sz_t == 1) (unitOL (PUSH_G nm), sz_t)
 
-         nm     = getName v
+         nm = case isDataConId_maybe v of
+                 Just c  -> getName c
+                 Nothing -> getName v
+
          sz_t   = taggedIdSizeW v
          sz_u   = untaggedIdSizeW v
          nwords = if tagged then sz_t else sz_u
@@ -618,11 +655,44 @@ pushAtom False d p (AnnLit lit)
         MachInt i    -> code IntRep
         MachFloat r  -> code FloatRep
         MachDouble r -> code DoubleRep
+        MachChar c   -> code CharRep
+        MachStr s    -> pushStr s
      where
         code rep
            = let size_host_words = untaggedSizeW rep
              in (unitOL (PUSH_UBX lit size_host_words), size_host_words)
 
+        pushStr s 
+           = let mallocvilleAddr
+                    = case s of
+                         CharStr s i -> A# s
+
+                         FastString _ l ba -> 
+                            -- sigh, a string in the heap is no good to us.
+                            -- We need a static C pointer, since the type of 
+                            -- a string literal is Addr#.  So, copy the string 
+                            -- into C land and introduce a memory leak 
+                            -- at the same time.
+                            let n = I# l
+                            -- CAREFUL!  Chars are 32 bits in ghc 4.09+
+                            in  unsafePerformIO (
+                                   do a@(Ptr addr) <- mallocBytes (n+1)
+                                      strncpy a ba (fromIntegral n)
+                                      writeCharOffAddr addr n '\0'
+                                      return addr
+                                   )
+                         _ -> panic "StgInterp.lit2expr: unhandled string constant type"
+
+                 addrLit 
+                    = MachInt (toInteger (addrToInt mallocvilleAddr))
+             in
+                -- Get the addr on the stack, untaggedly
+                (unitOL (PUSH_UBX addrLit 1), 1)
+
+
+
+
+
 pushAtom tagged d p (AnnApp f (_, AnnType _))
    = pushAtom tagged d p (snd f)
 
@@ -630,6 +700,8 @@ pushAtom tagged d p other
    = pprPanic "ByteCodeGen.pushAtom" 
               (pprCoreExpr (deAnnotate (undefined, other)))
 
+foreign import "strncpy" strncpy :: Ptr a -> ByteArray# -> CInt -> IO ()
+
 
 -- Given a bunch of alts code and their discrs, do the donkey work
 -- of making a multiway branch using a switch tree.
@@ -702,7 +774,7 @@ mkMultiBranch maybe_ncons raw_ways
 
          (algMinBound, algMaxBound)
             = case maybe_ncons of
-                 Just n  -> (fIRST_TAG, fIRST_TAG + n - 1)
+                 Just n  -> (0, n - 1)
                  Nothing -> (minBound, maxBound)
 
          (DiscrI i1) `eqAlt` (DiscrI i2) = i1 == i2
@@ -859,14 +931,16 @@ assembleBCO :: ProtoBCO Name -> IO UnlinkedBCO
 
 assembleBCO (ProtoBCO nm instrs origin)
    = let
-         -- pass 1: collect up the offsets of the local labels
-         label_env = mkLabelEnv emptyFM 0 instrs
+         -- pass 1: collect up the offsets of the local labels.
+         -- Remember that the first insn starts at offset 1 since offset 0
+         -- (eventually) will hold the total # of insns.
+         label_env = mkLabelEnv emptyFM 1 instrs
 
          mkLabelEnv env i_offset [] = env
          mkLabelEnv env i_offset (i:is)
             = let new_env 
                      = case i of LABEL n -> addToFM env n i_offset ; _ -> env
-              in  mkLabelEnv new_env (i_offset + instrSizeB i) is
+              in  mkLabelEnv new_env (i_offset + instrSize16s i) is
 
          findLabel lab
             = case lookupFM label_env lab of
@@ -915,7 +989,7 @@ mkBits findLabel st proto_insns
                PUSH_G    nm       -> do (p, st2) <- ptr st nm
                                         instr2 st2 i_PUSH_G p
                PUSH_AS   nm pk    -> do (p, st2)  <- ptr st nm
-                                        (np, st3) <- ret_itbl st2 pk
+                                        (np, st3) <- ctoi_itbl st2 pk
                                         instr3 st3 i_PUSH_AS p np
                PUSH_UBX  lit nws  -> do (np, st2) <- literal st lit
                                         instr3 st2 i_PUSH_UBX np nws
@@ -940,13 +1014,12 @@ mkBits findLabel st proto_insns
                                         instr3 st2 i_TESTLT_D np (findLabel l)
                TESTEQ_D  d l      -> do (np, st2) <- double st d
                                         instr3 st2 i_TESTEQ_D np (findLabel l)
-               TESTLT_P  i l      -> do (np, st2) <- int st i
-                                        instr3 st2 i_TESTLT_P np (findLabel l)
-               TESTEQ_P  i l      -> do (np, st2) <- int st i
-                                        instr3 st2 i_TESTEQ_P np (findLabel l)
+               TESTLT_P  i l      -> instr3 st i_TESTLT_P i (findLabel l)
+               TESTEQ_P  i l      -> instr3 st i_TESTEQ_P i (findLabel l)
                CASEFAIL           -> instr1 st i_CASEFAIL
                ENTER              -> instr1 st i_ENTER
-               RETURN             -> instr1 st i_RETURN
+               RETURN rep         -> do (itbl_no,st2) <- itoc_itbl st rep
+                                        instr2 st2 i_RETURN itbl_no
 
        i2s :: Int -> Word16
        i2s = fromIntegral
@@ -1004,53 +1077,67 @@ mkBits findLabel st proto_insns
        literal st (MachInt j)    = int st (fromIntegral j)
        literal st (MachFloat r)  = float st (fromRational r)
        literal st (MachDouble r) = double st (fromRational r)
+       literal st (MachChar c)   = int st c
 
-       ret_itbl st pk
+       ctoi_itbl st pk
           = addr st ret_itbl_addr
             where
-               ret_itbl_addr 
-                  = case pk of
-                       IntRep    -> stg_ctoi_ret_R1_info
-                       FloatRep  -> stg_ctoi_ret_F1_info
-                       DoubleRep -> stg_ctoi_ret_D1_info
-                    where  -- TEMP HACK
-                       stg_ctoi_ret_F1_info = nullAddr
-                       stg_ctoi_ret_D1_info = nullAddr
+               ret_itbl_addr = case pk of
+                                  PtrRep    -> stg_ctoi_ret_R1_info
+                                  IntRep    -> stg_ctoi_ret_R1_info
+                                  FloatRep  -> stg_ctoi_ret_F1_info
+                                  DoubleRep -> stg_ctoi_ret_D1_info
+                                  _ -> pprPanic "mkBits.ctoi_itbl" (ppr pk)
+                               where  -- TEMP HACK
+                                  stg_ctoi_ret_F1_info = nullAddr
+                                  stg_ctoi_ret_D1_info = nullAddr
+
+       itoc_itbl st pk
+          = addr st ret_itbl_addr
+            where
+               ret_itbl_addr = case pk of
+                                  IntRep    -> stg_gc_unbx_r1_info
+                                  FloatRep  -> stg_gc_f1_info
+                                  DoubleRep -> stg_gc_d1_info
                      
 foreign label "stg_ctoi_ret_R1_info" stg_ctoi_ret_R1_info :: Addr
 --foreign label "stg_ctoi_ret_F1_info" stg_ctoi_ret_F1_info :: Addr
 --foreign label "stg_ctoi_ret_D1_info" stg_ctoi_ret_D1_info :: Addr
 
--- The size in bytes of an instruction.
-instrSizeB :: BCInstr -> Int
-instrSizeB instr
+foreign label "stg_gc_unbx_r1_info" stg_gc_unbx_r1_info :: Addr
+foreign label "stg_gc_f1_info"      stg_gc_f1_info :: Addr
+foreign label "stg_gc_d1_info"      stg_gc_d1_info :: Addr
+
+-- The size in 16-bit entities of an instruction.
+instrSize16s :: BCInstr -> Int
+instrSize16s instr
    = case instr of
-        ARGCHECK _     -> 4
-        PUSH_L   _     -> 4
-        PUSH_LL  _ _   -> 6
-        PUSH_LLL _ _ _ -> 8
-        PUSH_G   _     -> 4
-        PUSH_AS  _ _   -> 6
-        PUSH_UBX _ _   -> 6
-        PUSH_TAG _     -> 4
-        SLIDE    _ _   -> 6
-        ALLOC    _     -> 4
-        MKAP     _ _   -> 6
-        UNPACK   _     -> 4
-        UPK_TAG  _ _ _ -> 8
-        PACK     _ _   -> 6
-        LABEL    _     -> 4
-        TESTLT_I _ _   -> 6
-        TESTEQ_I _ _   -> 6
-        TESTLT_F _ _   -> 6
-        TESTEQ_F _ _   -> 6
-        TESTLT_D _ _   -> 6
-        TESTEQ_D _ _   -> 6
-        TESTLT_P _ _   -> 6
-        TESTEQ_P _ _   -> 6
-        CASEFAIL       -> 2
-        ENTER          -> 2
-        RETURN         -> 2
+        ARGCHECK _     -> 2
+        PUSH_L   _     -> 2
+        PUSH_LL  _ _   -> 3
+        PUSH_LLL _ _ _ -> 4
+        PUSH_G   _     -> 2
+        PUSH_AS  _ _   -> 3
+        PUSH_UBX _ _   -> 3
+        PUSH_TAG _     -> 2
+        SLIDE    _ _   -> 3
+        ALLOC    _     -> 2
+        MKAP     _ _   -> 3
+        UNPACK   _     -> 2
+        UPK_TAG  _ _ _ -> 4
+        PACK     _ _   -> 3
+        LABEL    _     -> 0    -- !!
+        TESTLT_I _ _   -> 3
+        TESTEQ_I _ _   -> 3
+        TESTLT_F _ _   -> 3
+        TESTEQ_F _ _   -> 3
+        TESTLT_D _ _   -> 3
+        TESTEQ_D _ _   -> 3
+        TESTLT_P _ _   -> 3
+        TESTEQ_P _ _   -> 3
+        CASEFAIL       -> 1
+        ENTER          -> 1
+        RETURN   _     -> 2
 
 
 -- Make lists of host-sized words for literals, so that when the
@@ -1134,18 +1221,13 @@ GLOBAL_VAR(v_cafTable, [], [HValue])
 --   = do linked_expr <- linkIExpr ie ce (root_bco, other_bcos)
 --     return linked_expr
 
-
-linkBCOs :: ItblEnv -> ClosureEnv -> [UnlinkedBCO] 
-         -> IO [HValue]   -- IO [BCO#] really
-linkBCOs ie ce binds = mapM (linkBCO ie ce) binds
-
 linkBCO ie ce (UnlinkedBCO nm insnsSS literalsSS ptrsSS itblsSS)
    = do insns    <- listFromSS insnsSS
         literals <- listFromSS literalsSS
         ptrs     <- listFromSS ptrsSS
         itbls    <- listFromSS itblsSS
 
-        let linked_ptrs  = map (lookupCE ce) ptrs
+        linked_ptrs  <- mapM (lookupCE ce) ptrs
         linked_itbls <- mapM (lookupIE ie) itbls
 
         let n_insns    = sizeSS insnsSS
@@ -1161,7 +1243,11 @@ linkBCO ie ce (UnlinkedBCO nm insnsSS literalsSS ptrsSS itblsSS)
                         :: UArray Int Addr
             itbls_barr = case itbls_arr of UArray lo hi barr -> barr
 
-            insns_arr = array (0, n_insns-1) (indexify insns)
+            insns_arr | n_insns > 65535
+                      = panic "linkBCO: >= 64k insns in BCO"
+                      | otherwise 
+                      = array (0, n_insns) 
+                              (indexify (fromIntegral n_insns:insns))
                         :: UArray Int Word16
             insns_barr = case insns_arr of UArray lo hi barr -> barr
 
@@ -1184,22 +1270,32 @@ newBCO a b c d
    = IO (\s -> case newBCO# a b c d s of (# s1, bco #) -> (# s1, BCO bco #))
 
 
-lookupCE :: ClosureEnv -> Name -> HValue
+lookupCE :: ClosureEnv -> Name -> IO HValue
 lookupCE ce nm 
    = case lookupFM ce nm of
-        Just aa -> unsafeCoerce# aa
-        Nothing -> pprPanic "ByteCodeGen.lookupCE" (ppr nm)
+        Just aa -> return aa
+        Nothing 
+           -> do m <- lookupSymbol (nameToCLabel nm "closure")
+                 case m of
+                    Just (A# addr) -> case addrToHValue# addr of
+                                         (# hval #) -> return hval
+                    Nothing        -> pprPanic "ByteCodeGen.lookupCE" (ppr nm)
 
 lookupIE :: ItblEnv -> Name -> IO Addr
 lookupIE ie con_nm 
    = case lookupFM ie con_nm of
         Just (Ptr a) -> return a
-        Nothing      
+        Nothing
            -> do -- try looking up in the object files.
                  m <- lookupSymbol (nameToCLabel con_nm "con_info")
                  case m of
                     Just addr -> return addr
-                    Nothing   -> pprPanic "ByteCodeGen.lookupIE" (ppr con_nm)
+                    Nothing 
+                       -> do -- perhaps a nullary constructor?
+                             n <- lookupSymbol (nameToCLabel con_nm "static_info")
+                             case n of
+                                Just addr -> return addr
+                                Nothing -> pprPanic "ByteCodeGen.lookupIE" (ppr con_nm)
 
 -- HACK!!!  ToDo: cleaner
 nameToCLabel :: Name -> String{-suffix-} -> String
@@ -1208,54 +1304,6 @@ nameToCLabel n suffix
      ++ '_':occNameString(rdrNameOcc rn) ++ '_':suffix
      where rn = toRdrName n
 
-
-{-
-lookupCon ie con = 
-  case lookupFM ie con of
-    Just (Ptr addr) -> return addr
-    Nothing   -> do
-       -- try looking up in the object files.
-        m <- lookupSymbol (nameToCLabel con "con_info")
-       case m of
-           Just addr -> return addr
-           Nothing   -> pprPanic "linkIExpr" (ppr con)
-
--- nullary constructors don't have normal _con_info tables.
-lookupNullaryCon ie con =
-  case lookupFM ie con of
-    Just (Ptr addr) -> return (ConApp addr)
-    Nothing -> do
-       -- try looking up in the object files.
-       m <- lookupSymbol (nameToCLabel con "closure")
-       case m of
-           Just (A# addr) -> return (Native (unsafeCoerce# addr))
-           Nothing   -> pprPanic "lookupNullaryCon" (ppr con)
-
-
-lookupNative ce var =
-  unsafeInterleaveIO (do
-      case lookupFM ce var of
-       Just e  -> return (Native e)
-       Nothing -> do
-           -- try looking up in the object files.
-           let lbl = (nameToCLabel var "closure")
-           m <- lookupSymbol lbl
-           case m of
-               Just (A# addr)
-                   -> do addCAF (unsafeCoerce# addr)
-                         return (Native (unsafeCoerce# addr))
-               Nothing   -> pprPanic "linkIExpr" (ppr var)
-  )
-
--- some VarI/VarP refer to top-level interpreted functions; we change
--- them into Natives here.
-lookupVar ce f v =
-  unsafeInterleaveIO (
-       case lookupFM ce (getName v) of
-           Nothing -> return (f v)
-           Just e  -> return (Native e)
-  )
--}
 \end{code}
 
 %************************************************************************
@@ -1281,8 +1329,6 @@ mkITbls (tc:tcs) = do itbls  <- mkITbl tc
 
 mkITbl :: TyCon -> IO ItblEnv
 mkITbl tc
---   | trace ("TYCON: " ++ showSDoc (ppr tc)) False
---   = error "?!?!"
    | not (isDataTyCon tc) 
    = return emptyFM
    | n == length dcs  -- paranoia; this is an assertion.
@@ -1477,7 +1523,6 @@ i_MKAP     = (bci_MKAP :: Int)
 i_UNPACK   = (bci_UNPACK :: Int)
 i_UPK_TAG  = (bci_UPK_TAG :: Int)
 i_PACK     = (bci_PACK :: Int)
-i_LABEL    = (bci_LABEL :: Int)
 i_TESTLT_I = (bci_TESTLT_I :: Int)
 i_TESTEQ_I = (bci_TESTEQ_I :: Int)
 i_TESTLT_F = (bci_TESTLT_F :: Int)