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