4a38a1ede376a61c3402c20b46715dabfe4b92ce
[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)
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
255
256 # SVP64 Prefix fields: see https://libre-soc.org/openpower/sv/svp64/
257 class SVP64PrefixFields:
258 def __init__(self):
259 self.insn = SelectableInt(0, 32)
260 # 6 bit major opcode EXT001, 2 bits "identifying" (7, 9), 24 SV ReMap
261 self.major = FieldSelectableInt(self.insn, tuple(range(0,6)))
262 self.pid = FieldSelectableInt(self.insn, (7, 9)) # must be 0b11
263 rmfields = [6, 8] + list(range(10,32)) # SVP64 24-bit RM (ReMap)
264 self.rm = FieldSelectableInt(self.insn, rmfields)
265
266
267 class SPR(dict):
268 def __init__(self, dec2, initial_sprs={}):
269 self.sd = dec2
270 dict.__init__(self)
271 for key, v in initial_sprs.items():
272 if isinstance(key, SelectableInt):
273 key = key.value
274 key = special_sprs.get(key, key)
275 if isinstance(key, int):
276 info = spr_dict[key]
277 else:
278 info = spr_byname[key]
279 if not isinstance(v, SelectableInt):
280 v = SelectableInt(v, info.length)
281 self[key] = v
282
283 def __getitem__(self, key):
284 print("get spr", key)
285 print("dict", self.items())
286 # if key in special_sprs get the special spr, otherwise return key
287 if isinstance(key, SelectableInt):
288 key = key.value
289 if isinstance(key, int):
290 key = spr_dict[key].SPR
291 key = special_sprs.get(key, key)
292 if key == 'HSRR0': # HACK!
293 key = 'SRR0'
294 if key == 'HSRR1': # HACK!
295 key = 'SRR1'
296 if key in self:
297 res = dict.__getitem__(self, key)
298 else:
299 if isinstance(key, int):
300 info = spr_dict[key]
301 else:
302 info = spr_byname[key]
303 dict.__setitem__(self, key, SelectableInt(0, info.length))
304 res = dict.__getitem__(self, key)
305 print("spr returning", key, res)
306 return res
307
308 def __setitem__(self, key, value):
309 if isinstance(key, SelectableInt):
310 key = key.value
311 if isinstance(key, int):
312 key = spr_dict[key].SPR
313 print("spr key", key)
314 key = special_sprs.get(key, key)
315 if key == 'HSRR0': # HACK!
316 self.__setitem__('SRR0', value)
317 if key == 'HSRR1': # HACK!
318 self.__setitem__('SRR1', value)
319 print("setting spr", key, value)
320 dict.__setitem__(self, key, value)
321
322 def __call__(self, ridx):
323 return self[ridx]
324
325 def get_pdecode_idx_in(dec2, name):
326 op = dec2.dec.op
327 in1_sel = yield op.in1_sel
328 in2_sel = yield op.in2_sel
329 in3_sel = yield op.in3_sel
330 # get the IN1/2/3 from the decoder (includes SVP64 remap and isvec)
331 in1 = yield dec2.e.read_reg1.data
332 in2 = yield dec2.e.read_reg2.data
333 in3 = yield dec2.e.read_reg3.data
334 in1_isvec = yield dec2.in1_isvec
335 in2_isvec = yield dec2.in2_isvec
336 in3_isvec = yield dec2.in3_isvec
337 print ("get_pdecode_idx", in1_sel, In1Sel.RA.value, in1, in1_isvec)
338 # identify which regnames map to in1/2/3
339 if name == 'RA':
340 if (in1_sel == In1Sel.RA.value or
341 (in1_sel == In1Sel.RA_OR_ZERO.value and in1 != 0)):
342 return in1, in1_isvec
343 if in1_sel == In1Sel.RA_OR_ZERO.value:
344 return in1, in1_isvec
345 elif name == 'RB':
346 if in2_sel == In2Sel.RB.value:
347 return in2, in2_isvec
348 if in3_sel == In3Sel.RB.value:
349 return in3, in3_isvec
350 # XXX TODO, RC doesn't exist yet!
351 elif name == 'RC':
352 assert False, "RC does not exist yet"
353 elif name == 'RS':
354 if in1_sel == In1Sel.RS.value:
355 return in1, in1_isvec
356 if in2_sel == In2Sel.RS.value:
357 return in2, in2_isvec
358 if in3_sel == In3Sel.RS.value:
359 return in3, in3_isvec
360 return None, False
361
362
363 def get_pdecode_idx_out(dec2, name):
364 op = dec2.dec.op
365 out_sel = yield op.out_sel
366 # get the IN1/2/3 from the decoder (includes SVP64 remap and isvec)
367 out = yield dec2.e.write_reg.data
368 o_isvec = yield dec2.o_isvec
369 print ("get_pdecode_idx_out", out_sel, OutSel.RA.value, out, o_isvec)
370 # identify which regnames map to out / o2
371 if name == 'RA':
372 if out_sel == OutSel.RA.value:
373 return out, o_isvec
374 elif name == 'RT':
375 if out_sel == OutSel.RT.value:
376 return out, o_isvec
377 print ("get_pdecode_idx_out not found", name)
378 return None, False
379
380
381 # XXX TODO
382 def get_pdecode_idx_out2(dec2, name):
383 op = dec2.dec.op
384 print ("TODO: get_pdecode_idx_out2", name)
385 return None, False
386
387
388 class ISACaller:
389 # decoder2 - an instance of power_decoder2
390 # regfile - a list of initial values for the registers
391 # initial_{etc} - initial values for SPRs, Condition Register, Mem, MSR
392 # respect_pc - tracks the program counter. requires initial_insns
393 def __init__(self, decoder2, regfile, initial_sprs=None, initial_cr=0,
394 initial_mem=None, initial_msr=0,
395 initial_svstate=0,
396 initial_insns=None, respect_pc=False,
397 disassembly=None,
398 initial_pc=0,
399 bigendian=False):
400
401 self.bigendian = bigendian
402 self.halted = False
403 self.is_svp64_mode = False
404 self.respect_pc = respect_pc
405 if initial_sprs is None:
406 initial_sprs = {}
407 if initial_mem is None:
408 initial_mem = {}
409 if initial_insns is None:
410 initial_insns = {}
411 assert self.respect_pc == False, "instructions required to honor pc"
412
413 print("ISACaller insns", respect_pc, initial_insns, disassembly)
414 print("ISACaller initial_msr", initial_msr)
415
416 # "fake program counter" mode (for unit testing)
417 self.fake_pc = 0
418 disasm_start = 0
419 if not respect_pc:
420 if isinstance(initial_mem, tuple):
421 self.fake_pc = initial_mem[0]
422 disasm_start = self.fake_pc
423 else:
424 disasm_start = initial_pc
425
426 # disassembly: we need this for now (not given from the decoder)
427 self.disassembly = {}
428 if disassembly:
429 for i, code in enumerate(disassembly):
430 self.disassembly[i*4 + disasm_start] = code
431
432 # set up registers, instruction memory, data memory, PC, SPRs, MSR
433 self.svp64rm = SVP64RM()
434 if isinstance(initial_svstate, int):
435 initial_svstate = SVP64State(initial_svstate)
436 self.svstate = initial_svstate
437 self.gpr = GPR(decoder2, self, self.svstate, regfile)
438 self.mem = Mem(row_bytes=8, initial_mem=initial_mem)
439 self.imem = Mem(row_bytes=4, initial_mem=initial_insns)
440 self.pc = PC()
441 self.spr = SPR(decoder2, initial_sprs)
442 self.msr = SelectableInt(initial_msr, 64) # underlying reg
443
444 # TODO, needed here:
445 # FPR (same as GPR except for FP nums)
446 # 4.2.2 p124 FPSCR (definitely "separate" - not in SPR)
447 # note that mffs, mcrfs, mtfsf "manage" this FPSCR
448 # 2.3.1 CR (and sub-fields CR0..CR6 - CR0 SO comes from XER.SO)
449 # note that mfocrf, mfcr, mtcr, mtocrf, mcrxrx "manage" CRs
450 # -- Done
451 # 2.3.2 LR (actually SPR #8) -- Done
452 # 2.3.3 CTR (actually SPR #9) -- Done
453 # 2.3.4 TAR (actually SPR #815)
454 # 3.2.2 p45 XER (actually SPR #1) -- Done
455 # 3.2.3 p46 p232 VRSAVE (actually SPR #256)
456
457 # create CR then allow portions of it to be "selectable" (below)
458 #rev_cr = int('{:016b}'.format(initial_cr)[::-1], 2)
459 self.cr = SelectableInt(initial_cr, 64) # underlying reg
460 #self.cr = FieldSelectableInt(self._cr, list(range(32, 64)))
461
462 # "undefined", just set to variable-bit-width int (use exts "max")
463 #self.undefined = SelectableInt(0, 256) # TODO, not hard-code 256!
464
465 self.namespace = {}
466 self.namespace.update(self.spr)
467 self.namespace.update({'GPR': self.gpr,
468 'MEM': self.mem,
469 'SPR': self.spr,
470 'memassign': self.memassign,
471 'NIA': self.pc.NIA,
472 'CIA': self.pc.CIA,
473 'CR': self.cr,
474 'MSR': self.msr,
475 'undefined': undefined,
476 'mode_is_64bit': True,
477 'SO': XER_bits['SO']
478 })
479
480 # update pc to requested start point
481 self.set_pc(initial_pc)
482
483 # field-selectable versions of Condition Register TODO check bitranges?
484 self.crl = []
485 for i in range(8):
486 bits = tuple(range(i*4+32, (i+1)*4+32)) # errr... maybe?
487 _cr = FieldSelectableInt(self.cr, bits)
488 self.crl.append(_cr)
489 self.namespace["CR%d" % i] = _cr
490
491 self.decoder = decoder2.dec
492 self.dec2 = decoder2
493
494 def TRAP(self, trap_addr=0x700, trap_bit=PIb.TRAP):
495 print("TRAP:", hex(trap_addr), hex(self.namespace['MSR'].value))
496 # store CIA(+4?) in SRR0, set NIA to 0x700
497 # store MSR in SRR1, set MSR to um errr something, have to check spec
498 self.spr['SRR0'].value = self.pc.CIA.value
499 self.spr['SRR1'].value = self.namespace['MSR'].value
500 self.trap_nia = SelectableInt(trap_addr, 64)
501 self.spr['SRR1'][trap_bit] = 1 # change *copy* of MSR in SRR1
502
503 # set exception bits. TODO: this should, based on the address
504 # in figure 66 p1065 V3.0B and the table figure 65 p1063 set these
505 # bits appropriately. however it turns out that *for now* in all
506 # cases (all trap_addrs) the exact same thing is needed.
507 self.msr[MSRb.IR] = 0
508 self.msr[MSRb.DR] = 0
509 self.msr[MSRb.FE0] = 0
510 self.msr[MSRb.FE1] = 0
511 self.msr[MSRb.EE] = 0
512 self.msr[MSRb.RI] = 0
513 self.msr[MSRb.SF] = 1
514 self.msr[MSRb.TM] = 0
515 self.msr[MSRb.VEC] = 0
516 self.msr[MSRb.VSX] = 0
517 self.msr[MSRb.PR] = 0
518 self.msr[MSRb.FP] = 0
519 self.msr[MSRb.PMM] = 0
520 self.msr[MSRb.TEs] = 0
521 self.msr[MSRb.TEe] = 0
522 self.msr[MSRb.UND] = 0
523 self.msr[MSRb.LE] = 1
524
525 def memassign(self, ea, sz, val):
526 self.mem.memassign(ea, sz, val)
527
528 def prep_namespace(self, formname, op_fields):
529 # TODO: get field names from form in decoder*1* (not decoder2)
530 # decoder2 is hand-created, and decoder1.sigform is auto-generated
531 # from spec
532 # then "yield" fields only from op_fields rather than hard-coded
533 # list, here.
534 fields = self.decoder.sigforms[formname]
535 for name in op_fields:
536 if name == 'spr':
537 sig = getattr(fields, name.upper())
538 else:
539 sig = getattr(fields, name)
540 val = yield sig
541 # these are all opcode fields involved in index-selection of CR,
542 # and need to do "standard" arithmetic. CR[BA+32] for example
543 # would, if using SelectableInt, only be 5-bit.
544 if name in ['BF', 'BFA', 'BC', 'BA', 'BB', 'BT', 'BI']:
545 self.namespace[name] = val
546 else:
547 self.namespace[name] = SelectableInt(val, sig.width)
548
549 self.namespace['XER'] = self.spr['XER']
550 self.namespace['CA'] = self.spr['XER'][XER_bits['CA']].value
551 self.namespace['CA32'] = self.spr['XER'][XER_bits['CA32']].value
552
553 def handle_carry_(self, inputs, outputs, already_done):
554 inv_a = yield self.dec2.e.do.invert_in
555 if inv_a:
556 inputs[0] = ~inputs[0]
557
558 imm_ok = yield self.dec2.e.do.imm_data.ok
559 if imm_ok:
560 imm = yield self.dec2.e.do.imm_data.data
561 inputs.append(SelectableInt(imm, 64))
562 assert len(outputs) >= 1
563 print("outputs", repr(outputs))
564 if isinstance(outputs, list) or isinstance(outputs, tuple):
565 output = outputs[0]
566 else:
567 output = outputs
568 gts = []
569 for x in inputs:
570 print("gt input", x, output)
571 gt = (gtu(x, output))
572 gts.append(gt)
573 print(gts)
574 cy = 1 if any(gts) else 0
575 print("CA", cy, gts)
576 if not (1 & already_done):
577 self.spr['XER'][XER_bits['CA']] = cy
578
579 print("inputs", already_done, inputs)
580 # 32 bit carry
581 # ARGH... different for OP_ADD... *sigh*...
582 op = yield self.dec2.e.do.insn_type
583 if op == MicrOp.OP_ADD.value:
584 res32 = (output.value & (1 << 32)) != 0
585 a32 = (inputs[0].value & (1 << 32)) != 0
586 if len(inputs) >= 2:
587 b32 = (inputs[1].value & (1 << 32)) != 0
588 else:
589 b32 = False
590 cy32 = res32 ^ a32 ^ b32
591 print("CA32 ADD", cy32)
592 else:
593 gts = []
594 for x in inputs:
595 print("input", x, output)
596 print(" x[32:64]", x, x[32:64])
597 print(" o[32:64]", output, output[32:64])
598 gt = (gtu(x[32:64], output[32:64])) == SelectableInt(1, 1)
599 gts.append(gt)
600 cy32 = 1 if any(gts) else 0
601 print("CA32", cy32, gts)
602 if not (2 & already_done):
603 self.spr['XER'][XER_bits['CA32']] = cy32
604
605 def handle_overflow(self, inputs, outputs, div_overflow):
606 if hasattr(self.dec2.e.do, "invert_in"):
607 inv_a = yield self.dec2.e.do.invert_in
608 if inv_a:
609 inputs[0] = ~inputs[0]
610
611 imm_ok = yield self.dec2.e.do.imm_data.ok
612 if imm_ok:
613 imm = yield self.dec2.e.do.imm_data.data
614 inputs.append(SelectableInt(imm, 64))
615 assert len(outputs) >= 1
616 print("handle_overflow", inputs, outputs, div_overflow)
617 if len(inputs) < 2 and div_overflow is None:
618 return
619
620 # div overflow is different: it's returned by the pseudo-code
621 # because it's more complex than can be done by analysing the output
622 if div_overflow is not None:
623 ov, ov32 = div_overflow, div_overflow
624 # arithmetic overflow can be done by analysing the input and output
625 elif len(inputs) >= 2:
626 output = outputs[0]
627
628 # OV (64-bit)
629 input_sgn = [exts(x.value, x.bits) < 0 for x in inputs]
630 output_sgn = exts(output.value, output.bits) < 0
631 ov = 1 if input_sgn[0] == input_sgn[1] and \
632 output_sgn != input_sgn[0] else 0
633
634 # OV (32-bit)
635 input32_sgn = [exts(x.value, 32) < 0 for x in inputs]
636 output32_sgn = exts(output.value, 32) < 0
637 ov32 = 1 if input32_sgn[0] == input32_sgn[1] and \
638 output32_sgn != input32_sgn[0] else 0
639
640 self.spr['XER'][XER_bits['OV']] = ov
641 self.spr['XER'][XER_bits['OV32']] = ov32
642 so = self.spr['XER'][XER_bits['SO']]
643 so = so | ov
644 self.spr['XER'][XER_bits['SO']] = so
645
646 def handle_comparison(self, outputs):
647 out = outputs[0]
648 assert isinstance(out, SelectableInt), \
649 "out zero not a SelectableInt %s" % repr(outputs)
650 print("handle_comparison", out.bits, hex(out.value))
651 # TODO - XXX *processor* in 32-bit mode
652 # https://bugs.libre-soc.org/show_bug.cgi?id=424
653 # if is_32bit:
654 # o32 = exts(out.value, 32)
655 # print ("handle_comparison exts 32 bit", hex(o32))
656 out = exts(out.value, out.bits)
657 print("handle_comparison exts", hex(out))
658 zero = SelectableInt(out == 0, 1)
659 positive = SelectableInt(out > 0, 1)
660 negative = SelectableInt(out < 0, 1)
661 SO = self.spr['XER'][XER_bits['SO']]
662 print("handle_comparison SO", SO)
663 cr_field = selectconcat(negative, positive, zero, SO)
664 self.crl[0].eq(cr_field)
665
666 def set_pc(self, pc_val):
667 self.namespace['NIA'] = SelectableInt(pc_val, 64)
668 self.pc.update(self.namespace, self.is_svp64_mode)
669
670 def setup_one(self):
671 """set up one instruction
672 """
673 if self.respect_pc:
674 pc = self.pc.CIA.value
675 else:
676 pc = self.fake_pc
677 self._pc = pc
678 ins = self.imem.ld(pc, 4, False, True)
679 if ins is None:
680 raise KeyError("no instruction at 0x%x" % pc)
681 print("setup: 0x%x 0x%x %s" % (pc, ins & 0xffffffff, bin(ins)))
682 print("CIA NIA", self.respect_pc, self.pc.CIA.value, self.pc.NIA.value)
683
684 yield self.dec2.sv_rm.eq(0)
685 yield self.dec2.dec.raw_opcode_in.eq(ins & 0xffffffff)
686 yield self.dec2.dec.bigendian.eq(self.bigendian)
687 yield self.dec2.state.msr.eq(self.msr.value)
688 yield self.dec2.state.pc.eq(pc)
689
690 # SVP64. first, check if the opcode is EXT001, and SVP64 id bits set
691 yield Settle()
692 opcode = yield self.dec2.dec.opcode_in
693 pfx = SVP64PrefixFields() # TODO should probably use SVP64PrefixDecoder
694 pfx.insn.value = opcode
695 major = pfx.major.asint(msb0=True) # MSB0 inversion
696 print ("prefix test: opcode:", major, bin(major),
697 pfx.insn[7] == 0b1, pfx.insn[9] == 0b1)
698 self.is_svp64_mode = ((major == 0b000001) and
699 pfx.insn[7].value == 0b1 and
700 pfx.insn[9].value == 0b1)
701 self.pc.update_nia(self.is_svp64_mode)
702 if not self.is_svp64_mode:
703 return
704
705 # in SVP64 mode. decode/print out svp64 prefix, get v3.0B instruction
706 print ("svp64.rm", bin(pfx.rm.asint(msb0=True)))
707 print (" svstate.vl", self.svstate.vl.asint(msb0=True))
708 print (" svstate.mvl", self.svstate.maxvl.asint(msb0=True))
709 sv_rm = pfx.rm.asint()
710 ins = self.imem.ld(pc+4, 4, False, True)
711 print(" svsetup: 0x%x 0x%x %s" % (pc+4, ins & 0xffffffff, bin(ins)))
712 yield self.dec2.dec.raw_opcode_in.eq(ins & 0xffffffff) # v3.0B suffix
713 yield self.dec2.sv_rm.eq(sv_rm) # svp64 prefix
714 yield Settle()
715
716 def execute_one(self):
717 """execute one instruction
718 """
719 # get the disassembly code for this instruction
720 if self.is_svp64_mode:
721 code = self.disassembly[self._pc+4]
722 print(" svp64 sim-execute", hex(self._pc), code)
723 else:
724 code = self.disassembly[self._pc]
725 print("sim-execute", hex(self._pc), code)
726 opname = code.split(' ')[0]
727 yield from self.call(opname)
728
729 # don't use this except in special circumstances
730 if not self.respect_pc:
731 self.fake_pc += 4
732
733 print("execute one, CIA NIA", self.pc.CIA.value, self.pc.NIA.value)
734
735 def get_assembly_name(self):
736 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
737 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
738 dec_insn = yield self.dec2.e.do.insn
739 asmcode = yield self.dec2.dec.op.asmcode
740 print("get assembly name asmcode", asmcode, hex(dec_insn))
741 asmop = insns.get(asmcode, None)
742 int_op = yield self.dec2.dec.op.internal_op
743
744 # sigh reconstruct the assembly instruction name
745 if hasattr(self.dec2.e.do, "oe"):
746 ov_en = yield self.dec2.e.do.oe.oe
747 ov_ok = yield self.dec2.e.do.oe.ok
748 else:
749 ov_en = False
750 ov_ok = False
751 if hasattr(self.dec2.e.do, "rc"):
752 rc_en = yield self.dec2.e.do.rc.rc
753 rc_ok = yield self.dec2.e.do.rc.ok
754 else:
755 rc_en = False
756 rc_ok = False
757 # grrrr have to special-case MUL op (see DecodeOE)
758 print("ov %d en %d rc %d en %d op %d" %
759 (ov_ok, ov_en, rc_ok, rc_en, int_op))
760 if int_op in [MicrOp.OP_MUL_H64.value, MicrOp.OP_MUL_H32.value]:
761 print("mul op")
762 if rc_en & rc_ok:
763 asmop += "."
764 else:
765 if not asmop.endswith("."): # don't add "." to "andis."
766 if rc_en & rc_ok:
767 asmop += "."
768 if hasattr(self.dec2.e.do, "lk"):
769 lk = yield self.dec2.e.do.lk
770 if lk:
771 asmop += "l"
772 print("int_op", int_op)
773 if int_op in [MicrOp.OP_B.value, MicrOp.OP_BC.value]:
774 AA = yield self.dec2.dec.fields.FormI.AA[0:-1]
775 print("AA", AA)
776 if AA:
777 asmop += "a"
778 spr_msb = yield from self.get_spr_msb()
779 if int_op == MicrOp.OP_MFCR.value:
780 if spr_msb:
781 asmop = 'mfocrf'
782 else:
783 asmop = 'mfcr'
784 # XXX TODO: for whatever weird reason this doesn't work
785 # https://bugs.libre-soc.org/show_bug.cgi?id=390
786 if int_op == MicrOp.OP_MTCRF.value:
787 if spr_msb:
788 asmop = 'mtocrf'
789 else:
790 asmop = 'mtcrf'
791 return asmop
792
793 def get_spr_msb(self):
794 dec_insn = yield self.dec2.e.do.insn
795 return dec_insn & (1 << 20) != 0 # sigh - XFF.spr[-1]?
796
797 def call(self, name):
798 """call(opcode) - the primary execution point for instructions
799 """
800 name = name.strip() # remove spaces if not already done so
801 if self.halted:
802 print("halted - not executing", name)
803 return
804
805 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
806 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
807 asmop = yield from self.get_assembly_name()
808 print("call", name, asmop)
809
810 # check privileged
811 int_op = yield self.dec2.dec.op.internal_op
812 spr_msb = yield from self.get_spr_msb()
813
814 instr_is_privileged = False
815 if int_op in [MicrOp.OP_ATTN.value,
816 MicrOp.OP_MFMSR.value,
817 MicrOp.OP_MTMSR.value,
818 MicrOp.OP_MTMSRD.value,
819 # TODO: OP_TLBIE
820 MicrOp.OP_RFID.value]:
821 instr_is_privileged = True
822 if int_op in [MicrOp.OP_MFSPR.value,
823 MicrOp.OP_MTSPR.value] and spr_msb:
824 instr_is_privileged = True
825
826 print("is priv", instr_is_privileged, hex(self.msr.value),
827 self.msr[MSRb.PR])
828 # check MSR priv bit and whether op is privileged: if so, throw trap
829 if instr_is_privileged and self.msr[MSRb.PR] == 1:
830 self.TRAP(0x700, PIb.PRIV)
831 self.namespace['NIA'] = self.trap_nia
832 self.pc.update(self.namespace, self.is_svp64_mode)
833 return
834
835 # check halted condition
836 if name == 'attn':
837 self.halted = True
838 return
839
840 # check illegal instruction
841 illegal = False
842 if name not in ['mtcrf', 'mtocrf']:
843 illegal = name != asmop
844
845 if illegal:
846 print("illegal", name, asmop)
847 self.TRAP(0x700, PIb.ILLEG)
848 self.namespace['NIA'] = self.trap_nia
849 self.pc.update(self.namespace, self.is_svp64_mode)
850 print("name %s != %s - calling ILLEGAL trap, PC: %x" %
851 (name, asmop, self.pc.CIA.value))
852 return
853
854 info = self.instrs[name]
855 yield from self.prep_namespace(info.form, info.op_fields)
856
857 # preserve order of register names
858 input_names = create_args(list(info.read_regs) +
859 list(info.uninit_regs))
860 print(input_names)
861
862 # get SVP64 entry for the current instruction
863 sv_rm = self.svp64rm.instrs.get(name)
864 if sv_rm is not None:
865 dest_cr, src_cr, src_byname, dest_byname = decode_extra(sv_rm)
866 else:
867 dest_cr, src_cr, src_byname, dest_byname = False, False, {}, {}
868 print ("sv rm", sv_rm, dest_cr, src_cr, src_byname, dest_byname)
869
870 # get SVSTATE srcstep. TODO: dststep (twin predication)
871 srcstep = self.svstate.srcstep.asint(msb0=True)
872
873 # main input registers (RT, RA ...)
874 inputs = []
875 for name in input_names:
876 # using PowerDecoder2, first, find the decoder index.
877 # (mapping name RA RB RC RS to in1, in2, in3)
878 regnum, is_vec = yield from get_pdecode_idx_in(self.dec2, name)
879 if regnum is None:
880 # doing this is not part of svp64, it's because output
881 # registers, to be modified, need to be in the namespace.
882 regnum, is_vec = yield from get_pdecode_idx_out(self.dec2, name)
883 # here's where we go "vector". TODO: zero-testing (RA_IS_ZERO)
884 if is_vec:
885 regnum += srcstep # TODO, elwidth overrides
886
887 # in case getting the register number is needed, _RA, _RB
888 regname = "_" + name
889 self.namespace[regname] = regnum
890 print('reading reg %s %d' % (name, regnum), is_vec)
891 reg_val = self.gpr(regnum)
892 inputs.append(reg_val)
893
894 # "special" registers
895 for special in info.special_regs:
896 if special in special_sprs:
897 inputs.append(self.spr[special])
898 else:
899 inputs.append(self.namespace[special])
900
901 # clear trap (trap) NIA
902 self.trap_nia = None
903
904 print(inputs)
905 results = info.func(self, *inputs)
906 print(results)
907
908 # "inject" decorator takes namespace from function locals: we need to
909 # overwrite NIA being overwritten (sigh)
910 if self.trap_nia is not None:
911 self.namespace['NIA'] = self.trap_nia
912
913 print("after func", self.namespace['CIA'], self.namespace['NIA'])
914
915 # detect if CA/CA32 already in outputs (sra*, basically)
916 already_done = 0
917 if info.write_regs:
918 output_names = create_args(info.write_regs)
919 for name in output_names:
920 if name == 'CA':
921 already_done |= 1
922 if name == 'CA32':
923 already_done |= 2
924
925 print("carry already done?", bin(already_done))
926 if hasattr(self.dec2.e.do, "output_carry"):
927 carry_en = yield self.dec2.e.do.output_carry
928 else:
929 carry_en = False
930 if carry_en:
931 yield from self.handle_carry_(inputs, results, already_done)
932
933 # detect if overflow was in return result
934 overflow = None
935 if info.write_regs:
936 for name, output in zip(output_names, results):
937 if name == 'overflow':
938 overflow = output
939
940 if hasattr(self.dec2.e.do, "oe"):
941 ov_en = yield self.dec2.e.do.oe.oe
942 ov_ok = yield self.dec2.e.do.oe.ok
943 else:
944 ov_en = False
945 ov_ok = False
946 print("internal overflow", overflow, ov_en, ov_ok)
947 if ov_en & ov_ok:
948 yield from self.handle_overflow(inputs, results, overflow)
949
950 if hasattr(self.dec2.e.do, "rc"):
951 rc_en = yield self.dec2.e.do.rc.rc
952 else:
953 rc_en = False
954 if rc_en:
955 self.handle_comparison(results)
956
957 # svp64 loop can end early if the dest is scalar
958 svp64_dest_vector = False
959
960 # any modified return results?
961 if info.write_regs:
962 for name, output in zip(output_names, results):
963 if name == 'overflow': # ignore, done already (above)
964 continue
965 if isinstance(output, int):
966 output = SelectableInt(output, 256)
967 if name in ['CA', 'CA32']:
968 if carry_en:
969 print("writing %s to XER" % name, output)
970 self.spr['XER'][XER_bits[name]] = output.value
971 else:
972 print("NOT writing %s to XER" % name, output)
973 elif name in info.special_regs:
974 print('writing special %s' % name, output, special_sprs)
975 if name in special_sprs:
976 self.spr[name] = output
977 else:
978 self.namespace[name].eq(output)
979 if name == 'MSR':
980 print('msr written', hex(self.msr.value))
981 else:
982 regnum, is_vec = yield from get_pdecode_idx_out(self.dec2,
983 name)
984 if regnum is None:
985 # temporary hack for not having 2nd output
986 regnum = yield getattr(self.decoder, name)
987 is_vec = False
988 # here's where we go "vector".
989 if is_vec:
990 regnum += srcstep # TODO, elwidth overrides
991 svp64_dest_vector = True
992 print('writing reg %d %s' % (regnum, str(output)), is_vec)
993 if output.bits > 64:
994 output = SelectableInt(output.value, 64)
995 self.gpr[regnum] = output
996
997 # check if it is the SVSTATE.src/dest step that needs incrementing
998 # this is our Sub-Program-Counter loop from 0 to VL-1
999 if self.is_svp64_mode:
1000 # XXX twin predication TODO
1001 vl = self.svstate.vl.asint(msb0=True)
1002 mvl = self.svstate.maxvl.asint(msb0=True)
1003 srcstep = self.svstate.srcstep.asint(msb0=True)
1004 print (" svstate.vl", vl)
1005 print (" svstate.mvl", mvl)
1006 print (" svstate.srcstep", srcstep)
1007 # check if srcstep needs incrementing by one, stop PC advancing
1008 if svp64_dest_vector and srcstep != vl-1:
1009 self.svstate.srcstep += SelectableInt(1, 7)
1010 self.pc.NIA.value = self.pc.CIA.value
1011 self.namespace['NIA'] = self.pc.NIA
1012 print("end of sub-pc call", self.namespace['CIA'],
1013 self.namespace['NIA'])
1014 return # DO NOT allow PC to update whilst Sub-PC loop running
1015 # reset to zero
1016 self.svstate.srcstep[0:7] = 0
1017 print (" svstate.srcstep loop end (PC to update)")
1018 self.pc.update_nia(self.is_svp64_mode)
1019 self.namespace['NIA'] = self.pc.NIA
1020
1021 # UPDATE program counter
1022 self.pc.update(self.namespace, self.is_svp64_mode)
1023 print("end of call", self.namespace['CIA'], self.namespace['NIA'])
1024
1025
1026 def inject():
1027 """Decorator factory.
1028
1029 this decorator will "inject" variables into the function's namespace,
1030 from the *dictionary* in self.namespace. it therefore becomes possible
1031 to make it look like a whole stack of variables which would otherwise
1032 need "self." inserted in front of them (*and* for those variables to be
1033 added to the instance) "appear" in the function.
1034
1035 "self.namespace['SI']" for example becomes accessible as just "SI" but
1036 *only* inside the function, when decorated.
1037 """
1038 def variable_injector(func):
1039 @wraps(func)
1040 def decorator(*args, **kwargs):
1041 try:
1042 func_globals = func.__globals__ # Python 2.6+
1043 except AttributeError:
1044 func_globals = func.func_globals # Earlier versions.
1045
1046 context = args[0].namespace # variables to be injected
1047 saved_values = func_globals.copy() # Shallow copy of dict.
1048 func_globals.update(context)
1049 result = func(*args, **kwargs)
1050 print("globals after", func_globals['CIA'], func_globals['NIA'])
1051 print("args[0]", args[0].namespace['CIA'],
1052 args[0].namespace['NIA'])
1053 args[0].namespace = func_globals
1054 #exec (func.__code__, func_globals)
1055
1056 # finally:
1057 # func_globals = saved_values # Undo changes.
1058
1059 return result
1060
1061 return decorator
1062
1063 return variable_injector