Skip to main content

ab_riscv_primitives/instructions/rv64/zk/zkn/
zkne.rs

1//! RV64 Zkne extension
2
3#[cfg(test)]
4mod tests;
5
6use crate::instructions::Instruction;
7use crate::instructions::rv64::zk::zkn::zknd::{Rv64ZkndInstruction, Rv64ZkndKsRnum};
8use crate::registers::general_purpose::Register;
9use ab_riscv_macros::instruction;
10use core::fmt;
11
12/// RISC-V RV64 Zkne instructions
13#[instruction(
14    reorder = [Aes64Es, Aes64Esm, Aes64Ks1i, Aes64Ks2],
15    ignore = [Rv64ZkndInstruction],
16    inherit = [Rv64ZkndInstruction],
17)]
18#[derive(Debug, Clone, Copy)]
19#[derive_const(PartialEq, Eq)]
20pub enum Rv64ZkneInstruction<Reg> {
21    /// AES final round encryption: ShiftRows + SubBytes, no MixColumns
22    Aes64Es { rd: Reg, rs1: Reg, rs2: Reg },
23    /// AES middle round encryption: ShiftRows + SubBytes + MixColumns
24    Aes64Esm { rd: Reg, rs1: Reg, rs2: Reg },
25}
26
27#[instruction]
28const impl<Reg> Instruction for Rv64ZkneInstruction<Reg>
29where
30    Reg: [const] Register<Type = u64>,
31{
32    type Reg = Reg;
33
34    #[inline(always)]
35    #[cfg_attr(feature = "no-panic", no_panic_const::no_panic(const))]
36    fn try_decode(instruction: u32) -> Option<Self> {
37        let opcode = (instruction & 0b111_1111) as u8;
38        let rd_bits = ((instruction >> 7) & 0x1f) as u8;
39        let funct3 = ((instruction >> 12) & 0b111) as u8;
40        let rs1_bits = ((instruction >> 15) & 0x1f) as u8;
41        let rs2_bits = ((instruction >> 20) & 0x1f) as u8;
42        let funct7 = ((instruction >> 25) & 0b111_1111) as u8;
43
44        // R-type: OP opcode (0x33)
45        //   aes64es:  funct7=0b001_1001, funct3=0 -> MATCH=0x3200_0033
46        //   aes64esm: funct7=0b001_1011, funct3=0 -> MATCH=0x3600_0033
47        match opcode {
48            0b011_0011 => {
49                if funct3 != 0b000 {
50                    None?;
51                }
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 funct7 {
56                    0b001_1001 => Some(Self::Aes64Es { rd, rs1, rs2 }),
57                    0b001_1011 => Some(Self::Aes64Esm { rd, rs1, rs2 }),
58                    _ => None,
59                }
60            }
61            _ => None,
62        }
63    }
64
65    #[inline(always)]
66    fn alignment() -> u8 {
67        align_of::<u32>() as u8
68    }
69
70    #[inline(always)]
71    fn size(&self) -> u8 {
72        size_of::<u32>() as u8
73    }
74}
75
76#[instruction]
77impl<Reg> fmt::Display for Rv64ZkneInstruction<Reg>
78where
79    Reg: fmt::Display + Copy,
80{
81    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82        match self {
83            Self::Aes64Es { rd: rd1, rs1, rs2 } => write!(f, "aes64es {rd1}, {rs1}, {rs2}"),
84            Self::Aes64Esm { rd, rs1, rs2 } => write!(f, "aes64esm {rd}, {rs1}, {rs2}"),
85        }
86    }
87}