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