ab_riscv_primitives/instructions/v.rs
1//! V extension
2
3pub mod zve64x;
4
5use crate::registers::general_purpose::{RegType, Register};
6use core::fmt;
7
8/// `mstatus.VS` / `sstatus.VS` / `vsstatus.VS` field encoding.
9///
10/// Context status for the vector extension, analogous to `mstatus.FS`.
11/// Located at bits `[10:9]` in the respective status registers.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13#[repr(u8)]
14pub enum VsStatus {
15 /// Vector unit is off; any vector instruction or CSR access raises illegal instruction
16 Off = 0,
17 /// Vector state is known to be in its initial state
18 Initial = 1,
19 /// Vector state is potentially modified but matches the last saved state
20 Clean = 2,
21 /// Vector state has been modified since the last save
22 Dirty = 3,
23}
24
25impl VsStatus {
26 /// Decode from a 2-bit field value
27 #[inline(always)]
28 pub const fn from_bits(bits: u8) -> Self {
29 match bits & 0b11 {
30 0 => Self::Off,
31 1 => Self::Initial,
32 2 => Self::Clean,
33 _ => Self::Dirty,
34 }
35 }
36
37 /// Encode to a 2-bit field value
38 #[inline(always)]
39 pub const fn to_bits(self) -> u8 {
40 self as u8
41 }
42}
43
44/// Vector length multiplier (LMUL) setting
45///
46/// Encoded in `vtype[2:0]` as a signed 3-bit value.
47/// `LMUL = 2^vlmul` where `vlmul` is sign-extended. Positive values give integer multipliers,
48/// negative values give fractional.
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50#[repr(u8)]
51pub enum Vlmul {
52 /// LMUL = 1 (`vlmul` encoding 0b000)
53 M1 = 0b000,
54 /// LMUL = 2 (`vlmul` encoding 0b001)
55 M2 = 0b001,
56 /// LMUL = 4 (`vlmul` encoding 0b010)
57 M4 = 0b010,
58 /// LMUL = 8 (`vlmul` encoding 0b011)
59 M8 = 0b011,
60 /// LMUL = 1/8 (`vlmul` encoding 0b101)
61 Mf8 = 0b101,
62 /// LMUL = 1/4 (`vlmul` encoding 0b110)
63 Mf4 = 0b110,
64 /// LMUL = 1/2 (`vlmul` encoding 0b111)
65 Mf2 = 0b111,
66}
67
68impl Vlmul {
69 /// Decode from the 3-bit `vlmul` field. Returns `None` for reserved encoding 0b100.
70 #[inline(always)]
71 pub const fn from_bits(bits: u8) -> Option<Self> {
72 match bits & 0b111 {
73 0b000 => Some(Self::M1),
74 0b001 => Some(Self::M2),
75 0b010 => Some(Self::M4),
76 0b011 => Some(Self::M8),
77 0b101 => Some(Self::Mf8),
78 0b110 => Some(Self::Mf4),
79 0b111 => Some(Self::Mf2),
80 _ => None,
81 }
82 }
83
84 /// Encode to the 3-bit `vlmul` field
85 #[inline(always)]
86 pub const fn to_bits(self) -> u8 {
87 self as u8
88 }
89
90 /// Compute `VLMAX = LMUL * VLEN / SEW`.
91 ///
92 /// For fractional LMUL, this is `VLEN / (SEW * denominator)`.
93 /// Returns 0 when the result would be less than 1 (insufficient bits).
94 #[inline(always)]
95 pub const fn vlmax(self, vlen_bits: u32, sew_bits: u32) -> u32 {
96 match self {
97 Self::M1 => vlen_bits / sew_bits,
98 Self::M2 => (vlen_bits * 2) / sew_bits,
99 Self::M4 => (vlen_bits * 4) / sew_bits,
100 Self::M8 => (vlen_bits * 8) / sew_bits,
101 Self::Mf2 => vlen_bits / (sew_bits * 2),
102 Self::Mf4 => vlen_bits / (sew_bits * 4),
103 Self::Mf8 => vlen_bits / (sew_bits * 8),
104 }
105 }
106
107 /// Number of vector registers occupied by one register group at this `LMUL`.
108 ///
109 /// Fractional `LMUL` values (`Mf2`, `Mf4`, `Mf8`) each occupy exactly `1` register.
110 /// Integer `LMUL` values occupy `1`, `2`, `4, or `8` registers respectively.
111 #[inline(always)]
112 pub const fn register_count(self) -> u8 {
113 match self {
114 Self::Mf8 | Self::Mf4 | Self::Mf2 | Self::M1 => 1,
115 Self::M2 => 2,
116 Self::M4 => 4,
117 Self::M8 => 8,
118 }
119 }
120
121 /// LMUL as a `(numerator, denominator)` fraction where `LMUL = num / den`.
122 ///
123 /// Both values are powers of two with exactly one equal to `1`. Useful for computing
124 /// `EMUL = (EEW / SEW) * LMUL` without floating-point arithmetic.
125 #[inline(always)]
126 pub const fn as_fraction(self) -> (u8, u8) {
127 match self {
128 Self::Mf8 => (1, 8),
129 Self::Mf4 => (1, 4),
130 Self::Mf2 => (1, 2),
131 Self::M1 => (1, 1),
132 Self::M2 => (2, 1),
133 Self::M4 => (4, 1),
134 Self::M8 => (8, 1),
135 }
136 }
137
138 /// Compute `EMUL` for an indexed load: `EMUL = (index_eew / sew) * LMUL`.
139 ///
140 /// Returns the register count for the index register group, or `None` when `EMUL` falls
141 /// outside the legal range `[1/8, 8]`.
142 #[inline(always)]
143 pub const fn index_register_count(self, index_eew: Eew, sew: Vsew) -> Option<u8> {
144 let (lmul_num, lmul_den) = self.as_fraction();
145 let num = u16::from(index_eew.bits()) * u16::from(lmul_num);
146 let den = u16::from(sew.bits()) * u16::from(lmul_den);
147 // Both are products of powers of two; GCD equals the smaller value.
148 let g = if num < den { num } else { den };
149 let (n, d) = (num / g, den / g);
150 // Legal EMUL fractions: 1/8, 1/4, 1/2, 1, 2, 4, 8
151 let legal = matches!(
152 (n, d),
153 (1, 8) | (1, 4) | (1, 2) | (1, 1) | (2, 1) | (4, 1) | (8, 1)
154 );
155 if !legal {
156 return None;
157 }
158 // Register count is max(1, n/d) = n when d==1, else 1
159 Some(if d > 1 { 1 } else { n as u8 })
160 }
161}
162
163impl fmt::Display for Vlmul {
164 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165 match self {
166 Self::M1 => write!(f, "m1"),
167 Self::M2 => write!(f, "m2"),
168 Self::M4 => write!(f, "m4"),
169 Self::M8 => write!(f, "m8"),
170 Self::Mf8 => write!(f, "mf8"),
171 Self::Mf4 => write!(f, "mf4"),
172 Self::Mf2 => write!(f, "mf2"),
173 }
174 }
175}
176
177/// Selected element width (SEW).
178///
179/// Encoded in `vtype[5:3]` as `vsew`. `SEW = 8 * 2^vsew`.
180#[derive(Debug, Clone, Copy, PartialEq, Eq)]
181#[repr(u8)]
182pub enum Vsew {
183 /// SEW = 8 bits (vsew = 0b000)
184 E8 = 0b000,
185 /// SEW = 16 bits (vsew = 0b001)
186 E16 = 0b001,
187 /// SEW = 32 bits (vsew = 0b010)
188 E32 = 0b010,
189 /// SEW = 64 bits (vsew = 0b011)
190 E64 = 0b011,
191}
192
193impl Vsew {
194 /// Decode from the 3-bit vsew field. Returns `None` for reserved encodings.
195 #[inline(always)]
196 pub const fn from_bits(bits: u8) -> Option<Self> {
197 match bits & 0b111 {
198 0b000 => Some(Self::E8),
199 0b001 => Some(Self::E16),
200 0b010 => Some(Self::E32),
201 0b011 => Some(Self::E64),
202 _ => None,
203 }
204 }
205
206 /// Encode to the 3-bit vsew field
207 #[inline(always)]
208 pub const fn to_bits(self) -> u8 {
209 self as u8
210 }
211
212 /// Element width in bits
213 #[inline(always)]
214 pub const fn bits(self) -> u8 {
215 match self {
216 Self::E8 => 8,
217 Self::E16 => 16,
218 Self::E32 => 32,
219 Self::E64 => 64,
220 }
221 }
222
223 /// Element width in bytes
224 #[inline(always)]
225 pub const fn bytes(self) -> u8 {
226 match self {
227 Self::E8 => 1,
228 Self::E16 => 2,
229 Self::E32 => 4,
230 Self::E64 => 8,
231 }
232 }
233
234 /// Convert to the corresponding `Eew` variant.
235 ///
236 /// Every valid `Vsew` value has a directly corresponding `Eew` value because both
237 /// enumerate the same set of widths (8/16/32/64 bits). The conversion is always
238 /// successful.
239 #[inline(always)]
240 pub const fn as_eew(self) -> Eew {
241 match self {
242 Self::E8 => Eew::E8,
243 Self::E16 => Eew::E16,
244 Self::E32 => Eew::E32,
245 Self::E64 => Eew::E64,
246 }
247 }
248}
249
250impl fmt::Display for Vsew {
251 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
252 match self {
253 Self::E8 => write!(f, "e8"),
254 Self::E16 => write!(f, "e16"),
255 Self::E32 => write!(f, "e32"),
256 Self::E64 => write!(f, "e64"),
257 }
258 }
259}
260
261/// Effective element width for vector memory operations
262#[derive(Debug, Clone, Copy, PartialEq, Eq)]
263#[repr(u8)]
264pub enum Eew {
265 /// 8-bit elements
266 E8 = 0b000,
267 /// 16-bit elements
268 E16 = 0b101,
269 /// 32-bit elements
270 E32 = 0b110,
271 /// 64-bit elements
272 E64 = 0b111,
273}
274
275impl Eew {
276 /// Max element width in bytes
277 pub const MAX_BYTES: u8 = 8;
278
279 /// Decode the width field into an element width
280 #[inline(always)]
281 pub const fn from_width(width: u8) -> Option<Self> {
282 match width {
283 0b000 => Some(Self::E8),
284 0b101 => Some(Self::E16),
285 0b110 => Some(Self::E32),
286 0b111 => Some(Self::E64),
287 _ => None,
288 }
289 }
290
291 /// Element width in bits
292 #[inline(always)]
293 pub const fn bits(self) -> u8 {
294 match self {
295 Self::E8 => 8,
296 Self::E16 => 16,
297 Self::E32 => 32,
298 Self::E64 => 64,
299 }
300 }
301
302 /// Element width in bytes.
303 ///
304 /// Guaranteed to be `<= Self::MAX_BYTES`.
305 #[inline(always)]
306 pub const fn bytes(self) -> u8 {
307 match self {
308 Self::E8 => 1,
309 Self::E16 => 2,
310 Self::E32 => 4,
311 Self::E64 => 8,
312 }
313 }
314}
315
316impl fmt::Display for Eew {
317 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
318 self.bits().fmt(f)
319 }
320}
321
322/// Vector fixed-point rounding mode.
323///
324/// Encoded in the `vxrm` CSR bits `[1:0]` and mirrored in `vcsr[2:1]`.
325#[derive(Debug, Clone, Copy, PartialEq, Eq)]
326#[repr(u8)]
327pub enum Vxrm {
328 /// Round-to-nearest-up (rnu)
329 Rnu = 0b00,
330 /// Round-to-nearest-even (rne)
331 Rne = 0b01,
332 /// Round-down / truncate (rdn)
333 Rdn = 0b10,
334 /// Round-to-odd (rod)
335 Rod = 0b11,
336}
337
338impl Vxrm {
339 /// Decode from a 2-bit field
340 #[inline(always)]
341 pub const fn from_bits(bits: u8) -> Self {
342 match bits & 0b11 {
343 0b00 => Self::Rnu,
344 0b01 => Self::Rne,
345 0b10 => Self::Rdn,
346 _ => Self::Rod,
347 }
348 }
349
350 /// Encode to a 2-bit field
351 #[inline(always)]
352 pub const fn to_bits(self) -> u8 {
353 self as u8
354 }
355}
356
357/// Decoded `vtype` register contents.
358///
359/// The vtype CSR controls the interpretation of the vector register file: element width, register
360/// grouping, and tail/mask agnostic policies.
361///
362/// The raw encoding is XLEN-dependent (vill is at bit XLEN-1), but this decoded form is
363/// XLEN-independent.
364#[derive(Debug, Clone, Copy, PartialEq, Eq)]
365pub struct Vtype<const ELEN: u32, const VLEN: u32> {
366 /// Vector mask agnostic policy (bit `7`)
367 vma: bool,
368 /// Vector tail agnostic policy (bit `6`)
369 vta: bool,
370 /// Selected element width (bits `[5:3]`)
371 vsew: Vsew,
372 /// Vector length multiplier (bits `[2:0]`)
373 vlmul: Vlmul,
374}
375
376impl<const ELEN: u32, const VLEN: u32> Vtype<ELEN, VLEN> {
377 /// Vector mask agnostic policy (bit `7`)
378 pub const fn vma(&self) -> bool {
379 self.vma
380 }
381
382 /// Vector tail agnostic policy (bit `6`)
383 pub const fn vta(&self) -> bool {
384 self.vta
385 }
386
387 /// Selected element width (bits `[5:3]`)
388 pub const fn vsew(&self) -> Vsew {
389 self.vsew
390 }
391
392 /// Vector length multiplier (bits `[2:0]`)
393 pub const fn vlmul(&self) -> Vlmul {
394 self.vlmul
395 }
396
397 /// Decode from raw register value.
398 ///
399 /// The `XLEN` is taken from `Reg::XLEN` and must be 32 for RV32 or 64 for RV64. The `vill` bit
400 /// is placed at bit position `Reg::XLEN - 1`.
401 ///
402 /// All bits in `[Reg::XLEN-1:8]` must be zero; non-zero bits indicate an unrecognized
403 /// encoding and cause `None` to be returned (this includes `vill`).
404 #[inline(always)]
405 pub const fn from_raw<Reg>(raw: Reg::Type) -> Option<Self>
406 where
407 Reg: [const] Register,
408 {
409 let raw = raw.as_u64();
410
411 // All bits in [XLEN-1:8] must be zero
412 if (raw >> 8) != 0 {
413 return None;
414 }
415
416 let vlmul_bits = (raw & 0b111) as u8;
417 let vsew_bits = ((raw >> 3) & 0b111) as u8;
418 let vta = ((raw >> 6) & 1) != 0;
419 let vma = ((raw >> 7) & 1) != 0;
420
421 let vlmul = Vlmul::from_bits(vlmul_bits)?;
422 let vsew = Vsew::from_bits(vsew_bits)?;
423
424 let sew = vsew.bits();
425 if u32::from(sew) > ELEN {
426 return None;
427 }
428
429 if vlmul.vlmax(VLEN, u32::from(sew)) == 0 {
430 return None;
431 }
432
433 Some(Self {
434 vma,
435 vta,
436 vsew,
437 vlmul,
438 })
439 }
440
441 /// Encode to a raw `vtype` register value of type `Reg::Type`.
442 ///
443 /// The encoded value contains `vlmul`, `vsew`, `vta`, and `vma` in bits `[7:0]` with
444 /// `vill = 0`. To construct a raw value with `vill = 1` (illegal configuration), use
445 /// [`Self::illegal_raw`].
446 #[inline(always)]
447 pub const fn to_raw<Reg>(self) -> Reg::Type
448 where
449 Reg: [const] Register,
450 {
451 let mut raw = 0u8;
452 raw |= self.vlmul.to_bits();
453 raw |= self.vsew.to_bits() << 3;
454
455 if self.vta {
456 raw |= 1 << 6;
457 }
458
459 if self.vma {
460 raw |= 1 << 7;
461 }
462
463 Reg::Type::from(raw)
464 }
465
466 /// Construct a raw value for `vtype` with `vill=1` (illegal configuration).
467 ///
468 /// Per spec: when `vill` is set, the remaining bits are zero and `vl` is also set to zero. Any
469 /// subsequent vector instruction that depends on `vtype` will raise an illegal-instruction
470 /// exception.
471 #[inline(always)]
472 pub const fn illegal_raw<Reg>() -> Reg::Type
473 where
474 Reg: [const] Register,
475 {
476 let vill_bit = Reg::XLEN - 1;
477 Reg::Type::from(1u8) << vill_bit
478 }
479}