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