**FOR NOW** LD/ST relies on detection of twin-predication to determine
[soc.git] / src / soc / decoder / isa / caller.py
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
6
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.
10
11 related bugs:
12
13 * https://bugs.libre-soc.org/show_bug.cgi?id=424
14 """
15
16 from nmigen.back.pysim import Settle
17 from functools import wraps
18 from copy import copy
19 from soc.decoder.orderedset import OrderedSet
20 from soc.decoder.selectable_int import (FieldSelectableInt, SelectableInt,
21 selectconcat)
22 from soc.decoder.power_enums import (spr_dict, spr_byname, XER_bits,
23 insns, MicrOp, In1Sel, In2Sel, In3Sel,
24 OutSel, CROutSel)
25
26 from soc.decoder.power_enums import SVPtype
27
28 from soc.decoder.helpers import exts, gtu, ltu, undefined
29 from soc.consts import PIb, MSRb # big-endian (PowerISA versions)
30 from soc.decoder.power_svp64 import SVP64RM, decode_extra
31
32 from soc.decoder.isa.radixmmu import RADIX
33 from soc.decoder.isa.mem import Mem, swap_order
34
35 from collections import namedtuple
36 import math
37 import sys
38
39 instruction_info = namedtuple('instruction_info',
40 'func read_regs uninit_regs write_regs ' +
41 'special_regs op_fields form asmregs')
42
43 special_sprs = {
44 'LR': 8,
45 'CTR': 9,
46 'TAR': 815,
47 'XER': 1,
48 'VRSAVE': 256}
49
50
51 REG_SORT_ORDER = {
52 # TODO (lkcl): adjust other registers that should be in a particular order
53 # probably CA, CA32, and CR
54 "RT": 0,
55 "RA": 0,
56 "RB": 0,
57 "RS": 0,
58 "CR": 0,
59 "LR": 0,
60 "CTR": 0,
61 "TAR": 0,
62 "CA": 0,
63 "CA32": 0,
64 "MSR": 0,
65
66 "overflow": 1,
67 }
68
69
70 def create_args(reglist, extra=None):
71 retval = list(OrderedSet(reglist))
72 retval.sort(key=lambda reg: REG_SORT_ORDER[reg])
73 if extra is not None:
74 return [extra] + retval
75 return retval
76
77
78
79 class GPR(dict):
80 def __init__(self, decoder, isacaller, svstate, regfile):
81 dict.__init__(self)
82 self.sd = decoder
83 self.isacaller = isacaller
84 self.svstate = svstate
85 for i in range(32):
86 self[i] = SelectableInt(regfile[i], 64)
87
88 def __call__(self, ridx):
89 return self[ridx]
90
91 def set_form(self, form):
92 self.form = form
93
94 def getz(self, rnum):
95 # rnum = rnum.value # only SelectableInt allowed
96 print("GPR getzero?", rnum)
97 if rnum == 0:
98 return SelectableInt(0, 64)
99 return self[rnum]
100
101 def _get_regnum(self, attr):
102 getform = self.sd.sigforms[self.form]
103 rnum = getattr(getform, attr)
104 return rnum
105
106 def ___getitem__(self, attr):
107 """ XXX currently not used
108 """
109 rnum = self._get_regnum(attr)
110 offs = self.svstate.srcstep
111 print("GPR getitem", attr, rnum, "srcoffs", offs)
112 return self.regfile[rnum]
113
114 def dump(self):
115 for i in range(0, len(self), 8):
116 s = []
117 for j in range(8):
118 s.append("%08x" % self[i+j].value)
119 s = ' '.join(s)
120 print("reg", "%2d" % i, s)
121
122
123 class PC:
124 def __init__(self, pc_init=0):
125 self.CIA = SelectableInt(pc_init, 64)
126 self.NIA = self.CIA + SelectableInt(4, 64) # only true for v3.0B!
127
128 def update_nia(self, is_svp64):
129 increment = 8 if is_svp64 else 4
130 self.NIA = self.CIA + SelectableInt(increment, 64)
131
132 def update(self, namespace, is_svp64):
133 """updates the program counter (PC) by 4 if v3.0B mode or 8 if SVP64
134 """
135 self.CIA = namespace['NIA'].narrow(64)
136 self.update_nia(is_svp64)
137 namespace['CIA'] = self.CIA
138 namespace['NIA'] = self.NIA
139
140
141 # Simple-V: see https://libre-soc.org/openpower/sv
142 class SVP64State:
143 def __init__(self, init=0):
144 self.spr = SelectableInt(init, 32)
145 # fields of SVSTATE, see https://libre-soc.org/openpower/sv/sprs/
146 self.maxvl = FieldSelectableInt(self.spr, tuple(range(0,7)))
147 self.vl = FieldSelectableInt(self.spr, tuple(range(7,14)))
148 self.srcstep = FieldSelectableInt(self.spr, tuple(range(14,21)))
149 self.dststep = FieldSelectableInt(self.spr, tuple(range(21,28)))
150 self.subvl = FieldSelectableInt(self.spr, tuple(range(28,30)))
151 self.svstep = FieldSelectableInt(self.spr, tuple(range(30,32)))
152
153
154 # SVP64 ReMap field
155 class SVP64RMFields:
156 def __init__(self, init=0):
157 self.spr = SelectableInt(init, 24)
158 # SVP64 RM fields: see https://libre-soc.org/openpower/sv/svp64/
159 self.mmode = FieldSelectableInt(self.spr, [0])
160 self.mask = FieldSelectableInt(self.spr, tuple(range(1,4)))
161 self.elwidth = FieldSelectableInt(self.spr, tuple(range(4,6)))
162 self.ewsrc = FieldSelectableInt(self.spr, tuple(range(6,8)))
163 self.subvl = FieldSelectableInt(self.spr, tuple(range(8,10)))
164 self.extra = FieldSelectableInt(self.spr, tuple(range(10,19)))
165 self.mode = FieldSelectableInt(self.spr, tuple(range(19,24)))
166 # these cover the same extra field, split into parts as EXTRA2
167 self.extra2 = list(range(4))
168 self.extra2[0] = FieldSelectableInt(self.spr, tuple(range(10,12)))
169 self.extra2[1] = FieldSelectableInt(self.spr, tuple(range(12,14)))
170 self.extra2[2] = FieldSelectableInt(self.spr, tuple(range(14,16)))
171 self.extra2[3] = FieldSelectableInt(self.spr, tuple(range(16,18)))
172 self.smask = FieldSelectableInt(self.spr, tuple(range(16,19)))
173 # and here as well, but EXTRA3
174 self.extra3 = list(range(3))
175 self.extra3[0] = FieldSelectableInt(self.spr, tuple(range(10,13)))
176 self.extra3[1] = FieldSelectableInt(self.spr, tuple(range(13,16)))
177 self.extra3[2] = FieldSelectableInt(self.spr, tuple(range(16,19)))
178
179
180 SVP64RM_MMODE_SIZE = len(SVP64RMFields().mmode.br)
181 SVP64RM_MASK_SIZE = len(SVP64RMFields().mask.br)
182 SVP64RM_ELWIDTH_SIZE = len(SVP64RMFields().elwidth.br)
183 SVP64RM_EWSRC_SIZE = len(SVP64RMFields().ewsrc.br)
184 SVP64RM_SUBVL_SIZE = len(SVP64RMFields().subvl.br)
185 SVP64RM_EXTRA2_SPEC_SIZE = len(SVP64RMFields().extra2[0].br)
186 SVP64RM_EXTRA3_SPEC_SIZE = len(SVP64RMFields().extra3[0].br)
187 SVP64RM_SMASK_SIZE = len(SVP64RMFields().smask.br)
188 SVP64RM_MODE_SIZE = len(SVP64RMFields().mode.br)
189
190
191 # SVP64 Prefix fields: see https://libre-soc.org/openpower/sv/svp64/
192 class SVP64PrefixFields:
193 def __init__(self):
194 self.insn = SelectableInt(0, 32)
195 # 6 bit major opcode EXT001, 2 bits "identifying" (7, 9), 24 SV ReMap
196 self.major = FieldSelectableInt(self.insn, tuple(range(0,6)))
197 self.pid = FieldSelectableInt(self.insn, (7, 9)) # must be 0b11
198 rmfields = [6, 8] + list(range(10,32)) # SVP64 24-bit RM (ReMap)
199 self.rm = FieldSelectableInt(self.insn, rmfields)
200
201
202 SV64P_MAJOR_SIZE = len(SVP64PrefixFields().major.br)
203 SV64P_PID_SIZE = len(SVP64PrefixFields().pid.br)
204 SV64P_RM_SIZE = len(SVP64PrefixFields().rm.br)
205
206
207 class SPR(dict):
208 def __init__(self, dec2, initial_sprs={}):
209 self.sd = dec2
210 dict.__init__(self)
211 for key, v in initial_sprs.items():
212 if isinstance(key, SelectableInt):
213 key = key.value
214 key = special_sprs.get(key, key)
215 if isinstance(key, int):
216 info = spr_dict[key]
217 else:
218 info = spr_byname[key]
219 if not isinstance(v, SelectableInt):
220 v = SelectableInt(v, info.length)
221 self[key] = v
222
223 def __getitem__(self, key):
224 print("get spr", key)
225 print("dict", self.items())
226 # if key in special_sprs get the special spr, otherwise return key
227 if isinstance(key, SelectableInt):
228 key = key.value
229 if isinstance(key, int):
230 key = spr_dict[key].SPR
231 key = special_sprs.get(key, key)
232 if key == 'HSRR0': # HACK!
233 key = 'SRR0'
234 if key == 'HSRR1': # HACK!
235 key = 'SRR1'
236 if key in self:
237 res = dict.__getitem__(self, key)
238 else:
239 if isinstance(key, int):
240 info = spr_dict[key]
241 else:
242 info = spr_byname[key]
243 dict.__setitem__(self, key, SelectableInt(0, info.length))
244 res = dict.__getitem__(self, key)
245 print("spr returning", key, res)
246 return res
247
248 def __setitem__(self, key, value):
249 if isinstance(key, SelectableInt):
250 key = key.value
251 if isinstance(key, int):
252 key = spr_dict[key].SPR
253 print("spr key", key)
254 key = special_sprs.get(key, key)
255 if key == 'HSRR0': # HACK!
256 self.__setitem__('SRR0', value)
257 if key == 'HSRR1': # HACK!
258 self.__setitem__('SRR1', value)
259 print("setting spr", key, value)
260 dict.__setitem__(self, key, value)
261
262 def __call__(self, ridx):
263 return self[ridx]
264
265 def get_pdecode_idx_in(dec2, name):
266 op = dec2.dec.op
267 in1_sel = yield op.in1_sel
268 in2_sel = yield op.in2_sel
269 in3_sel = yield op.in3_sel
270 # get the IN1/2/3 from the decoder (includes SVP64 remap and isvec)
271 in1 = yield dec2.e.read_reg1.data
272 in2 = yield dec2.e.read_reg2.data
273 in3 = yield dec2.e.read_reg3.data
274 in1_isvec = yield dec2.in1_isvec
275 in2_isvec = yield dec2.in2_isvec
276 in3_isvec = yield dec2.in3_isvec
277 print ("get_pdecode_idx_in in1", name, in1_sel, In1Sel.RA.value,
278 in1, in1_isvec)
279 print ("get_pdecode_idx_in in2", name, in2_sel, In2Sel.RB.value,
280 in2, in2_isvec)
281 print ("get_pdecode_idx_in in3", name, in3_sel, In3Sel.RS.value,
282 in3, in3_isvec)
283 # identify which regnames map to in1/2/3
284 if name == 'RA':
285 if (in1_sel == In1Sel.RA.value or
286 (in1_sel == In1Sel.RA_OR_ZERO.value and in1 != 0)):
287 return in1, in1_isvec
288 if in1_sel == In1Sel.RA_OR_ZERO.value:
289 return in1, in1_isvec
290 elif name == 'RB':
291 if in2_sel == In2Sel.RB.value:
292 return in2, in2_isvec
293 if in3_sel == In3Sel.RB.value:
294 return in3, in3_isvec
295 # XXX TODO, RC doesn't exist yet!
296 elif name == 'RC':
297 assert False, "RC does not exist yet"
298 elif name == 'RS':
299 if in1_sel == In1Sel.RS.value:
300 return in1, in1_isvec
301 if in2_sel == In2Sel.RS.value:
302 return in2, in2_isvec
303 if in3_sel == In3Sel.RS.value:
304 return in3, in3_isvec
305 return None, False
306
307
308 def get_pdecode_cr_out(dec2, name):
309 op = dec2.dec.op
310 out_sel = yield op.cr_out
311 out_bitfield = yield dec2.dec_cr_out.cr_bitfield.data
312 sv_cr_out = yield op.sv_cr_out
313 spec = yield dec2.crout_svdec.spec
314 sv_override = yield dec2.dec_cr_out.sv_override
315 # get the IN1/2/3 from the decoder (includes SVP64 remap and isvec)
316 out = yield dec2.e.write_cr.data
317 o_isvec = yield dec2.o_isvec
318 print ("get_pdecode_cr_out", out_sel, CROutSel.CR0.value, out, o_isvec)
319 print (" sv_cr_out", sv_cr_out)
320 print (" cr_bf", out_bitfield)
321 print (" spec", spec)
322 print (" override", sv_override)
323 # identify which regnames map to out / o2
324 if name == 'CR0':
325 if out_sel == CROutSel.CR0.value:
326 return out, o_isvec
327 print ("get_pdecode_idx_out not found", name)
328 return None, False
329
330
331 def get_pdecode_idx_out(dec2, name):
332 op = dec2.dec.op
333 out_sel = yield op.out_sel
334 # get the IN1/2/3 from the decoder (includes SVP64 remap and isvec)
335 out = yield dec2.e.write_reg.data
336 o_isvec = yield dec2.o_isvec
337 print ("get_pdecode_idx_out", out_sel, OutSel.RA.value, out, o_isvec)
338 # identify which regnames map to out / o2
339 if name == 'RA':
340 if out_sel == OutSel.RA.value:
341 return out, o_isvec
342 elif name == 'RT':
343 if out_sel == OutSel.RT.value:
344 return out, o_isvec
345 print ("get_pdecode_idx_out not found", name)
346 return None, False
347
348
349 # XXX TODO
350 def get_pdecode_idx_out2(dec2, name):
351 op = dec2.dec.op
352 print ("TODO: get_pdecode_idx_out2", name)
353 return None, False
354
355
356 class ISACaller:
357 # decoder2 - an instance of power_decoder2
358 # regfile - a list of initial values for the registers
359 # initial_{etc} - initial values for SPRs, Condition Register, Mem, MSR
360 # respect_pc - tracks the program counter. requires initial_insns
361 def __init__(self, decoder2, regfile, initial_sprs=None, initial_cr=0,
362 initial_mem=None, initial_msr=0,
363 initial_svstate=0,
364 initial_insns=None, respect_pc=False,
365 disassembly=None,
366 initial_pc=0,
367 bigendian=False,
368 mmu=False):
369
370 self.bigendian = bigendian
371 self.halted = False
372 self.is_svp64_mode = False
373 self.respect_pc = respect_pc
374 if initial_sprs is None:
375 initial_sprs = {}
376 if initial_mem is None:
377 initial_mem = {}
378 if initial_insns is None:
379 initial_insns = {}
380 assert self.respect_pc == False, "instructions required to honor pc"
381
382 print("ISACaller insns", respect_pc, initial_insns, disassembly)
383 print("ISACaller initial_msr", initial_msr)
384
385 # "fake program counter" mode (for unit testing)
386 self.fake_pc = 0
387 disasm_start = 0
388 if not respect_pc:
389 if isinstance(initial_mem, tuple):
390 self.fake_pc = initial_mem[0]
391 disasm_start = self.fake_pc
392 else:
393 disasm_start = initial_pc
394
395 # disassembly: we need this for now (not given from the decoder)
396 self.disassembly = {}
397 if disassembly:
398 for i, code in enumerate(disassembly):
399 self.disassembly[i*4 + disasm_start] = code
400
401 # set up registers, instruction memory, data memory, PC, SPRs, MSR
402 self.svp64rm = SVP64RM()
403 if isinstance(initial_svstate, int):
404 initial_svstate = SVP64State(initial_svstate)
405 self.svstate = initial_svstate
406 self.gpr = GPR(decoder2, self, self.svstate, regfile)
407 self.spr = SPR(decoder2, initial_sprs) # initialise SPRs before MMU
408 self.mem = Mem(row_bytes=8, initial_mem=initial_mem)
409 if mmu:
410 self.mem = RADIX(self.mem, self)
411 self.imem = Mem(row_bytes=4, initial_mem=initial_insns)
412 self.pc = PC()
413 self.msr = SelectableInt(initial_msr, 64) # underlying reg
414
415 # TODO, needed here:
416 # FPR (same as GPR except for FP nums)
417 # 4.2.2 p124 FPSCR (definitely "separate" - not in SPR)
418 # note that mffs, mcrfs, mtfsf "manage" this FPSCR
419 # 2.3.1 CR (and sub-fields CR0..CR6 - CR0 SO comes from XER.SO)
420 # note that mfocrf, mfcr, mtcr, mtocrf, mcrxrx "manage" CRs
421 # -- Done
422 # 2.3.2 LR (actually SPR #8) -- Done
423 # 2.3.3 CTR (actually SPR #9) -- Done
424 # 2.3.4 TAR (actually SPR #815)
425 # 3.2.2 p45 XER (actually SPR #1) -- Done
426 # 3.2.3 p46 p232 VRSAVE (actually SPR #256)
427
428 # create CR then allow portions of it to be "selectable" (below)
429 #rev_cr = int('{:016b}'.format(initial_cr)[::-1], 2)
430 self.cr = SelectableInt(initial_cr, 64) # underlying reg
431 #self.cr = FieldSelectableInt(self._cr, list(range(32, 64)))
432
433 # "undefined", just set to variable-bit-width int (use exts "max")
434 #self.undefined = SelectableInt(0, 256) # TODO, not hard-code 256!
435
436 self.namespace = {}
437 self.namespace.update(self.spr)
438 self.namespace.update({'GPR': self.gpr,
439 'MEM': self.mem,
440 'SPR': self.spr,
441 'memassign': self.memassign,
442 'NIA': self.pc.NIA,
443 'CIA': self.pc.CIA,
444 'CR': self.cr,
445 'MSR': self.msr,
446 'undefined': undefined,
447 'mode_is_64bit': True,
448 'SO': XER_bits['SO']
449 })
450
451 # update pc to requested start point
452 self.set_pc(initial_pc)
453
454 # field-selectable versions of Condition Register TODO check bitranges?
455 self.crl = []
456 for i in range(8):
457 bits = tuple(range(i*4+32, (i+1)*4+32)) # errr... maybe?
458 _cr = FieldSelectableInt(self.cr, bits)
459 self.crl.append(_cr)
460 self.namespace["CR%d" % i] = _cr
461
462 self.decoder = decoder2.dec
463 self.dec2 = decoder2
464
465 def TRAP(self, trap_addr=0x700, trap_bit=PIb.TRAP):
466 print("TRAP:", hex(trap_addr), hex(self.namespace['MSR'].value))
467 # store CIA(+4?) in SRR0, set NIA to 0x700
468 # store MSR in SRR1, set MSR to um errr something, have to check spec
469 self.spr['SRR0'].value = self.pc.CIA.value
470 self.spr['SRR1'].value = self.namespace['MSR'].value
471 self.trap_nia = SelectableInt(trap_addr, 64)
472 self.spr['SRR1'][trap_bit] = 1 # change *copy* of MSR in SRR1
473
474 # set exception bits. TODO: this should, based on the address
475 # in figure 66 p1065 V3.0B and the table figure 65 p1063 set these
476 # bits appropriately. however it turns out that *for now* in all
477 # cases (all trap_addrs) the exact same thing is needed.
478 self.msr[MSRb.IR] = 0
479 self.msr[MSRb.DR] = 0
480 self.msr[MSRb.FE0] = 0
481 self.msr[MSRb.FE1] = 0
482 self.msr[MSRb.EE] = 0
483 self.msr[MSRb.RI] = 0
484 self.msr[MSRb.SF] = 1
485 self.msr[MSRb.TM] = 0
486 self.msr[MSRb.VEC] = 0
487 self.msr[MSRb.VSX] = 0
488 self.msr[MSRb.PR] = 0
489 self.msr[MSRb.FP] = 0
490 self.msr[MSRb.PMM] = 0
491 self.msr[MSRb.TEs] = 0
492 self.msr[MSRb.TEe] = 0
493 self.msr[MSRb.UND] = 0
494 self.msr[MSRb.LE] = 1
495
496 def memassign(self, ea, sz, val):
497 self.mem.memassign(ea, sz, val)
498
499 def prep_namespace(self, formname, op_fields):
500 # TODO: get field names from form in decoder*1* (not decoder2)
501 # decoder2 is hand-created, and decoder1.sigform is auto-generated
502 # from spec
503 # then "yield" fields only from op_fields rather than hard-coded
504 # list, here.
505 fields = self.decoder.sigforms[formname]
506 for name in op_fields:
507 if name == 'spr':
508 sig = getattr(fields, name.upper())
509 else:
510 sig = getattr(fields, name)
511 val = yield sig
512 # these are all opcode fields involved in index-selection of CR,
513 # and need to do "standard" arithmetic. CR[BA+32] for example
514 # would, if using SelectableInt, only be 5-bit.
515 if name in ['BF', 'BFA', 'BC', 'BA', 'BB', 'BT', 'BI']:
516 self.namespace[name] = val
517 else:
518 self.namespace[name] = SelectableInt(val, sig.width)
519
520 self.namespace['XER'] = self.spr['XER']
521 self.namespace['CA'] = self.spr['XER'][XER_bits['CA']].value
522 self.namespace['CA32'] = self.spr['XER'][XER_bits['CA32']].value
523
524 def handle_carry_(self, inputs, outputs, already_done):
525 inv_a = yield self.dec2.e.do.invert_in
526 if inv_a:
527 inputs[0] = ~inputs[0]
528
529 imm_ok = yield self.dec2.e.do.imm_data.ok
530 if imm_ok:
531 imm = yield self.dec2.e.do.imm_data.data
532 inputs.append(SelectableInt(imm, 64))
533 assert len(outputs) >= 1
534 print("outputs", repr(outputs))
535 if isinstance(outputs, list) or isinstance(outputs, tuple):
536 output = outputs[0]
537 else:
538 output = outputs
539 gts = []
540 for x in inputs:
541 print("gt input", x, output)
542 gt = (gtu(x, output))
543 gts.append(gt)
544 print(gts)
545 cy = 1 if any(gts) else 0
546 print("CA", cy, gts)
547 if not (1 & already_done):
548 self.spr['XER'][XER_bits['CA']] = cy
549
550 print("inputs", already_done, inputs)
551 # 32 bit carry
552 # ARGH... different for OP_ADD... *sigh*...
553 op = yield self.dec2.e.do.insn_type
554 if op == MicrOp.OP_ADD.value:
555 res32 = (output.value & (1 << 32)) != 0
556 a32 = (inputs[0].value & (1 << 32)) != 0
557 if len(inputs) >= 2:
558 b32 = (inputs[1].value & (1 << 32)) != 0
559 else:
560 b32 = False
561 cy32 = res32 ^ a32 ^ b32
562 print("CA32 ADD", cy32)
563 else:
564 gts = []
565 for x in inputs:
566 print("input", x, output)
567 print(" x[32:64]", x, x[32:64])
568 print(" o[32:64]", output, output[32:64])
569 gt = (gtu(x[32:64], output[32:64])) == SelectableInt(1, 1)
570 gts.append(gt)
571 cy32 = 1 if any(gts) else 0
572 print("CA32", cy32, gts)
573 if not (2 & already_done):
574 self.spr['XER'][XER_bits['CA32']] = cy32
575
576 def handle_overflow(self, inputs, outputs, div_overflow):
577 if hasattr(self.dec2.e.do, "invert_in"):
578 inv_a = yield self.dec2.e.do.invert_in
579 if inv_a:
580 inputs[0] = ~inputs[0]
581
582 imm_ok = yield self.dec2.e.do.imm_data.ok
583 if imm_ok:
584 imm = yield self.dec2.e.do.imm_data.data
585 inputs.append(SelectableInt(imm, 64))
586 assert len(outputs) >= 1
587 print("handle_overflow", inputs, outputs, div_overflow)
588 if len(inputs) < 2 and div_overflow is None:
589 return
590
591 # div overflow is different: it's returned by the pseudo-code
592 # because it's more complex than can be done by analysing the output
593 if div_overflow is not None:
594 ov, ov32 = div_overflow, div_overflow
595 # arithmetic overflow can be done by analysing the input and output
596 elif len(inputs) >= 2:
597 output = outputs[0]
598
599 # OV (64-bit)
600 input_sgn = [exts(x.value, x.bits) < 0 for x in inputs]
601 output_sgn = exts(output.value, output.bits) < 0
602 ov = 1 if input_sgn[0] == input_sgn[1] and \
603 output_sgn != input_sgn[0] else 0
604
605 # OV (32-bit)
606 input32_sgn = [exts(x.value, 32) < 0 for x in inputs]
607 output32_sgn = exts(output.value, 32) < 0
608 ov32 = 1 if input32_sgn[0] == input32_sgn[1] and \
609 output32_sgn != input32_sgn[0] else 0
610
611 self.spr['XER'][XER_bits['OV']] = ov
612 self.spr['XER'][XER_bits['OV32']] = ov32
613 so = self.spr['XER'][XER_bits['SO']]
614 so = so | ov
615 self.spr['XER'][XER_bits['SO']] = so
616
617 def handle_comparison(self, outputs, cr_idx=0):
618 out = outputs[0]
619 assert isinstance(out, SelectableInt), \
620 "out zero not a SelectableInt %s" % repr(outputs)
621 print("handle_comparison", out.bits, hex(out.value))
622 # TODO - XXX *processor* in 32-bit mode
623 # https://bugs.libre-soc.org/show_bug.cgi?id=424
624 # if is_32bit:
625 # o32 = exts(out.value, 32)
626 # print ("handle_comparison exts 32 bit", hex(o32))
627 out = exts(out.value, out.bits)
628 print("handle_comparison exts", hex(out))
629 zero = SelectableInt(out == 0, 1)
630 positive = SelectableInt(out > 0, 1)
631 negative = SelectableInt(out < 0, 1)
632 SO = self.spr['XER'][XER_bits['SO']]
633 print("handle_comparison SO", SO)
634 cr_field = selectconcat(negative, positive, zero, SO)
635 self.crl[cr_idx].eq(cr_field)
636
637 def set_pc(self, pc_val):
638 self.namespace['NIA'] = SelectableInt(pc_val, 64)
639 self.pc.update(self.namespace, self.is_svp64_mode)
640
641 def setup_one(self):
642 """set up one instruction
643 """
644 if self.respect_pc:
645 pc = self.pc.CIA.value
646 else:
647 pc = self.fake_pc
648 self._pc = pc
649 ins = self.imem.ld(pc, 4, False, True)
650 if ins is None:
651 raise KeyError("no instruction at 0x%x" % pc)
652 print("setup: 0x%x 0x%x %s" % (pc, ins & 0xffffffff, bin(ins)))
653 print("CIA NIA", self.respect_pc, self.pc.CIA.value, self.pc.NIA.value)
654
655 yield self.dec2.sv_rm.eq(0)
656 yield self.dec2.dec.raw_opcode_in.eq(ins & 0xffffffff)
657 yield self.dec2.dec.bigendian.eq(self.bigendian)
658 yield self.dec2.state.msr.eq(self.msr.value)
659 yield self.dec2.state.pc.eq(pc)
660 if self.svstate is not None:
661 yield self.dec2.state.svstate.eq(self.svstate.spr.value)
662
663 # SVP64. first, check if the opcode is EXT001, and SVP64 id bits set
664 yield Settle()
665 opcode = yield self.dec2.dec.opcode_in
666 pfx = SVP64PrefixFields() # TODO should probably use SVP64PrefixDecoder
667 pfx.insn.value = opcode
668 major = pfx.major.asint(msb0=True) # MSB0 inversion
669 print ("prefix test: opcode:", major, bin(major),
670 pfx.insn[7] == 0b1, pfx.insn[9] == 0b1)
671 self.is_svp64_mode = ((major == 0b000001) and
672 pfx.insn[7].value == 0b1 and
673 pfx.insn[9].value == 0b1)
674 self.pc.update_nia(self.is_svp64_mode)
675 self.namespace['NIA'] = self.pc.NIA
676 if not self.is_svp64_mode:
677 return
678
679 # in SVP64 mode. decode/print out svp64 prefix, get v3.0B instruction
680 print ("svp64.rm", bin(pfx.rm.asint(msb0=True)))
681 print (" svstate.vl", self.svstate.vl.asint(msb0=True))
682 print (" svstate.mvl", self.svstate.maxvl.asint(msb0=True))
683 sv_rm = pfx.rm.asint(msb0=True)
684 ins = self.imem.ld(pc+4, 4, False, True)
685 print(" svsetup: 0x%x 0x%x %s" % (pc+4, ins & 0xffffffff, bin(ins)))
686 yield self.dec2.dec.raw_opcode_in.eq(ins & 0xffffffff) # v3.0B suffix
687 yield self.dec2.sv_rm.eq(sv_rm) # svp64 prefix
688 yield Settle()
689
690 def execute_one(self):
691 """execute one instruction
692 """
693 # get the disassembly code for this instruction
694 if self.is_svp64_mode:
695 code = self.disassembly[self._pc+4]
696 print(" svp64 sim-execute", hex(self._pc), code)
697 else:
698 code = self.disassembly[self._pc]
699 print("sim-execute", hex(self._pc), code)
700 opname = code.split(' ')[0]
701 yield from self.call(opname)
702
703 # don't use this except in special circumstances
704 if not self.respect_pc:
705 self.fake_pc += 4
706
707 print("execute one, CIA NIA", self.pc.CIA.value, self.pc.NIA.value)
708
709 def get_assembly_name(self):
710 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
711 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
712 dec_insn = yield self.dec2.e.do.insn
713 asmcode = yield self.dec2.dec.op.asmcode
714 print("get assembly name asmcode", asmcode, hex(dec_insn))
715 asmop = insns.get(asmcode, None)
716 int_op = yield self.dec2.dec.op.internal_op
717
718 # sigh reconstruct the assembly instruction name
719 if hasattr(self.dec2.e.do, "oe"):
720 ov_en = yield self.dec2.e.do.oe.oe
721 ov_ok = yield self.dec2.e.do.oe.ok
722 else:
723 ov_en = False
724 ov_ok = False
725 if hasattr(self.dec2.e.do, "rc"):
726 rc_en = yield self.dec2.e.do.rc.rc
727 rc_ok = yield self.dec2.e.do.rc.ok
728 else:
729 rc_en = False
730 rc_ok = False
731 # grrrr have to special-case MUL op (see DecodeOE)
732 print("ov %d en %d rc %d en %d op %d" %
733 (ov_ok, ov_en, rc_ok, rc_en, int_op))
734 if int_op in [MicrOp.OP_MUL_H64.value, MicrOp.OP_MUL_H32.value]:
735 print("mul op")
736 if rc_en & rc_ok:
737 asmop += "."
738 else:
739 if not asmop.endswith("."): # don't add "." to "andis."
740 if rc_en & rc_ok:
741 asmop += "."
742 if hasattr(self.dec2.e.do, "lk"):
743 lk = yield self.dec2.e.do.lk
744 if lk:
745 asmop += "l"
746 print("int_op", int_op)
747 if int_op in [MicrOp.OP_B.value, MicrOp.OP_BC.value]:
748 AA = yield self.dec2.dec.fields.FormI.AA[0:-1]
749 print("AA", AA)
750 if AA:
751 asmop += "a"
752 spr_msb = yield from self.get_spr_msb()
753 if int_op == MicrOp.OP_MFCR.value:
754 if spr_msb:
755 asmop = 'mfocrf'
756 else:
757 asmop = 'mfcr'
758 # XXX TODO: for whatever weird reason this doesn't work
759 # https://bugs.libre-soc.org/show_bug.cgi?id=390
760 if int_op == MicrOp.OP_MTCRF.value:
761 if spr_msb:
762 asmop = 'mtocrf'
763 else:
764 asmop = 'mtcrf'
765 return asmop
766
767 def get_spr_msb(self):
768 dec_insn = yield self.dec2.e.do.insn
769 return dec_insn & (1 << 20) != 0 # sigh - XFF.spr[-1]?
770
771 def call(self, name):
772 """call(opcode) - the primary execution point for instructions
773 """
774 name = name.strip() # remove spaces if not already done so
775 if self.halted:
776 print("halted - not executing", name)
777 return
778
779 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
780 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
781 asmop = yield from self.get_assembly_name()
782 print("call", name, asmop)
783
784 # check privileged
785 int_op = yield self.dec2.dec.op.internal_op
786 spr_msb = yield from self.get_spr_msb()
787
788 instr_is_privileged = False
789 if int_op in [MicrOp.OP_ATTN.value,
790 MicrOp.OP_MFMSR.value,
791 MicrOp.OP_MTMSR.value,
792 MicrOp.OP_MTMSRD.value,
793 # TODO: OP_TLBIE
794 MicrOp.OP_RFID.value]:
795 instr_is_privileged = True
796 if int_op in [MicrOp.OP_MFSPR.value,
797 MicrOp.OP_MTSPR.value] and spr_msb:
798 instr_is_privileged = True
799
800 print("is priv", instr_is_privileged, hex(self.msr.value),
801 self.msr[MSRb.PR])
802 # check MSR priv bit and whether op is privileged: if so, throw trap
803 if instr_is_privileged and self.msr[MSRb.PR] == 1:
804 self.TRAP(0x700, PIb.PRIV)
805 self.namespace['NIA'] = self.trap_nia
806 self.pc.update(self.namespace, self.is_svp64_mode)
807 return
808
809 # check halted condition
810 if name == 'attn':
811 self.halted = True
812 return
813
814 # check illegal instruction
815 illegal = False
816 if name not in ['mtcrf', 'mtocrf']:
817 illegal = name != asmop
818
819 if illegal:
820 print("illegal", name, asmop)
821 self.TRAP(0x700, PIb.ILLEG)
822 self.namespace['NIA'] = self.trap_nia
823 self.pc.update(self.namespace, self.is_svp64_mode)
824 print("name %s != %s - calling ILLEGAL trap, PC: %x" %
825 (name, asmop, self.pc.CIA.value))
826 return
827
828 info = self.instrs[name]
829 yield from self.prep_namespace(info.form, info.op_fields)
830
831 # preserve order of register names
832 input_names = create_args(list(info.read_regs) +
833 list(info.uninit_regs))
834 print(input_names)
835
836 # get SVP64 entry for the current instruction
837 sv_rm = self.svp64rm.instrs.get(name)
838 if sv_rm is not None:
839 dest_cr, src_cr, src_byname, dest_byname = decode_extra(sv_rm)
840 else:
841 dest_cr, src_cr, src_byname, dest_byname = False, False, {}, {}
842 print ("sv rm", sv_rm, dest_cr, src_cr, src_byname, dest_byname)
843
844 # get SVSTATE VL (oh and print out some debug stuff)
845 if self.is_svp64_mode:
846 vl = self.svstate.vl.asint(msb0=True)
847 srcstep = self.svstate.srcstep.asint(msb0=True)
848 sv_a_nz = yield self.dec2.sv_a_nz
849 in1 = yield self.dec2.e.read_reg1.data
850 print ("SVP64: VL, srcstep, sv_a_nz, in1",
851 vl, srcstep, sv_a_nz, in1)
852
853 # VL=0 in SVP64 mode means "do nothing: skip instruction"
854 if self.is_svp64_mode and vl == 0:
855 self.pc.update(self.namespace, self.is_svp64_mode)
856 print("SVP64: VL=0, end of call", self.namespace['CIA'],
857 self.namespace['NIA'])
858 return
859
860 # main input registers (RT, RA ...)
861 inputs = []
862 for name in input_names:
863 # using PowerDecoder2, first, find the decoder index.
864 # (mapping name RA RB RC RS to in1, in2, in3)
865 regnum, is_vec = yield from get_pdecode_idx_in(self.dec2, name)
866 if regnum is None:
867 # doing this is not part of svp64, it's because output
868 # registers, to be modified, need to be in the namespace.
869 regnum, is_vec = yield from get_pdecode_idx_out(self.dec2, name)
870
871 # in case getting the register number is needed, _RA, _RB
872 regname = "_" + name
873 self.namespace[regname] = regnum
874 print('reading reg %s %d' % (name, regnum), is_vec)
875 reg_val = self.gpr(regnum)
876 inputs.append(reg_val)
877
878 # "special" registers
879 for special in info.special_regs:
880 if special in special_sprs:
881 inputs.append(self.spr[special])
882 else:
883 inputs.append(self.namespace[special])
884
885 # clear trap (trap) NIA
886 self.trap_nia = None
887
888 print("inputs", inputs)
889 results = info.func(self, *inputs)
890 print("results", results)
891
892 # "inject" decorator takes namespace from function locals: we need to
893 # overwrite NIA being overwritten (sigh)
894 if self.trap_nia is not None:
895 self.namespace['NIA'] = self.trap_nia
896
897 print("after func", self.namespace['CIA'], self.namespace['NIA'])
898
899 # detect if CA/CA32 already in outputs (sra*, basically)
900 already_done = 0
901 if info.write_regs:
902 output_names = create_args(info.write_regs)
903 for name in output_names:
904 if name == 'CA':
905 already_done |= 1
906 if name == 'CA32':
907 already_done |= 2
908
909 print("carry already done?", bin(already_done))
910 if hasattr(self.dec2.e.do, "output_carry"):
911 carry_en = yield self.dec2.e.do.output_carry
912 else:
913 carry_en = False
914 if carry_en:
915 yield from self.handle_carry_(inputs, results, already_done)
916
917 # detect if overflow was in return result
918 overflow = None
919 if info.write_regs:
920 for name, output in zip(output_names, results):
921 if name == 'overflow':
922 overflow = output
923
924 if hasattr(self.dec2.e.do, "oe"):
925 ov_en = yield self.dec2.e.do.oe.oe
926 ov_ok = yield self.dec2.e.do.oe.ok
927 else:
928 ov_en = False
929 ov_ok = False
930 print("internal overflow", overflow, ov_en, ov_ok)
931 if ov_en & ov_ok:
932 yield from self.handle_overflow(inputs, results, overflow)
933
934 if hasattr(self.dec2.e.do, "rc"):
935 rc_en = yield self.dec2.e.do.rc.rc
936 else:
937 rc_en = False
938 if rc_en:
939 regnum, is_vec = yield from get_pdecode_cr_out(self.dec2, "CR0")
940 self.handle_comparison(results, regnum)
941
942 # any modified return results?
943 if info.write_regs:
944 for name, output in zip(output_names, results):
945 if name == 'overflow': # ignore, done already (above)
946 continue
947 if isinstance(output, int):
948 output = SelectableInt(output, 256)
949 if name in ['CA', 'CA32']:
950 if carry_en:
951 print("writing %s to XER" % name, output)
952 self.spr['XER'][XER_bits[name]] = output.value
953 else:
954 print("NOT writing %s to XER" % name, output)
955 elif name in info.special_regs:
956 print('writing special %s' % name, output, special_sprs)
957 if name in special_sprs:
958 self.spr[name] = output
959 else:
960 self.namespace[name].eq(output)
961 if name == 'MSR':
962 print('msr written', hex(self.msr.value))
963 else:
964 regnum, is_vec = yield from get_pdecode_idx_out(self.dec2,
965 name)
966 if regnum is None:
967 # temporary hack for not having 2nd output
968 regnum = yield getattr(self.decoder, name)
969 is_vec = False
970 print('writing reg %d %s' % (regnum, str(output)), is_vec)
971 if output.bits > 64:
972 output = SelectableInt(output.value, 64)
973 self.gpr[regnum] = output
974
975 # check if it is the SVSTATE.src/dest step that needs incrementing
976 # this is our Sub-Program-Counter loop from 0 to VL-1
977 if self.is_svp64_mode:
978 # XXX twin predication TODO
979 vl = self.svstate.vl.asint(msb0=True)
980 mvl = self.svstate.maxvl.asint(msb0=True)
981 srcstep = self.svstate.srcstep.asint(msb0=True)
982 sv_ptype = yield self.dec2.dec.op.SV_Ptype
983 no_out_vec = not (yield self.dec2.no_out_vec)
984 no_in_vec = not (yield self.dec2.no_in_vec)
985 print (" svstate.vl", vl)
986 print (" svstate.mvl", mvl)
987 print (" svstate.srcstep", srcstep)
988 print (" no_out_vec", no_out_vec)
989 print (" no_in_vec", no_in_vec)
990 print (" sv_ptype", sv_ptype, sv_ptype == SVPtype.P2.value)
991 # check if srcstep needs incrementing by one, stop PC advancing
992 # svp64 loop can end early if the dest is scalar for single-pred
993 # but for 2-pred both src/dest have to be checked.
994 # XXX this might not be true! it may just be LD/ST
995 if sv_ptype == SVPtype.P2.value:
996 svp64_is_vector = (no_out_vec or no_in_vec)
997 else:
998 svp64_is_vector = no_out_vec
999 if svp64_is_vector and srcstep != vl-1:
1000 self.svstate.srcstep += SelectableInt(1, 7)
1001 self.pc.NIA.value = self.pc.CIA.value
1002 self.namespace['NIA'] = self.pc.NIA
1003 print("end of sub-pc call", self.namespace['CIA'],
1004 self.namespace['NIA'])
1005 return # DO NOT allow PC to update whilst Sub-PC loop running
1006 # reset to zero
1007 self.svstate.srcstep[0:7] = 0
1008 print (" svstate.srcstep loop end (PC to update)")
1009 self.pc.update_nia(self.is_svp64_mode)
1010 self.namespace['NIA'] = self.pc.NIA
1011
1012 # UPDATE program counter
1013 self.pc.update(self.namespace, self.is_svp64_mode)
1014 print("end of call", self.namespace['CIA'], self.namespace['NIA'])
1015
1016
1017 def inject():
1018 """Decorator factory.
1019
1020 this decorator will "inject" variables into the function's namespace,
1021 from the *dictionary* in self.namespace. it therefore becomes possible
1022 to make it look like a whole stack of variables which would otherwise
1023 need "self." inserted in front of them (*and* for those variables to be
1024 added to the instance) "appear" in the function.
1025
1026 "self.namespace['SI']" for example becomes accessible as just "SI" but
1027 *only* inside the function, when decorated.
1028 """
1029 def variable_injector(func):
1030 @wraps(func)
1031 def decorator(*args, **kwargs):
1032 try:
1033 func_globals = func.__globals__ # Python 2.6+
1034 except AttributeError:
1035 func_globals = func.func_globals # Earlier versions.
1036
1037 context = args[0].namespace # variables to be injected
1038 saved_values = func_globals.copy() # Shallow copy of dict.
1039 func_globals.update(context)
1040 result = func(*args, **kwargs)
1041 print("globals after", func_globals['CIA'], func_globals['NIA'])
1042 print("args[0]", args[0].namespace['CIA'],
1043 args[0].namespace['NIA'])
1044 args[0].namespace = func_globals
1045 #exec (func.__code__, func_globals)
1046
1047 # finally:
1048 # func_globals = saved_values # Undo changes.
1049
1050 return result
1051
1052 return decorator
1053
1054 return variable_injector
1055
1056