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