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