Skip to main content

ab_riscv_primitives/instructions/
v.rs

1//! V extension
2
3#[cfg(test)]
4mod tests;
5pub mod zvexx;
6
7use crate::hart::{HartConfig, VectorHartConfig};
8use crate::instructions::{ImplementedExtension, Instruction, IsaExtension};
9use crate::registers::general_purpose::{RegType, Register};
10use core::hint::cold_path;
11use core::marker::{ConstParamTy, PhantomData};
12use core::ops::RangeInclusive;
13use core::{cmp, fmt};
14
15/// Vector register width `VLEN` of hart configuration, usable as a const generic argument
16const HART_VLEN<Hart: VectorHartConfig>: Vlen = Hart::VECTOR_LENGTHS.vlen;
17
18/// Vector start element index
19#[derive(Debug, Clone, Copy)]
20#[derive_const(Default, PartialEq, Eq, Ord, PartialOrd)]
21pub struct Vstart(u16);
22
23impl fmt::Display for Vstart {
24    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25        write!(f, "{}", self.0)
26    }
27}
28
29const impl From<u16> for Vstart {
30    #[inline(always)]
31    fn from(value: u16) -> Self {
32        Self(value)
33    }
34}
35
36const impl From<Vstart> for u16 {
37    #[inline(always)]
38    fn from(value: Vstart) -> Self {
39        value.0
40    }
41}
42
43impl PartialEq<Vl> for Vstart {
44    fn eq(&self, other: &Vl) -> bool {
45        u32::from(self.0) == u32::from(*other)
46    }
47}
48
49impl PartialOrd<Vl> for Vstart {
50    #[inline(always)]
51    fn partial_cmp(&self, other: &Vl) -> Option<cmp::Ordering> {
52        Some(u32::from(self.0).cmp(&u32::from(*other)))
53    }
54}
55
56impl Vstart {
57    /// Zero vector start element index
58    pub const ZERO: Self = Self(0);
59
60    /// Returns a range of vector offsets from `self` to `vl`.
61    ///
62    /// Note: the range might be empty if `vl` is zero.
63    #[inline(always)]
64    pub const fn range_to(self, vl: Vl) -> RangeInclusive<u16> {
65        let vl = u32::from(vl);
66        if vl == 0 {
67            // Empty range
68            #[expect(clippy::reversed_empty_ranges, reason = "Intentional empty range")]
69            {
70                1..=0
71            }
72        } else {
73            self.0..=(vl - 1) as u16
74        }
75    }
76}
77
78/// Vector length
79#[derive(Debug, Clone, Copy)]
80#[derive_const(Default, PartialEq, Eq, Ord, PartialOrd)]
81pub struct Vl(u32);
82
83impl fmt::Display for Vl {
84    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85        write!(f, "{}", self.0)
86    }
87}
88
89const impl From<u8> for Vl {
90    #[inline(always)]
91    fn from(value: u8) -> Self {
92        Self(u32::from(value))
93    }
94}
95
96const impl From<u16> for Vl {
97    #[inline(always)]
98    fn from(value: u16) -> Self {
99        Self(u32::from(value))
100    }
101}
102
103const impl From<Vl> for u32 {
104    #[inline(always)]
105    fn from(value: Vl) -> Self {
106        value.0
107    }
108}
109
110const impl From<Vl> for u64 {
111    #[inline(always)]
112    fn from(value: Vl) -> Self {
113        u64::from(value.0)
114    }
115}
116
117impl PartialEq<Vstart> for Vl {
118    fn eq(&self, other: &Vstart) -> bool {
119        self.0 == u32::from(u16::from(*other))
120    }
121}
122
123impl PartialOrd<Vstart> for Vl {
124    #[inline(always)]
125    fn partial_cmp(&self, other: &Vstart) -> Option<cmp::Ordering> {
126        Some(self.0.cmp(&u32::from(u16::from(*other))))
127    }
128}
129
130impl Vl {
131    /// Zero vector length
132    pub const ZERO: Self = Self(0);
133
134    /// Create a new vector length from a value.
135    ///
136    /// Returns `None` if the value is greater than the maximum vector length.
137    #[inline(always)]
138    pub const fn new(n: u32) -> Option<Self> {
139        if n > u32::from(Vlen::L65_536) {
140            None
141        } else {
142            Some(Self(n))
143        }
144    }
145
146    /// Create a new vector length from a value with saturation
147    #[inline(always)]
148    pub const fn new_saturating(n: u32) -> Self {
149        let n = u32::from(Vlen::L65_536).min(n);
150        Self(n)
151    }
152
153    /// Returns the vector length in bytes
154    #[inline(always)]
155    pub const fn bytes(self) -> u16 {
156        self.0.div_ceil(u8::BITS) as u16
157    }
158}
159
160/// Element length
161#[derive(ConstParamTy, Debug, Clone, Copy)]
162#[derive_const(PartialEq, Eq, PartialOrd, Ord)]
163#[repr(u32)]
164pub enum Elen {
165    /// Element length is 8 bits
166    L8 = 8,
167    /// Element length is 16 bits
168    L16 = 16,
169    /// Element length is 32 bits
170    L32 = 32,
171    /// Element length is 64 bits
172    L64 = 64,
173    /// Element length is 128 bits
174    L128 = 128,
175    /// Element length is 256 bits
176    L256 = 256,
177    /// Element length is 512 bits
178    L512 = 512,
179    /// Element length is 1024 bits
180    L1024 = 1024,
181    /// Element length is 2048 bits
182    L2048 = 2048,
183    /// Element length is 4096 bits
184    L4096 = 4096,
185    /// Element length is 8192 bits
186    L8192 = 8192,
187    /// Element length is 16_384 bits
188    L16_384 = 16_384,
189    /// Element length is 32_768 bits
190    L32_768 = 32_768,
191    /// Element length is 65_536 bits
192    L65_536 = 65_536,
193}
194
195const impl From<Elen> for u32 {
196    #[inline(always)]
197    fn from(value: Elen) -> Self {
198        value as u32
199    }
200}
201
202impl Elen {
203    /// Whether elements of width `eew` are supported, which is the case when `EEW <= ELEN`
204    #[inline(always)]
205    pub const fn supports(self, eew: Eew) -> bool {
206        u32::from(eew.bits_width()) <= u32::from(self)
207    }
208}
209
210/// Vector length
211#[derive(ConstParamTy, Debug, Clone, Copy)]
212#[derive_const(PartialEq, Eq, PartialOrd, Ord)]
213#[repr(u32)]
214pub enum Vlen {
215    /// Vector length is 8 bits
216    L8 = 8,
217    /// Vector length is 16 bits
218    L16 = 16,
219    /// Vector length is 32 bits
220    L32 = 32,
221    /// Vector length is 64 bits
222    L64 = 64,
223    /// Vector length is 128 bits
224    L128 = 128,
225    /// Vector length is 256 bits
226    L256 = 256,
227    /// Vector length is 512 bits
228    L512 = 512,
229    /// Vector length is 1024 bits
230    L1024 = 1024,
231    /// Vector length is 2048 bits
232    L2048 = 2048,
233    /// Vector length is 4096 bits
234    L4096 = 4096,
235    /// Vector length is 8192 bits
236    L8192 = 8192,
237    /// Vector length is 16_384 bits
238    L16_384 = 16_384,
239    /// Vector length is 32_768 bits
240    L32_768 = 32_768,
241    /// Vector length is 65_536 bits
242    L65_536 = 65_536,
243}
244
245const impl From<Vlen> for u32 {
246    #[inline(always)]
247    fn from(value: Vlen) -> Self {
248        value as u32
249    }
250}
251
252impl Vlen {
253    /// Vlen in bytes
254    #[inline(always)]
255    pub const fn bytes(self) -> u32 {
256        self as u32 / u8::BITS
257    }
258}
259
260/// `mstatus.VS` / `sstatus.VS` / `vsstatus.VS` field encoding.
261///
262/// Context status for the vector extension, analogous to `mstatus.FS`.
263/// Located at bits `[10:9]` in the respective status registers.
264#[derive(Debug, Clone, Copy)]
265#[derive_const(PartialEq, Eq)]
266#[repr(u8)]
267pub enum VsStatus {
268    /// Vector unit is off; any vector instruction or CSR access raises illegal instruction
269    Off = 0,
270    /// Vector state is known to be in its initial state
271    Initial = 1,
272    /// Vector state is potentially modified but matches the last saved state
273    Clean = 2,
274    /// Vector state has been modified since the last save
275    Dirty = 3,
276}
277
278impl VsStatus {
279    /// Decode from a 2-bit field value
280    #[inline(always)]
281    pub const fn from_bits(bits: u8) -> Self {
282        match bits & 0b11 {
283            0 => Self::Off,
284            1 => Self::Initial,
285            2 => Self::Clean,
286            _ => Self::Dirty,
287        }
288    }
289
290    /// Encode to a 2-bit field value
291    #[inline(always)]
292    pub const fn to_bits(self) -> u8 {
293        self as u8
294    }
295}
296
297/// Vector length multiplier (LMUL) setting.
298///
299/// Encoded in `vtype[2:0]` as a signed 3-bit value.
300/// `LMUL = 2^vlmul` where `vlmul` is sign-extended. Positive values give integer multipliers,
301/// negative values give fractional.
302#[derive(Debug, Clone, Copy)]
303#[derive_const(PartialEq, Eq)]
304#[repr(u8)]
305pub enum Vlmul {
306    /// LMUL = 1 (`vlmul` encoding 0b000)
307    M1 = 0b000,
308    /// LMUL = 2 (`vlmul` encoding 0b001)
309    M2 = 0b001,
310    /// LMUL = 4 (`vlmul` encoding 0b010)
311    M4 = 0b010,
312    /// LMUL = 8 (`vlmul` encoding 0b011)
313    M8 = 0b011,
314    /// LMUL = 1/8 (`vlmul` encoding 0b101)
315    Mf8 = 0b101,
316    /// LMUL = 1/4 (`vlmul` encoding 0b110)
317    Mf4 = 0b110,
318    /// LMUL = 1/2 (`vlmul` encoding 0b111)
319    Mf2 = 0b111,
320}
321
322impl Vlmul {
323    /// Decode from the 3-bit `vlmul` field. Returns `None` for reserved encoding 0b100.
324    #[inline(always)]
325    pub const fn from_bits(bits: u8) -> Option<Self> {
326        match bits & 0b111 {
327            0b000 => Some(Self::M1),
328            0b001 => Some(Self::M2),
329            0b010 => Some(Self::M4),
330            0b011 => Some(Self::M8),
331            0b101 => Some(Self::Mf8),
332            0b110 => Some(Self::Mf4),
333            0b111 => Some(Self::Mf2),
334            _ => None,
335        }
336    }
337
338    /// Encode to the 3-bit `vlmul` field
339    #[inline(always)]
340    pub const fn to_bits(self) -> u8 {
341        self as u8
342    }
343
344    /// Compute `VLMAX = LMUL * VLEN / SEW`.
345    ///
346    /// For fractional LMUL, this is `VLEN / (SEW * denominator)`.
347    /// Returns `Vl::ZERO` when the result would be less than 1 (insufficient bits).
348    #[inline(always)]
349    #[cfg_attr(feature = "no-panic", no_panic_const::no_panic)]
350    pub const fn vlmax<const VLEN: Vlen>(self, sew: Vsew) -> Vl {
351        let sew_bits = u32::from(sew.bits_width());
352        let vl = match self {
353            Self::M1 => u32::from(VLEN) / sew_bits,
354            Self::M2 => (u32::from(VLEN) * 2) / sew_bits,
355            Self::M4 => (u32::from(VLEN) * 4) / sew_bits,
356            Self::M8 => (u32::from(VLEN) * 8) / sew_bits,
357            Self::Mf2 => u32::from(VLEN) / (sew_bits * 2),
358            Self::Mf4 => u32::from(VLEN) / (sew_bits * 4),
359            Self::Mf8 => u32::from(VLEN) / (sew_bits * 8),
360        };
361        Vl::new(vl).expect(
362            "At most `8 * VLEN / 8` (`LMUL = 8`, `SEW = 8`), which never exceeds the maximum \
363            vector length; qed",
364        )
365    }
366
367    /// Number of vector registers occupied by one register group at this `LMUL`.
368    ///
369    /// Fractional `LMUL` values (`Mf2`, `Mf4`, `Mf8`) each occupy exactly 1 register.
370    /// Integer `LMUL` values occupy 1, 2, 4, or 8 registers respectively.
371    #[inline(always)]
372    #[cfg_attr(feature = "no-panic", no_panic_const::no_panic)]
373    pub const fn register_count(self) -> VRegGroupSize {
374        match self {
375            Self::Mf8 | Self::Mf4 | Self::Mf2 | Self::M1 => VRegGroupSize::R1,
376            Self::M2 => VRegGroupSize::R2,
377            Self::M4 => VRegGroupSize::R4,
378            Self::M8 => VRegGroupSize::R8,
379        }
380    }
381
382    /// Whether this is a fractional multiplier, so a register group is a part of one register
383    #[inline(always)]
384    pub const fn is_fractional(self) -> bool {
385        matches!(self, Self::Mf8 | Self::Mf4 | Self::Mf2)
386    }
387
388    /// Twice this multiplier, `None` above `M8`
389    #[inline(always)]
390    pub const fn double(self) -> Option<Self> {
391        match self {
392            Self::Mf8 => Some(Self::Mf4),
393            Self::Mf4 => Some(Self::Mf2),
394            Self::Mf2 => Some(Self::M1),
395            Self::M1 => Some(Self::M2),
396            Self::M2 => Some(Self::M4),
397            Self::M4 => Some(Self::M8),
398            Self::M8 => {
399                cold_path();
400                None
401            }
402        }
403    }
404
405    /// `LMUL` in eighths, so that fractional multipliers are integers too
406    #[inline(always)]
407    const fn eighths(self) -> u32 {
408        match self {
409            Self::Mf8 => 1,
410            Self::Mf4 => 2,
411            Self::Mf2 => 4,
412            Self::M1 => 8,
413            Self::M2 => 16,
414            Self::M4 => 32,
415            Self::M8 => 64,
416        }
417    }
418
419    /// Inverse of [`Self::eighths()`], `None` outside the legal range `[1/8, 8]`
420    #[inline(always)]
421    const fn from_eighths(eighths: u32) -> Option<Self> {
422        match eighths {
423            1 => Some(Self::Mf8),
424            2 => Some(Self::Mf4),
425            4 => Some(Self::Mf2),
426            8 => Some(Self::M1),
427            16 => Some(Self::M2),
428            32 => Some(Self::M4),
429            64 => Some(Self::M8),
430            _ => {
431                cold_path();
432                None
433            }
434        }
435    }
436
437    /// Effective multiplier `EMUL = LMUL * EEW / SEW` of an operand with element width `eew`
438    /// under this `LMUL` and `sew`.
439    ///
440    /// Returns `None` when `EMUL` falls outside the legal range `[1/8, 8]`.
441    #[inline(always)]
442    #[cfg_attr(feature = "no-panic", no_panic_const::no_panic)]
443    pub const fn emul(self, eew: Eew, sew: Vsew) -> Option<Self> {
444        let eighths = self.eighths() * u32::from(eew.bits_width()) / u32::from(sew.bits_width());
445        Self::from_eighths(eighths)
446    }
447
448    /// Number of vector registers occupied by the destination group of a widening instruction,
449    /// whose `EMUL = 2 * LMUL`.
450    ///
451    /// Returns `None` for `M8`, where `EMUL` would be `16`.
452    #[inline(always)]
453    #[cfg_attr(feature = "no-panic", no_panic_const::no_panic)]
454    pub const fn widening_register_count(self) -> Option<VRegGroupSize> {
455        Some(self.double()?.register_count())
456    }
457
458    /// Compute `EMUL` for an indexed load: `EMUL = (index_eew / sew) * LMUL`.
459    ///
460    /// Returns the register count for the index register group, or `None` when `EMUL` falls
461    /// outside the legal range `[1/8, 8]`.
462    #[inline(always)]
463    #[cfg_attr(feature = "no-panic", no_panic_const::no_panic)]
464    pub const fn index_register_count(self, index_eew: Eew, sew: Vsew) -> Option<VRegGroupSize> {
465        Some(self.emul(index_eew, sew)?.register_count())
466    }
467
468    /// Compute EMUL for a data operand of a memory instruction with a given effective element
469    /// width: `EMUL = (eew / sew) * LMUL`.
470    ///
471    /// Mathematically identical to [`Self::index_register_count`], but exposed under a distinct
472    /// name for call sites where the EEW describes the *data* being loaded or stored rather than an
473    /// index. Keeping the two entry points separate avoids accidental semantic drift if
474    /// one of them is later specialised.
475    ///
476    /// Returns `None` when the resulting EMUL falls outside the legal range `[1/8, 8]`.
477    #[inline(always)]
478    #[cfg_attr(feature = "no-panic", no_panic_const::no_panic)]
479    pub const fn data_register_count(self, eew: Eew, sew: Vsew) -> Option<VRegGroupSize> {
480        self.index_register_count(eew, sew)
481    }
482}
483
484impl fmt::Display for Vlmul {
485    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
486        match self {
487            Self::M1 => write!(f, "m1"),
488            Self::M2 => write!(f, "m2"),
489            Self::M4 => write!(f, "m4"),
490            Self::M8 => write!(f, "m8"),
491            Self::Mf8 => write!(f, "mf8"),
492            Self::Mf4 => write!(f, "mf4"),
493            Self::Mf2 => write!(f, "mf2"),
494        }
495    }
496}
497
498/// Number of vector registers in a register group.
499///
500/// Register groups always consist of a power of two number of registers, whether from
501/// `LMUL`, `EMUL` of a memory operand or a whole-register move.
502#[derive(Debug, Clone, Copy)]
503#[derive_const(PartialEq, Eq)]
504#[repr(u8)]
505pub enum VRegGroupSize {
506    /// A single register
507    R1 = 1,
508    /// Two registers
509    R2 = 2,
510    /// Four registers
511    R4 = 4,
512    /// Eight registers
513    R8 = 8,
514}
515
516impl VRegGroupSize {
517    /// Number of registers in the group
518    #[inline(always)]
519    pub const fn get(self) -> u8 {
520        self as u8
521    }
522
523    /// Size of a group with `factor` times fewer registers, at least one.
524    ///
525    /// This is the source group of a `vzext`/`vsext`, whose `EMUL = LMUL / factor`.
526    #[inline(always)]
527    pub const fn divide_by_factor(self, factor: VsewFactor) -> Self {
528        match self.get() / factor.factor() {
529            2 => Self::R2,
530            4 => Self::R4,
531            _ => Self::R1,
532        }
533    }
534}
535
536impl fmt::Display for VRegGroupSize {
537    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
538        write!(f, "{}", self.get())
539    }
540}
541
542/// Factor by which Vsew width is divided
543#[derive(Debug, Clone, Copy)]
544#[derive_const(PartialEq, Eq)]
545#[repr(u8)]
546pub enum VsewFactor {
547    /// Divide width by 2
548    F2 = 2,
549    /// Divide width by 4
550    F4 = 4,
551    /// Divide width by 8
552    F8 = 8,
553}
554
555impl VsewFactor {
556    /// Return the numeric divisor used to scale down a [`Vsew`] bit-width
557    #[inline(always)]
558    pub const fn factor(self) -> u8 {
559        self as u8
560    }
561}
562
563/// Selected element width (SEW).
564///
565/// Encoded in `vtype[5:3]` as `vsew`. `SEW = 8 * 2^vsew`.
566#[derive(ConstParamTy, Debug, Clone, Copy)]
567#[derive_const(PartialEq, Eq)]
568#[repr(u8)]
569pub enum Vsew {
570    /// SEW = 8 bits (vsew = 0b000)
571    E8 = 8,
572    /// SEW = 16 bits (vsew = 0b001)
573    E16 = 16,
574    /// SEW = 32 bits (vsew = 0b010)
575    E32 = 32,
576    /// SEW = 64 bits (vsew = 0b011)
577    E64 = 64,
578}
579
580impl Vsew {
581    /// Decode from the 3-bit vsew field. Returns `None` for reserved encodings.
582    #[inline(always)]
583    pub const fn from_bits(bits: u8) -> Option<Self> {
584        match bits & 0b111 {
585            0b000 => Some(Self::E8),
586            0b001 => Some(Self::E16),
587            0b010 => Some(Self::E32),
588            0b011 => Some(Self::E64),
589            _ => {
590                cold_path();
591                None
592            }
593        }
594    }
595
596    /// Create a selected element width that matches the register width
597    #[inline(always)]
598    #[cfg_attr(feature = "no-panic", no_panic_const::no_panic)]
599    pub const fn from_xlen<Reg>() -> Self
600    where
601        Reg: [const] Register,
602    {
603        const {
604            match Reg::XLEN {
605                32 => Self::E32,
606                64 => Self::E64,
607                _ => {
608                    // TODO: Should have been `unreachable!()`:
609                    //  https://github.com/rust-lang/rust/issues/159645
610                    panic!("Invalid register width")
611                }
612            }
613        }
614    }
615
616    /// Encode to the 3-bit vsew field
617    #[inline(always)]
618    pub const fn to_bits(self) -> u8 {
619        match self {
620            Vsew::E8 => 0b000,
621            Vsew::E16 => 0b001,
622            Vsew::E32 => 0b010,
623            Vsew::E64 => 0b011,
624        }
625    }
626
627    /// Get the double element width, if available
628    #[inline(always)]
629    pub const fn double_width(self) -> Option<Self> {
630        match self {
631            Self::E8 => Some(Self::E16),
632            Self::E16 => Some(Self::E32),
633            Self::E32 => Some(Self::E64),
634            Self::E64 => {
635                cold_path();
636                None
637            }
638        }
639    }
640
641    /// Divide Vsew width by a given factor
642    #[inline(always)]
643    #[cfg_attr(feature = "no-panic", no_panic_const::no_panic)]
644    pub const fn divide_by_factor(self, factor: VsewFactor) -> Option<Self> {
645        let Some(divide_by_factor) = self.bits_width().div_exact(factor.factor()) else {
646            cold_path();
647            return None;
648        };
649        match divide_by_factor {
650            8 => Some(Self::E8),
651            16 => Some(Self::E16),
652            32 => Some(Self::E32),
653            _ => {
654                cold_path();
655                None
656            }
657        }
658    }
659
660    /// Element width in bits
661    #[inline(always)]
662    pub const fn bits_width(self) -> u8 {
663        match self {
664            Self::E8 => 8,
665            Self::E16 => 16,
666            Self::E32 => 32,
667            Self::E64 => 64,
668        }
669    }
670
671    /// Element width in bytes
672    #[inline(always)]
673    pub const fn bytes_width(self) -> u8 {
674        match self {
675            Self::E8 => 1,
676            Self::E16 => 2,
677            Self::E32 => 4,
678            Self::E64 => 8,
679        }
680    }
681
682    /// Convert to the corresponding `Eew` variant.
683    ///
684    /// Every valid `Vsew` value has a directly corresponding `Eew` value because both
685    /// enumerate the same set of widths (8/16/32/64 bits). The conversion is always
686    /// successful.
687    #[inline(always)]
688    pub const fn as_eew(self) -> Eew {
689        match self {
690            Self::E8 => Eew::E8,
691            Self::E16 => Eew::E16,
692            Self::E32 => Eew::E32,
693            Self::E64 => Eew::E64,
694        }
695    }
696}
697
698impl fmt::Display for Vsew {
699    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
700        match self {
701            Self::E8 => write!(f, "e8"),
702            Self::E16 => write!(f, "e16"),
703            Self::E32 => write!(f, "e32"),
704            Self::E64 => write!(f, "e64"),
705        }
706    }
707}
708
709/// Effective element width of a vector operand.
710///
711/// Memory operands carry it in the instruction, register operands derive it from `SEW`.
712#[derive(ConstParamTy, Debug, Clone, Copy)]
713#[derive_const(PartialEq, Eq)]
714#[repr(u8)]
715pub enum Eew {
716    /// 8-bit elements
717    E8 = 1,
718    /// 16-bit elements
719    E16 = 2,
720    /// 32-bit elements
721    E32 = 4,
722    /// 64-bit elements
723    E64 = 8,
724}
725
726impl Eew {
727    /// Max element width in bytes
728    pub const MAX_BYTES: u8 = Self::E64.bytes_width();
729
730    /// Decode the width field into an element width
731    #[inline(always)]
732    pub const fn from_width(width: u8) -> Option<Self> {
733        match width {
734            0b000 => Some(Self::E8),
735            0b101 => Some(Self::E16),
736            0b110 => Some(Self::E32),
737            0b111 => Some(Self::E64),
738            _ => {
739                cold_path();
740                None
741            }
742        }
743    }
744
745    /// Encode to the 3-bit Eew field
746    #[inline(always)]
747    pub const fn to_bits(self) -> u8 {
748        match self {
749            Eew::E8 => 0b000,
750            Eew::E16 => 0b101,
751            Eew::E32 => 0b110,
752            Eew::E64 => 0b111,
753        }
754    }
755
756    /// Element width in bits
757    #[inline(always)]
758    pub const fn bits_width(self) -> u8 {
759        match self {
760            Self::E8 => 8,
761            Self::E16 => 16,
762            Self::E32 => 32,
763            Self::E64 => 64,
764        }
765    }
766
767    /// Element width in bytes.
768    ///
769    /// Guaranteed to be `<= Self::MAX_BYTES`.
770    #[inline(always)]
771    pub const fn bytes_width(self) -> u8 {
772        match self {
773            Self::E8 => 1,
774            Self::E16 => 2,
775            Self::E32 => 4,
776            Self::E64 => 8,
777        }
778    }
779}
780
781const impl From<Vsew> for Eew {
782    #[inline(always)]
783    fn from(sew: Vsew) -> Self {
784        sew.as_eew()
785    }
786}
787
788impl fmt::Display for Eew {
789    #[inline]
790    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
791        fmt::Display::fmt(&self.bits_width(), f)
792    }
793}
794
795/// Vector fixed-point rounding mode.
796///
797/// Encoded in the `vxrm` CSR bits `[1:0]` and mirrored in `vcsr[2:1]`.
798#[derive(Debug, Clone, Copy)]
799#[derive_const(Default, PartialEq, Eq)]
800#[repr(u8)]
801pub enum Vxrm {
802    /// Round-to-nearest-up (rnu)
803    #[default]
804    Rnu = 0b00,
805    /// Round-to-nearest-even (rne)
806    Rne = 0b01,
807    /// Round-down / truncate (rdn)
808    Rdn = 0b10,
809    /// Round-to-odd (rod)
810    Rod = 0b11,
811}
812
813impl Vxrm {
814    /// Decode from a 2-bit field
815    #[inline(always)]
816    pub const fn from_bits(bits: u8) -> Self {
817        match bits & 0b11 {
818            0b00 => Self::Rnu,
819            0b01 => Self::Rne,
820            0b10 => Self::Rdn,
821            _ => Self::Rod,
822        }
823    }
824
825    /// Encode to a 2-bit field
826    #[inline(always)]
827    pub const fn to_bits(self) -> u8 {
828        self as u8
829    }
830}
831
832/// Decoded `vtype` register contents.
833///
834/// The vtype CSR controls the interpretation of the vector register file: element width, register
835/// grouping, and tail/mask agnostic policies.
836///
837/// The raw encoding is XLEN-dependent (vill is at bit XLEN-1), but this decoded form is
838/// XLEN-independent.
839#[derive(Debug, Clone, Copy)]
840pub struct Vtype<Hart>
841where
842    Hart: VectorHartConfig,
843{
844    /// Vector mask agnostic policy (bit `7`)
845    vma: bool,
846    /// Vector tail agnostic policy (bit `6`)
847    vta: bool,
848    /// Selected element width (bits `[5:3]`)
849    vsew: Vsew,
850    /// Vector length multiplier (bits `[2:0]`)
851    vlmul: Vlmul,
852    hart: PhantomData<Hart>,
853}
854
855const impl<Hart> PartialEq for Vtype<Hart>
856where
857    Hart: VectorHartConfig,
858{
859    #[inline(always)]
860    fn eq(&self, other: &Self) -> bool {
861        self.vma == other.vma
862            && self.vta == other.vta
863            && self.vsew == other.vsew
864            && self.vlmul == other.vlmul
865    }
866}
867
868const impl<Hart> Eq for Vtype<Hart> where Hart: VectorHartConfig {}
869
870impl<Hart> Vtype<Hart>
871where
872    Hart: VectorHartConfig,
873{
874    /// Vector mask agnostic policy (bit `7`)
875    pub const fn vma(&self) -> bool {
876        self.vma
877    }
878
879    /// Vector tail agnostic policy (bit `6`)
880    pub const fn vta(&self) -> bool {
881        self.vta
882    }
883
884    /// Selected element width (bits `[5:3]`)
885    pub const fn vsew(&self) -> Vsew {
886        self.vsew
887    }
888
889    /// Vector length multiplier (bits `[2:0]`)
890    pub const fn vlmul(&self) -> Vlmul {
891        self.vlmul
892    }
893
894    /// Number of registers in a group of elements with effective element width `eew`, where
895    /// `EMUL = (EEW / SEW) * LMUL`.
896    ///
897    /// Returns `None` when `EEW` exceeds `ELEN` or `EMUL` falls outside the legal range
898    /// `[1/8, 8]`, both of which are reserved.
899    #[inline(always)]
900    #[cfg_attr(feature = "no-panic", no_panic_const::no_panic)]
901    pub const fn eew_register_count(&self, eew: Eew) -> Option<VRegGroupSize> {
902        if !Hart::VECTOR_LENGTHS.elen.supports(eew) {
903            cold_path();
904            return None;
905        }
906        self.vlmul.index_register_count(eew, self.vsew)
907    }
908
909    /// `VLMAX = LMUL * VLEN / SEW`, which is at least 1 for any valid `vtype`
910    #[inline(always)]
911    #[cfg_attr(feature = "no-panic", no_panic_const::no_panic)]
912    pub const fn vlmax(&self) -> Vl {
913        self.vlmul.vlmax::<{ HART_VLEN::<Hart> }>(self.vsew)
914    }
915
916    /// Decode from raw register value.
917    ///
918    /// The `XLEN` is taken from `Reg::XLEN` and must be 32 for RV32 or 64 for RV64. The `vill` bit
919    /// is placed at bit position `Reg::XLEN - 1`.
920    ///
921    /// All bits in `[Reg::XLEN-1:8]` must be zero; non-zero bits indicate an unrecognized
922    /// encoding and cause `None` to be returned (this includes `vill`).
923    #[inline(always)]
924    #[cfg_attr(feature = "no-panic", no_panic_const::no_panic)]
925    pub const fn from_raw<Reg>(raw: Reg::Type) -> Option<Self>
926    where
927        Reg: [const] Register,
928    {
929        let raw = raw.as_u64();
930
931        // All bits in [XLEN-1:8] must be zero
932        if (raw >> 8u8) != 0 {
933            cold_path();
934            return None;
935        }
936
937        let vlmul_bits = (raw & 0b111) as u8;
938        let vsew_bits = ((raw >> 3u8) & 0b111) as u8;
939        let vta = ((raw >> 6u8) & 1) != 0;
940        let vma = ((raw >> 7u8) & 1) != 0;
941
942        let Some(vlmul) = Vlmul::from_bits(vlmul_bits) else {
943            cold_path();
944            return None;
945        };
946        let Some(vsew) = Vsew::from_bits(vsew_bits) else {
947            cold_path();
948            return None;
949        };
950
951        let elen = Hart::VECTOR_LENGTHS.elen;
952        let sew = vsew.bits_width();
953        if u32::from(sew) > u32::from(elen) {
954            cold_path();
955            return None;
956        }
957
958        // Only `SEW <= LMUL * ELEN` must be supported for fractional `LMUL`, anything beyond that
959        // is reserved and treated as `vill` like in the Sail model. Since `ELEN <= VLEN`,
960        // this also guarantees that at least one element fits and `VLMAX` is non-zero.
961        if u32::from(sew) * 8 > u32::from(elen) * vlmul.eighths() {
962            cold_path();
963            return None;
964        }
965
966        Some(Self {
967            vma,
968            vta,
969            vsew,
970            vlmul,
971            hart: PhantomData,
972        })
973    }
974
975    /// Encode to a raw `vtype` register value of type `Reg::Type`.
976    ///
977    /// The encoded value contains `vlmul`, `vsew`, `vta`, and `vma` in bits `[7:0]` with
978    /// `vill = 0`. To construct a raw value with `vill = 1` (illegal configuration), use
979    /// [`Self::illegal_raw`].
980    #[inline(always)]
981    #[cfg_attr(feature = "no-panic", no_panic_const::no_panic)]
982    pub const fn to_raw<Reg>(self) -> Reg::Type
983    where
984        Reg: [const] Register,
985    {
986        let mut raw = 0u8;
987        raw |= self.vlmul.to_bits();
988        raw |= self.vsew.to_bits() << 3u8;
989
990        if self.vta {
991            raw |= 1 << 6u8;
992        }
993
994        if self.vma {
995            raw |= 1 << 7u8;
996        }
997
998        Reg::Type::from(raw)
999    }
1000
1001    /// Construct a raw value for `vtype` with `vill=1` (illegal configuration).
1002    ///
1003    /// Per spec: when `vill` is set, the remaining bits are zero and `vl` is also set to zero. Any
1004    /// subsequent vector instruction that depends on `vtype` will raise an illegal-instruction
1005    /// exception.
1006    #[inline(always)]
1007    #[cfg_attr(feature = "no-panic", no_panic_const::no_panic)]
1008    pub const fn illegal_raw<Reg>() -> Reg::Type
1009    where
1010        Reg: [const] Register,
1011    {
1012        let vill_bit = Reg::XLEN - 1;
1013        Reg::Type::from(1u8) << vill_bit
1014    }
1015}
1016
1017/// RISC-V V instruction (placeholder)
1018#[derive(Debug, Clone, Copy)]
1019#[derive_const(PartialEq, Eq)]
1020#[doc(hidden)]
1021pub enum V<Hart>
1022where
1023    Hart: HartConfig,
1024{
1025    V(Hart::Reg, !),
1026}
1027
1028const impl<Reg, Hart> Instruction for V<Hart>
1029where
1030    Reg: [const] Register,
1031    Hart: [const] VectorHartConfig<Reg = Reg>,
1032{
1033    const IMPLEMENTED_EXTENSIONS: &'static [ImplementedExtension] = &[];
1034
1035    const OWN_ISA_EXTENSIONS: &'static [IsaExtension] = &[];
1036
1037    const ALIGNMENT: u8 = align_of::<u32>() as u8;
1038
1039    type Hart = Hart;
1040
1041    #[inline(always)]
1042    fn try_decode(_instruction: u32) -> Option<Self> {
1043        None
1044    }
1045
1046    #[inline(always)]
1047    fn size(&self) -> u8 {
1048        size_of::<u32>() as u8
1049    }
1050}
1051
1052impl<Reg, Hart> fmt::Display for V<Hart>
1053where
1054    Reg: fmt::Display,
1055    Hart: HartConfig<Reg = Reg>,
1056{
1057    fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
1058        match self {
1059            V::V(_, _) => {
1060                unreachable!("Impossible to construct V instruction")
1061            }
1062        }
1063    }
1064}