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