Skip to main content

sp1_core_machine/operations/
add_u32.rs

1use sp1_core_executor::events::ByteRecord;
2use sp1_hypercube::air::SP1AirBuilder;
3use sp1_primitives::consts::u32_to_u16_limbs;
4
5use slop_air::AirBuilder;
6use slop_algebra::{AbstractField, Field};
7use sp1_derive::AlignedBorrow;
8
9use crate::{air::WordAirBuilder, utils::u32_to_half_word};
10
11/// A set of columns needed to compute the add of two u32s as a u32.
12#[derive(AlignedBorrow, Default, Debug, Clone, Copy)]
13#[repr(C)]
14pub struct AddU32Operation<T> {
15    /// The result of `a + b`.
16    pub value: [T; 2],
17}
18
19impl<F: Field> AddU32Operation<F> {
20    pub fn populate(&mut self, record: &mut impl ByteRecord, a_u32: u32, b_u32: u32) -> u32 {
21        let expected = a_u32.wrapping_add(b_u32);
22        self.value = u32_to_half_word(expected);
23        // Range check
24        record.add_u16_range_checks(&u32_to_u16_limbs(expected));
25        expected
26    }
27
28    /// Evaluate the add operation.
29    /// Assumes that `a`, `b` are valid u32s of two u16 limbs.
30    /// Constrains that `is_real` is boolean.
31    /// If `is_real` is true, the `value` is constrained to a valid u32 representing `a + b`.
32    pub fn eval<AB: SP1AirBuilder>(
33        builder: &mut AB,
34        a: [AB::Expr; 2],
35        b: [AB::Expr; 2],
36        cols: AddU32Operation<AB::Var>,
37        is_real: AB::Expr,
38    ) {
39        builder.assert_bool(is_real.clone());
40
41        let base = AB::F::from_canonical_u32(1 << 16);
42        let mut builder_is_real = builder.when(is_real.clone());
43        let mut carry = AB::Expr::zero();
44
45        // The set of constraints are
46        //  - carry is initialized to zero
47        //  - 2^16 * carry_next + value[i] = a[i] + b[i] + carry
48        //  - carry is boolean
49        //  - 0 <= value[i] < 2^16
50        for i in 0..2 {
51            carry = (a[i].clone() + b[i].clone() - cols.value[i] + carry) * base.inverse();
52            builder_is_real.assert_bool(carry.clone());
53        }
54
55        // Range check each limb.
56        builder.slice_range_check_u16(&cols.value, is_real);
57    }
58}