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