summaryrefslogtreecommitdiff
path: root/compiler/ghci/ByteCodeItbls.lhs
blob: e6da6407bb0cc364386b68da171beff4159df3c5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
%
% (c) The University of Glasgow 2000-2006
%
ByteCodeItbls: Generate infotables for interpreter-made bytecodes

\begin{code}
{-# OPTIONS -optc-DNON_POSIX_SOURCE #-}

#ifndef GHCI_TABLES_NEXT_TO_CODE
{-# OPTIONS_GHC -Wwarn #-}
-- There are lots of warnings when GHCI_TABLES_NEXT_TO_CODE is off.
-- It would be nice to fix this properly, but for now we turn -Werror
-- off.
#endif

module ByteCodeItbls ( ItblEnv, ItblPtr(..), itblCode, mkITbls
                     , StgInfoTable(..)
                     , State(..), runState, evalState, execState, MonadT(..)
                     ) where

#include "HsVersions.h"

import Name             ( Name, getName )
import NameEnv
import ClosureInfo
import DataCon          ( DataCon, dataConRepArgTys, dataConIdentity )
import TyCon            ( TyCon, tyConFamilySize, isDataTyCon, tyConDataCons )
import Constants        ( mIN_PAYLOAD_SIZE, wORD_SIZE )
import CgHeapery        ( mkVirtHeapOffsets )
import Util

import Foreign
import Foreign.C

import Control.Monad    ( liftM )

import GHC.Exts         ( Int(I#), addr2Int# )
import GHC.Ptr          ( Ptr(..) )
\end{code}

%************************************************************************
%*                                                                      *
\subsection{Manufacturing of info tables for DataCons}
%*                                                                      *
%************************************************************************

\begin{code}
newtype ItblPtr = ItblPtr (Ptr ()) deriving Show

itblCode :: ItblPtr -> Ptr ()
itblCode (ItblPtr ptr)
 | ghciTablesNextToCode = castPtr ptr `plusPtr` conInfoTableSizeB
 | otherwise            = castPtr ptr

-- XXX bogus
conInfoTableSizeB :: Int
conInfoTableSizeB = 3 * wORD_SIZE

type ItblEnv = NameEnv (Name, ItblPtr)
        -- We need the Name in the range so we know which
        -- elements to filter out when unloading a module

mkItblEnv :: [(Name,ItblPtr)] -> ItblEnv
mkItblEnv pairs = mkNameEnv [(n, (n,p)) | (n,p) <- pairs]


-- Make info tables for the data decls in this module
mkITbls :: [TyCon] -> IO ItblEnv
mkITbls [] = return emptyNameEnv
mkITbls (tc:tcs) = do itbls  <- mkITbl tc
                      itbls2 <- mkITbls tcs
                      return (itbls `plusNameEnv` itbls2)

mkITbl :: TyCon -> IO ItblEnv
mkITbl tc
   | not (isDataTyCon tc) 
   = return emptyNameEnv
   | dcs `lengthIs` n -- paranoia; this is an assertion.
   = make_constr_itbls dcs
     where
        dcs = tyConDataCons tc
        n   = tyConFamilySize tc

mkITbl _ = error "Unmatched patter in mkITbl: assertion failed!"

#include "../includes/rts/storage/ClosureTypes.h"
cONSTR :: Int   -- Defined in ClosureTypes.h
cONSTR = CONSTR 

-- Assumes constructors are numbered from zero, not one
make_constr_itbls :: [DataCon] -> IO ItblEnv
make_constr_itbls cons
   = do is <- mapM mk_dirret_itbl (zip cons [0..])
        return (mkItblEnv is)
     where
        mk_dirret_itbl (dcon, conNo)
           = mk_itbl dcon conNo stg_interp_constr_entry

        mk_itbl :: DataCon -> Int -> Ptr () -> IO (Name,ItblPtr)
        mk_itbl dcon conNo entry_addr = do
           let rep_args = [ (typeCgRep arg,arg) | arg <- dataConRepArgTys dcon ]
               (tot_wds, ptr_wds, _) = mkVirtHeapOffsets False{-not a THUNK-} rep_args

               ptrs'  = ptr_wds
               nptrs' = tot_wds - ptr_wds
               nptrs_really
                  | ptrs' + nptrs' >= mIN_PAYLOAD_SIZE = nptrs'
                  | otherwise = mIN_PAYLOAD_SIZE - ptrs'
               code' = mkJumpToAddr entry_addr
               itbl  = StgInfoTable {
#ifndef GHCI_TABLES_NEXT_TO_CODE
                           entry = entry_addr,
#endif
                           ptrs  = fromIntegral ptrs', 
                           nptrs = fromIntegral nptrs_really,
                           tipe  = fromIntegral cONSTR,
                           srtlen = fromIntegral conNo
#ifdef GHCI_TABLES_NEXT_TO_CODE
                         , code  = code'
#endif
                        }
           qNameCString <- newArray0 0 $ dataConIdentity dcon 
           let conInfoTbl = StgConInfoTable {
                                 conDesc = qNameCString,
                                 infoTable = itbl
                            }
               -- Make a piece of code to jump to "entry_label".
               -- This is the only arch-dependent bit.
           addrCon <- newExec pokeConItbl conInfoTbl
                    --putStrLn ("SIZE of itbl is " ++ show (sizeOf itbl))
                    --putStrLn ("# ptrs  of itbl is " ++ show ptrs)
                    --putStrLn ("# nptrs of itbl is " ++ show nptrs_really)
           return (getName dcon, ItblPtr (castFunPtrToPtr addrCon))


-- Make code which causes a jump to the given address.  This is the
-- only arch-dependent bit of the itbl story.  The returned list is
-- itblCodeLength elements (bytes) long.

-- For sparc_TARGET_ARCH, i386_TARGET_ARCH, etc.
#include "nativeGen/NCG.h"

itblCodeLength :: Int
itblCodeLength = length (mkJumpToAddr undefined)

mkJumpToAddr :: Ptr () -> [ItblCode]

ptrToInt :: Ptr a -> Int
ptrToInt (Ptr a#) = I# (addr2Int# a#)

#if sparc_TARGET_ARCH
-- After some consideration, we'll try this, where
-- 0x55555555 stands in for the address to jump to.
-- According to includes/rts/MachRegs.h, %g3 is very
-- likely indeed to be baggable.
--
--   0000 07155555              sethi   %hi(0x55555555), %g3
--   0004 8610E155              or      %g3, %lo(0x55555555), %g3
--   0008 81C0C000              jmp     %g3
--   000c 01000000              nop

type ItblCode = Word32
mkJumpToAddr a
   = let w32 = fromIntegral (ptrToInt a)

         hi22, lo10 :: Word32 -> Word32
         lo10 x = x .&. 0x3FF
         hi22 x = (x `shiftR` 10) .&. 0x3FFFF

     in  [ 0x07000000 .|. (hi22 w32),
           0x8610E000 .|. (lo10 w32),
           0x81C0C000,
           0x01000000 ]

#elif powerpc_TARGET_ARCH
-- We'll use r12, for no particular reason.
-- 0xDEADBEEF stands for the adress:
-- 3D80DEAD lis r12,0xDEAD
-- 618CBEEF ori r12,r12,0xBEEF
-- 7D8903A6 mtctr r12
-- 4E800420 bctr

type ItblCode = Word32
mkJumpToAddr a =
    let w32 = fromIntegral (ptrToInt a)
        hi16 x = (x `shiftR` 16) .&. 0xFFFF
        lo16 x = x .&. 0xFFFF
    in  [
        0x3D800000 .|. hi16 w32,
        0x618C0000 .|. lo16 w32,
        0x7D8903A6, 0x4E800420
        ]

#elif i386_TARGET_ARCH
-- Let the address to jump to be 0xWWXXYYZZ.
-- Generate   movl $0xWWXXYYZZ,%eax  ;  jmp *%eax
-- which is
-- B8 ZZ YY XX WW FF E0

type ItblCode = Word8
mkJumpToAddr a
   = let w32 = fromIntegral (ptrToInt a) :: Word32
         insnBytes :: [Word8]
         insnBytes
            = [0xB8, byte0 w32, byte1 w32, 
                     byte2 w32, byte3 w32, 
               0xFF, 0xE0]
     in
         insnBytes

#elif x86_64_TARGET_ARCH
-- Generates:
--      jmpq *.L1(%rip)
--      .align 8
-- .L1: 
--      .quad <addr>
--
-- We need a full 64-bit pointer (we can't assume the info table is
-- allocated in low memory).  Assuming the info pointer is aligned to
-- an 8-byte boundary, the addr will also be aligned.

type ItblCode = Word8
mkJumpToAddr a
   = let w64 = fromIntegral (ptrToInt a) :: Word64
         insnBytes :: [Word8]
         insnBytes
            = [0xff, 0x25, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,
               byte0 w64, byte1 w64, byte2 w64, byte3 w64,
               byte4 w64, byte5 w64, byte6 w64, byte7 w64]
     in
         insnBytes

#elif alpha_TARGET_ARCH
type ItblCode = Word32
mkJumpToAddr a
    = [ 0xc3800000      -- br   at, .+4
      , 0xa79c000c      -- ldq  at, 12(at)
      , 0x6bfc0000      -- jmp  (at)    # with zero hint -- oh well
      , 0x47ff041f      -- nop
      , fromIntegral (w64 .&. 0x0000FFFF)
      , fromIntegral ((w64 `shiftR` 32) .&. 0x0000FFFF) ]
    where w64 = fromIntegral (ptrToInt a) :: Word64

#else
type ItblCode = Word32
mkJumpToAddr a
    = undefined
#endif

#if defined(i386_TARGET_ARCH) || defined(x86_64_TARGET_ARCH)
byte0, byte1, byte2, byte3 :: (Integral w, Bits w) => w -> Word8
byte0 w = fromIntegral w
byte1 w = fromIntegral (w `shiftR` 8)
byte2 w = fromIntegral (w `shiftR` 16)
byte3 w = fromIntegral (w `shiftR` 24)
#endif

#if defined(x86_64_TARGET_ARCH)
byte4, byte5, byte6, byte7 :: (Integral w, Bits w) => w -> Word8
byte4 w = fromIntegral (w `shiftR` 32)
byte5 w = fromIntegral (w `shiftR` 40)
byte6 w = fromIntegral (w `shiftR` 48)
byte7 w = fromIntegral (w `shiftR` 56)
#endif

#ifndef __HADDOCK__
-- entry point for direct returns for created constr itbls
foreign import ccall "&stg_interp_constr_entry" stg_interp_constr_entry :: Ptr ()
#endif




-- Ultra-minimalist version specially for constructors
#if SIZEOF_VOID_P == 8
type HalfWord = Word32
#else
type HalfWord = Word16
#endif

data StgConInfoTable = StgConInfoTable {
   conDesc   :: Ptr Word8,
   infoTable :: StgInfoTable
}

instance Storable StgConInfoTable where
   sizeOf conInfoTable    
      = sum [ sizeOf (conDesc conInfoTable)
            , sizeOf (infoTable conInfoTable) ]
   alignment _ = SIZEOF_VOID_P
   peek ptr 
      = evalState (castPtr ptr) $ do
#ifdef GHCI_TABLES_NEXT_TO_CODE
           desc <- load
#endif
           itbl <- load
#ifndef GHCI_TABLES_NEXT_TO_CODE
           desc <- load
#endif
           return  
              StgConInfoTable 
              { 
#ifdef GHCI_TABLES_NEXT_TO_CODE
                conDesc   = castPtr $ ptr `plusPtr` conInfoTableSizeB `plusPtr` desc
#else
                conDesc   = desc
#endif
              , infoTable = itbl
              }
   poke = error "poke(StgConInfoTable): use pokeConItbl instead"


pokeConItbl :: Ptr StgConInfoTable -> Ptr StgConInfoTable -> StgConInfoTable
            -> IO ()
pokeConItbl wr_ptr ex_ptr itbl 
      = evalState (castPtr wr_ptr) $ do
#ifdef GHCI_TABLES_NEXT_TO_CODE
           store (conDesc itbl `minusPtr` (ex_ptr `plusPtr` conInfoTableSizeB))
#endif
           store (infoTable itbl)
#ifndef GHCI_TABLES_NEXT_TO_CODE
           store (conDesc itbl)
#endif

data StgInfoTable = StgInfoTable {
#ifndef GHCI_TABLES_NEXT_TO_CODE
   entry  :: Ptr (),
#endif
   ptrs   :: HalfWord,
   nptrs  :: HalfWord,
   tipe   :: HalfWord,
   srtlen :: HalfWord
#ifdef GHCI_TABLES_NEXT_TO_CODE
 , code   :: [ItblCode]
#endif
  }

instance Storable StgInfoTable where

   sizeOf itbl 
      = sum
        [
#ifndef GHCI_TABLES_NEXT_TO_CODE
         fieldSz entry itbl,
#endif
         fieldSz ptrs itbl,
         fieldSz nptrs itbl,
         fieldSz tipe itbl,
         fieldSz srtlen itbl
#ifdef GHCI_TABLES_NEXT_TO_CODE
        ,fieldSz (head.code) itbl * itblCodeLength
#endif
        ]

   alignment _ 
      = SIZEOF_VOID_P

   poke a0 itbl
      = evalState (castPtr a0)
      $ do
#ifndef GHCI_TABLES_NEXT_TO_CODE
           store (entry  itbl)
#endif
           store (ptrs   itbl)
           store (nptrs  itbl)
           store (tipe   itbl)
           store (srtlen itbl)
#ifdef GHCI_TABLES_NEXT_TO_CODE
           sequence_ (map store (code itbl))
#endif

   peek a0
      = evalState (castPtr a0)
      $ do
#ifndef GHCI_TABLES_NEXT_TO_CODE
           entry'  <- load
#endif
           ptrs'   <- load
           nptrs'  <- load
           tipe'   <- load
           srtlen' <- load
#ifdef GHCI_TABLES_NEXT_TO_CODE
           code'   <- sequence (replicate itblCodeLength load)
#endif
           return 
              StgInfoTable { 
#ifndef GHCI_TABLES_NEXT_TO_CODE
                 entry  = entry',
#endif
                 ptrs   = ptrs',
                 nptrs  = nptrs',
                 tipe   = tipe',
                 srtlen = srtlen'
#ifdef GHCI_TABLES_NEXT_TO_CODE
                ,code   = code'
#endif
              }

fieldSz :: (Storable a, Storable b) => (a -> b) -> a -> Int
fieldSz sel x = sizeOf (sel x)

newtype State s m a = State (s -> m (s, a))

instance Monad m => Monad (State s m) where
  return a      = State (\s -> return (s, a))
  State m >>= k = State (\s -> m s >>= \(s', a) -> case k a of State n -> n s')
  fail str      = State (\_ -> fail str)

class (Monad m, Monad (t m)) => MonadT t m where
  lift :: m a -> t m a

instance Monad m => MonadT (State s) m where
  lift m        = State (\s -> m >>= \a -> return (s, a))

runState :: Monad m => s -> State s m a -> m (s, a)
runState s (State m) = m s

evalState :: Monad m => s -> State s m a -> m a
evalState s m = liftM snd (runState s m)

execState :: Monad m => s -> State s m a -> m s
execState s m = liftM fst (runState s m)

type PtrIO = State (Ptr Word8) IO

advance :: Storable a => PtrIO (Ptr a)
advance = State adv where
    adv addr = case castPtr addr of { addrCast -> return
        (addr `plusPtr` sizeOfPointee addrCast, addrCast) }

sizeOfPointee :: (Storable a) => Ptr a -> Int
sizeOfPointee addr = sizeOf (typeHack addr)
    where typeHack = undefined :: Ptr a -> a

store :: Storable a => a -> PtrIO ()
store x = do addr <- advance
             lift (poke addr x)

load :: Storable a => PtrIO a
load = do addr <- advance
          lift (peek addr)


newExec :: Storable a => (Ptr a -> Ptr a -> a -> IO ()) -> a -> IO (FunPtr ())
newExec poke_fn obj
   = alloca $ \pcode -> do
        wr_ptr <- _allocateExec (fromIntegral (sizeOf obj)) pcode
        ex_ptr <- peek pcode
        poke_fn wr_ptr ex_ptr obj
        return (castPtrToFunPtr ex_ptr)

foreign import ccall unsafe "allocateExec"
  _allocateExec :: CUInt -> Ptr (Ptr a) -> IO (Ptr a)  
\end{code}