openvm_rv32im_circuit/load_sign_extend/
execution.rs

1use std::{
2    array,
3    borrow::{Borrow, BorrowMut},
4    mem::size_of,
5};
6
7use openvm_circuit::{
8    arch::*,
9    system::memory::{online::GuestMemory, POINTER_MAX_BITS},
10};
11use openvm_circuit_primitives_derive::AlignedBytesBorrow;
12use openvm_instructions::{
13    instruction::Instruction,
14    program::DEFAULT_PC_STEP,
15    riscv::{RV32_IMM_AS, RV32_REGISTER_AS, RV32_REGISTER_NUM_LIMBS},
16    LocalOpcode,
17};
18use openvm_rv32im_transpiler::Rv32LoadStoreOpcode::{self, *};
19use openvm_stark_backend::p3_field::PrimeField32;
20
21use super::core::LoadSignExtendExecutor;
22
23#[derive(AlignedBytesBorrow, Clone)]
24#[repr(C)]
25struct LoadSignExtendPreCompute {
26    imm_extended: u32,
27    a: u8,
28    b: u8,
29    e: u8,
30}
31
32impl<A, const LIMB_BITS: usize> LoadSignExtendExecutor<A, { RV32_REGISTER_NUM_LIMBS }, LIMB_BITS> {
33    /// Return (is_loadb, enabled)
34    fn pre_compute_impl<F: PrimeField32>(
35        &self,
36        pc: u32,
37        inst: &Instruction<F>,
38        data: &mut LoadSignExtendPreCompute,
39    ) -> Result<(bool, bool), StaticProgramError> {
40        let Instruction {
41            opcode,
42            a,
43            b,
44            c,
45            d,
46            e,
47            f,
48            g,
49            ..
50        } = inst;
51
52        let e_u32 = e.as_canonical_u32();
53        if d.as_canonical_u32() != RV32_REGISTER_AS || e_u32 == RV32_IMM_AS {
54            return Err(StaticProgramError::InvalidInstruction(pc));
55        }
56
57        let local_opcode = Rv32LoadStoreOpcode::from_usize(
58            opcode.local_opcode_idx(Rv32LoadStoreOpcode::CLASS_OFFSET),
59        );
60        match local_opcode {
61            LOADB | LOADH => {}
62            _ => unreachable!("LoadSignExtendExecutor should only handle LOADB/LOADH opcodes"),
63        }
64
65        let imm = c.as_canonical_u32();
66        let imm_sign = g.as_canonical_u32();
67        let imm_extended = imm + imm_sign * 0xffff0000;
68
69        *data = LoadSignExtendPreCompute {
70            imm_extended,
71            a: a.as_canonical_u32() as u8,
72            b: b.as_canonical_u32() as u8,
73            e: e_u32 as u8,
74        };
75        let enabled = !f.is_zero();
76        Ok((local_opcode == LOADB, enabled))
77    }
78}
79
80macro_rules! dispatch {
81    ($execute_impl:ident, $is_loadb:ident, $enabled:ident) => {
82        match ($is_loadb, $enabled) {
83            (true, true) => Ok($execute_impl::<_, _, true, true>),
84            (true, false) => Ok($execute_impl::<_, _, true, false>),
85            (false, true) => Ok($execute_impl::<_, _, false, true>),
86            (false, false) => Ok($execute_impl::<_, _, false, false>),
87        }
88    };
89}
90
91impl<F, A, const LIMB_BITS: usize> Executor<F>
92    for LoadSignExtendExecutor<A, { RV32_REGISTER_NUM_LIMBS }, LIMB_BITS>
93where
94    F: PrimeField32,
95{
96    fn pre_compute_size(&self) -> usize {
97        size_of::<LoadSignExtendPreCompute>()
98    }
99
100    #[inline(always)]
101    fn pre_compute<Ctx: ExecutionCtxTrait>(
102        &self,
103        pc: u32,
104        inst: &Instruction<F>,
105        data: &mut [u8],
106    ) -> Result<ExecuteFunc<F, Ctx>, StaticProgramError> {
107        let pre_compute: &mut LoadSignExtendPreCompute = data.borrow_mut();
108        let (is_loadb, enabled) = self.pre_compute_impl(pc, inst, pre_compute)?;
109        dispatch!(execute_e1_impl, is_loadb, enabled)
110    }
111
112    #[cfg(feature = "tco")]
113    fn handler<Ctx>(
114        &self,
115        pc: u32,
116        inst: &Instruction<F>,
117        data: &mut [u8],
118    ) -> Result<Handler<F, Ctx>, StaticProgramError>
119    where
120        Ctx: ExecutionCtxTrait,
121    {
122        let pre_compute: &mut LoadSignExtendPreCompute = data.borrow_mut();
123        let (is_loadb, enabled) = self.pre_compute_impl(pc, inst, pre_compute)?;
124        dispatch!(execute_e1_tco_handler, is_loadb, enabled)
125    }
126}
127
128impl<F, A, const LIMB_BITS: usize> MeteredExecutor<F>
129    for LoadSignExtendExecutor<A, { RV32_REGISTER_NUM_LIMBS }, LIMB_BITS>
130where
131    F: PrimeField32,
132{
133    fn metered_pre_compute_size(&self) -> usize {
134        size_of::<E2PreCompute<LoadSignExtendPreCompute>>()
135    }
136
137    fn metered_pre_compute<Ctx>(
138        &self,
139        chip_idx: usize,
140        pc: u32,
141        inst: &Instruction<F>,
142        data: &mut [u8],
143    ) -> Result<ExecuteFunc<F, Ctx>, StaticProgramError>
144    where
145        Ctx: MeteredExecutionCtxTrait,
146    {
147        let pre_compute: &mut E2PreCompute<LoadSignExtendPreCompute> = data.borrow_mut();
148        pre_compute.chip_idx = chip_idx as u32;
149        let (is_loadb, enabled) = self.pre_compute_impl(pc, inst, &mut pre_compute.data)?;
150        dispatch!(execute_e2_impl, is_loadb, enabled)
151    }
152
153    #[cfg(feature = "tco")]
154    fn metered_handler<Ctx>(
155        &self,
156        chip_idx: usize,
157        pc: u32,
158        inst: &Instruction<F>,
159        data: &mut [u8],
160    ) -> Result<Handler<F, Ctx>, StaticProgramError>
161    where
162        Ctx: MeteredExecutionCtxTrait,
163    {
164        let pre_compute: &mut E2PreCompute<LoadSignExtendPreCompute> = data.borrow_mut();
165        pre_compute.chip_idx = chip_idx as u32;
166        let (is_loadb, enabled) = self.pre_compute_impl(pc, inst, &mut pre_compute.data)?;
167        dispatch!(execute_e2_tco_handler, is_loadb, enabled)
168    }
169}
170
171#[inline(always)]
172unsafe fn execute_e12_impl<
173    F: PrimeField32,
174    CTX: ExecutionCtxTrait,
175    const IS_LOADB: bool,
176    const ENABLED: bool,
177>(
178    pre_compute: &LoadSignExtendPreCompute,
179    vm_state: &mut VmExecState<F, GuestMemory, CTX>,
180) {
181    let rs1_bytes: [u8; RV32_REGISTER_NUM_LIMBS] =
182        vm_state.vm_read(RV32_REGISTER_AS, pre_compute.b as u32);
183    let rs1_val = u32::from_le_bytes(rs1_bytes);
184    let ptr_val = rs1_val.wrapping_add(pre_compute.imm_extended);
185    // sign_extend([r32{c,g}(b):2]_e)`
186    debug_assert!(ptr_val < (1 << POINTER_MAX_BITS));
187    let shift_amount = ptr_val % 4;
188    let ptr_val = ptr_val - shift_amount; // aligned ptr
189
190    let read_data: [u8; RV32_REGISTER_NUM_LIMBS] = vm_state.vm_read(pre_compute.e as u32, ptr_val);
191
192    let write_data = if IS_LOADB {
193        let byte = read_data[shift_amount as usize];
194        let sign_extended = (byte as i8) as i32;
195        sign_extended.to_le_bytes()
196    } else {
197        if shift_amount != 0 && shift_amount != 2 {
198            vm_state.exit_code = Err(ExecutionError::Fail {
199                pc: vm_state.pc,
200                msg: "LoadSignExtend invalid shift amount",
201            });
202            return;
203        }
204        let half: [u8; 2] = array::from_fn(|i| read_data[shift_amount as usize + i]);
205        (i16::from_le_bytes(half) as i32).to_le_bytes()
206    };
207
208    if ENABLED {
209        vm_state.vm_write(RV32_REGISTER_AS, pre_compute.a as u32, &write_data);
210    }
211
212    vm_state.pc += DEFAULT_PC_STEP;
213    vm_state.instret += 1;
214}
215
216#[create_tco_handler]
217unsafe fn execute_e1_impl<
218    F: PrimeField32,
219    CTX: ExecutionCtxTrait,
220    const IS_LOADB: bool,
221    const ENABLED: bool,
222>(
223    pre_compute: &[u8],
224    vm_state: &mut VmExecState<F, GuestMemory, CTX>,
225) {
226    let pre_compute: &LoadSignExtendPreCompute = pre_compute.borrow();
227    execute_e12_impl::<F, CTX, IS_LOADB, ENABLED>(pre_compute, vm_state);
228}
229
230#[create_tco_handler]
231unsafe fn execute_e2_impl<
232    F: PrimeField32,
233    CTX: MeteredExecutionCtxTrait,
234    const IS_LOADB: bool,
235    const ENABLED: bool,
236>(
237    pre_compute: &[u8],
238    vm_state: &mut VmExecState<F, GuestMemory, CTX>,
239) {
240    let pre_compute: &E2PreCompute<LoadSignExtendPreCompute> = pre_compute.borrow();
241    vm_state
242        .ctx
243        .on_height_change(pre_compute.chip_idx as usize, 1);
244    execute_e12_impl::<F, CTX, IS_LOADB, ENABLED>(&pre_compute.data, vm_state);
245}