resolve spr names in ISACaller
[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, spr_byname, XER_bits,
13 insns, InternalOp)
14 from soc.decoder.helpers import exts, trunc_div, trunc_rem
15 from collections import namedtuple
16 import math
17 import sys
18
19 instruction_info = namedtuple('instruction_info',
20 'func read_regs uninit_regs write_regs ' + \
21 'special_regs op_fields form asmregs')
22
23 special_sprs = {
24 'LR': 8,
25 'CTR': 9,
26 'TAR': 815,
27 'XER': 1,
28 'VRSAVE': 256}
29
30
31 def swap_order(x, nbytes):
32 x = x.to_bytes(nbytes, byteorder='little')
33 x = int.from_bytes(x, byteorder='big', signed=False)
34 return x
35
36
37 def create_args(reglist, extra=None):
38 args = OrderedSet()
39 for reg in reglist:
40 args.add(reg)
41 args = list(args)
42 if extra:
43 args = [extra] + args
44 return args
45
46
47 class Mem:
48
49 def __init__(self, row_bytes=8, initial_mem=None):
50 self.mem = {}
51 self.bytes_per_word = row_bytes
52 self.word_log2 = math.ceil(math.log2(row_bytes))
53 print ("Sim-Mem", initial_mem, self.bytes_per_word, self.word_log2)
54 if not initial_mem:
55 return
56
57 # different types of memory data structures recognised (for convenience)
58 if isinstance(initial_mem, list):
59 initial_mem = (0, initial_mem)
60 if isinstance(initial_mem, tuple):
61 startaddr, mem = initial_mem
62 initial_mem = {}
63 for i, val in enumerate(mem):
64 initial_mem[startaddr + row_bytes*i] = (val, row_bytes)
65
66 for addr, (val, width) in initial_mem.items():
67 #val = swap_order(val, width)
68 self.st(addr, val, width, swap=False)
69
70 def _get_shifter_mask(self, wid, remainder):
71 shifter = ((self.bytes_per_word - wid) - remainder) * \
72 8 # bits per byte
73 # XXX https://bugs.libre-soc.org/show_bug.cgi?id=377
74 # BE/LE mode?
75 shifter = remainder * 8
76 mask = (1 << (wid * 8)) - 1
77 print ("width,rem,shift,mask", wid, remainder, hex(shifter), hex(mask))
78 return shifter, mask
79
80 # TODO: Implement ld/st of lesser width
81 def ld(self, address, width=8, swap=True, check_in_mem=False):
82 print("ld from addr 0x{:x} width {:d}".format(address, width))
83 remainder = address & (self.bytes_per_word - 1)
84 address = address >> self.word_log2
85 assert remainder & (width - 1) == 0, "Unaligned access unsupported!"
86 if address in self.mem:
87 val = self.mem[address]
88 elif check_in_mem:
89 return None
90 else:
91 val = 0
92 print("mem @ 0x{:x} rem {:d} : 0x{:x}".format(address, remainder, val))
93
94 if width != self.bytes_per_word:
95 shifter, mask = self._get_shifter_mask(width, remainder)
96 print ("masking", hex(val), hex(mask<<shifter), shifter)
97 val = val & (mask << shifter)
98 val >>= shifter
99 if swap:
100 val = swap_order(val, width)
101 print("Read 0x{:x} from addr 0x{:x}".format(val, address))
102 return val
103
104 def st(self, addr, v, width=8, swap=True):
105 staddr = addr
106 remainder = addr & (self.bytes_per_word - 1)
107 addr = addr >> self.word_log2
108 print("Writing 0x{:x} to ST 0x{:x} memaddr 0x{:x}/{:x}".format(v,
109 staddr, addr, remainder, swap))
110 assert remainder & (width - 1) == 0, "Unaligned access unsupported!"
111 if swap:
112 v = swap_order(v, width)
113 if width != self.bytes_per_word:
114 if addr in self.mem:
115 val = self.mem[addr]
116 else:
117 val = 0
118 shifter, mask = self._get_shifter_mask(width, remainder)
119 val &= ~(mask << shifter)
120 val |= v << shifter
121 self.mem[addr] = val
122 else:
123 self.mem[addr] = v
124 print("mem @ 0x{:x}: 0x{:x}".format(addr, self.mem[addr]))
125
126 def __call__(self, addr, sz):
127 val = self.ld(addr.value, sz)
128 print ("memread", addr, sz, val)
129 return SelectableInt(val, sz*8)
130
131 def memassign(self, addr, sz, val):
132 print ("memassign", addr, sz, val)
133 self.st(addr.value, val.value, sz)
134
135
136 class GPR(dict):
137 def __init__(self, decoder, regfile):
138 dict.__init__(self)
139 self.sd = decoder
140 for i in range(32):
141 self[i] = SelectableInt(regfile[i], 64)
142
143 def __call__(self, ridx):
144 return self[ridx]
145
146 def set_form(self, form):
147 self.form = form
148
149 def getz(self, rnum):
150 #rnum = rnum.value # only SelectableInt allowed
151 print("GPR getzero", rnum)
152 if rnum == 0:
153 return SelectableInt(0, 64)
154 return self[rnum]
155
156 def _get_regnum(self, attr):
157 getform = self.sd.sigforms[self.form]
158 rnum = getattr(getform, attr)
159 return rnum
160
161 def ___getitem__(self, attr):
162 print("GPR getitem", attr)
163 rnum = self._get_regnum(attr)
164 return self.regfile[rnum]
165
166 def dump(self):
167 for i in range(0, len(self), 8):
168 s = []
169 for j in range(8):
170 s.append("%08x" % self[i+j].value)
171 s = ' '.join(s)
172 print("reg", "%2d" % i, s)
173
174 class PC:
175 def __init__(self, pc_init=0):
176 self.CIA = SelectableInt(pc_init, 64)
177 self.NIA = self.CIA + SelectableInt(4, 64)
178
179 def update(self, namespace):
180 self.CIA = namespace['NIA'].narrow(64)
181 self.NIA = self.CIA + SelectableInt(4, 64)
182 namespace['CIA'] = self.CIA
183 namespace['NIA'] = self.NIA
184
185
186 class SPR(dict):
187 def __init__(self, dec2, initial_sprs={}):
188 self.sd = dec2
189 dict.__init__(self)
190 for key, v in initial_sprs.items():
191 if isinstance(key, SelectableInt):
192 key = key.value
193 key = special_sprs.get(key, key)
194 if isinstance(key, int):
195 info = spr_dict[key]
196 else:
197 info = spr_byname[key]
198 if not isinstance(v, SelectableInt):
199 v = SelectableInt(v, info.length)
200 self[key] = v
201
202 def __getitem__(self, key):
203 print ("get spr", key)
204 print ("dict", self.items())
205 # if key in special_sprs get the special spr, otherwise return key
206 if isinstance(key, SelectableInt):
207 key = key.value
208 if isinstance(key, int):
209 key = spr_dict[key].SPR
210 key = special_sprs.get(key, key)
211 if key in self:
212 res = dict.__getitem__(self, key)
213 else:
214 info = spr_dict[key]
215 dict.__setitem__(self, key, SelectableInt(0, info.length))
216 res = dict.__getitem__(self, key)
217 print ("spr returning", key, res)
218 return res
219
220 def __setitem__(self, key, value):
221 if isinstance(key, SelectableInt):
222 key = key.value
223 if isinstance(key, int):
224 key = spr_dict[key].SPR
225 print ("spr key", key)
226 key = special_sprs.get(key, key)
227 print ("setting spr", key, value)
228 dict.__setitem__(self, key, value)
229
230 def __call__(self, ridx):
231 return self[ridx]
232
233
234 class ISACaller:
235 # decoder2 - an instance of power_decoder2
236 # regfile - a list of initial values for the registers
237 # initial_{etc} - initial values for SPRs, Condition Register, Mem, MSR
238 # respect_pc - tracks the program counter. requires initial_insns
239 def __init__(self, decoder2, regfile, initial_sprs=None, initial_cr=0,
240 initial_mem=None, initial_msr=0,
241 initial_insns=None, respect_pc=False,
242 disassembly=None):
243
244 self.respect_pc = respect_pc
245 if initial_sprs is None:
246 initial_sprs = {}
247 if initial_mem is None:
248 initial_mem = {}
249 if initial_insns is None:
250 initial_insns = {}
251 assert self.respect_pc == False, "instructions required to honor pc"
252
253 print ("ISACaller insns", respect_pc, initial_insns, disassembly)
254
255 # "fake program counter" mode (for unit testing)
256 self.fake_pc = 0
257 if not respect_pc:
258 if isinstance(initial_mem, tuple):
259 self.fake_pc = initial_mem[0]
260
261 # disassembly: we need this for now (not given from the decoder)
262 self.disassembly = {}
263 if disassembly:
264 for i, code in enumerate(disassembly):
265 self.disassembly[i*4 + self.fake_pc] = code
266
267 # set up registers, instruction memory, data memory, PC, SPRs, MSR
268 self.gpr = GPR(decoder2, regfile)
269 self.mem = Mem(row_bytes=8, initial_mem=initial_mem)
270 self.imem = Mem(row_bytes=4, initial_mem=initial_insns)
271 self.pc = PC()
272 self.spr = SPR(decoder2, initial_sprs)
273 self.msr = SelectableInt(initial_msr, 64) # underlying reg
274
275 # TODO, needed here:
276 # FPR (same as GPR except for FP nums)
277 # 4.2.2 p124 FPSCR (definitely "separate" - not in SPR)
278 # note that mffs, mcrfs, mtfsf "manage" this FPSCR
279 # 2.3.1 CR (and sub-fields CR0..CR6 - CR0 SO comes from XER.SO)
280 # note that mfocrf, mfcr, mtcr, mtocrf, mcrxrx "manage" CRs
281 # -- Done
282 # 2.3.2 LR (actually SPR #8) -- Done
283 # 2.3.3 CTR (actually SPR #9) -- Done
284 # 2.3.4 TAR (actually SPR #815)
285 # 3.2.2 p45 XER (actually SPR #1) -- Done
286 # 3.2.3 p46 p232 VRSAVE (actually SPR #256)
287
288 # create CR then allow portions of it to be "selectable" (below)
289 self._cr = SelectableInt(initial_cr, 64) # underlying reg
290 self.cr = FieldSelectableInt(self._cr, list(range(32,64)))
291
292 # "undefined", just set to variable-bit-width int (use exts "max")
293 self.undefined = SelectableInt(0, 256) # TODO, not hard-code 256!
294
295 self.namespace = {}
296 self.namespace.update(self.spr)
297 self.namespace.update({'GPR': self.gpr,
298 'MEM': self.mem,
299 'SPR': self.spr,
300 'memassign': self.memassign,
301 'NIA': self.pc.NIA,
302 'CIA': self.pc.CIA,
303 'CR': self.cr,
304 'MSR': self.msr,
305 'undefined': self.undefined,
306 'mode_is_64bit': True,
307 'SO': XER_bits['SO']
308 })
309
310
311 # field-selectable versions of Condition Register TODO check bitranges?
312 self.crl = []
313 for i in range(8):
314 bits = tuple(range(i*4, (i+1)*4))# errr... maybe?
315 _cr = FieldSelectableInt(self.cr, bits)
316 self.crl.append(_cr)
317 self.namespace["CR%d" % i] = _cr
318
319 self.decoder = decoder2.dec
320 self.dec2 = decoder2
321
322 def TRAP(self, trap_addr=0x700):
323 print ("TRAP: TODO")
324 #self.namespace['NIA'] = trap_addr
325 #self.SRR0 = self.namespace['CIA'] + 4
326 #self.SRR1 = self.namespace['MSR']
327 #self.namespace['MSR'][45] = 1
328 # store CIA(+4?) in SRR0, set NIA to 0x700
329 # store MSR in SRR1, set MSR to um errr something, have to check spec
330
331 def memassign(self, ea, sz, val):
332 self.mem.memassign(ea, sz, val)
333
334 def prep_namespace(self, formname, op_fields):
335 # TODO: get field names from form in decoder*1* (not decoder2)
336 # decoder2 is hand-created, and decoder1.sigform is auto-generated
337 # from spec
338 # then "yield" fields only from op_fields rather than hard-coded
339 # list, here.
340 fields = self.decoder.sigforms[formname]
341 for name in op_fields:
342 if name == 'spr':
343 sig = getattr(fields, name.upper())
344 else:
345 sig = getattr(fields, name)
346 val = yield sig
347 if name in ['BF', 'BFA']:
348 self.namespace[name] = val
349 else:
350 self.namespace[name] = SelectableInt(val, sig.width)
351
352 self.namespace['XER'] = self.spr['XER']
353 self.namespace['CA'] = self.spr['XER'][XER_bits['CA']].value
354 self.namespace['CA32'] = self.spr['XER'][XER_bits['CA32']].value
355
356 def handle_carry_(self, inputs, outputs, already_done):
357 inv_a = yield self.dec2.e.invert_a
358 if inv_a:
359 inputs[0] = ~inputs[0]
360
361 imm_ok = yield self.dec2.e.imm_data.ok
362 if imm_ok:
363 imm = yield self.dec2.e.imm_data.data
364 inputs.append(SelectableInt(imm, 64))
365 assert len(outputs) >= 1
366 print ("outputs", repr(outputs))
367 if isinstance(outputs, list) or isinstance(outputs, tuple):
368 output = outputs[0]
369 else:
370 output = outputs
371 gts = []
372 for x in inputs:
373 print ("gt input", x, output)
374 gt = (x > output)
375 gts.append(gt)
376 print(gts)
377 cy = 1 if any(gts) else 0
378 if not (1 & already_done):
379 self.spr['XER'][XER_bits['CA']] = cy
380
381 print ("inputs", inputs)
382 # 32 bit carry
383 gts = []
384 for x in inputs:
385 print ("input", x, output)
386 gt = (x[32:64] > output[32:64]) == SelectableInt(1, 1)
387 gts.append(gt)
388 cy32 = 1 if any(gts) else 0
389 if not (2 & already_done):
390 self.spr['XER'][XER_bits['CA32']] = cy32
391
392 def handle_overflow(self, inputs, outputs, div_overflow):
393 inv_a = yield self.dec2.e.invert_a
394 if inv_a:
395 inputs[0] = ~inputs[0]
396
397 imm_ok = yield self.dec2.e.imm_data.ok
398 if imm_ok:
399 imm = yield self.dec2.e.imm_data.data
400 inputs.append(SelectableInt(imm, 64))
401 assert len(outputs) >= 1
402 print ("handle_overflow", inputs, outputs, div_overflow)
403 if len(inputs) < 2 and div_overflow != 1:
404 return
405
406 # div overflow is different: it's returned by the pseudo-code
407 # because it's more complex than can be done by analysing the output
408 if div_overflow == 1:
409 ov, ov32 = 1, 1
410 # arithmetic overflow can be done by analysing the input and output
411 elif len(inputs) >= 2:
412 output = outputs[0]
413
414 # OV (64-bit)
415 input_sgn = [exts(x.value, x.bits) < 0 for x in inputs]
416 output_sgn = exts(output.value, output.bits) < 0
417 ov = 1 if input_sgn[0] == input_sgn[1] and \
418 output_sgn != input_sgn[0] else 0
419
420 # OV (32-bit)
421 input32_sgn = [exts(x.value, 32) < 0 for x in inputs]
422 output32_sgn = exts(output.value, 32) < 0
423 ov32 = 1 if input32_sgn[0] == input32_sgn[1] and \
424 output32_sgn != input32_sgn[0] else 0
425
426 self.spr['XER'][XER_bits['OV']] = ov
427 self.spr['XER'][XER_bits['OV32']] = ov32
428 so = self.spr['XER'][XER_bits['SO']]
429 so = so | ov
430 self.spr['XER'][XER_bits['SO']] = so
431
432 def handle_comparison(self, outputs):
433 out = outputs[0]
434 out = exts(out.value, out.bits)
435 zero = SelectableInt(out == 0, 1)
436 positive = SelectableInt(out > 0, 1)
437 negative = SelectableInt(out < 0, 1)
438 SO = self.spr['XER'][XER_bits['SO']]
439 cr_field = selectconcat(negative, positive, zero, SO)
440 self.crl[0].eq(cr_field)
441
442 def set_pc(self, pc_val):
443 self.namespace['NIA'] = SelectableInt(pc_val, 64)
444 self.pc.update(self.namespace)
445
446 def setup_one(self):
447 """set up one instruction
448 """
449 if self.respect_pc:
450 pc = self.pc.CIA.value
451 else:
452 pc = self.fake_pc
453 self._pc = pc
454 ins = self.imem.ld(pc, 4, False, True)
455 if ins is None:
456 raise KeyError("no instruction at 0x%x" % pc)
457 print("setup: 0x%x 0x%x %s" % (pc, ins & 0xffffffff, bin(ins)))
458 print ("NIA, CIA", self.pc.CIA.value, self.pc.NIA.value)
459
460 yield self.dec2.dec.raw_opcode_in.eq(ins & 0xffffffff)
461 yield self.dec2.dec.bigendian.eq(0) # little / big?
462
463 def execute_one(self):
464 """execute one instruction
465 """
466 # get the disassembly code for this instruction
467 code = self.disassembly[self._pc]
468 print("sim-execute", hex(self._pc), code)
469 opname = code.split(' ')[0]
470 yield from self.call(opname)
471
472 if not self.respect_pc:
473 self.fake_pc += 4
474 print ("NIA, CIA", self.pc.CIA.value, self.pc.NIA.value)
475
476 def get_assembly_name(self):
477 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
478 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
479 asmcode = yield self.dec2.dec.op.asmcode
480 asmop = insns.get(asmcode, None)
481
482 # sigh reconstruct the assembly instruction name
483 ov_en = yield self.dec2.e.oe.oe
484 ov_ok = yield self.dec2.e.oe.ok
485 if ov_en & ov_ok:
486 asmop += "."
487 lk = yield self.dec2.e.lk
488 if lk:
489 asmop += "l"
490 int_op = yield self.dec2.dec.op.internal_op
491 print ("int_op", int_op)
492 if int_op in [InternalOp.OP_B.value, InternalOp.OP_BC.value]:
493 AA = yield self.dec2.dec.fields.FormI.AA[0:-1]
494 print ("AA", AA)
495 if AA:
496 asmop += "a"
497 if int_op == InternalOp.OP_MFCR.value:
498 dec_insn = yield self.dec2.e.insn
499 if dec_insn & (1<<20) != 0: # sigh
500 asmop = 'mfocrf'
501 else:
502 asmop = 'mfcr'
503 # XXX TODO: for whatever weird reason this doesn't work
504 # https://bugs.libre-soc.org/show_bug.cgi?id=390
505 if int_op == InternalOp.OP_MTCRF.value:
506 dec_insn = yield self.dec2.e.insn
507 if dec_insn & (1<<20) != 0: # sigh
508 asmop = 'mtocrf'
509 else:
510 asmop = 'mtcrf'
511 return asmop
512
513 def call(self, name):
514 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
515 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
516 asmop = yield from self.get_assembly_name()
517 print ("call", name, asmop)
518 if name not in ['mtcrf', 'mtocrf']:
519 assert name == asmop, "name %s != %s" % (name, asmop)
520
521 info = self.instrs[name]
522 yield from self.prep_namespace(info.form, info.op_fields)
523
524 # preserve order of register names
525 input_names = create_args(list(info.read_regs) + list(info.uninit_regs))
526 print(input_names)
527
528 # main registers (RT, RA ...)
529 inputs = []
530 for name in input_names:
531 regnum = yield getattr(self.decoder, name)
532 regname = "_" + name
533 self.namespace[regname] = regnum
534 print('reading reg %d' % regnum)
535 inputs.append(self.gpr(regnum))
536
537 # "special" registers
538 for special in info.special_regs:
539 if special in special_sprs:
540 inputs.append(self.spr[special])
541 else:
542 inputs.append(self.namespace[special])
543
544 print(inputs)
545 results = info.func(self, *inputs)
546 print(results)
547
548 # detect if CA/CA32 already in outputs (sra*, basically)
549 already_done = 0
550 if info.write_regs:
551 output_names = create_args(info.write_regs)
552 for name in output_names:
553 if name == 'CA':
554 already_done |= 1
555 if name == 'CA32':
556 already_done |= 2
557
558 print ("carry already done?", bin(already_done))
559 carry_en = yield self.dec2.e.output_carry
560 if carry_en:
561 yield from self.handle_carry_(inputs, results, already_done)
562
563 # detect if overflow was in return result
564 overflow = None
565 if info.write_regs:
566 for name, output in zip(output_names, results):
567 if name == 'overflow':
568 overflow = output
569
570 ov_en = yield self.dec2.e.oe.oe
571 ov_ok = yield self.dec2.e.oe.ok
572 print ("internal overflow", overflow)
573 if ov_en & ov_ok:
574 yield from self.handle_overflow(inputs, results, overflow)
575
576 rc_en = yield self.dec2.e.rc.data
577 if rc_en:
578 self.handle_comparison(results)
579
580 # any modified return results?
581 if info.write_regs:
582 for name, output in zip(output_names, results):
583 if name == 'overflow': # ignore, done already (above)
584 continue
585 if isinstance(output, int):
586 output = SelectableInt(output, 256)
587 if name in ['CA', 'CA32']:
588 if carry_en:
589 print ("writing %s to XER" % name, output)
590 self.spr['XER'][XER_bits[name]] = output.value
591 else:
592 print ("NOT writing %s to XER" % name, output)
593 elif name in info.special_regs:
594 print('writing special %s' % name, output, special_sprs)
595 if name in special_sprs:
596 self.spr[name] = output
597 else:
598 self.namespace[name].eq(output)
599 if name == 'MSR':
600 print ('msr written', hex(self.msr.value))
601 else:
602 regnum = yield getattr(self.decoder, name)
603 print('writing reg %d %s' % (regnum, str(output)))
604 if output.bits > 64:
605 output = SelectableInt(output.value, 64)
606 self.gpr[regnum] = output
607
608 # update program counter
609 self.pc.update(self.namespace)
610
611
612 def inject():
613 """Decorator factory.
614
615 this decorator will "inject" variables into the function's namespace,
616 from the *dictionary* in self.namespace. it therefore becomes possible
617 to make it look like a whole stack of variables which would otherwise
618 need "self." inserted in front of them (*and* for those variables to be
619 added to the instance) "appear" in the function.
620
621 "self.namespace['SI']" for example becomes accessible as just "SI" but
622 *only* inside the function, when decorated.
623 """
624 def variable_injector(func):
625 @wraps(func)
626 def decorator(*args, **kwargs):
627 try:
628 func_globals = func.__globals__ # Python 2.6+
629 except AttributeError:
630 func_globals = func.func_globals # Earlier versions.
631
632 context = args[0].namespace # variables to be injected
633 saved_values = func_globals.copy() # Shallow copy of dict.
634 func_globals.update(context)
635 result = func(*args, **kwargs)
636 args[0].namespace = func_globals
637 #exec (func.__code__, func_globals)
638
639 #finally:
640 # func_globals = saved_values # Undo changes.
641
642 return result
643
644 return decorator
645
646 return variable_injector
647