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