(no commit message)
[libreriscv.git] / openpower / sv / rfc / ls010.mdwn
1 # RFC ls010 SVP64 Zero-Overhead Loop Prefix Subsystem
2
3 Credits and acknowledgements:
4
5 * Luke Leighton
6 * Jacob Lifshay
7 * Hendrik Boom
8 * Richard Wilbur
9 * Alexandre Oliva
10 * Cesar Strauss
11 * NLnet Foundation, for funding
12 * OpenPOWER Foundation
13 * Paul Mackerras
14 * Toshaan Bharvani
15 * IBM for the Power ISA itself
16
17 Links:
18
19 * <https://bugs.libre-soc.org/show_bug.cgi?id=1045>
20
21 # Introduction
22
23 Simple-V is a type of Vectorisation best described as a "Prefix Loop
24 Subsystem" similar to the 5 decades-old Zilog Z80 `LDIR` instruction and to the 8086 `REP`
25 Prefix instruction. More advanced features are similar to the Z80
26 `CPIR` instruction. If viewed one-dimensionally as an actual Vector ISA it introduces
27 over 1.5 million 64-bit Vector instructions. SVP64, the instruction
28 format, is therefore best viewed as an orthogonal RISC-paradigm "Prefixing"
29 subsystem instead.
30
31 Except where explicitly stated all bit numbers remain as in the rest of
32 the Power ISA: in MSB0 form (the bits are numbered from 0 at the MSB on
33 the left and counting up as you move rightwards to the LSB end). All bit
34 ranges are inclusive (so `4:6` means bits 4, 5, and 6, in MSB0 order).
35 **All register numbering and element numbering however is LSB0 ordering**
36 which is a different convention from that used elsewhere in the Power ISA.
37
38 The SVP64 prefix always comes before the suffix in PC order and must be
39 considered an independent "Defined word" that augments the behaviour of
40 the following instruction, but does **not** change the actual Decoding
41 of that following instruction. **All prefixed instructions retain their
42 non-prefixed encoding and definition**.
43
44 Two apparent exceptions to the above hard rule exist: SV Branch-Conditional
45 operations and LD/ST-update "Post-Increment" Mode. Post-Increment
46 was considered sufficiently high priority (significantly reducing hot-loop
47 instruction count) that one bit in the Prefix is reserved for it.
48 Vectorised Branch-Conditional operations "embed" the original Scalar
49 Branch-Conditional behaviour into a much more advanced variant that
50 is highly suited to High-Performance Computation (HPC), Supercomputing,
51 and parallel GPU Workloads.
52
53 *Architectural Resource Allocation note: it is prohibited to accept RFCs
54 which fundamentally violate this hard requirement. Under no circumstances
55 must the Suffix space have an alternate instruction encoding allocated
56 within SVP64 that is entirely different from the non-prefixed Defined
57 Word. Hardware Implementors critically rely on this inviolate guarantee
58 to implement High-Performance Multi-Issue micro-architectures that can
59 sustain 100% throughput*
60
61 Subset implementations in hardware are permitted, as long as certain
62 rules are followed, allowing for full soft-emulation including future
63 revisions. Compliancy Subsets exist to ensure minimum levels of binary
64 interoperability expectations within certain environments.
65
66 ## SVP64 encoding features
67
68 A number of features need to be compacted into a very small space of
69 only 24 bits:
70
71 * Independent per-register Scalar/Vector tagging and range extension on
72 every register
73 * Element width overrides on both source and destination
74 * Predication on both source and destination
75 * Two different sources of predication: INT and CR Fields
76 * SV Modes including saturation (for Audio, Video and DSP), mapreduce,
77 fail-first and predicate-result mode.
78
79 Different classes of operations require different formats. The earlier
80 sections cover the common formats and the four separate modes follow:
81 CR operations (crops), Arithmetic/Logical (termed "normal"), Load/Store
82 and Branch-Conditional.
83
84 ## Definition of Reserved in this spec.
85
86 For the new fields added in SVP64, instructions that have any of their
87 fields set to a reserved value must cause an illegal instruction trap,
88 to allow emulation of future instruction sets, or for subsets of SVP64 to
89 be implemented in hardware and the rest emulated. This includes SVP64
90 SPRs: reading or writing values which are not supported in hardware
91 must also raise illegal instruction traps in order to allow emulation.
92 Unless otherwise stated, reserved values are always all zeros.
93
94 This is unlike OpenPower ISA v3.1, which in many instances does not
95 require a trap if reserved fields are nonzero. Where the standard Power
96 ISA definition is intended the red keyword `RESERVED` is used.
97
98 ## Definition of "UnVectoriseable"
99
100 Any operation that inherently makes no sense if repeated is termed
101 "UnVectoriseable" or "UnVectorised". Examples include `sc` or `sync`
102 which have no registers. `mtmsr` is also classed as UnVectoriseable
103 because there is only one `MSR`.
104
105 ## Register files, elements, and Element-width Overrides
106
107 In the Upper Compliancy Levels of SVP64 the size of the GPR and FPR Register
108 files are expanded from 32 to 128 entries, and the number of CR Fields
109 expanded from CR0-CR7 to CR0-CR127. (Note: A future version of SVP64 is anticipated
110 to extend the VSR register file).
111
112 Memory access remains exactly the same: the effects of `MSR.LE` remain
113 exactly the same, affecting as they already do and remain **only**
114 on the Load and Store memory-register operation byte-order, and having
115 nothing to do with the ordering of the contents of register files or
116 register-register operations.
117
118 To be absolutely clear:
119
120 ```
121 No conceptual arithmetic ordering or other changes over the Scalar
122 Power ISA definitions to registers or register files or to arithmetic
123 or Logical Operations beyond element-width subdivision and sequential
124 element numbering are expressed or implied
125 ```
126
127 Element offset
128 numbering is naturally **LSB0-sequentially-incrementing from zero, not
129 MSB0-incrementing** including when element-width overrides are used,
130 at which point the elements progress through each register
131 sequentially from the LSB end
132 (confusingly numbered the highest in MSB0 ordering) and progress
133 incrementally to the MSB end (confusingly numbered the lowest in
134 MSB0 ordering).
135
136 When exclusively using MSB0-numbering, SVP64
137 becomes unnecessarily complex to both express and subsequently understand:
138 the required conditional subtractions from 63,
139 31, 15 and 7 unfortunately become a hostile minefield, obscuring both
140 intent and meaning. Therefore for the
141 purposes of this section the more natural **LSB0 numbering is assumed**
142 and it is left to the reader to translate to MSB0 numbering.
143
144 The Canonical specification for how element-sequential numbering and
145 element-width overrides is defined is expressed in the following c
146 structure, assuming a Little-Endian system, and naturally using LSB0
147 numbering everywhere because the ANSI c specification is inherently LSB0:
148
149 ```
150 #pragma pack
151 typedef union {
152 uint8_t b[]; // elwidth 8
153 uint16_t s[]; // elwidth 16
154 uint32_t i[]; // elwidth 32
155 uint64_t l[]; // elwidth 64
156 uint8_t actual_bytes[8];
157 } el_reg_t;
158
159 elreg_t int_regfile[128];
160
161 void get_register_element(el_reg_t* el, int gpr, int element, int width) {
162 switch (width) {
163 case 64: el->l = int_regfile[gpr].l[element];
164 case 32: el->i = int_regfile[gpr].i[element];
165 case 16: el->s = int_regfile[gpr].s[element];
166 case 8 : el->b = int_regfile[gpr].b[element];
167 }
168 }
169 void set_register_element(el_reg_t* el, int gpr, int element, int width) {
170 switch (width) {
171 case 64: int_regfile[gpr].l[element] = el->l;
172 case 32: int_regfile[gpr].i[element] = el->i;
173 case 16: int_regfile[gpr].s[element] = el->s;
174 case 8 : int_regfile[gpr].b[element] = el->b;
175 }
176 }
177 ```
178
179 Example Vector-looped add operation implementation when elwidths are 64-bit:
180
181 ```
182 # add RT, RA,RB using the "uint64_t" union member, "l"
183 for i in range(VL):
184 int_regfile[RT].l[i] = int_regfile[RA].l[i] + int_regfile[RB].l[i]
185 ```
186
187 However if elwidth overrides are set to 16 for both source and destination:
188
189 ```
190 # add RT, RA, RB using the "uint64_t" union member "s"
191 for i in range(VL):
192 int_regfile[RT].s[i] = int_regfile[RA].s[i] + int_regfile[RB].s[i]
193 ```
194
195 Hardware Architectural note: to avoid a Read-Modify-Write at the register
196 file it is strongly recommended to implement byte-level write-enable lines
197 exactly as has been implemented in DRAM ICs for many decades. Additionally
198 the predicate mask bit is advised to be associated with the element
199 operation and alongside the result ultimately passed to the register file.
200 When element-width is set to 64-bit the relevant predicate mask bit
201 may be repeated eight times and pull all eight write-port byte-level
202 lines HIGH. Clearly when element-width is set to 8-bit the relevant
203 predicate mask bit corresponds directly with one single byte-level
204 write-enable line. It is up to the Hardware Architect to then amortise
205 (merge) elements together into both PredicatedSIMD Pipelines as well
206 as simultaneous non-overlapping Register File writes, to achieve High
207 Performance designs.
208
209 ## Scalar Identity Behaviour
210
211 SVP64 is designed so that when the prefix is all zeros, and
212 VL=1, no effect or
213 influence occurs (no augmentation) such that all standard Power ISA
214 v3.0/v3 1 instructions covered by the prefix are "unaltered". This
215 is termed `scalar identity behaviour` (based on the mathematical
216 definition for "identity", as in, "identity matrix" or better "identity
217 transformation").
218
219 Note that this is completely different from when VL=0. VL=0 turns all
220 operations under its influence into `nops` (regardless of the prefix)
221 whereas when VL=1 and the SV prefix is all zeros, the operation simply
222 acts as if SV had not been applied at all to the instruction (an
223 "identity transformation").
224
225 The fact that `VL` is dynamic and can be set to any value at runtime based
226 on program conditions and behaviour means very specifically that
227 `scalar identity behaviour` is **not** a redundant encoding. If the
228 only means by which VL could be set was by way of static-compiled
229 immediates then this assertion would be false. VL should not
230 be confused with MAXVL when understanding this key aspect of SimpleV.
231
232 ## Register Naming and size
233
234 As indicated above SV Registers are simply the GPR, FPR and CR
235 register files extended linearly to larger sizes; SV Vectorisation
236 iterates sequentially through these registers (LSB0 sequential ordering
237 from 0 to VL-1).
238
239 Where the integer regfile in standard scalar Power ISA v3.0B/v3.1B is
240 r0 to r31, SV extends this as r0 to r127. Likewise FP registers are
241 extended to 128 (fp0 to fp127), and CR Fields are extended to 128 entries,
242 CR0 thru CR127.
243
244 The names of the registers therefore reflects a simple linear extension
245 of the Power ISA v3.0B / v3.1B register naming, and in hardware this
246 would be reflected by a linear increase in the size of the underlying
247 SRAM used for the regfiles.
248
249 Note: when an EXTRA field (defined below) is zero, SV is deliberately
250 designed so that the register fields are identical to as if SV was not in
251 effect i.e. under these circumstances (EXTRA=0) the register field names
252 RA, RB etc. are interpreted and treated as v3.0B / v3.1B scalar registers.
253 This is part of `scalar identity behaviour` described above.
254
255 ## Future expansion.
256
257 With the way that EXTRA fields are defined and applied to register fields,
258 future versions of SV may involve 256 or greater registers. Backwards
259 binary compatibility may be achieved with a PCR bit (Program Compatibility
260 Register). Further discussion is out of scope for this version of SVP64.
261
262 Additionally, a future variant of SVP64 will be applied to the Scalar
263 (Quad-precision and 128-bit) VSX instructions. Element-width overrides
264 are an opportunity to expand the Power ISA to 256-bit, 512-bit and
265 1024-bit operations.
266
267 --------
268
269 \newpage{}
270
271 # New 64-bit Instruction Encoding spaces
272
273 The following seven new areas are defined within Primary Opcode 9 (EXT009) as a
274 new 64-bit encoding space, alongside EXT1xx.
275
276 | 0-5 | 6 | 7 | 8-31 | 32| Description |
277 |-----|---|---|-------|---|------------------------------------|
278 | PO | 0 | x | xxxx | 0 | EXT200-231 or `RESERVED2` (56-bit) |
279 | PO | 0 | 0 | !zero | 1 | SVP64Single:EXT232-263, or `RESERVED3` |
280 | PO | 0 | 0 | 0000 | 1 | Scalar EXT232-263 |
281 | PO | 0 | 1 | nnnn | 1 | SVP64:EXT232-263 |
282 | PO | 1 | 0 | 0000 | x | EXT300-363 or `RESERVED1` (32-bit) |
283 | PO | 1 | 0 | !zero | n | SVP64Single:EXT000-063 or `RESERVED4` |
284 | PO | 1 | 1 | nnnn | n | SVP64:EXT000-063 |
285
286 Note that for the future SVP64Single Encoding (currently RESERVED) it
287 is prohibited to have bits 8-31 be zero, unlike for SVP64 Vector space,
288 for which bits 8-31
289 can be zero (termed `scalar identity behaviour`). This
290 prohibition allows SVP64Single to share its
291 Encoding space with Scalar Ext232-263 and Scalar EXT300-363.
292
293 *Architectural Resource Allocation Note: **under no circumstances** must
294 different Defined Words be allocated within any `EXT{z}` prefixed
295 or unprefixed space for a given value of `z`. Even if UnVectoriseable
296 an instruction Defined Word space must have the exact same Instruction
297 and exact same Instruction Encoding in all spaces (including
298 being RESERVED if UnVectoriseable) or not be allocated at all.
299 This is required as an inviolate hard rule governing Primary Opcode 9
300 that may not be revoked under any circumstances. A useful way to think
301 of this is that the Prefix Encoding is, like the 8086 REP instruction,
302 an independent 32-bit Defined Word.*
303
304 Ecoding spaces and their potential are illustrated:
305
306 | Encoding | Available bits | Scalar | Vectoriseable | SVP64Single |
307 |----------|----------------|--------|---------------|--------------|
308 |EXT000-063| 32 | yes | yes |yes |
309 |EXT100-163| 64 | yes | no |no |
310 |EXT200-231| 56 | N/A |not applicable |not applicable|
311 |EXT232-263| 32 | yes | yes |yes |
312 |EXT300-363| 32 | yes | no |no |
313
314 Prefixed-Prefixed (96-bit) instructions are prohibited. EXT200-231 presently
315 remains unallocated (RESERVED) and therefore its potential is not yet defined
316 (Not Applicable). Additional Sandbox Opcodes are defined as EXT254 and EXT322,
317 alongside EXT022.
318
319 # Remapped Encoding (`RM[0:23]`)
320
321 In the SVP64 Vector Prefix spaces, the 24 bits 8-31 are termed `RM`. Bits 32-37 are
322 the Primary Opcode of the Suffix "Defined Word". 38-63 are the remainder of the
323 Defined Word. Note that the new EXT232-263 SVP64 area it is obviously mandatory
324 that bit 32 is required to be set to 1.
325
326 | 0-5 | 6 | 7 | 8-31 | 32-37 | 38-64 |Description |
327 |-----|---|---|----------|--------|----------|-----------------------|
328 | PO | 0 | 1 | RM[0:23] | 1nnnnn | xxxxxxxx | SVP64:EXT232-263 |
329 | PO | 1 | 1 | RM[0:23] | nnnnnn | xxxxxxxx | SVP64:EXT000-063 |
330
331 It is important to note that unlike v3.1 64-bit prefixed instructions
332 there is insufficient space in `RM` to provide identification of any SVP64
333 Fields without first partially decoding the 32-bit suffix. Similar to
334 the "Forms" (X-Form, D-Form) the `RM` format is individually associated
335 with every instruction. However this still does not adversely affect Multi-Issue
336 Decoding because the identification of the *length* of anything in the
337 64-bit space has been kept brutally simple (EXT009), and further decoding
338 of any number of 64-bit Encodings in parallel at that point is fully independent.
339
340 Extreme caution and care must be taken when extending SVP64
341 in future, to not create unnecessary relationships between prefix and
342 suffix that could complicate decoding, adding latency.
343
344 ## Common RM fields
345
346 The following fields are common to all Remapped Encodings:
347
348 | Field Name | Field bits | Description |
349 |------------|------------|----------------------------------------|
350 | MASKMODE | `0` | Execution (predication) Mask Kind |
351 | MASK | `1:3` | Execution Mask |
352 | SUBVL | `8:9` | Sub-vector length |
353
354 The following fields are optional or encoded differently depending
355 on context after decoding of the Scalar suffix:
356
357 | Field Name | Field bits | Description |
358 |------------|------------|----------------------------------------|
359 | ELWIDTH | `4:5` | Element Width |
360 | ELWIDTH_SRC | `6:7` | Element Width for Source |
361 | EXTRA | `10:18` | Register Extra encoding |
362 | MODE | `19:23` | changes Vector behaviour |
363
364 * MODE changes the behaviour of the SV operation (result saturation,
365 mapreduce)
366 * SUBVL groups elements together into vec2, vec3, vec4 for use in 3D
367 and Audio/Video DSP work
368 * ELWIDTH and ELWIDTH_SRC overrides the instruction's destination and
369 source operand width
370 * MASK (and MASK_SRC) and MASKMODE provide predication (two types of
371 sources: scalar INT and Vector CR).
372 * Bits 10 to 18 (EXTRA) are further decoded depending on the RM category
373 for the instruction, which is determined only by decoding the Scalar 32
374 bit suffix.
375
376 Similar to Power ISA `X-Form` etc. EXTRA bits are given designations,
377 such as `RM-1P-3S1D` which indicates for this example that the operation
378 is to be single-predicated and that there are 3 source operand EXTRA
379 tags and one destination operand tag.
380
381 Note that if ELWIDTH != ELWIDTH_SRC this may result in reduced performance
382 or increased latency in some implementations due to lane-crossing.
383
384 ## Mode
385
386 Mode is an augmentation of SV behaviour. Different types of instructions
387 have different needs, similar to Power ISA v3.1 64 bit prefix 8LS and MTRR
388 formats apply to different instruction types. Modes include Reduction,
389 Iteration, arithmetic saturation, and Fail-First. More specific details
390 in each section and in the SVP64 appendix
391
392 * For condition register operations see [[sv/cr_ops]]
393 * For LD/ST Modes, see [[sv/ldst]].
394 * For Branch modes, see [[sv/branches]]
395 * For arithmetic and logical, see [[sv/normal]]
396
397 ## ELWIDTH Encoding
398
399 Default behaviour is set to 0b00 so that zeros follow the convention
400 of `scalar identity behaviour`. In this case it means that elwidth
401 overrides are not applicable. Thus if a 32 bit instruction operates
402 on 32 bit, `elwidth=0b00` specifies that this behaviour is unmodified.
403 Likewise when a processor is switched from 64 bit to 32 bit mode,
404 `elwidth=0b00` states that, again, the behaviour is not to be modified.
405
406 Only when elwidth is nonzero is the element width overridden to the
407 explicitly required value.
408
409 ### Elwidth for Integers:
410
411 | Value | Mnemonic | Description |
412 |-------|----------------|------------------------------------|
413 | 00 | DEFAULT | default behaviour for operation |
414 | 01 | `ELWIDTH=w` | Word: 32-bit integer |
415 | 10 | `ELWIDTH=h` | Halfword: 16-bit integer |
416 | 11 | `ELWIDTH=b` | Byte: 8-bit integer |
417
418 This encoding is chosen such that the byte width may be computed as
419 `8<<(3-ew)`
420
421 ### Elwidth for FP Registers:
422
423 | Value | Mnemonic | Description |
424 |-------|----------------|------------------------------------|
425 | 00 | DEFAULT | default behaviour for FP operation |
426 | 01 | `ELWIDTH=f32` | 32-bit IEEE 754 Single floating-point |
427 | 10 | `ELWIDTH=f16` | 16-bit IEEE 754 Half floating-point |
428 | 11 | `ELWIDTH=bf16` | Reserved for `bf16` |
429
430 Note:
431 [`bf16`](https://en.wikipedia.org/wiki/Bfloat16_floating-point_format)
432 is reserved for a future implementation of SV
433
434 Note that any IEEE754 FP operation in Power ISA ending in "s" (`fadds`) shall
435 perform its operation at **half** the ELWIDTH then padded back out
436 to ELWIDTH. `sv.fadds/ew=f32` shall perform an IEEE754 FP16 operation that is then "padded" to fill out to an IEEE754 FP32. When ELWIDTH=DEFAULT
437 clearly the behaviour of `sv.fadds` is performed at 32-bit accuracy
438 then padded back out to fit in IEEE754 FP64, exactly as for Scalar
439 v3.0B "single" FP. Any FP operation ending in "s" where ELWIDTH=f16
440 or ELWIDTH=bf16 is reserved and must raise an illegal instruction
441 (IEEE754 FP8 or BF8 are not defined).
442
443 ### Elwidth for CRs (no meaning)
444
445 Element-width overrides for CR Fields has no meaning. The bits
446 are therefore used for other purposes, or when Rc=1, the Elwidth
447 applies to the result being tested (a GPR or FPR), but not to the
448 Vector of CR Fields.
449
450 ## SUBVL Encoding
451
452 The default for SUBVL is 1 and its encoding is 0b00 to indicate that
453 SUBVL is effectively disabled (a SUBVL for-loop of only one element). this
454 lines up in combination with all other "default is all zeros" behaviour.
455
456 | Value | Mnemonic | Subvec | Description |
457 |-------|-----------|---------|------------------------|
458 | 00 | `SUBVL=1` | single | Sub-vector length of 1 |
459 | 01 | `SUBVL=2` | vec2 | Sub-vector length of 2 |
460 | 10 | `SUBVL=3` | vec3 | Sub-vector length of 3 |
461 | 11 | `SUBVL=4` | vec4 | Sub-vector length of 4 |
462
463 The SUBVL encoding value may be thought of as an inclusive range of a
464 sub-vector. SUBVL=2 represents a vec2, its encoding is 0b01, therefore
465 this may be considered to be elements 0b00 to 0b01 inclusive.
466
467 ## MASK/MASK_SRC & MASKMODE Encoding
468
469 One bit (`MASKMODE`) indicates the mode: CR or Int predication. The two
470 types may not be mixed.
471
472 Special note: to disable predication this field must be set to zero in
473 combination with Integer Predication also being set to 0b000. this has the
474 effect of enabling "all 1s" in the predicate mask, which is equivalent to
475 "not having any predication at all" and consequently, in combination with
476 all other default zeros, fully disables SV (`scalar identity behaviour`).
477
478 `MASKMODE` may be set to one of 2 values:
479
480 | Value | Description |
481 |-----------|------------------------------------------------------|
482 | 0 | MASK/MASK_SRC are encoded using Integer Predication |
483 | 1 | MASK/MASK_SRC are encoded using CR-based Predication |
484
485 Integer Twin predication has a second set of 3 bits that uses the same
486 encoding thus allowing either the same register (r3, r10 or r31) to be
487 used for both src and dest, or different regs (one for src, one for dest).
488
489 Likewise CR based twin predication has a second set of 3 bits, allowing
490 a different test to be applied.
491
492 Note that it is assumed that Predicate Masks (whether INT or CR) are
493 read *before* the operations proceed. In practice (for CR Fields)
494 this creates an unnecessary block on parallelism. Therefore, it is up
495 to the programmer to ensure that the CR fields used as Predicate Masks
496 are not being written to by any parallel Vector Loop. Doing so results
497 in **UNDEFINED** behaviour, according to the definition outlined in the
498 Power ISA v3.0B Specification.
499
500 Hardware Implementations are therefore free and clear to delay reading
501 of individual CR fields until the actual predicated element operation
502 needs to take place, safe in the knowledge that no programmer will have
503 issued a Vector Instruction where previous elements could have overwritten
504 (destroyed) not-yet-executed CR-Predicated element operations.
505
506 ### Integer Predication (MASKMODE=0)
507
508 When the predicate mode bit is zero the 3 bits are interpreted as below.
509 Twin predication has an identical 3 bit field similarly encoded.
510
511 `MASK` and `MASK_SRC` may be set to one of 8 values, to provide the
512 following meaning:
513
514 | Value | Mnemonic | Element `i` enabled if: |
515 |-------|----------|------------------------------|
516 | 000 | ALWAYS | predicate effectively all 1s |
517 | 001 | 1 << R3 | `i == R3` |
518 | 010 | R3 | `R3 & (1 << i)` is non-zero |
519 | 011 | ~R3 | `R3 & (1 << i)` is zero |
520 | 100 | R10 | `R10 & (1 << i)` is non-zero |
521 | 101 | ~R10 | `R10 & (1 << i)` is zero |
522 | 110 | R30 | `R30 & (1 << i)` is non-zero |
523 | 111 | ~R30 | `R30 & (1 << i)` is zero |
524
525 r10 and r30 are at the high end of temporary and unused registers,
526 so as not to interfere with register allocation from ABIs.
527
528 ### CR-based Predication (MASKMODE=1)
529
530 When the predicate mode bit is one the 3 bits are interpreted as below.
531 Twin predication has an identical 3 bit field similarly encoded.
532
533 `MASK` and `MASK_SRC` may be set to one of 8 values, to provide the
534 following meaning:
535
536 | Value | Mnemonic | Element `i` is enabled if |
537 |-------|----------|--------------------------|
538 | 000 | lt | `CR[offs+i].LT` is set |
539 | 001 | nl/ge | `CR[offs+i].LT` is clear |
540 | 010 | gt | `CR[offs+i].GT` is set |
541 | 011 | ng/le | `CR[offs+i].GT` is clear |
542 | 100 | eq | `CR[offs+i].EQ` is set |
543 | 101 | ne | `CR[offs+i].EQ` is clear |
544 | 110 | so/un | `CR[offs+i].FU` is set |
545 | 111 | ns/nu | `CR[offs+i].FU` is clear |
546
547 `offs` is defined as CR32 (4x8) so as to mesh cleanly with Vectorised
548 Rc=1 operations (see below). Rc=1 operations start from CR8 (TBD).
549
550 The CR Predicates chosen must start on a boundary that Vectorised CR
551 operations can access cleanly, in full. With EXTRA2 restricting starting
552 points to multiples of 8 (CR0, CR8, CR16...) both Vectorised Rc=1 and
553 CR Predicate Masks have to be adapted to fit on these boundaries as well.
554
555 ## Extra Remapped Encoding <a name="extra_remap"> </a>
556
557 Shows all instruction-specific fields in the Remapped Encoding
558 `RM[10:18]` for all instruction variants. Note that due to the very
559 tight space, the encoding mode is *not* included in the prefix itself.
560 The mode is "applied", similar to Power ISA "Forms" (X-Form, D-Form)
561 on a per-instruction basis, and, like "Forms" are given a designation
562 (below) of the form `RM-nP-nSnD`. The full list of which instructions
563 use which remaps is here [[opcode_regs_deduped]].
564
565 **Please note the following**:
566
567 ```
568 Machine-readable CSV files have been provided which will make the task
569 of creating SV-aware ISA decoders, documentation, assembler tools
570 compiler tools Simulators documentation all aspects of SVP64 easier
571 and less prone to mistakes. Please avoid manual re-creation of
572 information from the written specification wording, and use the
573 CSV files or use the Canonical tool which creates the CSV files,
574 named sv_analysis.py. The information contained within sv_analysis.py
575 is considered to be part of this Specification, even encoded as it
576 is in python3.
577 ```
578
579 The mappings are part of the SVP64 Specification in exactly the same
580 way as X-Form, D-Form. New Scalar instructions added to the Power ISA
581 will need a corresponding SVP64 Mapping, which can be derived by-rote
582 from examining the Register "Profile" of the instruction.
583
584 There are two categories: Single and Twin Predication. Due to space
585 considerations further subdivision of Single Predication is based on
586 whether the number of src operands is 2 or 3. With only 9 bits available
587 some compromises have to be made.
588
589 * `RM-1P-3S1D` Single Predication dest/src1/2/3, applies to 4-operand
590 instructions (fmadd, isel, madd).
591 * `RM-1P-2S1D` Single Predication dest/src1/2 applies to 3-operand
592 instructions (src1 src2 dest)
593 * `RM-2P-1S1D` Twin Predication (src=1, dest=1)
594 * `RM-2P-2S1D` Twin Predication (src=2, dest=1) primarily for LDST (Indexed)
595 * `RM-2P-1S2D` Twin Predication (src=1, dest=2) primarily for LDST Update
596
597 ### RM-1P-3S1D
598
599 | Field Name | Field bits | Description |
600 |------------|------------|----------------------------------------|
601 | Rdest\_EXTRA2 | `10:11` | extends Rdest (R\*\_EXTRA2 Encoding) |
602 | Rsrc1\_EXTRA2 | `12:13` | extends Rsrc1 (R\*\_EXTRA2 Encoding) |
603 | Rsrc2\_EXTRA2 | `14:15` | extends Rsrc2 (R\*\_EXTRA2 Encoding) |
604 | Rsrc3\_EXTRA2 | `16:17` | extends Rsrc3 (R\*\_EXTRA2 Encoding) |
605 | EXTRA2_MODE | `18` | used by `divmod2du` and `maddedu` for RS |
606
607 These are for 3 operand in and either 1 or 2 out instructions.
608 3-in 1-out includes `madd RT,RA,RB,RC`. (DRAFT) instructions
609 such as `maddedu` have an implicit second destination, RS, the
610 selection of which is determined by bit 18.
611
612 ### RM-1P-2S1D
613
614 | Field Name | Field bits | Description |
615 |------------|------------|-------------------------------------------|
616 | Rdest\_EXTRA3 | `10:12` | extends Rdest |
617 | Rsrc1\_EXTRA3 | `13:15` | extends Rsrc1 |
618 | Rsrc2\_EXTRA3 | `16:18` | extends Rsrc3 |
619
620 These are for 2 operand 1 dest instructions, such as `add RT, RA,
621 RB`. However also included are unusual instructions with an implicit
622 dest that is identical to its src reg, such as `rlwinmi`.
623
624 Normally, with instructions such as `rlwinmi`, the scalar v3.0B ISA would
625 not have sufficient bit fields to allow an alternative destination.
626 With SV however this becomes possible. Therefore, the fact that the
627 dest is implicitly also a src should not mislead: due to the *prefix*
628 they are different SV regs.
629
630 * `rlwimi RA, RS, ...`
631 * Rsrc1_EXTRA3 applies to RS as the first src
632 * Rsrc2_EXTRA3 applies to RA as the secomd src
633 * Rdest_EXTRA3 applies to RA to create an **independent** dest.
634
635 With the addition of the EXTRA bits, the three registers
636 each may be *independently* made vector or scalar, and be independently
637 augmented to 7 bits in length.
638
639 ### RM-2P-1S1D/2S
640
641 | Field Name | Field bits | Description |
642 |------------|------------|----------------------------|
643 | Rdest_EXTRA3 | `10:12` | extends Rdest |
644 | Rsrc1_EXTRA3 | `13:15` | extends Rsrc1 |
645 | MASK_SRC | `16:18` | Execution Mask for Source |
646
647 `RM-2P-2S` is for `stw` etc. and is Rsrc1 Rsrc2.
648
649 ### RM-1P-2S1D
650
651 single-predicate, three registers (2 read, 1 write)
652
653 | Field Name | Field bits | Description |
654 |------------|------------|----------------------------|
655 | Rdest_EXTRA3 | `10:12` | extends Rdest |
656 | Rsrc1_EXTRA3 | `13:15` | extends Rsrc1 |
657 | Rsrc2_EXTRA3 | `16:18` | extends Rsrc2 |
658
659 ### RM-2P-2S1D/1S2D/3S
660
661 The primary purpose for this encoding is for Twin Predication on LOAD
662 and STORE operations. see [[sv/ldst]] for detailed anslysis.
663
664 **RM-2P-2S1D:**
665
666 | Field Name | Field bits | Description |
667 |------------|------------|----------------------------|
668 | Rdest_EXTRA2 | `10:11` | extends Rdest (R\*\_EXTRA2 Encoding) |
669 | Rsrc1_EXTRA2 | `12:13` | extends Rsrc1 (R\*\_EXTRA2 Encoding) |
670 | Rsrc2_EXTRA2 | `14:15` | extends Rsrc2 (R\*\_EXTRA2 Encoding) |
671 | MASK_SRC | `16:18` | Execution Mask for Source |
672
673 **RM-2P-1S2D:**
674
675 For RM-2P-1S2D the EXTRA2 dest and src names are switched (Rsrc_EXTRA2
676 is in bits 10:11, Rdest1_EXTRA2 in 12:13)
677
678 | Field Name | Field bits | Description |
679 |------------|------------|----------------------------|
680 | Rsrc2_EXTRA2 | `10:11` | extends Rsrc2 (R\*\_EXTRA2 Encoding) |
681 | Rsrc1_EXTRA2 | `12:13` | extends Rsrc1 (R\*\_EXTRA2 Encoding) |
682 | Rdest_EXTRA2 | `14:15` | extends Rdest (R\*\_EXTRA2 Encoding) |
683 | MASK_SRC | `16:18` | Execution Mask for Source |
684
685 **RM-2P-3S:**
686
687 Also that for RM-2P-3S (to cover `stdx` etc.) the names are switched to 3 src:
688 Rsrc1_EXTRA2, Rsrc2_EXTRA2, Rsrc3_EXTRA2.
689
690 | Field Name | Field bits | Description |
691 |------------|------------|----------------------------|
692 | Rsrc1_EXTRA2 | `10:11` | extends Rsrc1 (R\*\_EXTRA2 Encoding) |
693 | Rsrc2_EXTRA2 | `12:13` | extends Rsrc2 (R\*\_EXTRA2 Encoding) |
694 | Rsrc3_EXTRA2 | `14:15` | extends Rsrc3 (R\*\_EXTRA2 Encoding) |
695 | MASK_SRC | `16:18` | Execution Mask for Source |
696
697 Note also that LD with update indexed, which takes 2 src and
698 creates 2 dest registers (e.g. `lhaux RT,RA,RB`), does not have room
699 for 4 registers and also Twin Predication. Therefore these are treated as
700 RM-2P-2S1D and the src spec for RA is also used for the same RA as a dest.
701
702 Note that if ELWIDTH != ELWIDTH_SRC this may result in reduced performance
703 or increased latency in some implementations due to lane-crossing.
704
705 ## R\*\_EXTRA2/3
706
707 EXTRA is the means by which two things are achieved:
708
709 1. Registers are marked as either Vector *or Scalar*
710 2. Register field numbers (limited typically to 5 bit)
711 are extended in range, both for Scalar and Vector.
712
713 The register files are therefore extended:
714
715 * INT (GPR) is extended from r0-31 to r0-127
716 * FP (FPR) is extended from fp0-32 to fp0-fp127
717 * CR Fields are extended from CR0-7 to CR0-127
718
719 However due to pressure in `RM.EXTRA` not all these registers
720 are accessible by all instructions, particularly those with
721 a large number of operands (`madd`, `isel`).
722
723 In the following tables register numbers are constructed from the
724 standard v3.0B / v3.1B 32 bit register field (RA, FRA) and the EXTRA2 or
725 EXTRA3 field from the SV Prefix, determined by the specific RM-xx-yyyy
726 designation for a given instruction. The prefixing is arranged so that
727 interoperability between prefixing and nonprefixing of scalar registers
728 is direct and convenient (when the EXTRA field is all zeros).
729
730 A pseudocode algorithm explains the relationship, for INT/FP (see
731 SVP64 appendix for CRs)
732
733 ```
734 if extra3_mode:
735 spec = EXTRA3
736 else:
737 spec = EXTRA2 << 1 # same as EXTRA3, shifted
738 if spec[0]: # vector
739 return (RA << 2) | spec[1:2]
740 else: # scalar
741 return (spec[1:2] << 5) | RA
742 ```
743
744 Future versions may extend to 256 by shifting Vector numbering up.
745 Scalar will not be altered.
746
747 Note that in some cases the range of starting points for Vectors
748 is limited.
749
750 ### INT/FP EXTRA3
751
752 If EXTRA3 is zero, maps to "scalar identity" (scalar Power ISA field
753 naming).
754
755 Fields are as follows:
756
757 * Value: R_EXTRA3
758 * Mode: register is tagged as scalar or vector
759 * Range/Inc: the range of registers accessible from this EXTRA
760 encoding, and the "increment" (accessibility). "/4" means
761 that this EXTRA encoding may only give access (starting point)
762 every 4th register.
763 * MSB..LSB: the bit field showing how the register opcode field
764 combines with EXTRA to give (extend) the register number (GPR)
765
766 | Value | Mode | Range/Inc | 6..0 |
767 |-----------|-------|---------------|---------------------|
768 | 000 | Scalar | `r0-r31`/1 | `0b00 RA` |
769 | 001 | Scalar | `r32-r63`/1 | `0b01 RA` |
770 | 010 | Scalar | `r64-r95`/1 | `0b10 RA` |
771 | 011 | Scalar | `r96-r127`/1 | `0b11 RA` |
772 | 100 | Vector | `r0-r124`/4 | `RA 0b00` |
773 | 101 | Vector | `r1-r125`/4 | `RA 0b01` |
774 | 110 | Vector | `r2-r126`/4 | `RA 0b10` |
775 | 111 | Vector | `r3-r127`/4 | `RA 0b11` |
776
777 ### INT/FP EXTRA2
778
779 If EXTRA2 is zero will map to
780 "scalar identity behaviour" i.e Scalar Power ISA register naming:
781
782 | Value | Mode | Range/inc | 6..0 |
783 |----------|-------|---------------|-----------|
784 | 00 | Scalar | `r0-r31`/1 | `0b00 RA` |
785 | 01 | Scalar | `r32-r63`/1 | `0b01 RA` |
786 | 10 | Vector | `r0-r124`/4 | `RA 0b00` |
787 | 11 | Vector | `r2-r126`/4 | `RA 0b10` |
788
789 **Note that unlike in EXTRA3, in EXTRA2**:
790
791 * the GPR Vectors may only start from
792 `r0, r2, r4, r6, r8` and likewise FPR Vectors.
793 * the GPR Scalars may only go from `r0, r1, r2.. r63` and likewise FPR Scalars.
794
795 as there is insufficient bits to cover the full range.
796
797 ### CR Field EXTRA3
798
799 CR Field encoding is essentially the same but made more complex due to CRs
800 being bit-based, because the application of SVP64 element-numbering applies
801 to the CR *Field* numbering not the CR register *bit* numbering.
802 Note that Vectors may only start from `CR0, CR4, CR8, CR12, CR16, CR20`...
803 and Scalars may only go from `CR0, CR1, ... CR31`
804
805 Encoding shown MSB down to LSB
806
807 For a 5-bit operand (BA, BB, BT):
808
809 | Value | Mode | Range/Inc | 8..5 | 4..2 | 1..0 |
810 |-------|------|---------------|-----------| --------|---------|
811 | 000 | Scalar | `CR0-CR7`/1 | 0b0000 | BA[0:2] | BA[3:4] |
812 | 001 | Scalar | `CR8-CR15`/1 | 0b0001 | BA[0:2] | BA[3:4] |
813 | 010 | Scalar | `CR16-CR23`/1 | 0b0010 | BA[0:2] | BA[3:4] |
814 | 011 | Scalar | `CR24-CR31`/1 | 0b0011 | BA[0:2] | BA[3:4] |
815 | 100 | Vector | `CR0-CR112`/16 | BA[0:2] 0 | 0b000 | BA[3:4] |
816 | 101 | Vector | `CR4-CR116`/16 | BA[0:2] 0 | 0b100 | BA[3:4] |
817 | 110 | Vector | `CR8-CR120`/16 | BA[0:2] 1 | 0b000 | BA[3:4] |
818 | 111 | Vector | `CR12-CR124`/16 | BA[0:2] 1 | 0b100 | BA[3:4] |
819
820 For a 3-bit operand (e.g. BFA):
821
822 | Value | Mode | Range/Inc | 6..3 | 2..0 |
823 |-------|------|---------------|-----------| --------|
824 | 000 | Scalar | `CR0-CR7`/1 | 0b0000 | BFA |
825 | 001 | Scalar | `CR8-CR15`/1 | 0b0001 | BFA |
826 | 010 | Scalar | `CR16-CR23`/1 | 0b0010 | BFA |
827 | 011 | Scalar | `CR24-CR31`/1 | 0b0011 | BFA |
828 | 100 | Vector | `CR0-CR112`/16 | BFA 0 | 0b000 |
829 | 101 | Vector | `CR4-CR116`/16 | BFA 0 | 0b100 |
830 | 110 | Vector | `CR8-CR120`/16 | BFA 1 | 0b000 |
831 | 111 | Vector | `CR12-CR124`/16 | BFA 1 | 0b100 |
832
833 ### CR EXTRA2
834
835 CR encoding is essentially the same but made more complex due to CRs
836 being bit-based, because the application of SVP64 element-numbering applies
837 to the CR *Field* numbering not the CR register *bit* numbering.
838 See separate section for explanation and pseudocode.
839 Note that Vectors may only start from CR0, CR8, CR16, CR24, CR32...
840
841 Encoding shown MSB down to LSB
842
843 For a 5-bit operand (BA, BB, BC):
844
845 | Value | Mode | Range/Inc | 8..5 | 4..2 | 1..0 |
846 |-------|--------|----------------|---------|---------|---------|
847 | 00 | Scalar | `CR0-CR7`/1 | 0b0000 | BA[0:2] | BA[3:4] |
848 | 01 | Scalar | `CR8-CR15`/1 | 0b0001 | BA[0:2] | BA[3:4] |
849 | 10 | Vector | `CR0-CR112`/16 | BA[0:2] 0 | 0b000 | BA[3:4] |
850 | 11 | Vector | `CR8-CR120`/16 | BA[0:2] 1 | 0b000 | BA[3:4] |
851
852 For a 3-bit operand (e.g. BFA):
853
854 | Value | Mode | Range/Inc | 6..3 | 2..0 |
855 |-------|------|---------------|-----------| --------|
856 | 00 | Scalar | `CR0-CR7`/1 | 0b0000 | BFA |
857 | 01 | Scalar | `CR8-CR15`/1 | 0b0001 | BFA |
858 | 10 | Vector | `CR0-CR112`/16 | BFA 0 | 0b000 |
859 | 11 | Vector | `CR8-CR120`/16 | BFA 1 | 0b000 |
860
861 --------
862
863 \newpage{}
864
865
866 # Normal SVP64 Modes, for Arithmetic and Logical Operations
867
868 Normal SVP64 Mode covers Arithmetic and Logical operations
869 to provide suitable additional behaviour. The Mode
870 field is bits 19-23 of the [[svp64]] RM Field.
871
872 ## Mode
873
874 Mode is an augmentation of SV behaviour, providing additional
875 functionality. Some of these alterations are element-based (saturation),
876 others involve post-analysis (predicate result) and others are
877 Vector-based (mapreduce, fail-on-first).
878
879 [[sv/ldst]], [[sv/cr_ops]] and [[sv/branches]] are covered separately:
880 the following Modes apply to Arithmetic and Logical SVP64 operations:
881
882 * **simple** mode is straight vectorisation. no augmentations: the
883 vector comprises an array of independently created results.
884 * **ffirst** or data-dependent fail-on-first: see separate section.
885 the vector may be truncated depending on certain criteria.
886 *VL is altered as a result*.
887 * **sat mode** or saturation: clamps each element result to a min/max
888 rather than overflows / wraps. allows signed and unsigned clamping
889 for both INT and FP.
890 * **reduce mode**. if used correctly, a mapreduce (or a prefix sum)
891 is performed. see [[svp64/appendix]].
892 note that there are comprehensive caveats when using this mode.
893 * **pred-result** will test the result (CR testing selects a bit of CR
894 and inverts it, just like branch conditional testing) and if the
895 test fails it is as if the *destination* predicate bit was zero even
896 before starting the operation. When Rc=1 the CR element however is
897 still stored in the CR regfile, even if the test failed. See appendix
898 for details.
899
900 Note that ffirst and reduce modes are not anticipated to be
901 high-performance in some implementations. ffirst due to interactions
902 with VL, and reduce due to it requiring additional operations to produce
903 a result. simple, saturate and pred-result are however inter-element
904 independent and may easily be parallelised to give high performance,
905 regardless of the value of VL.
906
907 The Mode table for Arithmetic and Logical operations is laid out as
908 follows:
909
910 | 0-1 | 2 | 3 4 | description |
911 | --- | --- |---------|-------------------------- |
912 | 00 | 0 | dz sz | simple mode |
913 | 00 | 1 | 0 RG | scalar reduce mode (mapreduce) |
914 | 00 | 1 | 1 / | reserved |
915 | 01 | inv | CR-bit | Rc=1: ffirst CR sel |
916 | 01 | inv | VLi RC1 | Rc=0: ffirst z/nonz |
917 | 10 | N | dz sz | sat mode: N=0/1 u/s |
918 | 11 | inv | CR-bit | Rc=1: pred-result CR sel |
919 | 11 | inv | zz RC1 | Rc=0: pred-result z/nonz |
920
921 Fields:
922
923 * **sz / dz** if predication is enabled will put zeros into the dest
924 (or as src in the case of twin pred) when the predicate bit is zero.
925 otherwise the element is ignored or skipped, depending on context.
926 * **zz**: both sz and dz are set equal to this flag
927 * **inv CR bit** just as in branches (BO) these bits allow testing of
928 a CR bit and whether it is set (inv=0) or unset (inv=1)
929 * **RG** inverts the Vector Loop order (VL-1 downto 0) rather
930 than the normal 0..VL-1
931 * **N** sets signed/unsigned saturation.
932 * **RC1** as if Rc=1, enables access to `VLi`.
933 * **VLi** VL inclusive: in fail-first mode, the truncation of
934 VL *includes* the current element at the failure point rather
935 than excludes it from the count.
936
937 For LD/ST Modes, see [[sv/ldst]]. For Condition Registers see
938 [[sv/cr_ops]]. For Branch modes, see [[sv/branches]].
939
940 ## Rounding, clamp and saturate
941
942 To help ensure for example that audio quality is not compromised by
943 overflow, "saturation" is provided, as well as a way to detect when
944 saturation occurred if desired (Rc=1). When Rc=1 there will be a *vector*
945 of CRs, one CR per element in the result (Note: this is different from
946 VSX which has a single CR per block).
947
948 When N=0 the result is saturated to within the maximum range of an
949 unsigned value. For integer ops this will be 0 to 2^elwidth-1. Similar
950 logic applies to FP operations, with the result being saturated to
951 maximum rather than returning INF, and the minimum to +0.0
952
953 When N=1 the same occurs except that the result is saturated to the min
954 or max of a signed result, and for FP to the min and max value rather
955 than returning +/- INF.
956
957 When Rc=1, the CR "overflow" bit is set on the CR associated with the
958 element, to indicate whether saturation occurred. Note that due to
959 the hugely detrimental effect it has on parallel processing, XER.SO is
960 **ignored** completely and is **not** brought into play here. The CR
961 overflow bit is therefore simply set to zero if saturation did not occur,
962 and to one if it did. This behaviour (ignoring XER.SO) is actually optional in
963 the SFFS Compliancy Subset: for SVP64 it is made mandatory *but only on
964 Vectorised instructions*.
965
966 Note also that saturate on operations that set OE=1 must raise an Illegal
967 Instruction due to the conflicting use of the CR.so bit for storing if
968 saturation occurred. Vectorised Integer Operations that produce a Carry-Out (CA,
969 CA32): these two bits will be `UNDEFINED` if saturation is also requested.
970
971 Note that the operation takes place at the maximum bitwidth (max of
972 src and dest elwidth) and that truncation occurs to the range of the
973 dest elwidth.
974
975 *Programmer's Note: Post-analysis of the Vector of CRs to find out if any
976 given element hit saturation may be done using a mapreduced CR op (cror),
977 or by using the new crrweird instruction with Rc=1, which will transfer
978 the required CR bits to a scalar integer and update CR0, which will allow
979 testing the scalar integer for nonzero. see [[sv/cr_int_predication]].
980 Alternatively, a Data-Dependent Fail-First may be used to truncate the
981 Vector Length to non-saturated elements, greatly increasing the productivity
982 of parallelised inner hot-loops.*
983
984 ## Reduce mode
985
986 Reduction in SVP64 is similar in essence to other Vector Processing ISAs,
987 but leverages the underlying scalar Base v3.0B operations. Thus it is
988 more a convention that the programmer may utilise to give the appearance
989 and effect of a Horizontal Vector Reduction. Due to the unusual decoupling
990 it is also possible to perform prefix-sum (Fibonacci Series) in certain
991 circumstances. Details are in the SVP64 appendix
992
993 Reduce Mode should not be confused with Parallel Reduction [[sv/remap]].
994 As explained in the [[sv/appendix]] Reduce Mode switches off the check
995 which would normally stop looping if the result register is scalar.
996 Thus, the result scalar register, if also used as a source scalar,
997 may be used to perform sequential accumulation. This *deliberately*
998 sets up a chain of Register Hazard Dependencies, whereas Parallel Reduce
999 [[sv/remap]] deliberately issues a Tree-Schedule of operations that may
1000 be parallelised.
1001
1002 ## Data-dependent Fail-on-first
1003
1004 Data-dependent fail-on-first is very different from LD/ST Fail-First
1005 (also known as Fault-First) and is actually CR-field-driven.
1006 Vector elements are required to appear
1007 to be executed in sequential Program Order. When REMAP is not active,
1008 element 0 would be the first.
1009
1010 Data-driven (CR-driven) fail-on-first activates when Rc=1 or other
1011 CR-creating operation produces a result (including cmp). Similar to
1012 branch, an analysis of the CR is performed and if the test fails, the
1013 vector operation terminates and discards all element operations **at and
1014 above the current one**, and VL is truncated to either the *previous*
1015 element or the current one, depending on whether VLi (VL "inclusive")
1016 is clear or set, respectively.
1017
1018 Thus the new VL comprises a contiguous vector of results, all of which
1019 pass the testing criteria (equal to zero, less than zero etc as defined
1020 by the CR-bit test).
1021
1022 *Note: when VLi is clear, the behaviour at first seems counter-intuitive.
1023 A result is calculated but if the test fails it is prohibited from being
1024 actually written. This becomes intuitive again when it is remembered
1025 that the length that VL is set to is the number of *written* elements, and
1026 only when VLI is set will the current element be included in that count.*
1027
1028 The CR-based data-driven fail-on-first is "new" and not found in ARM SVE
1029 or RVV. At the same time it is "old" because it is almost identical to
1030 a generalised form of Z80's `CPIR` instruction. It is extremely useful
1031 for reducing instruction count, however requires speculative execution
1032 involving modifications of VL to get high performance implementations.
1033 An additional mode (RC1=1) effectively turns what would otherwise be an
1034 arithmetic operation into a type of `cmp`. The CR is stored (and the
1035 CR.eq bit tested against the `inv` field). If the CR.eq bit is equal to
1036 `inv` then the Vector is truncated and the loop ends.
1037
1038 VLi is only available as an option when `Rc=0` (or for instructions
1039 which do not have Rc). When set, the current element is always also
1040 included in the count (the new length that VL will be set to). This may
1041 be useful in combination with "inv" to truncate the Vector to *exclude*
1042 elements that fail a test, or, in the case of implementations of strncpy,
1043 to include the terminating zero.
1044
1045 In CR-based data-driven fail-on-first there is only the option to select
1046 and test one bit of each CR (just as with branch BO). For more complex
1047 tests this may be insufficient. If that is the case, a vectorised crop
1048 such as crand, cror or [[sv/cr_int_predication]] crweirder may be used,
1049 and ffirst applied to the crop instead of to the arithmetic vector. Note
1050 that crops are covered by the [[sv/cr_ops]] Mode format.
1051
1052 Use of Fail-on-first with Vertical-First Mode is not prohibited but is
1053 not really recommended. The effect of truncating VL
1054 may have unintended and unexpected consequences on subsequent instructions.
1055 VLi set will be fine: it is when VLi is clear that problems may be faced.
1056
1057 *Programmer's note: `VLi` is only accessible in normal operations which in
1058 turn limits the CR field bit-testing to only `EQ/NE`. [[sv/cr_ops]] are
1059 not so limited. Thus it is possible to use for example `sv.cror/ff=gt/vli
1060 *0,*0,*0`, which is not a `nop` because it allows Fail-First Mode to
1061 perform a test and truncate VL.*
1062
1063 *Hardware implementor's note: effective Sequential Program Order must be preserved.
1064 Speculative Execution is perfectly permitted as long as the speculative elements
1065 are held back from writing to register files (kept in Resevation Stations),
1066 until such time as the relevant
1067 CR Field bit(s) has been analysed. All Speculative elements sequentially beyond the
1068 test-failure point **MUST** be cancelled. This is no different from standard
1069 Out-of-Order Execution and the modification effort to efficiently support
1070 Data-Dependent Fail-First within a pre-existing Multi-Issue Out-of-Order Engine
1071 is anticipated to be minimal. In-Order systems on the other hand are expected,
1072 unavoidably, to be low-performance*.
1073
1074 Two extremely important aspects of ffirst are:
1075
1076 * LDST ffirst may never set VL equal to zero. This because on the first
1077 element an exception must be raised "as normal".
1078 * CR-based data-dependent ffirst on the other hand **can** set VL equal
1079 to zero. This is the only means in the entirety of SV that VL may be set
1080 to zero (with the exception of via the SV.STATE SPR). When VL is set
1081 zero due to the first element failing the CR bit-test, all subsequent
1082 vectorised operations are effectively `nops` which is
1083 *precisely the desired and intended behaviour*.
1084
1085 The second crucial aspect, compared to LDST Ffirst:
1086
1087 * LD/ST Failfirst may (beyond the initial first element
1088 conditions) truncate VL for any architecturally suitable reason. Beyond
1089 the first element LD/ST Failfirst is arbitrarily speculative and 100%
1090 non-deterministic.
1091 * CR-based data-dependent first on the other hand MUST NOT truncate VL
1092 arbitrarily to a length decided by the hardware: VL MUST only be
1093 truncated based explicitly on whether a test fails. This because it is
1094 a precise Deterministic test on which algorithms can and will will rely.
1095
1096 **Floating-point Exceptions**
1097
1098 When Floating-point exceptions are enabled VL must be truncated at
1099 the point where the Exception appears not to have occurred. If `VLi`
1100 is set then VL must include the faulting element, and thus the faulting
1101 element will always raise its exception. If however `VLi` is clear then
1102 VL **excludes** the faulting element and thus the exception will **never**
1103 be raised.
1104
1105 Although very strongly discouraged the Exception Mode that permits
1106 Floating Point Exception notification to arrive too late to unwind
1107 is permitted (under protest, due it violating the otherwise 100%
1108 Deterministic nature of Data-dependent Fail-first) and is `UNDEFINED`
1109 behaviour.
1110
1111 **Use of lax FP Exception Notification Mode could result in parallel
1112 computations proceeding with invalid results that have to be explicitly
1113 detected, whereas with the strict FP Execption Mode enabled, FFirst
1114 truncates VL, allows subsequent parallel computation to avoid the
1115 exceptions entirely**
1116
1117 ## Data-dependent fail-first on CR operations (crand etc)
1118
1119 Operations that actually produce or alter CR Field as a result have
1120 their own SVP64 Mode, described in [[sv/cr_ops]].
1121
1122 ## pred-result mode
1123
1124 This mode merges common CR testing with predication, saving on instruction
1125 count. Below is the pseudocode excluding predicate zeroing and elwidth
1126 overrides. Note that the pseudocode for SVP64 CR-ops is slightly different.
1127
1128 ```
1129 for i in range(VL):
1130 # predication test, skip all masked out elements.
1131 if predicate_masked_out(i):
1132 continue
1133 result = op(iregs[RA+i], iregs[RB+i])
1134 CRnew = analyse(result) # calculates eq/lt/gt
1135 # Rc=1 always stores the CR field
1136 if Rc=1 or RC1:
1137 CR.field[offs+i] = CRnew
1138 # now test CR, similar to branch
1139 if RC1 or CR.field[BO[0:1]] != BO[2]:
1140 continue # test failed: cancel store
1141 # result optionally stored but CR always is
1142 iregs[RT+i] = result
1143 ```
1144
1145 The reason for allowing the CR element to be stored is so that
1146 post-analysis of the CR Vector may be carried out. For example:
1147 Saturation may have occurred (and been prevented from updating, by the
1148 test) but it is desirable to know *which* elements fail saturation.
1149
1150 Note that RC1 Mode basically turns all operations into `cmp`. The
1151 calculation is performed but it is only the CR that is written. The
1152 element result is *always* discarded, never written (just like `cmp`).
1153
1154 Note that predication is still respected: predicate zeroing is slightly
1155 different: elements that fail the CR test *or* are masked out are zero'd.
1156
1157 --------
1158
1159 \newpage{}
1160
1161 # SV Load and Store
1162
1163 **Rationale**
1164
1165 All Vector ISAs dating back fifty years have extensive and comprehensive
1166 Load and Store operations that go far beyond the capabilities of Scalar
1167 RISC and most CISC processors, yet at their heart on an individual element
1168 basis may be found to be no different from RISC Scalar equivalents.
1169
1170 The resource savings from Vector LD/ST are significant and stem
1171 from the fact that one single instruction can trigger a dozen (or in
1172 some microarchitectures such as Cray or NEC SX Aurora) hundreds of
1173 element-level Memory accesses.
1174
1175 Additionally, and simply: if the Arithmetic side of an ISA supports
1176 Vector Operations, then in order to keep the ALUs 100% occupied the
1177 Memory infrastructure (and the ISA itself) correspondingly needs Vector
1178 Memory Operations as well.
1179
1180 Vectorised Load and Store also presents an extra dimension (literally)
1181 which creates scenarios unique to Vector applications, that a Scalar
1182 (and even a SIMD) ISA simply never encounters. SVP64 endeavours to add
1183 the modes typically found in *all* Scalable Vector ISAs, without changing
1184 the behaviour of the underlying Base (Scalar) v3.0B operations in any way.
1185 (The sole apparent exception is Post-Increment Mode on LD/ST-update instructions)
1186
1187 ## Modes overview
1188
1189 Vectorisation of Load and Store requires creation, from scalar operations,
1190 a number of different modes:
1191
1192 * **fixed aka "unit" stride** - contiguous sequence with no gaps
1193 * **element strided** - sequential but regularly offset, with gaps
1194 * **vector indexed** - vector of base addresses and vector of offsets
1195 * **Speculative fail-first** - where it makes sense to do so
1196 * **Structure Packing** - covered in SV by [[sv/remap]] and Pack/Unpack Mode.
1197
1198 *Despite being constructed from Scalar LD/ST none of these Modes exist
1199 or make sense in any Scalar ISA. They **only** exist in Vector ISAs*
1200
1201 Also included in SVP64 LD/ST is both signed and unsigned Saturation,
1202 as well as Element-width overrides and Twin-Predication.
1203
1204 Note also that Indexed [[sv/remap]] mode may be applied to both v3.0
1205 LD/ST Immediate instructions *and* v3.0 LD/ST Indexed instructions.
1206 LD/ST-Indexed should not be conflated with Indexed REMAP mode:
1207 clarification is provided below.
1208
1209 **Determining the LD/ST Modes**
1210
1211 A minor complication (caused by the retro-fitting of modern Vector
1212 features to a Scalar ISA) is that certain features do not exactly make
1213 sense or are considered a security risk. Fail-first on Vector Indexed
1214 would allow attackers to probe large numbers of pages from userspace,
1215 where strided fail-first (by creating contiguous sequential LDs) does not.
1216
1217 In addition, reduce mode makes no sense. Realistically we need an
1218 alternative table definition for [[sv/svp64]] `RM.MODE`. The following
1219 modes make sense:
1220
1221 * saturation
1222 * predicate-result (mostly for cache-inhibited LD/ST)
1223 * simple (no augmentation)
1224 * fail-first (where Vector Indexed is banned)
1225 * Signed Effective Address computation (Vector Indexed only)
1226
1227 More than that however it is necessary to fit the usual Vector ISA
1228 capabilities onto both Power ISA LD/ST with immediate and to LD/ST
1229 Indexed. They present subtly different Mode tables, which, due to lack
1230 of space, have the following quirks:
1231
1232 * LD/ST Immediate has no individual control over src/dest zeroing,
1233 whereas LD/ST Indexed does.
1234 * LD/ST Indexed has limited zeroing on pred-result, LD/ST Immediate has
1235 *no* option to select zeroing on pred-result.
1236
1237 ## Format and fields
1238
1239 Fields used in tables below:
1240
1241 * **sz / dz** if predication is enabled will put zeros into the dest
1242 (or as src in the case of twin pred) when the predicate bit is zero.
1243 otherwise the element is ignored or skipped, depending on context.
1244 * **zz**: both sz and dz are set equal to this flag.
1245 * **inv CR bit** just as in branches (BO) these bits allow testing of
1246 a CR bit and whether it is set (inv=0) or unset (inv=1)
1247 * **N** sets signed/unsigned saturation.
1248 * **RC1** as if Rc=1, stores CRs *but not the result*
1249 * **SEA** - Signed Effective Address, if enabled performs sign-extension on
1250 registers that have been reduced due to elwidth overrides
1251 * **PI** - post-increment mode (applies to LD/ST with update only).
1252 the Effective Address utilised is always just RA, i.e. the computation of
1253 EA is stored in RA **after** it is actually used.
1254 * **LF** - Load/Store Fail or Fault First: for any reason Load or Store Vectors
1255 may be truncated to (at least) one element, and VL altered to indicate such.
1256
1257 **LD/ST immediate**
1258
1259 The table for [[sv/svp64]] for `immed(RA)` which is `RM.MODE`
1260 (bits 19:23 of `RM`) is:
1261
1262 | 0-1 | 2 | 3 4 | description |
1263 | --- | --- |---------|--------------------------- |
1264 | 00 | 0 | zz els | simple mode |
1265 | 00 | 1 | PI LF | post-increment and Fault-First |
1266 | 01 | inv | CR-bit | Rc=1: ffirst CR sel |
1267 | 01 | inv | els RC1 | Rc=0: ffirst z/nonz |
1268 | 10 | N | zz els | sat mode: N=0/1 u/s |
1269 | 11 | inv | CR-bit | Rc=1: pred-result CR sel |
1270 | 11 | inv | els RC1 | Rc=0: pred-result z/nonz |
1271
1272 The `els` bit is only relevant when `RA.isvec` is clear: this indicates
1273 whether stride is unit or element:
1274
1275 ```
1276 if RA.isvec:
1277 svctx.ldstmode = indexed
1278 elif els == 0:
1279 svctx.ldstmode = unitstride
1280 elif immediate != 0:
1281 svctx.ldstmode = elementstride
1282 ```
1283
1284 An immediate of zero is a safety-valve to allow `LD-VSPLAT`: in effect
1285 the multiplication of the immediate-offset by zero results in reading from
1286 the exact same memory location, *even with a Vector register*. (Normally
1287 this type of behaviour is reserved for the mapreduce modes)
1288
1289 For `LD-VSPLAT`, on non-cache-inhibited Loads, the read can occur just
1290 the once and be copied, rather than hitting the Data Cache multiple
1291 times with the same memory read at the same location. The benefit of
1292 Cache-inhibited LD-splats is that it allows for memory-mapped peripherals
1293 to have multiple data values read in quick succession and stored in
1294 sequentially numbered registers (but, see Note below).
1295
1296 For non-cache-inhibited ST from a vector source onto a scalar destination:
1297 with the Vector loop effectively creating multiple memory writes to
1298 the same location, we can deduce that the last of these will be the
1299 "successful" one. Thus, implementations are free and clear to optimise
1300 out the overwriting STs, leaving just the last one as the "winner".
1301 Bear in mind that predicate masks will skip some elements (in source
1302 non-zeroing mode). Cache-inhibited ST operations on the other hand
1303 **MUST** write out a Vector source multiple successive times to the exact
1304 same Scalar destination. Just like Cache-inhibited LDs, multiple values
1305 may be written out in quick succession to a memory-mapped peripheral
1306 from sequentially-numbered registers.
1307
1308 Note that any memory location may be Cache-inhibited
1309 (Power ISA v3.1, Book III, 1.6.1, p1033)
1310
1311 *Programmer's Note: an immediate also with a Scalar source as a "VSPLAT"
1312 mode is simply not possible: there are not enough Mode bits. One single
1313 Scalar Load operation may be used instead, followed by any arithmetic
1314 operation (including a simple mv) in "Splat" mode.*
1315
1316 **LD/ST Indexed**
1317
1318 The modes for `RA+RB` indexed version are slightly different
1319 but are the same `RM.MODE` bits (19:23 of `RM`):
1320
1321 | 0-1 | 2 | 3 4 | description |
1322 | --- | --- |---------|-------------------------- |
1323 | 00 | SEA | dz sz | simple mode |
1324 | 01 | SEA | dz sz | Strided (scalar only source) |
1325 | 10 | N | dz sz | sat mode: N=0/1 u/s |
1326 | 11 | inv | CR-bit | Rc=1: pred-result CR sel |
1327 | 11 | inv | zz RC1 | Rc=0: pred-result z/nonz |
1328
1329 Vector Indexed Strided Mode is qualified as follows:
1330
1331 if mode = 0b01 and !RA.isvec and !RB.isvec:
1332 svctx.ldstmode = elementstride
1333
1334 A summary of the effect of Vectorisation of src or dest:
1335
1336 ```
1337 imm(RA) RT.v RA.v no stride allowed
1338 imm(RA) RT.s RA.v no stride allowed
1339 imm(RA) RT.v RA.s stride-select allowed
1340 imm(RA) RT.s RA.s not vectorised
1341 RA,RB RT.v {RA|RB}.v Standard Indexed
1342 RA,RB RT.s {RA|RB}.v Indexed but single LD (no VSPLAT)
1343 RA,RB RT.v {RA&RB}.s VSPLAT possible. stride selectable
1344 RA,RB RT.s {RA&RB}.s not vectorised (scalar identity)
1345 ```
1346
1347 Signed Effective Address computation is only relevant for Vector Indexed
1348 Mode, when elwidth overrides are applied. The source override applies to
1349 RB, and before adding to RA in order to calculate the Effective Address,
1350 if SEA is set RB is sign-extended from elwidth bits to the full 64 bits.
1351 For other Modes (ffirst, saturate), all EA computation with elwidth
1352 overrides is unsigned.
1353
1354 Note that cache-inhibited LD/ST when VSPLAT is activated will perform
1355 **multiple** LD/ST operations, sequentially. Even with scalar src
1356 a Cache-inhibited LD will read the same memory location *multiple
1357 times*, storing the result in successive Vector destination registers.
1358 This because the cache-inhibit instructions are typically used to read
1359 and write memory-mapped peripherals. If a genuine cache-inhibited
1360 LD-VSPLAT is required then a single *scalar* cache-inhibited LD should
1361 be performed, followed by a VSPLAT-augmented mv, copying the one *scalar*
1362 value into multiple register destinations.
1363
1364 Note also that cache-inhibited VSPLAT with Predicate-result is possible.
1365 This allows for example to issue a massive batch of memory-mapped
1366 peripheral reads, stopping at the first NULL-terminated character and
1367 truncating VL to that point. No branch is needed to issue that large
1368 burst of LDs, which may be valuable in Embedded scenarios.
1369
1370 ## Vectorisation of Scalar Power ISA v3.0B
1371
1372 Scalar Power ISA Load/Store operations may be seen from their
1373 pseudocode to be of the form:
1374
1375 ```
1376 lbux RT, RA, RB
1377 EA <- (RA) + (RB)
1378 RT <- MEM(EA)
1379 ```
1380
1381 and for immediate variants:
1382
1383 ```
1384 lb RT,D(RA)
1385 EA <- RA + EXTS(D)
1386 RT <- MEM(EA)
1387 ```
1388
1389 Thus in the first example, the source registers may each be independently
1390 marked as scalar or vector, and likewise the destination; in the second
1391 example only the one source and one dest may be marked as scalar or
1392 vector.
1393
1394 Thus we can see that Vector Indexed may be covered, and, as demonstrated
1395 with the pseudocode below, the immediate can be used to give unit
1396 stride or element stride. With there being no way to tell which from
1397 the Power v3.0B Scalar opcode alone, the choice is provided instead by
1398 the SV Context.
1399
1400 ```
1401 # LD not VLD! format - ldop RT, immed(RA)
1402 # op_width: lb=1, lh=2, lw=4, ld=8
1403 op_load(RT, RA, op_width, immed, svctx, RAupdate):
1404  ps = get_pred_val(FALSE, RA); # predication on src
1405  pd = get_pred_val(FALSE, RT); # ... AND on dest
1406  for (i=0, j=0, u=0; i < VL && j < VL;):
1407 # skip nonpredicates elements
1408 if (RA.isvec) while (!(ps & 1<<i)) i++;
1409 if (RAupdate.isvec) while (!(ps & 1<<u)) u++;
1410 if (RT.isvec) while (!(pd & 1<<j)) j++;
1411 if postinc:
1412 offs = 0; # added afterwards
1413 if RA.isvec: srcbase = ireg[RA+i]
1414 else srcbase = ireg[RA]
1415 elif svctx.ldstmode == elementstride:
1416 # element stride mode
1417 srcbase = ireg[RA]
1418 offs = i * immed # j*immed for a ST
1419 elif svctx.ldstmode == unitstride:
1420 # unit stride mode
1421 srcbase = ireg[RA]
1422 offs = immed + (i * op_width) # j*op_width for ST
1423 elif RA.isvec:
1424 # quirky Vector indexed mode but with an immediate
1425 srcbase = ireg[RA+i]
1426 offs = immed;
1427 else
1428 # standard scalar mode (but predicated)
1429 # no stride multiplier means VSPLAT mode
1430 srcbase = ireg[RA]
1431 offs = immed
1432
1433 # compute EA
1434 EA = srcbase + offs
1435 # load from memory
1436 ireg[RT+j] <= MEM[EA];
1437 # check post-increment of EA
1438 if postinc: EA = srcbase + immed;
1439 # update RA?
1440 if RAupdate: ireg[RAupdate+u] = EA;
1441 if (!RT.isvec)
1442 break # destination scalar, end now
1443 if (RA.isvec) i++;
1444 if (RAupdate.isvec) u++;
1445 if (RT.isvec) j++;
1446 ```
1447
1448 Indexed LD is:
1449
1450 ```
1451 # format: ldop RT, RA, RB
1452 function op_ldx(RT, RA, RB, RAupdate=False) # LD not VLD!
1453  ps = get_pred_val(FALSE, RA); # predication on src
1454  pd = get_pred_val(FALSE, RT); # ... AND on dest
1455  for (i=0, j=0, k=0, u=0; i < VL && j < VL && k < VL):
1456 # skip nonpredicated RA, RB and RT
1457 if (RA.isvec) while (!(ps & 1<<i)) i++;
1458 if (RAupdate.isvec) while (!(ps & 1<<u)) u++;
1459 if (RB.isvec) while (!(ps & 1<<k)) k++;
1460 if (RT.isvec) while (!(pd & 1<<j)) j++;
1461 if svctx.ldstmode == elementstride:
1462 EA = ireg[RA] + ireg[RB]*j # register-strided
1463 else
1464 EA = ireg[RA+i] + ireg[RB+k] # indexed address
1465 if RAupdate: ireg[RAupdate+u] = EA
1466 ireg[RT+j] <= MEM[EA];
1467 if (!RT.isvec)
1468 break # destination scalar, end immediately
1469 if (RA.isvec) i++;
1470 if (RAupdate.isvec) u++;
1471 if (RB.isvec) k++;
1472 if (RT.isvec) j++;
1473 ```
1474
1475 Note that Element-Strided uses the Destination Step because with both
1476 sources being Scalar as a prerequisite condition of activation of
1477 Element-Stride Mode, the source step (being Scalar) would never advance.
1478
1479 Note in both cases that [[sv/svp64]] allows RA-as-a-dest in "update"
1480 mode (`ldux`) to be effectively a *completely different* register from
1481 RA-as-a-source. This because there is room in svp64 to extend RA-as-src
1482 as well as RA-as-dest, both independently as scalar or vector *and*
1483 independently extending their range.
1484
1485 *Programmer's note: being able to set RA-as-a-source as separate from
1486 RA-as-a-destination as Scalar is **extremely valuable** once it is
1487 remembered that Simple-V element operations must be in Program Order,
1488 especially in loops, for saving on multiple address computations. Care
1489 does have to be taken however that RA-as-src is not overwritten by
1490 RA-as-dest unless intentionally desired, especially in element-strided
1491 Mode.*
1492
1493 ## LD/ST Indexed vs Indexed REMAP
1494
1495 Unfortunately the word "Indexed" is used twice in completely different
1496 contexts, potentially causing confusion.
1497
1498 * There has existed instructions in the Power ISA `ld RT,RA,RB` since
1499 its creation: these are called "LD/ST Indexed" instructions and their
1500 name and meaning is well-established.
1501 * There now exists, in Simple-V, a REMAP mode called "Indexed"
1502 Mode that can be applied to *any* instruction **including those
1503 named LD/ST Indexed**.
1504
1505 Whilst it may be costly in terms of register reads to allow REMAP Indexed
1506 Mode to be applied to any Vectorised LD/ST Indexed operation such as
1507 `sv.ld *RT,RA,*RB`, or even misleadingly labelled as redundant, firstly
1508 the strict application of the RISC Paradigm that Simple-V follows makes
1509 it awkward to consider *preventing* the application of Indexed REMAP to
1510 such operations, and secondly they are not actually the same at all.
1511
1512 Indexed REMAP, as applied to RB in the instruction `sv.ld *RT,RA,*RB`
1513 effectively performs an *in-place* re-ordering of the offsets, RB.
1514 To achieve the same effect without Indexed REMAP would require taking
1515 a *copy* of the Vector of offsets starting at RB, manually explicitly
1516 reordering them, and finally using the copy of re-ordered offsets in a
1517 non-REMAP'ed `sv.ld`. Using non-strided LD as an example, pseudocode
1518 showing what actually occurs, where the pseudocode for `indexed_remap`
1519 may be found in [[sv/remap]]:
1520
1521 ```
1522 # sv.ld *RT,RA,*RB with Index REMAP applied to RB
1523 for i in 0..VL-1:
1524 if remap.indexed:
1525 rb_idx = indexed_remap(i) # remap
1526 else:
1527 rb_idx = i # use the index as-is
1528 EA = GPR(RA) + GPR(RB+rb_idx)
1529 GPR(RT+i) = MEM(EA, 8)
1530 ```
1531
1532 Thus it can be seen that the use of Indexed REMAP saves copying
1533 and manual reordering of the Vector of RB offsets.
1534
1535 ## LD/ST ffirst
1536
1537 LD/ST ffirst treats the first LD/ST in a vector (element 0 if REMAP
1538 is not active) as an ordinary one, with all behaviour with respect to
1539 Interrupts Exceptions Page Faults Memory Management being identical
1540 in every regard to Scalar v3.0 Power ISA LD/ST. However for elements
1541 1 and above, if an exception would occur, then VL is **truncated**
1542 to the previous element: the exception is **not** then raised because
1543 the LD/ST that would otherwise have caused an exception is *required*
1544 to be cancelled. Additionally an implementor may choose to truncate VL
1545 for any arbitrary reason *except for the very first*.
1546
1547 ffirst LD/ST to multiple pages via a Vectorised Index base is
1548 considered a security risk due to the abuse of probing multiple
1549 pages in rapid succession and getting speculative feedback on which
1550 pages would fail. Therefore Vector Indexed LD/ST is prohibited
1551 entirely, and the Mode bit instead used for element-strided LD/ST.
1552
1553 ```
1554 for(i = 0; i < VL; i++)
1555 reg[rt + i] = mem[reg[ra] + i * reg[rb]];
1556 ```
1557
1558 High security implementations where any kind of speculative probing of
1559 memory pages is considered a risk should take advantage of the fact
1560 that implementations may truncate VL at any point, without requiring
1561 software to be rewritten and made non-portable. Such implementations may
1562 choose to *always* set VL=1 which will have the effect of terminating
1563 any speculative probing (and also adversely affect performance), but
1564 will at least not require applications to be rewritten.
1565
1566 Low-performance simpler hardware implementations may also choose (always)
1567 to also set VL=1 as the bare minimum compliant implementation of LD/ST
1568 Fail-First. It is however critically important to remember that the first
1569 element LD/ST **MUST** be treated as an ordinary LD/ST, i.e. **MUST**
1570 raise exceptions exactly like an ordinary LD/ST.
1571
1572 For ffirst LD/STs, VL may be truncated arbitrarily to a nonzero value
1573 for any implementation-specific reason. For example: it is perfectly
1574 reasonable for implementations to alter VL when ffirst LD or ST operations
1575 are initiated on a nonaligned boundary, such that within a loop the
1576 subsequent iteration of that loop begins the following ffirst LD/ST
1577 operations on an aligned boundary such as the beginning of a cache line,
1578 or beginning of a Virtual Memory page. Likewise, to reduce workloads or
1579 balance resources.
1580
1581 Vertical-First Mode is slightly strange in that only one element at a time
1582 is ever executed anyway. Given that programmers may legitimately choose
1583 to alter srcstep and dststep in non-sequential order as part of explicit
1584 loops, it is neither possible nor safe to make speculative assumptions
1585 about future LD/STs. Therefore, Fail-First LD/ST in Vertical-First is
1586 `UNDEFINED`. This is very different from Arithmetic (Data-dependent)
1587 FFirst where Vertical-First Mode is fully deterministic, not speculative.
1588
1589 ## LOAD/STORE Elwidths <a name="elwidth"></a>
1590
1591 Loads and Stores are almost unique in that the Power Scalar ISA
1592 provides a width for the operation (lb, lh, lw, ld). Only `extsb` and
1593 others like it provide an explicit operation width. There are therefore
1594 *three* widths involved:
1595
1596 * operation width (lb=8, lh=16, lw=32, ld=64)
1597 * src element width override (8/16/32/default)
1598 * destination element width override (8/16/32/default)
1599
1600 Some care is therefore needed to express and make clear the transformations,
1601 which are expressly in this order:
1602
1603 * Calculate the Effective Address from RA at full width
1604 but (on Indexed Load) allow srcwidth overrides on RB
1605 * Load at the operation width (lb/lh/lw/ld) as usual
1606 * byte-reversal as usual
1607 * Non-saturated mode:
1608 - zero-extension or truncation from operation width to dest elwidth
1609 - place result in destination at dest elwidth
1610 * Saturated mode:
1611 - Sign-extension or truncation from operation width to dest width
1612 - signed/unsigned saturation down to dest elwidth
1613
1614 In order to respect Power v3.0B Scalar behaviour the memory side
1615 is treated effectively as completely separate and distinct from SV
1616 augmentation. This is primarily down to quirks surrounding LE/BE and
1617 byte-reversal.
1618
1619 It is rather unfortunately possible to request an elwidth override on
1620 the memory side which does not mesh with the overridden operation width:
1621 these result in `UNDEFINED` behaviour. The reason is that the effect
1622 of attempting a 64-bit `sv.ld` operation with a source elwidth override
1623 of 8/16/32 would result in overlapping memory requests, particularly
1624 on unit and element strided operations. Thus it is `UNDEFINED` when
1625 the elwidth is smaller than the memory operation width. Examples include
1626 `sv.lw/sw=16/els` which requests (overlapping) 4-byte memory reads offset
1627 from each other at 2-byte intervals. Store likewise is also `UNDEFINED`
1628 where the dest elwidth override is less than the operation width.
1629
1630 Note the following regarding the pseudocode to follow:
1631
1632 * `scalar identity behaviour` SV Context parameter conditions turn this
1633 into a straight absolute fully-compliant Scalar v3.0B LD operation
1634 * `brev` selects whether the operation is the byte-reversed variant (`ldbrx`
1635 rather than `ld`)
1636 * `op_width` specifies the operation width (`lb`, `lh`, `lw`, `ld`) as
1637 a "normal" part of Scalar v3.0B LD
1638 * `imm_offs` specifies the immediate offset `ld r3, imm_offs(r5)`, again
1639 as a "normal" part of Scalar v3.0B LD
1640 * `svctx` specifies the SV Context and includes VL as well as
1641 source and destination elwidth overrides.
1642
1643 Below is the pseudocode for Unit-Strided LD (which includes Vector
1644 capability). Observe in particular that RA, as the base address in both
1645 Immediate and Indexed LD/ST, does not have element-width overriding
1646 applied to it.
1647
1648 Note that predication, predication-zeroing, and other modes except
1649 saturation have all been removed, for clarity and simplicity:
1650
1651 ```
1652 # LD not VLD!
1653 # this covers unit stride mode and a type of vector offset
1654 function op_ld(RT, RA, op_width, imm_offs, svctx)
1655 for (int i = 0, int j = 0; i < svctx.VL && j < svctx.VL):
1656 if not svctx.unit/el-strided:
1657 # strange vector mode, compute 64 bit address which is
1658 # not polymorphic! elwidth hardcoded to 64 here
1659 srcbase = get_polymorphed_reg(RA, 64, i)
1660 else:
1661 # unit / element stride mode, compute 64 bit address
1662 srcbase = get_polymorphed_reg(RA, 64, 0)
1663 # adjust for unit/el-stride
1664 srcbase += ....
1665
1666 # read the underlying memory
1667 memread <= MEM(srcbase + imm_offs, op_width)
1668
1669 # check saturation.
1670 if svpctx.saturation_mode:
1671 # ... saturation adjustment...
1672 memread = clamp(memread, op_width, svctx.dest_elwidth)
1673 else:
1674 # truncate/extend to over-ridden dest width.
1675 memread = adjust_wid(memread, op_width, svctx.dest_elwidth)
1676
1677 # takes care of inserting memory-read (now correctly byteswapped)
1678 # into regfile underlying LE-defined order, into the right place
1679 # within the NEON-like register, respecting destination element
1680 # bitwidth, and the element index (j)
1681 set_polymorphed_reg(RT, svctx.dest_elwidth, j, memread)
1682
1683 # increments both src and dest element indices (no predication here)
1684 i++;
1685 j++;
1686 ```
1687
1688 Note above that the source elwidth is *not used at all* in LD-immediate.
1689
1690 For LD/Indexed, the key is that in the calculation of the Effective Address,
1691 RA has no elwidth override but RB does. Pseudocode below is simplified
1692 for clarity: predication and all modes except saturation are removed:
1693
1694 ```
1695 # LD not VLD! ld*rx if brev else ld*
1696 function op_ld(RT, RA, RB, op_width, svctx, brev)
1697 for (int i = 0, int j = 0; i < svctx.VL && j < svctx.VL):
1698 if not svctx.el-strided:
1699 # RA not polymorphic! elwidth hardcoded to 64 here
1700 srcbase = get_polymorphed_reg(RA, 64, i)
1701 else:
1702 # element stride mode, again RA not polymorphic
1703 srcbase = get_polymorphed_reg(RA, 64, 0)
1704 # RB *is* polymorphic
1705 offs = get_polymorphed_reg(RB, svctx.src_elwidth, i)
1706 # sign-extend
1707 if svctx.SEA: offs = sext(offs, svctx.src_elwidth, 64)
1708
1709 # takes care of (merges) processor LE/BE and ld/ldbrx
1710 bytereverse = brev XNOR MSR.LE
1711
1712 # read the underlying memory
1713 memread <= MEM(srcbase + offs, op_width)
1714
1715 # optionally performs byteswap at op width
1716 if (bytereverse):
1717 memread = byteswap(memread, op_width)
1718
1719 if svpctx.saturation_mode:
1720 # ... saturation adjustment...
1721 memread = clamp(memread, op_width, svctx.dest_elwidth)
1722 else:
1723 # truncate/extend to over-ridden dest width.
1724 memread = adjust_wid(memread, op_width, svctx.dest_elwidth)
1725
1726 # takes care of inserting memory-read (now correctly byteswapped)
1727 # into regfile underlying LE-defined order, into the right place
1728 # within the NEON-like register, respecting destination element
1729 # bitwidth, and the element index (j)
1730 set_polymorphed_reg(RT, svctx.dest_elwidth, j, memread)
1731
1732 # increments both src and dest element indices (no predication here)
1733 i++;
1734 j++;
1735 ```
1736
1737 ## Remapped LD/ST
1738
1739 In the [[sv/remap]] page the concept of "Remapping" is described. Whilst
1740 it is expensive to set up (2 64-bit opcodes minimum) it provides a way to
1741 arbitrarily perform 1D, 2D and 3D "remapping" of up to 64 elements worth
1742 of LDs or STs. The usual interest in such re-mapping is for example in
1743 separating out 24-bit RGB channel data into separate contiguous registers.
1744
1745 REMAP easily covers this capability, and with dest elwidth overrides
1746 and saturation may do so with built-in conversion that would normally
1747 require additional width-extension, sign-extension and min/max Vectorised
1748 instructions as post-processing stages.
1749
1750 Thus we do not need to provide specialist LD/ST "Structure Packed" opcodes
1751 because the generic abstracted concept of "Remapping", when applied to
1752 LD/ST, will give that same capability, with far more flexibility.
1753
1754 It is worth noting that Pack/Unpack Modes of SVSTATE, which may be
1755 established through `svstep`, are also an easy way to perform regular
1756 Structure Packing, at the vec2/vec3/vec4 granularity level. Beyond that,
1757 REMAP will need to be used.
1758
1759 --------
1760
1761 \newpage{}
1762
1763 # Condition Register SVP64 Operations
1764
1765 Condition Register Fields are only 4 bits wide: this presents some
1766 interesting conceptual challenges for SVP64, which was designed
1767 primarily for vectors of arithmetic and logical operations. However
1768 if predicates may be bits of CR Fields it makes sense to extend
1769 Simple-V to cover CR Operations, especially given that Vectorised Rc=1
1770 may be processed by Vectorised CR Operations tbat usefully in turn
1771 may become Predicate Masks to yet more Vector operations, like so:
1772
1773 ```
1774 sv.cmpi/ew=8 *B,*ra,0 # compare bytes against zero
1775 sv.cmpi/ew=8 *B2,*ra,13. # and against newline
1776 sv.cror PM.EQ,B.EQ,B2.EQ # OR compares to create mask
1777 sv.stb/sm=EQ ... # store only nonzero/newline
1778 ```
1779
1780 Element width however is clearly meaningless for a 4-bit collation of
1781 Conditions, EQ LT GE SO. Likewise, arithmetic saturation (an important
1782 part of Arithmetic SVP64) has no meaning. An alternative Mode Format is
1783 required, and given that elwidths are meaningless for CR Fields the bits
1784 in SVP64 `RM` may be used for other purposes.
1785
1786 This alternative mapping **only** applies to instructions that **only**
1787 reference a CR Field or CR bit as the sole exclusive result. This section
1788 **does not** apply to instructions which primarily produce arithmetic
1789 results that also, as an aside, produce a corresponding CR Field (such as
1790 when Rc=1). Instructions that involve Rc=1 are definitively arithmetic
1791 in nature, where the corresponding Condition Register Field can be
1792 considered to be a "co-result". Such CR Field "co-result" arithmeric
1793 operations are firmly out of scope for this section, being covered fully
1794 by [[sv/normal]].
1795
1796 * Examples of v3.0B instructions to which this section does
1797 apply is
1798 - `mfcr` and `cmpi` (3 bit operands) and
1799 - `crnor` and `crand` (5 bit operands).
1800 * Examples to which this section does **not** apply include
1801 `fadds.` and `subf.` which both produce arithmetic results
1802 (and a CR Field co-result).
1803
1804 The CR Mode Format still applies to `sv.cmpi` because despite
1805 taking a GPR as input, the output from the Base Scalar v3.0B `cmpi`
1806 instruction is purely to a Condition Register Field.
1807
1808 Other modes are still applicable and include:
1809
1810 * **Data-dependent fail-first**.
1811 useful to truncate VL based on analysis of a Condition Register result bit.
1812 * **Reduction**.
1813 Reduction is useful for analysing a Vector of Condition Register Fields
1814 and reducing it to one single Condition Register Field.
1815
1816 Predicate-result does not make any sense because when Rc=1 a co-result
1817 is created (a CR Field). Testing the co-result allows the decision to
1818 be made to store or not store the main result, and for CR Ops the CR
1819 Field result *is* the main result.
1820
1821 ## Format
1822
1823 SVP64 RM `MODE` (includes `ELWIDTH_SRC` bits) for CR-based operations:
1824
1825 |6 | 7 |19-20| 21 | 22 23 | description |
1826 |--|---|-----| --- |---------|----------------- |
1827 |/ | / |0 RG | 0 | dz sz | simple mode |
1828 |/ | / |0 RG | 1 | dz sz | scalar reduce mode (mapreduce) |
1829 |zz|SNZ|1 VLI| inv | CR-bit | Ffirst 3-bit mode |
1830 |/ |SNZ|1 VLI| inv | dz sz | Ffirst 5-bit mode (implies CR-bit from result) |
1831
1832 Fields:
1833
1834 * **sz / dz** if predication is enabled will put zeros into the dest
1835 (or as src in the case of twin pred) when the predicate bit is zero.
1836 otherwise the element is ignored or skipped, depending on context.
1837 * **zz** set both sz and dz equal to this flag
1838 * **SNZ** In fail-first mode, on the bit being tested, when sz=1 and
1839 SNZ=1 a value "1" is put in place of "0".
1840 * **inv CR-bit** just as in branches (BO) these bits allow testing of
1841 a CR bit and whether it is set (inv=0) or unset (inv=1)
1842 * **RG** inverts the Vector Loop order (VL-1 downto 0) rather
1843 than the normal 0..VL-1
1844 * **SVM** sets "subvector" reduce mode
1845 * **VLi** VL inclusive: in fail-first mode, the truncation of
1846 VL *includes* the current element at the failure point rather
1847 than excludes it from the count.
1848
1849 ## Data-dependent fail-first on CR operations
1850
1851 The principle of data-dependent fail-first is that if, during the course
1852 of sequentially evaluating an element's Condition Test, one such test
1853 is encountered which fails, then VL (Vector Length) is truncated (set)
1854 at that point. In the case of Arithmetic SVP64 Operations the Condition
1855 Register Field generated from Rc=1 is used as the basis for the truncation
1856 decision. However with CR-based operations that CR Field result to be
1857 tested is provided *by the operation itself*.
1858
1859 Data-dependent SVP64 Vectorised Operations involving the creation
1860 or modification of a CR can require an extra two bits, which are not
1861 available in the compact space of the SVP64 RM `MODE` Field. With the
1862 concept of element width overrides being meaningless for CR Fields it
1863 is possible to use the `ELWIDTH` field for alternative purposes.
1864
1865 Condition Register based operations such as `sv.mfcr` and `sv.crand`
1866 can thus be made more flexible. However the rules that apply in this
1867 section also apply to future CR-based instructions.
1868
1869 There are two primary different types of CR operations:
1870
1871 * Those which have a 3-bit operand field (referring to a CR Field)
1872 * Those which have a 5-bit operand (referring to a bit within the
1873 whole 32-bit CR)
1874
1875 Examining these two types it is observed that the difference may
1876 be considered to be that the 5-bit variant *already* provides the
1877 prerequisite information about which CR Field bit (EQ, GE, LT, SO) is
1878 to be operated on by the instruction. Thus, logically, we may set the
1879 following rule:
1880
1881 * When a 5-bit CR Result field is used in an instruction, the
1882 5-bit variant of Data-Dependent Fail-First
1883 must be used. i.e. the bit of the CR field to be tested is
1884 the one that has just been modified (created) by the operation.
1885 * When a 3-bit CR Result field is used the 3-bit variant
1886 must be used, providing as it does the missing `CRbit` field
1887 in order to select which CR Field bit of the result shall
1888 be tested (EQ, LE, GE, SO)
1889
1890 The reason why the 3-bit CR variant needs the additional CR-bit field
1891 should be obvious from the fact that the 3-bit CR Field from the base
1892 Power ISA v3.0B operation clearly does not contain and is missing the
1893 two CR Field Selector bits. Thus, these two bits (to select EQ, LE,
1894 GE or SO) must be provided in another way.
1895
1896 Examples of the former type:
1897
1898 * crand, cror, crnor. These all are 5-bit (BA, BB, BT). The bit
1899 to be tested against `inv` is the one selected by `BT`
1900 * mcrf. This has only 3-bit (BF, BFA). In order to select the
1901 bit to be tested, the alternative encoding must be used.
1902 With `CRbit` coming from the SVP64 RM bits 22-23 the bit
1903 of BF to be tested is identified.
1904
1905 Just as with SVP64 [[sv/branches]] there is the option to truncate
1906 VL to include the element being tested (`VLi=1`) and to exclude it
1907 (`VLi=0`).
1908
1909 Also exactly as with [[sv/normal]] fail-first, VL cannot, unlike
1910 [[sv/ldst]], be set to an arbitrary value. Deterministic behaviour
1911 is *required*.
1912
1913 ## Reduction and Iteration
1914
1915 Bearing in mind as described in the svp64 Appendix, SVP64 Horizontal
1916 Reduction is a deterministic schedule on top of base Scalar v3.0
1917 operations, the same rules apply to CR Operations, i.e. that programmers
1918 must follow certain conventions in order for an *end result* of a
1919 reduction to be achieved. Unlike other Vector ISAs *there are no explicit
1920 reduction opcodes* in SVP64: Schedules however achieve the same effect.
1921
1922 Due to these conventions only reduction on operations such as `crand`
1923 and `cror` are meaningful because these have Condition Register Fields
1924 as both input and output. Meaningless operations are not prohibited
1925 because the cost in hardware of doing so is prohibitive, but neither
1926 are they `UNDEFINED`. Implementations are still required to execute them
1927 but are at liberty to optimise out any operations that would ultimately
1928 be overwritten, as long as Strict Program Order is still obvservable by
1929 the programmer.
1930
1931 Also bear in mind that 'Reverse Gear' may be enabled, which can be
1932 used in combination with overlapping CR operations to iteratively
1933 accumulate results. Issuing a `sv.crand` operation for example with
1934 `BA` differing from `BB` by one Condition Register Field would result
1935 in a cascade effect, where the first-encountered CR Field would set the
1936 result to zero, and also all subsequent CR Field elements thereafter:
1937
1938 ```
1939 # sv.crand/mr/rg CR4.ge.v, CR5.ge.v, CR4.ge.v
1940 for i in VL-1 downto 0 # reverse gear
1941 CR.field[4+i].ge &= CR.field[5+i].ge
1942 ```
1943
1944 `sv.crxor` with reduction would be particularly useful for parity
1945 calculation for example, although there are many ways in which the same
1946 calculation could be carried out after transferring a vector of CR Fields
1947 to a GPR using crweird operations.
1948
1949 Implementations are free and clear to optimise these reductions in any way
1950 they see fit, as long as the end-result is compatible with Strict Program
1951 Order being observed, and Interrupt latency is not adversely impacted.
1952
1953 ## Unusual and quirky CR operations
1954
1955 **cmp and other compare ops**
1956
1957 `cmp` and `cmpi` etc take GPRs as sources and create a CR Field as a result.
1958
1959 cmpli BF,L,RA,UI
1960 cmpeqb BF,RA,RB
1961
1962 With `ELWIDTH` applying to the source GPR operands this is perfectly fine.
1963
1964 **crweird operations**
1965
1966 There are 4 weird CR-GPR operations and one reasonable one in
1967 the [[cr_int_predication]] set:
1968
1969 * crrweird
1970 * mtcrweird
1971 * crweirder
1972 * crweird
1973 * mcrfm - reasonably normal and referring to CR Fields for src and dest.
1974
1975 The "weird" operations have a non-standard behaviour, being able to
1976 treat *individual bits* of a GPR effectively as elements. They are
1977 expected to be Micro-coded by most Hardware implementations.
1978
1979
1980 --------
1981
1982 \newpage{}
1983
1984 # SVP64 Branch Conditional behaviour
1985
1986 Please note: although similar, SVP64 Branch instructions should be
1987 considered completely separate and distinct from standard scalar
1988 OpenPOWER-approved v3.0B branches. **v3.0B branches are in no way
1989 impacted, altered, changed or modified in any way, shape or form by the
1990 SVP64 Vectorised Variants**.
1991
1992 It is also extremely important to note that Branches are the sole
1993 pseudo-exception in SVP64 to `Scalar Identity Behaviour`. SVP64 Branches
1994 contain additional modes that are useful for scalar operations (i.e. even
1995 when VL=1 or when using single-bit predication).
1996
1997 **Rationale**
1998
1999 Scalar 3.0B Branch Conditional operations, `bc`, `bctar` etc. test
2000 a Condition Register. However for parallel processing it is simply
2001 impossible to perform multiple independent branches: the Program
2002 Counter simply cannot branch to multiple destinations based on multiple
2003 conditions. The best that can be done is to test multiple Conditions
2004 and make a decision of a *single* branch, based on analysis of a *Vector*
2005 of CR Fields which have just been calculated from a *Vector* of results.
2006
2007 In 3D Shader binaries, which are inherently parallelised and predicated,
2008 testing all or some results and branching based on multiple tests is
2009 extremely common, and a fundamental part of Shader Compilers. Example:
2010 without such multi-condition test-and-branch, if a predicate mask is
2011 all zeros a large batch of instructions may be masked out to `nop`,
2012 and it would waste CPU cycles to run them. 3D GPU ISAs can test for
2013 this scenario and, with the appropriate predicate-analysis instruction,
2014 jump over fully-masked-out operations, by spotting that *all* Conditions
2015 are false.
2016
2017 Unless Branches are aware and capable of such analysis, additional
2018 instructions would be required which perform Horizontal Cumulative
2019 analysis of Vectorised Condition Register Fields, in order to reduce
2020 the Vector of CR Fields down to one single yes or no decision that a
2021 Scalar-only v3.0B Branch-Conditional could cope with. Such instructions
2022 would be unavoidable, required, and costly by comparison to a single
2023 Vector-aware Branch. Therefore, in order to be commercially competitive,
2024 `sv.bc` and other Vector-aware Branch Conditional instructions are a
2025 high priority for 3D GPU (and OpenCL-style) workloads.
2026
2027 Given that Power ISA v3.0B is already quite powerful, particularly
2028 the Condition Registers and their interaction with Branches, there are
2029 opportunities to create extremely flexible and compact Vectorised Branch
2030 behaviour. In addition, the side-effects (updating of CTR, truncation
2031 of VL, described below) make it a useful instruction even if the branch
2032 points to the next instruction (no actual branch).
2033
2034 ## Overview
2035
2036 When considering an "array" of branch-tests, there are four
2037 primarily-useful modes: AND, OR, NAND and NOR of all Conditions.
2038 NAND and NOR may be synthesised from AND and OR by inverting `BO[1]`
2039 which just leaves two modes:
2040
2041 * Branch takes place on the **first** CR Field test to succeed
2042 (a Great Big OR of all condition tests). Exit occurs
2043 on the first **successful** test.
2044 * Branch takes place only if **all** CR field tests succeed:
2045 a Great Big AND of all condition tests. Exit occurs
2046 on the first **failed** test.
2047
2048 Early-exit is enacted such that the Vectorised Branch does not
2049 perform needless extra tests, which will help reduce reads on
2050 the Condition Register file.
2051
2052 *Note: Early-exit is **MANDATORY** (required) behaviour. Branches
2053 **MUST** exit at the first sequentially-encountered failure point,
2054 for exactly the same reasons for which it is mandatory in programming
2055 languages doing early-exit: to avoid damaging side-effects and to provide
2056 deterministic behaviour. Speculative testing of Condition Register
2057 Fields is permitted, as is speculative calculation of CTR, as long as,
2058 as usual in any Out-of-Order microarchitecture, that speculative testing
2059 is cancelled should an early-exit occur. i.e. the speculation must be
2060 "precise": Program Order must be preserved*
2061
2062 Also note that when early-exit occurs in Horizontal-first Mode, srcstep,
2063 dststep etc. are all reset, ready to begin looping from the beginning
2064 for the next instruction. However for Vertical-first Mode srcstep
2065 etc. are incremented "as usual" i.e. an early-exit has no special impact,
2066 regardless of whether the branch occurred or not. This can leave srcstep
2067 etc. in what may be considered an unusual state on exit from a loop and
2068 it is up to the programmer to reset srcstep, dststep etc. to known-good
2069 values *(easily achieved with `setvl`)*.
2070
2071 Additional useful behaviour involves two primary Modes (both of which
2072 may be enabled and combined):
2073
2074 * **VLSET Mode**: identical to Data-Dependent Fail-First Mode
2075 for Arithmetic SVP64 operations, with more
2076 flexibility and a close interaction and integration into the
2077 underlying base Scalar v3.0B Branch instruction.
2078 Truncation of VL takes place around the early-exit point.
2079 * **CTR-test Mode**: gives much more flexibility over when and why
2080 CTR is decremented, including options to decrement if a Condition
2081 test succeeds *or if it fails*.
2082
2083 With these side-effects, basic Boolean Logic Analysis advises that it
2084 is important to provide a means to enact them each based on whether
2085 testing succeeds *or fails*. This results in a not-insignificant number
2086 of additional Mode Augmentation bits, accompanying VLSET and CTR-test
2087 Modes respectively.
2088
2089 Predicate skipping or zeroing may, as usual with SVP64, be controlled by
2090 `sz`. Where the predicate is masked out and zeroing is enabled, then in
2091 such circumstances the same Boolean Logic Analysis dictates that rather
2092 than testing only against zero, the option to test against one is also
2093 prudent. This introduces a new immediate field, `SNZ`, which works in
2094 conjunction with `sz`.
2095
2096 Vectorised Branches can be used in either SVP64 Horizontal-First or
2097 Vertical-First Mode. Essentially, at an element level, the behaviour
2098 is identical in both Modes, although the `ALL` bit is meaningless in
2099 Vertical-First Mode.
2100
2101 It is also important to bear in mind that, fundamentally, Vectorised
2102 Branch-Conditional is still extremely close to the Scalar v3.0B
2103 Branch-Conditional instructions, and that the same v3.0B Scalar
2104 Branch-Conditional instructions are still *completely separate and
2105 independent*, being unaltered and unaffected by their SVP64 variants in
2106 every conceivable way.
2107
2108 *Programming note: One important point is that SVP64 instructions are
2109 64 bit. (8 bytes not 4). This needs to be taken into consideration
2110 when computing branch offsets: the offset is relative to the start of
2111 the instruction, which **includes** the SVP64 Prefix*
2112
2113 ## Format and fields
2114
2115 With element-width overrides being meaningless for Condition Register
2116 Fields, bits 4 thru 7 of SVP64 RM may be used for additional Mode bits.
2117
2118 SVP64 RM `MODE` (includes repurposing `ELWIDTH` bits 4:5, and
2119 `ELWIDTH_SRC` bits 6-7 for *alternate* uses) for Branch Conditional:
2120
2121 | 4 | 5 | 6 | 7 | 17 | 18 | 19 | 20 | 21 | 22 23 | description |
2122 | - | - | - | - | -- | -- | -- | -- | --- |--------|----------------- |
2123 |ALL|SNZ| / | / | SL |SLu | 0 | 0 | / | LRu sz | simple mode |
2124 |ALL|SNZ| / |VSb| SL |SLu | 0 | 1 | VLI | LRu sz | VLSET mode |
2125 |ALL|SNZ|CTi| / | SL |SLu | 1 | 0 | / | LRu sz | CTR-test mode |
2126 |ALL|SNZ|CTi|VSb| SL |SLu | 1 | 1 | VLI | LRu sz | CTR-test+VLSET mode |
2127
2128 Brief description of fields:
2129
2130 * **sz=1** if predication is enabled and `sz=1` and a predicate
2131 element bit is zero, `SNZ` will
2132 be substituted in place of the CR bit selected by `BI`,
2133 as the Condition tested.
2134 Contrast this with
2135 normal SVP64 `sz=1` behaviour, where *only* a zero is put in
2136 place of masked-out predicate bits.
2137 * **sz=0** When `sz=0` skipping occurs as usual on
2138 masked-out elements, but unlike all
2139 other SVP64 behaviour which entirely skips an element with
2140 no related side-effects at all, there are certain
2141 special circumstances where CTR
2142 may be decremented. See CTR-test Mode, below.
2143 * **ALL** when set, all branch conditional tests must pass in order for
2144 the branch to succeed. When clear, it is the first sequentially
2145 encountered successful test that causes the branch to succeed.
2146 This is identical behaviour to how programming languages perform
2147 early-exit on Boolean Logic chains.
2148 * **VLI** VLSET is identical to Data-dependent Fail-First mode.
2149 In VLSET mode, VL *may* (depending on `VSb`) be truncated.
2150 If VLI (Vector Length Inclusive) is clear,
2151 VL is truncated to *exclude* the current element, otherwise it is
2152 included. SVSTATE.MVL is not altered: only VL.
2153 * **SL** identical to `LR` except applicable to SVSTATE. If `SL`
2154 is set, SVSTATE is transferred to SVLR (conditionally on
2155 whether `SLu` is set).
2156 * **SLu**: SVSTATE Link Update, like `LRu` except applies to SVSTATE.
2157 * **LRu**: Link Register Update, used in conjunction with LK=1
2158 to make LR update conditional
2159 * **VSb** In VLSET Mode, after testing,
2160 if VSb is set, VL is truncated if the test succeeds. If VSb is clear,
2161 VL is truncated if a test *fails*. Masked-out (skipped)
2162 bits are not considered
2163 part of testing when `sz=0`
2164 * **CTi** CTR inversion. CTR-test Mode normally decrements per element
2165 tested. CTR inversion decrements if a test *fails*. Only relevant
2166 in CTR-test Mode.
2167
2168 LRu and CTR-test modes are where SVP64 Branches subtly differ from
2169 Scalar v3.0B Branches. `sv.bcl` for example will always update LR,
2170 whereas `sv.bcl/lru` will only update LR if the branch succeeds.
2171
2172 Of special interest is that when using ALL Mode (Great Big AND of all
2173 Condition Tests), if `VL=0`, which is rare but can occur in Data-Dependent
2174 Modes, the Branch will always take place because there will be no failing
2175 Condition Tests to prevent it. Likewise when not using ALL Mode (Great
2176 Big OR of all Condition Tests) and `VL=0` the Branch is guaranteed not
2177 to occur because there will be no *successful* Condition Tests to make
2178 it happen.
2179
2180 ## Vectorised CR Field numbering, and Scalar behaviour
2181
2182 It is important to keep in mind that just like all SVP64 instructions,
2183 the `BI` field of the base v3.0B Branch Conditional instruction may be
2184 extended by SVP64 EXTRA augmentation, as well as be marked as either
2185 Scalar or Vector. It is also crucially important to keep in mind that for
2186 CRs, SVP64 sequentially increments the CR *Field* numbers. CR *Fields*
2187 are treated as elements, not bit-numbers of the CR *register*.
2188
2189 The `BI` operand of Branch Conditional operations is five bits, in scalar
2190 v3.0B this would select one bit of the 32 bit CR, comprising eight CR
2191 Fields of 4 bits each. In SVP64 there are 16 32 bit CRs, containing
2192 128 4-bit CR Fields. Therefore, the 2 LSBs of `BI` select the bit from
2193 the CR Field (EQ LT GT SO), and the top 3 bits are extended to either
2194 scalar or vector and to select CR Fields 0..127 as specified in SVP64
2195 [[sv/svp64/appendix]].
2196
2197 When the CR Fields selected by SVP64-Augmented `BI` is marked as scalar,
2198 then as the usual SVP64 rules apply: the Vector loop ends at the first
2199 element tested (the first CR *Field*), after taking predication into
2200 consideration. Thus, also as usual, when a predicate mask is given, and
2201 `BI` marked as scalar, and `sz` is zero, srcstep skips forward to the
2202 first non-zero predicated element, and only that one element is tested.
2203
2204 In other words, the fact that this is a Branch Operation (instead of an
2205 arithmetic one) does not result, ultimately, in significant changes as
2206 to how SVP64 is fundamentally applied, except with respect to:
2207
2208 * the unique properties associated with conditionally
2209 changing the Program Counter (aka "a Branch"), resulting in early-out
2210 opportunities
2211 * CTR-testing
2212
2213 Both are outlined below, in later sections.
2214
2215 ## Horizontal-First and Vertical-First Modes
2216
2217 In SVP64 Horizontal-First Mode, the first failure in ALL mode (Great Big
2218 AND) results in early exit: no more updates to CTR occur (if requested);
2219 no branch occurs, and LR is not updated (if requested). Likewise for
2220 non-ALL mode (Great Big Or) on first success early exit also occurs,
2221 however this time with the Branch proceeding. In both cases the testing
2222 of the Vector of CRs should be done in linear sequential order (or in
2223 REMAP re-sequenced order): such that tests that are sequentially beyond
2224 the exit point are *not* carried out. (*Note: it is standard practice
2225 in Programming languages to exit early from conditional tests, however a
2226 little unusual to consider in an ISA that is designed for Parallel Vector
2227 Processing. The reason is to have strictly-defined guaranteed behaviour*)
2228
2229 In Vertical-First Mode, setting the `ALL` bit results in `UNDEFINED`
2230 behaviour. Given that only one element is being tested at a time in
2231 Vertical-First Mode, a test designed to be done on multiple bits is
2232 meaningless.
2233
2234 ## Description and Modes
2235
2236 Predication in both INT and CR modes may be applied to `sv.bc` and other
2237 SVP64 Branch Conditional operations, exactly as they may be applied to
2238 other SVP64 operations. When `sz` is zero, any masked-out Branch-element
2239 operations are not included in condition testing, exactly like all other
2240 SVP64 operations, *including* side-effects such as potentially updating
2241 LR or CTR, which will also be skipped. There is *one* exception here,
2242 which is when `BO[2]=0, sz=0, CTR-test=0, CTi=1` and the relevant element
2243 predicate mask bit is also zero: under these special circumstances CTR
2244 will also decrement.
2245
2246 When `sz` is non-zero, this normally requests insertion of a zero in
2247 place of the input data, when the relevant predicate mask bit is zero.
2248 This would mean that a zero is inserted in place of `CR[BI+32]` for
2249 testing against `BO`, which may not be desirable in all circumstances.
2250 Therefore, an extra field is provided `SNZ`, which, if set, will insert
2251 a **one** in place of a masked-out element, instead of a zero.
2252
2253 (*Note: Both options are provided because it is useful to deliberately
2254 cause the Branch-Conditional Vector testing to fail at a specific point,
2255 controlled by the Predicate mask. This is particularly useful in `VLSET`
2256 mode, which will truncate SVSTATE.VL at the point of the first failed
2257 test.*)
2258
2259 Normally, CTR mode will decrement once per Condition Test, resulting under
2260 normal circumstances that CTR reduces by up to VL in Horizontal-First
2261 Mode. Just as when v3.0B Branch-Conditional saves at least one instruction
2262 on tight inner loops through auto-decrementation of CTR, likewise it
2263 is also possible to save instruction count for SVP64 loops in both
2264 Vertical-First and Horizontal-First Mode, particularly in circumstances
2265 where there is conditional interaction between the element computation
2266 and testing, and the continuation (or otherwise) of a given loop. The
2267 potential combinations of interactions is why CTR testing options have
2268 been added.
2269
2270 Also, the unconditional bit `BO[0]` is still relevant when Predication
2271 is applied to the Branch because in `ALL` mode all nonmasked bits have
2272 to be tested, and when `sz=0` skipping occurs. Even when VLSET mode is
2273 not used, CTR may still be decremented by the total number of nonmasked
2274 elements, acting in effect as either a popcount or cntlz depending
2275 on which mode bits are set. In short, Vectorised Branch becomes an
2276 extremely powerful tool.
2277
2278 **Micro-Architectural Implementation Note**: *when implemented on top
2279 of a Multi-Issue Out-of-Order Engine it is possible to pass a copy of
2280 the predicate and the prerequisite CR Fields to all Branch Units, as
2281 well as the current value of CTR at the time of multi-issue, and for
2282 each Branch Unit to compute how many times CTR would be subtracted,
2283 in a fully-deterministic and parallel fashion. A SIMD-based Branch
2284 Unit, receiving and processing multiple CR Fields covered by multiple
2285 predicate bits, would do the exact same thing. Obviously, however, if
2286 CTR is modified within any given loop (mtctr) the behaviour of CTR is
2287 no longer deterministic.*
2288
2289 ### Link Register Update
2290
2291 For a Scalar Branch, unconditional updating of the Link Register LR
2292 is useful and practical. However, if a loop of CR Fields is tested,
2293 unconditional updating of LR becomes problematic.
2294
2295 For example when using `bclr` with `LRu=1,LK=0` in Horizontal-First Mode,
2296 LR's value will be unconditionally overwritten after the first element,
2297 such that for execution (testing) of the second element, LR has the value
2298 `CIA+8`. This is covered in the `bclrl` example, in a later section.
2299
2300 The addition of a LRu bit modifies behaviour in conjunction with LK,
2301 as follows:
2302
2303 * `sv.bc` When LRu=0,LK=0, Link Register is not updated
2304 * `sv.bcl` When LRu=0,LK=1, Link Register is updated unconditionally
2305 * `sv.bcl/lru` When LRu=1,LK=1, Link Register will
2306 only be updated if the Branch Condition fails.
2307 * `sv.bc/lru` When LRu=1,LK=0, Link Register will only be updated if
2308 the Branch Condition succeeds.
2309
2310 This avoids destruction of LR during loops (particularly Vertical-First
2311 ones).
2312
2313 **SVLR and SVSTATE**
2314
2315 For precisely the reasons why `LK=1` was added originally to the Power
2316 ISA, with SVSTATE being a peer of the Program Counter it becomes necessary
2317 to also add an SVLR (SVSTATE Link Register) and corresponding control bits
2318 `SL` and `SLu`.
2319
2320 ### CTR-test
2321
2322 Where a standard Scalar v3.0B branch unconditionally decrements CTR when
2323 `BO[2]` is clear, CTR-test Mode introduces more flexibility which allows
2324 CTR to be used for many more types of Vector loops constructs.
2325
2326 CTR-test mode and CTi interaction is as follows: note that `BO[2]`
2327 is still required to be clear for CTR decrements to be considered,
2328 exactly as is the case in Scalar Power ISA v3.0B
2329
2330 * **CTR-test=0, CTi=0**: CTR decrements on a per-element basis
2331 if `BO[2]` is zero. Masked-out elements when `sz=0` are
2332 skipped (i.e. CTR is *not* decremented when the predicate
2333 bit is zero and `sz=0`).
2334 * **CTR-test=0, CTi=1**: CTR decrements on a per-element basis
2335 if `BO[2]` is zero and a masked-out element is skipped
2336 (`sz=0` and predicate bit is zero). This one special case is the
2337 **opposite** of other combinations, as well as being
2338 completely different from normal SVP64 `sz=0` behaviour)
2339 * **CTR-test=1, CTi=0**: CTR decrements on a per-element basis
2340 if `BO[2]` is zero and the Condition Test succeeds.
2341 Masked-out elements when `sz=0` are skipped (including
2342 not decrementing CTR)
2343 * **CTR-test=1, CTi=1**: CTR decrements on a per-element basis
2344 if `BO[2]` is zero and the Condition Test *fails*.
2345 Masked-out elements when `sz=0` are skipped (including
2346 not decrementing CTR)
2347
2348 `CTR-test=0, CTi=1, sz=0` requires special emphasis because it is the
2349 only time in the entirety of SVP64 that has side-effects when
2350 a predicate mask bit is clear. **All** other SVP64 operations
2351 entirely skip an element when sz=0 and a predicate mask bit is zero.
2352 It is also critical to emphasise that in this unusual mode,
2353 no other side-effects occur: **only** CTR is decremented, i.e. the
2354 rest of the Branch operation is skipped.
2355
2356 ### VLSET Mode
2357
2358 VLSET Mode truncates the Vector Length so that subsequent instructions
2359 operate on a reduced Vector Length. This is similar to Data-dependent
2360 Fail-First and LD/ST Fail-First, where for VLSET the truncation occurs
2361 at the Branch decision-point.
2362
2363 Interestingly, due to the side-effects of `VLSET` mode it is actually
2364 useful to use Branch Conditional even to perform no actual branch
2365 operation, i.e to point to the instruction after the branch. Truncation of
2366 VL would thus conditionally occur yet control flow alteration would not.
2367
2368 `VLSET` mode with Vertical-First is particularly unusual. Vertical-First
2369 is designed to be used for explicit looping, where an explicit call to
2370 `svstep` is required to move both srcstep and dststep on to the next
2371 element, until VL (or other condition) is reached. Vertical-First Looping
2372 is expected (required) to terminate if the end of the Vector, VL, is
2373 reached. If however that loop is terminated early because VL is truncated,
2374 VLSET with Vertical-First becomes meaningless. Resolving this would
2375 require two branches: one Conditional, the other branching unconditionally
2376 to create the loop, where the Conditional one jumps over it.
2377
2378 Therefore, with `VSb`, the option to decide whether truncation should
2379 occur if the branch succeeds *or* if the branch condition fails allows
2380 for the flexibility required. This allows a Vertical-First Branch to
2381 *either* be used as a branch-back (loop) *or* as part of a conditional
2382 exit or function call from *inside* a loop, and for VLSET to be integrated
2383 into both types of decision-making.
2384
2385 In the case of a Vertical-First branch-back (loop), with `VSb=0` the
2386 branch takes place if success conditions are met, but on exit from that
2387 loop (branch condition fails), VL will be truncated. This is extremely
2388 useful.
2389
2390 `VLSET` mode with Horizontal-First when `VSb=0` is still useful, because
2391 it can be used to truncate VL to the first predicated (non-masked-out)
2392 element.
2393
2394 The truncation point for VL, when VLi is clear, must not include skipped
2395 elements that preceded the current element being tested. Example:
2396 `sz=0, VLi=0, predicate mask = 0b110010` and the Condition Register
2397 failure point is at CR Field element 4.
2398
2399 * Testing at element 0 is skipped because its predicate bit is zero
2400 * Testing at element 1 passed
2401 * Testing elements 2 and 3 are skipped because their
2402 respective predicate mask bits are zero
2403 * Testing element 4 fails therefore VL is truncated to **2**
2404 not 4 due to elements 2 and 3 being skipped.
2405
2406 If `sz=1` in the above example *then* VL would have been set to 4 because
2407 in non-zeroing mode the zero'd elements are still effectively part of the
2408 Vector (with their respective elements set to `SNZ`)
2409
2410 If `VLI=1` then VL would be set to 5 regardless of sz, due to being inclusive
2411 of the element actually being tested.
2412
2413 ### VLSET and CTR-test combined
2414
2415 If both CTR-test and VLSET Modes are requested, it is important to
2416 observe the correct order. What occurs depends on whether VLi is enabled,
2417 because VLi affects the length, VL.
2418
2419 If VLi (VL truncate inclusive) is set:
2420
2421 1. compute the test including whether CTR triggers
2422 2. (optionally) decrement CTR
2423 3. (optionally) truncate VL (VSb inverts the decision)
2424 4. decide (based on step 1) whether to terminate looping
2425 (including not executing step 5)
2426 5. decide whether to branch.
2427
2428 If VLi is clear, then when a test fails that element
2429 and any following it
2430 should **not** be considered part of the Vector. Consequently:
2431
2432 1. compute the branch test including whether CTR triggers
2433 2. if the test fails against VSb, truncate VL to the *previous*
2434 element, and terminate looping. No further steps executed.
2435 3. (optionally) decrement CTR
2436 4. decide whether to branch.
2437
2438 ## Boolean Logic combinations
2439
2440 In a Scalar ISA, Branch-Conditional testing even of vector results may be
2441 performed through inversion of tests. NOR of all tests may be performed
2442 by inversion of the scalar condition and branching *out* from the scalar
2443 loop around elements, using scalar operations.
2444
2445 In a parallel (Vector) ISA it is the ISA itself which must perform
2446 the prerequisite logic manipulation. Thus for SVP64 there are an
2447 extraordinary number of nesessary combinations which provide completely
2448 different and useful behaviour. Available options to combine:
2449
2450 * `BO[0]` to make an unconditional branch would seem irrelevant if
2451 it were not for predication and for side-effects (CTR Mode
2452 for example)
2453 * Enabling CTR-test Mode and setting `BO[2]` can still result in the
2454 Branch
2455 taking place, not because the Condition Test itself failed, but
2456 because CTR reached zero **because**, as required by CTR-test mode,
2457 CTR was decremented as a **result** of Condition Tests failing.
2458 * `BO[1]` to select whether the CR bit being tested is zero or nonzero
2459 * `R30` and `~R30` and other predicate mask options including CR and
2460 inverted CR bit testing
2461 * `sz` and `SNZ` to insert either zeros or ones in place of masked-out
2462 predicate bits
2463 * `ALL` or `ANY` behaviour corresponding to `AND` of all tests and
2464 `OR` of all tests, respectively.
2465 * Predicate Mask bits, which combine in effect with the CR being
2466 tested.
2467 * Inversion of Predicate Masks (`~r3` instead of `r3`, or using
2468 `NE` rather than `EQ`) which results in an additional
2469 level of possible ANDing, ORing etc. that would otherwise
2470 need explicit instructions.
2471
2472 The most obviously useful combinations here are to set `BO[1]` to zero
2473 in order to turn `ALL` into Great-Big-NAND and `ANY` into Great-Big-NOR.
2474 Other Mode bits which perform behavioural inversion then have to work
2475 round the fact that the Condition Testing is NOR or NAND. The alternative
2476 to not having additional behavioural inversion (`SNZ`, `VSb`, `CTi`)
2477 would be to have a second (unconditional) branch directly after the first,
2478 which the first branch jumps over. This contrivance is avoided by the
2479 behavioural inversion bits.
2480
2481 ## Pseudocode and examples
2482
2483 Please see the SVP64 appendix regarding CR bit ordering and for
2484 the definition of `CR{n}`
2485
2486 For comparative purposes this is a copy of the v3.0B `bc` pseudocode
2487
2488 ```
2489 if (mode_is_64bit) then M <- 0
2490 else M <- 32
2491 if ¬BO[2] then CTR <- CTR - 1
2492 ctr_ok <- BO[2] | ((CTR[M:63] != 0) ^ BO[3])
2493 cond_ok <- BO[0] | ¬(CR[BI+32] ^ BO[1])
2494 if ctr_ok & cond_ok then
2495 if AA then NIA <-iea EXTS(BD || 0b00)
2496 else NIA <-iea CIA + EXTS(BD || 0b00)
2497 if LK then LR <-iea CIA + 4
2498 ```
2499
2500 Simplified pseudocode including LRu and CTR skipping, which illustrates
2501 clearly that SVP64 Scalar Branches (VL=1) are **not** identical to
2502 v3.0B Scalar Branches. The key areas where differences occur are the
2503 inclusion of predication (which can still be used when VL=1), in when and
2504 why CTR is decremented (CTRtest Mode) and whether LR is updated (which
2505 is unconditional in v3.0B when LK=1, and conditional in SVP64 when LRu=1).
2506
2507 Inline comments highlight the fact that the Scalar Branch behaviour and
2508 pseudocode is still clearly visible and embedded within the Vectorised
2509 variant:
2510
2511 ```
2512 if (mode_is_64bit) then M <- 0
2513 else M <- 32
2514 # the bit of CR to test, if the predicate bit is zero,
2515 # is overridden
2516 testbit = CR[BI+32]
2517 if ¬predicate_bit then testbit = SVRMmode.SNZ
2518 # otherwise apart from the override ctr_ok and cond_ok
2519 # are exactly the same
2520 ctr_ok <- BO[2] | ((CTR[M:63] != 0) ^ BO[3])
2521 cond_ok <- BO[0] | ¬(testbit ^ BO[1])
2522 if ¬predicate_bit & ¬SVRMmode.sz then
2523 # this is entirely new: CTR-test mode still decrements CTR
2524 # even when predicate-bits are zero
2525 if ¬BO[2] & CTRtest & ¬CTi then
2526 CTR = CTR - 1
2527 # instruction finishes here
2528 else
2529 # usual BO[2] CTR-mode now under CTR-test mode as well
2530 if ¬BO[2] & ¬(CTRtest & (cond_ok ^ CTi)) then CTR <- CTR - 1
2531 # new VLset mode, conditional test truncates VL
2532 if VLSET and VSb = (cond_ok & ctr_ok) then
2533 if SVRMmode.VLI then SVSTATE.VL = srcstep+1
2534 else SVSTATE.VL = srcstep
2535 # usual LR is now conditional, but also joined by SVLR
2536 lr_ok <- LK
2537 svlr_ok <- SVRMmode.SL
2538 if ctr_ok & cond_ok then
2539 if AA then NIA <-iea EXTS(BD || 0b00)
2540 else NIA <-iea CIA + EXTS(BD || 0b00)
2541 if SVRMmode.LRu then lr_ok <- ¬lr_ok
2542 if SVRMmode.SLu then svlr_ok <- ¬svlr_ok
2543 if lr_ok then LR <-iea CIA + 4
2544 if svlr_ok then SVLR <- SVSTATE
2545 ```
2546
2547 Below is the pseudocode for SVP64 Branches, which is a little less
2548 obvious but identical to the above. The lack of obviousness is down to
2549 the early-exit opportunities.
2550
2551 Effective pseudocode for Horizontal-First Mode:
2552
2553 ```
2554 if (mode_is_64bit) then M <- 0
2555 else M <- 32
2556 cond_ok = not SVRMmode.ALL
2557 for srcstep in range(VL):
2558 # select predicate bit or zero/one
2559 if predicate[srcstep]:
2560 # get SVP64 extended CR field 0..127
2561 SVCRf = SVP64EXTRA(BI>>2)
2562 CRbits = CR{SVCRf}
2563 testbit = CRbits[BI & 0b11]
2564 # testbit = CR[BI+32+srcstep*4]
2565 else if not SVRMmode.sz:
2566 # inverted CTR test skip mode
2567 if ¬BO[2] & CTRtest & ¬CTI then
2568 CTR = CTR - 1
2569 continue # skip to next element
2570 else
2571 testbit = SVRMmode.SNZ
2572 # actual element test here
2573 ctr_ok <- BO[2] | ((CTR[M:63] != 0) ^ BO[3])
2574 el_cond_ok <- BO[0] | ¬(testbit ^ BO[1])
2575 # check if CTR dec should occur
2576 ctrdec = ¬BO[2]
2577 if CTRtest & (el_cond_ok ^ CTi) then
2578 ctrdec = 0b0
2579 if ctrdec then CTR <- CTR - 1
2580 # merge in the test
2581 if SVRMmode.ALL:
2582 cond_ok &= (el_cond_ok & ctr_ok)
2583 else
2584 cond_ok |= (el_cond_ok & ctr_ok)
2585 # test for VL to be set (and exit)
2586 if VLSET and VSb = (el_cond_ok & ctr_ok) then
2587 if SVRMmode.VLI then SVSTATE.VL = srcstep+1
2588 else SVSTATE.VL = srcstep
2589 break
2590 # early exit?
2591 if SVRMmode.ALL != (el_cond_ok & ctr_ok):
2592 break
2593 # SVP64 rules about Scalar registers still apply!
2594 if SVCRf.scalar:
2595 break
2596 # loop finally done, now test if branch (and update LR)
2597 lr_ok <- LK
2598 svlr_ok <- SVRMmode.SL
2599 if cond_ok then
2600 if AA then NIA <-iea EXTS(BD || 0b00)
2601 else NIA <-iea CIA + EXTS(BD || 0b00)
2602 if SVRMmode.LRu then lr_ok <- ¬lr_ok
2603 if SVRMmode.SLu then svlr_ok <- ¬svlr_ok
2604 if lr_ok then LR <-iea CIA + 4
2605 if svlr_ok then SVLR <- SVSTATE
2606 ```
2607
2608 Pseudocode for Vertical-First Mode:
2609
2610 ```
2611 # get SVP64 extended CR field 0..127
2612 SVCRf = SVP64EXTRA(BI>>2)
2613 CRbits = CR{SVCRf}
2614 # select predicate bit or zero/one
2615 if predicate[srcstep]:
2616 if BRc = 1 then # CR0 vectorised
2617 CR{SVCRf+srcstep} = CRbits
2618 testbit = CRbits[BI & 0b11]
2619 else if not SVRMmode.sz:
2620 # inverted CTR test skip mode
2621 if ¬BO[2] & CTRtest & ¬CTI then
2622 CTR = CTR - 1
2623 SVSTATE.srcstep = new_srcstep
2624 exit # no branch testing
2625 else
2626 testbit = SVRMmode.SNZ
2627 # actual element test here
2628 cond_ok <- BO[0] | ¬(testbit ^ BO[1])
2629 # test for VL to be set (and exit)
2630 if VLSET and cond_ok = VSb then
2631 if SVRMmode.VLI
2632 SVSTATE.VL = new_srcstep+1
2633 else
2634 SVSTATE.VL = new_srcstep
2635 ```
2636
2637 ### Example Shader code
2638
2639 ```
2640 // assume f() g() or h() modify a and/or b
2641 while(a > 2) {
2642 if(b < 5)
2643 f();
2644 else
2645 g();
2646 h();
2647 }
2648 ```
2649
2650 which compiles to something like:
2651
2652 ```
2653 vec<i32> a, b;
2654 // ...
2655 pred loop_pred = a > 2;
2656 // loop continues while any of a elements greater than 2
2657 while(loop_pred.any()) {
2658 // vector of predicate bits
2659 pred if_pred = loop_pred & (b < 5);
2660 // only call f() if at least 1 bit set
2661 if(if_pred.any()) {
2662 f(if_pred);
2663 }
2664 label1:
2665 // loop mask ANDs with inverted if-test
2666 pred else_pred = loop_pred & ~if_pred;
2667 // only call g() if at least 1 bit set
2668 if(else_pred.any()) {
2669 g(else_pred);
2670 }
2671 h(loop_pred);
2672 }
2673 ```
2674
2675 which will end up as:
2676
2677 ```
2678 # start from while loop test point
2679 b looptest
2680 while_loop:
2681 sv.cmpi CR80.v, b.v, 5 # vector compare b into CR64 Vector
2682 sv.bc/m=r30/~ALL/sz CR80.v.LT skip_f # skip when none
2683 # only calculate loop_pred & pred_b because needed in f()
2684 sv.crand CR80.v.SO, CR60.v.GT, CR80.V.LT # if = loop & pred_b
2685 f(CR80.v.SO)
2686 skip_f:
2687 # illustrate inversion of pred_b. invert r30, test ALL
2688 # rather than SOME, but masked-out zero test would FAIL,
2689 # therefore masked-out instead is tested against 1 not 0
2690 sv.bc/m=~r30/ALL/SNZ CR80.v.LT skip_g
2691 # else = loop & ~pred_b, need this because used in g()
2692 sv.crternari(A&~B) CR80.v.SO, CR60.v.GT, CR80.V.LT
2693 g(CR80.v.SO)
2694 skip_g:
2695 # conditionally call h(r30) if any loop pred set
2696 sv.bclr/m=r30/~ALL/sz BO[1]=1 h()
2697 looptest:
2698 sv.cmpi CR60.v a.v, 2 # vector compare a into CR60 vector
2699 sv.crweird r30, CR60.GT # transfer GT vector to r30
2700 sv.bc/m=r30/~ALL/sz BO[1]=1 while_loop
2701 end:
2702 ```
2703
2704 ### LRu example
2705
2706 show why LRu would be useful in a loop. Imagine the following
2707 c code:
2708
2709 ```
2710 for (int i = 0; i < 8; i++) {
2711 if (x < y) break;
2712 }
2713 ```
2714
2715 Under these circumstances exiting from the loop is not only based on
2716 CTR it has become conditional on a CR result. Thus it is desirable that
2717 NIA *and* LR only be modified if the conditions are met
2718
2719 v3.0 pseudocode for `bclrl`:
2720
2721 ```
2722 if (mode_is_64bit) then M <- 0
2723 else M <- 32
2724 if ¬BO[2] then CTR <- CTR - 1
2725 ctr_ok <- BO[2] | ((CTR[M:63] != 0) ^ BO[3])
2726 cond_ok <- BO[0] | ¬(CR[BI+32] ^ BO[1])
2727 if ctr_ok & cond_ok then NIA <-iea LR[0:61] || 0b00
2728 if LK then LR <-iea CIA + 4
2729 ```
2730
2731 the latter part for SVP64 `bclrl` becomes:
2732
2733 ```
2734 for i in 0 to VL-1:
2735 ...
2736 ...
2737 cond_ok <- BO[0] | ¬(CR[BI+32] ^ BO[1])
2738 lr_ok <- LK
2739 if ctr_ok & cond_ok then
2740 NIA <-iea LR[0:61] || 0b00
2741 if SVRMmode.LRu then lr_ok <- ¬lr_ok
2742 if lr_ok then LR <-iea CIA + 4
2743 # if NIA modified exit loop
2744 ```
2745
2746 The reason why should be clear from this being a Vector loop:
2747 unconditional destruction of LR when LK=1 makes `sv.bclrl` ineffective,
2748 because the intention going into the loop is that the branch should be to
2749 the copy of LR set at the *start* of the loop, not half way through it.
2750 However if the change to LR only occurs if the branch is taken then it
2751 becomes a useful instruction.
2752
2753 The following pseudocode should **not** be implemented because it
2754 violates the fundamental principle of SVP64 which is that SVP64 looping
2755 is a thin wrapper around Scalar Instructions. The pseducode below is
2756 more an actual Vector ISA Branch and as such is not at all appropriate:
2757
2758 ```
2759 for i in 0 to VL-1:
2760 ...
2761 ...
2762 cond_ok <- BO[0] | ¬(CR[BI+32] ^ BO[1])
2763 if ctr_ok & cond_ok then NIA <-iea LR[0:61] || 0b00
2764 # only at the end of looping is LK checked.
2765 # this completely violates the design principle of SVP64
2766 # and would actually need to be a separate (scalar)
2767 # instruction "set LR to CIA+4 but retrospectively"
2768 # which is clearly impossible
2769 if LK then LR <-iea CIA + 4
2770 ```
2771
2772 [[!tag opf_rfc]]