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