Skip to main content

sp1_core_machine/operations/
subw.rs

1use std::num::Wrapping;
2
3use sp1_core_executor::events::ByteRecord;
4use sp1_hypercube::{air::SP1AirBuilder, Word};
5use sp1_primitives::consts::{u64_to_u16_limbs, WORD_SIZE};
6use struct_reflection::{StructReflection, StructReflectionHelper};
7
8use slop_air::AirBuilder;
9use slop_algebra::{AbstractField, Field};
10use sp1_derive::{AlignedBorrow, InputExpr, InputParams, IntoShape, SP1OperationBuilder};
11
12use crate::{
13    air::{SP1Operation, SP1OperationBuilder, WordAirBuilder},
14    operations::{U16MSBOperation, U16MSBOperationInput},
15};
16
17/// A set of columns needed to compute the sub of two words.
18#[derive(
19    AlignedBorrow, Default, Debug, Clone, Copy, IntoShape, SP1OperationBuilder, StructReflection,
20)]
21#[repr(C)]
22pub struct SubwOperation<T> {
23    /// The result of `a - b`.
24    pub value: [T; WORD_SIZE / 2],
25    /// The msb of the result.
26    pub msb: U16MSBOperation<T>,
27}
28
29impl<F: Field> SubwOperation<F> {
30    pub fn populate(&mut self, record: &mut impl ByteRecord, a_u64: u64, b_u64: u64) {
31        let value = (Wrapping(a_u64 as i32) - Wrapping(b_u64 as i32)).0 as i64 as u64;
32        let limbs = u64_to_u16_limbs(value);
33        self.value = [F::from_canonical_u16(limbs[0]), F::from_canonical_u16(limbs[1])];
34
35        // Range check
36        record.add_u16_range_checks(&limbs[..WORD_SIZE / 2]);
37        self.msb.populate_msb(record, limbs[1]);
38    }
39
40    /// Evaluate the sub operation.
41    /// Assumes that `a`, `b` are valid `Word`s of u16 limbs.
42    /// Constrains that `is_real` is boolean.
43    /// If `is_real` is true, the `value` is constrained to be the lower u32 of the SUBW result.
44    /// Also, the `msb` will be constrained to equal the most significant bit of the `value`.
45    pub fn eval<AB>(
46        builder: &mut AB,
47        a: Word<AB::Var>,
48        b: Word<AB::Var>,
49        cols: SubwOperation<AB::Var>,
50        is_real: AB::Expr,
51    ) where
52        AB: SP1AirBuilder + SP1OperationBuilder<U16MSBOperation<<AB as AirBuilder>::F>>,
53    {
54        builder.assert_bool(is_real.clone());
55
56        let base = AB::F::from_canonical_u32(1 << 16);
57        let mut builder_is_real = builder.when(is_real.clone());
58        let mut carry = AB::Expr::one();
59        let one = AB::Expr::one();
60
61        // Use the same logic as addition, for (a + (2^32 - b)).
62        // This by using `2^16 - 1 - b[i]` as the added limb, and initializing the carry to 1.
63        for i in 0..WORD_SIZE / 2 {
64            carry = (a[i] + base - one.clone() - b[i] - cols.value[i] + carry) * base.inverse();
65            builder_is_real.assert_bool(carry.clone());
66        }
67
68        // Range check each limb.
69        builder.slice_range_check_u16(&cols.value, is_real.clone());
70
71        U16MSBOperation::<AB::F>::eval(
72            builder,
73            U16MSBOperationInput::new(cols.value[1].into(), cols.msb, is_real.clone()),
74        );
75    }
76}
77
78#[derive(Debug, Clone, InputExpr, InputParams)]
79pub struct SubwOperationInput<AB: SP1AirBuilder> {
80    pub a: Word<AB::Var>,
81    pub b: Word<AB::Var>,
82    pub cols: SubwOperation<AB::Var>,
83    pub is_real: AB::Expr,
84}
85
86impl<AB> SP1Operation<AB> for SubwOperation<<AB as AirBuilder>::F>
87where
88    AB: SP1AirBuilder + SP1OperationBuilder<U16MSBOperation<<AB as AirBuilder>::F>>,
89{
90    type Input = SubwOperationInput<AB>;
91    type Output = ();
92
93    fn lower(builder: &mut AB, input: Self::Input) -> Self::Output {
94        Self::eval(builder, input.a, input.b, input.cols, input.is_real);
95    }
96}