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
13 from soc
.decoder
.helpers
import exts
14 from collections
import namedtuple
17 instruction_info
= namedtuple('instruction_info',
18 'func read_regs uninit_regs write_regs ' + \
19 'special_regs op_fields form asmregs')
29 def swap_order(x
, nbytes
):
30 x
= x
.to_bytes(nbytes
, byteorder
='little')
31 x
= int.from_bytes(x
, byteorder
='big', signed
=False)
35 def create_args(reglist
, extra
=None):
47 def __init__(self
, row_bytes
=8, initial_mem
=None):
49 self
.bytes_per_word
= row_bytes
50 self
.word_log2
= math
.ceil(math
.log2(row_bytes
))
51 print ("Sim-Mem", initial_mem
, self
.bytes_per_word
, self
.word_log2
)
55 # different types of memory data structures recognised (for convenience)
56 if isinstance(initial_mem
, list):
57 initial_mem
= (0, initial_mem
)
58 if isinstance(initial_mem
, tuple):
59 startaddr
, mem
= initial_mem
61 for i
, val
in enumerate(mem
):
62 initial_mem
[startaddr
+ row_bytes
*i
] = (val
, row_bytes
)
64 for addr
, (val
, width
) in initial_mem
.items():
65 #val = swap_order(val, width)
66 self
.st(addr
, val
, width
, swap
=False)
68 def _get_shifter_mask(self
, wid
, remainder
):
69 shifter
= ((self
.bytes_per_word
- wid
) - remainder
) * \
71 # XXX https://bugs.libre-soc.org/show_bug.cgi?id=377
73 shifter
= remainder
* 8
74 mask
= (1 << (wid
* 8)) - 1
75 print ("width,rem,shift,mask", wid
, remainder
, hex(shifter
), hex(mask
))
78 # TODO: Implement ld/st of lesser width
79 def ld(self
, address
, width
=8, swap
=True):
80 print("ld from addr 0x{:x} width {:d}".format(address
, width
))
81 remainder
= address
& (self
.bytes_per_word
- 1)
82 address
= address
>> self
.word_log2
83 assert remainder
& (width
- 1) == 0, "Unaligned access unsupported!"
84 if address
in self
.mem
:
85 val
= self
.mem
[address
]
88 print("mem @ 0x{:x} rem {:d} : 0x{:x}".format(address
, remainder
, val
))
90 if width
!= self
.bytes_per_word
:
91 shifter
, mask
= self
._get
_shifter
_mask
(width
, remainder
)
92 print ("masking", hex(val
), hex(mask
<<shifter
), shifter
)
93 val
= val
& (mask
<< shifter
)
96 val
= swap_order(val
, width
)
97 print("Read 0x{:x} from addr 0x{:x}".format(val
, address
))
100 def st(self
, addr
, v
, width
=8, swap
=True):
102 remainder
= addr
& (self
.bytes_per_word
- 1)
103 addr
= addr
>> self
.word_log2
104 print("Writing 0x{:x} to ST 0x{:x} memaddr 0x{:x}/{:x}".format(v
,
105 staddr
, addr
, remainder
, swap
))
106 assert remainder
& (width
- 1) == 0, "Unaligned access unsupported!"
108 v
= swap_order(v
, width
)
109 if width
!= self
.bytes_per_word
:
114 shifter
, mask
= self
._get
_shifter
_mask
(width
, remainder
)
115 val
&= ~
(mask
<< shifter
)
120 print("mem @ 0x{:x}: 0x{:x}".format(addr
, self
.mem
[addr
]))
122 def __call__(self
, addr
, sz
):
123 val
= self
.ld(addr
.value
, sz
)
124 print ("memread", addr
, sz
, val
)
125 return SelectableInt(val
, sz
*8)
127 def memassign(self
, addr
, sz
, val
):
128 print ("memassign", addr
, sz
, val
)
129 self
.st(addr
.value
, val
.value
, sz
)
133 def __init__(self
, decoder
, regfile
):
137 self
[i
] = SelectableInt(regfile
[i
], 64)
139 def __call__(self
, ridx
):
142 def set_form(self
, form
):
145 def getz(self
, rnum
):
146 #rnum = rnum.value # only SelectableInt allowed
147 print("GPR getzero", rnum
)
149 return SelectableInt(0, 64)
152 def _get_regnum(self
, attr
):
153 getform
= self
.sd
.sigforms
[self
.form
]
154 rnum
= getattr(getform
, attr
)
157 def ___getitem__(self
, attr
):
158 print("GPR getitem", attr
)
159 rnum
= self
._get
_regnum
(attr
)
160 return self
.regfile
[rnum
]
163 for i
in range(0, len(self
), 8):
166 s
.append("%08x" % self
[i
+j
].value
)
168 print("reg", "%2d" % i
, s
)
171 def __init__(self
, pc_init
=0):
172 self
.CIA
= SelectableInt(pc_init
, 64)
173 self
.NIA
= self
.CIA
+ SelectableInt(4, 64)
175 def update(self
, namespace
):
176 self
.CIA
= namespace
['NIA'].narrow(64)
177 self
.NIA
= self
.CIA
+ SelectableInt(4, 64)
178 namespace
['CIA'] = self
.CIA
179 namespace
['NIA'] = self
.NIA
183 def __init__(self
, dec2
, initial_sprs
={}):
186 self
.update(initial_sprs
)
188 def __getitem__(self
, key
):
189 # if key in special_sprs get the special spr, otherwise return key
190 if isinstance(key
, SelectableInt
):
192 key
= special_sprs
.get(key
, key
)
194 return dict.__getitem
__(self
, key
)
197 dict.__setitem
__(self
, key
, SelectableInt(0, info
.length
))
198 return dict.__getitem
__(self
, key
)
200 def __setitem__(self
, key
, value
):
201 if isinstance(key
, SelectableInt
):
203 key
= special_sprs
.get(key
, key
)
204 dict.__setitem
__(self
, key
, value
)
206 def __call__(self
, ridx
):
211 # decoder2 - an instance of power_decoder2
212 # regfile - a list of initial values for the registers
213 # initial_{etc} - initial values for SPRs, Condition Register, Mem, MSR
214 # respect_pc - tracks the program counter. requires initial_insns
215 def __init__(self
, decoder2
, regfile
, initial_sprs
=None, initial_cr
=0,
216 initial_mem
=None, initial_msr
=0,
217 initial_insns
=None, respect_pc
=False,
220 self
.respect_pc
= respect_pc
221 if initial_sprs
is None:
223 if initial_mem
is None:
225 if initial_insns
is None:
227 assert self
.respect_pc
== False, "instructions required to honor pc"
229 print ("ISACaller insns", respect_pc
, initial_insns
, disassembly
)
231 # "fake program counter" mode (for unit testing)
233 if isinstance(initial_mem
, tuple):
234 self
.fake_pc
= initial_mem
[0]
238 # disassembly: we need this for now (not given from the decoder)
239 self
.disassembly
= {}
241 for i
, code
in enumerate(disassembly
):
242 self
.disassembly
[i
*4 + self
.fake_pc
] = code
244 # set up registers, instruction memory, data memory, PC, SPRs, MSR
245 self
.gpr
= GPR(decoder2
, regfile
)
246 self
.mem
= Mem(row_bytes
=8, initial_mem
=initial_mem
)
247 self
.imem
= Mem(row_bytes
=4, initial_mem
=initial_insns
)
249 self
.spr
= SPR(decoder2
, initial_sprs
)
250 self
.msr
= SelectableInt(initial_msr
, 64) # underlying reg
253 # FPR (same as GPR except for FP nums)
254 # 4.2.2 p124 FPSCR (definitely "separate" - not in SPR)
255 # note that mffs, mcrfs, mtfsf "manage" this FPSCR
256 # 2.3.1 CR (and sub-fields CR0..CR6 - CR0 SO comes from XER.SO)
257 # note that mfocrf, mfcr, mtcr, mtocrf, mcrxrx "manage" CRs
259 # 2.3.2 LR (actually SPR #8) -- Done
260 # 2.3.3 CTR (actually SPR #9) -- Done
261 # 2.3.4 TAR (actually SPR #815)
262 # 3.2.2 p45 XER (actually SPR #1) -- Done
263 # 3.2.3 p46 p232 VRSAVE (actually SPR #256)
265 # create CR then allow portions of it to be "selectable" (below)
266 self
._cr
= SelectableInt(initial_cr
, 64) # underlying reg
267 self
.cr
= FieldSelectableInt(self
._cr
, list(range(32,64)))
269 # "undefined", just set to variable-bit-width int (use exts "max")
270 self
.undefined
= SelectableInt(0, 256) # TODO, not hard-code 256!
272 self
.namespace
= {'GPR': self
.gpr
,
275 'memassign': self
.memassign
,
280 'undefined': self
.undefined
,
281 'mode_is_64bit': True,
285 # field-selectable versions of Condition Register TODO check bitranges?
288 bits
= tuple(range(i
*4, (i
+1)*4))# errr... maybe?
289 _cr
= FieldSelectableInt(self
.cr
, bits
)
291 self
.namespace
["CR%d" % i
] = _cr
293 self
.decoder
= decoder2
.dec
296 def TRAP(self
, trap_addr
=0x700):
298 # store CIA(+4?) in SRR0, set NIA to 0x700
299 # store MSR in SRR1, set MSR to um errr something, have to check spec
301 def memassign(self
, ea
, sz
, val
):
302 self
.mem
.memassign(ea
, sz
, val
)
304 def prep_namespace(self
, formname
, op_fields
):
305 # TODO: get field names from form in decoder*1* (not decoder2)
306 # decoder2 is hand-created, and decoder1.sigform is auto-generated
308 # then "yield" fields only from op_fields rather than hard-coded
310 fields
= self
.decoder
.sigforms
[formname
]
311 for name
in op_fields
:
313 sig
= getattr(fields
, name
.upper())
315 sig
= getattr(fields
, name
)
317 if name
in ['BF', 'BFA']:
318 self
.namespace
[name
] = val
320 self
.namespace
[name
] = SelectableInt(val
, sig
.width
)
322 self
.namespace
['XER'] = self
.spr
['XER']
323 self
.namespace
['CA'] = self
.spr
['XER'][XER_bits
['CA']].value
324 self
.namespace
['CA32'] = self
.spr
['XER'][XER_bits
['CA32']].value
326 def handle_carry_(self
, inputs
, outputs
, already_done
):
327 inv_a
= yield self
.dec2
.e
.invert_a
329 inputs
[0] = ~inputs
[0]
331 imm_ok
= yield self
.dec2
.e
.imm_data
.ok
333 imm
= yield self
.dec2
.e
.imm_data
.data
334 inputs
.append(SelectableInt(imm
, 64))
335 assert len(outputs
) >= 1
337 gts
= [(x
> output
) for x
in inputs
]
339 cy
= 1 if any(gts
) else 0
340 if not (1 & already_done
):
341 self
.spr
['XER'][XER_bits
['CA']] = cy
343 print ("inputs", inputs
)
345 gts
= [(x
[32:64] > output
[32:64]) == SelectableInt(1, 1)
347 cy32
= 1 if any(gts
) else 0
348 if not (2 & already_done
):
349 self
.spr
['XER'][XER_bits
['CA32']] = cy32
351 def handle_overflow(self
, inputs
, outputs
):
352 inv_a
= yield self
.dec2
.e
.invert_a
354 inputs
[0] = ~inputs
[0]
356 imm_ok
= yield self
.dec2
.e
.imm_data
.ok
358 imm
= yield self
.dec2
.e
.imm_data
.data
359 inputs
.append(SelectableInt(imm
, 64))
360 assert len(outputs
) >= 1
361 print ("handle_overflow", inputs
, outputs
)
366 input_sgn
= [exts(x
.value
, x
.bits
) < 0 for x
in inputs
]
367 output_sgn
= exts(output
.value
, output
.bits
) < 0
368 ov
= 1 if input_sgn
[0] == input_sgn
[1] and \
369 output_sgn
!= input_sgn
[0] else 0
372 input32_sgn
= [exts(x
.value
, 32) < 0 for x
in inputs
]
373 output32_sgn
= exts(output
.value
, 32) < 0
374 ov32
= 1 if input32_sgn
[0] == input32_sgn
[1] and \
375 output32_sgn
!= input32_sgn
[0] else 0
377 self
.spr
['XER'][XER_bits
['OV']] = ov
378 self
.spr
['XER'][XER_bits
['OV32']] = ov32
379 so
= self
.spr
['XER'][XER_bits
['SO']]
381 self
.spr
['XER'][XER_bits
['SO']] = so
383 def handle_comparison(self
, outputs
):
385 out
= exts(out
.value
, out
.bits
)
386 zero
= SelectableInt(out
== 0, 1)
387 positive
= SelectableInt(out
> 0, 1)
388 negative
= SelectableInt(out
< 0, 1)
389 SO
= self
.spr
['XER'][XER_bits
['SO']]
390 cr_field
= selectconcat(negative
, positive
, zero
, SO
)
391 self
.crl
[0].eq(cr_field
)
393 def set_pc(self
, pc_val
):
394 self
.namespace
['NIA'] = SelectableInt(pc_val
, 64)
395 self
.pc
.update(self
.namespace
)
398 """set up one instruction
401 pc
= self
.pc
.CIA
.value
405 ins
= self
.imem
.ld(pc
, 4, False)
406 print("setup: 0x{:X} 0x{:X}".format(pc
, ins
& 0xffffffff))
408 yield self
.dec2
.dec
.raw_opcode_in
.eq(ins
)
409 yield self
.dec2
.dec
.bigendian
.eq(0) # little / big?
411 def execute_one(self
):
412 """execute one instruction
414 # get the disassembly code for this instruction
415 code
= self
.disassembly
[self
._pc
]
416 print("sim-execute", hex(self
._pc
), code
)
417 opname
= code
.split(' ')[0]
418 yield from self
.call(opname
)
420 if not self
.respect_pc
:
423 def call(self
, name
):
424 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
425 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
426 info
= self
.instrs
[name
]
427 yield from self
.prep_namespace(info
.form
, info
.op_fields
)
429 # preserve order of register names
430 input_names
= create_args(list(info
.read_regs
) + list(info
.uninit_regs
))
433 # main registers (RT, RA ...)
435 for name
in input_names
:
436 regnum
= yield getattr(self
.decoder
, name
)
438 self
.namespace
[regname
] = regnum
439 print('reading reg %d' % regnum
)
440 inputs
.append(self
.gpr(regnum
))
442 # "special" registers
443 for special
in info
.special_regs
:
444 if special
in special_sprs
:
445 inputs
.append(self
.spr
[special
])
447 inputs
.append(self
.namespace
[special
])
450 results
= info
.func(self
, *inputs
)
453 # detect if CA/CA32 already in outputs (sra*, basically)
456 output_names
= create_args(info
.write_regs
)
457 for name
in output_names
:
463 print ("carry already done?", bin(already_done
))
464 carry_en
= yield self
.dec2
.e
.output_carry
466 yield from self
.handle_carry_(inputs
, results
, already_done
)
467 ov_en
= yield self
.dec2
.e
.oe
.oe
468 ov_ok
= yield self
.dec2
.e
.oe
.ok
470 yield from self
.handle_overflow(inputs
, results
)
471 rc_en
= yield self
.dec2
.e
.rc
.data
473 self
.handle_comparison(results
)
475 # any modified return results?
477 for name
, output
in zip(output_names
, results
):
478 if isinstance(output
, int):
479 output
= SelectableInt(output
, 256)
480 if name
in ['CA', 'CA32']:
482 print ("writing %s to XER" % name
, output
)
483 self
.spr
['XER'][XER_bits
[name
]] = output
.value
485 print ("NOT writing %s to XER" % name
, output
)
486 elif name
in info
.special_regs
:
487 print('writing special %s' % name
, output
, special_sprs
)
488 if name
in special_sprs
:
489 self
.spr
[name
] = output
491 self
.namespace
[name
].eq(output
)
493 regnum
= yield getattr(self
.decoder
, name
)
494 print('writing reg %d %s' % (regnum
, str(output
)))
496 output
= SelectableInt(output
.value
, 64)
497 self
.gpr
[regnum
] = output
499 # update program counter
500 self
.pc
.update(self
.namespace
)
504 """Decorator factory.
506 this decorator will "inject" variables into the function's namespace,
507 from the *dictionary* in self.namespace. it therefore becomes possible
508 to make it look like a whole stack of variables which would otherwise
509 need "self." inserted in front of them (*and* for those variables to be
510 added to the instance) "appear" in the function.
512 "self.namespace['SI']" for example becomes accessible as just "SI" but
513 *only* inside the function, when decorated.
515 def variable_injector(func
):
517 def decorator(*args
, **kwargs
):
519 func_globals
= func
.__globals
__ # Python 2.6+
520 except AttributeError:
521 func_globals
= func
.func_globals
# Earlier versions.
523 context
= args
[0].namespace
# variables to be injected
524 saved_values
= func_globals
.copy() # Shallow copy of dict.
525 func_globals
.update(context
)
526 result
= func(*args
, **kwargs
)
527 args
[0].namespace
= func_globals
528 #exec (func.__code__, func_globals)
531 # func_globals = saved_values # Undo changes.
537 return variable_injector