273ffd17b9814047517559a0174c6c1c8bf9cb23
1 """core of the python-based POWER9 simulator
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.
8 from functools
import wraps
9 from soc
.decoder
.orderedset
import OrderedSet
10 from soc
.decoder
.selectable_int
import (FieldSelectableInt
, SelectableInt
,
12 from soc
.decoder
.power_enums
import (spr_dict
, spr_byname
, XER_bits
,
14 from soc
.decoder
.helpers
import exts
, trunc_div
, trunc_rem
15 from soc
.consts
import PI
, MSR
17 from collections
import namedtuple
21 instruction_info
= namedtuple('instruction_info',
22 'func read_regs uninit_regs write_regs ' + \
23 'special_regs op_fields form asmregs')
33 def swap_order(x
, nbytes
):
34 x
= x
.to_bytes(nbytes
, byteorder
='little')
35 x
= int.from_bytes(x
, byteorder
='big', signed
=False)
39 def create_args(reglist
, extra
=None):
51 def __init__(self
, row_bytes
=8, initial_mem
=None):
53 self
.bytes_per_word
= row_bytes
54 self
.word_log2
= math
.ceil(math
.log2(row_bytes
))
55 print ("Sim-Mem", initial_mem
, self
.bytes_per_word
, self
.word_log2
)
59 # different types of memory data structures recognised (for convenience)
60 if isinstance(initial_mem
, list):
61 initial_mem
= (0, initial_mem
)
62 if isinstance(initial_mem
, tuple):
63 startaddr
, mem
= initial_mem
65 for i
, val
in enumerate(mem
):
66 initial_mem
[startaddr
+ row_bytes
*i
] = (val
, row_bytes
)
68 for addr
, (val
, width
) in initial_mem
.items():
69 #val = swap_order(val, width)
70 self
.st(addr
, val
, width
, swap
=False)
72 def _get_shifter_mask(self
, wid
, remainder
):
73 shifter
= ((self
.bytes_per_word
- wid
) - remainder
) * \
75 # XXX https://bugs.libre-soc.org/show_bug.cgi?id=377
77 shifter
= remainder
* 8
78 mask
= (1 << (wid
* 8)) - 1
79 print ("width,rem,shift,mask", wid
, remainder
, hex(shifter
), hex(mask
))
82 # TODO: Implement ld/st of lesser width
83 def ld(self
, address
, width
=8, swap
=True, check_in_mem
=False):
84 print("ld from addr 0x{:x} width {:d}".format(address
, width
))
85 remainder
= address
& (self
.bytes_per_word
- 1)
86 address
= address
>> self
.word_log2
87 assert remainder
& (width
- 1) == 0, "Unaligned access unsupported!"
88 if address
in self
.mem
:
89 val
= self
.mem
[address
]
94 print("mem @ 0x{:x} rem {:d} : 0x{:x}".format(address
, remainder
, val
))
96 if width
!= self
.bytes_per_word
:
97 shifter
, mask
= self
._get
_shifter
_mask
(width
, remainder
)
98 print ("masking", hex(val
), hex(mask
<<shifter
), shifter
)
99 val
= val
& (mask
<< shifter
)
102 val
= swap_order(val
, width
)
103 print("Read 0x{:x} from addr 0x{:x}".format(val
, address
))
106 def st(self
, addr
, v
, width
=8, swap
=True):
108 remainder
= addr
& (self
.bytes_per_word
- 1)
109 addr
= addr
>> self
.word_log2
110 print("Writing 0x{:x} to ST 0x{:x} memaddr 0x{:x}/{:x}".format(v
,
111 staddr
, addr
, remainder
, swap
))
112 assert remainder
& (width
- 1) == 0, "Unaligned access unsupported!"
114 v
= swap_order(v
, width
)
115 if width
!= self
.bytes_per_word
:
120 shifter
, mask
= self
._get
_shifter
_mask
(width
, remainder
)
121 val
&= ~
(mask
<< shifter
)
126 print("mem @ 0x{:x}: 0x{:x}".format(addr
, self
.mem
[addr
]))
128 def __call__(self
, addr
, sz
):
129 val
= self
.ld(addr
.value
, sz
)
130 print ("memread", addr
, sz
, val
)
131 return SelectableInt(val
, sz
*8)
133 def memassign(self
, addr
, sz
, val
):
134 print ("memassign", addr
, sz
, val
)
135 self
.st(addr
.value
, val
.value
, sz
)
139 def __init__(self
, decoder
, regfile
):
143 self
[i
] = SelectableInt(regfile
[i
], 64)
145 def __call__(self
, ridx
):
148 def set_form(self
, form
):
151 def getz(self
, rnum
):
152 #rnum = rnum.value # only SelectableInt allowed
153 print("GPR getzero", rnum
)
155 return SelectableInt(0, 64)
158 def _get_regnum(self
, attr
):
159 getform
= self
.sd
.sigforms
[self
.form
]
160 rnum
= getattr(getform
, attr
)
163 def ___getitem__(self
, attr
):
164 print("GPR getitem", attr
)
165 rnum
= self
._get
_regnum
(attr
)
166 return self
.regfile
[rnum
]
169 for i
in range(0, len(self
), 8):
172 s
.append("%08x" % self
[i
+j
].value
)
174 print("reg", "%2d" % i
, s
)
177 def __init__(self
, pc_init
=0):
178 self
.CIA
= SelectableInt(pc_init
, 64)
179 self
.NIA
= self
.CIA
+ SelectableInt(4, 64)
181 def update(self
, namespace
):
182 self
.CIA
= namespace
['NIA'].narrow(64)
183 self
.NIA
= self
.CIA
+ SelectableInt(4, 64)
184 namespace
['CIA'] = self
.CIA
185 namespace
['NIA'] = self
.NIA
189 def __init__(self
, dec2
, initial_sprs
={}):
192 for key
, v
in initial_sprs
.items():
193 if isinstance(key
, SelectableInt
):
195 key
= special_sprs
.get(key
, key
)
196 if isinstance(key
, int):
199 info
= spr_byname
[key
]
200 if not isinstance(v
, SelectableInt
):
201 v
= SelectableInt(v
, info
.length
)
204 def __getitem__(self
, key
):
205 print ("get spr", key
)
206 print ("dict", self
.items())
207 # if key in special_sprs get the special spr, otherwise return key
208 if isinstance(key
, SelectableInt
):
210 if isinstance(key
, int):
211 key
= spr_dict
[key
].SPR
212 key
= special_sprs
.get(key
, key
)
214 res
= dict.__getitem
__(self
, key
)
216 if isinstance(key
, int):
219 info
= spr_byname
[key
]
220 dict.__setitem
__(self
, key
, SelectableInt(0, info
.length
))
221 res
= dict.__getitem
__(self
, key
)
222 print ("spr returning", key
, res
)
225 def __setitem__(self
, key
, value
):
226 if isinstance(key
, SelectableInt
):
228 if isinstance(key
, int):
229 key
= spr_dict
[key
].SPR
230 print ("spr key", key
)
231 key
= special_sprs
.get(key
, key
)
232 print ("setting spr", key
, value
)
233 dict.__setitem
__(self
, key
, value
)
235 def __call__(self
, ridx
):
240 # decoder2 - an instance of power_decoder2
241 # regfile - a list of initial values for the registers
242 # initial_{etc} - initial values for SPRs, Condition Register, Mem, MSR
243 # respect_pc - tracks the program counter. requires initial_insns
244 def __init__(self
, decoder2
, regfile
, initial_sprs
=None, initial_cr
=0,
245 initial_mem
=None, initial_msr
=0,
246 initial_insns
=None, respect_pc
=False,
249 self
.respect_pc
= respect_pc
250 if initial_sprs
is None:
252 if initial_mem
is None:
254 if initial_insns
is None:
256 assert self
.respect_pc
== False, "instructions required to honor pc"
258 print ("ISACaller insns", respect_pc
, initial_insns
, disassembly
)
260 # "fake program counter" mode (for unit testing)
263 if isinstance(initial_mem
, tuple):
264 self
.fake_pc
= initial_mem
[0]
266 # disassembly: we need this for now (not given from the decoder)
267 self
.disassembly
= {}
269 for i
, code
in enumerate(disassembly
):
270 self
.disassembly
[i
*4 + self
.fake_pc
] = code
272 # set up registers, instruction memory, data memory, PC, SPRs, MSR
273 self
.gpr
= GPR(decoder2
, regfile
)
274 self
.mem
= Mem(row_bytes
=8, initial_mem
=initial_mem
)
275 self
.imem
= Mem(row_bytes
=4, initial_mem
=initial_insns
)
277 self
.spr
= SPR(decoder2
, initial_sprs
)
278 self
.msr
= SelectableInt(initial_msr
, 64) # underlying reg
281 # FPR (same as GPR except for FP nums)
282 # 4.2.2 p124 FPSCR (definitely "separate" - not in SPR)
283 # note that mffs, mcrfs, mtfsf "manage" this FPSCR
284 # 2.3.1 CR (and sub-fields CR0..CR6 - CR0 SO comes from XER.SO)
285 # note that mfocrf, mfcr, mtcr, mtocrf, mcrxrx "manage" CRs
287 # 2.3.2 LR (actually SPR #8) -- Done
288 # 2.3.3 CTR (actually SPR #9) -- Done
289 # 2.3.4 TAR (actually SPR #815)
290 # 3.2.2 p45 XER (actually SPR #1) -- Done
291 # 3.2.3 p46 p232 VRSAVE (actually SPR #256)
293 # create CR then allow portions of it to be "selectable" (below)
294 self
._cr
= SelectableInt(initial_cr
, 64) # underlying reg
295 self
.cr
= FieldSelectableInt(self
._cr
, list(range(32,64)))
297 # "undefined", just set to variable-bit-width int (use exts "max")
298 self
.undefined
= SelectableInt(0, 256) # TODO, not hard-code 256!
301 self
.namespace
.update(self
.spr
)
302 self
.namespace
.update({'GPR': self
.gpr
,
305 'memassign': self
.memassign
,
310 'undefined': self
.undefined
,
311 'mode_is_64bit': True,
316 # field-selectable versions of Condition Register TODO check bitranges?
319 bits
= tuple(range(i
*4, (i
+1)*4))# errr... maybe?
320 _cr
= FieldSelectableInt(self
.cr
, bits
)
322 self
.namespace
["CR%d" % i
] = _cr
324 self
.decoder
= decoder2
.dec
327 def TRAP(self
, trap_addr
=0x700):
329 # store CIA(+4?) in SRR0, set NIA to 0x700
330 # store MSR in SRR1, set MSR to um errr something, have to check spec
331 self
.spr
['SRR0'] = self
.pc
.CIA
332 self
.spr
['SRR1'] = self
.namespace
['MSR']
333 self
.set_pc(trap_addr
)
334 self
.namespace
['MSR'][63-PI
.TRAP
] = 1 # bit 45, "this is a trap"
336 def memassign(self
, ea
, sz
, val
):
337 self
.mem
.memassign(ea
, sz
, val
)
339 def prep_namespace(self
, formname
, op_fields
):
340 # TODO: get field names from form in decoder*1* (not decoder2)
341 # decoder2 is hand-created, and decoder1.sigform is auto-generated
343 # then "yield" fields only from op_fields rather than hard-coded
345 fields
= self
.decoder
.sigforms
[formname
]
346 for name
in op_fields
:
348 sig
= getattr(fields
, name
.upper())
350 sig
= getattr(fields
, name
)
352 if name
in ['BF', 'BFA']:
353 self
.namespace
[name
] = val
355 self
.namespace
[name
] = SelectableInt(val
, sig
.width
)
357 self
.namespace
['XER'] = self
.spr
['XER']
358 self
.namespace
['CA'] = self
.spr
['XER'][XER_bits
['CA']].value
359 self
.namespace
['CA32'] = self
.spr
['XER'][XER_bits
['CA32']].value
361 def handle_carry_(self
, inputs
, outputs
, already_done
):
362 inv_a
= yield self
.dec2
.e
.invert_a
364 inputs
[0] = ~inputs
[0]
366 imm_ok
= yield self
.dec2
.e
.imm_data
.ok
368 imm
= yield self
.dec2
.e
.imm_data
.data
369 inputs
.append(SelectableInt(imm
, 64))
370 assert len(outputs
) >= 1
371 print ("outputs", repr(outputs
))
372 if isinstance(outputs
, list) or isinstance(outputs
, tuple):
378 print ("gt input", x
, output
)
382 cy
= 1 if any(gts
) else 0
383 if not (1 & already_done
):
384 self
.spr
['XER'][XER_bits
['CA']] = cy
386 print ("inputs", inputs
)
390 print ("input", x
, output
)
391 gt
= (x
[32:64] > output
[32:64]) == SelectableInt(1, 1)
393 cy32
= 1 if any(gts
) else 0
394 if not (2 & already_done
):
395 self
.spr
['XER'][XER_bits
['CA32']] = cy32
397 def handle_overflow(self
, inputs
, outputs
, div_overflow
):
398 inv_a
= yield self
.dec2
.e
.invert_a
400 inputs
[0] = ~inputs
[0]
402 imm_ok
= yield self
.dec2
.e
.imm_data
.ok
404 imm
= yield self
.dec2
.e
.imm_data
.data
405 inputs
.append(SelectableInt(imm
, 64))
406 assert len(outputs
) >= 1
407 print ("handle_overflow", inputs
, outputs
, div_overflow
)
408 if len(inputs
) < 2 and div_overflow
!= 1:
411 # div overflow is different: it's returned by the pseudo-code
412 # because it's more complex than can be done by analysing the output
413 if div_overflow
== 1:
415 # arithmetic overflow can be done by analysing the input and output
416 elif len(inputs
) >= 2:
420 input_sgn
= [exts(x
.value
, x
.bits
) < 0 for x
in inputs
]
421 output_sgn
= exts(output
.value
, output
.bits
) < 0
422 ov
= 1 if input_sgn
[0] == input_sgn
[1] and \
423 output_sgn
!= input_sgn
[0] else 0
426 input32_sgn
= [exts(x
.value
, 32) < 0 for x
in inputs
]
427 output32_sgn
= exts(output
.value
, 32) < 0
428 ov32
= 1 if input32_sgn
[0] == input32_sgn
[1] and \
429 output32_sgn
!= input32_sgn
[0] else 0
431 self
.spr
['XER'][XER_bits
['OV']] = ov
432 self
.spr
['XER'][XER_bits
['OV32']] = ov32
433 so
= self
.spr
['XER'][XER_bits
['SO']]
435 self
.spr
['XER'][XER_bits
['SO']] = so
437 def handle_comparison(self
, outputs
):
439 out
= exts(out
.value
, out
.bits
)
440 zero
= SelectableInt(out
== 0, 1)
441 positive
= SelectableInt(out
> 0, 1)
442 negative
= SelectableInt(out
< 0, 1)
443 SO
= self
.spr
['XER'][XER_bits
['SO']]
444 cr_field
= selectconcat(negative
, positive
, zero
, SO
)
445 self
.crl
[0].eq(cr_field
)
447 def set_pc(self
, pc_val
):
448 self
.namespace
['NIA'] = SelectableInt(pc_val
, 64)
449 self
.pc
.update(self
.namespace
)
452 """set up one instruction
455 pc
= self
.pc
.CIA
.value
459 ins
= self
.imem
.ld(pc
, 4, False, True)
461 raise KeyError("no instruction at 0x%x" % pc
)
462 print("setup: 0x%x 0x%x %s" % (pc
, ins
& 0xffffffff, bin(ins
)))
463 print ("NIA, CIA", self
.pc
.CIA
.value
, self
.pc
.NIA
.value
)
465 yield self
.dec2
.dec
.raw_opcode_in
.eq(ins
& 0xffffffff)
466 yield self
.dec2
.dec
.bigendian
.eq(0) # little / big?
468 def execute_one(self
):
469 """execute one instruction
471 # get the disassembly code for this instruction
472 code
= self
.disassembly
[self
._pc
]
473 print("sim-execute", hex(self
._pc
), code
)
474 opname
= code
.split(' ')[0]
475 yield from self
.call(opname
)
477 if not self
.respect_pc
:
479 print ("NIA, CIA", self
.pc
.CIA
.value
, self
.pc
.NIA
.value
)
481 def get_assembly_name(self
):
482 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
483 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
484 asmcode
= yield self
.dec2
.dec
.op
.asmcode
485 asmop
= insns
.get(asmcode
, None)
487 # sigh reconstruct the assembly instruction name
488 ov_en
= yield self
.dec2
.e
.oe
.oe
489 ov_ok
= yield self
.dec2
.e
.oe
.ok
492 lk
= yield self
.dec2
.e
.lk
495 int_op
= yield self
.dec2
.dec
.op
.internal_op
496 print ("int_op", int_op
)
497 if int_op
in [InternalOp
.OP_B
.value
, InternalOp
.OP_BC
.value
]:
498 AA
= yield self
.dec2
.dec
.fields
.FormI
.AA
[0:-1]
502 if int_op
== InternalOp
.OP_MFCR
.value
:
503 dec_insn
= yield self
.dec2
.e
.insn
504 if dec_insn
& (1<<20) != 0: # sigh
508 # XXX TODO: for whatever weird reason this doesn't work
509 # https://bugs.libre-soc.org/show_bug.cgi?id=390
510 if int_op
== InternalOp
.OP_MTCRF
.value
:
511 dec_insn
= yield self
.dec2
.e
.insn
512 if dec_insn
& (1<<20) != 0: # sigh
518 def call(self
, name
):
519 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
520 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
521 asmop
= yield from self
.get_assembly_name()
522 print ("call", name
, asmop
)
523 if name
not in ['mtcrf', 'mtocrf']:
524 assert name
== asmop
, "name %s != %s" % (name
, asmop
)
526 info
= self
.instrs
[name
]
527 yield from self
.prep_namespace(info
.form
, info
.op_fields
)
529 # preserve order of register names
530 input_names
= create_args(list(info
.read_regs
) + list(info
.uninit_regs
))
533 # main registers (RT, RA ...)
535 for name
in input_names
:
536 regnum
= yield getattr(self
.decoder
, name
)
538 self
.namespace
[regname
] = regnum
539 print('reading reg %d' % regnum
)
540 inputs
.append(self
.gpr(regnum
))
542 # "special" registers
543 for special
in info
.special_regs
:
544 if special
in special_sprs
:
545 inputs
.append(self
.spr
[special
])
547 inputs
.append(self
.namespace
[special
])
550 results
= info
.func(self
, *inputs
)
553 # detect if CA/CA32 already in outputs (sra*, basically)
556 output_names
= create_args(info
.write_regs
)
557 for name
in output_names
:
563 print ("carry already done?", bin(already_done
))
564 carry_en
= yield self
.dec2
.e
.output_carry
566 yield from self
.handle_carry_(inputs
, results
, already_done
)
568 # detect if overflow was in return result
571 for name
, output
in zip(output_names
, results
):
572 if name
== 'overflow':
575 ov_en
= yield self
.dec2
.e
.oe
.oe
576 ov_ok
= yield self
.dec2
.e
.oe
.ok
577 print ("internal overflow", overflow
)
579 yield from self
.handle_overflow(inputs
, results
, overflow
)
581 rc_en
= yield self
.dec2
.e
.rc
.data
583 self
.handle_comparison(results
)
585 # any modified return results?
587 for name
, output
in zip(output_names
, results
):
588 if name
== 'overflow': # ignore, done already (above)
590 if isinstance(output
, int):
591 output
= SelectableInt(output
, 256)
592 if name
in ['CA', 'CA32']:
594 print ("writing %s to XER" % name
, output
)
595 self
.spr
['XER'][XER_bits
[name
]] = output
.value
597 print ("NOT writing %s to XER" % name
, output
)
598 elif name
in info
.special_regs
:
599 print('writing special %s' % name
, output
, special_sprs
)
600 if name
in special_sprs
:
601 self
.spr
[name
] = output
603 self
.namespace
[name
].eq(output
)
605 print ('msr written', hex(self
.msr
.value
))
607 regnum
= yield getattr(self
.decoder
, name
)
608 print('writing reg %d %s' % (regnum
, str(output
)))
610 output
= SelectableInt(output
.value
, 64)
611 self
.gpr
[regnum
] = output
613 # update program counter
614 self
.pc
.update(self
.namespace
)
618 """Decorator factory.
620 this decorator will "inject" variables into the function's namespace,
621 from the *dictionary* in self.namespace. it therefore becomes possible
622 to make it look like a whole stack of variables which would otherwise
623 need "self." inserted in front of them (*and* for those variables to be
624 added to the instance) "appear" in the function.
626 "self.namespace['SI']" for example becomes accessible as just "SI" but
627 *only* inside the function, when decorated.
629 def variable_injector(func
):
631 def decorator(*args
, **kwargs
):
633 func_globals
= func
.__globals
__ # Python 2.6+
634 except AttributeError:
635 func_globals
= func
.func_globals
# Earlier versions.
637 context
= args
[0].namespace
# variables to be injected
638 saved_values
= func_globals
.copy() # Shallow copy of dict.
639 func_globals
.update(context
)
640 result
= func(*args
, **kwargs
)
641 args
[0].namespace
= func_globals
642 #exec (func.__code__, func_globals)
645 # func_globals = saved_values # Undo changes.
651 return variable_injector