7ade13afd13381ab3df36fde8343973e39d0fbc3
1 # SPDX-License-Identifier: LGPLv3+
2 # Copyright (C) 2020, 2021 Luke Kenneth Casson Leighton <lkcl@lkcl.net>
3 # Copyright (C) 2020 Michael Nolan
4 # Funded by NLnet http://nlnet.nl
5 """core of the python-based POWER9 simulator
7 this is part of a cycle-accurate POWER9 simulator. its primary purpose is
8 not speed, it is for both learning and educational purposes, as well as
9 a method of verifying the HDL.
13 * https://bugs.libre-soc.org/show_bug.cgi?id=424
16 from nmigen
.back
.pysim
import Settle
17 from functools
import wraps
19 from soc
.decoder
.orderedset
import OrderedSet
20 from soc
.decoder
.selectable_int
import (FieldSelectableInt
, SelectableInt
,
22 from soc
.decoder
.power_enums
import (spr_dict
, spr_byname
, XER_bits
,
23 insns
, MicrOp
, In1Sel
, In2Sel
, In3Sel
,
25 from soc
.decoder
.helpers
import exts
, gtu
, ltu
, undefined
26 from soc
.consts
import PIb
, MSRb
# big-endian (PowerISA versions)
27 from soc
.decoder
.power_svp64
import SVP64RM
, decode_extra
29 from collections
import namedtuple
33 instruction_info
= namedtuple('instruction_info',
34 'func read_regs uninit_regs write_regs ' +
35 'special_regs op_fields form asmregs')
45 def swap_order(x
, nbytes
):
46 x
= x
.to_bytes(nbytes
, byteorder
='little')
47 x
= int.from_bytes(x
, byteorder
='big', signed
=False)
52 # TODO (lkcl): adjust other registers that should be in a particular order
53 # probably CA, CA32, and CR
70 def create_args(reglist
, extra
=None):
71 retval
= list(OrderedSet(reglist
))
72 retval
.sort(key
=lambda reg
: REG_SORT_ORDER
[reg
])
74 return [extra
] + retval
80 def __init__(self
, row_bytes
=8, initial_mem
=None):
82 self
.bytes_per_word
= row_bytes
83 self
.word_log2
= math
.ceil(math
.log2(row_bytes
))
84 print("Sim-Mem", initial_mem
, self
.bytes_per_word
, self
.word_log2
)
88 # different types of memory data structures recognised (for convenience)
89 if isinstance(initial_mem
, list):
90 initial_mem
= (0, initial_mem
)
91 if isinstance(initial_mem
, tuple):
92 startaddr
, mem
= initial_mem
94 for i
, val
in enumerate(mem
):
95 initial_mem
[startaddr
+ row_bytes
*i
] = (val
, row_bytes
)
97 for addr
, (val
, width
) in initial_mem
.items():
98 #val = swap_order(val, width)
99 self
.st(addr
, val
, width
, swap
=False)
101 def _get_shifter_mask(self
, wid
, remainder
):
102 shifter
= ((self
.bytes_per_word
- wid
) - remainder
) * \
104 # XXX https://bugs.libre-soc.org/show_bug.cgi?id=377
106 shifter
= remainder
* 8
107 mask
= (1 << (wid
* 8)) - 1
108 print("width,rem,shift,mask", wid
, remainder
, hex(shifter
), hex(mask
))
111 # TODO: Implement ld/st of lesser width
112 def ld(self
, address
, width
=8, swap
=True, check_in_mem
=False):
113 print("ld from addr 0x{:x} width {:d}".format(address
, width
))
114 remainder
= address
& (self
.bytes_per_word
- 1)
115 address
= address
>> self
.word_log2
116 assert remainder
& (width
- 1) == 0, "Unaligned access unsupported!"
117 if address
in self
.mem
:
118 val
= self
.mem
[address
]
123 print("mem @ 0x{:x} rem {:d} : 0x{:x}".format(address
, remainder
, val
))
125 if width
!= self
.bytes_per_word
:
126 shifter
, mask
= self
._get
_shifter
_mask
(width
, remainder
)
127 print("masking", hex(val
), hex(mask
<< shifter
), shifter
)
128 val
= val
& (mask
<< shifter
)
131 val
= swap_order(val
, width
)
132 print("Read 0x{:x} from addr 0x{:x}".format(val
, address
))
135 def st(self
, addr
, v
, width
=8, swap
=True):
137 remainder
= addr
& (self
.bytes_per_word
- 1)
138 addr
= addr
>> self
.word_log2
139 print("Writing 0x{:x} to ST 0x{:x} "
140 "memaddr 0x{:x}/{:x}".format(v
, staddr
, addr
, remainder
, swap
))
141 assert remainder
& (width
- 1) == 0, "Unaligned access unsupported!"
143 v
= swap_order(v
, width
)
144 if width
!= self
.bytes_per_word
:
149 shifter
, mask
= self
._get
_shifter
_mask
(width
, remainder
)
150 val
&= ~
(mask
<< shifter
)
155 print("mem @ 0x{:x}: 0x{:x}".format(addr
, self
.mem
[addr
]))
157 def __call__(self
, addr
, sz
):
158 val
= self
.ld(addr
.value
, sz
, swap
=False)
159 print("memread", addr
, sz
, val
)
160 return SelectableInt(val
, sz
*8)
162 def memassign(self
, addr
, sz
, val
):
163 print("memassign", addr
, sz
, val
)
164 self
.st(addr
.value
, val
.value
, sz
, swap
=False)
168 def __init__(self
, decoder
, isacaller
, svstate
, regfile
):
171 self
.isacaller
= isacaller
172 self
.svstate
= svstate
174 self
[i
] = SelectableInt(regfile
[i
], 64)
176 def __call__(self
, ridx
):
179 def set_form(self
, form
):
182 def getz(self
, rnum
):
183 # rnum = rnum.value # only SelectableInt allowed
184 print("GPR getzero", rnum
)
186 return SelectableInt(0, 64)
189 def _get_regnum(self
, attr
):
190 getform
= self
.sd
.sigforms
[self
.form
]
191 rnum
= getattr(getform
, attr
)
194 def ___getitem__(self
, attr
):
195 """ XXX currently not used
197 rnum
= self
._get
_regnum
(attr
)
198 offs
= self
.svstate
.srcstep
199 print("GPR getitem", attr
, rnum
, "srcoffs", offs
)
200 return self
.regfile
[rnum
]
203 for i
in range(0, len(self
), 8):
206 s
.append("%08x" % self
[i
+j
].value
)
208 print("reg", "%2d" % i
, s
)
212 def __init__(self
, pc_init
=0):
213 self
.CIA
= SelectableInt(pc_init
, 64)
214 self
.NIA
= self
.CIA
+ SelectableInt(4, 64)
216 def update(self
, namespace
, is_svp64
):
217 """updates the program counter (PC) by 4 if v3.0B mode or 8 if SVP64
219 increment
= 8 if is_svp64
else 4
220 self
.CIA
= namespace
['NIA'].narrow(64)
221 self
.NIA
= self
.CIA
+ SelectableInt(increment
, 64)
222 namespace
['CIA'] = self
.CIA
223 namespace
['NIA'] = self
.NIA
226 # Simple-V: see https://libre-soc.org/openpower/sv
228 def __init__(self
, init
=0):
229 self
.spr
= SelectableInt(init
, 32)
230 # fields of SVSTATE, see https://libre-soc.org/openpower/sv/sprs/
231 self
.maxvl
= FieldSelectableInt(self
.spr
, tuple(range(0,7)))
232 self
.vl
= FieldSelectableInt(self
.spr
, tuple(range(7,14)))
233 self
.srcstep
= FieldSelectableInt(self
.spr
, tuple(range(14,21)))
234 self
.dststep
= FieldSelectableInt(self
.spr
, tuple(range(21,28)))
235 self
.subvl
= FieldSelectableInt(self
.spr
, tuple(range(28,30)))
236 self
.svstep
= FieldSelectableInt(self
.spr
, tuple(range(30,32)))
241 def __init__(self
, init
=0):
242 self
.spr
= SelectableInt(init
, 24)
243 # SVP64 RM fields: see https://libre-soc.org/openpower/sv/svp64/
244 self
.mmode
= FieldSelectableInt(self
.spr
, [0])
245 self
.mask
= FieldSelectableInt(self
.spr
, tuple(range(1,4)))
246 self
.elwidth
= FieldSelectableInt(self
.spr
, tuple(range(4,6)))
247 self
.ewsrc
= FieldSelectableInt(self
.spr
, tuple(range(6,8)))
248 self
.subvl
= FieldSelectableInt(self
.spr
, tuple(range(8,10)))
249 self
.extra
= FieldSelectableInt(self
.spr
, tuple(range(10,19)))
250 self
.mode
= FieldSelectableInt(self
.spr
, tuple(range(19,24)))
253 # SVP64 Prefix fields: see https://libre-soc.org/openpower/sv/svp64/
254 class SVP64PrefixFields
:
256 self
.insn
= SelectableInt(0, 32)
257 # 6 bit major opcode EXT001, 2 bits "identifying" (7, 9), 24 SV ReMap
258 self
.major
= FieldSelectableInt(self
.insn
, tuple(range(0,6)))
259 self
.pid
= FieldSelectableInt(self
.insn
, (7, 9)) # must be 0b11
260 rmfields
= [6, 8] + list(range(10,32)) # SVP64 24-bit RM (ReMap)
261 self
.rm
= FieldSelectableInt(self
.insn
, rmfields
)
265 def __init__(self
, dec2
, initial_sprs
={}):
268 for key
, v
in initial_sprs
.items():
269 if isinstance(key
, SelectableInt
):
271 key
= special_sprs
.get(key
, key
)
272 if isinstance(key
, int):
275 info
= spr_byname
[key
]
276 if not isinstance(v
, SelectableInt
):
277 v
= SelectableInt(v
, info
.length
)
280 def __getitem__(self
, key
):
281 print("get spr", key
)
282 print("dict", self
.items())
283 # if key in special_sprs get the special spr, otherwise return key
284 if isinstance(key
, SelectableInt
):
286 if isinstance(key
, int):
287 key
= spr_dict
[key
].SPR
288 key
= special_sprs
.get(key
, key
)
289 if key
== 'HSRR0': # HACK!
291 if key
== 'HSRR1': # HACK!
294 res
= dict.__getitem
__(self
, key
)
296 if isinstance(key
, int):
299 info
= spr_byname
[key
]
300 dict.__setitem
__(self
, key
, SelectableInt(0, info
.length
))
301 res
= dict.__getitem
__(self
, key
)
302 print("spr returning", key
, res
)
305 def __setitem__(self
, key
, value
):
306 if isinstance(key
, SelectableInt
):
308 if isinstance(key
, int):
309 key
= spr_dict
[key
].SPR
310 print("spr key", key
)
311 key
= special_sprs
.get(key
, key
)
312 if key
== 'HSRR0': # HACK!
313 self
.__setitem
__('SRR0', value
)
314 if key
== 'HSRR1': # HACK!
315 self
.__setitem
__('SRR1', value
)
316 print("setting spr", key
, value
)
317 dict.__setitem
__(self
, key
, value
)
319 def __call__(self
, ridx
):
322 def get_pdecode_idx_in(dec2
, name
):
324 in1_sel
= yield op
.in1_sel
325 in2_sel
= yield op
.in2_sel
326 in3_sel
= yield op
.in3_sel
327 # get the IN1/2/3 from the decoder (includes SVP64 remap and isvec)
328 in1
= yield dec2
.e
.read_reg1
.data
329 in2
= yield dec2
.e
.read_reg2
.data
330 in3
= yield dec2
.e
.read_reg3
.data
331 in1_isvec
= yield dec2
.in1_isvec
332 in2_isvec
= yield dec2
.in2_isvec
333 in3_isvec
= yield dec2
.in3_isvec
334 print ("get_pdecode_idx", in1_sel
, In1Sel
.RA
.value
, in1
, in1_isvec
)
335 # identify which regnames map to in1/2/3
337 if (in1_sel
== In1Sel
.RA
.value
or
338 (in1_sel
== In1Sel
.RA_OR_ZERO
.value
and in1
!= 0)):
339 return in1
, in1_isvec
340 if in1_sel
== In1Sel
.RA_OR_ZERO
.value
:
341 return in1
, in1_isvec
343 if in2_sel
== In2Sel
.RB
.value
:
344 return in2
, in2_isvec
345 if in3_sel
== In3Sel
.RB
.value
:
346 return in3
, in3_isvec
347 # XXX TODO, RC doesn't exist yet!
349 assert False, "RC does not exist yet"
351 if in1_sel
== In1Sel
.RS
.value
:
352 return in1
, in1_isvec
353 if in2_sel
== In2Sel
.RS
.value
:
354 return in2
, in2_isvec
355 if in3_sel
== In3Sel
.RS
.value
:
356 return in3
, in3_isvec
360 def get_pdecode_idx_out(dec2
, name
):
362 out_sel
= yield op
.out_sel
363 # get the IN1/2/3 from the decoder (includes SVP64 remap and isvec)
364 out
= yield dec2
.e
.write_reg
.data
365 o_isvec
= yield dec2
.o_isvec
366 print ("get_pdecode_idx_out", out_sel
, OutSel
.RA
.value
, out
, o_isvec
)
367 # identify which regnames map to out / o2
369 if out_sel
== OutSel
.RA
.value
:
372 if out_sel
== OutSel
.RT
.value
:
374 print ("get_pdecode_idx_out not found", name
)
379 def get_pdecode_idx_out2(dec2
, name
):
381 print ("TODO: get_pdecode_idx_out2", name
)
386 # decoder2 - an instance of power_decoder2
387 # regfile - a list of initial values for the registers
388 # initial_{etc} - initial values for SPRs, Condition Register, Mem, MSR
389 # respect_pc - tracks the program counter. requires initial_insns
390 def __init__(self
, decoder2
, regfile
, initial_sprs
=None, initial_cr
=0,
391 initial_mem
=None, initial_msr
=0,
393 initial_insns
=None, respect_pc
=False,
398 self
.bigendian
= bigendian
400 self
.is_svp64_mode
= False
401 self
.respect_pc
= respect_pc
402 if initial_sprs
is None:
404 if initial_mem
is None:
406 if initial_insns
is None:
408 assert self
.respect_pc
== False, "instructions required to honor pc"
410 print("ISACaller insns", respect_pc
, initial_insns
, disassembly
)
411 print("ISACaller initial_msr", initial_msr
)
413 # "fake program counter" mode (for unit testing)
417 if isinstance(initial_mem
, tuple):
418 self
.fake_pc
= initial_mem
[0]
419 disasm_start
= self
.fake_pc
421 disasm_start
= initial_pc
423 # disassembly: we need this for now (not given from the decoder)
424 self
.disassembly
= {}
426 for i
, code
in enumerate(disassembly
):
427 self
.disassembly
[i
*4 + disasm_start
] = code
429 # set up registers, instruction memory, data memory, PC, SPRs, MSR
430 self
.svp64rm
= SVP64RM()
431 if isinstance(initial_svstate
, int):
432 initial_svstate
= SVP64State(initial_svstate
)
433 self
.svstate
= initial_svstate
434 self
.gpr
= GPR(decoder2
, self
, self
.svstate
, regfile
)
435 self
.mem
= Mem(row_bytes
=8, initial_mem
=initial_mem
)
436 self
.imem
= Mem(row_bytes
=4, initial_mem
=initial_insns
)
438 self
.spr
= SPR(decoder2
, initial_sprs
)
439 self
.msr
= SelectableInt(initial_msr
, 64) # underlying reg
442 # FPR (same as GPR except for FP nums)
443 # 4.2.2 p124 FPSCR (definitely "separate" - not in SPR)
444 # note that mffs, mcrfs, mtfsf "manage" this FPSCR
445 # 2.3.1 CR (and sub-fields CR0..CR6 - CR0 SO comes from XER.SO)
446 # note that mfocrf, mfcr, mtcr, mtocrf, mcrxrx "manage" CRs
448 # 2.3.2 LR (actually SPR #8) -- Done
449 # 2.3.3 CTR (actually SPR #9) -- Done
450 # 2.3.4 TAR (actually SPR #815)
451 # 3.2.2 p45 XER (actually SPR #1) -- Done
452 # 3.2.3 p46 p232 VRSAVE (actually SPR #256)
454 # create CR then allow portions of it to be "selectable" (below)
455 #rev_cr = int('{:016b}'.format(initial_cr)[::-1], 2)
456 self
.cr
= SelectableInt(initial_cr
, 64) # underlying reg
457 #self.cr = FieldSelectableInt(self._cr, list(range(32, 64)))
459 # "undefined", just set to variable-bit-width int (use exts "max")
460 #self.undefined = SelectableInt(0, 256) # TODO, not hard-code 256!
463 self
.namespace
.update(self
.spr
)
464 self
.namespace
.update({'GPR': self
.gpr
,
467 'memassign': self
.memassign
,
472 'undefined': undefined
,
473 'mode_is_64bit': True,
477 # update pc to requested start point
478 self
.set_pc(initial_pc
)
480 # field-selectable versions of Condition Register TODO check bitranges?
483 bits
= tuple(range(i
*4+32, (i
+1)*4+32)) # errr... maybe?
484 _cr
= FieldSelectableInt(self
.cr
, bits
)
486 self
.namespace
["CR%d" % i
] = _cr
488 self
.decoder
= decoder2
.dec
491 def TRAP(self
, trap_addr
=0x700, trap_bit
=PIb
.TRAP
):
492 print("TRAP:", hex(trap_addr
), hex(self
.namespace
['MSR'].value
))
493 # store CIA(+4?) in SRR0, set NIA to 0x700
494 # store MSR in SRR1, set MSR to um errr something, have to check spec
495 self
.spr
['SRR0'].value
= self
.pc
.CIA
.value
496 self
.spr
['SRR1'].value
= self
.namespace
['MSR'].value
497 self
.trap_nia
= SelectableInt(trap_addr
, 64)
498 self
.spr
['SRR1'][trap_bit
] = 1 # change *copy* of MSR in SRR1
500 # set exception bits. TODO: this should, based on the address
501 # in figure 66 p1065 V3.0B and the table figure 65 p1063 set these
502 # bits appropriately. however it turns out that *for now* in all
503 # cases (all trap_addrs) the exact same thing is needed.
504 self
.msr
[MSRb
.IR
] = 0
505 self
.msr
[MSRb
.DR
] = 0
506 self
.msr
[MSRb
.FE0
] = 0
507 self
.msr
[MSRb
.FE1
] = 0
508 self
.msr
[MSRb
.EE
] = 0
509 self
.msr
[MSRb
.RI
] = 0
510 self
.msr
[MSRb
.SF
] = 1
511 self
.msr
[MSRb
.TM
] = 0
512 self
.msr
[MSRb
.VEC
] = 0
513 self
.msr
[MSRb
.VSX
] = 0
514 self
.msr
[MSRb
.PR
] = 0
515 self
.msr
[MSRb
.FP
] = 0
516 self
.msr
[MSRb
.PMM
] = 0
517 self
.msr
[MSRb
.TEs
] = 0
518 self
.msr
[MSRb
.TEe
] = 0
519 self
.msr
[MSRb
.UND
] = 0
520 self
.msr
[MSRb
.LE
] = 1
522 def memassign(self
, ea
, sz
, val
):
523 self
.mem
.memassign(ea
, sz
, val
)
525 def prep_namespace(self
, formname
, op_fields
):
526 # TODO: get field names from form in decoder*1* (not decoder2)
527 # decoder2 is hand-created, and decoder1.sigform is auto-generated
529 # then "yield" fields only from op_fields rather than hard-coded
531 fields
= self
.decoder
.sigforms
[formname
]
532 for name
in op_fields
:
534 sig
= getattr(fields
, name
.upper())
536 sig
= getattr(fields
, name
)
538 # these are all opcode fields involved in index-selection of CR,
539 # and need to do "standard" arithmetic. CR[BA+32] for example
540 # would, if using SelectableInt, only be 5-bit.
541 if name
in ['BF', 'BFA', 'BC', 'BA', 'BB', 'BT', 'BI']:
542 self
.namespace
[name
] = val
544 self
.namespace
[name
] = SelectableInt(val
, sig
.width
)
546 self
.namespace
['XER'] = self
.spr
['XER']
547 self
.namespace
['CA'] = self
.spr
['XER'][XER_bits
['CA']].value
548 self
.namespace
['CA32'] = self
.spr
['XER'][XER_bits
['CA32']].value
550 def handle_carry_(self
, inputs
, outputs
, already_done
):
551 inv_a
= yield self
.dec2
.e
.do
.invert_in
553 inputs
[0] = ~inputs
[0]
555 imm_ok
= yield self
.dec2
.e
.do
.imm_data
.ok
557 imm
= yield self
.dec2
.e
.do
.imm_data
.data
558 inputs
.append(SelectableInt(imm
, 64))
559 assert len(outputs
) >= 1
560 print("outputs", repr(outputs
))
561 if isinstance(outputs
, list) or isinstance(outputs
, tuple):
567 print("gt input", x
, output
)
568 gt
= (gtu(x
, output
))
571 cy
= 1 if any(gts
) else 0
573 if not (1 & already_done
):
574 self
.spr
['XER'][XER_bits
['CA']] = cy
576 print("inputs", already_done
, inputs
)
578 # ARGH... different for OP_ADD... *sigh*...
579 op
= yield self
.dec2
.e
.do
.insn_type
580 if op
== MicrOp
.OP_ADD
.value
:
581 res32
= (output
.value
& (1 << 32)) != 0
582 a32
= (inputs
[0].value
& (1 << 32)) != 0
584 b32
= (inputs
[1].value
& (1 << 32)) != 0
587 cy32
= res32 ^ a32 ^ b32
588 print("CA32 ADD", cy32
)
592 print("input", x
, output
)
593 print(" x[32:64]", x
, x
[32:64])
594 print(" o[32:64]", output
, output
[32:64])
595 gt
= (gtu(x
[32:64], output
[32:64])) == SelectableInt(1, 1)
597 cy32
= 1 if any(gts
) else 0
598 print("CA32", cy32
, gts
)
599 if not (2 & already_done
):
600 self
.spr
['XER'][XER_bits
['CA32']] = cy32
602 def handle_overflow(self
, inputs
, outputs
, div_overflow
):
603 if hasattr(self
.dec2
.e
.do
, "invert_in"):
604 inv_a
= yield self
.dec2
.e
.do
.invert_in
606 inputs
[0] = ~inputs
[0]
608 imm_ok
= yield self
.dec2
.e
.do
.imm_data
.ok
610 imm
= yield self
.dec2
.e
.do
.imm_data
.data
611 inputs
.append(SelectableInt(imm
, 64))
612 assert len(outputs
) >= 1
613 print("handle_overflow", inputs
, outputs
, div_overflow
)
614 if len(inputs
) < 2 and div_overflow
is None:
617 # div overflow is different: it's returned by the pseudo-code
618 # because it's more complex than can be done by analysing the output
619 if div_overflow
is not None:
620 ov
, ov32
= div_overflow
, div_overflow
621 # arithmetic overflow can be done by analysing the input and output
622 elif len(inputs
) >= 2:
626 input_sgn
= [exts(x
.value
, x
.bits
) < 0 for x
in inputs
]
627 output_sgn
= exts(output
.value
, output
.bits
) < 0
628 ov
= 1 if input_sgn
[0] == input_sgn
[1] and \
629 output_sgn
!= input_sgn
[0] else 0
632 input32_sgn
= [exts(x
.value
, 32) < 0 for x
in inputs
]
633 output32_sgn
= exts(output
.value
, 32) < 0
634 ov32
= 1 if input32_sgn
[0] == input32_sgn
[1] and \
635 output32_sgn
!= input32_sgn
[0] else 0
637 self
.spr
['XER'][XER_bits
['OV']] = ov
638 self
.spr
['XER'][XER_bits
['OV32']] = ov32
639 so
= self
.spr
['XER'][XER_bits
['SO']]
641 self
.spr
['XER'][XER_bits
['SO']] = so
643 def handle_comparison(self
, outputs
):
645 assert isinstance(out
, SelectableInt
), \
646 "out zero not a SelectableInt %s" % repr(outputs
)
647 print("handle_comparison", out
.bits
, hex(out
.value
))
648 # TODO - XXX *processor* in 32-bit mode
649 # https://bugs.libre-soc.org/show_bug.cgi?id=424
651 # o32 = exts(out.value, 32)
652 # print ("handle_comparison exts 32 bit", hex(o32))
653 out
= exts(out
.value
, out
.bits
)
654 print("handle_comparison exts", hex(out
))
655 zero
= SelectableInt(out
== 0, 1)
656 positive
= SelectableInt(out
> 0, 1)
657 negative
= SelectableInt(out
< 0, 1)
658 SO
= self
.spr
['XER'][XER_bits
['SO']]
659 print("handle_comparison SO", SO
)
660 cr_field
= selectconcat(negative
, positive
, zero
, SO
)
661 self
.crl
[0].eq(cr_field
)
663 def set_pc(self
, pc_val
):
664 self
.namespace
['NIA'] = SelectableInt(pc_val
, 64)
665 self
.pc
.update(self
.namespace
, self
.is_svp64_mode
)
668 """set up one instruction
671 pc
= self
.pc
.CIA
.value
675 ins
= self
.imem
.ld(pc
, 4, False, True)
677 raise KeyError("no instruction at 0x%x" % pc
)
678 print("setup: 0x%x 0x%x %s" % (pc
, ins
& 0xffffffff, bin(ins
)))
679 print("CIA NIA", self
.respect_pc
, self
.pc
.CIA
.value
, self
.pc
.NIA
.value
)
681 yield self
.dec2
.sv_rm
.eq(0)
682 yield self
.dec2
.dec
.raw_opcode_in
.eq(ins
& 0xffffffff)
683 yield self
.dec2
.dec
.bigendian
.eq(self
.bigendian
)
684 yield self
.dec2
.state
.msr
.eq(self
.msr
.value
)
685 yield self
.dec2
.state
.pc
.eq(pc
)
687 # SVP64. first, check if the opcode is EXT001, and SVP64 id bits set
689 opcode
= yield self
.dec2
.dec
.opcode_in
690 pfx
= SVP64PrefixFields() # TODO should probably use SVP64PrefixDecoder
691 pfx
.insn
.value
= opcode
692 major
= pfx
.major
.asint(msb0
=True) # MSB0 inversion
693 print ("prefix test: opcode:", major
, bin(major
),
694 pfx
.insn
[7] == 0b1, pfx
.insn
[9] == 0b1)
695 self
.is_svp64_mode
= ((major
== 0b000001) and
696 pfx
.insn
[7].value
== 0b1 and
697 pfx
.insn
[9].value
== 0b1)
698 if not self
.is_svp64_mode
:
701 # in SVP64 mode. decode/print out svp64 prefix, get v3.0B instruction
702 print ("svp64.rm", bin(pfx
.rm
.asint(msb0
=True)))
703 print (" svstate.vl", self
.svstate
.vl
.asint(msb0
=True))
704 print (" svstate.mvl", self
.svstate
.maxvl
.asint(msb0
=True))
705 sv_rm
= pfx
.rm
.asint()
706 ins
= self
.imem
.ld(pc
+4, 4, False, True)
707 print(" svsetup: 0x%x 0x%x %s" % (pc
+4, ins
& 0xffffffff, bin(ins
)))
708 yield self
.dec2
.dec
.raw_opcode_in
.eq(ins
& 0xffffffff) # v3.0B suffix
709 yield self
.dec2
.sv_rm
.eq(sv_rm
) # svp64 prefix
712 def execute_one(self
):
713 """execute one instruction
715 # get the disassembly code for this instruction
716 if self
.is_svp64_mode
:
717 code
= self
.disassembly
[self
._pc
+4]
718 print(" svp64 sim-execute", hex(self
._pc
), code
)
720 code
= self
.disassembly
[self
._pc
]
721 print("sim-execute", hex(self
._pc
), code
)
722 opname
= code
.split(' ')[0]
723 yield from self
.call(opname
)
725 # don't use this except in special circumstances
726 if not self
.respect_pc
:
729 print("execute one, CIA NIA", self
.pc
.CIA
.value
, self
.pc
.NIA
.value
)
731 def get_assembly_name(self
):
732 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
733 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
734 dec_insn
= yield self
.dec2
.e
.do
.insn
735 asmcode
= yield self
.dec2
.dec
.op
.asmcode
736 print("get assembly name asmcode", asmcode
, hex(dec_insn
))
737 asmop
= insns
.get(asmcode
, None)
738 int_op
= yield self
.dec2
.dec
.op
.internal_op
740 # sigh reconstruct the assembly instruction name
741 if hasattr(self
.dec2
.e
.do
, "oe"):
742 ov_en
= yield self
.dec2
.e
.do
.oe
.oe
743 ov_ok
= yield self
.dec2
.e
.do
.oe
.ok
747 if hasattr(self
.dec2
.e
.do
, "rc"):
748 rc_en
= yield self
.dec2
.e
.do
.rc
.rc
749 rc_ok
= yield self
.dec2
.e
.do
.rc
.ok
753 # grrrr have to special-case MUL op (see DecodeOE)
754 print("ov %d en %d rc %d en %d op %d" %
755 (ov_ok
, ov_en
, rc_ok
, rc_en
, int_op
))
756 if int_op
in [MicrOp
.OP_MUL_H64
.value
, MicrOp
.OP_MUL_H32
.value
]:
761 if not asmop
.endswith("."): # don't add "." to "andis."
764 if hasattr(self
.dec2
.e
.do
, "lk"):
765 lk
= yield self
.dec2
.e
.do
.lk
768 print("int_op", int_op
)
769 if int_op
in [MicrOp
.OP_B
.value
, MicrOp
.OP_BC
.value
]:
770 AA
= yield self
.dec2
.dec
.fields
.FormI
.AA
[0:-1]
774 spr_msb
= yield from self
.get_spr_msb()
775 if int_op
== MicrOp
.OP_MFCR
.value
:
780 # XXX TODO: for whatever weird reason this doesn't work
781 # https://bugs.libre-soc.org/show_bug.cgi?id=390
782 if int_op
== MicrOp
.OP_MTCRF
.value
:
789 def get_spr_msb(self
):
790 dec_insn
= yield self
.dec2
.e
.do
.insn
791 return dec_insn
& (1 << 20) != 0 # sigh - XFF.spr[-1]?
793 def call(self
, name
):
794 """call(opcode) - the primary execution point for instructions
796 name
= name
.strip() # remove spaces if not already done so
798 print("halted - not executing", name
)
801 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
802 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
803 asmop
= yield from self
.get_assembly_name()
804 print("call", name
, asmop
)
807 int_op
= yield self
.dec2
.dec
.op
.internal_op
808 spr_msb
= yield from self
.get_spr_msb()
810 instr_is_privileged
= False
811 if int_op
in [MicrOp
.OP_ATTN
.value
,
812 MicrOp
.OP_MFMSR
.value
,
813 MicrOp
.OP_MTMSR
.value
,
814 MicrOp
.OP_MTMSRD
.value
,
816 MicrOp
.OP_RFID
.value
]:
817 instr_is_privileged
= True
818 if int_op
in [MicrOp
.OP_MFSPR
.value
,
819 MicrOp
.OP_MTSPR
.value
] and spr_msb
:
820 instr_is_privileged
= True
822 print("is priv", instr_is_privileged
, hex(self
.msr
.value
),
824 # check MSR priv bit and whether op is privileged: if so, throw trap
825 if instr_is_privileged
and self
.msr
[MSRb
.PR
] == 1:
826 self
.TRAP(0x700, PIb
.PRIV
)
827 self
.namespace
['NIA'] = self
.trap_nia
828 self
.pc
.update(self
.namespace
, self
.is_svp64_mode
)
831 # check halted condition
836 # check illegal instruction
838 if name
not in ['mtcrf', 'mtocrf']:
839 illegal
= name
!= asmop
842 print("illegal", name
, asmop
)
843 self
.TRAP(0x700, PIb
.ILLEG
)
844 self
.namespace
['NIA'] = self
.trap_nia
845 self
.pc
.update(self
.namespace
, self
.is_svp64_mode
)
846 print("name %s != %s - calling ILLEGAL trap, PC: %x" %
847 (name
, asmop
, self
.pc
.CIA
.value
))
850 info
= self
.instrs
[name
]
851 yield from self
.prep_namespace(info
.form
, info
.op_fields
)
853 # preserve order of register names
854 input_names
= create_args(list(info
.read_regs
) +
855 list(info
.uninit_regs
))
858 # get SVP64 entry for the current instruction
859 sv_rm
= self
.svp64rm
.instrs
.get(name
)
860 if sv_rm
is not None:
861 dest_cr
, src_cr
, src_byname
, dest_byname
= decode_extra(sv_rm
)
863 dest_cr
, src_cr
, src_byname
, dest_byname
= False, False, {}, {}
864 print ("sv rm", sv_rm
, dest_cr
, src_cr
, src_byname
, dest_byname
)
866 # main input registers (RT, RA ...)
868 for name
in input_names
:
869 # using PowerDecoder2, first, find the decoder index.
870 # (mapping name RA RB RC RS to in1, in2, in3)
871 regnum
, is_vec
= yield from get_pdecode_idx_in(self
.dec2
, name
)
873 # doing this is not part of svp64, it's because output
874 # registers, to be modified, need to be in the namespace.
875 regnum
, is_vec
= yield from get_pdecode_idx_out(self
.dec2
, name
)
876 # in case getting the register number is needed, _RA, _RB
878 self
.namespace
[regname
] = regnum
879 print('reading reg %s %d' % (name
, regnum
), is_vec
)
880 reg_val
= self
.gpr(regnum
)
881 inputs
.append(reg_val
)
883 # "special" registers
884 for special
in info
.special_regs
:
885 if special
in special_sprs
:
886 inputs
.append(self
.spr
[special
])
888 inputs
.append(self
.namespace
[special
])
890 # clear trap (trap) NIA
894 results
= info
.func(self
, *inputs
)
897 # "inject" decorator takes namespace from function locals: we need to
898 # overwrite NIA being overwritten (sigh)
899 if self
.trap_nia
is not None:
900 self
.namespace
['NIA'] = self
.trap_nia
902 print("after func", self
.namespace
['CIA'], self
.namespace
['NIA'])
904 # detect if CA/CA32 already in outputs (sra*, basically)
907 output_names
= create_args(info
.write_regs
)
908 for name
in output_names
:
914 print("carry already done?", bin(already_done
))
915 if hasattr(self
.dec2
.e
.do
, "output_carry"):
916 carry_en
= yield self
.dec2
.e
.do
.output_carry
920 yield from self
.handle_carry_(inputs
, results
, already_done
)
922 # detect if overflow was in return result
925 for name
, output
in zip(output_names
, results
):
926 if name
== 'overflow':
929 if hasattr(self
.dec2
.e
.do
, "oe"):
930 ov_en
= yield self
.dec2
.e
.do
.oe
.oe
931 ov_ok
= yield self
.dec2
.e
.do
.oe
.ok
935 print("internal overflow", overflow
, ov_en
, ov_ok
)
937 yield from self
.handle_overflow(inputs
, results
, overflow
)
939 if hasattr(self
.dec2
.e
.do
, "rc"):
940 rc_en
= yield self
.dec2
.e
.do
.rc
.rc
944 self
.handle_comparison(results
)
946 # any modified return results?
948 for name
, output
in zip(output_names
, results
):
949 if name
== 'overflow': # ignore, done already (above)
951 if isinstance(output
, int):
952 output
= SelectableInt(output
, 256)
953 if name
in ['CA', 'CA32']:
955 print("writing %s to XER" % name
, output
)
956 self
.spr
['XER'][XER_bits
[name
]] = output
.value
958 print("NOT writing %s to XER" % name
, output
)
959 elif name
in info
.special_regs
:
960 print('writing special %s' % name
, output
, special_sprs
)
961 if name
in special_sprs
:
962 self
.spr
[name
] = output
964 self
.namespace
[name
].eq(output
)
966 print('msr written', hex(self
.msr
.value
))
968 regnum
, is_vec
= yield from get_pdecode_idx_out(self
.dec2
,
971 # temporary hack for not having 2nd output
972 regnum
= yield getattr(self
.decoder
, name
)
974 print('writing reg %d %s' % (regnum
, str(output
)), is_vec
)
976 output
= SelectableInt(output
.value
, 64)
977 self
.gpr
[regnum
] = output
979 print("end of call", self
.namespace
['CIA'], self
.namespace
['NIA'])
981 # check if it is the SVSTATE.src/dest step that needs incrementing
982 # this is our Sub-Program-Counter loop from 0 to VL-1
983 if self
.is_svp64_mode
:
984 # XXX twin predication TODO
985 vl
= self
.svstate
.vl
.asint(msb0
=True)
986 mvl
= self
.svstate
.maxvl
.asint(msb0
=True)
987 srcstep
= self
.svstate
.srcstep
.asint(msb0
=True)
988 print (" svstate.vl", vl
)
989 print (" svstate.mvl", mvl
)
990 print (" svstate.srcstep", srcstep
)
991 # check if srcstep needs incrementing by one
993 self
.svstate
.srcstep
+= SelectableInt(1, 7)
994 return # DO NOT allow PC to update whilst Sub-PC loop running
996 self
.svstate
.srcstep
[0:7] = 0
997 print (" svstate.srcstep loop end (PC to update)")
999 # UPDATE program counter
1000 self
.pc
.update(self
.namespace
, self
.is_svp64_mode
)
1004 """Decorator factory.
1006 this decorator will "inject" variables into the function's namespace,
1007 from the *dictionary* in self.namespace. it therefore becomes possible
1008 to make it look like a whole stack of variables which would otherwise
1009 need "self." inserted in front of them (*and* for those variables to be
1010 added to the instance) "appear" in the function.
1012 "self.namespace['SI']" for example becomes accessible as just "SI" but
1013 *only* inside the function, when decorated.
1015 def variable_injector(func
):
1017 def decorator(*args
, **kwargs
):
1019 func_globals
= func
.__globals
__ # Python 2.6+
1020 except AttributeError:
1021 func_globals
= func
.func_globals
# Earlier versions.
1023 context
= args
[0].namespace
# variables to be injected
1024 saved_values
= func_globals
.copy() # Shallow copy of dict.
1025 func_globals
.update(context
)
1026 result
= func(*args
, **kwargs
)
1027 print("globals after", func_globals
['CIA'], func_globals
['NIA'])
1028 print("args[0]", args
[0].namespace
['CIA'],
1029 args
[0].namespace
['NIA'])
1030 args
[0].namespace
= func_globals
1031 #exec (func.__code__, func_globals)
1034 # func_globals = saved_values # Undo changes.
1040 return variable_injector