157
|
1 import ppci
|
158
|
2 import ir
|
|
3
|
|
4 class AsmLabel:
|
|
5 def __init__(self, lab):
|
|
6 self.lab = lab
|
|
7 def __repr__(self):
|
|
8 return '{0}:'.format(self.lab)
|
|
9
|
|
10 class Op:
|
|
11 def __init__(self, op, a, b):
|
|
12 self.op = op
|
|
13 self.a = a
|
|
14 self.b = b
|
|
15 def __repr__(self):
|
|
16 return '{0} {1}, {2}'.format(self.op, self.a, self.b)
|
157
|
17
|
|
18 class X86CodeGen:
|
|
19 def __init__(self, diag):
|
|
20 self.diag = diag
|
|
21
|
158
|
22 def emit(self, i):
|
|
23 self.asm.append(i)
|
|
24
|
157
|
25 def genBin(self, i):
|
158
|
26 self.asm = []
|
|
27 self.genModule(i)
|
157
|
28
|
158
|
29 def genModule(self, m):
|
|
30 for g in m.Globals:
|
|
31 self.emit(AsmLabel(g.name))
|
|
32 # Ignore types for now ..
|
|
33 self.emit('dw 0')
|
|
34 for f in m.Functions:
|
|
35 self.genFunction(f)
|
|
36 def genFunction(self, f):
|
|
37 self.emit('global {0}'.format(f.name))
|
|
38 self.emit(AsmLabel(f.name))
|
|
39 for bb in f.BasicBlocks:
|
|
40 self.genBB(bb)
|
|
41 def genBB(self, bb):
|
|
42 for i in bb.Instructions:
|
|
43 self.genIns(i)
|
|
44 def genIns(self, i):
|
|
45 if type(i) is ir.BinaryOperator:
|
|
46 if i.operation == 'fadd':
|
|
47 r = 'rax'
|
|
48 self.emit(Op('add', r, '11'))
|
|
49 elif type(i) is ir.RetInstruction:
|
|
50 self.emit('ret')
|
|
51 else:
|
|
52 print('Unknown ins', i)
|
|
53
|