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