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