add decode_prte function to RADIX
[soc.git] / src / soc / decoder / isa / caller.py
1 # SPDX-License-Identifier: LGPLv3+
2 # Copyright (C) 2020, 2021 Luke Kenneth Casson Leighton <lkcl@lkcl.net>
3 # Copyright (C) 2020 Michael Nolan
4 # Funded by NLnet http://nlnet.nl
5 """core of the python-based POWER9 simulator
6
7 this is part of a cycle-accurate POWER9 simulator. its primary purpose is
8 not speed, it is for both learning and educational purposes, as well as
9 a method of verifying the HDL.
10
11 related bugs:
12
13 * https://bugs.libre-soc.org/show_bug.cgi?id=424
14 """
15
16 from nmigen.back.pysim import Settle
17 from functools import wraps
18 from copy import copy
19 from soc.decoder.orderedset import OrderedSet
20 from soc.decoder.selectable_int import (FieldSelectableInt, SelectableInt,
21 selectconcat)
22 from soc.decoder.power_enums import (spr_dict, spr_byname, XER_bits,
23 insns, MicrOp, In1Sel, In2Sel, In3Sel,
24 OutSel, CROutSel)
25 from soc.decoder.helpers import exts, gtu, ltu, undefined
26 from soc.consts import PIb, MSRb # big-endian (PowerISA versions)
27 from soc.decoder.power_svp64 import SVP64RM, decode_extra
28
29 from collections import namedtuple
30 import math
31 import sys
32
33 instruction_info = namedtuple('instruction_info',
34 'func read_regs uninit_regs write_regs ' +
35 'special_regs op_fields form asmregs')
36
37 special_sprs = {
38 'LR': 8,
39 'CTR': 9,
40 'TAR': 815,
41 'XER': 1,
42 'VRSAVE': 256}
43
44
45 def swap_order(x, nbytes):
46 x = x.to_bytes(nbytes, byteorder='little')
47 x = int.from_bytes(x, byteorder='big', signed=False)
48 return x
49
50
51 REG_SORT_ORDER = {
52 # TODO (lkcl): adjust other registers that should be in a particular order
53 # probably CA, CA32, and CR
54 "RT": 0,
55 "RA": 0,
56 "RB": 0,
57 "RS": 0,
58 "CR": 0,
59 "LR": 0,
60 "CTR": 0,
61 "TAR": 0,
62 "CA": 0,
63 "CA32": 0,
64 "MSR": 0,
65
66 "overflow": 1,
67 }
68
69
70 def create_args(reglist, extra=None):
71 retval = list(OrderedSet(reglist))
72 retval.sort(key=lambda reg: REG_SORT_ORDER[reg])
73 if extra is not None:
74 return [extra] + retval
75 return retval
76
77
78 """
79 Get Root Page
80
81 //Accessing 2nd double word of partition table (pate1)
82 //Ref: Power ISA Manual v3.0B, Book-III, section 5.7.6.1
83 // PTCR Layout
84 // ====================================================
85 // -----------------------------------------------
86 // | /// | PATB | /// | PATS |
87 // -----------------------------------------------
88 // 0 4 51 52 58 59 63
89 // PATB[4:51] holds the base address of the Partition Table,
90 // right shifted by 12 bits.
91 // This is because the address of the Partition base is
92 // 4k aligned. Hence, the lower 12bits, which are always
93 // 0 are ommitted from the PTCR.
94 //
95 // Thus, The Partition Table Base is obtained by (PATB << 12)
96 //
97 // PATS represents the partition table size right-shifted by 12 bits.
98 // The minimal size of the partition table is 4k.
99 // Thus partition table size = (1 << PATS + 12).
100 //
101 // Partition Table
102 // ====================================================
103 // 0 PATE0 63 PATE1 127
104 // |----------------------|----------------------|
105 // | | |
106 // |----------------------|----------------------|
107 // | | |
108 // |----------------------|----------------------|
109 // | | | <-- effLPID
110 // |----------------------|----------------------|
111 // .
112 // .
113 // .
114 // |----------------------|----------------------|
115 // | | |
116 // |----------------------|----------------------|
117 //
118 // The effective LPID forms the index into the Partition Table.
119 //
120 // Each entry in the partition table contains 2 double words, PATE0, PATE1,
121 // corresponding to that partition.
122 //
123 // In case of Radix, The structure of PATE0 and PATE1 is as follows.
124 //
125 // PATE0 Layout
126 // -----------------------------------------------
127 // |1|RTS1|/| RPDB | RTS2 | RPDS |
128 // -----------------------------------------------
129 // 0 1 2 3 4 55 56 58 59 63
130 //
131 // HR[0] : For Radix Page table, first bit should be 1.
132 // RTS1[1:2] : Gives one fragment of the Radix treesize
133 // RTS2[56:58] : Gives the second fragment of the Radix Tree size.
134 // RTS = (RTS1 << 3 + RTS2) + 31.
135 //
136 // RPDB[4:55] = Root Page Directory Base.
137 // RPDS = Logarithm of Root Page Directory Size right shifted by 3.
138 // Thus, Root page directory size = 1 << (RPDS + 3).
139 // Note: RPDS >= 5.
140 //
141 // PATE1 Layout
142 // -----------------------------------------------
143 // |///| PRTB | // | PRTS |
144 // -----------------------------------------------
145 // 0 3 4 51 52 58 59 63
146 //
147 // PRTB[4:51] = Process Table Base. This is aligned to size.
148 // PRTS[59: 63] = Process Table Size right shifted by 12.
149 // Minimal size of the process table is 4k.
150 // Process Table Size = (1 << PRTS + 12).
151 // Note: PRTS <= 24.
152 //
153 // Computing the size aligned Process Table Base:
154 // table_base = (PRTB & ~((1 << PRTS) - 1)) << 12
155 // Thus, the lower 12+PRTS bits of table_base will
156 // be zero.
157
158
159 //Ref: Power ISA Manual v3.0B, Book-III, section 5.7.6.2
160 //
161 // Process Table
162 // ==========================
163 // 0 PRTE0 63 PRTE1 127
164 // |----------------------|----------------------|
165 // | | |
166 // |----------------------|----------------------|
167 // | | |
168 // |----------------------|----------------------|
169 // | | | <-- effPID
170 // |----------------------|----------------------|
171 // .
172 // .
173 // .
174 // |----------------------|----------------------|
175 // | | |
176 // |----------------------|----------------------|
177 //
178 // The effective Process id (PID) forms the index into the Process Table.
179 //
180 // Each entry in the partition table contains 2 double words, PRTE0, PRTE1,
181 // corresponding to that process
182 //
183 // In case of Radix, The structure of PRTE0 and PRTE1 is as follows.
184 //
185 // PRTE0 Layout
186 // -----------------------------------------------
187 // |/|RTS1|/| RPDB | RTS2 | RPDS |
188 // -----------------------------------------------
189 // 0 1 2 3 4 55 56 58 59 63
190 //
191 // RTS1[1:2] : Gives one fragment of the Radix treesize
192 // RTS2[56:58] : Gives the second fragment of the Radix Tree size.
193 // RTS = (RTS1 << 3 + RTS2) << 31,
194 // since minimal Radix Tree size is 4G.
195 //
196 // RPDB = Root Page Directory Base.
197 // RPDS = Root Page Directory Size right shifted by 3.
198 // Thus, Root page directory size = RPDS << 3.
199 // Note: RPDS >= 5.
200 //
201 // PRTE1 Layout
202 // -----------------------------------------------
203 // | /// |
204 // -----------------------------------------------
205 // 0 63
206 // All bits are reserved.
207
208
209 """
210
211 # see qemu/target/ppc/mmu-radix64.c for reference
212 class RADIX:
213 def __init__(self, mem, caller):
214 self.mem = mem
215 self.caller = caller
216
217 # cached page table stuff
218 self.pgtbl0 = 0
219 self.pt0_valid = False
220 self.pgtbl3 = 0
221 self.pt3_valid = False
222
223 def ld(self, address, width=8, swap=True, check_in_mem=False):
224 print("RADIX: ld from addr 0x%x width %d" % (address, width))
225
226 pte = self._walk_tree()
227 # use pte to caclculate phys address
228 return self.mem.ld(address, width, swap, check_in_mem)
229
230 # TODO implement
231 def st(self, addr, v, width=8, swap=True):
232 print("RADIX: st to addr 0x%x width %d data %x" % (addr, width, v))
233 # use pte to caclculate phys address (addr)
234 return self.mem.st(addr, v, width, swap)
235
236 # def memassign(self, addr, sz, val):
237 def _next_level(self):
238 return True
239 ## DSISR_R_BADCONFIG
240 ## read_entry
241 ## DSISR_NOPTE
242 ## Prepare for next iteration
243
244 def _walk_tree(self):
245 """walk tree
246
247 // vaddr 64 Bit
248 // vaddr |-----------------------------------------------------|
249 // | Unused | Used |
250 // |-----------|-----------------------------------------|
251 // | 0000000 | usefulBits = X bits (typically 52) |
252 // |-----------|-----------------------------------------|
253 // | |<--Cursize---->| |
254 // | | Index | |
255 // | | into Page | |
256 // | | Directory | |
257 // |-----------------------------------------------------|
258 // | |
259 // V |
260 // PDE |---------------------------| |
261 // |V|L|//| NLB |///|NLS| |
262 // |---------------------------| |
263 // PDE = Page Directory Entry |
264 // [0] = V = Valid Bit |
265 // [1] = L = Leaf bit. If 0, then |
266 // [4:55] = NLB = Next Level Base |
267 // right shifted by 8 |
268 // [59:63] = NLS = Next Level Size |
269 // | NLS >= 5 |
270 // | V
271 // | |--------------------------|
272 // | | usfulBits = X-Cursize |
273 // | |--------------------------|
274 // |---------------------><--NLS-->| |
275 // | Index | |
276 // | into | |
277 // | PDE | |
278 // |--------------------------|
279 // |
280 // If the next PDE obtained by |
281 // (NLB << 8 + 8 * index) is a |
282 // nonleaf, then repeat the above. |
283 // |
284 // If the next PDE is a leaf, |
285 // then Leaf PDE structure is as |
286 // follows |
287 // |
288 // |
289 // Leaf PDE |
290 // |------------------------------| |----------------|
291 // |V|L|sw|//|RPN|sw|R|C|/|ATT|EAA| | usefulBits |
292 // |------------------------------| |----------------|
293 // [0] = V = Valid Bit |
294 // [1] = L = Leaf Bit = 1 if leaf |
295 // PDE |
296 // [2] = Sw = Sw bit 0. |
297 // [7:51] = RPN = Real Page Number, V
298 // real_page = RPN << 12 -------------> Logical OR
299 // [52:54] = Sw Bits 1:3 |
300 // [55] = R = Reference |
301 // [56] = C = Change V
302 // [58:59] = Att = Physical Address
303 // 0b00 = Normal Memory
304 // 0b01 = SAO
305 // 0b10 = Non Idenmpotent
306 // 0b11 = Tolerant I/O
307 // [60:63] = Encoded Access
308 // Authority
309 //
310 """
311 # walk tree starts on prtbl
312 while True:
313 ret = self._next_level()
314 if ret: return ret
315
316 def _decode_prte(self, data):
317 """PRTE0 Layout
318 -----------------------------------------------
319 |/|RTS1|/| RPDB | RTS2 | RPDS |
320 -----------------------------------------------
321 0 1 2 3 4 55 56 58 59 63
322 """
323 zero = SelectableInt(0, 1)
324 rts = selectconcat(data[5:8], # [56-58] - RTS2
325 data[61:63], # [1-2] - RTS1
326 zero)
327 masksize = data[0:5] # [59-63] - RPDS
328 mbits = selectconcat(masksize, zero)
329 pgbase = selectconcat(SelectableInt(0, 16),
330 data[8:56]) # [8-55] - part of RPDB
331 return (rts, mbits, pgbase)
332
333 def _segment_check(self):
334 """checks segment valid
335 mbits := '0' & r.mask_size;
336 v.shift := r.shift + (31 - 12) - mbits;
337 nonzero := or(r.addr(61 downto 31) and not finalmask(30 downto 0));
338 if r.addr(63) /= r.addr(62) or nonzero = '1' then
339 v.state := RADIX_FINISH;
340 v.segerror := '1';
341 elsif mbits < 5 or mbits > 16 or mbits > (r.shift + (31 - 12)) then
342 v.state := RADIX_FINISH;
343 v.badtree := '1';
344 else
345 v.state := RADIX_LOOKUP;
346 """
347
348 def _check_perms(self):
349 """check page permissions
350 -- test leaf bit
351 if data(62) = '1' then
352 -- check permissions and RC bits
353 perm_ok := '0';
354 if r.priv = '1' or data(3) = '0' then
355 if r.iside = '0' then
356 perm_ok := data(1) or (data(2) and not r.store);
357 else
358 -- no IAMR, so no KUEP support for now
359 -- deny execute permission if cache inhibited
360 perm_ok := data(0) and not data(5);
361 end if;
362 end if;
363 rc_ok := data(8) and (data(7) or not r.store);
364 if perm_ok = '1' and rc_ok = '1' then
365 v.state := RADIX_LOAD_TLB;
366 else
367 v.state := RADIX_FINISH;
368 v.perm_err := not perm_ok;
369 -- permission error takes precedence over RC error
370 v.rc_error := perm_ok;
371 end if;
372 """
373
374
375 class Mem:
376
377 def __init__(self, row_bytes=8, initial_mem=None):
378 self.mem = {}
379 self.bytes_per_word = row_bytes
380 self.word_log2 = math.ceil(math.log2(row_bytes))
381 print("Sim-Mem", initial_mem, self.bytes_per_word, self.word_log2)
382 if not initial_mem:
383 return
384
385 # different types of memory data structures recognised (for convenience)
386 if isinstance(initial_mem, list):
387 initial_mem = (0, initial_mem)
388 if isinstance(initial_mem, tuple):
389 startaddr, mem = initial_mem
390 initial_mem = {}
391 for i, val in enumerate(mem):
392 initial_mem[startaddr + row_bytes*i] = (val, row_bytes)
393
394 for addr, (val, width) in initial_mem.items():
395 #val = swap_order(val, width)
396 self.st(addr, val, width, swap=False)
397
398 def _get_shifter_mask(self, wid, remainder):
399 shifter = ((self.bytes_per_word - wid) - remainder) * \
400 8 # bits per byte
401 # XXX https://bugs.libre-soc.org/show_bug.cgi?id=377
402 # BE/LE mode?
403 shifter = remainder * 8
404 mask = (1 << (wid * 8)) - 1
405 print("width,rem,shift,mask", wid, remainder, hex(shifter), hex(mask))
406 return shifter, mask
407
408 # TODO: Implement ld/st of lesser width
409 def ld(self, address, width=8, swap=True, check_in_mem=False):
410 print("ld from addr 0x{:x} width {:d}".format(address, width))
411 remainder = address & (self.bytes_per_word - 1)
412 address = address >> self.word_log2
413 assert remainder & (width - 1) == 0, "Unaligned access unsupported!"
414 if address in self.mem:
415 val = self.mem[address]
416 elif check_in_mem:
417 return None
418 else:
419 val = 0
420 print("mem @ 0x{:x} rem {:d} : 0x{:x}".format(address, remainder, val))
421
422 if width != self.bytes_per_word:
423 shifter, mask = self._get_shifter_mask(width, remainder)
424 print("masking", hex(val), hex(mask << shifter), shifter)
425 val = val & (mask << shifter)
426 val >>= shifter
427 if swap:
428 val = swap_order(val, width)
429 print("Read 0x{:x} from addr 0x{:x}".format(val, address))
430 return val
431
432 def st(self, addr, v, width=8, swap=True):
433 staddr = addr
434 remainder = addr & (self.bytes_per_word - 1)
435 addr = addr >> self.word_log2
436 print("Writing 0x{:x} to ST 0x{:x} "
437 "memaddr 0x{:x}/{:x}".format(v, staddr, addr, remainder, swap))
438 assert remainder & (width - 1) == 0, "Unaligned access unsupported!"
439 if swap:
440 v = swap_order(v, width)
441 if width != self.bytes_per_word:
442 if addr in self.mem:
443 val = self.mem[addr]
444 else:
445 val = 0
446 shifter, mask = self._get_shifter_mask(width, remainder)
447 val &= ~(mask << shifter)
448 val |= v << shifter
449 self.mem[addr] = val
450 else:
451 self.mem[addr] = v
452 print("mem @ 0x{:x}: 0x{:x}".format(addr, self.mem[addr]))
453
454 def __call__(self, addr, sz):
455 val = self.ld(addr.value, sz, swap=False)
456 print("memread", addr, sz, val)
457 return SelectableInt(val, sz*8)
458
459 def memassign(self, addr, sz, val):
460 print("memassign", addr, sz, val)
461 self.st(addr.value, val.value, sz, swap=False)
462
463
464 class GPR(dict):
465 def __init__(self, decoder, isacaller, svstate, regfile):
466 dict.__init__(self)
467 self.sd = decoder
468 self.isacaller = isacaller
469 self.svstate = svstate
470 for i in range(32):
471 self[i] = SelectableInt(regfile[i], 64)
472
473 def __call__(self, ridx):
474 return self[ridx]
475
476 def set_form(self, form):
477 self.form = form
478
479 def getz(self, rnum):
480 # rnum = rnum.value # only SelectableInt allowed
481 print("GPR getzero", rnum)
482 if rnum == 0:
483 return SelectableInt(0, 64)
484 return self[rnum]
485
486 def _get_regnum(self, attr):
487 getform = self.sd.sigforms[self.form]
488 rnum = getattr(getform, attr)
489 return rnum
490
491 def ___getitem__(self, attr):
492 """ XXX currently not used
493 """
494 rnum = self._get_regnum(attr)
495 offs = self.svstate.srcstep
496 print("GPR getitem", attr, rnum, "srcoffs", offs)
497 return self.regfile[rnum]
498
499 def dump(self):
500 for i in range(0, len(self), 8):
501 s = []
502 for j in range(8):
503 s.append("%08x" % self[i+j].value)
504 s = ' '.join(s)
505 print("reg", "%2d" % i, s)
506
507
508 class PC:
509 def __init__(self, pc_init=0):
510 self.CIA = SelectableInt(pc_init, 64)
511 self.NIA = self.CIA + SelectableInt(4, 64) # only true for v3.0B!
512
513 def update_nia(self, is_svp64):
514 increment = 8 if is_svp64 else 4
515 self.NIA = self.CIA + SelectableInt(increment, 64)
516
517 def update(self, namespace, is_svp64):
518 """updates the program counter (PC) by 4 if v3.0B mode or 8 if SVP64
519 """
520 self.CIA = namespace['NIA'].narrow(64)
521 self.update_nia(is_svp64)
522 namespace['CIA'] = self.CIA
523 namespace['NIA'] = self.NIA
524
525
526 # Simple-V: see https://libre-soc.org/openpower/sv
527 class SVP64State:
528 def __init__(self, init=0):
529 self.spr = SelectableInt(init, 32)
530 # fields of SVSTATE, see https://libre-soc.org/openpower/sv/sprs/
531 self.maxvl = FieldSelectableInt(self.spr, tuple(range(0,7)))
532 self.vl = FieldSelectableInt(self.spr, tuple(range(7,14)))
533 self.srcstep = FieldSelectableInt(self.spr, tuple(range(14,21)))
534 self.dststep = FieldSelectableInt(self.spr, tuple(range(21,28)))
535 self.subvl = FieldSelectableInt(self.spr, tuple(range(28,30)))
536 self.svstep = FieldSelectableInt(self.spr, tuple(range(30,32)))
537
538
539 # SVP64 ReMap field
540 class SVP64RMFields:
541 def __init__(self, init=0):
542 self.spr = SelectableInt(init, 24)
543 # SVP64 RM fields: see https://libre-soc.org/openpower/sv/svp64/
544 self.mmode = FieldSelectableInt(self.spr, [0])
545 self.mask = FieldSelectableInt(self.spr, tuple(range(1,4)))
546 self.elwidth = FieldSelectableInt(self.spr, tuple(range(4,6)))
547 self.ewsrc = FieldSelectableInt(self.spr, tuple(range(6,8)))
548 self.subvl = FieldSelectableInt(self.spr, tuple(range(8,10)))
549 self.extra = FieldSelectableInt(self.spr, tuple(range(10,19)))
550 self.mode = FieldSelectableInt(self.spr, tuple(range(19,24)))
551 # these cover the same extra field, split into parts as EXTRA2
552 self.extra2 = list(range(4))
553 self.extra2[0] = FieldSelectableInt(self.spr, tuple(range(10,12)))
554 self.extra2[1] = FieldSelectableInt(self.spr, tuple(range(12,14)))
555 self.extra2[2] = FieldSelectableInt(self.spr, tuple(range(14,16)))
556 self.extra2[3] = FieldSelectableInt(self.spr, tuple(range(16,18)))
557 self.smask = FieldSelectableInt(self.spr, tuple(range(16,19)))
558 # and here as well, but EXTRA3
559 self.extra3 = list(range(3))
560 self.extra3[0] = FieldSelectableInt(self.spr, tuple(range(10,13)))
561 self.extra3[1] = FieldSelectableInt(self.spr, tuple(range(13,16)))
562 self.extra3[2] = FieldSelectableInt(self.spr, tuple(range(16,19)))
563
564
565 SVP64RM_MMODE_SIZE = len(SVP64RMFields().mmode.br)
566 SVP64RM_MASK_SIZE = len(SVP64RMFields().mask.br)
567 SVP64RM_ELWIDTH_SIZE = len(SVP64RMFields().elwidth.br)
568 SVP64RM_EWSRC_SIZE = len(SVP64RMFields().ewsrc.br)
569 SVP64RM_SUBVL_SIZE = len(SVP64RMFields().subvl.br)
570 SVP64RM_EXTRA2_SPEC_SIZE = len(SVP64RMFields().extra2[0].br)
571 SVP64RM_EXTRA3_SPEC_SIZE = len(SVP64RMFields().extra3[0].br)
572 SVP64RM_SMASK_SIZE = len(SVP64RMFields().smask.br)
573 SVP64RM_MODE_SIZE = len(SVP64RMFields().mode.br)
574
575
576 # SVP64 Prefix fields: see https://libre-soc.org/openpower/sv/svp64/
577 class SVP64PrefixFields:
578 def __init__(self):
579 self.insn = SelectableInt(0, 32)
580 # 6 bit major opcode EXT001, 2 bits "identifying" (7, 9), 24 SV ReMap
581 self.major = FieldSelectableInt(self.insn, tuple(range(0,6)))
582 self.pid = FieldSelectableInt(self.insn, (7, 9)) # must be 0b11
583 rmfields = [6, 8] + list(range(10,32)) # SVP64 24-bit RM (ReMap)
584 self.rm = FieldSelectableInt(self.insn, rmfields)
585
586
587 SV64P_MAJOR_SIZE = len(SVP64PrefixFields().major.br)
588 SV64P_PID_SIZE = len(SVP64PrefixFields().pid.br)
589 SV64P_RM_SIZE = len(SVP64PrefixFields().rm.br)
590
591
592 class SPR(dict):
593 def __init__(self, dec2, initial_sprs={}):
594 self.sd = dec2
595 dict.__init__(self)
596 for key, v in initial_sprs.items():
597 if isinstance(key, SelectableInt):
598 key = key.value
599 key = special_sprs.get(key, key)
600 if isinstance(key, int):
601 info = spr_dict[key]
602 else:
603 info = spr_byname[key]
604 if not isinstance(v, SelectableInt):
605 v = SelectableInt(v, info.length)
606 self[key] = v
607
608 def __getitem__(self, key):
609 print("get spr", key)
610 print("dict", self.items())
611 # if key in special_sprs get the special spr, otherwise return key
612 if isinstance(key, SelectableInt):
613 key = key.value
614 if isinstance(key, int):
615 key = spr_dict[key].SPR
616 key = special_sprs.get(key, key)
617 if key == 'HSRR0': # HACK!
618 key = 'SRR0'
619 if key == 'HSRR1': # HACK!
620 key = 'SRR1'
621 if key in self:
622 res = dict.__getitem__(self, key)
623 else:
624 if isinstance(key, int):
625 info = spr_dict[key]
626 else:
627 info = spr_byname[key]
628 dict.__setitem__(self, key, SelectableInt(0, info.length))
629 res = dict.__getitem__(self, key)
630 print("spr returning", key, res)
631 return res
632
633 def __setitem__(self, key, value):
634 if isinstance(key, SelectableInt):
635 key = key.value
636 if isinstance(key, int):
637 key = spr_dict[key].SPR
638 print("spr key", key)
639 key = special_sprs.get(key, key)
640 if key == 'HSRR0': # HACK!
641 self.__setitem__('SRR0', value)
642 if key == 'HSRR1': # HACK!
643 self.__setitem__('SRR1', value)
644 print("setting spr", key, value)
645 dict.__setitem__(self, key, value)
646
647 def __call__(self, ridx):
648 return self[ridx]
649
650 def get_pdecode_idx_in(dec2, name):
651 op = dec2.dec.op
652 in1_sel = yield op.in1_sel
653 in2_sel = yield op.in2_sel
654 in3_sel = yield op.in3_sel
655 # get the IN1/2/3 from the decoder (includes SVP64 remap and isvec)
656 in1 = yield dec2.e.read_reg1.data
657 in2 = yield dec2.e.read_reg2.data
658 in3 = yield dec2.e.read_reg3.data
659 in1_isvec = yield dec2.in1_isvec
660 in2_isvec = yield dec2.in2_isvec
661 in3_isvec = yield dec2.in3_isvec
662 print ("get_pdecode_idx", in1_sel, In1Sel.RA.value, in1, in1_isvec)
663 # identify which regnames map to in1/2/3
664 if name == 'RA':
665 if (in1_sel == In1Sel.RA.value or
666 (in1_sel == In1Sel.RA_OR_ZERO.value and in1 != 0)):
667 return in1, in1_isvec
668 if in1_sel == In1Sel.RA_OR_ZERO.value:
669 return in1, in1_isvec
670 elif name == 'RB':
671 if in2_sel == In2Sel.RB.value:
672 return in2, in2_isvec
673 if in3_sel == In3Sel.RB.value:
674 return in3, in3_isvec
675 # XXX TODO, RC doesn't exist yet!
676 elif name == 'RC':
677 assert False, "RC does not exist yet"
678 elif name == 'RS':
679 if in1_sel == In1Sel.RS.value:
680 return in1, in1_isvec
681 if in2_sel == In2Sel.RS.value:
682 return in2, in2_isvec
683 if in3_sel == In3Sel.RS.value:
684 return in3, in3_isvec
685 return None, False
686
687
688 def get_pdecode_cr_out(dec2, name):
689 op = dec2.dec.op
690 out_sel = yield op.cr_out
691 out_bitfield = yield dec2.dec_cr_out.cr_bitfield.data
692 sv_cr_out = yield op.sv_cr_out
693 spec = yield dec2.crout_svdec.spec
694 sv_override = yield dec2.dec_cr_out.sv_override
695 # get the IN1/2/3 from the decoder (includes SVP64 remap and isvec)
696 out = yield dec2.e.write_cr.data
697 o_isvec = yield dec2.o_isvec
698 print ("get_pdecode_cr_out", out_sel, CROutSel.CR0.value, out, o_isvec)
699 print (" sv_cr_out", sv_cr_out)
700 print (" cr_bf", out_bitfield)
701 print (" spec", spec)
702 print (" override", sv_override)
703 # identify which regnames map to out / o2
704 if name == 'CR0':
705 if out_sel == CROutSel.CR0.value:
706 return out, o_isvec
707 print ("get_pdecode_idx_out not found", name)
708 return None, False
709
710
711 def get_pdecode_idx_out(dec2, name):
712 op = dec2.dec.op
713 out_sel = yield op.out_sel
714 # get the IN1/2/3 from the decoder (includes SVP64 remap and isvec)
715 out = yield dec2.e.write_reg.data
716 o_isvec = yield dec2.o_isvec
717 print ("get_pdecode_idx_out", out_sel, OutSel.RA.value, out, o_isvec)
718 # identify which regnames map to out / o2
719 if name == 'RA':
720 if out_sel == OutSel.RA.value:
721 return out, o_isvec
722 elif name == 'RT':
723 if out_sel == OutSel.RT.value:
724 return out, o_isvec
725 print ("get_pdecode_idx_out not found", name)
726 return None, False
727
728
729 # XXX TODO
730 def get_pdecode_idx_out2(dec2, name):
731 op = dec2.dec.op
732 print ("TODO: get_pdecode_idx_out2", name)
733 return None, False
734
735
736 class ISACaller:
737 # decoder2 - an instance of power_decoder2
738 # regfile - a list of initial values for the registers
739 # initial_{etc} - initial values for SPRs, Condition Register, Mem, MSR
740 # respect_pc - tracks the program counter. requires initial_insns
741 def __init__(self, decoder2, regfile, initial_sprs=None, initial_cr=0,
742 initial_mem=None, initial_msr=0,
743 initial_svstate=0,
744 initial_insns=None, respect_pc=False,
745 disassembly=None,
746 initial_pc=0,
747 bigendian=False,
748 mmu=False):
749
750 self.bigendian = bigendian
751 self.halted = False
752 self.is_svp64_mode = False
753 self.respect_pc = respect_pc
754 if initial_sprs is None:
755 initial_sprs = {}
756 if initial_mem is None:
757 initial_mem = {}
758 if initial_insns is None:
759 initial_insns = {}
760 assert self.respect_pc == False, "instructions required to honor pc"
761
762 print("ISACaller insns", respect_pc, initial_insns, disassembly)
763 print("ISACaller initial_msr", initial_msr)
764
765 # "fake program counter" mode (for unit testing)
766 self.fake_pc = 0
767 disasm_start = 0
768 if not respect_pc:
769 if isinstance(initial_mem, tuple):
770 self.fake_pc = initial_mem[0]
771 disasm_start = self.fake_pc
772 else:
773 disasm_start = initial_pc
774
775 # disassembly: we need this for now (not given from the decoder)
776 self.disassembly = {}
777 if disassembly:
778 for i, code in enumerate(disassembly):
779 self.disassembly[i*4 + disasm_start] = code
780
781 # set up registers, instruction memory, data memory, PC, SPRs, MSR
782 self.svp64rm = SVP64RM()
783 if isinstance(initial_svstate, int):
784 initial_svstate = SVP64State(initial_svstate)
785 self.svstate = initial_svstate
786 self.gpr = GPR(decoder2, self, self.svstate, regfile)
787 self.mem = Mem(row_bytes=8, initial_mem=initial_mem)
788 if mmu:
789 self.mem = RADIX(self.mem, self)
790 self.imem = Mem(row_bytes=4, initial_mem=initial_insns)
791 self.pc = PC()
792 self.spr = SPR(decoder2, initial_sprs)
793 self.msr = SelectableInt(initial_msr, 64) # underlying reg
794
795 # TODO, needed here:
796 # FPR (same as GPR except for FP nums)
797 # 4.2.2 p124 FPSCR (definitely "separate" - not in SPR)
798 # note that mffs, mcrfs, mtfsf "manage" this FPSCR
799 # 2.3.1 CR (and sub-fields CR0..CR6 - CR0 SO comes from XER.SO)
800 # note that mfocrf, mfcr, mtcr, mtocrf, mcrxrx "manage" CRs
801 # -- Done
802 # 2.3.2 LR (actually SPR #8) -- Done
803 # 2.3.3 CTR (actually SPR #9) -- Done
804 # 2.3.4 TAR (actually SPR #815)
805 # 3.2.2 p45 XER (actually SPR #1) -- Done
806 # 3.2.3 p46 p232 VRSAVE (actually SPR #256)
807
808 # create CR then allow portions of it to be "selectable" (below)
809 #rev_cr = int('{:016b}'.format(initial_cr)[::-1], 2)
810 self.cr = SelectableInt(initial_cr, 64) # underlying reg
811 #self.cr = FieldSelectableInt(self._cr, list(range(32, 64)))
812
813 # "undefined", just set to variable-bit-width int (use exts "max")
814 #self.undefined = SelectableInt(0, 256) # TODO, not hard-code 256!
815
816 self.namespace = {}
817 self.namespace.update(self.spr)
818 self.namespace.update({'GPR': self.gpr,
819 'MEM': self.mem,
820 'SPR': self.spr,
821 'memassign': self.memassign,
822 'NIA': self.pc.NIA,
823 'CIA': self.pc.CIA,
824 'CR': self.cr,
825 'MSR': self.msr,
826 'undefined': undefined,
827 'mode_is_64bit': True,
828 'SO': XER_bits['SO']
829 })
830
831 # update pc to requested start point
832 self.set_pc(initial_pc)
833
834 # field-selectable versions of Condition Register TODO check bitranges?
835 self.crl = []
836 for i in range(8):
837 bits = tuple(range(i*4+32, (i+1)*4+32)) # errr... maybe?
838 _cr = FieldSelectableInt(self.cr, bits)
839 self.crl.append(_cr)
840 self.namespace["CR%d" % i] = _cr
841
842 self.decoder = decoder2.dec
843 self.dec2 = decoder2
844
845 def TRAP(self, trap_addr=0x700, trap_bit=PIb.TRAP):
846 print("TRAP:", hex(trap_addr), hex(self.namespace['MSR'].value))
847 # store CIA(+4?) in SRR0, set NIA to 0x700
848 # store MSR in SRR1, set MSR to um errr something, have to check spec
849 self.spr['SRR0'].value = self.pc.CIA.value
850 self.spr['SRR1'].value = self.namespace['MSR'].value
851 self.trap_nia = SelectableInt(trap_addr, 64)
852 self.spr['SRR1'][trap_bit] = 1 # change *copy* of MSR in SRR1
853
854 # set exception bits. TODO: this should, based on the address
855 # in figure 66 p1065 V3.0B and the table figure 65 p1063 set these
856 # bits appropriately. however it turns out that *for now* in all
857 # cases (all trap_addrs) the exact same thing is needed.
858 self.msr[MSRb.IR] = 0
859 self.msr[MSRb.DR] = 0
860 self.msr[MSRb.FE0] = 0
861 self.msr[MSRb.FE1] = 0
862 self.msr[MSRb.EE] = 0
863 self.msr[MSRb.RI] = 0
864 self.msr[MSRb.SF] = 1
865 self.msr[MSRb.TM] = 0
866 self.msr[MSRb.VEC] = 0
867 self.msr[MSRb.VSX] = 0
868 self.msr[MSRb.PR] = 0
869 self.msr[MSRb.FP] = 0
870 self.msr[MSRb.PMM] = 0
871 self.msr[MSRb.TEs] = 0
872 self.msr[MSRb.TEe] = 0
873 self.msr[MSRb.UND] = 0
874 self.msr[MSRb.LE] = 1
875
876 def memassign(self, ea, sz, val):
877 self.mem.memassign(ea, sz, val)
878
879 def prep_namespace(self, formname, op_fields):
880 # TODO: get field names from form in decoder*1* (not decoder2)
881 # decoder2 is hand-created, and decoder1.sigform is auto-generated
882 # from spec
883 # then "yield" fields only from op_fields rather than hard-coded
884 # list, here.
885 fields = self.decoder.sigforms[formname]
886 for name in op_fields:
887 if name == 'spr':
888 sig = getattr(fields, name.upper())
889 else:
890 sig = getattr(fields, name)
891 val = yield sig
892 # these are all opcode fields involved in index-selection of CR,
893 # and need to do "standard" arithmetic. CR[BA+32] for example
894 # would, if using SelectableInt, only be 5-bit.
895 if name in ['BF', 'BFA', 'BC', 'BA', 'BB', 'BT', 'BI']:
896 self.namespace[name] = val
897 else:
898 self.namespace[name] = SelectableInt(val, sig.width)
899
900 self.namespace['XER'] = self.spr['XER']
901 self.namespace['CA'] = self.spr['XER'][XER_bits['CA']].value
902 self.namespace['CA32'] = self.spr['XER'][XER_bits['CA32']].value
903
904 def handle_carry_(self, inputs, outputs, already_done):
905 inv_a = yield self.dec2.e.do.invert_in
906 if inv_a:
907 inputs[0] = ~inputs[0]
908
909 imm_ok = yield self.dec2.e.do.imm_data.ok
910 if imm_ok:
911 imm = yield self.dec2.e.do.imm_data.data
912 inputs.append(SelectableInt(imm, 64))
913 assert len(outputs) >= 1
914 print("outputs", repr(outputs))
915 if isinstance(outputs, list) or isinstance(outputs, tuple):
916 output = outputs[0]
917 else:
918 output = outputs
919 gts = []
920 for x in inputs:
921 print("gt input", x, output)
922 gt = (gtu(x, output))
923 gts.append(gt)
924 print(gts)
925 cy = 1 if any(gts) else 0
926 print("CA", cy, gts)
927 if not (1 & already_done):
928 self.spr['XER'][XER_bits['CA']] = cy
929
930 print("inputs", already_done, inputs)
931 # 32 bit carry
932 # ARGH... different for OP_ADD... *sigh*...
933 op = yield self.dec2.e.do.insn_type
934 if op == MicrOp.OP_ADD.value:
935 res32 = (output.value & (1 << 32)) != 0
936 a32 = (inputs[0].value & (1 << 32)) != 0
937 if len(inputs) >= 2:
938 b32 = (inputs[1].value & (1 << 32)) != 0
939 else:
940 b32 = False
941 cy32 = res32 ^ a32 ^ b32
942 print("CA32 ADD", cy32)
943 else:
944 gts = []
945 for x in inputs:
946 print("input", x, output)
947 print(" x[32:64]", x, x[32:64])
948 print(" o[32:64]", output, output[32:64])
949 gt = (gtu(x[32:64], output[32:64])) == SelectableInt(1, 1)
950 gts.append(gt)
951 cy32 = 1 if any(gts) else 0
952 print("CA32", cy32, gts)
953 if not (2 & already_done):
954 self.spr['XER'][XER_bits['CA32']] = cy32
955
956 def handle_overflow(self, inputs, outputs, div_overflow):
957 if hasattr(self.dec2.e.do, "invert_in"):
958 inv_a = yield self.dec2.e.do.invert_in
959 if inv_a:
960 inputs[0] = ~inputs[0]
961
962 imm_ok = yield self.dec2.e.do.imm_data.ok
963 if imm_ok:
964 imm = yield self.dec2.e.do.imm_data.data
965 inputs.append(SelectableInt(imm, 64))
966 assert len(outputs) >= 1
967 print("handle_overflow", inputs, outputs, div_overflow)
968 if len(inputs) < 2 and div_overflow is None:
969 return
970
971 # div overflow is different: it's returned by the pseudo-code
972 # because it's more complex than can be done by analysing the output
973 if div_overflow is not None:
974 ov, ov32 = div_overflow, div_overflow
975 # arithmetic overflow can be done by analysing the input and output
976 elif len(inputs) >= 2:
977 output = outputs[0]
978
979 # OV (64-bit)
980 input_sgn = [exts(x.value, x.bits) < 0 for x in inputs]
981 output_sgn = exts(output.value, output.bits) < 0
982 ov = 1 if input_sgn[0] == input_sgn[1] and \
983 output_sgn != input_sgn[0] else 0
984
985 # OV (32-bit)
986 input32_sgn = [exts(x.value, 32) < 0 for x in inputs]
987 output32_sgn = exts(output.value, 32) < 0
988 ov32 = 1 if input32_sgn[0] == input32_sgn[1] and \
989 output32_sgn != input32_sgn[0] else 0
990
991 self.spr['XER'][XER_bits['OV']] = ov
992 self.spr['XER'][XER_bits['OV32']] = ov32
993 so = self.spr['XER'][XER_bits['SO']]
994 so = so | ov
995 self.spr['XER'][XER_bits['SO']] = so
996
997 def handle_comparison(self, outputs, cr_idx=0):
998 out = outputs[0]
999 assert isinstance(out, SelectableInt), \
1000 "out zero not a SelectableInt %s" % repr(outputs)
1001 print("handle_comparison", out.bits, hex(out.value))
1002 # TODO - XXX *processor* in 32-bit mode
1003 # https://bugs.libre-soc.org/show_bug.cgi?id=424
1004 # if is_32bit:
1005 # o32 = exts(out.value, 32)
1006 # print ("handle_comparison exts 32 bit", hex(o32))
1007 out = exts(out.value, out.bits)
1008 print("handle_comparison exts", hex(out))
1009 zero = SelectableInt(out == 0, 1)
1010 positive = SelectableInt(out > 0, 1)
1011 negative = SelectableInt(out < 0, 1)
1012 SO = self.spr['XER'][XER_bits['SO']]
1013 print("handle_comparison SO", SO)
1014 cr_field = selectconcat(negative, positive, zero, SO)
1015 self.crl[cr_idx].eq(cr_field)
1016
1017 def set_pc(self, pc_val):
1018 self.namespace['NIA'] = SelectableInt(pc_val, 64)
1019 self.pc.update(self.namespace, self.is_svp64_mode)
1020
1021 def setup_one(self):
1022 """set up one instruction
1023 """
1024 if self.respect_pc:
1025 pc = self.pc.CIA.value
1026 else:
1027 pc = self.fake_pc
1028 self._pc = pc
1029 ins = self.imem.ld(pc, 4, False, True)
1030 if ins is None:
1031 raise KeyError("no instruction at 0x%x" % pc)
1032 print("setup: 0x%x 0x%x %s" % (pc, ins & 0xffffffff, bin(ins)))
1033 print("CIA NIA", self.respect_pc, self.pc.CIA.value, self.pc.NIA.value)
1034
1035 yield self.dec2.sv_rm.eq(0)
1036 yield self.dec2.dec.raw_opcode_in.eq(ins & 0xffffffff)
1037 yield self.dec2.dec.bigendian.eq(self.bigendian)
1038 yield self.dec2.state.msr.eq(self.msr.value)
1039 yield self.dec2.state.pc.eq(pc)
1040 yield self.dec2.state.svstate.eq(self.svstate.spr.value)
1041
1042 # SVP64. first, check if the opcode is EXT001, and SVP64 id bits set
1043 yield Settle()
1044 opcode = yield self.dec2.dec.opcode_in
1045 pfx = SVP64PrefixFields() # TODO should probably use SVP64PrefixDecoder
1046 pfx.insn.value = opcode
1047 major = pfx.major.asint(msb0=True) # MSB0 inversion
1048 print ("prefix test: opcode:", major, bin(major),
1049 pfx.insn[7] == 0b1, pfx.insn[9] == 0b1)
1050 self.is_svp64_mode = ((major == 0b000001) and
1051 pfx.insn[7].value == 0b1 and
1052 pfx.insn[9].value == 0b1)
1053 self.pc.update_nia(self.is_svp64_mode)
1054 if not self.is_svp64_mode:
1055 return
1056
1057 # in SVP64 mode. decode/print out svp64 prefix, get v3.0B instruction
1058 print ("svp64.rm", bin(pfx.rm.asint(msb0=True)))
1059 print (" svstate.vl", self.svstate.vl.asint(msb0=True))
1060 print (" svstate.mvl", self.svstate.maxvl.asint(msb0=True))
1061 sv_rm = pfx.rm.asint(msb0=True)
1062 ins = self.imem.ld(pc+4, 4, False, True)
1063 print(" svsetup: 0x%x 0x%x %s" % (pc+4, ins & 0xffffffff, bin(ins)))
1064 yield self.dec2.dec.raw_opcode_in.eq(ins & 0xffffffff) # v3.0B suffix
1065 yield self.dec2.sv_rm.eq(sv_rm) # svp64 prefix
1066 yield Settle()
1067
1068 def execute_one(self):
1069 """execute one instruction
1070 """
1071 # get the disassembly code for this instruction
1072 if self.is_svp64_mode:
1073 code = self.disassembly[self._pc+4]
1074 print(" svp64 sim-execute", hex(self._pc), code)
1075 else:
1076 code = self.disassembly[self._pc]
1077 print("sim-execute", hex(self._pc), code)
1078 opname = code.split(' ')[0]
1079 yield from self.call(opname)
1080
1081 # don't use this except in special circumstances
1082 if not self.respect_pc:
1083 self.fake_pc += 4
1084
1085 print("execute one, CIA NIA", self.pc.CIA.value, self.pc.NIA.value)
1086
1087 def get_assembly_name(self):
1088 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
1089 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
1090 dec_insn = yield self.dec2.e.do.insn
1091 asmcode = yield self.dec2.dec.op.asmcode
1092 print("get assembly name asmcode", asmcode, hex(dec_insn))
1093 asmop = insns.get(asmcode, None)
1094 int_op = yield self.dec2.dec.op.internal_op
1095
1096 # sigh reconstruct the assembly instruction name
1097 if hasattr(self.dec2.e.do, "oe"):
1098 ov_en = yield self.dec2.e.do.oe.oe
1099 ov_ok = yield self.dec2.e.do.oe.ok
1100 else:
1101 ov_en = False
1102 ov_ok = False
1103 if hasattr(self.dec2.e.do, "rc"):
1104 rc_en = yield self.dec2.e.do.rc.rc
1105 rc_ok = yield self.dec2.e.do.rc.ok
1106 else:
1107 rc_en = False
1108 rc_ok = False
1109 # grrrr have to special-case MUL op (see DecodeOE)
1110 print("ov %d en %d rc %d en %d op %d" %
1111 (ov_ok, ov_en, rc_ok, rc_en, int_op))
1112 if int_op in [MicrOp.OP_MUL_H64.value, MicrOp.OP_MUL_H32.value]:
1113 print("mul op")
1114 if rc_en & rc_ok:
1115 asmop += "."
1116 else:
1117 if not asmop.endswith("."): # don't add "." to "andis."
1118 if rc_en & rc_ok:
1119 asmop += "."
1120 if hasattr(self.dec2.e.do, "lk"):
1121 lk = yield self.dec2.e.do.lk
1122 if lk:
1123 asmop += "l"
1124 print("int_op", int_op)
1125 if int_op in [MicrOp.OP_B.value, MicrOp.OP_BC.value]:
1126 AA = yield self.dec2.dec.fields.FormI.AA[0:-1]
1127 print("AA", AA)
1128 if AA:
1129 asmop += "a"
1130 spr_msb = yield from self.get_spr_msb()
1131 if int_op == MicrOp.OP_MFCR.value:
1132 if spr_msb:
1133 asmop = 'mfocrf'
1134 else:
1135 asmop = 'mfcr'
1136 # XXX TODO: for whatever weird reason this doesn't work
1137 # https://bugs.libre-soc.org/show_bug.cgi?id=390
1138 if int_op == MicrOp.OP_MTCRF.value:
1139 if spr_msb:
1140 asmop = 'mtocrf'
1141 else:
1142 asmop = 'mtcrf'
1143 return asmop
1144
1145 def get_spr_msb(self):
1146 dec_insn = yield self.dec2.e.do.insn
1147 return dec_insn & (1 << 20) != 0 # sigh - XFF.spr[-1]?
1148
1149 def call(self, name):
1150 """call(opcode) - the primary execution point for instructions
1151 """
1152 name = name.strip() # remove spaces if not already done so
1153 if self.halted:
1154 print("halted - not executing", name)
1155 return
1156
1157 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
1158 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
1159 asmop = yield from self.get_assembly_name()
1160 print("call", name, asmop)
1161
1162 # check privileged
1163 int_op = yield self.dec2.dec.op.internal_op
1164 spr_msb = yield from self.get_spr_msb()
1165
1166 instr_is_privileged = False
1167 if int_op in [MicrOp.OP_ATTN.value,
1168 MicrOp.OP_MFMSR.value,
1169 MicrOp.OP_MTMSR.value,
1170 MicrOp.OP_MTMSRD.value,
1171 # TODO: OP_TLBIE
1172 MicrOp.OP_RFID.value]:
1173 instr_is_privileged = True
1174 if int_op in [MicrOp.OP_MFSPR.value,
1175 MicrOp.OP_MTSPR.value] and spr_msb:
1176 instr_is_privileged = True
1177
1178 print("is priv", instr_is_privileged, hex(self.msr.value),
1179 self.msr[MSRb.PR])
1180 # check MSR priv bit and whether op is privileged: if so, throw trap
1181 if instr_is_privileged and self.msr[MSRb.PR] == 1:
1182 self.TRAP(0x700, PIb.PRIV)
1183 self.namespace['NIA'] = self.trap_nia
1184 self.pc.update(self.namespace, self.is_svp64_mode)
1185 return
1186
1187 # check halted condition
1188 if name == 'attn':
1189 self.halted = True
1190 return
1191
1192 # check illegal instruction
1193 illegal = False
1194 if name not in ['mtcrf', 'mtocrf']:
1195 illegal = name != asmop
1196
1197 if illegal:
1198 print("illegal", name, asmop)
1199 self.TRAP(0x700, PIb.ILLEG)
1200 self.namespace['NIA'] = self.trap_nia
1201 self.pc.update(self.namespace, self.is_svp64_mode)
1202 print("name %s != %s - calling ILLEGAL trap, PC: %x" %
1203 (name, asmop, self.pc.CIA.value))
1204 return
1205
1206 info = self.instrs[name]
1207 yield from self.prep_namespace(info.form, info.op_fields)
1208
1209 # preserve order of register names
1210 input_names = create_args(list(info.read_regs) +
1211 list(info.uninit_regs))
1212 print(input_names)
1213
1214 # get SVP64 entry for the current instruction
1215 sv_rm = self.svp64rm.instrs.get(name)
1216 if sv_rm is not None:
1217 dest_cr, src_cr, src_byname, dest_byname = decode_extra(sv_rm)
1218 else:
1219 dest_cr, src_cr, src_byname, dest_byname = False, False, {}, {}
1220 print ("sv rm", sv_rm, dest_cr, src_cr, src_byname, dest_byname)
1221
1222 # get SVSTATE srcstep. TODO: dststep (twin predication)
1223 srcstep = self.svstate.srcstep.asint(msb0=True)
1224 vl = self.svstate.vl.asint(msb0=True)
1225 mvl = self.svstate.maxvl.asint(msb0=True)
1226
1227 # VL=0 in SVP64 mode means "do nothing: skip instruction"
1228 if self.is_svp64_mode and vl == 0:
1229 self.pc.update(self.namespace, self.is_svp64_mode)
1230 print("end of call", self.namespace['CIA'], self.namespace['NIA'])
1231 return
1232
1233 # main input registers (RT, RA ...)
1234 inputs = []
1235 for name in input_names:
1236 # using PowerDecoder2, first, find the decoder index.
1237 # (mapping name RA RB RC RS to in1, in2, in3)
1238 regnum, is_vec = yield from get_pdecode_idx_in(self.dec2, name)
1239 if regnum is None:
1240 # doing this is not part of svp64, it's because output
1241 # registers, to be modified, need to be in the namespace.
1242 regnum, is_vec = yield from get_pdecode_idx_out(self.dec2, name)
1243 # here's where we go "vector". TODO: zero-testing (RA_IS_ZERO)
1244 # XXX already done by PowerDecoder2, now
1245 #if is_vec:
1246 # regnum += srcstep # TODO, elwidth overrides
1247
1248 # in case getting the register number is needed, _RA, _RB
1249 regname = "_" + name
1250 self.namespace[regname] = regnum
1251 print('reading reg %s %d' % (name, regnum), is_vec)
1252 reg_val = self.gpr(regnum)
1253 inputs.append(reg_val)
1254
1255 # "special" registers
1256 for special in info.special_regs:
1257 if special in special_sprs:
1258 inputs.append(self.spr[special])
1259 else:
1260 inputs.append(self.namespace[special])
1261
1262 # clear trap (trap) NIA
1263 self.trap_nia = None
1264
1265 print("inputs", inputs)
1266 results = info.func(self, *inputs)
1267 print("results", results)
1268
1269 # "inject" decorator takes namespace from function locals: we need to
1270 # overwrite NIA being overwritten (sigh)
1271 if self.trap_nia is not None:
1272 self.namespace['NIA'] = self.trap_nia
1273
1274 print("after func", self.namespace['CIA'], self.namespace['NIA'])
1275
1276 # detect if CA/CA32 already in outputs (sra*, basically)
1277 already_done = 0
1278 if info.write_regs:
1279 output_names = create_args(info.write_regs)
1280 for name in output_names:
1281 if name == 'CA':
1282 already_done |= 1
1283 if name == 'CA32':
1284 already_done |= 2
1285
1286 print("carry already done?", bin(already_done))
1287 if hasattr(self.dec2.e.do, "output_carry"):
1288 carry_en = yield self.dec2.e.do.output_carry
1289 else:
1290 carry_en = False
1291 if carry_en:
1292 yield from self.handle_carry_(inputs, results, already_done)
1293
1294 # detect if overflow was in return result
1295 overflow = None
1296 if info.write_regs:
1297 for name, output in zip(output_names, results):
1298 if name == 'overflow':
1299 overflow = output
1300
1301 if hasattr(self.dec2.e.do, "oe"):
1302 ov_en = yield self.dec2.e.do.oe.oe
1303 ov_ok = yield self.dec2.e.do.oe.ok
1304 else:
1305 ov_en = False
1306 ov_ok = False
1307 print("internal overflow", overflow, ov_en, ov_ok)
1308 if ov_en & ov_ok:
1309 yield from self.handle_overflow(inputs, results, overflow)
1310
1311 if hasattr(self.dec2.e.do, "rc"):
1312 rc_en = yield self.dec2.e.do.rc.rc
1313 else:
1314 rc_en = False
1315 if rc_en:
1316 regnum, is_vec = yield from get_pdecode_cr_out(self.dec2, "CR0")
1317 self.handle_comparison(results, regnum)
1318
1319 # any modified return results?
1320 if info.write_regs:
1321 for name, output in zip(output_names, results):
1322 if name == 'overflow': # ignore, done already (above)
1323 continue
1324 if isinstance(output, int):
1325 output = SelectableInt(output, 256)
1326 if name in ['CA', 'CA32']:
1327 if carry_en:
1328 print("writing %s to XER" % name, output)
1329 self.spr['XER'][XER_bits[name]] = output.value
1330 else:
1331 print("NOT writing %s to XER" % name, output)
1332 elif name in info.special_regs:
1333 print('writing special %s' % name, output, special_sprs)
1334 if name in special_sprs:
1335 self.spr[name] = output
1336 else:
1337 self.namespace[name].eq(output)
1338 if name == 'MSR':
1339 print('msr written', hex(self.msr.value))
1340 else:
1341 regnum, is_vec = yield from get_pdecode_idx_out(self.dec2,
1342 name)
1343 if regnum is None:
1344 # temporary hack for not having 2nd output
1345 regnum = yield getattr(self.decoder, name)
1346 is_vec = False
1347 print('writing reg %d %s' % (regnum, str(output)), is_vec)
1348 if output.bits > 64:
1349 output = SelectableInt(output.value, 64)
1350 self.gpr[regnum] = output
1351
1352 # check if it is the SVSTATE.src/dest step that needs incrementing
1353 # this is our Sub-Program-Counter loop from 0 to VL-1
1354 if self.is_svp64_mode:
1355 # XXX twin predication TODO
1356 vl = self.svstate.vl.asint(msb0=True)
1357 mvl = self.svstate.maxvl.asint(msb0=True)
1358 srcstep = self.svstate.srcstep.asint(msb0=True)
1359 print (" svstate.vl", vl)
1360 print (" svstate.mvl", mvl)
1361 print (" svstate.srcstep", srcstep)
1362 # check if srcstep needs incrementing by one, stop PC advancing
1363 # svp64 loop can end early if the dest is scalar
1364 svp64_dest_vector = not (yield self.dec2.no_out_vec)
1365 if svp64_dest_vector and srcstep != vl-1:
1366 self.svstate.srcstep += SelectableInt(1, 7)
1367 self.pc.NIA.value = self.pc.CIA.value
1368 self.namespace['NIA'] = self.pc.NIA
1369 print("end of sub-pc call", self.namespace['CIA'],
1370 self.namespace['NIA'])
1371 return # DO NOT allow PC to update whilst Sub-PC loop running
1372 # reset to zero
1373 self.svstate.srcstep[0:7] = 0
1374 print (" svstate.srcstep loop end (PC to update)")
1375 self.pc.update_nia(self.is_svp64_mode)
1376 self.namespace['NIA'] = self.pc.NIA
1377
1378 # UPDATE program counter
1379 self.pc.update(self.namespace, self.is_svp64_mode)
1380 print("end of call", self.namespace['CIA'], self.namespace['NIA'])
1381
1382
1383 def inject():
1384 """Decorator factory.
1385
1386 this decorator will "inject" variables into the function's namespace,
1387 from the *dictionary* in self.namespace. it therefore becomes possible
1388 to make it look like a whole stack of variables which would otherwise
1389 need "self." inserted in front of them (*and* for those variables to be
1390 added to the instance) "appear" in the function.
1391
1392 "self.namespace['SI']" for example becomes accessible as just "SI" but
1393 *only* inside the function, when decorated.
1394 """
1395 def variable_injector(func):
1396 @wraps(func)
1397 def decorator(*args, **kwargs):
1398 try:
1399 func_globals = func.__globals__ # Python 2.6+
1400 except AttributeError:
1401 func_globals = func.func_globals # Earlier versions.
1402
1403 context = args[0].namespace # variables to be injected
1404 saved_values = func_globals.copy() # Shallow copy of dict.
1405 func_globals.update(context)
1406 result = func(*args, **kwargs)
1407 print("globals after", func_globals['CIA'], func_globals['NIA'])
1408 print("args[0]", args[0].namespace['CIA'],
1409 args[0].namespace['NIA'])
1410 args[0].namespace = func_globals
1411 #exec (func.__code__, func_globals)
1412
1413 # finally:
1414 # func_globals = saved_values # Undo changes.
1415
1416 return result
1417
1418 return decorator
1419
1420 return variable_injector