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
,
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
29 from collections
import namedtuple
33 instruction_info
= namedtuple('instruction_info',
34 'func read_regs uninit_regs write_regs ' +
35 'special_regs op_fields form asmregs')
45 def swap_order(x
, nbytes
):
46 x
= x
.to_bytes(nbytes
, byteorder
='little')
47 x
= int.from_bytes(x
, byteorder
='big', signed
=False)
52 # TODO (lkcl): adjust other registers that should be in a particular order
53 # probably CA, CA32, and CR
70 def create_args(reglist
, extra
=None):
71 retval
= list(OrderedSet(reglist
))
72 retval
.sort(key
=lambda reg
: REG_SORT_ORDER
[reg
])
74 return [extra
] + retval
81 //Accessing 2nd double word of partition table (pate1)
82 //Ref: Power ISA Manual v3.0B, Book-III, section 5.7.6.1
84 // ====================================================
85 // -----------------------------------------------
86 // | /// | PATB | /// | PATS |
87 // -----------------------------------------------
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.
95 // Thus, The Partition Table Base is obtained by (PATB << 12)
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).
102 // ====================================================
103 // 0 PATE0 63 PATE1 127
104 // |----------------------|----------------------|
106 // |----------------------|----------------------|
108 // |----------------------|----------------------|
110 // |----------------------|----------------------|
114 // |----------------------|----------------------|
116 // |----------------------|----------------------|
118 // The effective LPID forms the index into the Partition Table.
120 // Each entry in the partition table contains 2 double words, PATE0, PATE1,
121 // corresponding to that partition.
123 // In case of Radix, The structure of PATE0 and PATE1 is as follows.
126 // -----------------------------------------------
127 // |1|RTS1|/| RPDB | RTS2 | RPDS |
128 // -----------------------------------------------
129 // 0 1 2 3 4 55 56 58 59 63
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.
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).
142 // -----------------------------------------------
143 // |///| PRTB | // | PRTS |
144 // -----------------------------------------------
145 // 0 3 4 51 52 58 59 63
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).
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
159 //Ref: Power ISA Manual v3.0B, Book-III, section 5.7.6.2
162 // ==========================
163 // 0 PRTE0 63 PRTE1 127
164 // |----------------------|----------------------|
166 // |----------------------|----------------------|
168 // |----------------------|----------------------|
170 // |----------------------|----------------------|
174 // |----------------------|----------------------|
176 // |----------------------|----------------------|
178 // The effective Process id (PID) forms the index into the Process Table.
180 // Each entry in the partition table contains 2 double words, PRTE0, PRTE1,
181 // corresponding to that process
183 // In case of Radix, The structure of PRTE0 and PRTE1 is as follows.
186 // -----------------------------------------------
187 // |/|RTS1|/| RPDB | RTS2 | RPDS |
188 // -----------------------------------------------
189 // 0 1 2 3 4 55 56 58 59 63
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.
196 // RPDB = Root Page Directory Base.
197 // RPDS = Root Page Directory Size right shifted by 3.
198 // Thus, Root page directory size = RPDS << 3.
202 // -----------------------------------------------
204 // -----------------------------------------------
206 // All bits are reserved.
211 # see qemu/target/ppc/mmu-radix64.c for reference
213 def __init__(self
, mem
, caller
):
217 # cached page table stuff
219 self
.pt0_valid
= False
221 self
.pt3_valid
= False
223 def ld(self
, address
, width
=8, swap
=True, check_in_mem
=False):
224 print("RADIX: ld from addr 0x{:x} width {:d}".format(address
, width
))
226 pte
= self
._walk
_tree
()
227 # use pte to caclculate phys address
228 #mem.ld(address,width,swap,check_in_mem)
231 # def st(self, addr, v, width=8, swap=True):
232 # def memassign(self, addr, sz, val):
233 def _next_level(self
):
238 ## Prepare for next iteration
240 def _walk_tree(self
):
244 // vaddr |-----------------------------------------------------|
246 // |-----------|-----------------------------------------|
247 // | 0000000 | usefulBits = X bits (typically 52) |
248 // |-----------|-----------------------------------------|
249 // | |<--Cursize---->| |
253 // |-----------------------------------------------------|
256 // PDE |---------------------------| |
257 // |V|L|//| NLB |///|NLS| |
258 // |---------------------------| |
259 // PDE = Page Directory Entry |
260 // [0] = V = Valid Bit |
261 // [1] = L = Leaf bit. If 0, then |
262 // [4:55] = NLB = Next Level Base |
263 // right shifted by 8 |
264 // [59:63] = NLS = Next Level Size |
267 // | |--------------------------|
268 // | | usfulBits = X-Cursize |
269 // | |--------------------------|
270 // |---------------------><--NLS-->| |
274 // |--------------------------|
276 // If the next PDE obtained by |
277 // (NLB << 8 + 8 * index) is a |
278 // nonleaf, then repeat the above. |
280 // If the next PDE is a leaf, |
281 // then Leaf PDE structure is as |
286 // |------------------------------| |----------------|
287 // |V|L|sw|//|RPN|sw|R|C|/|ATT|EAA| | usefulBits |
288 // |------------------------------| |----------------|
289 // [0] = V = Valid Bit |
290 // [1] = L = Leaf Bit = 1 if leaf |
292 // [2] = Sw = Sw bit 0. |
293 // [7:51] = RPN = Real Page Number, V
294 // real_page = RPN << 12 -------------> Logical OR
295 // [52:54] = Sw Bits 1:3 |
296 // [55] = R = Reference |
297 // [56] = C = Change V
298 // [58:59] = Att = Physical Address
299 // 0b00 = Normal Memory
301 // 0b10 = Non Idenmpotent
302 // 0b11 = Tolerant I/O
303 // [60:63] = Encoded Access
307 # walk tree starts on prtbl
309 ret
= self
._next
_level
()
312 def _segment_check(self
):
313 """checks segment valid
314 mbits := '0' & r.mask_size;
315 v.shift := r.shift + (31 - 12) - mbits;
316 nonzero := or(r.addr(61 downto 31) and not finalmask(30 downto 0));
317 if r.addr(63) /= r.addr(62) or nonzero = '1' then
318 v.state := RADIX_FINISH;
320 elsif mbits < 5 or mbits > 16 or mbits > (r.shift + (31 - 12)) then
321 v.state := RADIX_FINISH;
324 v.state := RADIX_LOOKUP;
327 def _check_perms(self
):
328 """check page permissions
330 if data(62) = '1' then
331 -- check permissions and RC bits
333 if r.priv = '1' or data(3) = '0' then
334 if r.iside = '0' then
335 perm_ok := data(1) or (data(2) and not r.store);
337 -- no IAMR, so no KUEP support for now
338 -- deny execute permission if cache inhibited
339 perm_ok := data(0) and not data(5);
342 rc_ok := data(8) and (data(7) or not r.store);
343 if perm_ok = '1' and rc_ok = '1' then
344 v.state := RADIX_LOAD_TLB;
346 v.state := RADIX_FINISH;
347 v.perm_err := not perm_ok;
348 -- permission error takes precedence over RC error
349 v.rc_error := perm_ok;
356 def __init__(self
, row_bytes
=8, initial_mem
=None):
358 self
.bytes_per_word
= row_bytes
359 self
.word_log2
= math
.ceil(math
.log2(row_bytes
))
360 print("Sim-Mem", initial_mem
, self
.bytes_per_word
, self
.word_log2
)
364 # different types of memory data structures recognised (for convenience)
365 if isinstance(initial_mem
, list):
366 initial_mem
= (0, initial_mem
)
367 if isinstance(initial_mem
, tuple):
368 startaddr
, mem
= initial_mem
370 for i
, val
in enumerate(mem
):
371 initial_mem
[startaddr
+ row_bytes
*i
] = (val
, row_bytes
)
373 for addr
, (val
, width
) in initial_mem
.items():
374 #val = swap_order(val, width)
375 self
.st(addr
, val
, width
, swap
=False)
377 def _get_shifter_mask(self
, wid
, remainder
):
378 shifter
= ((self
.bytes_per_word
- wid
) - remainder
) * \
380 # XXX https://bugs.libre-soc.org/show_bug.cgi?id=377
382 shifter
= remainder
* 8
383 mask
= (1 << (wid
* 8)) - 1
384 print("width,rem,shift,mask", wid
, remainder
, hex(shifter
), hex(mask
))
387 # TODO: Implement ld/st of lesser width
388 def ld(self
, address
, width
=8, swap
=True, check_in_mem
=False):
389 print("ld from addr 0x{:x} width {:d}".format(address
, width
))
390 remainder
= address
& (self
.bytes_per_word
- 1)
391 address
= address
>> self
.word_log2
392 assert remainder
& (width
- 1) == 0, "Unaligned access unsupported!"
393 if address
in self
.mem
:
394 val
= self
.mem
[address
]
399 print("mem @ 0x{:x} rem {:d} : 0x{:x}".format(address
, remainder
, val
))
401 if width
!= self
.bytes_per_word
:
402 shifter
, mask
= self
._get
_shifter
_mask
(width
, remainder
)
403 print("masking", hex(val
), hex(mask
<< shifter
), shifter
)
404 val
= val
& (mask
<< shifter
)
407 val
= swap_order(val
, width
)
408 print("Read 0x{:x} from addr 0x{:x}".format(val
, address
))
411 def st(self
, addr
, v
, width
=8, swap
=True):
413 remainder
= addr
& (self
.bytes_per_word
- 1)
414 addr
= addr
>> self
.word_log2
415 print("Writing 0x{:x} to ST 0x{:x} "
416 "memaddr 0x{:x}/{:x}".format(v
, staddr
, addr
, remainder
, swap
))
417 assert remainder
& (width
- 1) == 0, "Unaligned access unsupported!"
419 v
= swap_order(v
, width
)
420 if width
!= self
.bytes_per_word
:
425 shifter
, mask
= self
._get
_shifter
_mask
(width
, remainder
)
426 val
&= ~
(mask
<< shifter
)
431 print("mem @ 0x{:x}: 0x{:x}".format(addr
, self
.mem
[addr
]))
433 def __call__(self
, addr
, sz
):
434 val
= self
.ld(addr
.value
, sz
, swap
=False)
435 print("memread", addr
, sz
, val
)
436 return SelectableInt(val
, sz
*8)
438 def memassign(self
, addr
, sz
, val
):
439 print("memassign", addr
, sz
, val
)
440 self
.st(addr
.value
, val
.value
, sz
, swap
=False)
444 def __init__(self
, decoder
, isacaller
, svstate
, regfile
):
447 self
.isacaller
= isacaller
448 self
.svstate
= svstate
450 self
[i
] = SelectableInt(regfile
[i
], 64)
452 def __call__(self
, ridx
):
455 def set_form(self
, form
):
458 def getz(self
, rnum
):
459 # rnum = rnum.value # only SelectableInt allowed
460 print("GPR getzero", rnum
)
462 return SelectableInt(0, 64)
465 def _get_regnum(self
, attr
):
466 getform
= self
.sd
.sigforms
[self
.form
]
467 rnum
= getattr(getform
, attr
)
470 def ___getitem__(self
, attr
):
471 """ XXX currently not used
473 rnum
= self
._get
_regnum
(attr
)
474 offs
= self
.svstate
.srcstep
475 print("GPR getitem", attr
, rnum
, "srcoffs", offs
)
476 return self
.regfile
[rnum
]
479 for i
in range(0, len(self
), 8):
482 s
.append("%08x" % self
[i
+j
].value
)
484 print("reg", "%2d" % i
, s
)
488 def __init__(self
, pc_init
=0):
489 self
.CIA
= SelectableInt(pc_init
, 64)
490 self
.NIA
= self
.CIA
+ SelectableInt(4, 64) # only true for v3.0B!
492 def update_nia(self
, is_svp64
):
493 increment
= 8 if is_svp64
else 4
494 self
.NIA
= self
.CIA
+ SelectableInt(increment
, 64)
496 def update(self
, namespace
, is_svp64
):
497 """updates the program counter (PC) by 4 if v3.0B mode or 8 if SVP64
499 self
.CIA
= namespace
['NIA'].narrow(64)
500 self
.update_nia(is_svp64
)
501 namespace
['CIA'] = self
.CIA
502 namespace
['NIA'] = self
.NIA
505 # Simple-V: see https://libre-soc.org/openpower/sv
507 def __init__(self
, init
=0):
508 self
.spr
= SelectableInt(init
, 32)
509 # fields of SVSTATE, see https://libre-soc.org/openpower/sv/sprs/
510 self
.maxvl
= FieldSelectableInt(self
.spr
, tuple(range(0,7)))
511 self
.vl
= FieldSelectableInt(self
.spr
, tuple(range(7,14)))
512 self
.srcstep
= FieldSelectableInt(self
.spr
, tuple(range(14,21)))
513 self
.dststep
= FieldSelectableInt(self
.spr
, tuple(range(21,28)))
514 self
.subvl
= FieldSelectableInt(self
.spr
, tuple(range(28,30)))
515 self
.svstep
= FieldSelectableInt(self
.spr
, tuple(range(30,32)))
520 def __init__(self
, init
=0):
521 self
.spr
= SelectableInt(init
, 24)
522 # SVP64 RM fields: see https://libre-soc.org/openpower/sv/svp64/
523 self
.mmode
= FieldSelectableInt(self
.spr
, [0])
524 self
.mask
= FieldSelectableInt(self
.spr
, tuple(range(1,4)))
525 self
.elwidth
= FieldSelectableInt(self
.spr
, tuple(range(4,6)))
526 self
.ewsrc
= FieldSelectableInt(self
.spr
, tuple(range(6,8)))
527 self
.subvl
= FieldSelectableInt(self
.spr
, tuple(range(8,10)))
528 self
.extra
= FieldSelectableInt(self
.spr
, tuple(range(10,19)))
529 self
.mode
= FieldSelectableInt(self
.spr
, tuple(range(19,24)))
530 # these cover the same extra field, split into parts as EXTRA2
531 self
.extra2
= list(range(4))
532 self
.extra2
[0] = FieldSelectableInt(self
.spr
, tuple(range(10,12)))
533 self
.extra2
[1] = FieldSelectableInt(self
.spr
, tuple(range(12,14)))
534 self
.extra2
[2] = FieldSelectableInt(self
.spr
, tuple(range(14,16)))
535 self
.extra2
[3] = FieldSelectableInt(self
.spr
, tuple(range(16,18)))
536 self
.smask
= FieldSelectableInt(self
.spr
, tuple(range(16,19)))
537 # and here as well, but EXTRA3
538 self
.extra3
= list(range(3))
539 self
.extra3
[0] = FieldSelectableInt(self
.spr
, tuple(range(10,13)))
540 self
.extra3
[1] = FieldSelectableInt(self
.spr
, tuple(range(13,16)))
541 self
.extra3
[2] = FieldSelectableInt(self
.spr
, tuple(range(16,19)))
544 SVP64RM_MMODE_SIZE
= len(SVP64RMFields().mmode
.br
)
545 SVP64RM_MASK_SIZE
= len(SVP64RMFields().mask
.br
)
546 SVP64RM_ELWIDTH_SIZE
= len(SVP64RMFields().elwidth
.br
)
547 SVP64RM_EWSRC_SIZE
= len(SVP64RMFields().ewsrc
.br
)
548 SVP64RM_SUBVL_SIZE
= len(SVP64RMFields().subvl
.br
)
549 SVP64RM_EXTRA2_SPEC_SIZE
= len(SVP64RMFields().extra2
[0].br
)
550 SVP64RM_EXTRA3_SPEC_SIZE
= len(SVP64RMFields().extra3
[0].br
)
551 SVP64RM_SMASK_SIZE
= len(SVP64RMFields().smask
.br
)
552 SVP64RM_MODE_SIZE
= len(SVP64RMFields().mode
.br
)
555 # SVP64 Prefix fields: see https://libre-soc.org/openpower/sv/svp64/
556 class SVP64PrefixFields
:
558 self
.insn
= SelectableInt(0, 32)
559 # 6 bit major opcode EXT001, 2 bits "identifying" (7, 9), 24 SV ReMap
560 self
.major
= FieldSelectableInt(self
.insn
, tuple(range(0,6)))
561 self
.pid
= FieldSelectableInt(self
.insn
, (7, 9)) # must be 0b11
562 rmfields
= [6, 8] + list(range(10,32)) # SVP64 24-bit RM (ReMap)
563 self
.rm
= FieldSelectableInt(self
.insn
, rmfields
)
566 SV64P_MAJOR_SIZE
= len(SVP64PrefixFields().major
.br
)
567 SV64P_PID_SIZE
= len(SVP64PrefixFields().pid
.br
)
568 SV64P_RM_SIZE
= len(SVP64PrefixFields().rm
.br
)
572 def __init__(self
, dec2
, initial_sprs
={}):
575 for key
, v
in initial_sprs
.items():
576 if isinstance(key
, SelectableInt
):
578 key
= special_sprs
.get(key
, key
)
579 if isinstance(key
, int):
582 info
= spr_byname
[key
]
583 if not isinstance(v
, SelectableInt
):
584 v
= SelectableInt(v
, info
.length
)
587 def __getitem__(self
, key
):
588 print("get spr", key
)
589 print("dict", self
.items())
590 # if key in special_sprs get the special spr, otherwise return key
591 if isinstance(key
, SelectableInt
):
593 if isinstance(key
, int):
594 key
= spr_dict
[key
].SPR
595 key
= special_sprs
.get(key
, key
)
596 if key
== 'HSRR0': # HACK!
598 if key
== 'HSRR1': # HACK!
601 res
= dict.__getitem
__(self
, key
)
603 if isinstance(key
, int):
606 info
= spr_byname
[key
]
607 dict.__setitem
__(self
, key
, SelectableInt(0, info
.length
))
608 res
= dict.__getitem
__(self
, key
)
609 print("spr returning", key
, res
)
612 def __setitem__(self
, key
, value
):
613 if isinstance(key
, SelectableInt
):
615 if isinstance(key
, int):
616 key
= spr_dict
[key
].SPR
617 print("spr key", key
)
618 key
= special_sprs
.get(key
, key
)
619 if key
== 'HSRR0': # HACK!
620 self
.__setitem
__('SRR0', value
)
621 if key
== 'HSRR1': # HACK!
622 self
.__setitem
__('SRR1', value
)
623 print("setting spr", key
, value
)
624 dict.__setitem
__(self
, key
, value
)
626 def __call__(self
, ridx
):
629 def get_pdecode_idx_in(dec2
, name
):
631 in1_sel
= yield op
.in1_sel
632 in2_sel
= yield op
.in2_sel
633 in3_sel
= yield op
.in3_sel
634 # get the IN1/2/3 from the decoder (includes SVP64 remap and isvec)
635 in1
= yield dec2
.e
.read_reg1
.data
636 in2
= yield dec2
.e
.read_reg2
.data
637 in3
= yield dec2
.e
.read_reg3
.data
638 in1_isvec
= yield dec2
.in1_isvec
639 in2_isvec
= yield dec2
.in2_isvec
640 in3_isvec
= yield dec2
.in3_isvec
641 print ("get_pdecode_idx", in1_sel
, In1Sel
.RA
.value
, in1
, in1_isvec
)
642 # identify which regnames map to in1/2/3
644 if (in1_sel
== In1Sel
.RA
.value
or
645 (in1_sel
== In1Sel
.RA_OR_ZERO
.value
and in1
!= 0)):
646 return in1
, in1_isvec
647 if in1_sel
== In1Sel
.RA_OR_ZERO
.value
:
648 return in1
, in1_isvec
650 if in2_sel
== In2Sel
.RB
.value
:
651 return in2
, in2_isvec
652 if in3_sel
== In3Sel
.RB
.value
:
653 return in3
, in3_isvec
654 # XXX TODO, RC doesn't exist yet!
656 assert False, "RC does not exist yet"
658 if in1_sel
== In1Sel
.RS
.value
:
659 return in1
, in1_isvec
660 if in2_sel
== In2Sel
.RS
.value
:
661 return in2
, in2_isvec
662 if in3_sel
== In3Sel
.RS
.value
:
663 return in3
, in3_isvec
667 def get_pdecode_cr_out(dec2
, name
):
669 out_sel
= yield op
.cr_out
670 out_bitfield
= yield dec2
.dec_cr_out
.cr_bitfield
.data
671 sv_cr_out
= yield op
.sv_cr_out
672 spec
= yield dec2
.crout_svdec
.spec
673 sv_override
= yield dec2
.dec_cr_out
.sv_override
674 # get the IN1/2/3 from the decoder (includes SVP64 remap and isvec)
675 out
= yield dec2
.e
.write_cr
.data
676 o_isvec
= yield dec2
.o_isvec
677 print ("get_pdecode_cr_out", out_sel
, CROutSel
.CR0
.value
, out
, o_isvec
)
678 print (" sv_cr_out", sv_cr_out
)
679 print (" cr_bf", out_bitfield
)
680 print (" spec", spec
)
681 print (" override", sv_override
)
682 # identify which regnames map to out / o2
684 if out_sel
== CROutSel
.CR0
.value
:
686 print ("get_pdecode_idx_out not found", name
)
690 def get_pdecode_idx_out(dec2
, name
):
692 out_sel
= yield op
.out_sel
693 # get the IN1/2/3 from the decoder (includes SVP64 remap and isvec)
694 out
= yield dec2
.e
.write_reg
.data
695 o_isvec
= yield dec2
.o_isvec
696 print ("get_pdecode_idx_out", out_sel
, OutSel
.RA
.value
, out
, o_isvec
)
697 # identify which regnames map to out / o2
699 if out_sel
== OutSel
.RA
.value
:
702 if out_sel
== OutSel
.RT
.value
:
704 print ("get_pdecode_idx_out not found", name
)
709 def get_pdecode_idx_out2(dec2
, name
):
711 print ("TODO: get_pdecode_idx_out2", name
)
716 # decoder2 - an instance of power_decoder2
717 # regfile - a list of initial values for the registers
718 # initial_{etc} - initial values for SPRs, Condition Register, Mem, MSR
719 # respect_pc - tracks the program counter. requires initial_insns
720 def __init__(self
, decoder2
, regfile
, initial_sprs
=None, initial_cr
=0,
721 initial_mem
=None, initial_msr
=0,
723 initial_insns
=None, respect_pc
=False,
729 self
.bigendian
= bigendian
731 self
.is_svp64_mode
= False
732 self
.respect_pc
= respect_pc
733 if initial_sprs
is None:
735 if initial_mem
is None:
737 if initial_insns
is None:
739 assert self
.respect_pc
== False, "instructions required to honor pc"
741 print("ISACaller insns", respect_pc
, initial_insns
, disassembly
)
742 print("ISACaller initial_msr", initial_msr
)
744 # "fake program counter" mode (for unit testing)
748 if isinstance(initial_mem
, tuple):
749 self
.fake_pc
= initial_mem
[0]
750 disasm_start
= self
.fake_pc
752 disasm_start
= initial_pc
754 # disassembly: we need this for now (not given from the decoder)
755 self
.disassembly
= {}
757 for i
, code
in enumerate(disassembly
):
758 self
.disassembly
[i
*4 + disasm_start
] = code
760 # set up registers, instruction memory, data memory, PC, SPRs, MSR
761 self
.svp64rm
= SVP64RM()
762 if isinstance(initial_svstate
, int):
763 initial_svstate
= SVP64State(initial_svstate
)
764 self
.svstate
= initial_svstate
765 self
.gpr
= GPR(decoder2
, self
, self
.svstate
, regfile
)
766 self
.mem
= Mem(row_bytes
=8, initial_mem
=initial_mem
)
768 self
.mem
= RADIX(self
.mem
, self
)
769 self
.imem
= Mem(row_bytes
=4, initial_mem
=initial_insns
)
771 self
.spr
= SPR(decoder2
, initial_sprs
)
772 self
.msr
= SelectableInt(initial_msr
, 64) # underlying reg
775 # FPR (same as GPR except for FP nums)
776 # 4.2.2 p124 FPSCR (definitely "separate" - not in SPR)
777 # note that mffs, mcrfs, mtfsf "manage" this FPSCR
778 # 2.3.1 CR (and sub-fields CR0..CR6 - CR0 SO comes from XER.SO)
779 # note that mfocrf, mfcr, mtcr, mtocrf, mcrxrx "manage" CRs
781 # 2.3.2 LR (actually SPR #8) -- Done
782 # 2.3.3 CTR (actually SPR #9) -- Done
783 # 2.3.4 TAR (actually SPR #815)
784 # 3.2.2 p45 XER (actually SPR #1) -- Done
785 # 3.2.3 p46 p232 VRSAVE (actually SPR #256)
787 # create CR then allow portions of it to be "selectable" (below)
788 #rev_cr = int('{:016b}'.format(initial_cr)[::-1], 2)
789 self
.cr
= SelectableInt(initial_cr
, 64) # underlying reg
790 #self.cr = FieldSelectableInt(self._cr, list(range(32, 64)))
792 # "undefined", just set to variable-bit-width int (use exts "max")
793 #self.undefined = SelectableInt(0, 256) # TODO, not hard-code 256!
796 self
.namespace
.update(self
.spr
)
797 self
.namespace
.update({'GPR': self
.gpr
,
800 'memassign': self
.memassign
,
805 'undefined': undefined
,
806 'mode_is_64bit': True,
810 # update pc to requested start point
811 self
.set_pc(initial_pc
)
813 # field-selectable versions of Condition Register TODO check bitranges?
816 bits
= tuple(range(i
*4+32, (i
+1)*4+32)) # errr... maybe?
817 _cr
= FieldSelectableInt(self
.cr
, bits
)
819 self
.namespace
["CR%d" % i
] = _cr
821 self
.decoder
= decoder2
.dec
824 def TRAP(self
, trap_addr
=0x700, trap_bit
=PIb
.TRAP
):
825 print("TRAP:", hex(trap_addr
), hex(self
.namespace
['MSR'].value
))
826 # store CIA(+4?) in SRR0, set NIA to 0x700
827 # store MSR in SRR1, set MSR to um errr something, have to check spec
828 self
.spr
['SRR0'].value
= self
.pc
.CIA
.value
829 self
.spr
['SRR1'].value
= self
.namespace
['MSR'].value
830 self
.trap_nia
= SelectableInt(trap_addr
, 64)
831 self
.spr
['SRR1'][trap_bit
] = 1 # change *copy* of MSR in SRR1
833 # set exception bits. TODO: this should, based on the address
834 # in figure 66 p1065 V3.0B and the table figure 65 p1063 set these
835 # bits appropriately. however it turns out that *for now* in all
836 # cases (all trap_addrs) the exact same thing is needed.
837 self
.msr
[MSRb
.IR
] = 0
838 self
.msr
[MSRb
.DR
] = 0
839 self
.msr
[MSRb
.FE0
] = 0
840 self
.msr
[MSRb
.FE1
] = 0
841 self
.msr
[MSRb
.EE
] = 0
842 self
.msr
[MSRb
.RI
] = 0
843 self
.msr
[MSRb
.SF
] = 1
844 self
.msr
[MSRb
.TM
] = 0
845 self
.msr
[MSRb
.VEC
] = 0
846 self
.msr
[MSRb
.VSX
] = 0
847 self
.msr
[MSRb
.PR
] = 0
848 self
.msr
[MSRb
.FP
] = 0
849 self
.msr
[MSRb
.PMM
] = 0
850 self
.msr
[MSRb
.TEs
] = 0
851 self
.msr
[MSRb
.TEe
] = 0
852 self
.msr
[MSRb
.UND
] = 0
853 self
.msr
[MSRb
.LE
] = 1
855 def memassign(self
, ea
, sz
, val
):
856 self
.mem
.memassign(ea
, sz
, val
)
858 def prep_namespace(self
, formname
, op_fields
):
859 # TODO: get field names from form in decoder*1* (not decoder2)
860 # decoder2 is hand-created, and decoder1.sigform is auto-generated
862 # then "yield" fields only from op_fields rather than hard-coded
864 fields
= self
.decoder
.sigforms
[formname
]
865 for name
in op_fields
:
867 sig
= getattr(fields
, name
.upper())
869 sig
= getattr(fields
, name
)
871 # these are all opcode fields involved in index-selection of CR,
872 # and need to do "standard" arithmetic. CR[BA+32] for example
873 # would, if using SelectableInt, only be 5-bit.
874 if name
in ['BF', 'BFA', 'BC', 'BA', 'BB', 'BT', 'BI']:
875 self
.namespace
[name
] = val
877 self
.namespace
[name
] = SelectableInt(val
, sig
.width
)
879 self
.namespace
['XER'] = self
.spr
['XER']
880 self
.namespace
['CA'] = self
.spr
['XER'][XER_bits
['CA']].value
881 self
.namespace
['CA32'] = self
.spr
['XER'][XER_bits
['CA32']].value
883 def handle_carry_(self
, inputs
, outputs
, already_done
):
884 inv_a
= yield self
.dec2
.e
.do
.invert_in
886 inputs
[0] = ~inputs
[0]
888 imm_ok
= yield self
.dec2
.e
.do
.imm_data
.ok
890 imm
= yield self
.dec2
.e
.do
.imm_data
.data
891 inputs
.append(SelectableInt(imm
, 64))
892 assert len(outputs
) >= 1
893 print("outputs", repr(outputs
))
894 if isinstance(outputs
, list) or isinstance(outputs
, tuple):
900 print("gt input", x
, output
)
901 gt
= (gtu(x
, output
))
904 cy
= 1 if any(gts
) else 0
906 if not (1 & already_done
):
907 self
.spr
['XER'][XER_bits
['CA']] = cy
909 print("inputs", already_done
, inputs
)
911 # ARGH... different for OP_ADD... *sigh*...
912 op
= yield self
.dec2
.e
.do
.insn_type
913 if op
== MicrOp
.OP_ADD
.value
:
914 res32
= (output
.value
& (1 << 32)) != 0
915 a32
= (inputs
[0].value
& (1 << 32)) != 0
917 b32
= (inputs
[1].value
& (1 << 32)) != 0
920 cy32
= res32 ^ a32 ^ b32
921 print("CA32 ADD", cy32
)
925 print("input", x
, output
)
926 print(" x[32:64]", x
, x
[32:64])
927 print(" o[32:64]", output
, output
[32:64])
928 gt
= (gtu(x
[32:64], output
[32:64])) == SelectableInt(1, 1)
930 cy32
= 1 if any(gts
) else 0
931 print("CA32", cy32
, gts
)
932 if not (2 & already_done
):
933 self
.spr
['XER'][XER_bits
['CA32']] = cy32
935 def handle_overflow(self
, inputs
, outputs
, div_overflow
):
936 if hasattr(self
.dec2
.e
.do
, "invert_in"):
937 inv_a
= yield self
.dec2
.e
.do
.invert_in
939 inputs
[0] = ~inputs
[0]
941 imm_ok
= yield self
.dec2
.e
.do
.imm_data
.ok
943 imm
= yield self
.dec2
.e
.do
.imm_data
.data
944 inputs
.append(SelectableInt(imm
, 64))
945 assert len(outputs
) >= 1
946 print("handle_overflow", inputs
, outputs
, div_overflow
)
947 if len(inputs
) < 2 and div_overflow
is None:
950 # div overflow is different: it's returned by the pseudo-code
951 # because it's more complex than can be done by analysing the output
952 if div_overflow
is not None:
953 ov
, ov32
= div_overflow
, div_overflow
954 # arithmetic overflow can be done by analysing the input and output
955 elif len(inputs
) >= 2:
959 input_sgn
= [exts(x
.value
, x
.bits
) < 0 for x
in inputs
]
960 output_sgn
= exts(output
.value
, output
.bits
) < 0
961 ov
= 1 if input_sgn
[0] == input_sgn
[1] and \
962 output_sgn
!= input_sgn
[0] else 0
965 input32_sgn
= [exts(x
.value
, 32) < 0 for x
in inputs
]
966 output32_sgn
= exts(output
.value
, 32) < 0
967 ov32
= 1 if input32_sgn
[0] == input32_sgn
[1] and \
968 output32_sgn
!= input32_sgn
[0] else 0
970 self
.spr
['XER'][XER_bits
['OV']] = ov
971 self
.spr
['XER'][XER_bits
['OV32']] = ov32
972 so
= self
.spr
['XER'][XER_bits
['SO']]
974 self
.spr
['XER'][XER_bits
['SO']] = so
976 def handle_comparison(self
, outputs
, cr_idx
=0):
978 assert isinstance(out
, SelectableInt
), \
979 "out zero not a SelectableInt %s" % repr(outputs
)
980 print("handle_comparison", out
.bits
, hex(out
.value
))
981 # TODO - XXX *processor* in 32-bit mode
982 # https://bugs.libre-soc.org/show_bug.cgi?id=424
984 # o32 = exts(out.value, 32)
985 # print ("handle_comparison exts 32 bit", hex(o32))
986 out
= exts(out
.value
, out
.bits
)
987 print("handle_comparison exts", hex(out
))
988 zero
= SelectableInt(out
== 0, 1)
989 positive
= SelectableInt(out
> 0, 1)
990 negative
= SelectableInt(out
< 0, 1)
991 SO
= self
.spr
['XER'][XER_bits
['SO']]
992 print("handle_comparison SO", SO
)
993 cr_field
= selectconcat(negative
, positive
, zero
, SO
)
994 self
.crl
[cr_idx
].eq(cr_field
)
996 def set_pc(self
, pc_val
):
997 self
.namespace
['NIA'] = SelectableInt(pc_val
, 64)
998 self
.pc
.update(self
.namespace
, self
.is_svp64_mode
)
1000 def setup_one(self
):
1001 """set up one instruction
1004 pc
= self
.pc
.CIA
.value
1008 ins
= self
.imem
.ld(pc
, 4, False, True)
1010 raise KeyError("no instruction at 0x%x" % pc
)
1011 print("setup: 0x%x 0x%x %s" % (pc
, ins
& 0xffffffff, bin(ins
)))
1012 print("CIA NIA", self
.respect_pc
, self
.pc
.CIA
.value
, self
.pc
.NIA
.value
)
1014 yield self
.dec2
.sv_rm
.eq(0)
1015 yield self
.dec2
.dec
.raw_opcode_in
.eq(ins
& 0xffffffff)
1016 yield self
.dec2
.dec
.bigendian
.eq(self
.bigendian
)
1017 yield self
.dec2
.state
.msr
.eq(self
.msr
.value
)
1018 yield self
.dec2
.state
.pc
.eq(pc
)
1019 yield self
.dec2
.state
.svstate
.eq(self
.svstate
.spr
.value
)
1021 # SVP64. first, check if the opcode is EXT001, and SVP64 id bits set
1023 opcode
= yield self
.dec2
.dec
.opcode_in
1024 pfx
= SVP64PrefixFields() # TODO should probably use SVP64PrefixDecoder
1025 pfx
.insn
.value
= opcode
1026 major
= pfx
.major
.asint(msb0
=True) # MSB0 inversion
1027 print ("prefix test: opcode:", major
, bin(major
),
1028 pfx
.insn
[7] == 0b1, pfx
.insn
[9] == 0b1)
1029 self
.is_svp64_mode
= ((major
== 0b000001) and
1030 pfx
.insn
[7].value
== 0b1 and
1031 pfx
.insn
[9].value
== 0b1)
1032 self
.pc
.update_nia(self
.is_svp64_mode
)
1033 if not self
.is_svp64_mode
:
1036 # in SVP64 mode. decode/print out svp64 prefix, get v3.0B instruction
1037 print ("svp64.rm", bin(pfx
.rm
.asint(msb0
=True)))
1038 print (" svstate.vl", self
.svstate
.vl
.asint(msb0
=True))
1039 print (" svstate.mvl", self
.svstate
.maxvl
.asint(msb0
=True))
1040 sv_rm
= pfx
.rm
.asint(msb0
=True)
1041 ins
= self
.imem
.ld(pc
+4, 4, False, True)
1042 print(" svsetup: 0x%x 0x%x %s" % (pc
+4, ins
& 0xffffffff, bin(ins
)))
1043 yield self
.dec2
.dec
.raw_opcode_in
.eq(ins
& 0xffffffff) # v3.0B suffix
1044 yield self
.dec2
.sv_rm
.eq(sv_rm
) # svp64 prefix
1047 def execute_one(self
):
1048 """execute one instruction
1050 # get the disassembly code for this instruction
1051 if self
.is_svp64_mode
:
1052 code
= self
.disassembly
[self
._pc
+4]
1053 print(" svp64 sim-execute", hex(self
._pc
), code
)
1055 code
= self
.disassembly
[self
._pc
]
1056 print("sim-execute", hex(self
._pc
), code
)
1057 opname
= code
.split(' ')[0]
1058 yield from self
.call(opname
)
1060 # don't use this except in special circumstances
1061 if not self
.respect_pc
:
1064 print("execute one, CIA NIA", self
.pc
.CIA
.value
, self
.pc
.NIA
.value
)
1066 def get_assembly_name(self
):
1067 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
1068 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
1069 dec_insn
= yield self
.dec2
.e
.do
.insn
1070 asmcode
= yield self
.dec2
.dec
.op
.asmcode
1071 print("get assembly name asmcode", asmcode
, hex(dec_insn
))
1072 asmop
= insns
.get(asmcode
, None)
1073 int_op
= yield self
.dec2
.dec
.op
.internal_op
1075 # sigh reconstruct the assembly instruction name
1076 if hasattr(self
.dec2
.e
.do
, "oe"):
1077 ov_en
= yield self
.dec2
.e
.do
.oe
.oe
1078 ov_ok
= yield self
.dec2
.e
.do
.oe
.ok
1082 if hasattr(self
.dec2
.e
.do
, "rc"):
1083 rc_en
= yield self
.dec2
.e
.do
.rc
.rc
1084 rc_ok
= yield self
.dec2
.e
.do
.rc
.ok
1088 # grrrr have to special-case MUL op (see DecodeOE)
1089 print("ov %d en %d rc %d en %d op %d" %
1090 (ov_ok
, ov_en
, rc_ok
, rc_en
, int_op
))
1091 if int_op
in [MicrOp
.OP_MUL_H64
.value
, MicrOp
.OP_MUL_H32
.value
]:
1096 if not asmop
.endswith("."): # don't add "." to "andis."
1099 if hasattr(self
.dec2
.e
.do
, "lk"):
1100 lk
= yield self
.dec2
.e
.do
.lk
1103 print("int_op", int_op
)
1104 if int_op
in [MicrOp
.OP_B
.value
, MicrOp
.OP_BC
.value
]:
1105 AA
= yield self
.dec2
.dec
.fields
.FormI
.AA
[0:-1]
1109 spr_msb
= yield from self
.get_spr_msb()
1110 if int_op
== MicrOp
.OP_MFCR
.value
:
1115 # XXX TODO: for whatever weird reason this doesn't work
1116 # https://bugs.libre-soc.org/show_bug.cgi?id=390
1117 if int_op
== MicrOp
.OP_MTCRF
.value
:
1124 def get_spr_msb(self
):
1125 dec_insn
= yield self
.dec2
.e
.do
.insn
1126 return dec_insn
& (1 << 20) != 0 # sigh - XFF.spr[-1]?
1128 def call(self
, name
):
1129 """call(opcode) - the primary execution point for instructions
1131 name
= name
.strip() # remove spaces if not already done so
1133 print("halted - not executing", name
)
1136 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
1137 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
1138 asmop
= yield from self
.get_assembly_name()
1139 print("call", name
, asmop
)
1142 int_op
= yield self
.dec2
.dec
.op
.internal_op
1143 spr_msb
= yield from self
.get_spr_msb()
1145 instr_is_privileged
= False
1146 if int_op
in [MicrOp
.OP_ATTN
.value
,
1147 MicrOp
.OP_MFMSR
.value
,
1148 MicrOp
.OP_MTMSR
.value
,
1149 MicrOp
.OP_MTMSRD
.value
,
1151 MicrOp
.OP_RFID
.value
]:
1152 instr_is_privileged
= True
1153 if int_op
in [MicrOp
.OP_MFSPR
.value
,
1154 MicrOp
.OP_MTSPR
.value
] and spr_msb
:
1155 instr_is_privileged
= True
1157 print("is priv", instr_is_privileged
, hex(self
.msr
.value
),
1159 # check MSR priv bit and whether op is privileged: if so, throw trap
1160 if instr_is_privileged
and self
.msr
[MSRb
.PR
] == 1:
1161 self
.TRAP(0x700, PIb
.PRIV
)
1162 self
.namespace
['NIA'] = self
.trap_nia
1163 self
.pc
.update(self
.namespace
, self
.is_svp64_mode
)
1166 # check halted condition
1171 # check illegal instruction
1173 if name
not in ['mtcrf', 'mtocrf']:
1174 illegal
= name
!= asmop
1177 print("illegal", name
, asmop
)
1178 self
.TRAP(0x700, PIb
.ILLEG
)
1179 self
.namespace
['NIA'] = self
.trap_nia
1180 self
.pc
.update(self
.namespace
, self
.is_svp64_mode
)
1181 print("name %s != %s - calling ILLEGAL trap, PC: %x" %
1182 (name
, asmop
, self
.pc
.CIA
.value
))
1185 info
= self
.instrs
[name
]
1186 yield from self
.prep_namespace(info
.form
, info
.op_fields
)
1188 # preserve order of register names
1189 input_names
= create_args(list(info
.read_regs
) +
1190 list(info
.uninit_regs
))
1193 # get SVP64 entry for the current instruction
1194 sv_rm
= self
.svp64rm
.instrs
.get(name
)
1195 if sv_rm
is not None:
1196 dest_cr
, src_cr
, src_byname
, dest_byname
= decode_extra(sv_rm
)
1198 dest_cr
, src_cr
, src_byname
, dest_byname
= False, False, {}, {}
1199 print ("sv rm", sv_rm
, dest_cr
, src_cr
, src_byname
, dest_byname
)
1201 # get SVSTATE srcstep. TODO: dststep (twin predication)
1202 srcstep
= self
.svstate
.srcstep
.asint(msb0
=True)
1203 vl
= self
.svstate
.vl
.asint(msb0
=True)
1204 mvl
= self
.svstate
.maxvl
.asint(msb0
=True)
1206 # VL=0 in SVP64 mode means "do nothing: skip instruction"
1207 if self
.is_svp64_mode
and vl
== 0:
1208 self
.pc
.update(self
.namespace
, self
.is_svp64_mode
)
1209 print("end of call", self
.namespace
['CIA'], self
.namespace
['NIA'])
1212 # main input registers (RT, RA ...)
1214 for name
in input_names
:
1215 # using PowerDecoder2, first, find the decoder index.
1216 # (mapping name RA RB RC RS to in1, in2, in3)
1217 regnum
, is_vec
= yield from get_pdecode_idx_in(self
.dec2
, name
)
1219 # doing this is not part of svp64, it's because output
1220 # registers, to be modified, need to be in the namespace.
1221 regnum
, is_vec
= yield from get_pdecode_idx_out(self
.dec2
, name
)
1222 # here's where we go "vector". TODO: zero-testing (RA_IS_ZERO)
1223 # XXX already done by PowerDecoder2, now
1225 # regnum += srcstep # TODO, elwidth overrides
1227 # in case getting the register number is needed, _RA, _RB
1228 regname
= "_" + name
1229 self
.namespace
[regname
] = regnum
1230 print('reading reg %s %d' % (name
, regnum
), is_vec
)
1231 reg_val
= self
.gpr(regnum
)
1232 inputs
.append(reg_val
)
1234 # "special" registers
1235 for special
in info
.special_regs
:
1236 if special
in special_sprs
:
1237 inputs
.append(self
.spr
[special
])
1239 inputs
.append(self
.namespace
[special
])
1241 # clear trap (trap) NIA
1242 self
.trap_nia
= None
1244 print("inputs", inputs
)
1245 results
= info
.func(self
, *inputs
)
1246 print("results", results
)
1248 # "inject" decorator takes namespace from function locals: we need to
1249 # overwrite NIA being overwritten (sigh)
1250 if self
.trap_nia
is not None:
1251 self
.namespace
['NIA'] = self
.trap_nia
1253 print("after func", self
.namespace
['CIA'], self
.namespace
['NIA'])
1255 # detect if CA/CA32 already in outputs (sra*, basically)
1258 output_names
= create_args(info
.write_regs
)
1259 for name
in output_names
:
1265 print("carry already done?", bin(already_done
))
1266 if hasattr(self
.dec2
.e
.do
, "output_carry"):
1267 carry_en
= yield self
.dec2
.e
.do
.output_carry
1271 yield from self
.handle_carry_(inputs
, results
, already_done
)
1273 # detect if overflow was in return result
1276 for name
, output
in zip(output_names
, results
):
1277 if name
== 'overflow':
1280 if hasattr(self
.dec2
.e
.do
, "oe"):
1281 ov_en
= yield self
.dec2
.e
.do
.oe
.oe
1282 ov_ok
= yield self
.dec2
.e
.do
.oe
.ok
1286 print("internal overflow", overflow
, ov_en
, ov_ok
)
1288 yield from self
.handle_overflow(inputs
, results
, overflow
)
1290 if hasattr(self
.dec2
.e
.do
, "rc"):
1291 rc_en
= yield self
.dec2
.e
.do
.rc
.rc
1295 regnum
, is_vec
= yield from get_pdecode_cr_out(self
.dec2
, "CR0")
1296 self
.handle_comparison(results
, regnum
)
1298 # any modified return results?
1300 for name
, output
in zip(output_names
, results
):
1301 if name
== 'overflow': # ignore, done already (above)
1303 if isinstance(output
, int):
1304 output
= SelectableInt(output
, 256)
1305 if name
in ['CA', 'CA32']:
1307 print("writing %s to XER" % name
, output
)
1308 self
.spr
['XER'][XER_bits
[name
]] = output
.value
1310 print("NOT writing %s to XER" % name
, output
)
1311 elif name
in info
.special_regs
:
1312 print('writing special %s' % name
, output
, special_sprs
)
1313 if name
in special_sprs
:
1314 self
.spr
[name
] = output
1316 self
.namespace
[name
].eq(output
)
1318 print('msr written', hex(self
.msr
.value
))
1320 regnum
, is_vec
= yield from get_pdecode_idx_out(self
.dec2
,
1323 # temporary hack for not having 2nd output
1324 regnum
= yield getattr(self
.decoder
, name
)
1326 print('writing reg %d %s' % (regnum
, str(output
)), is_vec
)
1327 if output
.bits
> 64:
1328 output
= SelectableInt(output
.value
, 64)
1329 self
.gpr
[regnum
] = output
1331 # check if it is the SVSTATE.src/dest step that needs incrementing
1332 # this is our Sub-Program-Counter loop from 0 to VL-1
1333 if self
.is_svp64_mode
:
1334 # XXX twin predication TODO
1335 vl
= self
.svstate
.vl
.asint(msb0
=True)
1336 mvl
= self
.svstate
.maxvl
.asint(msb0
=True)
1337 srcstep
= self
.svstate
.srcstep
.asint(msb0
=True)
1338 print (" svstate.vl", vl
)
1339 print (" svstate.mvl", mvl
)
1340 print (" svstate.srcstep", srcstep
)
1341 # check if srcstep needs incrementing by one, stop PC advancing
1342 # svp64 loop can end early if the dest is scalar
1343 svp64_dest_vector
= not (yield self
.dec2
.no_out_vec
)
1344 if svp64_dest_vector
and srcstep
!= vl
-1:
1345 self
.svstate
.srcstep
+= SelectableInt(1, 7)
1346 self
.pc
.NIA
.value
= self
.pc
.CIA
.value
1347 self
.namespace
['NIA'] = self
.pc
.NIA
1348 print("end of sub-pc call", self
.namespace
['CIA'],
1349 self
.namespace
['NIA'])
1350 return # DO NOT allow PC to update whilst Sub-PC loop running
1352 self
.svstate
.srcstep
[0:7] = 0
1353 print (" svstate.srcstep loop end (PC to update)")
1354 self
.pc
.update_nia(self
.is_svp64_mode
)
1355 self
.namespace
['NIA'] = self
.pc
.NIA
1357 # UPDATE program counter
1358 self
.pc
.update(self
.namespace
, self
.is_svp64_mode
)
1359 print("end of call", self
.namespace
['CIA'], self
.namespace
['NIA'])
1363 """Decorator factory.
1365 this decorator will "inject" variables into the function's namespace,
1366 from the *dictionary* in self.namespace. it therefore becomes possible
1367 to make it look like a whole stack of variables which would otherwise
1368 need "self." inserted in front of them (*and* for those variables to be
1369 added to the instance) "appear" in the function.
1371 "self.namespace['SI']" for example becomes accessible as just "SI" but
1372 *only* inside the function, when decorated.
1374 def variable_injector(func
):
1376 def decorator(*args
, **kwargs
):
1378 func_globals
= func
.__globals
__ # Python 2.6+
1379 except AttributeError:
1380 func_globals
= func
.func_globals
# Earlier versions.
1382 context
= args
[0].namespace
# variables to be injected
1383 saved_values
= func_globals
.copy() # Shallow copy of dict.
1384 func_globals
.update(context
)
1385 result
= func(*args
, **kwargs
)
1386 print("globals after", func_globals
['CIA'], func_globals
['NIA'])
1387 print("args[0]", args
[0].namespace
['CIA'],
1388 args
[0].namespace
['NIA'])
1389 args
[0].namespace
= func_globals
1390 #exec (func.__code__, func_globals)
1393 # func_globals = saved_values # Undo changes.
1399 return variable_injector