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