[project @ 2002-08-01 14:34:42 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(..), 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 #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                        WordRep   -> stg_ctoi_ret_R1n_info
373                        IntRep    -> stg_ctoi_ret_R1n_info
374                        AddrRep   -> stg_ctoi_ret_R1n_info
375                        CharRep   -> stg_ctoi_ret_R1n_info
376                        FloatRep  -> stg_ctoi_ret_F1_info
377                        DoubleRep -> stg_ctoi_ret_D1_info
378                        VoidRep   -> stg_ctoi_ret_V_info
379                        other | isFollowableRep pk -> stg_ctoi_ret_R1p_info
380                                 -- Includes ArrayRep, ByteArrayRep, as well as
381                                 -- the obvious PtrRep
382                              | otherwise
383                              -> pprPanic "ByteCodeLink.ctoi_itbl" (ppr pk)
384
385        itoc_itbl st pk
386           = addr st ret_itbl_addr
387             where
388                ret_itbl_addr 
389                   = case pk of
390                        CharRep   -> stg_gc_unbx_r1_info
391                        IntRep    -> stg_gc_unbx_r1_info
392                        WordRep   -> stg_gc_unbx_r1_info
393                        AddrRep   -> stg_gc_unbx_r1_info
394                        FloatRep  -> stg_gc_f1_info
395                        DoubleRep -> stg_gc_d1_info
396                        VoidRep   -> nullPtr     -- Interpreter.c spots this special case
397                        other | isFollowableRep pk -> stg_gc_unpt_r1_info
398                              | otherwise
399                             -> pprPanic "ByteCodeLink.itoc_itbl" (ppr pk)
400                      
401 foreign label "stg_ctoi_ret_R1p_info" stg_ctoi_ret_R1p_info :: Ptr ()
402 foreign label "stg_ctoi_ret_R1n_info" stg_ctoi_ret_R1n_info :: Ptr ()
403 foreign label "stg_ctoi_ret_F1_info"  stg_ctoi_ret_F1_info :: Ptr ()
404 foreign label "stg_ctoi_ret_D1_info"  stg_ctoi_ret_D1_info :: Ptr ()
405 foreign label "stg_ctoi_ret_V_info"   stg_ctoi_ret_V_info :: Ptr ()
406
407 foreign label "stg_gc_unbx_r1_info" stg_gc_unbx_r1_info :: Ptr ()
408 foreign label "stg_gc_unpt_r1_info" stg_gc_unpt_r1_info :: Ptr ()
409 foreign label "stg_gc_f1_info"      stg_gc_f1_info :: Ptr ()
410 foreign label "stg_gc_d1_info"      stg_gc_d1_info :: Ptr ()
411
412 -- The size in 16-bit entities of an instruction.
413 instrSize16s :: BCInstr -> Int
414 instrSize16s instr
415    = case instr of
416         STKCHECK _     -> 2
417         ARGCHECK _     -> 2
418         PUSH_L   _     -> 2
419         PUSH_LL  _ _   -> 3
420         PUSH_LLL _ _ _ -> 4
421         PUSH_G   _     -> 2
422         PUSH_AS  _ _   -> 3
423         PUSH_UBX _ _   -> 3
424         PUSH_TAG _     -> 2
425         SLIDE    _ _   -> 3
426         ALLOC    _     -> 2
427         MKAP     _ _   -> 3
428         UNPACK   _     -> 2
429         UPK_TAG  _ _ _ -> 4
430         PACK     _ _   -> 3
431         LABEL    _     -> 0     -- !!
432         TESTLT_I _ _   -> 3
433         TESTEQ_I _ _   -> 3
434         TESTLT_F _ _   -> 3
435         TESTEQ_F _ _   -> 3
436         TESTLT_D _ _   -> 3
437         TESTEQ_D _ _   -> 3
438         TESTLT_P _ _   -> 3
439         TESTEQ_P _ _   -> 3
440         JMP      _     -> 2
441         CASEFAIL       -> 1
442         ENTER          -> 1
443         RETURN   _     -> 2
444
445
446 -- Make lists of host-sized words for literals, so that when the
447 -- words are placed in memory at increasing addresses, the
448 -- bit pattern is correct for the host's word size and endianness.
449 mkLitI   :: Int    -> [Word]
450 mkLitF   :: Float  -> [Word]
451 mkLitD   :: Double -> [Word]
452 mkLitPtr :: Ptr () -> [Word]
453 mkLitI64 :: Int64  -> [Word]
454
455 mkLitF f
456    = runST (do
457         arr <- newArray_ ((0::Int),0)
458         writeArray arr 0 f
459         f_arr <- castSTUArray arr
460         w0 <- readArray f_arr 0
461         return [w0 :: Word]
462      )
463
464 mkLitD d
465    | wORD_SIZE == 4
466    = runST (do
467         arr <- newArray_ ((0::Int),1)
468         writeArray arr 0 d
469         d_arr <- castSTUArray arr
470         w0 <- readArray d_arr 0
471         w1 <- readArray d_arr 1
472         return [w0 :: Word, w1]
473      )
474    | wORD_SIZE == 8
475    = runST (do
476         arr <- newArray_ ((0::Int),0)
477         writeArray arr 0 d
478         d_arr <- castSTUArray arr
479         w0 <- readArray d_arr 0
480         return [w0 :: Word]
481      )
482
483 mkLitI64 ii
484    | wORD_SIZE == 4
485    = runST (do
486         arr <- newArray_ ((0::Int),1)
487         writeArray arr 0 ii
488         d_arr <- castSTUArray arr
489         w0 <- readArray d_arr 0
490         w1 <- readArray d_arr 1
491         return [w0 :: Word,w1]
492      )
493    | wORD_SIZE == 8
494    = runST (do
495         arr <- newArray_ ((0::Int),0)
496         writeArray arr 0 ii
497         d_arr <- castSTUArray arr
498         w0 <- readArray d_arr 0
499         return [w0 :: Word]
500      )
501
502 mkLitI i
503    = runST (do
504         arr <- newArray_ ((0::Int),0)
505         writeArray arr 0 i
506         i_arr <- castSTUArray arr
507         w0 <- readArray i_arr 0
508         return [w0 :: Word]
509      )
510
511 mkLitPtr a
512    = runST (do
513         arr <- newArray_ ((0::Int),0)
514         writeArray arr 0 a
515         a_arr <- castSTUArray arr
516         w0 <- readArray a_arr 0
517         return [w0 :: Word]
518      )
519 \end{code}
520
521 %************************************************************************
522 %*                                                                      *
523 \subsection{Linking interpretables into something we can run}
524 %*                                                                      *
525 %************************************************************************
526
527 \begin{code}
528
529 {- 
530 data BCO# = BCO# ByteArray#             -- instrs   :: Array Word16#
531                  ByteArray#             -- literals :: Array Word32#
532                  PtrArray#              -- ptrs     :: Array HValue
533                  ByteArray#             -- itbls    :: Array Addr#
534 -}
535
536 linkBCO ie ce (UnlinkedBCO nm insnsSS literalsSS ptrsSS itblsSS)
537    = do insns    <- listFromSS insnsSS
538         literals <- listFromSS literalsSS
539         ptrs     <- listFromSS ptrsSS
540         itbls    <- listFromSS itblsSS
541
542         linked_ptrs     <- mapM (lookupCE ce) ptrs
543         linked_itbls    <- mapM (lookupIE ie) itbls
544         linked_literals <- mapM lookupLiteral literals
545
546         let n_insns    = sizeSS insnsSS
547             n_literals = sizeSS literalsSS
548             n_ptrs     = sizeSS ptrsSS
549             n_itbls    = sizeSS itblsSS
550
551         let ptrs_arr = array (0, n_ptrs-1) (indexify linked_ptrs)
552                        :: Array Int HValue
553             ptrs_parr = case ptrs_arr of Array lo hi parr -> parr
554
555             itbls_arr = array (0, n_itbls-1) (indexify linked_itbls)
556                         :: UArray Int ItblPtr
557             itbls_barr = case itbls_arr of UArray lo hi barr -> barr
558
559             insns_arr | n_insns > 65535
560                       = panic "linkBCO: >= 64k insns in BCO"
561                       | otherwise 
562                       = array (0, n_insns) 
563                               (indexify (fromIntegral n_insns:insns))
564                         :: UArray Int Word16
565             insns_barr = case insns_arr of UArray lo hi barr -> barr
566
567             literals_arr = array (0, n_literals-1) (indexify linked_literals)
568                            :: UArray Int Word
569             literals_barr = case literals_arr of UArray lo hi barr -> barr
570
571             indexify :: [a] -> [(Int, a)]
572             indexify xs = zip [0..] xs
573
574         BCO bco# <- newBCO insns_barr literals_barr ptrs_parr itbls_barr
575
576         -- WAS: return (unsafeCoerce# bco#)
577         case mkApUpd0# (unsafeCoerce# bco#) of
578            (# final_bco #) -> return final_bco
579
580
581 data BCO = BCO BCO#
582
583 newBCO :: ByteArray# -> ByteArray# -> Array# a -> ByteArray# -> IO BCO
584 newBCO a b c d
585    = IO (\s -> case newBCO# a b c d s of (# s1, bco #) -> (# s1, BCO bco #))
586
587
588 lookupLiteral :: Either Word FastString -> IO Word
589 lookupLiteral (Left w) = return w
590 lookupLiteral (Right addr_of_label_string)
591    = do let label_to_find = unpackFS addr_of_label_string
592         m <- lookupSymbol label_to_find 
593         case m of
594            -- Can't be bothered to find the official way to convert Addr# to Word#;
595            -- the FFI/Foreign designers make it too damn difficult
596            -- Hence we apply the Blunt Instrument, which works correctly
597            -- on all reasonable architectures anyway
598            Just (Ptr addr) -> return (W# (unsafeCoerce# addr))
599            Nothing         -> linkFail "ByteCodeLink: can't find label" 
600                                        label_to_find
601
602 lookupCE :: ClosureEnv -> Either Name PrimOp -> IO HValue
603 lookupCE ce (Right primop)
604    = do let sym_to_find = primopToCLabel primop "closure"
605         m <- lookupSymbol sym_to_find
606         case m of
607            Just (Ptr addr) -> case addrToHValue# addr of
608                                  (# hval #) -> return hval
609            Nothing -> linkFail "ByteCodeLink.lookupCE(primop)" sym_to_find
610 lookupCE ce (Left nm)
611    = case lookupFM ce nm of
612         Just aa -> return aa
613         Nothing 
614            -> ASSERT2(isExternalName nm, ppr nm)
615               do let sym_to_find = nameToCLabel nm "closure"
616                  m <- lookupSymbol sym_to_find
617                  case m of
618                     Just (Ptr addr) -> case addrToHValue# addr of
619                                           (# hval #) -> return hval
620                     Nothing         -> linkFail "ByteCodeLink.lookupCE" sym_to_find
621
622 lookupIE :: ItblEnv -> Name -> IO (Ptr a)
623 lookupIE ie con_nm 
624    = case lookupFM ie con_nm of
625         Just (Ptr a) -> return (Ptr a)
626         Nothing
627            -> do -- try looking up in the object files.
628                  let sym_to_find1 = nameToCLabel con_nm "con_info"
629                  m <- lookupSymbol sym_to_find1
630                  case m of
631                     Just addr -> return addr
632                     Nothing 
633                        -> do -- perhaps a nullary constructor?
634                              let sym_to_find2 = nameToCLabel con_nm "static_info"
635                              n <- lookupSymbol sym_to_find2
636                              case n of
637                                 Just addr -> return addr
638                                 Nothing   -> linkFail "ByteCodeLink.lookupIE" 
639                                                 (sym_to_find1 ++ " or " ++ sym_to_find2)
640
641 linkFail :: String -> String -> IO a
642 linkFail who what
643    = throwDyn (ProgramError $
644         unlines [ ""
645                 , "During interactive linking, GHCi couldn't find the following symbol:"
646                 , ' ' : ' ' : what 
647                 , "This may be due to you not asking GHCi to load extra object files,"
648                 , "archives or DLLs needed by your current session.  Restart GHCi, specifying"
649                 , "the missing library using the -L/path/to/object/dir and -lmissinglibname"
650                 , "flags, or simply by naming the relevant files on the GHCi command line."
651                 , "Alternatively, this link failure might indicate a bug in GHCi."
652                 , "If you suspect the latter, please send a bug report to:"
653                 , "  glasgow-haskell-bugs@haskell.org"
654                 ])
655
656 -- HACKS!!!  ToDo: cleaner
657 nameToCLabel :: Name -> String{-suffix-} -> String
658 nameToCLabel n suffix
659    = unpackFS(moduleNameFS (rdrNameModule rn)) 
660      ++ '_':occNameString(rdrNameOcc rn) ++ '_':suffix
661      where rn = toRdrName n
662
663 primopToCLabel :: PrimOp -> String{-suffix-} -> String
664 primopToCLabel primop suffix
665    = let str = "GHCziPrimopWrappers_" ++ occNameString (primOpOcc primop) ++ '_':suffix
666      in --trace ("primopToCLabel: " ++ str)
667         str
668
669 \end{code}
670
671 %************************************************************************
672 %*                                                                      *
673 \subsection{Connect to actual values for bytecode opcodes}
674 %*                                                                      *
675 %************************************************************************
676
677 \begin{code}
678
679 #include "Bytecodes.h"
680
681 i_ARGCHECK = (bci_ARGCHECK :: Int)
682 i_PUSH_L   = (bci_PUSH_L :: Int)
683 i_PUSH_LL  = (bci_PUSH_LL :: Int)
684 i_PUSH_LLL = (bci_PUSH_LLL :: Int)
685 i_PUSH_G   = (bci_PUSH_G :: Int)
686 i_PUSH_AS  = (bci_PUSH_AS :: Int)
687 i_PUSH_UBX = (bci_PUSH_UBX :: Int)
688 i_PUSH_TAG = (bci_PUSH_TAG :: Int)
689 i_SLIDE    = (bci_SLIDE :: Int)
690 i_ALLOC    = (bci_ALLOC :: Int)
691 i_MKAP     = (bci_MKAP :: Int)
692 i_UNPACK   = (bci_UNPACK :: Int)
693 i_UPK_TAG  = (bci_UPK_TAG :: Int)
694 i_PACK     = (bci_PACK :: Int)
695 i_TESTLT_I = (bci_TESTLT_I :: Int)
696 i_TESTEQ_I = (bci_TESTEQ_I :: Int)
697 i_TESTLT_F = (bci_TESTLT_F :: Int)
698 i_TESTEQ_F = (bci_TESTEQ_F :: Int)
699 i_TESTLT_D = (bci_TESTLT_D :: Int)
700 i_TESTEQ_D = (bci_TESTEQ_D :: Int)
701 i_TESTLT_P = (bci_TESTLT_P :: Int)
702 i_TESTEQ_P = (bci_TESTEQ_P :: Int)
703 i_CASEFAIL = (bci_CASEFAIL :: Int)
704 i_ENTER    = (bci_ENTER :: Int)
705 i_RETURN   = (bci_RETURN :: Int)
706 i_STKCHECK = (bci_STKCHECK :: Int)
707 i_JMP      = (bci_JMP :: Int)
708 #ifdef bci_CCALL
709 i_CCALL    = (bci_CCALL :: Int)
710 i_SWIZZLE  = (bci_SWIZZLE :: Int)
711 #else
712 i_CCALL    = error "Sorry pal, you need to bootstrap to use i_CCALL."
713 i_SWIZZLE  = error "Sorry pal, you need to bootstrap to use i_SWIZZLE."
714 #endif
715
716 iNTERP_STACK_CHECK_THRESH = (INTERP_STACK_CHECK_THRESH :: Int)
717
718 \end{code}