Skip to main content

ab_riscv_primitives/instructions/
zicond.rs

1//! Zicond 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 Zicond instruction (Integer Conditional Operations)
12#[instruction]
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum ZicondInstruction<Reg> {
15    /// `czero.eqz rd, rs1, rs2` - move zero to `rd` if `rs2 == 0`, else move `rs1`
16    CzeroEqz { rd: Reg, rs1: Reg, rs2: Reg },
17    /// `czero.nez rd, rs1, rs2` - move zero to `rd` if `rs2 != 0`, else move `rs1`
18    CzeroNez { rd: Reg, rs1: Reg, rs2: Reg },
19}
20
21#[instruction]
22impl<Reg> const Instruction for ZicondInstruction<Reg>
23where
24    Reg: [const] Register,
25{
26    type Reg = Reg;
27
28    #[inline(always)]
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) & 0x7f) as u8;
36
37        // Both Zicond instructions share opcode=0x33 (OP) and funct7=0x07
38        match (opcode, funct7) {
39            (0b011_0011, 0b000_0111) => {
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 {
44                    0b101 => Some(Self::CzeroEqz { rd, rs1, rs2 }),
45                    0b111 => Some(Self::CzeroNez { rd, rs1, rs2 }),
46                    _ => None,
47                }
48            }
49            _ => None,
50        }
51    }
52
53    #[inline(always)]
54    fn alignment() -> u8 {
55        align_of::<u32>() as u8
56    }
57
58    #[inline(always)]
59    fn size(&self) -> u8 {
60        size_of::<u32>() as u8
61    }
62}
63
64impl<Reg> fmt::Display for ZicondInstruction<Reg>
65where
66    Reg: fmt::Display,
67{
68    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69        match self {
70            Self::CzeroEqz { rd, rs1, rs2 } => write!(f, "czero.eqz {rd}, {rs1}, {rs2}"),
71            Self::CzeroNez { rd, rs1, rs2 } => write!(f, "czero.nez {rd}, {rs1}, {rs2}"),
72        }
73    }
74}