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
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.
13 * https://bugs.libre-soc.org/show_bug.cgi?id=424
16 from nmigen
.back
.pysim
import Settle
17 from functools
import wraps
19 from soc
.decoder
.orderedset
import OrderedSet
20 from soc
.decoder
.selectable_int
import (FieldSelectableInt
, SelectableInt
,
22 from soc
.decoder
.power_enums
import (spr_dict
, spr_byname
, XER_bits
,
23 insns
, MicrOp
, In1Sel
, In2Sel
, In3Sel
,
26 from soc
.decoder
.power_enums
import SPR
as DEC_SPR
28 from soc
.decoder
.helpers
import exts
, gtu
, ltu
, undefined
29 from soc
.consts
import PIb
, MSRb
# big-endian (PowerISA versions)
30 from soc
.decoder
.power_svp64
import SVP64RM
, decode_extra
32 from collections
import namedtuple
36 instruction_info
= namedtuple('instruction_info',
37 'func read_regs uninit_regs write_regs ' +
38 'special_regs op_fields form asmregs')
48 def swap_order(x
, nbytes
):
49 x
= x
.to_bytes(nbytes
, byteorder
='little')
50 x
= int.from_bytes(x
, byteorder
='big', signed
=False)
55 # TODO (lkcl): adjust other registers that should be in a particular order
56 # probably CA, CA32, and CR
73 def create_args(reglist
, extra
=None):
74 retval
= list(OrderedSet(reglist
))
75 retval
.sort(key
=lambda reg
: REG_SORT_ORDER
[reg
])
77 return [extra
] + retval
81 # very quick, TODO move to SelectableInt utils later
82 def genmask(shift
, size
):
83 res
= SelectableInt(0, size
)
86 res
[size
-1-i
] = SelectableInt(1, 1)
92 //Accessing 2nd double word of partition table (pate1)
93 //Ref: Power ISA Manual v3.0B, Book-III, section 5.7.6.1
95 // ====================================================
96 // -----------------------------------------------
97 // | /// | PATB | /// | PATS |
98 // -----------------------------------------------
100 // PATB[4:51] holds the base address of the Partition Table,
101 // right shifted by 12 bits.
102 // This is because the address of the Partition base is
103 // 4k aligned. Hence, the lower 12bits, which are always
104 // 0 are ommitted from the PTCR.
106 // Thus, The Partition Table Base is obtained by (PATB << 12)
108 // PATS represents the partition table size right-shifted by 12 bits.
109 // The minimal size of the partition table is 4k.
110 // Thus partition table size = (1 << PATS + 12).
113 // ====================================================
114 // 0 PATE0 63 PATE1 127
115 // |----------------------|----------------------|
117 // |----------------------|----------------------|
119 // |----------------------|----------------------|
121 // |----------------------|----------------------|
125 // |----------------------|----------------------|
127 // |----------------------|----------------------|
129 // The effective LPID forms the index into the Partition Table.
131 // Each entry in the partition table contains 2 double words, PATE0, PATE1,
132 // corresponding to that partition.
134 // In case of Radix, The structure of PATE0 and PATE1 is as follows.
137 // -----------------------------------------------
138 // |1|RTS1|/| RPDB | RTS2 | RPDS |
139 // -----------------------------------------------
140 // 0 1 2 3 4 55 56 58 59 63
142 // HR[0] : For Radix Page table, first bit should be 1.
143 // RTS1[1:2] : Gives one fragment of the Radix treesize
144 // RTS2[56:58] : Gives the second fragment of the Radix Tree size.
145 // RTS = (RTS1 << 3 + RTS2) + 31.
147 // RPDB[4:55] = Root Page Directory Base.
148 // RPDS = Logarithm of Root Page Directory Size right shifted by 3.
149 // Thus, Root page directory size = 1 << (RPDS + 3).
153 // -----------------------------------------------
154 // |///| PRTB | // | PRTS |
155 // -----------------------------------------------
156 // 0 3 4 51 52 58 59 63
158 // PRTB[4:51] = Process Table Base. This is aligned to size.
159 // PRTS[59: 63] = Process Table Size right shifted by 12.
160 // Minimal size of the process table is 4k.
161 // Process Table Size = (1 << PRTS + 12).
164 // Computing the size aligned Process Table Base:
165 // table_base = (PRTB & ~((1 << PRTS) - 1)) << 12
166 // Thus, the lower 12+PRTS bits of table_base will
170 //Ref: Power ISA Manual v3.0B, Book-III, section 5.7.6.2
173 // ==========================
174 // 0 PRTE0 63 PRTE1 127
175 // |----------------------|----------------------|
177 // |----------------------|----------------------|
179 // |----------------------|----------------------|
181 // |----------------------|----------------------|
185 // |----------------------|----------------------|
187 // |----------------------|----------------------|
189 // The effective Process id (PID) forms the index into the Process Table.
191 // Each entry in the partition table contains 2 double words, PRTE0, PRTE1,
192 // corresponding to that process
194 // In case of Radix, The structure of PRTE0 and PRTE1 is as follows.
197 // -----------------------------------------------
198 // |/|RTS1|/| RPDB | RTS2 | RPDS |
199 // -----------------------------------------------
200 // 0 1 2 3 4 55 56 58 59 63
202 // RTS1[1:2] : Gives one fragment of the Radix treesize
203 // RTS2[56:58] : Gives the second fragment of the Radix Tree size.
204 // RTS = (RTS1 << 3 + RTS2) << 31,
205 // since minimal Radix Tree size is 4G.
207 // RPDB = Root Page Directory Base.
208 // RPDS = Root Page Directory Size right shifted by 3.
209 // Thus, Root page directory size = RPDS << 3.
213 // -----------------------------------------------
215 // -----------------------------------------------
217 // All bits are reserved.
222 # see qemu/target/ppc/mmu-radix64.c for reference
224 def __init__(self
, mem
, caller
):
228 # cached page table stuff
230 self
.pt0_valid
= False
232 self
.pt3_valid
= False
234 def __call__(self
,*args
, **kwargs
):
235 print("TODO: implement RADIX.__call__()")
240 def ld(self
, address
, width
=8, swap
=True, check_in_mem
=False):
241 print("RADIX: ld from addr 0x%x width %d" % (address
, width
))
242 dsisr
= self
.caller
.spr
[DEC_SPR
.DSISR
.value
]
243 dar
= self
.caller
.spr
[DEC_SPR
.DAR
.value
]
244 pidr
= self
.caller
.spr
[DEC_SPR
.PIDR
.value
]
245 prtbl
= self
.caller
.spr
[DEC_SPR
.PRTBL
.value
]
247 pte
= self
._walk
_tree
()
248 # use pte to caclculate phys address
249 return self
.mem
.ld(address
, width
, swap
, check_in_mem
)
251 # XXX set SPRs on error
254 def st(self
, addr
, v
, width
=8, swap
=True):
255 print("RADIX: st to addr 0x%x width %d data %x" % (addr
, width
, v
))
256 dsisr
= self
.caller
.spr
[DEC_SPR
.DSISR
.value
]
257 dar
= self
.caller
.spr
[DEC_SPR
.DAR
.value
]
258 pidr
= self
.caller
.spr
[DEC_SPR
.PIDR
.value
]
259 prtbl
= self
.caller
.spr
[DEC_SPR
.PRTBL
.value
]
261 # use pte to caclculate phys address (addr)
262 return self
.mem
.st(addr
, v
, width
, swap
)
264 # XXX set SPRs on error
266 def memassign(self
, addr
, sz
, val
):
267 print("memassign", addr
, sz
, val
)
268 self
.st(addr
.value
, val
.value
, sz
, swap
=False)
270 def _next_level(self
):
275 ## Prepare for next iteration
277 def _walk_tree(self
):
281 // vaddr |-----------------------------------------------------|
283 // |-----------|-----------------------------------------|
284 // | 0000000 | usefulBits = X bits (typically 52) |
285 // |-----------|-----------------------------------------|
286 // | |<--Cursize---->| |
290 // |-----------------------------------------------------|
293 // PDE |---------------------------| |
294 // |V|L|//| NLB |///|NLS| |
295 // |---------------------------| |
296 // PDE = Page Directory Entry |
297 // [0] = V = Valid Bit |
298 // [1] = L = Leaf bit. If 0, then |
299 // [4:55] = NLB = Next Level Base |
300 // right shifted by 8 |
301 // [59:63] = NLS = Next Level Size |
304 // | |--------------------------|
305 // | | usfulBits = X-Cursize |
306 // | |--------------------------|
307 // |---------------------><--NLS-->| |
311 // |--------------------------|
313 // If the next PDE obtained by |
314 // (NLB << 8 + 8 * index) is a |
315 // nonleaf, then repeat the above. |
317 // If the next PDE is a leaf, |
318 // then Leaf PDE structure is as |
323 // |------------------------------| |----------------|
324 // |V|L|sw|//|RPN|sw|R|C|/|ATT|EAA| | usefulBits |
325 // |------------------------------| |----------------|
326 // [0] = V = Valid Bit |
327 // [1] = L = Leaf Bit = 1 if leaf |
329 // [2] = Sw = Sw bit 0. |
330 // [7:51] = RPN = Real Page Number, V
331 // real_page = RPN << 12 -------------> Logical OR
332 // [52:54] = Sw Bits 1:3 |
333 // [55] = R = Reference |
334 // [56] = C = Change V
335 // [58:59] = Att = Physical Address
336 // 0b00 = Normal Memory
338 // 0b10 = Non Idenmpotent
339 // 0b11 = Tolerant I/O
340 // [60:63] = Encoded Access
344 # walk tree starts on prtbl
346 ret
= self
._next
_level
()
349 def _decode_prte(self
, data
):
351 -----------------------------------------------
352 |/|RTS1|/| RPDB | RTS2 | RPDS |
353 -----------------------------------------------
354 0 1 2 3 4 55 56 58 59 63
356 # note that SelectableInt does big-endian! so the indices
357 # below *directly* match the spec, unlike microwatt which
358 # has to turn them around (to LE)
359 zero
= SelectableInt(0, 1)
360 rts
= selectconcat(zero
,
364 masksize
= data
[59:64] # RPDS
365 mbits
= selectconcat(zero
, masksize
)
366 pgbase
= selectconcat(data
[8:56], # part of RPDB
367 SelectableInt(0, 16),)
369 return (rts
, mbits
, pgbase
)
371 def _segment_check(self
, addr
, mbits
, shift
):
372 """checks segment valid
373 mbits := '0' & r.mask_size;
374 v.shift := r.shift + (31 - 12) - mbits;
375 nonzero := or(r.addr(61 downto 31) and not finalmask(30 downto 0));
376 if r.addr(63) /= r.addr(62) or nonzero = '1' then
377 v.state := RADIX_FINISH;
379 elsif mbits < 5 or mbits > 16 or mbits > (r.shift + (31 - 12)) then
380 v.state := RADIX_FINISH;
383 v.state := RADIX_LOOKUP;
385 # note that SelectableInt does big-endian! so the indices
386 # below *directly* match the spec, unlike microwatt which
387 # has to turn them around (to LE)
388 mask
= genmask(shift
, 43)
389 nonzero
= addr
[1:32] & mask
[12:43] # mask 31 LSBs (BE numbered 12:43)
390 print ("RADIX _segment_check nonzero", bin(nonzero
.value
))
391 print ("RADIX _segment_check addr[0-1]", addr
[0].value
, addr
[1].value
)
392 if addr
[0] != addr
[1] or nonzero
== 1:
394 limit
= shift
+ (31 - 12)
395 if mbits
< 5 or mbits
> 16 or mbits
> limit
:
397 new_shift
= shift
+ (31 - 12) - mbits
400 def _check_perms(self
):
401 """check page permissions
403 if data(62) = '1' then
404 -- check permissions and RC bits
406 if r.priv = '1' or data(3) = '0' then
407 if r.iside = '0' then
408 perm_ok := data(1) or (data(2) and not r.store);
410 -- no IAMR, so no KUEP support for now
411 -- deny execute permission if cache inhibited
412 perm_ok := data(0) and not data(5);
415 rc_ok := data(8) and (data(7) or not r.store);
416 if perm_ok = '1' and rc_ok = '1' then
417 v.state := RADIX_LOAD_TLB;
419 v.state := RADIX_FINISH;
420 v.perm_err := not perm_ok;
421 -- permission error takes precedence over RC error
422 v.rc_error := perm_ok;
426 def _get_prtable_addr(self
, prtbl
, addr
):
428 if r.addr(63) = '1' then
429 effpid := x"00000000";
433 prtable_addr := x"00" & r.prtbl(55 downto 36) &
434 ((r.prtbl(35 downto 12) and not finalmask(23 downto 0)) or
435 (effpid(31 downto 8) and finalmask(23 downto 0))) &
436 effpid(7 downto 0) & "0000";
439 def _get_pgtable_addr(self
):
441 pgtable_addr := x"00" & r.pgbase(55 downto 19) &
442 ((r.pgbase(18 downto 3) and not mask) or (addrsh and mask)) &
449 ((r.pde(55 downto 12) and not finalmask) or (r.addr(55 downto 12) and finalmask))
450 & r.pde(11 downto 0);
456 def __init__(self
, row_bytes
=8, initial_mem
=None):
458 self
.bytes_per_word
= row_bytes
459 self
.word_log2
= math
.ceil(math
.log2(row_bytes
))
460 print("Sim-Mem", initial_mem
, self
.bytes_per_word
, self
.word_log2
)
464 # different types of memory data structures recognised (for convenience)
465 if isinstance(initial_mem
, list):
466 initial_mem
= (0, initial_mem
)
467 if isinstance(initial_mem
, tuple):
468 startaddr
, mem
= initial_mem
470 for i
, val
in enumerate(mem
):
471 initial_mem
[startaddr
+ row_bytes
*i
] = (val
, row_bytes
)
473 for addr
, (val
, width
) in initial_mem
.items():
474 #val = swap_order(val, width)
475 self
.st(addr
, val
, width
, swap
=False)
477 def _get_shifter_mask(self
, wid
, remainder
):
478 shifter
= ((self
.bytes_per_word
- wid
) - remainder
) * \
480 # XXX https://bugs.libre-soc.org/show_bug.cgi?id=377
482 shifter
= remainder
* 8
483 mask
= (1 << (wid
* 8)) - 1
484 print("width,rem,shift,mask", wid
, remainder
, hex(shifter
), hex(mask
))
487 # TODO: Implement ld/st of lesser width
488 def ld(self
, address
, width
=8, swap
=True, check_in_mem
=False):
489 print("ld from addr 0x{:x} width {:d}".format(address
, width
))
490 remainder
= address
& (self
.bytes_per_word
- 1)
491 address
= address
>> self
.word_log2
492 assert remainder
& (width
- 1) == 0, "Unaligned access unsupported!"
493 if address
in self
.mem
:
494 val
= self
.mem
[address
]
499 print("mem @ 0x{:x} rem {:d} : 0x{:x}".format(address
, remainder
, val
))
501 if width
!= self
.bytes_per_word
:
502 shifter
, mask
= self
._get
_shifter
_mask
(width
, remainder
)
503 print("masking", hex(val
), hex(mask
<< shifter
), shifter
)
504 val
= val
& (mask
<< shifter
)
507 val
= swap_order(val
, width
)
508 print("Read 0x{:x} from addr 0x{:x}".format(val
, address
))
511 def st(self
, addr
, v
, width
=8, swap
=True):
513 remainder
= addr
& (self
.bytes_per_word
- 1)
514 addr
= addr
>> self
.word_log2
515 print("Writing 0x{:x} to ST 0x{:x} "
516 "memaddr 0x{:x}/{:x}".format(v
, staddr
, addr
, remainder
, swap
))
517 assert remainder
& (width
- 1) == 0, "Unaligned access unsupported!"
519 v
= swap_order(v
, width
)
520 if width
!= self
.bytes_per_word
:
525 shifter
, mask
= self
._get
_shifter
_mask
(width
, remainder
)
526 val
&= ~
(mask
<< shifter
)
531 print("mem @ 0x{:x}: 0x{:x}".format(addr
, self
.mem
[addr
]))
533 def __call__(self
, addr
, sz
):
534 val
= self
.ld(addr
.value
, sz
, swap
=False)
535 print("memread", addr
, sz
, val
)
536 return SelectableInt(val
, sz
*8)
538 def memassign(self
, addr
, sz
, val
):
539 print("memassign", addr
, sz
, val
)
540 self
.st(addr
.value
, val
.value
, sz
, swap
=False)
544 def __init__(self
, decoder
, isacaller
, svstate
, regfile
):
547 self
.isacaller
= isacaller
548 self
.svstate
= svstate
550 self
[i
] = SelectableInt(regfile
[i
], 64)
552 def __call__(self
, ridx
):
555 def set_form(self
, form
):
558 def getz(self
, rnum
):
559 # rnum = rnum.value # only SelectableInt allowed
560 print("GPR getzero", rnum
)
562 return SelectableInt(0, 64)
565 def _get_regnum(self
, attr
):
566 getform
= self
.sd
.sigforms
[self
.form
]
567 rnum
= getattr(getform
, attr
)
570 def ___getitem__(self
, attr
):
571 """ XXX currently not used
573 rnum
= self
._get
_regnum
(attr
)
574 offs
= self
.svstate
.srcstep
575 print("GPR getitem", attr
, rnum
, "srcoffs", offs
)
576 return self
.regfile
[rnum
]
579 for i
in range(0, len(self
), 8):
582 s
.append("%08x" % self
[i
+j
].value
)
584 print("reg", "%2d" % i
, s
)
588 def __init__(self
, pc_init
=0):
589 self
.CIA
= SelectableInt(pc_init
, 64)
590 self
.NIA
= self
.CIA
+ SelectableInt(4, 64) # only true for v3.0B!
592 def update_nia(self
, is_svp64
):
593 increment
= 8 if is_svp64
else 4
594 self
.NIA
= self
.CIA
+ SelectableInt(increment
, 64)
596 def update(self
, namespace
, is_svp64
):
597 """updates the program counter (PC) by 4 if v3.0B mode or 8 if SVP64
599 self
.CIA
= namespace
['NIA'].narrow(64)
600 self
.update_nia(is_svp64
)
601 namespace
['CIA'] = self
.CIA
602 namespace
['NIA'] = self
.NIA
605 # Simple-V: see https://libre-soc.org/openpower/sv
607 def __init__(self
, init
=0):
608 self
.spr
= SelectableInt(init
, 32)
609 # fields of SVSTATE, see https://libre-soc.org/openpower/sv/sprs/
610 self
.maxvl
= FieldSelectableInt(self
.spr
, tuple(range(0,7)))
611 self
.vl
= FieldSelectableInt(self
.spr
, tuple(range(7,14)))
612 self
.srcstep
= FieldSelectableInt(self
.spr
, tuple(range(14,21)))
613 self
.dststep
= FieldSelectableInt(self
.spr
, tuple(range(21,28)))
614 self
.subvl
= FieldSelectableInt(self
.spr
, tuple(range(28,30)))
615 self
.svstep
= FieldSelectableInt(self
.spr
, tuple(range(30,32)))
620 def __init__(self
, init
=0):
621 self
.spr
= SelectableInt(init
, 24)
622 # SVP64 RM fields: see https://libre-soc.org/openpower/sv/svp64/
623 self
.mmode
= FieldSelectableInt(self
.spr
, [0])
624 self
.mask
= FieldSelectableInt(self
.spr
, tuple(range(1,4)))
625 self
.elwidth
= FieldSelectableInt(self
.spr
, tuple(range(4,6)))
626 self
.ewsrc
= FieldSelectableInt(self
.spr
, tuple(range(6,8)))
627 self
.subvl
= FieldSelectableInt(self
.spr
, tuple(range(8,10)))
628 self
.extra
= FieldSelectableInt(self
.spr
, tuple(range(10,19)))
629 self
.mode
= FieldSelectableInt(self
.spr
, tuple(range(19,24)))
630 # these cover the same extra field, split into parts as EXTRA2
631 self
.extra2
= list(range(4))
632 self
.extra2
[0] = FieldSelectableInt(self
.spr
, tuple(range(10,12)))
633 self
.extra2
[1] = FieldSelectableInt(self
.spr
, tuple(range(12,14)))
634 self
.extra2
[2] = FieldSelectableInt(self
.spr
, tuple(range(14,16)))
635 self
.extra2
[3] = FieldSelectableInt(self
.spr
, tuple(range(16,18)))
636 self
.smask
= FieldSelectableInt(self
.spr
, tuple(range(16,19)))
637 # and here as well, but EXTRA3
638 self
.extra3
= list(range(3))
639 self
.extra3
[0] = FieldSelectableInt(self
.spr
, tuple(range(10,13)))
640 self
.extra3
[1] = FieldSelectableInt(self
.spr
, tuple(range(13,16)))
641 self
.extra3
[2] = FieldSelectableInt(self
.spr
, tuple(range(16,19)))
644 SVP64RM_MMODE_SIZE
= len(SVP64RMFields().mmode
.br
)
645 SVP64RM_MASK_SIZE
= len(SVP64RMFields().mask
.br
)
646 SVP64RM_ELWIDTH_SIZE
= len(SVP64RMFields().elwidth
.br
)
647 SVP64RM_EWSRC_SIZE
= len(SVP64RMFields().ewsrc
.br
)
648 SVP64RM_SUBVL_SIZE
= len(SVP64RMFields().subvl
.br
)
649 SVP64RM_EXTRA2_SPEC_SIZE
= len(SVP64RMFields().extra2
[0].br
)
650 SVP64RM_EXTRA3_SPEC_SIZE
= len(SVP64RMFields().extra3
[0].br
)
651 SVP64RM_SMASK_SIZE
= len(SVP64RMFields().smask
.br
)
652 SVP64RM_MODE_SIZE
= len(SVP64RMFields().mode
.br
)
655 # SVP64 Prefix fields: see https://libre-soc.org/openpower/sv/svp64/
656 class SVP64PrefixFields
:
658 self
.insn
= SelectableInt(0, 32)
659 # 6 bit major opcode EXT001, 2 bits "identifying" (7, 9), 24 SV ReMap
660 self
.major
= FieldSelectableInt(self
.insn
, tuple(range(0,6)))
661 self
.pid
= FieldSelectableInt(self
.insn
, (7, 9)) # must be 0b11
662 rmfields
= [6, 8] + list(range(10,32)) # SVP64 24-bit RM (ReMap)
663 self
.rm
= FieldSelectableInt(self
.insn
, rmfields
)
666 SV64P_MAJOR_SIZE
= len(SVP64PrefixFields().major
.br
)
667 SV64P_PID_SIZE
= len(SVP64PrefixFields().pid
.br
)
668 SV64P_RM_SIZE
= len(SVP64PrefixFields().rm
.br
)
672 def __init__(self
, dec2
, initial_sprs
={}):
675 for key
, v
in initial_sprs
.items():
676 if isinstance(key
, SelectableInt
):
678 key
= special_sprs
.get(key
, key
)
679 if isinstance(key
, int):
682 info
= spr_byname
[key
]
683 if not isinstance(v
, SelectableInt
):
684 v
= SelectableInt(v
, info
.length
)
687 def __getitem__(self
, key
):
688 print("get spr", key
)
689 print("dict", self
.items())
690 # if key in special_sprs get the special spr, otherwise return key
691 if isinstance(key
, SelectableInt
):
693 if isinstance(key
, int):
694 key
= spr_dict
[key
].SPR
695 key
= special_sprs
.get(key
, key
)
696 if key
== 'HSRR0': # HACK!
698 if key
== 'HSRR1': # HACK!
701 res
= dict.__getitem
__(self
, key
)
703 if isinstance(key
, int):
706 info
= spr_byname
[key
]
707 dict.__setitem
__(self
, key
, SelectableInt(0, info
.length
))
708 res
= dict.__getitem
__(self
, key
)
709 print("spr returning", key
, res
)
712 def __setitem__(self
, key
, value
):
713 if isinstance(key
, SelectableInt
):
715 if isinstance(key
, int):
716 key
= spr_dict
[key
].SPR
717 print("spr key", key
)
718 key
= special_sprs
.get(key
, key
)
719 if key
== 'HSRR0': # HACK!
720 self
.__setitem
__('SRR0', value
)
721 if key
== 'HSRR1': # HACK!
722 self
.__setitem
__('SRR1', value
)
723 print("setting spr", key
, value
)
724 dict.__setitem
__(self
, key
, value
)
726 def __call__(self
, ridx
):
729 def get_pdecode_idx_in(dec2
, name
):
731 in1_sel
= yield op
.in1_sel
732 in2_sel
= yield op
.in2_sel
733 in3_sel
= yield op
.in3_sel
734 # get the IN1/2/3 from the decoder (includes SVP64 remap and isvec)
735 in1
= yield dec2
.e
.read_reg1
.data
736 in2
= yield dec2
.e
.read_reg2
.data
737 in3
= yield dec2
.e
.read_reg3
.data
738 in1_isvec
= yield dec2
.in1_isvec
739 in2_isvec
= yield dec2
.in2_isvec
740 in3_isvec
= yield dec2
.in3_isvec
741 print ("get_pdecode_idx", in1_sel
, In1Sel
.RA
.value
, in1
, in1_isvec
)
742 # identify which regnames map to in1/2/3
744 if (in1_sel
== In1Sel
.RA
.value
or
745 (in1_sel
== In1Sel
.RA_OR_ZERO
.value
and in1
!= 0)):
746 return in1
, in1_isvec
747 if in1_sel
== In1Sel
.RA_OR_ZERO
.value
:
748 return in1
, in1_isvec
750 if in2_sel
== In2Sel
.RB
.value
:
751 return in2
, in2_isvec
752 if in3_sel
== In3Sel
.RB
.value
:
753 return in3
, in3_isvec
754 # XXX TODO, RC doesn't exist yet!
756 assert False, "RC does not exist yet"
758 if in1_sel
== In1Sel
.RS
.value
:
759 return in1
, in1_isvec
760 if in2_sel
== In2Sel
.RS
.value
:
761 return in2
, in2_isvec
762 if in3_sel
== In3Sel
.RS
.value
:
763 return in3
, in3_isvec
767 def get_pdecode_cr_out(dec2
, name
):
769 out_sel
= yield op
.cr_out
770 out_bitfield
= yield dec2
.dec_cr_out
.cr_bitfield
.data
771 sv_cr_out
= yield op
.sv_cr_out
772 spec
= yield dec2
.crout_svdec
.spec
773 sv_override
= yield dec2
.dec_cr_out
.sv_override
774 # get the IN1/2/3 from the decoder (includes SVP64 remap and isvec)
775 out
= yield dec2
.e
.write_cr
.data
776 o_isvec
= yield dec2
.o_isvec
777 print ("get_pdecode_cr_out", out_sel
, CROutSel
.CR0
.value
, out
, o_isvec
)
778 print (" sv_cr_out", sv_cr_out
)
779 print (" cr_bf", out_bitfield
)
780 print (" spec", spec
)
781 print (" override", sv_override
)
782 # identify which regnames map to out / o2
784 if out_sel
== CROutSel
.CR0
.value
:
786 print ("get_pdecode_idx_out not found", name
)
790 def get_pdecode_idx_out(dec2
, name
):
792 out_sel
= yield op
.out_sel
793 # get the IN1/2/3 from the decoder (includes SVP64 remap and isvec)
794 out
= yield dec2
.e
.write_reg
.data
795 o_isvec
= yield dec2
.o_isvec
796 print ("get_pdecode_idx_out", out_sel
, OutSel
.RA
.value
, out
, o_isvec
)
797 # identify which regnames map to out / o2
799 if out_sel
== OutSel
.RA
.value
:
802 if out_sel
== OutSel
.RT
.value
:
804 print ("get_pdecode_idx_out not found", name
)
809 def get_pdecode_idx_out2(dec2
, name
):
811 print ("TODO: get_pdecode_idx_out2", name
)
816 # decoder2 - an instance of power_decoder2
817 # regfile - a list of initial values for the registers
818 # initial_{etc} - initial values for SPRs, Condition Register, Mem, MSR
819 # respect_pc - tracks the program counter. requires initial_insns
820 def __init__(self
, decoder2
, regfile
, initial_sprs
=None, initial_cr
=0,
821 initial_mem
=None, initial_msr
=0,
823 initial_insns
=None, respect_pc
=False,
829 self
.bigendian
= bigendian
831 self
.is_svp64_mode
= False
832 self
.respect_pc
= respect_pc
833 if initial_sprs
is None:
835 if initial_mem
is None:
837 if initial_insns
is None:
839 assert self
.respect_pc
== False, "instructions required to honor pc"
841 print("ISACaller insns", respect_pc
, initial_insns
, disassembly
)
842 print("ISACaller initial_msr", initial_msr
)
844 # "fake program counter" mode (for unit testing)
848 if isinstance(initial_mem
, tuple):
849 self
.fake_pc
= initial_mem
[0]
850 disasm_start
= self
.fake_pc
852 disasm_start
= initial_pc
854 # disassembly: we need this for now (not given from the decoder)
855 self
.disassembly
= {}
857 for i
, code
in enumerate(disassembly
):
858 self
.disassembly
[i
*4 + disasm_start
] = code
860 # set up registers, instruction memory, data memory, PC, SPRs, MSR
861 self
.svp64rm
= SVP64RM()
862 if isinstance(initial_svstate
, int):
863 initial_svstate
= SVP64State(initial_svstate
)
864 self
.svstate
= initial_svstate
865 self
.gpr
= GPR(decoder2
, self
, self
.svstate
, regfile
)
866 self
.mem
= Mem(row_bytes
=8, initial_mem
=initial_mem
)
868 self
.mem
= RADIX(self
.mem
, self
)
869 self
.imem
= Mem(row_bytes
=4, initial_mem
=initial_insns
)
871 self
.spr
= SPR(decoder2
, initial_sprs
)
872 self
.msr
= SelectableInt(initial_msr
, 64) # underlying reg
875 # FPR (same as GPR except for FP nums)
876 # 4.2.2 p124 FPSCR (definitely "separate" - not in SPR)
877 # note that mffs, mcrfs, mtfsf "manage" this FPSCR
878 # 2.3.1 CR (and sub-fields CR0..CR6 - CR0 SO comes from XER.SO)
879 # note that mfocrf, mfcr, mtcr, mtocrf, mcrxrx "manage" CRs
881 # 2.3.2 LR (actually SPR #8) -- Done
882 # 2.3.3 CTR (actually SPR #9) -- Done
883 # 2.3.4 TAR (actually SPR #815)
884 # 3.2.2 p45 XER (actually SPR #1) -- Done
885 # 3.2.3 p46 p232 VRSAVE (actually SPR #256)
887 # create CR then allow portions of it to be "selectable" (below)
888 #rev_cr = int('{:016b}'.format(initial_cr)[::-1], 2)
889 self
.cr
= SelectableInt(initial_cr
, 64) # underlying reg
890 #self.cr = FieldSelectableInt(self._cr, list(range(32, 64)))
892 # "undefined", just set to variable-bit-width int (use exts "max")
893 #self.undefined = SelectableInt(0, 256) # TODO, not hard-code 256!
896 self
.namespace
.update(self
.spr
)
897 self
.namespace
.update({'GPR': self
.gpr
,
900 'memassign': self
.memassign
,
905 'undefined': undefined
,
906 'mode_is_64bit': True,
910 # update pc to requested start point
911 self
.set_pc(initial_pc
)
913 # field-selectable versions of Condition Register TODO check bitranges?
916 bits
= tuple(range(i
*4+32, (i
+1)*4+32)) # errr... maybe?
917 _cr
= FieldSelectableInt(self
.cr
, bits
)
919 self
.namespace
["CR%d" % i
] = _cr
921 self
.decoder
= decoder2
.dec
924 def TRAP(self
, trap_addr
=0x700, trap_bit
=PIb
.TRAP
):
925 print("TRAP:", hex(trap_addr
), hex(self
.namespace
['MSR'].value
))
926 # store CIA(+4?) in SRR0, set NIA to 0x700
927 # store MSR in SRR1, set MSR to um errr something, have to check spec
928 self
.spr
['SRR0'].value
= self
.pc
.CIA
.value
929 self
.spr
['SRR1'].value
= self
.namespace
['MSR'].value
930 self
.trap_nia
= SelectableInt(trap_addr
, 64)
931 self
.spr
['SRR1'][trap_bit
] = 1 # change *copy* of MSR in SRR1
933 # set exception bits. TODO: this should, based on the address
934 # in figure 66 p1065 V3.0B and the table figure 65 p1063 set these
935 # bits appropriately. however it turns out that *for now* in all
936 # cases (all trap_addrs) the exact same thing is needed.
937 self
.msr
[MSRb
.IR
] = 0
938 self
.msr
[MSRb
.DR
] = 0
939 self
.msr
[MSRb
.FE0
] = 0
940 self
.msr
[MSRb
.FE1
] = 0
941 self
.msr
[MSRb
.EE
] = 0
942 self
.msr
[MSRb
.RI
] = 0
943 self
.msr
[MSRb
.SF
] = 1
944 self
.msr
[MSRb
.TM
] = 0
945 self
.msr
[MSRb
.VEC
] = 0
946 self
.msr
[MSRb
.VSX
] = 0
947 self
.msr
[MSRb
.PR
] = 0
948 self
.msr
[MSRb
.FP
] = 0
949 self
.msr
[MSRb
.PMM
] = 0
950 self
.msr
[MSRb
.TEs
] = 0
951 self
.msr
[MSRb
.TEe
] = 0
952 self
.msr
[MSRb
.UND
] = 0
953 self
.msr
[MSRb
.LE
] = 1
955 def memassign(self
, ea
, sz
, val
):
956 self
.mem
.memassign(ea
, sz
, val
)
958 def prep_namespace(self
, formname
, op_fields
):
959 # TODO: get field names from form in decoder*1* (not decoder2)
960 # decoder2 is hand-created, and decoder1.sigform is auto-generated
962 # then "yield" fields only from op_fields rather than hard-coded
964 fields
= self
.decoder
.sigforms
[formname
]
965 for name
in op_fields
:
967 sig
= getattr(fields
, name
.upper())
969 sig
= getattr(fields
, name
)
971 # these are all opcode fields involved in index-selection of CR,
972 # and need to do "standard" arithmetic. CR[BA+32] for example
973 # would, if using SelectableInt, only be 5-bit.
974 if name
in ['BF', 'BFA', 'BC', 'BA', 'BB', 'BT', 'BI']:
975 self
.namespace
[name
] = val
977 self
.namespace
[name
] = SelectableInt(val
, sig
.width
)
979 self
.namespace
['XER'] = self
.spr
['XER']
980 self
.namespace
['CA'] = self
.spr
['XER'][XER_bits
['CA']].value
981 self
.namespace
['CA32'] = self
.spr
['XER'][XER_bits
['CA32']].value
983 def handle_carry_(self
, inputs
, outputs
, already_done
):
984 inv_a
= yield self
.dec2
.e
.do
.invert_in
986 inputs
[0] = ~inputs
[0]
988 imm_ok
= yield self
.dec2
.e
.do
.imm_data
.ok
990 imm
= yield self
.dec2
.e
.do
.imm_data
.data
991 inputs
.append(SelectableInt(imm
, 64))
992 assert len(outputs
) >= 1
993 print("outputs", repr(outputs
))
994 if isinstance(outputs
, list) or isinstance(outputs
, tuple):
1000 print("gt input", x
, output
)
1001 gt
= (gtu(x
, output
))
1004 cy
= 1 if any(gts
) else 0
1005 print("CA", cy
, gts
)
1006 if not (1 & already_done
):
1007 self
.spr
['XER'][XER_bits
['CA']] = cy
1009 print("inputs", already_done
, inputs
)
1011 # ARGH... different for OP_ADD... *sigh*...
1012 op
= yield self
.dec2
.e
.do
.insn_type
1013 if op
== MicrOp
.OP_ADD
.value
:
1014 res32
= (output
.value
& (1 << 32)) != 0
1015 a32
= (inputs
[0].value
& (1 << 32)) != 0
1016 if len(inputs
) >= 2:
1017 b32
= (inputs
[1].value
& (1 << 32)) != 0
1020 cy32
= res32 ^ a32 ^ b32
1021 print("CA32 ADD", cy32
)
1025 print("input", x
, output
)
1026 print(" x[32:64]", x
, x
[32:64])
1027 print(" o[32:64]", output
, output
[32:64])
1028 gt
= (gtu(x
[32:64], output
[32:64])) == SelectableInt(1, 1)
1030 cy32
= 1 if any(gts
) else 0
1031 print("CA32", cy32
, gts
)
1032 if not (2 & already_done
):
1033 self
.spr
['XER'][XER_bits
['CA32']] = cy32
1035 def handle_overflow(self
, inputs
, outputs
, div_overflow
):
1036 if hasattr(self
.dec2
.e
.do
, "invert_in"):
1037 inv_a
= yield self
.dec2
.e
.do
.invert_in
1039 inputs
[0] = ~inputs
[0]
1041 imm_ok
= yield self
.dec2
.e
.do
.imm_data
.ok
1043 imm
= yield self
.dec2
.e
.do
.imm_data
.data
1044 inputs
.append(SelectableInt(imm
, 64))
1045 assert len(outputs
) >= 1
1046 print("handle_overflow", inputs
, outputs
, div_overflow
)
1047 if len(inputs
) < 2 and div_overflow
is None:
1050 # div overflow is different: it's returned by the pseudo-code
1051 # because it's more complex than can be done by analysing the output
1052 if div_overflow
is not None:
1053 ov
, ov32
= div_overflow
, div_overflow
1054 # arithmetic overflow can be done by analysing the input and output
1055 elif len(inputs
) >= 2:
1059 input_sgn
= [exts(x
.value
, x
.bits
) < 0 for x
in inputs
]
1060 output_sgn
= exts(output
.value
, output
.bits
) < 0
1061 ov
= 1 if input_sgn
[0] == input_sgn
[1] and \
1062 output_sgn
!= input_sgn
[0] else 0
1065 input32_sgn
= [exts(x
.value
, 32) < 0 for x
in inputs
]
1066 output32_sgn
= exts(output
.value
, 32) < 0
1067 ov32
= 1 if input32_sgn
[0] == input32_sgn
[1] and \
1068 output32_sgn
!= input32_sgn
[0] else 0
1070 self
.spr
['XER'][XER_bits
['OV']] = ov
1071 self
.spr
['XER'][XER_bits
['OV32']] = ov32
1072 so
= self
.spr
['XER'][XER_bits
['SO']]
1074 self
.spr
['XER'][XER_bits
['SO']] = so
1076 def handle_comparison(self
, outputs
, cr_idx
=0):
1078 assert isinstance(out
, SelectableInt
), \
1079 "out zero not a SelectableInt %s" % repr(outputs
)
1080 print("handle_comparison", out
.bits
, hex(out
.value
))
1081 # TODO - XXX *processor* in 32-bit mode
1082 # https://bugs.libre-soc.org/show_bug.cgi?id=424
1084 # o32 = exts(out.value, 32)
1085 # print ("handle_comparison exts 32 bit", hex(o32))
1086 out
= exts(out
.value
, out
.bits
)
1087 print("handle_comparison exts", hex(out
))
1088 zero
= SelectableInt(out
== 0, 1)
1089 positive
= SelectableInt(out
> 0, 1)
1090 negative
= SelectableInt(out
< 0, 1)
1091 SO
= self
.spr
['XER'][XER_bits
['SO']]
1092 print("handle_comparison SO", SO
)
1093 cr_field
= selectconcat(negative
, positive
, zero
, SO
)
1094 self
.crl
[cr_idx
].eq(cr_field
)
1096 def set_pc(self
, pc_val
):
1097 self
.namespace
['NIA'] = SelectableInt(pc_val
, 64)
1098 self
.pc
.update(self
.namespace
, self
.is_svp64_mode
)
1100 def setup_one(self
):
1101 """set up one instruction
1104 pc
= self
.pc
.CIA
.value
1108 ins
= self
.imem
.ld(pc
, 4, False, True)
1110 raise KeyError("no instruction at 0x%x" % pc
)
1111 print("setup: 0x%x 0x%x %s" % (pc
, ins
& 0xffffffff, bin(ins
)))
1112 print("CIA NIA", self
.respect_pc
, self
.pc
.CIA
.value
, self
.pc
.NIA
.value
)
1114 yield self
.dec2
.sv_rm
.eq(0)
1115 yield self
.dec2
.dec
.raw_opcode_in
.eq(ins
& 0xffffffff)
1116 yield self
.dec2
.dec
.bigendian
.eq(self
.bigendian
)
1117 yield self
.dec2
.state
.msr
.eq(self
.msr
.value
)
1118 yield self
.dec2
.state
.pc
.eq(pc
)
1119 yield self
.dec2
.state
.svstate
.eq(self
.svstate
.spr
.value
)
1121 # SVP64. first, check if the opcode is EXT001, and SVP64 id bits set
1123 opcode
= yield self
.dec2
.dec
.opcode_in
1124 pfx
= SVP64PrefixFields() # TODO should probably use SVP64PrefixDecoder
1125 pfx
.insn
.value
= opcode
1126 major
= pfx
.major
.asint(msb0
=True) # MSB0 inversion
1127 print ("prefix test: opcode:", major
, bin(major
),
1128 pfx
.insn
[7] == 0b1, pfx
.insn
[9] == 0b1)
1129 self
.is_svp64_mode
= ((major
== 0b000001) and
1130 pfx
.insn
[7].value
== 0b1 and
1131 pfx
.insn
[9].value
== 0b1)
1132 self
.pc
.update_nia(self
.is_svp64_mode
)
1133 self
.namespace
['NIA'] = self
.pc
.NIA
1134 if not self
.is_svp64_mode
:
1137 # in SVP64 mode. decode/print out svp64 prefix, get v3.0B instruction
1138 print ("svp64.rm", bin(pfx
.rm
.asint(msb0
=True)))
1139 print (" svstate.vl", self
.svstate
.vl
.asint(msb0
=True))
1140 print (" svstate.mvl", self
.svstate
.maxvl
.asint(msb0
=True))
1141 sv_rm
= pfx
.rm
.asint(msb0
=True)
1142 ins
= self
.imem
.ld(pc
+4, 4, False, True)
1143 print(" svsetup: 0x%x 0x%x %s" % (pc
+4, ins
& 0xffffffff, bin(ins
)))
1144 yield self
.dec2
.dec
.raw_opcode_in
.eq(ins
& 0xffffffff) # v3.0B suffix
1145 yield self
.dec2
.sv_rm
.eq(sv_rm
) # svp64 prefix
1148 def execute_one(self
):
1149 """execute one instruction
1151 # get the disassembly code for this instruction
1152 if self
.is_svp64_mode
:
1153 code
= self
.disassembly
[self
._pc
+4]
1154 print(" svp64 sim-execute", hex(self
._pc
), code
)
1156 code
= self
.disassembly
[self
._pc
]
1157 print("sim-execute", hex(self
._pc
), code
)
1158 opname
= code
.split(' ')[0]
1159 yield from self
.call(opname
)
1161 # don't use this except in special circumstances
1162 if not self
.respect_pc
:
1165 print("execute one, CIA NIA", self
.pc
.CIA
.value
, self
.pc
.NIA
.value
)
1167 def get_assembly_name(self
):
1168 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
1169 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
1170 dec_insn
= yield self
.dec2
.e
.do
.insn
1171 asmcode
= yield self
.dec2
.dec
.op
.asmcode
1172 print("get assembly name asmcode", asmcode
, hex(dec_insn
))
1173 asmop
= insns
.get(asmcode
, None)
1174 int_op
= yield self
.dec2
.dec
.op
.internal_op
1176 # sigh reconstruct the assembly instruction name
1177 if hasattr(self
.dec2
.e
.do
, "oe"):
1178 ov_en
= yield self
.dec2
.e
.do
.oe
.oe
1179 ov_ok
= yield self
.dec2
.e
.do
.oe
.ok
1183 if hasattr(self
.dec2
.e
.do
, "rc"):
1184 rc_en
= yield self
.dec2
.e
.do
.rc
.rc
1185 rc_ok
= yield self
.dec2
.e
.do
.rc
.ok
1189 # grrrr have to special-case MUL op (see DecodeOE)
1190 print("ov %d en %d rc %d en %d op %d" %
1191 (ov_ok
, ov_en
, rc_ok
, rc_en
, int_op
))
1192 if int_op
in [MicrOp
.OP_MUL_H64
.value
, MicrOp
.OP_MUL_H32
.value
]:
1197 if not asmop
.endswith("."): # don't add "." to "andis."
1200 if hasattr(self
.dec2
.e
.do
, "lk"):
1201 lk
= yield self
.dec2
.e
.do
.lk
1204 print("int_op", int_op
)
1205 if int_op
in [MicrOp
.OP_B
.value
, MicrOp
.OP_BC
.value
]:
1206 AA
= yield self
.dec2
.dec
.fields
.FormI
.AA
[0:-1]
1210 spr_msb
= yield from self
.get_spr_msb()
1211 if int_op
== MicrOp
.OP_MFCR
.value
:
1216 # XXX TODO: for whatever weird reason this doesn't work
1217 # https://bugs.libre-soc.org/show_bug.cgi?id=390
1218 if int_op
== MicrOp
.OP_MTCRF
.value
:
1225 def get_spr_msb(self
):
1226 dec_insn
= yield self
.dec2
.e
.do
.insn
1227 return dec_insn
& (1 << 20) != 0 # sigh - XFF.spr[-1]?
1229 def call(self
, name
):
1230 """call(opcode) - the primary execution point for instructions
1232 name
= name
.strip() # remove spaces if not already done so
1234 print("halted - not executing", name
)
1237 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
1238 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
1239 asmop
= yield from self
.get_assembly_name()
1240 print("call", name
, asmop
)
1243 int_op
= yield self
.dec2
.dec
.op
.internal_op
1244 spr_msb
= yield from self
.get_spr_msb()
1246 instr_is_privileged
= False
1247 if int_op
in [MicrOp
.OP_ATTN
.value
,
1248 MicrOp
.OP_MFMSR
.value
,
1249 MicrOp
.OP_MTMSR
.value
,
1250 MicrOp
.OP_MTMSRD
.value
,
1252 MicrOp
.OP_RFID
.value
]:
1253 instr_is_privileged
= True
1254 if int_op
in [MicrOp
.OP_MFSPR
.value
,
1255 MicrOp
.OP_MTSPR
.value
] and spr_msb
:
1256 instr_is_privileged
= True
1258 print("is priv", instr_is_privileged
, hex(self
.msr
.value
),
1260 # check MSR priv bit and whether op is privileged: if so, throw trap
1261 if instr_is_privileged
and self
.msr
[MSRb
.PR
] == 1:
1262 self
.TRAP(0x700, PIb
.PRIV
)
1263 self
.namespace
['NIA'] = self
.trap_nia
1264 self
.pc
.update(self
.namespace
, self
.is_svp64_mode
)
1267 # check halted condition
1272 # check illegal instruction
1274 if name
not in ['mtcrf', 'mtocrf']:
1275 illegal
= name
!= asmop
1278 print("illegal", name
, asmop
)
1279 self
.TRAP(0x700, PIb
.ILLEG
)
1280 self
.namespace
['NIA'] = self
.trap_nia
1281 self
.pc
.update(self
.namespace
, self
.is_svp64_mode
)
1282 print("name %s != %s - calling ILLEGAL trap, PC: %x" %
1283 (name
, asmop
, self
.pc
.CIA
.value
))
1286 info
= self
.instrs
[name
]
1287 yield from self
.prep_namespace(info
.form
, info
.op_fields
)
1289 # preserve order of register names
1290 input_names
= create_args(list(info
.read_regs
) +
1291 list(info
.uninit_regs
))
1294 # get SVP64 entry for the current instruction
1295 sv_rm
= self
.svp64rm
.instrs
.get(name
)
1296 if sv_rm
is not None:
1297 dest_cr
, src_cr
, src_byname
, dest_byname
= decode_extra(sv_rm
)
1299 dest_cr
, src_cr
, src_byname
, dest_byname
= False, False, {}, {}
1300 print ("sv rm", sv_rm
, dest_cr
, src_cr
, src_byname
, dest_byname
)
1302 # get SVSTATE srcstep. TODO: dststep (twin predication)
1303 srcstep
= self
.svstate
.srcstep
.asint(msb0
=True)
1304 vl
= self
.svstate
.vl
.asint(msb0
=True)
1305 mvl
= self
.svstate
.maxvl
.asint(msb0
=True)
1307 # VL=0 in SVP64 mode means "do nothing: skip instruction"
1308 if self
.is_svp64_mode
and vl
== 0:
1309 self
.pc
.update(self
.namespace
, self
.is_svp64_mode
)
1310 print("end of call", self
.namespace
['CIA'], self
.namespace
['NIA'])
1313 # main input registers (RT, RA ...)
1315 for name
in input_names
:
1316 # using PowerDecoder2, first, find the decoder index.
1317 # (mapping name RA RB RC RS to in1, in2, in3)
1318 regnum
, is_vec
= yield from get_pdecode_idx_in(self
.dec2
, name
)
1320 # doing this is not part of svp64, it's because output
1321 # registers, to be modified, need to be in the namespace.
1322 regnum
, is_vec
= yield from get_pdecode_idx_out(self
.dec2
, name
)
1323 # here's where we go "vector". TODO: zero-testing (RA_IS_ZERO)
1324 # XXX already done by PowerDecoder2, now
1326 # regnum += srcstep # TODO, elwidth overrides
1328 # in case getting the register number is needed, _RA, _RB
1329 regname
= "_" + name
1330 self
.namespace
[regname
] = regnum
1331 print('reading reg %s %d' % (name
, regnum
), is_vec
)
1332 reg_val
= self
.gpr(regnum
)
1333 inputs
.append(reg_val
)
1335 # "special" registers
1336 for special
in info
.special_regs
:
1337 if special
in special_sprs
:
1338 inputs
.append(self
.spr
[special
])
1340 inputs
.append(self
.namespace
[special
])
1342 # clear trap (trap) NIA
1343 self
.trap_nia
= None
1345 print("inputs", inputs
)
1346 results
= info
.func(self
, *inputs
)
1347 print("results", results
)
1349 # "inject" decorator takes namespace from function locals: we need to
1350 # overwrite NIA being overwritten (sigh)
1351 if self
.trap_nia
is not None:
1352 self
.namespace
['NIA'] = self
.trap_nia
1354 print("after func", self
.namespace
['CIA'], self
.namespace
['NIA'])
1356 # detect if CA/CA32 already in outputs (sra*, basically)
1359 output_names
= create_args(info
.write_regs
)
1360 for name
in output_names
:
1366 print("carry already done?", bin(already_done
))
1367 if hasattr(self
.dec2
.e
.do
, "output_carry"):
1368 carry_en
= yield self
.dec2
.e
.do
.output_carry
1372 yield from self
.handle_carry_(inputs
, results
, already_done
)
1374 # detect if overflow was in return result
1377 for name
, output
in zip(output_names
, results
):
1378 if name
== 'overflow':
1381 if hasattr(self
.dec2
.e
.do
, "oe"):
1382 ov_en
= yield self
.dec2
.e
.do
.oe
.oe
1383 ov_ok
= yield self
.dec2
.e
.do
.oe
.ok
1387 print("internal overflow", overflow
, ov_en
, ov_ok
)
1389 yield from self
.handle_overflow(inputs
, results
, overflow
)
1391 if hasattr(self
.dec2
.e
.do
, "rc"):
1392 rc_en
= yield self
.dec2
.e
.do
.rc
.rc
1396 regnum
, is_vec
= yield from get_pdecode_cr_out(self
.dec2
, "CR0")
1397 self
.handle_comparison(results
, regnum
)
1399 # any modified return results?
1401 for name
, output
in zip(output_names
, results
):
1402 if name
== 'overflow': # ignore, done already (above)
1404 if isinstance(output
, int):
1405 output
= SelectableInt(output
, 256)
1406 if name
in ['CA', 'CA32']:
1408 print("writing %s to XER" % name
, output
)
1409 self
.spr
['XER'][XER_bits
[name
]] = output
.value
1411 print("NOT writing %s to XER" % name
, output
)
1412 elif name
in info
.special_regs
:
1413 print('writing special %s' % name
, output
, special_sprs
)
1414 if name
in special_sprs
:
1415 self
.spr
[name
] = output
1417 self
.namespace
[name
].eq(output
)
1419 print('msr written', hex(self
.msr
.value
))
1421 regnum
, is_vec
= yield from get_pdecode_idx_out(self
.dec2
,
1424 # temporary hack for not having 2nd output
1425 regnum
= yield getattr(self
.decoder
, name
)
1427 print('writing reg %d %s' % (regnum
, str(output
)), is_vec
)
1428 if output
.bits
> 64:
1429 output
= SelectableInt(output
.value
, 64)
1430 self
.gpr
[regnum
] = output
1432 # check if it is the SVSTATE.src/dest step that needs incrementing
1433 # this is our Sub-Program-Counter loop from 0 to VL-1
1434 if self
.is_svp64_mode
:
1435 # XXX twin predication TODO
1436 vl
= self
.svstate
.vl
.asint(msb0
=True)
1437 mvl
= self
.svstate
.maxvl
.asint(msb0
=True)
1438 srcstep
= self
.svstate
.srcstep
.asint(msb0
=True)
1439 print (" svstate.vl", vl
)
1440 print (" svstate.mvl", mvl
)
1441 print (" svstate.srcstep", srcstep
)
1442 # check if srcstep needs incrementing by one, stop PC advancing
1443 # svp64 loop can end early if the dest is scalar
1444 svp64_dest_vector
= not (yield self
.dec2
.no_out_vec
)
1445 if svp64_dest_vector
and srcstep
!= vl
-1:
1446 self
.svstate
.srcstep
+= SelectableInt(1, 7)
1447 self
.pc
.NIA
.value
= self
.pc
.CIA
.value
1448 self
.namespace
['NIA'] = self
.pc
.NIA
1449 print("end of sub-pc call", self
.namespace
['CIA'],
1450 self
.namespace
['NIA'])
1451 return # DO NOT allow PC to update whilst Sub-PC loop running
1453 self
.svstate
.srcstep
[0:7] = 0
1454 print (" svstate.srcstep loop end (PC to update)")
1455 self
.pc
.update_nia(self
.is_svp64_mode
)
1456 self
.namespace
['NIA'] = self
.pc
.NIA
1458 # UPDATE program counter
1459 self
.pc
.update(self
.namespace
, self
.is_svp64_mode
)
1460 print("end of call", self
.namespace
['CIA'], self
.namespace
['NIA'])
1464 """Decorator factory.
1466 this decorator will "inject" variables into the function's namespace,
1467 from the *dictionary* in self.namespace. it therefore becomes possible
1468 to make it look like a whole stack of variables which would otherwise
1469 need "self." inserted in front of them (*and* for those variables to be
1470 added to the instance) "appear" in the function.
1472 "self.namespace['SI']" for example becomes accessible as just "SI" but
1473 *only* inside the function, when decorated.
1475 def variable_injector(func
):
1477 def decorator(*args
, **kwargs
):
1479 func_globals
= func
.__globals
__ # Python 2.6+
1480 except AttributeError:
1481 func_globals
= func
.func_globals
# Earlier versions.
1483 context
= args
[0].namespace
# variables to be injected
1484 saved_values
= func_globals
.copy() # Shallow copy of dict.
1485 func_globals
.update(context
)
1486 result
= func(*args
, **kwargs
)
1487 print("globals after", func_globals
['CIA'], func_globals
['NIA'])
1488 print("args[0]", args
[0].namespace
['CIA'],
1489 args
[0].namespace
['NIA'])
1490 args
[0].namespace
= func_globals
1491 #exec (func.__code__, func_globals)
1494 # func_globals = saved_values # Undo changes.
1500 return variable_injector
1503 # very quick test of maskgen function (TODO, move to util later)
1504 if __name__
== '__main__':
1505 shift
= SelectableInt(5, 6)
1506 mask
= genmask(shift
, 43)
1507 print (" mask", bin(mask
.value
))
1509 mem
= Mem(row_bytes
=8)
1510 mem
= RADIX(mem
, None)
1511 # -----------------------------------------------
1512 # |/|RTS1|/| RPDB | RTS2 | RPDS |
1513 # -----------------------------------------------
1514 # |0|1 2|3|4 55|56 58|59 63|
1515 data
= SelectableInt(0, 64)
1518 data
[59:64] = 0b01101 # mask
1520 (rts
, mbits
, pgbase
) = mem
._decode
_prte
(data
)
1521 print (" rts", bin(rts
.value
), rts
.bits
)
1522 print (" mbits", bin(mbits
.value
), mbits
.bits
)
1523 print (" pgbase", hex(pgbase
.value
), pgbase
.bits
)
1524 addr
= SelectableInt(0x1000, 64)
1525 check
= mem
._segment
_check
(addr
, mbits
, shift
)
1526 print (" segment check", check
)