255
|
1 import logging
|
211
|
2 import ir
|
249
|
3 from target import Label, Comment, Alignment, LabelRef, Imm32, DebugInfo
|
218
|
4 import cortexm3 as arm
|
211
|
5 from ppci import CompilerError
|
269
|
6 import registerallocator
|
|
7 from instructionselector import InstructionSelector
|
272
|
8 import irmach
|
275
|
9 from irmach import makeIns
|
|
10 import canon
|
|
11 import asm
|
274
|
12
|
|
13 class ArmFrame(irmach.Frame):
|
|
14 """
|
|
15 Arm specific frame for functions.
|
|
16 """
|
275
|
17 def __init__(self, name):
|
|
18 # We use r7 as frame pointer.
|
|
19 super().__init__(name)
|
|
20 self.regs = ['r0', 'r1', 'r2', 'r3', 'r4', 'r5', 'r6']
|
|
21 self.rv = ir.Temp('special_RV')
|
|
22 self.p1 = ir.Temp('special_P1')
|
|
23 self.p2 = ir.Temp('special_P2')
|
|
24 self.p3 = ir.Temp('special_P3')
|
|
25 self.p4 = ir.Temp('special_P4')
|
|
26 self.fp = ir.Temp('special_FP')
|
|
27 # Pre-colored registers:
|
|
28 self.tempMap = {}
|
|
29 self.tempMap[self.rv] = 'r0'
|
|
30 self.tempMap[self.p1] = 'r1'
|
|
31 self.tempMap[self.p2] = 'r2'
|
|
32 self.tempMap[self.p3] = 'r3'
|
|
33 self.tempMap[self.p4] = 'r4'
|
|
34 self.tempMap[self.fp] = 'r7'
|
|
35 self.locVars = {}
|
|
36 self.parMap = {}
|
276
|
37 # Literal pool:
|
|
38 self.constants = []
|
275
|
39
|
|
40 def argLoc(self, pos):
|
|
41 """
|
|
42 Gets the function parameter location in IR-code format.
|
|
43 """
|
|
44 if pos == 0:
|
|
45 return self.p1
|
|
46 elif pos == 1:
|
|
47 return self.p2
|
|
48 elif pos == 2:
|
|
49 return self.p3
|
|
50 elif pos == 3:
|
|
51 return self.p4
|
|
52 else:
|
|
53 raise NotImplementedError('No more than 4 parameters implemented')
|
|
54
|
|
55 def allocVar(self, lvar):
|
|
56 if lvar not in self.locVars:
|
|
57 self.locVars[lvar] = self.stacksize
|
|
58 self.stacksize = self.stacksize + 4
|
|
59 return self.locVars[lvar]
|
|
60
|
276
|
61 def addConstant(self, value):
|
|
62 lab_name = '{}_literal_{}'.format(self.name, len(self.constants))
|
|
63 self.constants.append((lab_name, value))
|
|
64 return lab_name
|
|
65
|
275
|
66 def EntryExitGlue3(self):
|
|
67 """
|
|
68 Add code for the prologue and the epilogue. Add a label, the
|
|
69 return instruction and the stack pointer adjustment for the frame.
|
|
70 """
|
|
71 self.instructions.insert(0, makeIns('{}:'.format(self.name)))
|
|
72 self.instructions.insert(1, makeIns('push {lr, r7}'))
|
279
|
73 # Reserve stack space for locals:
|
|
74 self.instructions.insert(2, makeIns('sub sp, sp, {}'.format(self.stacksize)))
|
|
75 # Setup frame pointer:
|
|
76 self.instructions.insert(3, makeIns('mov r7, sp'))
|
|
77 # Stack grows downwards
|
|
78 self.instructions.append(makeIns('add sp, sp, {}'.format(self.stacksize)))
|
275
|
79 self.instructions.append(makeIns('pop {pc,r7}'))
|
276
|
80 # Add constant literals:
|
279
|
81 self.instructions.append(makeIns('align 4')) # Align at 4 bytes
|
276
|
82 for ln, v in self.constants:
|
|
83 self.instructions.append(makeIns('{}:'.format(ln)))
|
|
84 self.instructions.append(makeIns('dcd {}'.format(v)))
|
274
|
85
|
|
86
|
268
|
87 class ArmInstructionSelector(InstructionSelector):
|
276
|
88
|
269
|
89 """ Instruction selector for the arm architecture """
|
268
|
90 def munchExpr(self, e):
|
|
91 if isinstance(e, ir.Alloc):
|
|
92 return 0
|
279
|
93 elif isinstance(e, ir.Binop) and e.operation == '+' and \
|
|
94 isinstance(e.b, ir.Const) and e.b.value < 8:
|
275
|
95 a = self.munchExpr(e.a)
|
|
96 d = self.newTmp()
|
|
97 self.emit('add %d0, %s0, {}'.format(e.b.value), dst=[d], src=[a])
|
|
98 return d
|
268
|
99 elif isinstance(e, ir.Binop) and e.operation == '+':
|
275
|
100 a = self.munchExpr(e.a)
|
|
101 b = self.munchExpr(e.b)
|
268
|
102 d = self.newTmp()
|
|
103 self.emit('add %d0, %s0, %s1', dst=[d], src=[a, b])
|
|
104 return d
|
279
|
105 elif isinstance(e, ir.Binop) and e.operation == '-' and \
|
|
106 isinstance(e.b, ir.Const) and e.b.value < 8:
|
275
|
107 a = self.munchExpr(e.a)
|
|
108 d = self.newTmp()
|
|
109 self.emit('sub %d0, %s0, {}'.format(e.b.value), dst=[d], src=[a])
|
|
110 return d
|
269
|
111 elif isinstance(e, ir.Binop) and e.operation == '-':
|
275
|
112 a = self.munchExpr(e.a)
|
|
113 b = self.munchExpr(e.b)
|
269
|
114 d = self.newTmp()
|
|
115 self.emit('sub %d0, %s0, %s1', dst=[d], src=[a, b])
|
|
116 return d
|
268
|
117 elif isinstance(e, ir.Binop) and e.operation == '|':
|
275
|
118 a = self.munchExpr(e.a)
|
|
119 b = self.munchExpr(e.b)
|
268
|
120 d = self.newTmp()
|
279
|
121 self.move(d, a)
|
|
122 self.emit('orr %s1, %s0', dst=[], src=[b, d])
|
268
|
123 return d
|
|
124 elif isinstance(e, ir.Binop) and e.operation == '<<':
|
275
|
125 a = self.munchExpr(e.a)
|
|
126 b = self.munchExpr(e.b)
|
268
|
127 d = self.newTmp()
|
279
|
128 self.move(d, a)
|
|
129 self.emit('lsl %s1, %s0', dst=[], src=[b, d]) # TODO: is d a source variable?
|
268
|
130 return d
|
|
131 elif isinstance(e, ir.Binop) and e.operation == '*':
|
275
|
132 a = self.munchExpr(e.a)
|
|
133 b = self.munchExpr(e.b)
|
268
|
134 d = self.newTmp()
|
279
|
135 self.move(d, a)
|
|
136 # this mul instruction has operands swapped:
|
|
137 self.emit('mul %s0, %d0', dst=[d], src=[b, d])
|
268
|
138 return d
|
275
|
139 elif isinstance(e, ir.Const) and e.value < 256:
|
268
|
140 d = self.newTmp()
|
275
|
141 self.emit('mov %d0, {}'.format(e.value), dst=[d])
|
|
142 return d
|
276
|
143 elif isinstance(e, ir.Const) and e.value < (2**31):
|
|
144 d = self.newTmp()
|
|
145 ln = self.frame.addConstant(e.value)
|
|
146 self.emit('ldr %d0, {}'.format(ln), dst=[d])
|
|
147 return d
|
275
|
148 elif isinstance(e, ir.Mem) and isinstance(e.e, ir.Binop) and \
|
|
149 e.e.operation == '+' and isinstance(e.e.b, ir.Const):
|
|
150 base = self.munchExpr(e.e.a)
|
|
151 d = self.newTmp()
|
279
|
152 c = e.e.b.value
|
|
153 self.emit('ldr %d0, [%s0 + {}]'.format(c), src=[base], dst=[d])
|
268
|
154 return d
|
|
155 elif isinstance(e, ir.Mem):
|
|
156 # Load from memory
|
275
|
157 base = self.munchExpr(e.e)
|
268
|
158 d = self.newTmp()
|
275
|
159 self.emit('ldr %d0, [%s0]', src=[base], dst=[d])
|
268
|
160 return d
|
|
161 elif isinstance(e, ir.Temp):
|
275
|
162 return e
|
272
|
163 elif isinstance(e, ir.Call):
|
275
|
164 # Move arguments into proper locations:
|
|
165 reguses = []
|
|
166 for i, a in enumerate(e.arguments):
|
|
167 loc = self.frame.argLoc(i)
|
|
168 m = ir.Move(loc, a)
|
|
169 self.munchStm(m)
|
|
170 if isinstance(loc, ir.Temp):
|
|
171 reguses.append(loc)
|
|
172 self.emit('bl {}'.format(e.f.name), src=reguses, dst=[self.frame.rv])
|
|
173 d = self.newTmp()
|
|
174 self.move(d, self.frame.rv)
|
|
175 return d
|
268
|
176 else:
|
272
|
177 raise NotImplementedError('Expr --> {}'.format(e))
|
268
|
178
|
|
179 def munchStm(self, s):
|
275
|
180 if isinstance(s, ir.Terminator):
|
|
181 pass
|
279
|
182 elif isinstance(s, ir.Move) and isinstance(s.dst, ir.Mem) and \
|
|
183 isinstance(s.dst.e, ir.Binop) and s.dst.e.operation == '+' and \
|
|
184 isinstance(s.dst.e.b, ir.Const):
|
|
185 a = self.munchExpr(s.dst.e.a)
|
275
|
186 val = self.munchExpr(s.src)
|
279
|
187 c = s.dst.e.b.value
|
|
188 self.emit('str %s1, [%s0 + {}]'.format(c), src=[a, val])
|
275
|
189 elif isinstance(s, ir.Move) and isinstance(s.dst, ir.Mem):
|
268
|
190 memloc = self.munchExpr(s.dst.e)
|
|
191 val = self.munchExpr(s.src)
|
275
|
192 self.emit('str %s1, [%s0]', src=[memloc, val])
|
268
|
193 elif isinstance(s, ir.Move) and isinstance(s.dst, ir.Temp):
|
|
194 val = self.munchExpr(s.src)
|
275
|
195 dreg = s.dst
|
269
|
196 self.emit('mov %d0, %s0', dst=[dreg], src=[val])
|
275
|
197 elif isinstance(s, ir.Exp):
|
|
198 # Generate expression code and discard the result.
|
|
199 x = self.munchExpr(s.e)
|
279
|
200 self.emit('nop', src=[x])
|
268
|
201 elif isinstance(s, ir.Jump):
|
269
|
202 tgt = self.targets[s.target]
|
275
|
203 self.emit('b {}'.format(s.target.name), jumps=[tgt])
|
268
|
204 elif isinstance(s, ir.CJump):
|
269
|
205 a = self.munchExpr(s.a)
|
|
206 b = self.munchExpr(s.b)
|
|
207 self.emit('cmp %s0, %s1', src=[a, b])
|
|
208 ntgt = self.targets[s.lab_no]
|
|
209 ytgt = self.targets[s.lab_yes]
|
276
|
210 jmp_ins = makeIns('b {}'.format(s.lab_no.name), jumps=[ntgt])
|
269
|
211 # Explicitely add fallthrough:
|
276
|
212 self.emit('beq {}'.format(s.lab_yes.name), jumps=[ytgt, jmp_ins])
|
269
|
213 self.emit2(jmp_ins)
|
268
|
214 else:
|
274
|
215 raise NotImplementedError('Stmt --> {}'.format(s))
|
268
|
216
|
|
217
|
274
|
218 # TODO: this class could be target independent:
|
211
|
219 class ArmCodeGenerator:
|
268
|
220 def __init__(self, outs):
|
269
|
221 # TODO: schedule traces in better order.
|
|
222 # This is optional!
|
268
|
223 self.ins_sel = ArmInstructionSelector()
|
277
|
224 self.ra = registerallocator.RegisterAllocator()
|
268
|
225 self.outs = outs
|
|
226 self.outs.getSection('code').address = 0x08000000
|
|
227 self.outs.getSection('data').address = 0x20000000
|
|
228
|
275
|
229 def generateFunc(self, irfunc):
|
|
230 # Create a frame for this function:
|
|
231 frame = ArmFrame(irfunc.name)
|
277
|
232
|
275
|
233 # Canonicalize the intermediate language:
|
|
234 canon.make(irfunc, frame)
|
277
|
235 print('after canonicalize:')
|
|
236 irfunc.dump()
|
275
|
237 self.ins_sel.munchFunction(irfunc, frame)
|
277
|
238 print('Selected instructions:')
|
|
239 for i in frame.instructions:
|
|
240 print(i)
|
275
|
241
|
|
242 # Do register allocation:
|
277
|
243 self.ra.allocFrame(frame)
|
275
|
244 # TODO: Peep-hole here?
|
|
245
|
|
246 # Add label and return and stack adjustment:
|
|
247 frame.EntryExitGlue3()
|
|
248 return frame
|
274
|
249
|
|
250 def generate(self, ircode):
|
|
251 # Munch program into a bunch of frames. One frame per function.
|
|
252 # Each frame has a flat list of abstract instructions.
|
275
|
253 # Generate code for all functions:
|
|
254 self.frames = [self.generateFunc(func) for func in ircode.Functions]
|
274
|
255
|
275
|
256 # Materialize assembly
|
|
257 # Reparse the register allocated instructions into a stream of
|
|
258 # real instructions.
|
|
259 # TODO: this is ugly via string representations. This could be
|
|
260 # another interface?
|
|
261 assembler = asm.Assembler(target=arm.armtarget, stream=self.outs)
|
|
262 self.outs.selectSection('code')
|
279
|
263 # assembly glue to make it work:
|
|
264 self.outs.emit(arm.dcd_ins(Imm32(0x20000678))) # initial SP
|
|
265 self.outs.emit(arm.dcd_ins(Imm32(0x08000009))) # reset vector
|
|
266 self.outs.emit(arm.b_ins(LabelRef('main')))
|
275
|
267 for frame in self.frames:
|
|
268 for i in frame.instructions:
|
|
269 assembler.assemble_line(str(i))
|
268
|
270
|
276
|
271 # TODO: fixup references, do this in another way?
|
|
272 self.outs.backpatch()
|
|
273 self.outs.backpatch()
|
275
|
274 return self.frames
|
268
|
275
|