tracking down what looks like an error in the Simulator Mem ld/st
[soc.git] / src / soc / decoder / isa / caller.py
1 """core of the python-based POWER9 simulator
2
3 this is part of a cycle-accurate POWER9 simulator. its primary purpose is
4 not speed, it is for both learning and educational purposes, as well as
5 a method of verifying the HDL.
6 """
7
8 from functools import wraps
9 from soc.decoder.orderedset import OrderedSet
10 from soc.decoder.selectable_int import (FieldSelectableInt, SelectableInt,
11 selectconcat)
12 from soc.decoder.power_enums import spr_dict, XER_bits
13 from soc.decoder.helpers import exts
14 from collections import namedtuple
15 import math
16
17 instruction_info = namedtuple('instruction_info',
18 'func read_regs uninit_regs write_regs ' + \
19 'special_regs op_fields form asmregs')
20
21 special_sprs = {
22 'LR': 8,
23 'CTR': 9,
24 'TAR': 815,
25 'XER': 1,
26 'VRSAVE': 256}
27
28
29 def create_args(reglist, extra=None):
30 args = OrderedSet()
31 for reg in reglist:
32 args.add(reg)
33 args = list(args)
34 if extra:
35 args = [extra] + args
36 return args
37
38
39 class Mem:
40
41 def __init__(self, bytes_per_word=8, initial_mem=None):
42 self.mem = {}
43 self.bytes_per_word = bytes_per_word
44 self.word_log2 = math.ceil(math.log2(bytes_per_word))
45 if not initial_mem:
46 return
47 print ("Sim-Mem", initial_mem, self.bytes_per_word)
48 for addr, (val, width) in initial_mem.items():
49 self.st(addr, val, width)
50
51 def _get_shifter_mask(self, wid, remainder):
52 shifter = ((self.bytes_per_word - wid) - remainder) * \
53 8 # bits per byte
54 mask = (1 << (wid * 8)) - 1
55 print ("width,rem,shift,mask", wid, remainder, hex(shifter), hex(mask))
56 return shifter, mask
57
58 # TODO: Implement ld/st of lesser width
59 def ld(self, address, width=8):
60 print("ld from addr 0x{:x} width {:d}".format(address, width))
61 remainder = address & (self.bytes_per_word - 1)
62 address = address >> self.word_log2
63 assert remainder & (width - 1) == 0, "Unaligned access unsupported!"
64 if address in self.mem:
65 val = self.mem[address]
66 else:
67 val = 0
68 print("mem @ 0x{:x} rem {:d} : 0x{:x}".format(address, remainder, val))
69
70 if width != self.bytes_per_word:
71 shifter, mask = self._get_shifter_mask(width, remainder)
72 print ("masking", hex(val), hex(mask<<shifter), shifter)
73 val = val & (mask << shifter)
74 val >>= shifter
75 print("Read 0x{:x} from addr 0x{:x}".format(val, address))
76 return val
77
78 def st(self, addr, v, width=8):
79 staddr = addr
80 remainder = addr & (self.bytes_per_word - 1)
81 addr = addr >> self.word_log2
82 print("Writing 0x{:x} to ST 0x{:x} memaddr 0x{:x}/{:x}".format(v,
83 staddr, addr, remainder))
84 assert remainder & (width - 1) == 0, "Unaligned access unsupported!"
85 if width != self.bytes_per_word:
86 if addr in self.mem:
87 val = self.mem[addr]
88 else:
89 val = 0
90 shifter, mask = self._get_shifter_mask(width, remainder)
91 val &= ~(mask << shifter)
92 val |= v << shifter
93 self.mem[addr] = val
94 else:
95 self.mem[addr] = v
96 print("mem @ 0x{:x}: 0x{:x}".format(addr, self.mem[addr]))
97
98 def __call__(self, addr, sz):
99 val = self.ld(addr.value, sz)
100 print ("memread", addr, sz, val)
101 return SelectableInt(val, sz*8)
102
103 def memassign(self, addr, sz, val):
104 print ("memassign", addr, sz, val)
105 self.st(addr.value, val.value, sz)
106
107
108 class GPR(dict):
109 def __init__(self, decoder, regfile):
110 dict.__init__(self)
111 self.sd = decoder
112 for i in range(32):
113 self[i] = SelectableInt(regfile[i], 64)
114
115 def __call__(self, ridx):
116 return self[ridx]
117
118 def set_form(self, form):
119 self.form = form
120
121 def getz(self, rnum):
122 #rnum = rnum.value # only SelectableInt allowed
123 print("GPR getzero", rnum)
124 if rnum == 0:
125 return SelectableInt(0, 64)
126 return self[rnum]
127
128 def _get_regnum(self, attr):
129 getform = self.sd.sigforms[self.form]
130 rnum = getattr(getform, attr)
131 return rnum
132
133 def ___getitem__(self, attr):
134 print("GPR getitem", attr)
135 rnum = self._get_regnum(attr)
136 return self.regfile[rnum]
137
138 def dump(self):
139 for i in range(0, len(self), 8):
140 s = []
141 for j in range(8):
142 s.append("%08x" % self[i+j].value)
143 s = ' '.join(s)
144 print("reg", "%2d" % i, s)
145
146 class PC:
147 def __init__(self, pc_init=0):
148 self.CIA = SelectableInt(pc_init, 64)
149 self.NIA = self.CIA + SelectableInt(4, 64)
150
151 def update(self, namespace):
152 self.CIA = namespace['NIA'].narrow(64)
153 self.NIA = self.CIA + SelectableInt(4, 64)
154 namespace['CIA'] = self.CIA
155 namespace['NIA'] = self.NIA
156
157
158 class SPR(dict):
159 def __init__(self, dec2, initial_sprs={}):
160 self.sd = dec2
161 dict.__init__(self)
162 self.update(initial_sprs)
163
164 def __getitem__(self, key):
165 # if key in special_sprs get the special spr, otherwise return key
166 if isinstance(key, SelectableInt):
167 key = key.value
168 key = special_sprs.get(key, key)
169 if key in self:
170 return dict.__getitem__(self, key)
171 else:
172 info = spr_dict[key]
173 dict.__setitem__(self, key, SelectableInt(0, info.length))
174 return dict.__getitem__(self, key)
175
176 def __setitem__(self, key, value):
177 if isinstance(key, SelectableInt):
178 key = key.value
179 key = special_sprs.get(key, key)
180 dict.__setitem__(self, key, value)
181
182 def __call__(self, ridx):
183 return self[ridx]
184
185
186
187 class ISACaller:
188 # decoder2 - an instance of power_decoder2
189 # regfile - a list of initial values for the registers
190 def __init__(self, decoder2, regfile, initial_sprs=None, initial_cr=0,
191 initial_mem=None, initial_msr=0):
192 if initial_sprs is None:
193 initial_sprs = {}
194 if initial_mem is None:
195 initial_mem = {}
196 self.gpr = GPR(decoder2, regfile)
197 self.mem = Mem(bytes_per_word=8, initial_mem=initial_mem)
198 self.pc = PC()
199 self.spr = SPR(decoder2, initial_sprs)
200 self.msr = SelectableInt(initial_msr, 64) # underlying reg
201 # TODO, needed here:
202 # FPR (same as GPR except for FP nums)
203 # 4.2.2 p124 FPSCR (definitely "separate" - not in SPR)
204 # note that mffs, mcrfs, mtfsf "manage" this FPSCR
205 # 2.3.1 CR (and sub-fields CR0..CR6 - CR0 SO comes from XER.SO)
206 # note that mfocrf, mfcr, mtcr, mtocrf, mcrxrx "manage" CRs
207 # -- Done
208 # 2.3.2 LR (actually SPR #8) -- Done
209 # 2.3.3 CTR (actually SPR #9) -- Done
210 # 2.3.4 TAR (actually SPR #815)
211 # 3.2.2 p45 XER (actually SPR #1) -- Done
212 # 3.2.3 p46 p232 VRSAVE (actually SPR #256)
213
214 # create CR then allow portions of it to be "selectable" (below)
215 self._cr = SelectableInt(initial_cr, 64) # underlying reg
216 self.cr = FieldSelectableInt(self._cr, list(range(32,64)))
217
218 # "undefined", just set to variable-bit-width int (use exts "max")
219 self.undefined = SelectableInt(0, 256) # TODO, not hard-code 256!
220
221 self.namespace = {'GPR': self.gpr,
222 'MEM': self.mem,
223 'SPR': self.spr,
224 'memassign': self.memassign,
225 'NIA': self.pc.NIA,
226 'CIA': self.pc.CIA,
227 'CR': self.cr,
228 'MSR': self.msr,
229 'undefined': self.undefined,
230 'mode_is_64bit': True,
231 'SO': XER_bits['SO']
232 }
233
234 # field-selectable versions of Condition Register TODO check bitranges?
235 self.crl = []
236 for i in range(8):
237 bits = tuple(range(i*4, (i+1)*4))# errr... maybe?
238 _cr = FieldSelectableInt(self.cr, bits)
239 self.crl.append(_cr)
240 self.namespace["CR%d" % i] = _cr
241
242 self.decoder = decoder2.dec
243 self.dec2 = decoder2
244
245 def TRAP(self, trap_addr=0x700):
246 print ("TRAP: TODO")
247 # store CIA(+4?) in SRR0, set NIA to 0x700
248 # store MSR in SRR1, set MSR to um errr something, have to check spec
249
250 def memassign(self, ea, sz, val):
251 self.mem.memassign(ea, sz, val)
252
253 def prep_namespace(self, formname, op_fields):
254 # TODO: get field names from form in decoder*1* (not decoder2)
255 # decoder2 is hand-created, and decoder1.sigform is auto-generated
256 # from spec
257 # then "yield" fields only from op_fields rather than hard-coded
258 # list, here.
259 fields = self.decoder.sigforms[formname]
260 for name in op_fields:
261 if name == 'spr':
262 sig = getattr(fields, name.upper())
263 else:
264 sig = getattr(fields, name)
265 val = yield sig
266 if name in ['BF', 'BFA']:
267 self.namespace[name] = val
268 else:
269 self.namespace[name] = SelectableInt(val, sig.width)
270
271 self.namespace['XER'] = self.spr['XER']
272 self.namespace['CA'] = self.spr['XER'][XER_bits['CA']].value
273 self.namespace['CA32'] = self.spr['XER'][XER_bits['CA32']].value
274
275 def handle_carry_(self, inputs, outputs, already_done):
276 inv_a = yield self.dec2.e.invert_a
277 if inv_a:
278 inputs[0] = ~inputs[0]
279
280 imm_ok = yield self.dec2.e.imm_data.ok
281 if imm_ok:
282 imm = yield self.dec2.e.imm_data.data
283 inputs.append(SelectableInt(imm, 64))
284 assert len(outputs) >= 1
285 output = outputs[0]
286 gts = [(x > output) for x in inputs]
287 print(gts)
288 cy = 1 if any(gts) else 0
289 if not (1 & already_done):
290 self.spr['XER'][XER_bits['CA']] = cy
291
292 print ("inputs", inputs)
293 # 32 bit carry
294 gts = [(x[32:64] > output[32:64]) == SelectableInt(1, 1)
295 for x in inputs]
296 cy32 = 1 if any(gts) else 0
297 if not (2 & already_done):
298 self.spr['XER'][XER_bits['CA32']] = cy32
299
300 def handle_overflow(self, inputs, outputs):
301 inv_a = yield self.dec2.e.invert_a
302 if inv_a:
303 inputs[0] = ~inputs[0]
304
305 imm_ok = yield self.dec2.e.imm_data.ok
306 if imm_ok:
307 imm = yield self.dec2.e.imm_data.data
308 inputs.append(SelectableInt(imm, 64))
309 assert len(outputs) >= 1
310 if len(inputs) >= 2:
311 output = outputs[0]
312
313 # OV (64-bit)
314 input_sgn = [exts(x.value, x.bits) < 0 for x in inputs]
315 output_sgn = exts(output.value, output.bits) < 0
316 ov = 1 if input_sgn[0] == input_sgn[1] and \
317 output_sgn != input_sgn[0] else 0
318
319 # OV (32-bit)
320 input32_sgn = [exts(x.value, 32) < 0 for x in inputs]
321 output32_sgn = exts(output.value, 32) < 0
322 ov32 = 1 if input32_sgn[0] == input32_sgn[1] and \
323 output32_sgn != input32_sgn[0] else 0
324
325 self.spr['XER'][XER_bits['OV']] = ov
326 self.spr['XER'][XER_bits['OV32']] = ov32
327 so = self.spr['XER'][XER_bits['SO']]
328 so = so | ov
329 self.spr['XER'][XER_bits['SO']] = so
330
331
332
333 def handle_comparison(self, outputs):
334 out = outputs[0]
335 out = exts(out.value, out.bits)
336 zero = SelectableInt(out == 0, 1)
337 positive = SelectableInt(out > 0, 1)
338 negative = SelectableInt(out < 0, 1)
339 SO = self.spr['XER'][XER_bits['SO']]
340 cr_field = selectconcat(negative, positive, zero, SO)
341 self.crl[0].eq(cr_field)
342
343 def set_pc(self, pc_val):
344 self.namespace['NIA'] = SelectableInt(pc_val, 64)
345 self.pc.update(self.namespace)
346
347
348 def call(self, name):
349 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
350 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
351 info = self.instrs[name]
352 yield from self.prep_namespace(info.form, info.op_fields)
353
354 # preserve order of register names
355 input_names = create_args(list(info.read_regs) + list(info.uninit_regs))
356 print(input_names)
357
358 # main registers (RT, RA ...)
359 inputs = []
360 for name in input_names:
361 regnum = yield getattr(self.decoder, name)
362 regname = "_" + name
363 self.namespace[regname] = regnum
364 print('reading reg %d' % regnum)
365 inputs.append(self.gpr(regnum))
366
367 # "special" registers
368 for special in info.special_regs:
369 if special in special_sprs:
370 inputs.append(self.spr[special])
371 else:
372 inputs.append(self.namespace[special])
373
374 print(inputs)
375 results = info.func(self, *inputs)
376 print(results)
377
378 # detect if CA/CA32 already in outputs (sra*, basically)
379 already_done = 0
380 if info.write_regs:
381 output_names = create_args(info.write_regs)
382 for name in output_names:
383 if name == 'CA':
384 already_done |= 1
385 if name == 'CA32':
386 already_done |= 2
387
388 print ("carry already done?", bin(already_done))
389 carry_en = yield self.dec2.e.output_carry
390 if carry_en:
391 yield from self.handle_carry_(inputs, results, already_done)
392 ov_en = yield self.dec2.e.oe.oe
393 ov_ok = yield self.dec2.e.oe.ok
394 if ov_en & ov_ok:
395 yield from self.handle_overflow(inputs, results)
396 rc_en = yield self.dec2.e.rc.data
397 if rc_en:
398 self.handle_comparison(results)
399
400 # any modified return results?
401 if info.write_regs:
402 for name, output in zip(output_names, results):
403 if isinstance(output, int):
404 output = SelectableInt(output, 256)
405 if name in ['CA', 'CA32']:
406 if carry_en:
407 print ("writing %s to XER" % name, output)
408 self.spr['XER'][XER_bits[name]] = output.value
409 else:
410 print ("NOT writing %s to XER" % name, output)
411 elif name in info.special_regs:
412 print('writing special %s' % name, output, special_sprs)
413 if name in special_sprs:
414 self.spr[name] = output
415 else:
416 self.namespace[name].eq(output)
417 else:
418 regnum = yield getattr(self.decoder, name)
419 print('writing reg %d %s' % (regnum, str(output)))
420 if output.bits > 64:
421 output = SelectableInt(output.value, 64)
422 self.gpr[regnum] = output
423
424 # update program counter
425 self.pc.update(self.namespace)
426
427
428 def inject():
429 """Decorator factory.
430
431 this decorator will "inject" variables into the function's namespace,
432 from the *dictionary* in self.namespace. it therefore becomes possible
433 to make it look like a whole stack of variables which would otherwise
434 need "self." inserted in front of them (*and* for those variables to be
435 added to the instance) "appear" in the function.
436
437 "self.namespace['SI']" for example becomes accessible as just "SI" but
438 *only* inside the function, when decorated.
439 """
440 def variable_injector(func):
441 @wraps(func)
442 def decorator(*args, **kwargs):
443 try:
444 func_globals = func.__globals__ # Python 2.6+
445 except AttributeError:
446 func_globals = func.func_globals # Earlier versions.
447
448 context = args[0].namespace # variables to be injected
449 saved_values = func_globals.copy() # Shallow copy of dict.
450 func_globals.update(context)
451 result = func(*args, **kwargs)
452 args[0].namespace = func_globals
453 #exec (func.__code__, func_globals)
454
455 #finally:
456 # func_globals = saved_values # Undo changes.
457
458 return result
459
460 return decorator
461
462 return variable_injector
463