e5fdfc5a526190764e71d00cb26fd0eda4b87390
[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
268 # "fake program counter" mode (for unit testing)
269 self.fake_pc = 0
270 disasm_start = 0
271 if not respect_pc:
272 if isinstance(initial_mem, tuple):
273 self.fake_pc = initial_mem[0]
274 disasm_start = self.fake_pc
275 else:
276 disasm_start = initial_pc
277
278 # disassembly: we need this for now (not given from the decoder)
279 self.disassembly = {}
280 if disassembly:
281 for i, code in enumerate(disassembly):
282 self.disassembly[i*4 + disasm_start] = code
283
284 # set up registers, instruction memory, data memory, PC, SPRs, MSR
285 self.gpr = GPR(decoder2, regfile)
286 self.mem = Mem(row_bytes=8, initial_mem=initial_mem)
287 self.imem = Mem(row_bytes=4, initial_mem=initial_insns)
288 self.pc = PC()
289 self.spr = SPR(decoder2, initial_sprs)
290 self.msr = SelectableInt(initial_msr, 64) # underlying reg
291
292 # TODO, needed here:
293 # FPR (same as GPR except for FP nums)
294 # 4.2.2 p124 FPSCR (definitely "separate" - not in SPR)
295 # note that mffs, mcrfs, mtfsf "manage" this FPSCR
296 # 2.3.1 CR (and sub-fields CR0..CR6 - CR0 SO comes from XER.SO)
297 # note that mfocrf, mfcr, mtcr, mtocrf, mcrxrx "manage" CRs
298 # -- Done
299 # 2.3.2 LR (actually SPR #8) -- Done
300 # 2.3.3 CTR (actually SPR #9) -- Done
301 # 2.3.4 TAR (actually SPR #815)
302 # 3.2.2 p45 XER (actually SPR #1) -- Done
303 # 3.2.3 p46 p232 VRSAVE (actually SPR #256)
304
305 # create CR then allow portions of it to be "selectable" (below)
306 self._cr = SelectableInt(initial_cr, 64) # underlying reg
307 self.cr = FieldSelectableInt(self._cr, list(range(32,64)))
308
309 # "undefined", just set to variable-bit-width int (use exts "max")
310 self.undefined = SelectableInt(0, 256) # TODO, not hard-code 256!
311
312 self.namespace = {}
313 self.namespace.update(self.spr)
314 self.namespace.update({'GPR': self.gpr,
315 'MEM': self.mem,
316 'SPR': self.spr,
317 'memassign': self.memassign,
318 'NIA': self.pc.NIA,
319 'CIA': self.pc.CIA,
320 'CR': self.cr,
321 'MSR': self.msr,
322 'undefined': self.undefined,
323 'mode_is_64bit': True,
324 'SO': XER_bits['SO']
325 })
326
327 # update pc to requested start point
328 self.set_pc(initial_pc)
329
330 # field-selectable versions of Condition Register TODO check bitranges?
331 self.crl = []
332 for i in range(8):
333 bits = tuple(range(i*4, (i+1)*4))# errr... maybe?
334 _cr = FieldSelectableInt(self.cr, bits)
335 self.crl.append(_cr)
336 self.namespace["CR%d" % i] = _cr
337
338 self.decoder = decoder2.dec
339 self.dec2 = decoder2
340
341 def TRAP(self, trap_addr=0x700, trap_bit=PI.TRAP):
342 print ("TRAP:", hex(trap_addr))
343 # store CIA(+4?) in SRR0, set NIA to 0x700
344 # store MSR in SRR1, set MSR to um errr something, have to check spec
345 self.spr['SRR0'] = self.pc.CIA
346 self.spr['SRR1'] = self.namespace['MSR']
347 self.trap_nia = SelectableInt(trap_addr, 64)
348 self.namespace['MSR'][63-trap_bit] = 1
349
350 def memassign(self, ea, sz, val):
351 self.mem.memassign(ea, sz, val)
352
353 def prep_namespace(self, formname, op_fields):
354 # TODO: get field names from form in decoder*1* (not decoder2)
355 # decoder2 is hand-created, and decoder1.sigform is auto-generated
356 # from spec
357 # then "yield" fields only from op_fields rather than hard-coded
358 # list, here.
359 fields = self.decoder.sigforms[formname]
360 for name in op_fields:
361 if name == 'spr':
362 sig = getattr(fields, name.upper())
363 else:
364 sig = getattr(fields, name)
365 val = yield sig
366 if name in ['BF', 'BFA']:
367 self.namespace[name] = val
368 else:
369 self.namespace[name] = SelectableInt(val, sig.width)
370
371 self.namespace['XER'] = self.spr['XER']
372 self.namespace['CA'] = self.spr['XER'][XER_bits['CA']].value
373 self.namespace['CA32'] = self.spr['XER'][XER_bits['CA32']].value
374
375 def handle_carry_(self, inputs, outputs, already_done):
376 inv_a = yield self.dec2.e.do.invert_a
377 if inv_a:
378 inputs[0] = ~inputs[0]
379
380 imm_ok = yield self.dec2.e.do.imm_data.ok
381 if imm_ok:
382 imm = yield self.dec2.e.do.imm_data.data
383 inputs.append(SelectableInt(imm, 64))
384 assert len(outputs) >= 1
385 print ("outputs", repr(outputs))
386 if isinstance(outputs, list) or isinstance(outputs, tuple):
387 output = outputs[0]
388 else:
389 output = outputs
390 gts = []
391 for x in inputs:
392 print ("gt input", x, output)
393 gt = (x > output)
394 gts.append(gt)
395 print(gts)
396 cy = 1 if any(gts) else 0
397 if not (1 & already_done):
398 self.spr['XER'][XER_bits['CA']] = cy
399
400 print ("inputs", inputs)
401 # 32 bit carry
402 gts = []
403 for x in inputs:
404 print ("input", x, output)
405 gt = (x[32:64] > output[32:64]) == SelectableInt(1, 1)
406 gts.append(gt)
407 cy32 = 1 if any(gts) else 0
408 if not (2 & already_done):
409 self.spr['XER'][XER_bits['CA32']] = cy32
410
411 def handle_overflow(self, inputs, outputs, div_overflow):
412 inv_a = yield self.dec2.e.do.invert_a
413 if inv_a:
414 inputs[0] = ~inputs[0]
415
416 imm_ok = yield self.dec2.e.do.imm_data.ok
417 if imm_ok:
418 imm = yield self.dec2.e.do.imm_data.data
419 inputs.append(SelectableInt(imm, 64))
420 assert len(outputs) >= 1
421 print ("handle_overflow", inputs, outputs, div_overflow)
422 if len(inputs) < 2 and div_overflow is None:
423 return
424
425 # div overflow is different: it's returned by the pseudo-code
426 # because it's more complex than can be done by analysing the output
427 if div_overflow is not None:
428 ov, ov32 = div_overflow, div_overflow
429 # arithmetic overflow can be done by analysing the input and output
430 elif len(inputs) >= 2:
431 output = outputs[0]
432
433 # OV (64-bit)
434 input_sgn = [exts(x.value, x.bits) < 0 for x in inputs]
435 output_sgn = exts(output.value, output.bits) < 0
436 ov = 1 if input_sgn[0] == input_sgn[1] and \
437 output_sgn != input_sgn[0] else 0
438
439 # OV (32-bit)
440 input32_sgn = [exts(x.value, 32) < 0 for x in inputs]
441 output32_sgn = exts(output.value, 32) < 0
442 ov32 = 1 if input32_sgn[0] == input32_sgn[1] and \
443 output32_sgn != input32_sgn[0] else 0
444
445 self.spr['XER'][XER_bits['OV']] = ov
446 self.spr['XER'][XER_bits['OV32']] = ov32
447 so = self.spr['XER'][XER_bits['SO']]
448 so = so | ov
449 self.spr['XER'][XER_bits['SO']] = so
450
451 def handle_comparison(self, outputs):
452 out = outputs[0]
453 print ("handle_comparison", out.bits, hex(out.value))
454 # TODO - XXX *processor* in 32-bit mode
455 # https://bugs.libre-soc.org/show_bug.cgi?id=424
456 #if is_32bit:
457 # o32 = exts(out.value, 32)
458 # print ("handle_comparison exts 32 bit", hex(o32))
459 out = exts(out.value, out.bits)
460 print ("handle_comparison exts", hex(out))
461 zero = SelectableInt(out == 0, 1)
462 positive = SelectableInt(out > 0, 1)
463 negative = SelectableInt(out < 0, 1)
464 SO = self.spr['XER'][XER_bits['SO']]
465 print ("handle_comparison SO", SO)
466 cr_field = selectconcat(negative, positive, zero, SO)
467 self.crl[0].eq(cr_field)
468
469 def set_pc(self, pc_val):
470 self.namespace['NIA'] = SelectableInt(pc_val, 64)
471 self.pc.update(self.namespace)
472
473 def setup_one(self):
474 """set up one instruction
475 """
476 if self.respect_pc:
477 pc = self.pc.CIA.value
478 else:
479 pc = self.fake_pc
480 self._pc = pc
481 ins = self.imem.ld(pc, 4, False, True)
482 if ins is None:
483 raise KeyError("no instruction at 0x%x" % pc)
484 print("setup: 0x%x 0x%x %s" % (pc, ins & 0xffffffff, bin(ins)))
485 print ("CIA NIA", self.respect_pc, self.pc.CIA.value, self.pc.NIA.value)
486
487 yield self.dec2.dec.raw_opcode_in.eq(ins & 0xffffffff)
488 yield self.dec2.dec.bigendian.eq(self.bigendian)
489
490 def execute_one(self):
491 """execute one instruction
492 """
493 # get the disassembly code for this instruction
494 code = self.disassembly[self._pc]
495 print("sim-execute", hex(self._pc), code)
496 opname = code.split(' ')[0]
497 yield from self.call(opname)
498
499 if not self.respect_pc:
500 self.fake_pc += 4
501 print ("execute one, CIA NIA", self.pc.CIA.value, self.pc.NIA.value)
502
503 def get_assembly_name(self):
504 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
505 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
506 asmcode = yield self.dec2.dec.op.asmcode
507 print ("get assembly name asmcode", asmcode)
508 asmop = insns.get(asmcode, None)
509 int_op = yield self.dec2.dec.op.internal_op
510
511 # sigh reconstruct the assembly instruction name
512 ov_en = yield self.dec2.e.do.oe.oe
513 ov_ok = yield self.dec2.e.do.oe.ok
514 rc_en = yield self.dec2.e.do.rc.data
515 rc_ok = yield self.dec2.e.do.rc.ok
516 # grrrr have to special-case MUL op (see DecodeOE)
517 print ("ov en rc en", ov_ok, ov_en, rc_ok, rc_en, int_op)
518 if int_op in [MicrOp.OP_MUL_H64.value, MicrOp.OP_MUL_H32.value]:
519 print ("mul op")
520 if rc_en & rc_ok:
521 asmop += "."
522 else:
523 if ov_en & ov_ok:
524 asmop += "."
525 lk = yield self.dec2.e.do.lk
526 if lk:
527 asmop += "l"
528 print ("int_op", int_op)
529 if int_op in [MicrOp.OP_B.value, MicrOp.OP_BC.value]:
530 AA = yield self.dec2.dec.fields.FormI.AA[0:-1]
531 print ("AA", AA)
532 if AA:
533 asmop += "a"
534 if int_op == MicrOp.OP_MFCR.value:
535 dec_insn = yield self.dec2.e.do.insn
536 if dec_insn & (1<<20) != 0: # sigh
537 asmop = 'mfocrf'
538 else:
539 asmop = 'mfcr'
540 # XXX TODO: for whatever weird reason this doesn't work
541 # https://bugs.libre-soc.org/show_bug.cgi?id=390
542 if int_op == MicrOp.OP_MTCRF.value:
543 dec_insn = yield self.dec2.e.do.insn
544 if dec_insn & (1<<20) != 0: # sigh
545 asmop = 'mtocrf'
546 else:
547 asmop = 'mtcrf'
548 return asmop
549
550 def call(self, name):
551 name = name.strip() # remove spaces if not already done so
552 if self.halted:
553 print ("halted - not executing", name)
554 return
555
556 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
557 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
558 asmop = yield from self.get_assembly_name()
559 print ("call", name, asmop)
560
561 # check halted condition
562 if name == 'attn':
563 self.halted = True
564 return
565
566 # check illegal instruction
567 illegal = False
568 if name not in ['mtcrf', 'mtocrf']:
569 illegal = name != asmop
570
571 if illegal:
572 print ("name %s != %s - calling ILLEGAL trap" % (name, asmop))
573 self.TRAP(0x700, PI.ILLEG)
574 self.namespace['NIA'] = self.trap_nia
575 self.pc.update(self.namespace)
576 return
577
578 info = self.instrs[name]
579 yield from self.prep_namespace(info.form, info.op_fields)
580
581 # preserve order of register names
582 input_names = create_args(list(info.read_regs) +
583 list(info.uninit_regs))
584 print(input_names)
585
586 # main registers (RT, RA ...)
587 inputs = []
588 for name in input_names:
589 regnum = yield getattr(self.decoder, name)
590 regname = "_" + name
591 self.namespace[regname] = regnum
592 print('reading reg %d' % regnum)
593 inputs.append(self.gpr(regnum))
594
595 # "special" registers
596 for special in info.special_regs:
597 if special in special_sprs:
598 inputs.append(self.spr[special])
599 else:
600 inputs.append(self.namespace[special])
601
602 # clear trap (trap) NIA
603 self.trap_nia = None
604
605 print(inputs)
606 results = info.func(self, *inputs)
607 print(results)
608
609 # "inject" decorator takes namespace from function locals: we need to
610 # overwrite NIA being overwritten (sigh)
611 if self.trap_nia is not None:
612 self.namespace['NIA'] = self.trap_nia
613
614 print ("after func", self.namespace['CIA'], self.namespace['NIA'])
615
616 # detect if CA/CA32 already in outputs (sra*, basically)
617 already_done = 0
618 if info.write_regs:
619 output_names = create_args(info.write_regs)
620 for name in output_names:
621 if name == 'CA':
622 already_done |= 1
623 if name == 'CA32':
624 already_done |= 2
625
626 print ("carry already done?", bin(already_done))
627 carry_en = yield self.dec2.e.do.output_carry
628 if carry_en:
629 yield from self.handle_carry_(inputs, results, already_done)
630
631 # detect if overflow was in return result
632 overflow = None
633 if info.write_regs:
634 for name, output in zip(output_names, results):
635 if name == 'overflow':
636 overflow = output
637
638 ov_en = yield self.dec2.e.do.oe.oe
639 ov_ok = yield self.dec2.e.do.oe.ok
640 print ("internal overflow", overflow, ov_en, ov_ok)
641 if ov_en & ov_ok:
642 yield from self.handle_overflow(inputs, results, overflow)
643
644 rc_en = yield self.dec2.e.do.rc.data
645 if rc_en:
646 self.handle_comparison(results)
647
648 # any modified return results?
649 if info.write_regs:
650 for name, output in zip(output_names, results):
651 if name == 'overflow': # ignore, done already (above)
652 continue
653 if isinstance(output, int):
654 output = SelectableInt(output, 256)
655 if name in ['CA', 'CA32']:
656 if carry_en:
657 print ("writing %s to XER" % name, output)
658 self.spr['XER'][XER_bits[name]] = output.value
659 else:
660 print ("NOT writing %s to XER" % name, output)
661 elif name in info.special_regs:
662 print('writing special %s' % name, output, special_sprs)
663 if name in special_sprs:
664 self.spr[name] = output
665 else:
666 self.namespace[name].eq(output)
667 if name == 'MSR':
668 print ('msr written', hex(self.msr.value))
669 else:
670 regnum = yield getattr(self.decoder, name)
671 print('writing reg %d %s' % (regnum, str(output)))
672 if output.bits > 64:
673 output = SelectableInt(output.value, 64)
674 self.gpr[regnum] = output
675
676 print ("end of call", self.namespace['CIA'], self.namespace['NIA'])
677 # UPDATE program counter
678 self.pc.update(self.namespace)
679
680
681 def inject():
682 """Decorator factory.
683
684 this decorator will "inject" variables into the function's namespace,
685 from the *dictionary* in self.namespace. it therefore becomes possible
686 to make it look like a whole stack of variables which would otherwise
687 need "self." inserted in front of them (*and* for those variables to be
688 added to the instance) "appear" in the function.
689
690 "self.namespace['SI']" for example becomes accessible as just "SI" but
691 *only* inside the function, when decorated.
692 """
693 def variable_injector(func):
694 @wraps(func)
695 def decorator(*args, **kwargs):
696 try:
697 func_globals = func.__globals__ # Python 2.6+
698 except AttributeError:
699 func_globals = func.func_globals # Earlier versions.
700
701 context = args[0].namespace # variables to be injected
702 saved_values = func_globals.copy() # Shallow copy of dict.
703 func_globals.update(context)
704 result = func(*args, **kwargs)
705 print ("globals after", func_globals['CIA'], func_globals['NIA'])
706 print ("args[0]", args[0].namespace['CIA'],
707 args[0].namespace['NIA'])
708 args[0].namespace = func_globals
709 #exec (func.__code__, func_globals)
710
711 #finally:
712 # func_globals = saved_values # Undo changes.
713
714 return result
715
716 return decorator
717
718 return variable_injector
719