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