[project @ 2002-02-12 15:17:13 by simonmar]
[ghc-hetmet.git] / ghc / compiler / ghci / ByteCodeLink.lhs
1 %
2 % (c) The University of Glasgow 2000
3 %
4 \section[ByteCodeLink]{Bytecode assembler and linker}
5
6 \begin{code}
7
8 {-# OPTIONS -optc-DNON_POSIX_SOURCE #-}
9
10 module ByteCodeLink ( UnlinkedBCO, UnlinkedBCOExpr, assembleBCO,
11                       ClosureEnv, HValue, filterNameMap,
12                       linkIModules, linkIExpr, linkFail,
13                       iNTERP_STACK_CHECK_THRESH
14                    ) where
15
16 #include "HsVersions.h"
17
18 import Outputable
19 import Name             ( Name, getName, nameModule, toRdrName, isGlobalName )
20 import RdrName          ( rdrNameOcc, rdrNameModule )
21 import OccName          ( occNameString )
22 import FiniteMap        ( FiniteMap, addListToFM, filterFM,
23                           addToFM, lookupFM, emptyFM )
24 import CoreSyn
25 import Literal          ( Literal(..) )
26 import PrimOp           ( PrimOp, primOpOcc )
27 import PrimRep          ( PrimRep(..) )
28 import Constants        ( wORD_SIZE )
29 import Module           ( ModuleName, moduleName, moduleNameFS )
30 import Linker           ( lookupSymbol )
31 import FastString       ( FastString(..) )
32 import ByteCodeInstr    ( BCInstr(..), ProtoBCO(..) )
33 import ByteCodeItbls    ( ItblEnv, ItblPtr )
34 import FiniteMap
35 import Panic            ( GhcException(..) )
36
37 import Control.Monad    ( when, foldM )
38 import Control.Monad.ST ( runST )
39 import Data.Array.IArray ( array )
40
41 import GHC.Word         ( Word )
42 import Data.Array.MArray ( MArray, newArray_, readArray, writeArray )
43 import Data.Array.ST    ( castSTUArray )
44 import Data.Array.Base  ( UArray(..) )
45 import Foreign.Ptr      ( Ptr, nullPtr )
46 import Foreign          ( Word16, Ptr(..), free )
47 import System.Mem.Weak  ( addFinalizer )
48 import Data.Int         ( Int64 )
49
50 import System.IO        ( fixIO )
51 import Control.Exception ( throwDyn )
52
53 import GlaExts          ( BCO#, newBCO#, unsafeCoerce#, 
54                           ByteArray#, Array#, addrToHValue#, mkApUpd0# )
55
56 #if __GLASGOW_HASKELL__ >= 503
57 import GHC.Arr          ( Array(..) )
58 import GHC.IOBase       ( IO(..) )
59 #else
60 import PrelArr          ( Array(..) )
61 import PrelIOBase       ( IO(..) )
62 #endif
63 \end{code}
64
65 %************************************************************************
66 %*                                                                      *
67 \subsection{Top-level stuff}
68 %*                                                                      *
69 %************************************************************************
70
71 \begin{code}
72 -- Linking stuff
73 linkIModules :: ItblEnv    -- incoming global itbl env; returned updated
74              -> ClosureEnv -- incoming global closure env; returned updated
75              -> [([UnlinkedBCO], ItblEnv)]
76              -> IO ([HValue], ItblEnv, ClosureEnv)
77 linkIModules gie gce mods 
78    = do let (bcoss, ies) = unzip mods
79             bcos         = concat bcoss
80             final_gie    = foldr plusFM gie ies
81         (final_gce, linked_bcos) <- linkSomeBCOs True final_gie gce bcos
82         return (linked_bcos, final_gie, final_gce)
83
84
85 linkIExpr :: ItblEnv -> ClosureEnv -> UnlinkedBCOExpr
86           -> IO HValue    -- IO BCO# really
87 linkIExpr ie ce (root_ul_bco, aux_ul_bcos)
88    = do (aux_ce, _) <- linkSomeBCOs False ie ce aux_ul_bcos
89         (_, [root_bco]) <- linkSomeBCOs False ie aux_ce [root_ul_bco]
90         return root_bco
91
92 -- Link a bunch of BCOs and return them + updated closure env.
93 linkSomeBCOs :: Bool    -- False <=> add _all_ BCOs to returned closure env
94                         -- True  <=> add only toplevel BCOs to closure env
95              -> ItblEnv 
96              -> ClosureEnv 
97              -> [UnlinkedBCO]
98              -> IO (ClosureEnv, [HValue])
99 linkSomeBCOs toplevs_only ie ce_in ul_bcos
100    = do let nms = map nameOfUnlinkedBCO ul_bcos
101         hvals <- fixIO 
102                     ( \ hvs -> let ce_out = addListToFM ce_in (zipLazily nms hvs)
103                                in  mapM (linkBCO ie ce_out) ul_bcos )
104
105         let ce_all_additions = zip nms hvals
106             ce_top_additions = filter (isGlobalName.fst) ce_all_additions
107             ce_additions     = if toplevs_only then ce_top_additions 
108                                                else ce_all_additions
109             ce_out = -- make sure we're not inserting duplicate names into the 
110                      -- closure environment, which leads to trouble.
111                      ASSERT (all (not . (`elemFM` ce_in)) (map fst ce_additions))
112                      addListToFM ce_in ce_additions
113         return (ce_out, hvals)
114      where
115         -- A lazier zip, in which no demand is propagated to the second
116         -- list unless some demand is propagated to the snd of one of the
117         -- result list elems.
118         zipLazily []     ys = []
119         zipLazily (x:xs) ys = (x, head ys) : zipLazily xs (tail ys)
120
121
122 data UnlinkedBCO
123    = UnlinkedBCO Name
124                  (SizedSeq Word16)               -- insns
125                  (SizedSeq Word)                 -- literals
126                  (SizedSeq (Either Name PrimOp)) -- ptrs
127                  (SizedSeq Name)                 -- itbl refs
128
129 nameOfUnlinkedBCO (UnlinkedBCO nm _ _ _ _) = nm
130
131 -- When translating expressions, we need to distinguish the root
132 -- BCO for the expression
133 type UnlinkedBCOExpr = (UnlinkedBCO, [UnlinkedBCO])
134
135 instance Outputable UnlinkedBCO where
136    ppr (UnlinkedBCO nm insns lits ptrs itbls)
137       = sep [text "BCO", ppr nm, text "with", 
138              int (sizeSS insns), text "insns",
139              int (sizeSS lits), text "lits",
140              int (sizeSS ptrs), text "ptrs",
141              int (sizeSS itbls), text "itbls"]
142
143
144 -- these need a proper home
145 type ClosureEnv = FiniteMap Name HValue
146 data HValue     = HValue  -- dummy type, actually a pointer to some Real Code.
147
148 -- remove all entries for a given set of modules from the environment;
149 -- note that this removes all local names too (ie. temporary bindings from
150 -- the command line).
151 filterNameMap :: [ModuleName] -> FiniteMap Name a -> FiniteMap Name a
152 filterNameMap mods env 
153    = filterFM (\n _ -> isGlobalName n 
154                         && moduleName (nameModule n) `elem` mods) env
155 \end{code}
156
157 %************************************************************************
158 %*                                                                      *
159 \subsection{The bytecode assembler}
160 %*                                                                      *
161 %************************************************************************
162
163 The object format for bytecodes is: 16 bits for the opcode, and 16 for
164 each field -- so the code can be considered a sequence of 16-bit ints.
165 Each field denotes either a stack offset or number of items on the
166 stack (eg SLIDE), and index into the pointer table (eg PUSH_G), an
167 index into the literal table (eg PUSH_I/D/L), or a bytecode address in
168 this BCO.
169
170 \begin{code}
171 -- Top level assembler fn.
172 assembleBCO :: ProtoBCO Name -> IO UnlinkedBCO
173
174 assembleBCO (ProtoBCO nm instrs origin malloced)
175    = let
176          -- pass 1: collect up the offsets of the local labels.
177          -- Remember that the first insn starts at offset 1 since offset 0
178          -- (eventually) will hold the total # of insns.
179          label_env = mkLabelEnv emptyFM 1 instrs
180
181          mkLabelEnv env i_offset [] = env
182          mkLabelEnv env i_offset (i:is)
183             = let new_env 
184                      = case i of LABEL n -> addToFM env n i_offset ; _ -> env
185               in  mkLabelEnv new_env (i_offset + instrSize16s i) is
186
187          findLabel lab
188             = case lookupFM label_env lab of
189                  Just bco_offset -> bco_offset
190                  Nothing -> pprPanic "assembleBCO.findLabel" (int lab)
191      in
192      do  -- pass 2: generate the instruction, ptr and nonptr bits
193          insns <- return emptySS :: IO (SizedSeq Word16)
194          lits  <- return emptySS :: IO (SizedSeq Word)
195          ptrs  <- return emptySS :: IO (SizedSeq (Either Name PrimOp))
196          itbls <- return emptySS :: IO (SizedSeq Name)
197          let init_asm_state = (insns,lits,ptrs,itbls)
198          (final_insns, final_lits, final_ptrs, final_itbls) 
199             <- mkBits findLabel init_asm_state instrs
200
201          let ul_bco = UnlinkedBCO nm final_insns final_lits final_ptrs final_itbls
202
203          -- 8 Aug 01: Finalisers aren't safe when attached to non-primitive
204          -- objects, since they might get run too early.  Disable this until
205          -- we figure out what to do.
206          -- when (not (null malloced)) (addFinalizer ul_bco (mapM_ zonk malloced))
207
208          return ul_bco
209      where
210          zonk ptr = do -- putStrLn ("freeing malloc'd block at " ++ show (A# a#))
211                            free ptr
212
213 -- instrs nonptrs ptrs itbls
214 type AsmState = (SizedSeq Word16, SizedSeq Word, 
215                  SizedSeq (Either Name PrimOp), SizedSeq Name)
216
217 data SizedSeq a = SizedSeq !Int [a]
218 emptySS = SizedSeq 0 []
219 addToSS (SizedSeq n r_xs) x = return (SizedSeq (n+1) (x:r_xs))
220 addListToSS (SizedSeq n r_xs) xs 
221    = return (SizedSeq (n + length xs) (reverse xs ++ r_xs))
222 sizeSS (SizedSeq n r_xs) = n
223 listFromSS (SizedSeq n r_xs) = return (reverse r_xs)
224
225
226 -- This is where all the action is (pass 2 of the assembler)
227 mkBits :: (Int -> Int)                  -- label finder
228        -> AsmState
229        -> [BCInstr]                     -- instructions (in)
230        -> IO AsmState
231
232 mkBits findLabel st proto_insns
233   = foldM doInstr st proto_insns
234     where
235        doInstr :: AsmState -> BCInstr -> IO AsmState
236        doInstr st i
237           = case i of
238                SWIZZLE   stkoff n -> instr3 st i_SWIZZLE stkoff n
239                ARGCHECK  n        -> instr2 st i_ARGCHECK n
240                STKCHECK  n        -> instr2 st i_STKCHECK n
241                PUSH_L    o1       -> instr2 st i_PUSH_L o1
242                PUSH_LL   o1 o2    -> instr3 st i_PUSH_LL o1 o2
243                PUSH_LLL  o1 o2 o3 -> instr4 st i_PUSH_LLL o1 o2 o3
244                PUSH_G    nm       -> do (p, st2) <- ptr st nm
245                                         instr2 st2 i_PUSH_G p
246                PUSH_AS   nm pk    -> do (p, st2)  <- ptr st (Left nm)
247                                         (np, st3) <- ctoi_itbl st2 pk
248                                         instr3 st3 i_PUSH_AS p np
249                PUSH_UBX  (Left lit) nws  
250                                   -> do (np, st2) <- literal st lit
251                                         instr3 st2 i_PUSH_UBX np nws
252                PUSH_UBX  (Right aa) nws  
253                                   -> do (np, st2) <- addr st aa
254                                         instr3 st2 i_PUSH_UBX np nws
255
256                PUSH_TAG  tag      -> instr2 st i_PUSH_TAG tag
257                SLIDE     n by     -> instr3 st i_SLIDE n by
258                ALLOC     n        -> instr2 st i_ALLOC n
259                MKAP      off sz   -> instr3 st i_MKAP off sz
260                UNPACK    n        -> instr2 st i_UNPACK n
261                UPK_TAG   n m k    -> instr4 st i_UPK_TAG n m k
262                PACK      dcon sz  -> do (itbl_no,st2) <- itbl st dcon
263                                         instr3 st2 i_PACK itbl_no sz
264                LABEL     lab      -> return st
265                TESTLT_I  i l      -> do (np, st2) <- int st i
266                                         instr3 st2 i_TESTLT_I np (findLabel l)
267                TESTEQ_I  i l      -> do (np, st2) <- int st i
268                                         instr3 st2 i_TESTEQ_I np (findLabel l)
269                TESTLT_F  f l      -> do (np, st2) <- float st f
270                                         instr3 st2 i_TESTLT_F np (findLabel l)
271                TESTEQ_F  f l      -> do (np, st2) <- float st f
272                                         instr3 st2 i_TESTEQ_F np (findLabel l)
273                TESTLT_D  d l      -> do (np, st2) <- double st d
274                                         instr3 st2 i_TESTLT_D np (findLabel l)
275                TESTEQ_D  d l      -> do (np, st2) <- double st d
276                                         instr3 st2 i_TESTEQ_D np (findLabel l)
277                TESTLT_P  i l      -> instr3 st i_TESTLT_P i (findLabel l)
278                TESTEQ_P  i l      -> instr3 st i_TESTEQ_P i (findLabel l)
279                CASEFAIL           -> instr1 st i_CASEFAIL
280                JMP       l        -> instr2 st i_JMP (findLabel l)
281                ENTER              -> instr1 st i_ENTER
282                RETURN    rep      -> do (itbl_no,st2) <- itoc_itbl st rep
283                                         instr2 st2 i_RETURN itbl_no
284                CCALL     m_addr   -> do (np, st2) <- addr st m_addr
285                                         instr2 st2 i_CCALL np
286
287        i2s :: Int -> Word16
288        i2s = fromIntegral
289
290        instr1 (st_i0,st_l0,st_p0,st_I0) i1
291           = do st_i1 <- addToSS st_i0 (i2s i1)
292                return (st_i1,st_l0,st_p0,st_I0)
293
294        instr2 (st_i0,st_l0,st_p0,st_I0) i1 i2
295           = do st_i1 <- addToSS st_i0 (i2s i1)
296                st_i2 <- addToSS st_i1 (i2s i2)
297                return (st_i2,st_l0,st_p0,st_I0)
298
299        instr3 (st_i0,st_l0,st_p0,st_I0) i1 i2 i3
300           = do st_i1 <- addToSS st_i0 (i2s i1)
301                st_i2 <- addToSS st_i1 (i2s i2)
302                st_i3 <- addToSS st_i2 (i2s i3)
303                return (st_i3,st_l0,st_p0,st_I0)
304
305        instr4 (st_i0,st_l0,st_p0,st_I0) i1 i2 i3 i4
306           = do st_i1 <- addToSS st_i0 (i2s i1)
307                st_i2 <- addToSS st_i1 (i2s i2)
308                st_i3 <- addToSS st_i2 (i2s i3)
309                st_i4 <- addToSS st_i3 (i2s i4)
310                return (st_i4,st_l0,st_p0,st_I0)
311
312        float (st_i0,st_l0,st_p0,st_I0) f
313           = do let ws = mkLitF f
314                st_l1 <- addListToSS st_l0 ws
315                return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
316
317        double (st_i0,st_l0,st_p0,st_I0) d
318           = do let ws = mkLitD d
319                st_l1 <- addListToSS st_l0 ws
320                return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
321
322        int (st_i0,st_l0,st_p0,st_I0) i
323           = do let ws = mkLitI i
324                st_l1 <- addListToSS st_l0 ws
325                return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
326
327        int64 (st_i0,st_l0,st_p0,st_I0) i
328           = do let ws = mkLitI64 i
329                st_l1 <- addListToSS st_l0 ws
330                return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
331
332        addr (st_i0,st_l0,st_p0,st_I0) a
333           = do let ws = mkLitPtr a
334                st_l1 <- addListToSS st_l0 ws
335                return (sizeSS st_l0, (st_i0,st_l1,st_p0,st_I0))
336
337        ptr (st_i0,st_l0,st_p0,st_I0) p
338           = do st_p1 <- addToSS st_p0 p
339                return (sizeSS st_p0, (st_i0,st_l0,st_p1,st_I0))
340
341        itbl (st_i0,st_l0,st_p0,st_I0) dcon
342           = do st_I1 <- addToSS st_I0 (getName dcon)
343                return (sizeSS st_I0, (st_i0,st_l0,st_p0,st_I1))
344
345        literal st (MachWord w)    = int st (fromIntegral w)
346        literal st (MachInt j)     = int st (fromIntegral j)
347        literal st (MachFloat r)   = float st (fromRational r)
348        literal st (MachDouble r)  = double st (fromRational r)
349        literal st (MachChar c)    = int st c
350        literal st (MachInt64 ii)  = int64 st (fromIntegral ii)
351        literal st (MachWord64 ii) = int64 st (fromIntegral ii)
352        literal st other           = pprPanic "ByteCodeLink.literal" (ppr other)
353
354        ctoi_itbl st pk
355           = addr st ret_itbl_addr
356             where
357                ret_itbl_addr 
358                   = case pk of
359                        PtrRep    -> stg_ctoi_ret_R1p_info
360                        WordRep   -> stg_ctoi_ret_R1n_info
361                        IntRep    -> stg_ctoi_ret_R1n_info
362                        AddrRep   -> stg_ctoi_ret_R1n_info
363                        CharRep   -> stg_ctoi_ret_R1n_info
364                        FloatRep  -> stg_ctoi_ret_F1_info
365                        DoubleRep -> stg_ctoi_ret_D1_info
366                        VoidRep   -> stg_ctoi_ret_V_info
367                        other     -> pprPanic "ByteCodeLink.ctoi_itbl" (ppr pk)
368
369        itoc_itbl st pk
370           = addr st ret_itbl_addr
371             where
372                ret_itbl_addr 
373                   = case pk of
374                        CharRep   -> stg_gc_unbx_r1_info
375                        IntRep    -> stg_gc_unbx_r1_info
376                        WordRep   -> stg_gc_unbx_r1_info
377                        AddrRep   -> stg_gc_unbx_r1_info
378                        FloatRep  -> stg_gc_f1_info
379                        DoubleRep -> stg_gc_d1_info
380                        VoidRep   -> nullPtr
381                        -- Interpreter.c spots this special case
382                        other     -> pprPanic "ByteCodeLink.itoc_itbl" (ppr pk)
383                      
384 foreign label "stg_ctoi_ret_R1p_info" stg_ctoi_ret_R1p_info :: Ptr ()
385 foreign label "stg_ctoi_ret_R1n_info" stg_ctoi_ret_R1n_info :: Ptr ()
386 foreign label "stg_ctoi_ret_F1_info"  stg_ctoi_ret_F1_info :: Ptr ()
387 foreign label "stg_ctoi_ret_D1_info"  stg_ctoi_ret_D1_info :: Ptr ()
388 foreign label "stg_ctoi_ret_V_info"   stg_ctoi_ret_V_info :: Ptr ()
389
390 foreign label "stg_gc_unbx_r1_info" stg_gc_unbx_r1_info :: Ptr ()
391 foreign label "stg_gc_f1_info"      stg_gc_f1_info :: Ptr ()
392 foreign label "stg_gc_d1_info"      stg_gc_d1_info :: Ptr ()
393
394 -- The size in 16-bit entities of an instruction.
395 instrSize16s :: BCInstr -> Int
396 instrSize16s instr
397    = case instr of
398         STKCHECK _     -> 2
399         ARGCHECK _     -> 2
400         PUSH_L   _     -> 2
401         PUSH_LL  _ _   -> 3
402         PUSH_LLL _ _ _ -> 4
403         PUSH_G   _     -> 2
404         PUSH_AS  _ _   -> 3
405         PUSH_UBX _ _   -> 3
406         PUSH_TAG _     -> 2
407         SLIDE    _ _   -> 3
408         ALLOC    _     -> 2
409         MKAP     _ _   -> 3
410         UNPACK   _     -> 2
411         UPK_TAG  _ _ _ -> 4
412         PACK     _ _   -> 3
413         LABEL    _     -> 0     -- !!
414         TESTLT_I _ _   -> 3
415         TESTEQ_I _ _   -> 3
416         TESTLT_F _ _   -> 3
417         TESTEQ_F _ _   -> 3
418         TESTLT_D _ _   -> 3
419         TESTEQ_D _ _   -> 3
420         TESTLT_P _ _   -> 3
421         TESTEQ_P _ _   -> 3
422         JMP      _     -> 2
423         CASEFAIL       -> 1
424         ENTER          -> 1
425         RETURN   _     -> 2
426
427
428 -- Make lists of host-sized words for literals, so that when the
429 -- words are placed in memory at increasing addresses, the
430 -- bit pattern is correct for the host's word size and endianness.
431 mkLitI   :: Int    -> [Word]
432 mkLitF   :: Float  -> [Word]
433 mkLitD   :: Double -> [Word]
434 mkLitPtr :: Ptr ()   -> [Word]
435 mkLitI64 :: Int64  -> [Word]
436
437 mkLitF f
438    = runST (do
439         arr <- newArray_ ((0::Int),0)
440         writeArray arr 0 f
441         f_arr <- castSTUArray arr
442         w0 <- readArray f_arr 0
443         return [w0 :: Word]
444      )
445
446 mkLitD d
447    | wORD_SIZE == 4
448    = runST (do
449         arr <- newArray_ ((0::Int),1)
450         writeArray arr 0 d
451         d_arr <- castSTUArray arr
452         w0 <- readArray d_arr 0
453         w1 <- readArray d_arr 1
454         return [w0 :: Word, w1]
455      )
456    | wORD_SIZE == 8
457    = runST (do
458         arr <- newArray_ ((0::Int),0)
459         writeArray arr 0 d
460         d_arr <- castSTUArray arr
461         w0 <- readArray d_arr 0
462         return [w0 :: Word]
463      )
464
465 mkLitI64 ii
466    | wORD_SIZE == 4
467    = runST (do
468         arr <- newArray_ ((0::Int),1)
469         writeArray arr 0 ii
470         d_arr <- castSTUArray arr
471         w0 <- readArray d_arr 0
472         w1 <- readArray d_arr 1
473         return [w0 :: Word,w1]
474      )
475    | wORD_SIZE == 8
476    = runST (do
477         arr <- newArray_ ((0::Int),0)
478         writeArray arr 0 ii
479         d_arr <- castSTUArray arr
480         w0 <- readArray d_arr 0
481         return [w0 :: Word]
482      )
483
484 mkLitI i
485    = runST (do
486         arr <- newArray_ ((0::Int),0)
487         writeArray arr 0 i
488         i_arr <- castSTUArray arr
489         w0 <- readArray i_arr 0
490         return [w0 :: Word]
491      )
492
493 mkLitPtr a
494    = runST (do
495         arr <- newArray_ ((0::Int),0)
496         writeArray arr 0 a
497         a_arr <- castSTUArray arr
498         w0 <- readArray a_arr 0
499         return [w0 :: Word]
500      )
501 \end{code}
502
503 %************************************************************************
504 %*                                                                      *
505 \subsection{Linking interpretables into something we can run}
506 %*                                                                      *
507 %************************************************************************
508
509 \begin{code}
510
511 {- 
512 data BCO# = BCO# ByteArray#             -- instrs   :: Array Word16#
513                  ByteArray#             -- literals :: Array Word32#
514                  PtrArray#              -- ptrs     :: Array HValue
515                  ByteArray#             -- itbls    :: Array Addr#
516 -}
517
518 linkBCO ie ce (UnlinkedBCO nm insnsSS literalsSS ptrsSS itblsSS)
519    = do insns    <- listFromSS insnsSS
520         literals <- listFromSS literalsSS
521         ptrs     <- listFromSS ptrsSS
522         itbls    <- listFromSS itblsSS
523
524         linked_ptrs  <- mapM (lookupCE ce) ptrs
525         linked_itbls <- mapM (lookupIE ie) itbls
526
527         let n_insns    = sizeSS insnsSS
528             n_literals = sizeSS literalsSS
529             n_ptrs     = sizeSS ptrsSS
530             n_itbls    = sizeSS itblsSS
531
532         let ptrs_arr = array (0, n_ptrs-1) (indexify linked_ptrs)
533                        :: Array Int HValue
534             ptrs_parr = case ptrs_arr of Array lo hi parr -> parr
535
536             itbls_arr = array (0, n_itbls-1) (indexify linked_itbls)
537                         :: UArray Int ItblPtr
538             itbls_barr = case itbls_arr of UArray lo hi barr -> barr
539
540             insns_arr | n_insns > 65535
541                       = panic "linkBCO: >= 64k insns in BCO"
542                       | otherwise 
543                       = array (0, n_insns) 
544                               (indexify (fromIntegral n_insns:insns))
545                         :: UArray Int Word16
546             insns_barr = case insns_arr of UArray lo hi barr -> barr
547
548             literals_arr = array (0, n_literals-1) (indexify literals)
549                            :: UArray Int Word
550             literals_barr = case literals_arr of UArray lo hi barr -> barr
551
552             indexify :: [a] -> [(Int, a)]
553             indexify xs = zip [0..] xs
554
555         BCO bco# <- newBCO insns_barr literals_barr ptrs_parr itbls_barr
556
557         -- WAS: return (unsafeCoerce# bco#)
558         case mkApUpd0# (unsafeCoerce# bco#) of
559            (# final_bco #) -> return final_bco
560
561
562 data BCO = BCO BCO#
563
564 newBCO :: ByteArray# -> ByteArray# -> Array# a -> ByteArray# -> IO BCO
565 newBCO a b c d
566    = IO (\s -> case newBCO# a b c d s of (# s1, bco #) -> (# s1, BCO bco #))
567
568
569 lookupCE :: ClosureEnv -> Either Name PrimOp -> IO HValue
570 lookupCE ce (Right primop)
571    = do let sym_to_find = primopToCLabel primop "closure"
572         m <- lookupSymbol sym_to_find
573         case m of
574            Just (Ptr addr) -> case addrToHValue# addr of
575                                  (# hval #) -> return hval
576            Nothing -> linkFail "ByteCodeLink.lookupCE(primop)" sym_to_find
577 lookupCE ce (Left nm)
578    = case lookupFM ce nm of
579         Just aa -> return aa
580         Nothing 
581            -> ASSERT2(isGlobalName nm, ppr nm)
582               do let sym_to_find = nameToCLabel nm "closure"
583                  m <- lookupSymbol sym_to_find
584                  case m of
585                     Just (Ptr addr) -> case addrToHValue# addr of
586                                           (# hval #) -> return hval
587                     Nothing         -> linkFail "ByteCodeLink.lookupCE" sym_to_find
588
589 lookupIE :: ItblEnv -> Name -> IO (Ptr a)
590 lookupIE ie con_nm 
591    = case lookupFM ie con_nm of
592         Just (Ptr a) -> return (Ptr a)
593         Nothing
594            -> do -- try looking up in the object files.
595                  let sym_to_find1 = nameToCLabel con_nm "con_info"
596                  m <- lookupSymbol sym_to_find1
597                  case m of
598                     Just addr -> return addr
599                     Nothing 
600                        -> do -- perhaps a nullary constructor?
601                              let sym_to_find2 = nameToCLabel con_nm "static_info"
602                              n <- lookupSymbol sym_to_find2
603                              case n of
604                                 Just addr -> return addr
605                                 Nothing   -> linkFail "ByteCodeLink.lookupIE" 
606                                                 (sym_to_find1 ++ " or " ++ sym_to_find2)
607
608 linkFail :: String -> String -> IO a
609 linkFail who what
610    = throwDyn (ProgramError $
611         unlines [ ""
612                 , "During interactive linking, GHCi couldn't find the following symbol:"
613                 , ' ' : ' ' : what 
614                 , "This may be due to you not asking GHCi to load extra object files,"
615                 , "archives or DLLs needed by your current session.  Restart GHCi, specifying"
616                 , "the missing library using the -L/path/to/object/dir and -lmissinglibname"
617                 , "flags, or simply by naming the relevant files on the GHCi command line."
618                 , "Alternatively, this link failure might indicate a bug in GHCi."
619                 , "If you suspect the latter, please send a bug report to:"
620                 , "  glasgow-haskell-bugs@haskell.org"
621                 ])
622
623 -- HACKS!!!  ToDo: cleaner
624 nameToCLabel :: Name -> String{-suffix-} -> String
625 nameToCLabel n suffix
626    = _UNPK_(moduleNameFS (rdrNameModule rn)) 
627      ++ '_':occNameString(rdrNameOcc rn) ++ '_':suffix
628      where rn = toRdrName n
629
630 primopToCLabel :: PrimOp -> String{-suffix-} -> String
631 primopToCLabel primop suffix
632    = let str = "PrelPrimopWrappers_" ++ occNameString (primOpOcc primop) ++ '_':suffix
633      in --trace ("primopToCLabel: " ++ str)
634         str
635
636 \end{code}
637
638 %************************************************************************
639 %*                                                                      *
640 \subsection{Connect to actual values for bytecode opcodes}
641 %*                                                                      *
642 %************************************************************************
643
644 \begin{code}
645
646 #include "Bytecodes.h"
647
648 i_ARGCHECK = (bci_ARGCHECK :: Int)
649 i_PUSH_L   = (bci_PUSH_L :: Int)
650 i_PUSH_LL  = (bci_PUSH_LL :: Int)
651 i_PUSH_LLL = (bci_PUSH_LLL :: Int)
652 i_PUSH_G   = (bci_PUSH_G :: Int)
653 i_PUSH_AS  = (bci_PUSH_AS :: Int)
654 i_PUSH_UBX = (bci_PUSH_UBX :: Int)
655 i_PUSH_TAG = (bci_PUSH_TAG :: Int)
656 i_SLIDE    = (bci_SLIDE :: Int)
657 i_ALLOC    = (bci_ALLOC :: Int)
658 i_MKAP     = (bci_MKAP :: Int)
659 i_UNPACK   = (bci_UNPACK :: Int)
660 i_UPK_TAG  = (bci_UPK_TAG :: Int)
661 i_PACK     = (bci_PACK :: Int)
662 i_TESTLT_I = (bci_TESTLT_I :: Int)
663 i_TESTEQ_I = (bci_TESTEQ_I :: Int)
664 i_TESTLT_F = (bci_TESTLT_F :: Int)
665 i_TESTEQ_F = (bci_TESTEQ_F :: Int)
666 i_TESTLT_D = (bci_TESTLT_D :: Int)
667 i_TESTEQ_D = (bci_TESTEQ_D :: Int)
668 i_TESTLT_P = (bci_TESTLT_P :: Int)
669 i_TESTEQ_P = (bci_TESTEQ_P :: Int)
670 i_CASEFAIL = (bci_CASEFAIL :: Int)
671 i_ENTER    = (bci_ENTER :: Int)
672 i_RETURN   = (bci_RETURN :: Int)
673 i_STKCHECK = (bci_STKCHECK :: Int)
674 i_JMP      = (bci_JMP :: Int)
675 #ifdef bci_CCALL
676 i_CCALL    = (bci_CCALL :: Int)
677 i_SWIZZLE  = (bci_SWIZZLE :: Int)
678 #else
679 i_CCALL    = error "Sorry pal, you need to bootstrap to use i_CCALL."
680 i_SWIZZLE  = error "Sorry pal, you need to bootstrap to use i_SWIZZLE."
681 #endif
682
683 iNTERP_STACK_CHECK_THRESH = (INTERP_STACK_CHECK_THRESH :: Int)
684
685 \end{code}