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