94
|
1 from .errors import CompilerException
|
|
2 import struct
|
|
3
|
|
4 def bits(f):
|
|
5 while True:
|
|
6 Byte = f.read(1)
|
|
7 for i in range(8):
|
|
8 yield Byte & 0x1
|
|
9 Byte >>= 1
|
|
10
|
|
11 class BitReader:
|
|
12 def __init__(self, f):
|
|
13 self.stream = bits(f)
|
|
14 self.curword = None
|
|
15 def parseModule(self):
|
|
16 if self.read(8) != ord('B') or self.read(8) != ord('C'):
|
|
17 raise CompilerException('Invalid bitcode signature')
|
|
18 for bitsig in [0x0, 0xC, 0xE, 0xD]:
|
|
19 if self.read(4) != bitsig:
|
|
20 raise CompilerException('Invalid bitcode signature')
|
|
21
|
|
22 def read(self, numbits):
|
|
23 if numbits == 8:
|
|
24 b = self.stream.read(1)
|
|
25 print(b)
|
|
26 return int(b[0])
|
|
27 return 2
|
|
28
|
104
|
29 class BitstreamWriter:
|
|
30 def __init__(self, f):
|
|
31 self.f = f
|
|
32 self.u32 = 0
|
|
33 self.curpos = 0
|
|
34 def Emit1(self, val):
|
|
35 self.Emit(val, 1)
|
|
36 def Emit(self, val, numbits):
|
|
37 """ Emits value using numbits bits """
|
|
38 if numbits == 1:
|
|
39 if val != 0:
|
|
40 self.u32 |= (0x1 << self.curpos)
|
|
41 self.curpos += 1
|
|
42 if self.curpos == 32:
|
|
43 self.writeWord()
|
|
44 elif numbits > 1:
|
|
45 for i in range(numbits):
|
|
46 if val & (1 << i) != 0:
|
|
47 self.Emit1(1)
|
|
48 else:
|
|
49 self.Emit1(0)
|
|
50 def writeWord(self):
|
|
51 bts = struct.pack('<I', self.u32)
|
|
52 self.f.write(bts)
|
|
53 self.u32 = 0
|
|
54 self.curpos = 0
|
|
55 def flush(self):
|
|
56 if self.curpos != 0:
|
|
57 self.writeWord()
|
|
58
|
|
59 class BitcodeWriter:
|
|
60 def __init__(self):
|
|
61 pass
|
|
62 def WriteModule(self, module):
|
|
63 pass
|
|
64 def WriteModuleToFile(self, module, f):
|
|
65 s = BitstreamWriter(f)
|
|
66 s.Emit(ord('B'), 8)
|
|
67 s.Emit(ord('C'), 8)
|
|
68 s.Emit(0x0, 4)
|
|
69 s.Emit(0xC, 4)
|
|
70 s.Emit(0xE, 4)
|
|
71 s.Emit(0xD, 4)
|
|
72 self.WriteModule(module)
|
|
73 s.flush()
|
|
74
|