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 SVP64RMMode
, SVP64PredMode
,
26 SVP64PredInt
, SVP64PredCR
)
28 from soc
.decoder
.power_enums
import SVPtype
30 from soc
.decoder
.helpers
import exts
, gtu
, ltu
, undefined
31 from soc
.consts
import PIb
, MSRb
# big-endian (PowerISA versions)
32 from soc
.consts
import SVP64CROffs
33 from soc
.decoder
.power_svp64
import SVP64RM
, decode_extra
35 from soc
.decoder
.isa
.radixmmu
import RADIX
36 from soc
.decoder
.isa
.mem
import Mem
, swap_order
38 from collections
import namedtuple
42 instruction_info
= namedtuple('instruction_info',
43 'func read_regs uninit_regs write_regs ' +
44 'special_regs op_fields form asmregs')
55 # TODO (lkcl): adjust other registers that should be in a particular order
56 # probably CA, CA32, and CR
74 def create_args(reglist
, extra
=None):
75 retval
= list(OrderedSet(reglist
))
76 retval
.sort(key
=lambda reg
: REG_SORT_ORDER
[reg
])
78 return [extra
] + retval
84 def __init__(self
, decoder
, isacaller
, svstate
, regfile
):
87 self
.isacaller
= isacaller
88 self
.svstate
= svstate
90 self
[i
] = SelectableInt(regfile
[i
], 64)
92 def __call__(self
, ridx
):
95 def set_form(self
, form
):
99 # rnum = rnum.value # only SelectableInt allowed
100 print("GPR getzero?", rnum
)
102 return SelectableInt(0, 64)
105 def _get_regnum(self
, attr
):
106 getform
= self
.sd
.sigforms
[self
.form
]
107 rnum
= getattr(getform
, attr
)
110 def ___getitem__(self
, attr
):
111 """ XXX currently not used
113 rnum
= self
._get
_regnum
(attr
)
114 offs
= self
.svstate
.srcstep
115 print("GPR getitem", attr
, rnum
, "srcoffs", offs
)
116 return self
.regfile
[rnum
]
119 for i
in range(0, len(self
), 8):
122 s
.append("%08x" % self
[i
+j
].value
)
124 print("reg", "%2d" % i
, s
)
128 def __init__(self
, dec2
, initial_sprs
={}):
131 for key
, v
in initial_sprs
.items():
132 if isinstance(key
, SelectableInt
):
134 key
= special_sprs
.get(key
, key
)
135 if isinstance(key
, int):
138 info
= spr_byname
[key
]
139 if not isinstance(v
, SelectableInt
):
140 v
= SelectableInt(v
, info
.length
)
143 def __getitem__(self
, key
):
144 print("get spr", key
)
145 print("dict", self
.items())
146 # if key in special_sprs get the special spr, otherwise return key
147 if isinstance(key
, SelectableInt
):
149 if isinstance(key
, int):
150 key
= spr_dict
[key
].SPR
151 key
= special_sprs
.get(key
, key
)
152 if key
== 'HSRR0': # HACK!
154 if key
== 'HSRR1': # HACK!
157 res
= dict.__getitem
__(self
, key
)
159 if isinstance(key
, int):
162 info
= spr_byname
[key
]
163 dict.__setitem
__(self
, key
, SelectableInt(0, info
.length
))
164 res
= dict.__getitem
__(self
, key
)
165 print("spr returning", key
, res
)
168 def __setitem__(self
, key
, value
):
169 if isinstance(key
, SelectableInt
):
171 if isinstance(key
, int):
172 key
= spr_dict
[key
].SPR
173 print("spr key", key
)
174 key
= special_sprs
.get(key
, key
)
175 if key
== 'HSRR0': # HACK!
176 self
.__setitem
__('SRR0', value
)
177 if key
== 'HSRR1': # HACK!
178 self
.__setitem
__('SRR1', value
)
179 print("setting spr", key
, value
)
180 dict.__setitem
__(self
, key
, value
)
182 def __call__(self
, ridx
):
187 def __init__(self
, pc_init
=0):
188 self
.CIA
= SelectableInt(pc_init
, 64)
189 self
.NIA
= self
.CIA
+ SelectableInt(4, 64) # only true for v3.0B!
191 def update_nia(self
, is_svp64
):
192 increment
= 8 if is_svp64
else 4
193 self
.NIA
= self
.CIA
+ SelectableInt(increment
, 64)
195 def update(self
, namespace
, is_svp64
):
196 """updates the program counter (PC) by 4 if v3.0B mode or 8 if SVP64
198 self
.CIA
= namespace
['NIA'].narrow(64)
199 self
.update_nia(is_svp64
)
200 namespace
['CIA'] = self
.CIA
201 namespace
['NIA'] = self
.NIA
204 # Simple-V: see https://libre-soc.org/openpower/sv
206 def __init__(self
, init
=0):
207 self
.spr
= SelectableInt(init
, 32)
208 # fields of SVSTATE, see https://libre-soc.org/openpower/sv/sprs/
209 self
.maxvl
= FieldSelectableInt(self
.spr
, tuple(range(0,7)))
210 self
.vl
= FieldSelectableInt(self
.spr
, tuple(range(7,14)))
211 self
.srcstep
= FieldSelectableInt(self
.spr
, tuple(range(14,21)))
212 self
.dststep
= FieldSelectableInt(self
.spr
, tuple(range(21,28)))
213 self
.subvl
= FieldSelectableInt(self
.spr
, tuple(range(28,30)))
214 self
.svstep
= FieldSelectableInt(self
.spr
, tuple(range(30,32)))
219 def __init__(self
, init
=0):
220 self
.spr
= SelectableInt(init
, 24)
221 # SVP64 RM fields: see https://libre-soc.org/openpower/sv/svp64/
222 self
.mmode
= FieldSelectableInt(self
.spr
, [0])
223 self
.mask
= FieldSelectableInt(self
.spr
, tuple(range(1,4)))
224 self
.elwidth
= FieldSelectableInt(self
.spr
, tuple(range(4,6)))
225 self
.ewsrc
= FieldSelectableInt(self
.spr
, tuple(range(6,8)))
226 self
.subvl
= FieldSelectableInt(self
.spr
, tuple(range(8,10)))
227 self
.extra
= FieldSelectableInt(self
.spr
, tuple(range(10,19)))
228 self
.mode
= FieldSelectableInt(self
.spr
, tuple(range(19,24)))
229 # these cover the same extra field, split into parts as EXTRA2
230 self
.extra2
= list(range(4))
231 self
.extra2
[0] = FieldSelectableInt(self
.spr
, tuple(range(10,12)))
232 self
.extra2
[1] = FieldSelectableInt(self
.spr
, tuple(range(12,14)))
233 self
.extra2
[2] = FieldSelectableInt(self
.spr
, tuple(range(14,16)))
234 self
.extra2
[3] = FieldSelectableInt(self
.spr
, tuple(range(16,18)))
235 self
.smask
= FieldSelectableInt(self
.spr
, tuple(range(16,19)))
236 # and here as well, but EXTRA3
237 self
.extra3
= list(range(3))
238 self
.extra3
[0] = FieldSelectableInt(self
.spr
, tuple(range(10,13)))
239 self
.extra3
[1] = FieldSelectableInt(self
.spr
, tuple(range(13,16)))
240 self
.extra3
[2] = FieldSelectableInt(self
.spr
, tuple(range(16,19)))
243 SVP64RM_MMODE_SIZE
= len(SVP64RMFields().mmode
.br
)
244 SVP64RM_MASK_SIZE
= len(SVP64RMFields().mask
.br
)
245 SVP64RM_ELWIDTH_SIZE
= len(SVP64RMFields().elwidth
.br
)
246 SVP64RM_EWSRC_SIZE
= len(SVP64RMFields().ewsrc
.br
)
247 SVP64RM_SUBVL_SIZE
= len(SVP64RMFields().subvl
.br
)
248 SVP64RM_EXTRA2_SPEC_SIZE
= len(SVP64RMFields().extra2
[0].br
)
249 SVP64RM_EXTRA3_SPEC_SIZE
= len(SVP64RMFields().extra3
[0].br
)
250 SVP64RM_SMASK_SIZE
= len(SVP64RMFields().smask
.br
)
251 SVP64RM_MODE_SIZE
= len(SVP64RMFields().mode
.br
)
254 # SVP64 Prefix fields: see https://libre-soc.org/openpower/sv/svp64/
255 class SVP64PrefixFields
:
257 self
.insn
= SelectableInt(0, 32)
258 # 6 bit major opcode EXT001, 2 bits "identifying" (7, 9), 24 SV ReMap
259 self
.major
= FieldSelectableInt(self
.insn
, tuple(range(0,6)))
260 self
.pid
= FieldSelectableInt(self
.insn
, (7, 9)) # must be 0b11
261 rmfields
= [6, 8] + list(range(10,32)) # SVP64 24-bit RM (ReMap)
262 self
.rm
= FieldSelectableInt(self
.insn
, rmfields
)
265 SV64P_MAJOR_SIZE
= len(SVP64PrefixFields().major
.br
)
266 SV64P_PID_SIZE
= len(SVP64PrefixFields().pid
.br
)
267 SV64P_RM_SIZE
= len(SVP64PrefixFields().rm
.br
)
269 # decode SVP64 predicate integer to reg number and invert
270 def get_predint(gpr
, mask
):
273 if mask
== SVP64PredInt
.ALWAYS
.value
:
274 return 0xffff_ffff_ffff_ffff
275 if mask
== SVP64PredInt
.R3_UNARY
.value
:
276 return 1 << (gpr(3).value
& 0b111111)
277 if mask
== SVP64PredInt
.R3
.value
:
279 if mask
== SVP64PredInt
.R3_N
.value
:
281 if mask
== SVP64PredInt
.R10
.value
:
283 if mask
== SVP64PredInt
.R10_N
.value
:
284 return ~
gpr(10).value
285 if mask
== SVP64PredInt
.R30
.value
:
287 if mask
== SVP64PredInt
.R30_N
.value
:
288 return ~
gpr(30).value
290 # decode SVP64 predicate CR to reg number and invert status
291 def _get_predcr(mask
):
292 if mask
== SVP64PredCR
.LT
.value
:
294 if mask
== SVP64PredCR
.GE
.value
:
296 if mask
== SVP64PredCR
.GT
.value
:
298 if mask
== SVP64PredCR
.LE
.value
:
300 if mask
== SVP64PredCR
.EQ
.value
:
302 if mask
== SVP64PredCR
.NE
.value
:
304 if mask
== SVP64PredCR
.SO
.value
:
306 if mask
== SVP64PredCR
.NS
.value
:
309 # read individual CR fields (0..VL-1), extract the required bit
310 # and construct the mask
311 def get_predcr(crl
, mask
, vl
):
312 idx
, noninv
= _get_predcr(mask
)
315 cr
= crl
[i
+SVP64CROffs
.CRPred
]
316 if cr
[idx
].value
== noninv
:
321 def get_pdecode_idx_in(dec2
, name
):
323 in1_sel
= yield op
.in1_sel
324 in2_sel
= yield op
.in2_sel
325 in3_sel
= yield op
.in3_sel
326 # get the IN1/2/3 from the decoder (includes SVP64 remap and isvec)
327 in1
= yield dec2
.e
.read_reg1
.data
328 in2
= yield dec2
.e
.read_reg2
.data
329 in3
= yield dec2
.e
.read_reg3
.data
330 in1_isvec
= yield dec2
.in1_isvec
331 in2_isvec
= yield dec2
.in2_isvec
332 in3_isvec
= yield dec2
.in3_isvec
333 print ("get_pdecode_idx_in in1", name
, in1_sel
, In1Sel
.RA
.value
,
335 print ("get_pdecode_idx_in in2", name
, in2_sel
, In2Sel
.RB
.value
,
337 print ("get_pdecode_idx_in in3", name
, in3_sel
, In3Sel
.RS
.value
,
339 # identify which regnames map to in1/2/3
341 if (in1_sel
== In1Sel
.RA
.value
or
342 (in1_sel
== In1Sel
.RA_OR_ZERO
.value
and in1
!= 0)):
343 return in1
, in1_isvec
344 if in1_sel
== In1Sel
.RA_OR_ZERO
.value
:
345 return in1
, in1_isvec
347 if in2_sel
== In2Sel
.RB
.value
:
348 return in2
, in2_isvec
349 if in3_sel
== In3Sel
.RB
.value
:
350 return in3
, in3_isvec
351 # XXX TODO, RC doesn't exist yet!
353 assert False, "RC does not exist yet"
355 if in1_sel
== In1Sel
.RS
.value
:
356 return in1
, in1_isvec
357 if in2_sel
== In2Sel
.RS
.value
:
358 return in2
, in2_isvec
359 if in3_sel
== In3Sel
.RS
.value
:
360 return in3
, in3_isvec
364 def get_pdecode_cr_out(dec2
, name
):
366 out_sel
= yield op
.cr_out
367 out_bitfield
= yield dec2
.dec_cr_out
.cr_bitfield
.data
368 sv_cr_out
= yield op
.sv_cr_out
369 spec
= yield dec2
.crout_svdec
.spec
370 sv_override
= yield dec2
.dec_cr_out
.sv_override
371 # get the IN1/2/3 from the decoder (includes SVP64 remap and isvec)
372 out
= yield dec2
.e
.write_cr
.data
373 o_isvec
= yield dec2
.o_isvec
374 print ("get_pdecode_cr_out", out_sel
, CROutSel
.CR0
.value
, out
, o_isvec
)
375 print (" sv_cr_out", sv_cr_out
)
376 print (" cr_bf", out_bitfield
)
377 print (" spec", spec
)
378 print (" override", sv_override
)
379 # identify which regnames map to out / o2
381 if out_sel
== CROutSel
.CR0
.value
:
383 print ("get_pdecode_idx_out not found", name
)
387 def get_pdecode_idx_out(dec2
, name
):
389 out_sel
= yield op
.out_sel
390 # get the IN1/2/3 from the decoder (includes SVP64 remap and isvec)
391 out
= yield dec2
.e
.write_reg
.data
392 o_isvec
= yield dec2
.o_isvec
393 # identify which regnames map to out / o2
395 print ("get_pdecode_idx_out", out_sel
, OutSel
.RA
.value
, out
, o_isvec
)
396 if out_sel
== OutSel
.RA
.value
:
399 print ("get_pdecode_idx_out", out_sel
, OutSel
.RT
.value
,
400 OutSel
.RT_OR_ZERO
.value
, out
, o_isvec
)
401 if out_sel
== OutSel
.RT
.value
:
403 print ("get_pdecode_idx_out not found", name
)
408 def get_pdecode_idx_out2(dec2
, name
):
410 print ("TODO: get_pdecode_idx_out2", name
)
415 # decoder2 - an instance of power_decoder2
416 # regfile - a list of initial values for the registers
417 # initial_{etc} - initial values for SPRs, Condition Register, Mem, MSR
418 # respect_pc - tracks the program counter. requires initial_insns
419 def __init__(self
, decoder2
, regfile
, initial_sprs
=None, initial_cr
=0,
420 initial_mem
=None, initial_msr
=0,
422 initial_insns
=None, respect_pc
=False,
428 self
.bigendian
= bigendian
430 self
.is_svp64_mode
= False
431 self
.respect_pc
= respect_pc
432 if initial_sprs
is None:
434 if initial_mem
is None:
436 if initial_insns
is None:
438 assert self
.respect_pc
== False, "instructions required to honor pc"
440 print("ISACaller insns", respect_pc
, initial_insns
, disassembly
)
441 print("ISACaller initial_msr", initial_msr
)
443 # "fake program counter" mode (for unit testing)
447 if isinstance(initial_mem
, tuple):
448 self
.fake_pc
= initial_mem
[0]
449 disasm_start
= self
.fake_pc
451 disasm_start
= initial_pc
453 # disassembly: we need this for now (not given from the decoder)
454 self
.disassembly
= {}
456 for i
, code
in enumerate(disassembly
):
457 self
.disassembly
[i
*4 + disasm_start
] = code
459 # set up registers, instruction memory, data memory, PC, SPRs, MSR
460 self
.svp64rm
= SVP64RM()
461 if initial_svstate
is None:
463 if isinstance(initial_svstate
, int):
464 initial_svstate
= SVP64State(initial_svstate
)
465 self
.svstate
= initial_svstate
466 self
.gpr
= GPR(decoder2
, self
, self
.svstate
, regfile
)
467 self
.spr
= SPR(decoder2
, initial_sprs
) # initialise SPRs before MMU
468 self
.mem
= Mem(row_bytes
=8, initial_mem
=initial_mem
)
469 self
.imem
= Mem(row_bytes
=4, initial_mem
=initial_insns
)
470 # MMU mode, redirect underlying Mem through RADIX
472 self
.mem
= RADIX(self
.mem
, self
)
473 self
.imem
= RADIX(self
.imem
, self
)
475 self
.msr
= SelectableInt(initial_msr
, 64) # underlying reg
478 # FPR (same as GPR except for FP nums)
479 # 4.2.2 p124 FPSCR (definitely "separate" - not in SPR)
480 # note that mffs, mcrfs, mtfsf "manage" this FPSCR
481 # 2.3.1 CR (and sub-fields CR0..CR6 - CR0 SO comes from XER.SO)
482 # note that mfocrf, mfcr, mtcr, mtocrf, mcrxrx "manage" CRs
484 # 2.3.2 LR (actually SPR #8) -- Done
485 # 2.3.3 CTR (actually SPR #9) -- Done
486 # 2.3.4 TAR (actually SPR #815)
487 # 3.2.2 p45 XER (actually SPR #1) -- Done
488 # 3.2.3 p46 p232 VRSAVE (actually SPR #256)
490 # create CR then allow portions of it to be "selectable" (below)
491 #rev_cr = int('{:016b}'.format(initial_cr)[::-1], 2)
492 self
.cr
= SelectableInt(initial_cr
, 64) # underlying reg
493 #self.cr = FieldSelectableInt(self._cr, list(range(32, 64)))
495 # "undefined", just set to variable-bit-width int (use exts "max")
496 #self.undefined = SelectableInt(0, 256) # TODO, not hard-code 256!
499 self
.namespace
.update(self
.spr
)
500 self
.namespace
.update({'GPR': self
.gpr
,
503 'memassign': self
.memassign
,
506 'SVSTATE': self
.svstate
.spr
,
509 'undefined': undefined
,
510 'mode_is_64bit': True,
514 # update pc to requested start point
515 self
.set_pc(initial_pc
)
517 # field-selectable versions of Condition Register TODO check bitranges?
520 bits
= tuple(range(i
*4+32, (i
+1)*4+32)) # errr... maybe?
521 _cr
= FieldSelectableInt(self
.cr
, bits
)
523 self
.namespace
["CR%d" % i
] = _cr
525 self
.decoder
= decoder2
.dec
528 def TRAP(self
, trap_addr
=0x700, trap_bit
=PIb
.TRAP
):
529 print("TRAP:", hex(trap_addr
), hex(self
.namespace
['MSR'].value
))
530 # store CIA(+4?) in SRR0, set NIA to 0x700
531 # store MSR in SRR1, set MSR to um errr something, have to check spec
532 self
.spr
['SRR0'].value
= self
.pc
.CIA
.value
533 self
.spr
['SRR1'].value
= self
.namespace
['MSR'].value
534 self
.trap_nia
= SelectableInt(trap_addr
, 64)
535 self
.spr
['SRR1'][trap_bit
] = 1 # change *copy* of MSR in SRR1
537 # set exception bits. TODO: this should, based on the address
538 # in figure 66 p1065 V3.0B and the table figure 65 p1063 set these
539 # bits appropriately. however it turns out that *for now* in all
540 # cases (all trap_addrs) the exact same thing is needed.
541 self
.msr
[MSRb
.IR
] = 0
542 self
.msr
[MSRb
.DR
] = 0
543 self
.msr
[MSRb
.FE0
] = 0
544 self
.msr
[MSRb
.FE1
] = 0
545 self
.msr
[MSRb
.EE
] = 0
546 self
.msr
[MSRb
.RI
] = 0
547 self
.msr
[MSRb
.SF
] = 1
548 self
.msr
[MSRb
.TM
] = 0
549 self
.msr
[MSRb
.VEC
] = 0
550 self
.msr
[MSRb
.VSX
] = 0
551 self
.msr
[MSRb
.PR
] = 0
552 self
.msr
[MSRb
.FP
] = 0
553 self
.msr
[MSRb
.PMM
] = 0
554 self
.msr
[MSRb
.TEs
] = 0
555 self
.msr
[MSRb
.TEe
] = 0
556 self
.msr
[MSRb
.UND
] = 0
557 self
.msr
[MSRb
.LE
] = 1
559 def memassign(self
, ea
, sz
, val
):
560 self
.mem
.memassign(ea
, sz
, val
)
562 def prep_namespace(self
, formname
, op_fields
):
563 # TODO: get field names from form in decoder*1* (not decoder2)
564 # decoder2 is hand-created, and decoder1.sigform is auto-generated
566 # then "yield" fields only from op_fields rather than hard-coded
568 fields
= self
.decoder
.sigforms
[formname
]
569 for name
in op_fields
:
571 sig
= getattr(fields
, name
.upper())
573 sig
= getattr(fields
, name
)
575 # these are all opcode fields involved in index-selection of CR,
576 # and need to do "standard" arithmetic. CR[BA+32] for example
577 # would, if using SelectableInt, only be 5-bit.
578 if name
in ['BF', 'BFA', 'BC', 'BA', 'BB', 'BT', 'BI']:
579 self
.namespace
[name
] = val
581 self
.namespace
[name
] = SelectableInt(val
, sig
.width
)
583 self
.namespace
['XER'] = self
.spr
['XER']
584 self
.namespace
['CA'] = self
.spr
['XER'][XER_bits
['CA']].value
585 self
.namespace
['CA32'] = self
.spr
['XER'][XER_bits
['CA32']].value
587 def handle_carry_(self
, inputs
, outputs
, already_done
):
588 inv_a
= yield self
.dec2
.e
.do
.invert_in
590 inputs
[0] = ~inputs
[0]
592 imm_ok
= yield self
.dec2
.e
.do
.imm_data
.ok
594 imm
= yield self
.dec2
.e
.do
.imm_data
.data
595 inputs
.append(SelectableInt(imm
, 64))
596 assert len(outputs
) >= 1
597 print("outputs", repr(outputs
))
598 if isinstance(outputs
, list) or isinstance(outputs
, tuple):
604 print("gt input", x
, output
)
605 gt
= (gtu(x
, output
))
608 cy
= 1 if any(gts
) else 0
610 if not (1 & already_done
):
611 self
.spr
['XER'][XER_bits
['CA']] = cy
613 print("inputs", already_done
, inputs
)
615 # ARGH... different for OP_ADD... *sigh*...
616 op
= yield self
.dec2
.e
.do
.insn_type
617 if op
== MicrOp
.OP_ADD
.value
:
618 res32
= (output
.value
& (1 << 32)) != 0
619 a32
= (inputs
[0].value
& (1 << 32)) != 0
621 b32
= (inputs
[1].value
& (1 << 32)) != 0
624 cy32
= res32 ^ a32 ^ b32
625 print("CA32 ADD", cy32
)
629 print("input", x
, output
)
630 print(" x[32:64]", x
, x
[32:64])
631 print(" o[32:64]", output
, output
[32:64])
632 gt
= (gtu(x
[32:64], output
[32:64])) == SelectableInt(1, 1)
634 cy32
= 1 if any(gts
) else 0
635 print("CA32", cy32
, gts
)
636 if not (2 & already_done
):
637 self
.spr
['XER'][XER_bits
['CA32']] = cy32
639 def handle_overflow(self
, inputs
, outputs
, div_overflow
):
640 if hasattr(self
.dec2
.e
.do
, "invert_in"):
641 inv_a
= yield self
.dec2
.e
.do
.invert_in
643 inputs
[0] = ~inputs
[0]
645 imm_ok
= yield self
.dec2
.e
.do
.imm_data
.ok
647 imm
= yield self
.dec2
.e
.do
.imm_data
.data
648 inputs
.append(SelectableInt(imm
, 64))
649 assert len(outputs
) >= 1
650 print("handle_overflow", inputs
, outputs
, div_overflow
)
651 if len(inputs
) < 2 and div_overflow
is None:
654 # div overflow is different: it's returned by the pseudo-code
655 # because it's more complex than can be done by analysing the output
656 if div_overflow
is not None:
657 ov
, ov32
= div_overflow
, div_overflow
658 # arithmetic overflow can be done by analysing the input and output
659 elif len(inputs
) >= 2:
663 input_sgn
= [exts(x
.value
, x
.bits
) < 0 for x
in inputs
]
664 output_sgn
= exts(output
.value
, output
.bits
) < 0
665 ov
= 1 if input_sgn
[0] == input_sgn
[1] and \
666 output_sgn
!= input_sgn
[0] else 0
669 input32_sgn
= [exts(x
.value
, 32) < 0 for x
in inputs
]
670 output32_sgn
= exts(output
.value
, 32) < 0
671 ov32
= 1 if input32_sgn
[0] == input32_sgn
[1] and \
672 output32_sgn
!= input32_sgn
[0] else 0
674 self
.spr
['XER'][XER_bits
['OV']] = ov
675 self
.spr
['XER'][XER_bits
['OV32']] = ov32
676 so
= self
.spr
['XER'][XER_bits
['SO']]
678 self
.spr
['XER'][XER_bits
['SO']] = so
680 def handle_comparison(self
, outputs
, cr_idx
=0):
682 assert isinstance(out
, SelectableInt
), \
683 "out zero not a SelectableInt %s" % repr(outputs
)
684 print("handle_comparison", out
.bits
, hex(out
.value
))
685 # TODO - XXX *processor* in 32-bit mode
686 # https://bugs.libre-soc.org/show_bug.cgi?id=424
688 # o32 = exts(out.value, 32)
689 # print ("handle_comparison exts 32 bit", hex(o32))
690 out
= exts(out
.value
, out
.bits
)
691 print("handle_comparison exts", hex(out
))
692 zero
= SelectableInt(out
== 0, 1)
693 positive
= SelectableInt(out
> 0, 1)
694 negative
= SelectableInt(out
< 0, 1)
695 SO
= self
.spr
['XER'][XER_bits
['SO']]
696 print("handle_comparison SO", SO
)
697 cr_field
= selectconcat(negative
, positive
, zero
, SO
)
698 self
.crl
[cr_idx
].eq(cr_field
)
700 def set_pc(self
, pc_val
):
701 self
.namespace
['NIA'] = SelectableInt(pc_val
, 64)
702 self
.pc
.update(self
.namespace
, self
.is_svp64_mode
)
705 """set up one instruction
708 pc
= self
.pc
.CIA
.value
712 ins
= self
.imem
.ld(pc
, 4, False, True, instr_fetch
=True)
714 raise KeyError("no instruction at 0x%x" % pc
)
715 print("setup: 0x%x 0x%x %s" % (pc
, ins
& 0xffffffff, bin(ins
)))
716 print("CIA NIA", self
.respect_pc
, self
.pc
.CIA
.value
, self
.pc
.NIA
.value
)
718 yield self
.dec2
.sv_rm
.eq(0)
719 yield self
.dec2
.dec
.raw_opcode_in
.eq(ins
& 0xffffffff)
720 yield self
.dec2
.dec
.bigendian
.eq(self
.bigendian
)
721 yield self
.dec2
.state
.msr
.eq(self
.msr
.value
)
722 yield self
.dec2
.state
.pc
.eq(pc
)
723 if self
.svstate
is not None:
724 yield self
.dec2
.state
.svstate
.eq(self
.svstate
.spr
.value
)
726 # SVP64. first, check if the opcode is EXT001, and SVP64 id bits set
728 opcode
= yield self
.dec2
.dec
.opcode_in
729 pfx
= SVP64PrefixFields() # TODO should probably use SVP64PrefixDecoder
730 pfx
.insn
.value
= opcode
731 major
= pfx
.major
.asint(msb0
=True) # MSB0 inversion
732 print ("prefix test: opcode:", major
, bin(major
),
733 pfx
.insn
[7] == 0b1, pfx
.insn
[9] == 0b1)
734 self
.is_svp64_mode
= ((major
== 0b000001) and
735 pfx
.insn
[7].value
== 0b1 and
736 pfx
.insn
[9].value
== 0b1)
737 self
.pc
.update_nia(self
.is_svp64_mode
)
738 self
.namespace
['NIA'] = self
.pc
.NIA
739 self
.namespace
['SVSTATE'] = self
.svstate
.spr
740 if not self
.is_svp64_mode
:
743 # in SVP64 mode. decode/print out svp64 prefix, get v3.0B instruction
744 print ("svp64.rm", bin(pfx
.rm
.asint(msb0
=True)))
745 print (" svstate.vl", self
.svstate
.vl
.asint(msb0
=True))
746 print (" svstate.mvl", self
.svstate
.maxvl
.asint(msb0
=True))
747 sv_rm
= pfx
.rm
.asint(msb0
=True)
748 ins
= self
.imem
.ld(pc
+4, 4, False, True, instr_fetch
=True)
749 print(" svsetup: 0x%x 0x%x %s" % (pc
+4, ins
& 0xffffffff, bin(ins
)))
750 yield self
.dec2
.dec
.raw_opcode_in
.eq(ins
& 0xffffffff) # v3.0B suffix
751 yield self
.dec2
.sv_rm
.eq(sv_rm
) # svp64 prefix
754 def execute_one(self
):
755 """execute one instruction
757 # get the disassembly code for this instruction
758 if self
.is_svp64_mode
:
759 code
= self
.disassembly
[self
._pc
+4]
760 print(" svp64 sim-execute", hex(self
._pc
), code
)
762 code
= self
.disassembly
[self
._pc
]
763 print("sim-execute", hex(self
._pc
), code
)
764 opname
= code
.split(' ')[0]
765 yield from self
.call(opname
)
767 # don't use this except in special circumstances
768 if not self
.respect_pc
:
771 print("execute one, CIA NIA", self
.pc
.CIA
.value
, self
.pc
.NIA
.value
)
773 def get_assembly_name(self
):
774 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
775 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
776 dec_insn
= yield self
.dec2
.e
.do
.insn
777 asmcode
= yield self
.dec2
.dec
.op
.asmcode
778 print("get assembly name asmcode", asmcode
, hex(dec_insn
))
779 asmop
= insns
.get(asmcode
, None)
780 int_op
= yield self
.dec2
.dec
.op
.internal_op
782 # sigh reconstruct the assembly instruction name
783 if hasattr(self
.dec2
.e
.do
, "oe"):
784 ov_en
= yield self
.dec2
.e
.do
.oe
.oe
785 ov_ok
= yield self
.dec2
.e
.do
.oe
.ok
789 if hasattr(self
.dec2
.e
.do
, "rc"):
790 rc_en
= yield self
.dec2
.e
.do
.rc
.rc
791 rc_ok
= yield self
.dec2
.e
.do
.rc
.ok
795 # grrrr have to special-case MUL op (see DecodeOE)
796 print("ov %d en %d rc %d en %d op %d" %
797 (ov_ok
, ov_en
, rc_ok
, rc_en
, int_op
))
798 if int_op
in [MicrOp
.OP_MUL_H64
.value
, MicrOp
.OP_MUL_H32
.value
]:
803 if not asmop
.endswith("."): # don't add "." to "andis."
806 if hasattr(self
.dec2
.e
.do
, "lk"):
807 lk
= yield self
.dec2
.e
.do
.lk
810 print("int_op", int_op
)
811 if int_op
in [MicrOp
.OP_B
.value
, MicrOp
.OP_BC
.value
]:
812 AA
= yield self
.dec2
.dec
.fields
.FormI
.AA
[0:-1]
816 spr_msb
= yield from self
.get_spr_msb()
817 if int_op
== MicrOp
.OP_MFCR
.value
:
822 # XXX TODO: for whatever weird reason this doesn't work
823 # https://bugs.libre-soc.org/show_bug.cgi?id=390
824 if int_op
== MicrOp
.OP_MTCRF
.value
:
831 def get_spr_msb(self
):
832 dec_insn
= yield self
.dec2
.e
.do
.insn
833 return dec_insn
& (1 << 20) != 0 # sigh - XFF.spr[-1]?
835 def call(self
, name
):
836 """call(opcode) - the primary execution point for instructions
838 name
= name
.strip() # remove spaces if not already done so
840 print("halted - not executing", name
)
843 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
844 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
845 asmop
= yield from self
.get_assembly_name()
846 print("call", name
, asmop
)
849 int_op
= yield self
.dec2
.dec
.op
.internal_op
850 spr_msb
= yield from self
.get_spr_msb()
852 instr_is_privileged
= False
853 if int_op
in [MicrOp
.OP_ATTN
.value
,
854 MicrOp
.OP_MFMSR
.value
,
855 MicrOp
.OP_MTMSR
.value
,
856 MicrOp
.OP_MTMSRD
.value
,
858 MicrOp
.OP_RFID
.value
]:
859 instr_is_privileged
= True
860 if int_op
in [MicrOp
.OP_MFSPR
.value
,
861 MicrOp
.OP_MTSPR
.value
] and spr_msb
:
862 instr_is_privileged
= True
864 print("is priv", instr_is_privileged
, hex(self
.msr
.value
),
866 # check MSR priv bit and whether op is privileged: if so, throw trap
867 if instr_is_privileged
and self
.msr
[MSRb
.PR
] == 1:
868 self
.TRAP(0x700, PIb
.PRIV
)
869 self
.namespace
['NIA'] = self
.trap_nia
870 self
.pc
.update(self
.namespace
, self
.is_svp64_mode
)
873 # check halted condition
878 # check illegal instruction
880 if name
not in ['mtcrf', 'mtocrf']:
881 illegal
= name
!= asmop
883 # sigh deal with setvl not being supported by binutils (.long)
884 if asmop
.startswith('setvl'):
889 print("illegal", name
, asmop
)
890 self
.TRAP(0x700, PIb
.ILLEG
)
891 self
.namespace
['NIA'] = self
.trap_nia
892 self
.pc
.update(self
.namespace
, self
.is_svp64_mode
)
893 print("name %s != %s - calling ILLEGAL trap, PC: %x" %
894 (name
, asmop
, self
.pc
.CIA
.value
))
897 info
= self
.instrs
[name
]
898 yield from self
.prep_namespace(info
.form
, info
.op_fields
)
900 # preserve order of register names
901 input_names
= create_args(list(info
.read_regs
) +
902 list(info
.uninit_regs
))
905 # get SVP64 entry for the current instruction
906 sv_rm
= self
.svp64rm
.instrs
.get(name
)
907 if sv_rm
is not None:
908 dest_cr
, src_cr
, src_byname
, dest_byname
= decode_extra(sv_rm
)
910 dest_cr
, src_cr
, src_byname
, dest_byname
= False, False, {}, {}
911 print ("sv rm", sv_rm
, dest_cr
, src_cr
, src_byname
, dest_byname
)
913 # get SVSTATE VL (oh and print out some debug stuff)
914 if self
.is_svp64_mode
:
915 vl
= self
.svstate
.vl
.asint(msb0
=True)
916 srcstep
= self
.svstate
.srcstep
.asint(msb0
=True)
917 dststep
= self
.svstate
.srcstep
.asint(msb0
=True)
918 sv_a_nz
= yield self
.dec2
.sv_a_nz
919 in1
= yield self
.dec2
.e
.read_reg1
.data
920 print ("SVP64: VL, srcstep, dststep, sv_a_nz, in1",
921 vl
, srcstep
, dststep
, sv_a_nz
, in1
)
924 srcmask
= dstmask
= 0xffff_ffff_ffff_ffff
925 if self
.is_svp64_mode
:
926 pmode
= yield self
.dec2
.rm_dec
.predmode
927 sv_ptype
= yield self
.dec2
.dec
.op
.SV_Ptype
928 srcpred
= yield self
.dec2
.rm_dec
.srcpred
929 dstpred
= yield self
.dec2
.rm_dec
.dstpred
930 if pmode
== SVP64PredMode
.INT
.value
:
931 srcmask
= dstmask
= get_predint(self
.gpr
, dstpred
)
932 if sv_ptype
== SVPtype
.P2
.value
:
933 srcmask
= get_predint(self
.gpr
, srcpred
)
934 elif pmode
== SVP64PredMode
.CR
.value
:
935 srcmask
= dstmask
= get_predcr(self
.crl
, dstpred
, vl
)
936 if sv_ptype
== SVPtype
.P2
.value
:
937 srcmask
= get_predcr(self
.crl
, srcpred
, vl
)
938 print (" pmode", pmode
)
939 print (" ptype", sv_ptype
)
940 print (" srcmask", bin(srcmask
))
941 print (" dstmask", bin(dstmask
))
943 # okaaay, so here we simply advance srcstep (TODO dststep)
944 # until the predicate mask has a "1" bit... or we run out of VL
945 # let srcstep==VL be the indicator to move to next instruction
946 while (((1<<srcstep
) & srcmask
) == 0) and (srcstep
!= vl
):
947 print (" skip", bin(1<<srcstep
))
950 while (((1<<dststep
) & dstmask
) == 0) and (dststep
!= vl
):
951 print (" skip", bin(1<<dststep
))
954 # update SVSTATE with new srcstep
955 self
.svstate
.srcstep
[0:7] = srcstep
956 self
.svstate
.dststep
[0:7] = dststep
957 self
.namespace
['SVSTATE'] = self
.svstate
.spr
958 yield self
.dec2
.state
.svstate
.eq(self
.svstate
.spr
.value
)
959 yield Settle() # let decoder update
960 srcstep
= self
.svstate
.srcstep
.asint(msb0
=True)
961 dststep
= self
.svstate
.dststep
.asint(msb0
=True)
962 print (" srcstep", srcstep
)
963 print (" dststep", dststep
)
965 # check if end reached (we let srcstep overrun, above)
966 # nothing needs doing (TODO zeroing): just do next instruction
968 self
.svp64_reset_loop()
969 self
.update_pc_next()
972 # VL=0 in SVP64 mode means "do nothing: skip instruction"
973 if self
.is_svp64_mode
and vl
== 0:
974 self
.pc
.update(self
.namespace
, self
.is_svp64_mode
)
975 print("SVP64: VL=0, end of call", self
.namespace
['CIA'],
976 self
.namespace
['NIA'])
979 # main input registers (RT, RA ...)
981 for name
in input_names
:
982 # using PowerDecoder2, first, find the decoder index.
983 # (mapping name RA RB RC RS to in1, in2, in3)
984 regnum
, is_vec
= yield from get_pdecode_idx_in(self
.dec2
, name
)
986 # doing this is not part of svp64, it's because output
987 # registers, to be modified, need to be in the namespace.
988 regnum
, is_vec
= yield from get_pdecode_idx_out(self
.dec2
, name
)
990 # in case getting the register number is needed, _RA, _RB
992 self
.namespace
[regname
] = regnum
993 print('reading reg %s %s' % (name
, str(regnum
)), is_vec
)
994 reg_val
= self
.gpr(regnum
)
995 inputs
.append(reg_val
)
997 # "special" registers
998 for special
in info
.special_regs
:
999 if special
in special_sprs
:
1000 inputs
.append(self
.spr
[special
])
1002 inputs
.append(self
.namespace
[special
])
1004 # clear trap (trap) NIA
1005 self
.trap_nia
= None
1007 # execute actual instruction here
1008 print("inputs", inputs
)
1009 results
= info
.func(self
, *inputs
)
1010 print("results", results
)
1012 # "inject" decorator takes namespace from function locals: we need to
1013 # overwrite NIA being overwritten (sigh)
1014 if self
.trap_nia
is not None:
1015 self
.namespace
['NIA'] = self
.trap_nia
1017 print("after func", self
.namespace
['CIA'], self
.namespace
['NIA'])
1019 # detect if CA/CA32 already in outputs (sra*, basically)
1022 output_names
= create_args(info
.write_regs
)
1023 for name
in output_names
:
1029 print("carry already done?", bin(already_done
))
1030 if hasattr(self
.dec2
.e
.do
, "output_carry"):
1031 carry_en
= yield self
.dec2
.e
.do
.output_carry
1035 yield from self
.handle_carry_(inputs
, results
, already_done
)
1037 # detect if overflow was in return result
1040 for name
, output
in zip(output_names
, results
):
1041 if name
== 'overflow':
1044 if hasattr(self
.dec2
.e
.do
, "oe"):
1045 ov_en
= yield self
.dec2
.e
.do
.oe
.oe
1046 ov_ok
= yield self
.dec2
.e
.do
.oe
.ok
1050 print("internal overflow", overflow
, ov_en
, ov_ok
)
1052 yield from self
.handle_overflow(inputs
, results
, overflow
)
1054 if hasattr(self
.dec2
.e
.do
, "rc"):
1055 rc_en
= yield self
.dec2
.e
.do
.rc
.rc
1059 regnum
, is_vec
= yield from get_pdecode_cr_out(self
.dec2
, "CR0")
1060 self
.handle_comparison(results
, regnum
)
1062 # any modified return results?
1064 for name
, output
in zip(output_names
, results
):
1065 if name
== 'overflow': # ignore, done already (above)
1067 if isinstance(output
, int):
1068 output
= SelectableInt(output
, 256)
1069 if name
in ['CA', 'CA32']:
1071 print("writing %s to XER" % name
, output
)
1072 self
.spr
['XER'][XER_bits
[name
]] = output
.value
1074 print("NOT writing %s to XER" % name
, output
)
1075 elif name
in info
.special_regs
:
1076 print('writing special %s' % name
, output
, special_sprs
)
1077 if name
in special_sprs
:
1078 self
.spr
[name
] = output
1080 self
.namespace
[name
].eq(output
)
1082 print('msr written', hex(self
.msr
.value
))
1084 regnum
, is_vec
= yield from get_pdecode_idx_out(self
.dec2
,
1087 # temporary hack for not having 2nd output
1088 regnum
= yield getattr(self
.decoder
, name
)
1090 print('writing reg %d %s' % (regnum
, str(output
)), is_vec
)
1091 if output
.bits
> 64:
1092 output
= SelectableInt(output
.value
, 64)
1093 self
.gpr
[regnum
] = output
1095 # check if it is the SVSTATE.src/dest step that needs incrementing
1096 # this is our Sub-Program-Counter loop from 0 to VL-1
1097 if self
.is_svp64_mode
:
1098 # XXX twin predication TODO
1099 vl
= self
.svstate
.vl
.asint(msb0
=True)
1100 mvl
= self
.svstate
.maxvl
.asint(msb0
=True)
1101 srcstep
= self
.svstate
.srcstep
.asint(msb0
=True)
1102 dststep
= self
.svstate
.srcstep
.asint(msb0
=True)
1103 sv_ptype
= yield self
.dec2
.dec
.op
.SV_Ptype
1104 no_out_vec
= not (yield self
.dec2
.no_out_vec
)
1105 no_in_vec
= not (yield self
.dec2
.no_in_vec
)
1106 print (" svstate.vl", vl
)
1107 print (" svstate.mvl", mvl
)
1108 print (" svstate.srcstep", srcstep
)
1109 print (" svstate.dststep", dststep
)
1110 print (" no_out_vec", no_out_vec
)
1111 print (" no_in_vec", no_in_vec
)
1112 print (" sv_ptype", sv_ptype
, sv_ptype
== SVPtype
.P2
.value
)
1113 # check if srcstep needs incrementing by one, stop PC advancing
1114 # svp64 loop can end early if the dest is scalar for single-pred
1115 # but for 2-pred both src/dest have to be checked.
1116 # XXX this might not be true! it may just be LD/ST
1117 if sv_ptype
== SVPtype
.P2
.value
:
1118 svp64_is_vector
= (no_out_vec
or no_in_vec
)
1120 svp64_is_vector
= no_out_vec
1121 if svp64_is_vector
and srcstep
!= vl
-1:
1122 self
.svstate
.srcstep
+= SelectableInt(1, 7)
1123 self
.svstate
.dststep
+= SelectableInt(1, 7)
1124 self
.pc
.NIA
.value
= self
.pc
.CIA
.value
1125 self
.namespace
['NIA'] = self
.pc
.NIA
1126 self
.namespace
['SVSTATE'] = self
.svstate
.spr
1127 print("end of sub-pc call", self
.namespace
['CIA'],
1128 self
.namespace
['NIA'])
1129 return # DO NOT allow PC to update whilst Sub-PC loop running
1130 # reset loop to zero
1131 self
.svp64_reset_loop()
1133 self
.update_pc_next()
1135 def update_pc_next(self
):
1136 # UPDATE program counter
1137 self
.pc
.update(self
.namespace
, self
.is_svp64_mode
)
1138 self
.svstate
.spr
= self
.namespace
['SVSTATE']
1139 print("end of call", self
.namespace
['CIA'],
1140 self
.namespace
['NIA'],
1141 self
.namespace
['SVSTATE'])
1143 def svp64_reset_loop(self
):
1144 self
.svstate
.srcstep
[0:7] = 0
1145 self
.svstate
.dststep
[0:7] = 0
1146 print (" svstate.srcstep loop end (PC to update)")
1147 self
.pc
.update_nia(self
.is_svp64_mode
)
1148 self
.namespace
['NIA'] = self
.pc
.NIA
1149 self
.namespace
['SVSTATE'] = self
.svstate
.spr
1152 """Decorator factory.
1154 this decorator will "inject" variables into the function's namespace,
1155 from the *dictionary* in self.namespace. it therefore becomes possible
1156 to make it look like a whole stack of variables which would otherwise
1157 need "self." inserted in front of them (*and* for those variables to be
1158 added to the instance) "appear" in the function.
1160 "self.namespace['SI']" for example becomes accessible as just "SI" but
1161 *only* inside the function, when decorated.
1163 def variable_injector(func
):
1165 def decorator(*args
, **kwargs
):
1167 func_globals
= func
.__globals
__ # Python 2.6+
1168 except AttributeError:
1169 func_globals
= func
.func_globals
# Earlier versions.
1171 context
= args
[0].namespace
# variables to be injected
1172 saved_values
= func_globals
.copy() # Shallow copy of dict.
1173 func_globals
.update(context
)
1174 result
= func(*args
, **kwargs
)
1175 print("globals after", func_globals
['CIA'], func_globals
['NIA'])
1176 print("args[0]", args
[0].namespace
['CIA'],
1177 args
[0].namespace
['NIA'],
1178 args
[0].namespace
['SVSTATE'])
1179 args
[0].namespace
= func_globals
1180 #exec (func.__code__, func_globals)
1183 # func_globals = saved_values # Undo changes.
1189 return variable_injector