add a fake program counter to ISACaller
[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
8 from functools import wraps
9 from soc.decoder.orderedset import OrderedSet
10 from soc.decoder.selectable_int import (FieldSelectableInt, SelectableInt,
11 selectconcat)
12 from soc.decoder.power_enums import spr_dict, XER_bits
13 from soc.decoder.helpers import exts
14 from collections import namedtuple
15 import math
16
17 instruction_info = namedtuple('instruction_info',
18 'func read_regs uninit_regs write_regs ' + \
19 'special_regs op_fields form asmregs')
20
21 special_sprs = {
22 'LR': 8,
23 'CTR': 9,
24 'TAR': 815,
25 'XER': 1,
26 'VRSAVE': 256}
27
28
29 def swap_order(x, nbytes):
30 x = x.to_bytes(nbytes, byteorder='little')
31 x = int.from_bytes(x, byteorder='big', signed=False)
32 return x
33
34
35 def create_args(reglist, extra=None):
36 args = OrderedSet()
37 for reg in reglist:
38 args.add(reg)
39 args = list(args)
40 if extra:
41 args = [extra] + args
42 return args
43
44
45 class Mem:
46
47 def __init__(self, row_bytes=8, initial_mem=None):
48 self.mem = {}
49 self.bytes_per_word = row_bytes
50 self.word_log2 = math.ceil(math.log2(row_bytes))
51 print ("Sim-Mem", initial_mem, self.bytes_per_word, self.word_log2)
52 if not initial_mem:
53 return
54
55 # different types of memory data structures recognised (for convenience)
56 if isinstance(initial_mem, list):
57 initial_mem = (0, initial_mem)
58 if isinstance(initial_mem, tuple):
59 startaddr, mem = initial_mem
60 initial_mem = {}
61 for i, val in enumerate(mem):
62 initial_mem[startaddr + row_bytes*i] = (val, row_bytes)
63
64 for addr, (val, width) in initial_mem.items():
65 #val = swap_order(val, width)
66 self.st(addr, val, width, swap=False)
67
68 def _get_shifter_mask(self, wid, remainder):
69 shifter = ((self.bytes_per_word - wid) - remainder) * \
70 8 # bits per byte
71 # XXX https://bugs.libre-soc.org/show_bug.cgi?id=377
72 # BE/LE mode?
73 shifter = remainder * 8
74 mask = (1 << (wid * 8)) - 1
75 print ("width,rem,shift,mask", wid, remainder, hex(shifter), hex(mask))
76 return shifter, mask
77
78 # TODO: Implement ld/st of lesser width
79 def ld(self, address, width=8, swap=True):
80 print("ld from addr 0x{:x} width {:d}".format(address, width))
81 remainder = address & (self.bytes_per_word - 1)
82 address = address >> self.word_log2
83 assert remainder & (width - 1) == 0, "Unaligned access unsupported!"
84 if address in self.mem:
85 val = self.mem[address]
86 else:
87 val = 0
88 print("mem @ 0x{:x} rem {:d} : 0x{:x}".format(address, remainder, val))
89
90 if width != self.bytes_per_word:
91 shifter, mask = self._get_shifter_mask(width, remainder)
92 print ("masking", hex(val), hex(mask<<shifter), shifter)
93 val = val & (mask << shifter)
94 val >>= shifter
95 if swap:
96 val = swap_order(val, width)
97 print("Read 0x{:x} from addr 0x{:x}".format(val, address))
98 return val
99
100 def st(self, addr, v, width=8, swap=True):
101 staddr = addr
102 remainder = addr & (self.bytes_per_word - 1)
103 addr = addr >> self.word_log2
104 print("Writing 0x{:x} to ST 0x{:x} memaddr 0x{:x}/{:x}".format(v,
105 staddr, addr, remainder, swap))
106 assert remainder & (width - 1) == 0, "Unaligned access unsupported!"
107 if swap:
108 v = swap_order(v, width)
109 if width != self.bytes_per_word:
110 if addr in self.mem:
111 val = self.mem[addr]
112 else:
113 val = 0
114 shifter, mask = self._get_shifter_mask(width, remainder)
115 val &= ~(mask << shifter)
116 val |= v << shifter
117 self.mem[addr] = val
118 else:
119 self.mem[addr] = v
120 print("mem @ 0x{:x}: 0x{:x}".format(addr, self.mem[addr]))
121
122 def __call__(self, addr, sz):
123 val = self.ld(addr.value, sz)
124 print ("memread", addr, sz, val)
125 return SelectableInt(val, sz*8)
126
127 def memassign(self, addr, sz, val):
128 print ("memassign", addr, sz, val)
129 self.st(addr.value, val.value, sz)
130
131
132 class GPR(dict):
133 def __init__(self, decoder, regfile):
134 dict.__init__(self)
135 self.sd = decoder
136 for i in range(32):
137 self[i] = SelectableInt(regfile[i], 64)
138
139 def __call__(self, ridx):
140 return self[ridx]
141
142 def set_form(self, form):
143 self.form = form
144
145 def getz(self, rnum):
146 #rnum = rnum.value # only SelectableInt allowed
147 print("GPR getzero", rnum)
148 if rnum == 0:
149 return SelectableInt(0, 64)
150 return self[rnum]
151
152 def _get_regnum(self, attr):
153 getform = self.sd.sigforms[self.form]
154 rnum = getattr(getform, attr)
155 return rnum
156
157 def ___getitem__(self, attr):
158 print("GPR getitem", attr)
159 rnum = self._get_regnum(attr)
160 return self.regfile[rnum]
161
162 def dump(self):
163 for i in range(0, len(self), 8):
164 s = []
165 for j in range(8):
166 s.append("%08x" % self[i+j].value)
167 s = ' '.join(s)
168 print("reg", "%2d" % i, s)
169
170 class PC:
171 def __init__(self, pc_init=0):
172 self.CIA = SelectableInt(pc_init, 64)
173 self.NIA = self.CIA + SelectableInt(4, 64)
174
175 def update(self, namespace):
176 self.CIA = namespace['NIA'].narrow(64)
177 self.NIA = self.CIA + SelectableInt(4, 64)
178 namespace['CIA'] = self.CIA
179 namespace['NIA'] = self.NIA
180
181
182 class SPR(dict):
183 def __init__(self, dec2, initial_sprs={}):
184 self.sd = dec2
185 dict.__init__(self)
186 self.update(initial_sprs)
187
188 def __getitem__(self, key):
189 # if key in special_sprs get the special spr, otherwise return key
190 if isinstance(key, SelectableInt):
191 key = key.value
192 key = special_sprs.get(key, key)
193 if key in self:
194 return dict.__getitem__(self, key)
195 else:
196 info = spr_dict[key]
197 dict.__setitem__(self, key, SelectableInt(0, info.length))
198 return dict.__getitem__(self, key)
199
200 def __setitem__(self, key, value):
201 if isinstance(key, SelectableInt):
202 key = key.value
203 key = special_sprs.get(key, key)
204 dict.__setitem__(self, key, value)
205
206 def __call__(self, ridx):
207 return self[ridx]
208
209
210 class ISACaller:
211 # decoder2 - an instance of power_decoder2
212 # regfile - a list of initial values for the registers
213 # initial_{etc} - initial values for SPRs, Condition Register, Mem, MSR
214 # respect_pc - tracks the program counter. requires initial_insns
215 def __init__(self, decoder2, regfile, initial_sprs=None, initial_cr=0,
216 initial_mem=None, initial_msr=0,
217 initial_insns=None, respect_pc=False):
218
219 self.respect_pc = respect_pc
220 if initial_sprs is None:
221 initial_sprs = {}
222 if initial_mem is None:
223 initial_mem = {}
224 if initial_insns is None:
225 initial_insns = {}
226 assert self.respect_pc == False, "instructions required to honor pc"
227
228 # "fake program counter" mode (for unit testing)
229 if not respect_pc:
230 if isinstance(initial_mem, tuple):
231 self.fake_pc = initial_mem[0]
232 else:
233 self.fake_pc = 0
234
235 self.gpr = GPR(decoder2, regfile)
236 self.mem = Mem(row_bytes=8, initial_mem=initial_mem)
237 self.insns = Mem(row_bytes=4, initial_mem=initial_insns)
238 self.pc = PC()
239 self.spr = SPR(decoder2, initial_sprs)
240 self.msr = SelectableInt(initial_msr, 64) # underlying reg
241 # TODO, needed here:
242 # FPR (same as GPR except for FP nums)
243 # 4.2.2 p124 FPSCR (definitely "separate" - not in SPR)
244 # note that mffs, mcrfs, mtfsf "manage" this FPSCR
245 # 2.3.1 CR (and sub-fields CR0..CR6 - CR0 SO comes from XER.SO)
246 # note that mfocrf, mfcr, mtcr, mtocrf, mcrxrx "manage" CRs
247 # -- Done
248 # 2.3.2 LR (actually SPR #8) -- Done
249 # 2.3.3 CTR (actually SPR #9) -- Done
250 # 2.3.4 TAR (actually SPR #815)
251 # 3.2.2 p45 XER (actually SPR #1) -- Done
252 # 3.2.3 p46 p232 VRSAVE (actually SPR #256)
253
254 # create CR then allow portions of it to be "selectable" (below)
255 self._cr = SelectableInt(initial_cr, 64) # underlying reg
256 self.cr = FieldSelectableInt(self._cr, list(range(32,64)))
257
258 # "undefined", just set to variable-bit-width int (use exts "max")
259 self.undefined = SelectableInt(0, 256) # TODO, not hard-code 256!
260
261 self.namespace = {'GPR': self.gpr,
262 'MEM': self.mem,
263 'SPR': self.spr,
264 'memassign': self.memassign,
265 'NIA': self.pc.NIA,
266 'CIA': self.pc.CIA,
267 'CR': self.cr,
268 'MSR': self.msr,
269 'undefined': self.undefined,
270 'mode_is_64bit': True,
271 'SO': XER_bits['SO']
272 }
273
274 # field-selectable versions of Condition Register TODO check bitranges?
275 self.crl = []
276 for i in range(8):
277 bits = tuple(range(i*4, (i+1)*4))# errr... maybe?
278 _cr = FieldSelectableInt(self.cr, bits)
279 self.crl.append(_cr)
280 self.namespace["CR%d" % i] = _cr
281
282 self.decoder = decoder2.dec
283 self.dec2 = decoder2
284
285 def TRAP(self, trap_addr=0x700):
286 print ("TRAP: TODO")
287 # store CIA(+4?) in SRR0, set NIA to 0x700
288 # store MSR in SRR1, set MSR to um errr something, have to check spec
289
290 def memassign(self, ea, sz, val):
291 self.mem.memassign(ea, sz, val)
292
293 def prep_namespace(self, formname, op_fields):
294 # TODO: get field names from form in decoder*1* (not decoder2)
295 # decoder2 is hand-created, and decoder1.sigform is auto-generated
296 # from spec
297 # then "yield" fields only from op_fields rather than hard-coded
298 # list, here.
299 fields = self.decoder.sigforms[formname]
300 for name in op_fields:
301 if name == 'spr':
302 sig = getattr(fields, name.upper())
303 else:
304 sig = getattr(fields, name)
305 val = yield sig
306 if name in ['BF', 'BFA']:
307 self.namespace[name] = val
308 else:
309 self.namespace[name] = SelectableInt(val, sig.width)
310
311 self.namespace['XER'] = self.spr['XER']
312 self.namespace['CA'] = self.spr['XER'][XER_bits['CA']].value
313 self.namespace['CA32'] = self.spr['XER'][XER_bits['CA32']].value
314
315 def handle_carry_(self, inputs, outputs, already_done):
316 inv_a = yield self.dec2.e.invert_a
317 if inv_a:
318 inputs[0] = ~inputs[0]
319
320 imm_ok = yield self.dec2.e.imm_data.ok
321 if imm_ok:
322 imm = yield self.dec2.e.imm_data.data
323 inputs.append(SelectableInt(imm, 64))
324 assert len(outputs) >= 1
325 output = outputs[0]
326 gts = [(x > output) for x in inputs]
327 print(gts)
328 cy = 1 if any(gts) else 0
329 if not (1 & already_done):
330 self.spr['XER'][XER_bits['CA']] = cy
331
332 print ("inputs", inputs)
333 # 32 bit carry
334 gts = [(x[32:64] > output[32:64]) == SelectableInt(1, 1)
335 for x in inputs]
336 cy32 = 1 if any(gts) else 0
337 if not (2 & already_done):
338 self.spr['XER'][XER_bits['CA32']] = cy32
339
340 def handle_overflow(self, inputs, outputs):
341 inv_a = yield self.dec2.e.invert_a
342 if inv_a:
343 inputs[0] = ~inputs[0]
344
345 imm_ok = yield self.dec2.e.imm_data.ok
346 if imm_ok:
347 imm = yield self.dec2.e.imm_data.data
348 inputs.append(SelectableInt(imm, 64))
349 assert len(outputs) >= 1
350 print ("handle_overflow", inputs, outputs)
351 if len(inputs) >= 2:
352 output = outputs[0]
353
354 # OV (64-bit)
355 input_sgn = [exts(x.value, x.bits) < 0 for x in inputs]
356 output_sgn = exts(output.value, output.bits) < 0
357 ov = 1 if input_sgn[0] == input_sgn[1] and \
358 output_sgn != input_sgn[0] else 0
359
360 # OV (32-bit)
361 input32_sgn = [exts(x.value, 32) < 0 for x in inputs]
362 output32_sgn = exts(output.value, 32) < 0
363 ov32 = 1 if input32_sgn[0] == input32_sgn[1] and \
364 output32_sgn != input32_sgn[0] else 0
365
366 self.spr['XER'][XER_bits['OV']] = ov
367 self.spr['XER'][XER_bits['OV32']] = ov32
368 so = self.spr['XER'][XER_bits['SO']]
369 so = so | ov
370 self.spr['XER'][XER_bits['SO']] = so
371
372
373
374 def handle_comparison(self, outputs):
375 out = outputs[0]
376 out = exts(out.value, out.bits)
377 zero = SelectableInt(out == 0, 1)
378 positive = SelectableInt(out > 0, 1)
379 negative = SelectableInt(out < 0, 1)
380 SO = self.spr['XER'][XER_bits['SO']]
381 cr_field = selectconcat(negative, positive, zero, SO)
382 self.crl[0].eq(cr_field)
383
384 def set_pc(self, pc_val):
385 self.namespace['NIA'] = SelectableInt(pc_val, 64)
386 self.pc.update(self.namespace)
387
388 def call(self, name):
389 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
390 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
391 info = self.instrs[name]
392 yield from self.prep_namespace(info.form, info.op_fields)
393
394 # preserve order of register names
395 input_names = create_args(list(info.read_regs) + list(info.uninit_regs))
396 print(input_names)
397
398 # main registers (RT, RA ...)
399 inputs = []
400 for name in input_names:
401 regnum = yield getattr(self.decoder, name)
402 regname = "_" + name
403 self.namespace[regname] = regnum
404 print('reading reg %d' % regnum)
405 inputs.append(self.gpr(regnum))
406
407 # "special" registers
408 for special in info.special_regs:
409 if special in special_sprs:
410 inputs.append(self.spr[special])
411 else:
412 inputs.append(self.namespace[special])
413
414 print(inputs)
415 results = info.func(self, *inputs)
416 print(results)
417
418 # detect if CA/CA32 already in outputs (sra*, basically)
419 already_done = 0
420 if info.write_regs:
421 output_names = create_args(info.write_regs)
422 for name in output_names:
423 if name == 'CA':
424 already_done |= 1
425 if name == 'CA32':
426 already_done |= 2
427
428 print ("carry already done?", bin(already_done))
429 carry_en = yield self.dec2.e.output_carry
430 if carry_en:
431 yield from self.handle_carry_(inputs, results, already_done)
432 ov_en = yield self.dec2.e.oe.oe
433 ov_ok = yield self.dec2.e.oe.ok
434 if ov_en & ov_ok:
435 yield from self.handle_overflow(inputs, results)
436 rc_en = yield self.dec2.e.rc.data
437 if rc_en:
438 self.handle_comparison(results)
439
440 # any modified return results?
441 if info.write_regs:
442 for name, output in zip(output_names, results):
443 if isinstance(output, int):
444 output = SelectableInt(output, 256)
445 if name in ['CA', 'CA32']:
446 if carry_en:
447 print ("writing %s to XER" % name, output)
448 self.spr['XER'][XER_bits[name]] = output.value
449 else:
450 print ("NOT writing %s to XER" % name, output)
451 elif name in info.special_regs:
452 print('writing special %s' % name, output, special_sprs)
453 if name in special_sprs:
454 self.spr[name] = output
455 else:
456 self.namespace[name].eq(output)
457 else:
458 regnum = yield getattr(self.decoder, name)
459 print('writing reg %d %s' % (regnum, str(output)))
460 if output.bits > 64:
461 output = SelectableInt(output.value, 64)
462 self.gpr[regnum] = output
463
464 # update program counter
465 self.pc.update(self.namespace)
466
467
468 def inject():
469 """Decorator factory.
470
471 this decorator will "inject" variables into the function's namespace,
472 from the *dictionary* in self.namespace. it therefore becomes possible
473 to make it look like a whole stack of variables which would otherwise
474 need "self." inserted in front of them (*and* for those variables to be
475 added to the instance) "appear" in the function.
476
477 "self.namespace['SI']" for example becomes accessible as just "SI" but
478 *only* inside the function, when decorated.
479 """
480 def variable_injector(func):
481 @wraps(func)
482 def decorator(*args, **kwargs):
483 try:
484 func_globals = func.__globals__ # Python 2.6+
485 except AttributeError:
486 func_globals = func.func_globals # Earlier versions.
487
488 context = args[0].namespace # variables to be injected
489 saved_values = func_globals.copy() # Shallow copy of dict.
490 func_globals.update(context)
491 result = func(*args, **kwargs)
492 args[0].namespace = func_globals
493 #exec (func.__code__, func_globals)
494
495 #finally:
496 # func_globals = saved_values # Undo changes.
497
498 return result
499
500 return decorator
501
502 return variable_injector
503