Skip to main content

ab_riscv_primitives/instructions/rv32/b/
zba.rs

1//! RV32 Zba extension
2
3#[cfg(test)]
4mod tests;
5
6use crate::instructions::Instruction;
7use crate::registers::general_purpose::Register;
8use ab_riscv_macros::instruction;
9use core::fmt;
10
11/// RISC-V RV32 Zba instruction (Address generation)
12#[instruction]
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum Rv32ZbaInstruction<Reg> {
15    Sh1add { rd: Reg, rs1: Reg, rs2: Reg },
16    Sh2add { rd: Reg, rs1: Reg, rs2: Reg },
17    Sh3add { rd: Reg, rs1: Reg, rs2: Reg },
18}
19
20#[instruction]
21const impl<Reg> Instruction for Rv32ZbaInstruction<Reg>
22where
23    Reg: [const] Register<Type = u32>,
24{
25    type Reg = Reg;
26
27    #[inline(always)]
28    #[cfg_attr(feature = "no-panic", no_panic_const::no_panic(const))]
29    fn try_decode(instruction: u32) -> Option<Self> {
30        let opcode = (instruction & 0b111_1111) as u8;
31        let rd_bits = ((instruction >> 7) & 0x1f) as u8;
32        let funct3 = ((instruction >> 12) & 0b111) as u8;
33        let rs1_bits = ((instruction >> 15) & 0x1f) as u8;
34        let rs2_bits = ((instruction >> 20) & 0x1f) as u8;
35        let funct7 = ((instruction >> 25) & 0b111_1111) as u8;
36
37        match opcode {
38            // R-type
39            0b011_0011 => {
40                let rd = Reg::from_bits(rd_bits)?;
41                let rs1 = Reg::from_bits(rs1_bits)?;
42                let rs2 = Reg::from_bits(rs2_bits)?;
43                match (funct3, funct7) {
44                    (0b010, 0b001_0000) => Some(Self::Sh1add { rd, rs1, rs2 }),
45                    (0b100, 0b001_0000) => Some(Self::Sh2add { rd, rs1, rs2 }),
46                    (0b110, 0b001_0000) => Some(Self::Sh3add { rd, rs1, rs2 }),
47                    _ => None,
48                }
49            }
50            _ => None,
51        }
52    }
53
54    #[inline(always)]
55    fn alignment() -> u8 {
56        align_of::<u32>() as u8
57    }
58
59    #[inline(always)]
60    fn size(&self) -> u8 {
61        size_of::<u32>() as u8
62    }
63}
64
65#[instruction]
66impl<Reg> fmt::Display for Rv32ZbaInstruction<Reg>
67where
68    Reg: fmt::Display,
69{
70    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71        match self {
72            Self::Sh1add { rd, rs1, rs2 } => write!(f, "sh1add {rd}, {rs1}, {rs2}"),
73            Self::Sh2add { rd, rs1, rs2 } => write!(f, "sh2add {rd}, {rs1}, {rs2}"),
74            Self::Sh3add { rd, rs1, rs2 } => write!(f, "sh3add {rd}, {rs1}, {rs2}"),
75        }
76    }
77}