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