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