Skip to main content

ab_riscv_primitives/instructions/
zicond.rs

1//! Zicond extension
2
3#[cfg(test)]
4mod tests;
5
6use crate::hart::HartConfig;
7use crate::instructions::{ImplementedExtension, Instruction, IsaExtension};
8use crate::registers::general_purpose::Register;
9use ab_riscv_macros::instruction;
10use core::fmt;
11
12/// RISC-V Zicond instruction (Integer Conditional Operations)
13#[instruction]
14#[derive(Debug, Clone, Copy)]
15#[derive_const(PartialEq, Eq)]
16#[rustfmt::skip]
17pub enum ZicondInstruction<Hart>
18where
19    Hart: HartConfig,
20{
21    /// `czero.eqz rd, rs1, rs2` - move zero to `rd` if `rs2 == 0`, else move `rs1`
22    CzeroEqz { rd: Hart::Reg, rs1: Hart::Reg, rs2: Hart::Reg },
23    /// `czero.nez rd, rs1, rs2` - move zero to `rd` if `rs2 != 0`, else move `rs1`
24    CzeroNez { rd: Hart::Reg, rs1: Hart::Reg, rs2: Hart::Reg },
25}
26
27#[instruction]
28const impl<Reg, Hart> Instruction for ZicondInstruction<Hart>
29where
30    Reg: [const] Register,
31    Hart: [const] HartConfig<Reg = Reg>,
32{
33    const OWN_ISA_EXTENSIONS: &'static [IsaExtension] = &[IsaExtension::new("zicond", 1, 0)];
34
35    const ALIGNMENT: u8 = align_of::<u32>() as u8;
36
37    type Hart = Hart;
38
39    #[inline(always)]
40    #[cfg_attr(feature = "no-panic", no_panic_const::no_panic(const))]
41    fn try_decode(instruction: u32) -> Option<Self> {
42        let opcode = (instruction & 0b111_1111) as u8;
43        let rd_bits = ((instruction >> 7) & 0x1f) as u8;
44        let funct3 = ((instruction >> 12) & 0b111) as u8;
45        let rs1_bits = ((instruction >> 15) & 0x1f) as u8;
46        let rs2_bits = ((instruction >> 20) & 0x1f) as u8;
47        let funct7 = ((instruction >> 25) & 0x7f) as u8;
48
49        // Both Zicond instructions share opcode=0x33 (OP) and funct7=0x07
50        match (opcode, funct7) {
51            (0b011_0011, 0b000_0111) => {
52                let rd = Reg::from_bits(rd_bits)?;
53                let rs1 = Reg::from_bits(rs1_bits)?;
54                let rs2 = Reg::from_bits(rs2_bits)?;
55                match funct3 {
56                    0b101 => Some(Self::CzeroEqz { rd, rs1, rs2 }),
57                    0b111 => Some(Self::CzeroNez { rd, rs1, rs2 }),
58                    _ => None,
59                }
60            }
61            _ => None,
62        }
63    }
64
65    #[inline(always)]
66    fn size(&self) -> u8 {
67        size_of::<u32>() as u8
68    }
69}
70
71impl<Reg, Hart> fmt::Display for ZicondInstruction<Hart>
72where
73    Reg: fmt::Display,
74    Hart: HartConfig<Reg = Reg>,
75{
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        match self {
78            Self::CzeroEqz { rd, rs1, rs2 } => write!(f, "czero.eqz {rd}, {rs1}, {rs2}"),
79            Self::CzeroNez { rd, rs1, rs2 } => write!(f, "czero.nez {rd}, {rs1}, {rs2}"),
80        }
81    }
82}