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