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