Merge branch 'master' of http://darcs.haskell.org/ghc
[ghc-hetmet.git] / compiler / ghci / ByteCodeItbls.lhs
1 %
2 % (c) The University of Glasgow 2000-2006
3 %
4 ByteCodeItbls: Generate infotables for interpreter-made bytecodes
5
6 \begin{code}
7 {-# OPTIONS -optc-DNON_POSIX_SOURCE #-}
8
9 {-# OPTIONS -w #-}
10 -- The above warning supression flag is a temporary kludge.
11 -- While working on this module you are encouraged to remove it and fix
12 -- any warnings in the module. See
13 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
14 -- for details
15
16 module ByteCodeItbls ( ItblEnv, ItblPtr(..), itblCode, mkITbls
17                      , StgInfoTable(..)
18                      ) where
19
20 #include "HsVersions.h"
21
22 import Name             ( Name, getName )
23 import NameEnv
24 import SMRep            ( typeCgRep )
25 import DataCon          ( DataCon, dataConRepArgTys, dataConIdentity )
26 import TyCon            ( TyCon, tyConFamilySize, isDataTyCon, tyConDataCons )
27 import Constants        ( mIN_PAYLOAD_SIZE, wORD_SIZE )
28 import CgHeapery        ( mkVirtHeapOffsets )
29 import FastString       ( FastString(..) )
30 import Util
31 import Outputable
32
33 import Foreign
34 import Foreign.C
35 import Foreign.C.String
36 import Data.Bits        ( Bits(..), shiftR )
37
38 import GHC.Exts         ( Int(I#), addr2Int# )
39 import GHC.Ptr          ( Ptr(..) )
40
41 import Debug.Trace
42 import Text.Printf
43 \end{code}
44
45 %************************************************************************
46 %*                                                                      *
47 \subsection{Manufacturing of info tables for DataCons}
48 %*                                                                      *
49 %************************************************************************
50
51 \begin{code}
52 newtype ItblPtr = ItblPtr (Ptr ()) deriving Show
53
54 itblCode :: ItblPtr -> Ptr ()
55 itblCode (ItblPtr ptr)
56  | ghciTablesNextToCode = castPtr ptr `plusPtr` conInfoTableSizeB
57  | otherwise            = castPtr ptr
58
59 -- XXX bogus
60 conInfoTableSizeB = 3 * wORD_SIZE
61
62 type ItblEnv = NameEnv (Name, ItblPtr)
63         -- We need the Name in the range so we know which
64         -- elements to filter out when unloading a module
65
66 mkItblEnv :: [(Name,ItblPtr)] -> ItblEnv
67 mkItblEnv pairs = mkNameEnv [(n, (n,p)) | (n,p) <- pairs]
68
69
70 -- Make info tables for the data decls in this module
71 mkITbls :: [TyCon] -> IO ItblEnv
72 mkITbls [] = return emptyNameEnv
73 mkITbls (tc:tcs) = do itbls  <- mkITbl tc
74                       itbls2 <- mkITbls tcs
75                       return (itbls `plusNameEnv` itbls2)
76
77 mkITbl :: TyCon -> IO ItblEnv
78 mkITbl tc
79    | not (isDataTyCon tc) 
80    = return emptyNameEnv
81    | dcs `lengthIs` n -- paranoia; this is an assertion.
82    = make_constr_itbls dcs
83      where
84         dcs = tyConDataCons tc
85         n   = tyConFamilySize tc
86
87 #include "../includes/rts/storage/ClosureTypes.h"
88 cONSTR :: Int   -- Defined in ClosureTypes.h
89 cONSTR = CONSTR 
90
91 -- Assumes constructors are numbered from zero, not one
92 make_constr_itbls :: [DataCon] -> IO ItblEnv
93 make_constr_itbls cons
94    = do is <- mapM mk_dirret_itbl (zip cons [0..])
95         return (mkItblEnv is)
96      where
97         mk_dirret_itbl (dcon, conNo)
98            = mk_itbl dcon conNo stg_interp_constr_entry
99
100         mk_itbl :: DataCon -> Int -> Ptr () -> IO (Name,ItblPtr)
101         mk_itbl dcon conNo entry_addr = do
102            let rep_args = [ (typeCgRep arg,arg) | arg <- dataConRepArgTys dcon ]
103                (tot_wds, ptr_wds, _) = mkVirtHeapOffsets False{-not a THUNK-} rep_args
104
105                ptrs  = ptr_wds
106                nptrs = tot_wds - ptr_wds
107                nptrs_really
108                   | ptrs + nptrs >= mIN_PAYLOAD_SIZE = nptrs
109                   | otherwise = mIN_PAYLOAD_SIZE - ptrs
110                code = mkJumpToAddr entry_addr
111                itbl  = StgInfoTable {
112 #ifndef GHCI_TABLES_NEXT_TO_CODE
113                            entry = entry_addr,
114 #endif
115                            ptrs  = fromIntegral ptrs, 
116                            nptrs = fromIntegral nptrs_really,
117                            tipe  = fromIntegral cONSTR,
118                            srtlen = fromIntegral conNo
119 #ifdef GHCI_TABLES_NEXT_TO_CODE
120                          , code  = code
121 #endif
122                         }
123            qNameCString <- newArray0 0 $ dataConIdentity dcon 
124            let conInfoTbl = StgConInfoTable {
125                                  conDesc = qNameCString,
126                                  infoTable = itbl
127                             }
128                -- Make a piece of code to jump to "entry_label".
129                -- This is the only arch-dependent bit.
130            addrCon <- newExec pokeConItbl conInfoTbl
131                     --putStrLn ("SIZE of itbl is " ++ show (sizeOf itbl))
132                     --putStrLn ("# ptrs  of itbl is " ++ show ptrs)
133                     --putStrLn ("# nptrs of itbl is " ++ show nptrs_really)
134            return (getName dcon, ItblPtr (castFunPtrToPtr addrCon))
135
136
137 -- Make code which causes a jump to the given address.  This is the
138 -- only arch-dependent bit of the itbl story.  The returned list is
139 -- itblCodeLength elements (bytes) long.
140
141 -- For sparc_TARGET_ARCH, i386_TARGET_ARCH, etc.
142 #include "nativeGen/NCG.h"
143
144 itblCodeLength :: Int
145 itblCodeLength = length (mkJumpToAddr undefined)
146
147 mkJumpToAddr :: Ptr () -> [ItblCode]
148
149 ptrToInt (Ptr a#) = I# (addr2Int# a#)
150
151 #if sparc_TARGET_ARCH
152 -- After some consideration, we'll try this, where
153 -- 0x55555555 stands in for the address to jump to.
154 -- According to includes/rts/MachRegs.h, %g3 is very
155 -- likely indeed to be baggable.
156 --
157 --   0000 07155555              sethi   %hi(0x55555555), %g3
158 --   0004 8610E155              or      %g3, %lo(0x55555555), %g3
159 --   0008 81C0C000              jmp     %g3
160 --   000c 01000000              nop
161
162 type ItblCode = Word32
163 mkJumpToAddr a
164    = let w32 = fromIntegral (ptrToInt a)
165
166          hi22, lo10 :: Word32 -> Word32
167          lo10 x = x .&. 0x3FF
168          hi22 x = (x `shiftR` 10) .&. 0x3FFFF
169
170      in  [ 0x07000000 .|. (hi22 w32),
171            0x8610E000 .|. (lo10 w32),
172            0x81C0C000,
173            0x01000000 ]
174
175 #elif powerpc_TARGET_ARCH
176 -- We'll use r12, for no particular reason.
177 -- 0xDEADBEEF stands for the adress:
178 -- 3D80DEAD lis r12,0xDEAD
179 -- 618CBEEF ori r12,r12,0xBEEF
180 -- 7D8903A6 mtctr r12
181 -- 4E800420 bctr
182
183 type ItblCode = Word32
184 mkJumpToAddr a =
185     let w32 = fromIntegral (ptrToInt a)
186         hi16 x = (x `shiftR` 16) .&. 0xFFFF
187         lo16 x = x .&. 0xFFFF
188     in  [
189         0x3D800000 .|. hi16 w32,
190         0x618C0000 .|. lo16 w32,
191         0x7D8903A6, 0x4E800420
192         ]
193
194 #elif i386_TARGET_ARCH
195 -- Let the address to jump to be 0xWWXXYYZZ.
196 -- Generate   movl $0xWWXXYYZZ,%eax  ;  jmp *%eax
197 -- which is
198 -- B8 ZZ YY XX WW FF E0
199
200 type ItblCode = Word8
201 mkJumpToAddr a
202    = let w32 = fromIntegral (ptrToInt a) :: Word32
203          insnBytes :: [Word8]
204          insnBytes
205             = [0xB8, byte0 w32, byte1 w32, 
206                      byte2 w32, byte3 w32, 
207                0xFF, 0xE0]
208      in
209          insnBytes
210
211 #elif x86_64_TARGET_ARCH
212 -- Generates:
213 --      jmpq *.L1(%rip)
214 --      .align 8
215 -- .L1: 
216 --      .quad <addr>
217 --
218 -- We need a full 64-bit pointer (we can't assume the info table is
219 -- allocated in low memory).  Assuming the info pointer is aligned to
220 -- an 8-byte boundary, the addr will also be aligned.
221
222 type ItblCode = Word8
223 mkJumpToAddr a
224    = let w64 = fromIntegral (ptrToInt a) :: Word64
225          insnBytes :: [Word8]
226          insnBytes
227             = [0xff, 0x25, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,
228                byte0 w64, byte1 w64, byte2 w64, byte3 w64,
229                byte4 w64, byte5 w64, byte6 w64, byte7 w64]
230      in
231          insnBytes
232
233 #elif alpha_TARGET_ARCH
234 type ItblCode = Word32
235 mkJumpToAddr a
236     = [ 0xc3800000      -- br   at, .+4
237       , 0xa79c000c      -- ldq  at, 12(at)
238       , 0x6bfc0000      -- jmp  (at)    # with zero hint -- oh well
239       , 0x47ff041f      -- nop
240       , fromIntegral (w64 .&. 0x0000FFFF)
241       , fromIntegral ((w64 `shiftR` 32) .&. 0x0000FFFF) ]
242     where w64 = fromIntegral (ptrToInt a) :: Word64
243
244 #else
245 type ItblCode = Word32
246 mkJumpToAddr a
247     = undefined
248 #endif
249
250
251 byte0, byte1, byte2, byte3, byte4, byte5, byte6, byte7
252    :: (Integral w, Bits w) => w -> Word8
253 byte0 w = fromIntegral w
254 byte1 w = fromIntegral (w `shiftR` 8)
255 byte2 w = fromIntegral (w `shiftR` 16)
256 byte3 w = fromIntegral (w `shiftR` 24)
257 byte4 w = fromIntegral (w `shiftR` 32)
258 byte5 w = fromIntegral (w `shiftR` 40)
259 byte6 w = fromIntegral (w `shiftR` 48)
260 byte7 w = fromIntegral (w `shiftR` 56)
261
262
263 #ifndef __HADDOCK__
264 -- entry point for direct returns for created constr itbls
265 foreign import ccall "&stg_interp_constr_entry" stg_interp_constr_entry :: Ptr ()
266 #endif
267
268
269
270
271 -- Ultra-minimalist version specially for constructors
272 #if SIZEOF_VOID_P == 8
273 type HalfWord = Word32
274 #else
275 type HalfWord = Word16
276 #endif
277
278 data StgConInfoTable = StgConInfoTable {
279    conDesc   :: Ptr Word8,
280    infoTable :: StgInfoTable
281 }
282
283 instance Storable StgConInfoTable where
284    sizeOf conInfoTable    
285       = sum [ sizeOf (conDesc conInfoTable)
286             , sizeOf (infoTable conInfoTable) ]
287    alignment conInfoTable = SIZEOF_VOID_P
288    peek ptr 
289       = runState (castPtr ptr) $ do
290 #ifdef GHCI_TABLES_NEXT_TO_CODE
291            desc <- load
292 #endif
293            itbl <- load
294 #ifndef GHCI_TABLES_NEXT_TO_CODE
295            desc <- load
296 #endif
297            return  
298               StgConInfoTable 
299               { 
300 #ifdef GHCI_TABLES_NEXT_TO_CODE
301                 conDesc   = castPtr $ ptr `plusPtr` conInfoTableSizeB `plusPtr` desc
302 #else
303                 conDesc   = desc
304 #endif
305               , infoTable = itbl
306               }
307    poke = error "poke(StgConInfoTable): use pokeConItbl instead"
308
309
310 pokeConItbl :: Ptr StgConInfoTable -> Ptr StgConInfoTable -> StgConInfoTable
311             -> IO ()
312 pokeConItbl wr_ptr ex_ptr itbl 
313       = runState (castPtr wr_ptr) $ do
314 #ifdef GHCI_TABLES_NEXT_TO_CODE
315            store (conDesc itbl `minusPtr` (ex_ptr `plusPtr` conInfoTableSizeB))
316 #endif
317            store (infoTable itbl)
318 #ifndef GHCI_TABLES_NEXT_TO_CODE
319            store (conDesc itbl)
320 #endif
321
322 data StgInfoTable = StgInfoTable {
323 #ifndef GHCI_TABLES_NEXT_TO_CODE
324    entry  :: Ptr (),
325 #endif
326    ptrs   :: HalfWord,
327    nptrs  :: HalfWord,
328    tipe   :: HalfWord,
329    srtlen :: HalfWord
330 #ifdef GHCI_TABLES_NEXT_TO_CODE
331  , code   :: [ItblCode]
332 #endif
333   }
334
335 instance Storable StgInfoTable where
336
337    sizeOf itbl 
338       = sum
339         [
340 #ifndef GHCI_TABLES_NEXT_TO_CODE
341          fieldSz entry itbl,
342 #endif
343          fieldSz ptrs itbl,
344          fieldSz nptrs itbl,
345          fieldSz tipe itbl,
346          fieldSz srtlen itbl
347 #ifdef GHCI_TABLES_NEXT_TO_CODE
348         ,fieldSz (head.code) itbl * itblCodeLength
349 #endif
350         ]
351
352    alignment itbl 
353       = SIZEOF_VOID_P
354
355    poke a0 itbl
356       = runState (castPtr a0)
357       $ do
358 #ifndef GHCI_TABLES_NEXT_TO_CODE
359            store (entry  itbl)
360 #endif
361            store (ptrs   itbl)
362            store (nptrs  itbl)
363            store (tipe   itbl)
364            store (srtlen itbl)
365 #ifdef GHCI_TABLES_NEXT_TO_CODE
366            sequence_ (map store (code itbl))
367 #endif
368
369    peek a0
370       = runState (castPtr a0)
371       $ do
372 #ifndef GHCI_TABLES_NEXT_TO_CODE
373            entry  <- load
374 #endif
375            ptrs   <- load
376            nptrs  <- load
377            tipe   <- load
378            srtlen <- load
379 #ifdef GHCI_TABLES_NEXT_TO_CODE
380            code   <- sequence (replicate itblCodeLength load)
381 #endif
382            return 
383               StgInfoTable { 
384 #ifndef GHCI_TABLES_NEXT_TO_CODE
385                  entry  = entry,
386 #endif
387                  ptrs   = ptrs,
388                  nptrs  = nptrs, 
389                  tipe   = tipe,
390                  srtlen = srtlen
391 #ifdef GHCI_TABLES_NEXT_TO_CODE
392                 ,code   = code
393 #endif
394               }
395
396 fieldSz :: (Storable a, Storable b) => (a -> b) -> a -> Int
397 fieldSz sel x = sizeOf (sel x)
398
399 newtype State s m a = State (s -> m (s, a))
400
401 instance Monad m => Monad (State s m) where
402   return a      = State (\s -> return (s, a))
403   State m >>= k = State (\s -> m s >>= \(s', a) -> case k a of State n -> n s')
404   fail str      = State (\s -> fail str)
405
406 class (Monad m, Monad (t m)) => MonadT t m where
407   lift :: m a -> t m a
408
409 instance Monad m => MonadT (State s) m where
410   lift m        = State (\s -> m >>= \a -> return (s, a))
411
412 runState :: (Monad m) => s -> State s m a -> m a
413 runState s (State m) = m s >>= return . snd
414
415 type PtrIO = State (Ptr Word8) IO
416
417 advance :: Storable a => PtrIO (Ptr a)
418 advance = State adv where
419     adv addr = case castPtr addr of { addrCast -> return
420         (addr `plusPtr` sizeOfPointee addrCast, addrCast) }
421
422 sizeOfPointee :: (Storable a) => Ptr a -> Int
423 sizeOfPointee addr = sizeOf (typeHack addr)
424     where typeHack = undefined :: Ptr a -> a
425
426 store :: Storable a => a -> PtrIO ()
427 store x = do addr <- advance
428              lift (poke addr x)
429
430 load :: Storable a => PtrIO a
431 load = do addr <- advance
432           lift (peek addr)
433
434
435 newExec :: Storable a => (Ptr a -> Ptr a -> a -> IO ()) -> a -> IO (FunPtr ())
436 newExec poke_fn obj
437    = alloca $ \pcode -> do
438         wr_ptr <- _allocateExec (fromIntegral (sizeOf obj)) pcode
439         ex_ptr <- peek pcode
440         poke_fn wr_ptr ex_ptr obj
441         return (castPtrToFunPtr ex_ptr)
442    where
443    codeSize :: Storable a => a -> [a] -> Int
444    codeSize dummy array = sizeOf(dummy) * length array
445
446 foreign import ccall unsafe "allocateExec"
447   _allocateExec :: CUInt -> Ptr (Ptr a) -> IO (Ptr a)  
448 \end{code}