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