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