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