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