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
, XER_bits
, insns
, InternalOp
13 from soc
.decoder
.helpers
import exts
, trunc_div
, trunc_rem
14 from collections
import namedtuple
18 instruction_info
= namedtuple('instruction_info',
19 'func read_regs uninit_regs write_regs ' + \
20 'special_regs op_fields form asmregs')
30 def swap_order(x
, nbytes
):
31 x
= x
.to_bytes(nbytes
, byteorder
='little')
32 x
= int.from_bytes(x
, byteorder
='big', signed
=False)
36 def create_args(reglist
, extra
=None):
48 def __init__(self
, row_bytes
=8, initial_mem
=None):
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
)
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
62 for i
, val
in enumerate(mem
):
63 initial_mem
[startaddr
+ row_bytes
*i
] = (val
, row_bytes
)
65 for addr
, (val
, width
) in initial_mem
.items():
66 #val = swap_order(val, width)
67 self
.st(addr
, val
, width
, swap
=False)
69 def _get_shifter_mask(self
, wid
, remainder
):
70 shifter
= ((self
.bytes_per_word
- wid
) - remainder
) * \
72 # XXX https://bugs.libre-soc.org/show_bug.cgi?id=377
74 shifter
= remainder
* 8
75 mask
= (1 << (wid
* 8)) - 1
76 print ("width,rem,shift,mask", wid
, remainder
, hex(shifter
), hex(mask
))
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
]
91 print("mem @ 0x{:x} rem {:d} : 0x{:x}".format(address
, remainder
, val
))
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
)
99 val
= swap_order(val
, width
)
100 print("Read 0x{:x} from addr 0x{:x}".format(val
, address
))
103 def st(self
, addr
, v
, width
=8, swap
=True):
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!"
111 v
= swap_order(v
, width
)
112 if width
!= self
.bytes_per_word
:
117 shifter
, mask
= self
._get
_shifter
_mask
(width
, remainder
)
118 val
&= ~
(mask
<< shifter
)
123 print("mem @ 0x{:x}: 0x{:x}".format(addr
, self
.mem
[addr
]))
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)
130 def memassign(self
, addr
, sz
, val
):
131 print ("memassign", addr
, sz
, val
)
132 self
.st(addr
.value
, val
.value
, sz
)
136 def __init__(self
, decoder
, regfile
):
140 self
[i
] = SelectableInt(regfile
[i
], 64)
142 def __call__(self
, ridx
):
145 def set_form(self
, form
):
148 def getz(self
, rnum
):
149 #rnum = rnum.value # only SelectableInt allowed
150 print("GPR getzero", rnum
)
152 return SelectableInt(0, 64)
155 def _get_regnum(self
, attr
):
156 getform
= self
.sd
.sigforms
[self
.form
]
157 rnum
= getattr(getform
, attr
)
160 def ___getitem__(self
, attr
):
161 print("GPR getitem", attr
)
162 rnum
= self
._get
_regnum
(attr
)
163 return self
.regfile
[rnum
]
166 for i
in range(0, len(self
), 8):
169 s
.append("%08x" % self
[i
+j
].value
)
171 print("reg", "%2d" % i
, s
)
174 def __init__(self
, pc_init
=0):
175 self
.CIA
= SelectableInt(pc_init
, 64)
176 self
.NIA
= self
.CIA
+ SelectableInt(4, 64)
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
186 def __init__(self
, dec2
, initial_sprs
={}):
189 self
.update(initial_sprs
)
191 def __getitem__(self
, key
):
192 # if key in special_sprs get the special spr, otherwise return key
193 if isinstance(key
, SelectableInt
):
195 key
= special_sprs
.get(key
, key
)
197 return dict.__getitem
__(self
, key
)
200 dict.__setitem
__(self
, key
, SelectableInt(0, info
.length
))
201 return dict.__getitem
__(self
, key
)
203 def __setitem__(self
, key
, value
):
204 if isinstance(key
, SelectableInt
):
206 key
= special_sprs
.get(key
, key
)
207 dict.__setitem
__(self
, key
, value
)
209 def __call__(self
, ridx
):
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,
223 self
.respect_pc
= respect_pc
224 if initial_sprs
is None:
226 if initial_mem
is None:
228 if initial_insns
is None:
230 assert self
.respect_pc
== False, "instructions required to honor pc"
232 print ("ISACaller insns", respect_pc
, initial_insns
, disassembly
)
234 # "fake program counter" mode (for unit testing)
237 if isinstance(initial_mem
, tuple):
238 self
.fake_pc
= initial_mem
[0]
240 # disassembly: we need this for now (not given from the decoder)
241 self
.disassembly
= {}
243 for i
, code
in enumerate(disassembly
):
244 self
.disassembly
[i
*4 + self
.fake_pc
] = code
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
)
251 self
.spr
= SPR(decoder2
, initial_sprs
)
252 self
.msr
= SelectableInt(initial_msr
, 64) # underlying reg
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
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)
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)))
271 # "undefined", just set to variable-bit-width int (use exts "max")
272 self
.undefined
= SelectableInt(0, 256) # TODO, not hard-code 256!
274 self
.namespace
= {'GPR': self
.gpr
,
277 'memassign': self
.memassign
,
282 'undefined': self
.undefined
,
283 'mode_is_64bit': True,
287 # field-selectable versions of Condition Register TODO check bitranges?
290 bits
= tuple(range(i
*4, (i
+1)*4))# errr... maybe?
291 _cr
= FieldSelectableInt(self
.cr
, bits
)
293 self
.namespace
["CR%d" % i
] = _cr
295 self
.decoder
= decoder2
.dec
298 def TRAP(self
, trap_addr
=0x700):
300 #self.namespace['NIA'] = trap_addr
301 #self.SRR0 = self.namespace['CIA'] + 4
302 #self.SRR1 = self.namespace['MSR']
303 #self.namespace['MSR'][45] = 1
304 # store CIA(+4?) in SRR0, set NIA to 0x700
305 # store MSR in SRR1, set MSR to um errr something, have to check spec
307 def memassign(self
, ea
, sz
, val
):
308 self
.mem
.memassign(ea
, sz
, val
)
310 def prep_namespace(self
, formname
, op_fields
):
311 # TODO: get field names from form in decoder*1* (not decoder2)
312 # decoder2 is hand-created, and decoder1.sigform is auto-generated
314 # then "yield" fields only from op_fields rather than hard-coded
316 fields
= self
.decoder
.sigforms
[formname
]
317 for name
in op_fields
:
319 sig
= getattr(fields
, name
.upper())
321 sig
= getattr(fields
, name
)
323 if name
in ['BF', 'BFA']:
324 self
.namespace
[name
] = val
326 self
.namespace
[name
] = SelectableInt(val
, sig
.width
)
328 self
.namespace
['XER'] = self
.spr
['XER']
329 self
.namespace
['CA'] = self
.spr
['XER'][XER_bits
['CA']].value
330 self
.namespace
['CA32'] = self
.spr
['XER'][XER_bits
['CA32']].value
332 def handle_carry_(self
, inputs
, outputs
, already_done
):
333 inv_a
= yield self
.dec2
.e
.invert_a
335 inputs
[0] = ~inputs
[0]
337 imm_ok
= yield self
.dec2
.e
.imm_data
.ok
339 imm
= yield self
.dec2
.e
.imm_data
.data
340 inputs
.append(SelectableInt(imm
, 64))
341 assert len(outputs
) >= 1
342 print ("outputs", repr(outputs
))
343 if isinstance(outputs
, list) or isinstance(outputs
, tuple):
349 print ("gt input", x
, output
)
353 cy
= 1 if any(gts
) else 0
354 if not (1 & already_done
):
355 self
.spr
['XER'][XER_bits
['CA']] = cy
357 print ("inputs", inputs
)
361 print ("input", x
, output
)
362 gt
= (x
[32:64] > output
[32:64]) == SelectableInt(1, 1)
364 cy32
= 1 if any(gts
) else 0
365 if not (2 & already_done
):
366 self
.spr
['XER'][XER_bits
['CA32']] = cy32
368 def handle_overflow(self
, inputs
, outputs
, div_overflow
):
369 inv_a
= yield self
.dec2
.e
.invert_a
371 inputs
[0] = ~inputs
[0]
373 imm_ok
= yield self
.dec2
.e
.imm_data
.ok
375 imm
= yield self
.dec2
.e
.imm_data
.data
376 inputs
.append(SelectableInt(imm
, 64))
377 assert len(outputs
) >= 1
378 print ("handle_overflow", inputs
, outputs
, div_overflow
)
379 if len(inputs
) < 2 and div_overflow
!= 1:
382 # div overflow is different: it's returned by the pseudo-code
383 # because it's more complex than can be done by analysing the output
384 if div_overflow
== 1:
386 # arithmetic overflow can be done by analysing the input and output
387 elif len(inputs
) >= 2:
391 input_sgn
= [exts(x
.value
, x
.bits
) < 0 for x
in inputs
]
392 output_sgn
= exts(output
.value
, output
.bits
) < 0
393 ov
= 1 if input_sgn
[0] == input_sgn
[1] and \
394 output_sgn
!= input_sgn
[0] else 0
397 input32_sgn
= [exts(x
.value
, 32) < 0 for x
in inputs
]
398 output32_sgn
= exts(output
.value
, 32) < 0
399 ov32
= 1 if input32_sgn
[0] == input32_sgn
[1] and \
400 output32_sgn
!= input32_sgn
[0] else 0
402 self
.spr
['XER'][XER_bits
['OV']] = ov
403 self
.spr
['XER'][XER_bits
['OV32']] = ov32
404 so
= self
.spr
['XER'][XER_bits
['SO']]
406 self
.spr
['XER'][XER_bits
['SO']] = so
408 def handle_comparison(self
, outputs
):
410 out
= exts(out
.value
, out
.bits
)
411 zero
= SelectableInt(out
== 0, 1)
412 positive
= SelectableInt(out
> 0, 1)
413 negative
= SelectableInt(out
< 0, 1)
414 SO
= self
.spr
['XER'][XER_bits
['SO']]
415 cr_field
= selectconcat(negative
, positive
, zero
, SO
)
416 self
.crl
[0].eq(cr_field
)
418 def set_pc(self
, pc_val
):
419 self
.namespace
['NIA'] = SelectableInt(pc_val
, 64)
420 self
.pc
.update(self
.namespace
)
423 """set up one instruction
426 pc
= self
.pc
.CIA
.value
430 ins
= self
.imem
.ld(pc
, 4, False, True)
432 raise KeyError("no instruction at 0x%x" % pc
)
433 print("setup: 0x%x 0x%x %s" % (pc
, ins
& 0xffffffff, bin(ins
)))
434 print ("NIA, CIA", self
.pc
.CIA
.value
, self
.pc
.NIA
.value
)
436 yield self
.dec2
.dec
.raw_opcode_in
.eq(ins
& 0xffffffff)
437 yield self
.dec2
.dec
.bigendian
.eq(0) # little / big?
439 def execute_one(self
):
440 """execute one instruction
442 # get the disassembly code for this instruction
443 code
= self
.disassembly
[self
._pc
]
444 print("sim-execute", hex(self
._pc
), code
)
445 opname
= code
.split(' ')[0]
446 yield from self
.call(opname
)
448 if not self
.respect_pc
:
450 print ("NIA, CIA", self
.pc
.CIA
.value
, self
.pc
.NIA
.value
)
452 def get_assembly_name(self
):
453 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
454 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
455 asmcode
= yield self
.dec2
.dec
.op
.asmcode
456 asmop
= insns
.get(asmcode
, None)
458 # sigh reconstruct the assembly instruction name
459 ov_en
= yield self
.dec2
.e
.oe
.oe
460 ov_ok
= yield self
.dec2
.e
.oe
.ok
463 lk
= yield self
.dec2
.e
.lk
466 int_op
= yield self
.dec2
.dec
.op
.internal_op
467 print ("int_op", int_op
)
468 if int_op
in [InternalOp
.OP_B
.value
, InternalOp
.OP_BC
.value
]:
469 AA
= yield self
.dec2
.dec
.fields
.FormI
.AA
[0:-1]
473 if int_op
== InternalOp
.OP_MFCR
.value
:
474 dec_insn
= yield self
.dec2
.e
.insn
475 if dec_insn
& (1<<20) != 0: # sigh
479 # XXX TODO: for whatever weird reason this doesn't work
480 # https://bugs.libre-soc.org/show_bug.cgi?id=390
481 if int_op
== InternalOp
.OP_MTCRF
.value
:
482 dec_insn
= yield self
.dec2
.e
.insn
483 if dec_insn
& (1<<20) != 0: # sigh
489 def call(self
, name
):
490 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
491 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
492 asmop
= yield from self
.get_assembly_name()
493 print ("call", name
, asmop
)
494 if name
not in ['mtcrf', 'mtocrf']:
495 assert name
== asmop
, "name %s != %s" % (name
, asmop
)
497 info
= self
.instrs
[name
]
498 yield from self
.prep_namespace(info
.form
, info
.op_fields
)
500 # preserve order of register names
501 input_names
= create_args(list(info
.read_regs
) + list(info
.uninit_regs
))
504 # main registers (RT, RA ...)
506 for name
in input_names
:
507 regnum
= yield getattr(self
.decoder
, name
)
509 self
.namespace
[regname
] = regnum
510 print('reading reg %d' % regnum
)
511 inputs
.append(self
.gpr(regnum
))
513 # "special" registers
514 for special
in info
.special_regs
:
515 if special
in special_sprs
:
516 inputs
.append(self
.spr
[special
])
518 inputs
.append(self
.namespace
[special
])
521 results
= info
.func(self
, *inputs
)
524 # detect if CA/CA32 already in outputs (sra*, basically)
527 output_names
= create_args(info
.write_regs
)
528 for name
in output_names
:
534 print ("carry already done?", bin(already_done
))
535 carry_en
= yield self
.dec2
.e
.output_carry
537 yield from self
.handle_carry_(inputs
, results
, already_done
)
539 # detect if overflow was in return result
542 for name
, output
in zip(output_names
, results
):
543 if name
== 'overflow':
546 ov_en
= yield self
.dec2
.e
.oe
.oe
547 ov_ok
= yield self
.dec2
.e
.oe
.ok
548 print ("internal overflow", overflow
)
550 yield from self
.handle_overflow(inputs
, results
, overflow
)
552 rc_en
= yield self
.dec2
.e
.rc
.data
554 self
.handle_comparison(results
)
556 # any modified return results?
558 for name
, output
in zip(output_names
, results
):
559 if name
== 'overflow': # ignore, done already (above)
561 if isinstance(output
, int):
562 output
= SelectableInt(output
, 256)
563 if name
in ['CA', 'CA32']:
565 print ("writing %s to XER" % name
, output
)
566 self
.spr
['XER'][XER_bits
[name
]] = output
.value
568 print ("NOT writing %s to XER" % name
, output
)
569 elif name
in info
.special_regs
:
570 print('writing special %s' % name
, output
, special_sprs
)
571 if name
in special_sprs
:
572 self
.spr
[name
] = output
574 self
.namespace
[name
].eq(output
)
576 regnum
= yield getattr(self
.decoder
, name
)
577 print('writing reg %d %s' % (regnum
, str(output
)))
579 output
= SelectableInt(output
.value
, 64)
580 self
.gpr
[regnum
] = output
582 # update program counter
583 self
.pc
.update(self
.namespace
)
587 """Decorator factory.
589 this decorator will "inject" variables into the function's namespace,
590 from the *dictionary* in self.namespace. it therefore becomes possible
591 to make it look like a whole stack of variables which would otherwise
592 need "self." inserted in front of them (*and* for those variables to be
593 added to the instance) "appear" in the function.
595 "self.namespace['SI']" for example becomes accessible as just "SI" but
596 *only* inside the function, when decorated.
598 def variable_injector(func
):
600 def decorator(*args
, **kwargs
):
602 func_globals
= func
.__globals
__ # Python 2.6+
603 except AttributeError:
604 func_globals
= func
.func_globals
# Earlier versions.
606 context
= args
[0].namespace
# variables to be injected
607 saved_values
= func_globals
.copy() # Shallow copy of dict.
608 func_globals
.update(context
)
609 result
= func(*args
, **kwargs
)
610 args
[0].namespace
= func_globals
611 #exec (func.__code__, func_globals)
614 # func_globals = saved_values # Undo changes.
620 return variable_injector