Skip to main content

foundry_evm_symbolic/runtime/solver/normalize/
mul_div.rs

1//! Recognition of the 512-bit product high word and of the full-precision `mulDiv` quotient.
2
3use super::*;
4
5/// Newton steps that lift the `(3 * d) ^ 2` seed, an inverse modulo `2**4`, to `2**256`.
6const MIN_NEWTON_STEPS: usize = 6;
7
8/// Returns `(a, b)` when `minuend - subtrahend` is the high word of `a * b`.
9pub(super) fn mul_high_operands<'a>(
10    minuend: &'a SymExpr,
11    subtrahend: &'a SymExpr,
12) -> Option<(&'a SymExpr, &'a SymExpr)> {
13    // `(mm - lo) - lt(mm, lo)`.
14    if let SymExprKind::BinOp(SymBinOp::Sub, mm, lo) = minuend.kind()
15        && is_less_than_word(subtrahend, mm, lo)
16    {
17        return wide_product_operands(mm, lo);
18    }
19    // `mm - (lo + lt(mm, lo))`, whose sum is built as `ite(mm < lo, lo + 1, lo)`.
20    match subtrahend.kind() {
21        SymExprKind::Ite(condition, incremented, lo)
22            if is_less_than(condition, minuend, lo) && is_increment_of(incremented, lo) =>
23        {
24            wide_product_operands(minuend, lo)
25        }
26        SymExprKind::BinOp(SymBinOp::Add, left, right) => [(left, right), (right, left)]
27            .into_iter()
28            .find(|(lo, borrow)| is_less_than_word(borrow, minuend, lo))
29            .and_then(|(lo, _)| wide_product_operands(minuend, lo)),
30        _ => None,
31    }
32}
33
34/// Returns `(a, b, d)` when `expr` is the 512-by-256-bit `mulDiv(a, b, d)` quotient.
35///
36/// For any `d != 0` the algorithm computes `floor(a * b / d)` modulo `2**256`. The rewrite is
37/// still applied only under the library's own `mul_high(a, b) < d` check, where the quotient fits
38/// a word and the truncation never matters.
39pub(super) fn full_mul_div_operands(expr: &SymExpr) -> Option<(&SymExpr, &SymExpr, &SymExpr)> {
40    let SymExprKind::BinOp(SymBinOp::Mul, left, right) = expr.kind() else {
41        return None;
42    };
43    [(left, right), (right, left)].into_iter().find_map(|(shifted, inverse)| {
44        let odd = newton_inverse_operand(inverse)?;
45        let (denominator, twos) = word_division_operands(odd)?;
46        if !is_lowest_set_bit(twos, denominator) {
47            return None;
48        }
49        exact_shifted_product_operands(shifted, denominator, twos)
50    })
51}
52
53impl ConstraintContext {
54    /// Replaces a recognized `mulDiv` quotient by its exact value once the context proves
55    /// `mul_high(a, b) < d`.
56    pub(super) fn full_mul_div(&self, cx: &mut SymCx, expr: &SymExpr) -> Option<SymExpr> {
57        let (left, right, denominator) = full_mul_div_operands(expr)?;
58        let high = SymExpr::binop(cx, SymBinOp::MulHigh, left.clone(), right.clone());
59        let below = SymBoolExpr::cmp(cx, SymCmpOp::Ult, high.clone(), denominator.clone());
60        let not_above = SymBoolExpr::cmp(cx, SymCmpOp::Ule, denominator.clone(), high).not(cx);
61        // `mul_high(a, d) < d` holds exactly when `d != 0`.
62        let factor_below = (denominator == left || denominator == right)
63            && self.interval(denominator).is_some_and(|interval| !interval.min.is_zero());
64        (self.facts.contains(&below) || self.facts.contains(&not_above) || factor_below).then(
65            || {
66                SymExpr::ternop(
67                    cx,
68                    SymTernOp::MulDiv,
69                    left.clone(),
70                    right.clone(),
71                    denominator.clone(),
72                )
73            },
74        )
75    }
76
77    /// Records `mul_high(a, b) == 0` as a non-wrapping product.
78    pub(super) fn record_zero_mul_high(&mut self, constraint: &SymBoolExpr) {
79        if let Some(word) = constraint.zero_check_operand()
80            && let SymExprKind::BinOp(SymBinOp::MulHigh, left, right) = word.kind()
81        {
82            self.non_wrapping_products.insert((left.clone(), right.clone()));
83        }
84    }
85}
86
87/// Decides comparisons between `mul_high(a, b)` and one of its factors.
88pub(super) fn normalize_mul_high_factor_cmp(
89    cx: &mut SymCx,
90    op: SymCmpOp,
91    left: &SymExpr,
92    right: &SymExpr,
93) -> Option<SymBoolExpr> {
94    let (small, large, strict) = match op {
95        SymCmpOp::Ult => (left, right, true),
96        SymCmpOp::Ugt => (right, left, true),
97        SymCmpOp::Ule => (left, right, false),
98        SymCmpOp::Uge => (right, left, false),
99        SymCmpOp::Eq | SymCmpOp::Slt | SymCmpOp::Sgt => return None,
100    };
101    // `a * b < 2**256 * b`, so `mul_high(a, b) < b` exactly when `b != 0`.
102    if is_mul_high_factor(small, large) {
103        return Some(if strict {
104            SymBoolExpr::eq_word_const(cx, large, U256::ZERO).not(cx)
105        } else {
106            SymBoolExpr::constant(cx, true)
107        });
108    }
109    if is_mul_high_factor(large, small) {
110        return Some(if strict {
111            SymBoolExpr::constant(cx, false)
112        } else {
113            SymBoolExpr::eq_word_const(cx, small, U256::ZERO)
114        });
115    }
116    None
117}
118
119/// Rewrites `q + c == k` and `!q == k` for a word quotient `q` to `q == k'`, where a division
120/// reaches `MAX` only as `MAX / 1`.
121pub(super) fn normalize_quotient_offset_eq(
122    cx: &mut SymCx,
123    left: &SymExpr,
124    right: &SymExpr,
125) -> Option<SymBoolExpr> {
126    let mut target = right.as_const()?;
127    let mut quotient = left;
128    loop {
129        match quotient.kind() {
130            SymExprKind::BinOp(SymBinOp::Add, value, offset)
131                if let Some(offset) = offset.as_const() =>
132            {
133                target = target.wrapping_sub(offset);
134                quotient = value;
135            }
136            SymExprKind::Not(value) => {
137                target = !target;
138                quotient = value;
139            }
140            _ => break,
141        }
142    }
143    if let Some((numerator, denominator)) = word_division_operands(quotient)
144        && target == U256::MAX
145    {
146        let unit = SymBoolExpr::eq_word_const(cx, denominator, U256::ONE);
147        let max = SymBoolExpr::eq_word_const(cx, numerator, U256::MAX);
148        return Some(SymBoolExpr::and(cx, vec![unit, max]));
149    }
150    let is_quotient = word_division_operands(quotient).is_some()
151        || matches!(quotient.kind(), SymExprKind::TernOp(SymTernOp::MulDiv, ..));
152    (is_quotient && quotient != left).then(|| SymBoolExpr::eq_word_const(cx, quotient, target))
153}
154
155/// Returns `(x, y)` when `word` is the overflow check `x == 0 || (x * y) / x == y`, which holds
156/// exactly when `mul_high(x, y) == 0`.
157pub(super) fn checked_product_guard_operands(word: &SymExpr) -> Option<(&SymExpr, &SymExpr)> {
158    let SymExprKind::BinOp(SymBinOp::Or, left, right) = word.kind() else { return None };
159    [(left, right), (right, left)].into_iter().find_map(|(zero_word, quotient_word)| {
160        let zero_check = bool_word_condition(zero_word)?;
161        let quotient_check = bool_word_condition(quotient_word)?;
162        let factor = zero_check.zero_check_operand()?;
163        let SymBoolExprKind::Cmp(SymCmpOp::Eq, a, b) = quotient_check.kind() else {
164            return None;
165        };
166        [(a, b), (b, a)].into_iter().find_map(|(quotient, other)| {
167            let (product, divisor) = word_division_operands(quotient)?;
168            (divisor == factor && is_product_of(product, factor, other)).then_some((factor, other))
169        })
170    })
171}
172
173fn bool_word_condition(word: &SymExpr) -> Option<&SymBoolExpr> {
174    match word.kind() {
175        SymExprKind::Ite(condition, one, zero)
176            if one.as_const() == Some(U256::ONE) && zero.as_const() == Some(U256::ZERO) =>
177        {
178            Some(condition)
179        }
180        _ => None,
181    }
182}
183
184fn is_mul_high_factor(high: &SymExpr, factor: &SymExpr) -> bool {
185    matches!(
186        high.kind(),
187        SymExprKind::BinOp(SymBinOp::MulHigh, left, right) if left == factor || right == factor
188    )
189}
190
191fn wide_product_operands<'a>(mm: &'a SymExpr, lo: &SymExpr) -> Option<(&'a SymExpr, &'a SymExpr)> {
192    let SymExprKind::TernOp(SymTernOp::MulMod, left, right, modulus) = mm.kind() else {
193        return None;
194    };
195    (modulus.as_const() == Some(U256::MAX) && is_product_of(lo, left, right))
196        .then_some((left, right))
197}
198
199fn is_product_of(expr: &SymExpr, left: &SymExpr, right: &SymExpr) -> bool {
200    matches!(
201        expr.kind(),
202        SymExprKind::BinOp(SymBinOp::Mul, a, b)
203            if (a == left && b == right) || (a == right && b == left)
204    )
205}
206
207fn is_less_than_word(word: &SymExpr, left: &SymExpr, right: &SymExpr) -> bool {
208    matches!(
209        word.kind(),
210        SymExprKind::Ite(condition, one, zero)
211            if one.as_const() == Some(U256::ONE)
212                && zero.as_const() == Some(U256::ZERO)
213                && is_less_than(condition, left, right)
214    )
215}
216
217fn is_less_than(condition: &SymBoolExpr, left: &SymExpr, right: &SymExpr) -> bool {
218    match condition.kind() {
219        SymBoolExprKind::Cmp(SymCmpOp::Ult, a, b) => a == left && b == right,
220        SymBoolExprKind::Cmp(SymCmpOp::Ugt, a, b) => a == right && b == left,
221        _ => false,
222    }
223}
224
225fn is_increment_of(expr: &SymExpr, value: &SymExpr) -> bool {
226    matches!(
227        expr.kind(),
228        SymExprKind::BinOp(SymBinOp::Add, a, one) if a == value && one.as_const() == Some(U256::ONE)
229    )
230}
231
232/// Returns `d` when `expr` is at least [`MIN_NEWTON_STEPS`] of `inv * (2 - d * inv)` over the
233/// `(3 * d) ^ 2` seed, the inverse of an odd `d` modulo `2**256`.
234fn newton_inverse_operand(mut expr: &SymExpr) -> Option<&SymExpr> {
235    let mut odd = None;
236    let mut steps = 0;
237    loop {
238        match expr.kind() {
239            SymExprKind::BinOp(SymBinOp::Xor, seed, two)
240                if two.as_const() == Some(U256::from(2)) =>
241            {
242                let SymExprKind::BinOp(SymBinOp::Mul, value, three) = seed.kind() else {
243                    return None;
244                };
245                let matches = three.as_const() == Some(U256::from(3))
246                    && odd.is_none_or(|odd| odd == value)
247                    && steps >= MIN_NEWTON_STEPS;
248                return matches.then_some(value);
249            }
250            SymExprKind::BinOp(SymBinOp::Mul, left, right) => {
251                let (previous, value) = [(left, right), (right, left)].into_iter().find_map(
252                    |(previous, correction)| {
253                        let SymExprKind::BinOp(SymBinOp::Sub, two, product) = correction.kind()
254                        else {
255                            return None;
256                        };
257                        let SymExprKind::BinOp(SymBinOp::Mul, a, b) = product.kind() else {
258                            return None;
259                        };
260                        if two.as_const() != Some(U256::from(2)) {
261                            return None;
262                        }
263                        if a == previous {
264                            Some((previous, b))
265                        } else if b == previous {
266                            Some((previous, a))
267                        } else {
268                            None
269                        }
270                    },
271                )?;
272                if odd.is_some_and(|odd| odd != value) {
273                    return None;
274                }
275                odd = Some(value);
276                steps += 1;
277                expr = previous;
278            }
279            _ => return None,
280        }
281    }
282}
283
284/// Returns whether `twos` is `(0 - d) & d`, the lowest set bit of `d`.
285fn is_lowest_set_bit(twos: &SymExpr, denominator: &SymExpr) -> bool {
286    let SymExprKind::BinOp(SymBinOp::And, left, right) = twos.kind() else {
287        return false;
288    };
289    (left == denominator && is_negation_of(right, denominator))
290        || (right == denominator && is_negation_of(left, denominator))
291}
292
293fn is_negation_of(expr: &SymExpr, value: &SymExpr) -> bool {
294    matches!(
295        expr.kind(),
296        SymExprKind::BinOp(SymBinOp::Sub, zero, negated)
297            if zero.as_const() == Some(U256::ZERO) && negated == value
298    )
299}
300
301/// Returns `(a, b, d)` when `expr` is the low word of `(a * b - a * b % d) / twos`: the exact
302/// low quotient `(lo - rem) / twos` joined with `(high - borrow) * (2**256 / twos)`.
303fn exact_shifted_product_operands<'a>(
304    expr: &'a SymExpr,
305    denominator: &'a SymExpr,
306    twos: &SymExpr,
307) -> Option<(&'a SymExpr, &'a SymExpr, &'a SymExpr)> {
308    let SymExprKind::BinOp(SymBinOp::Or, left, right) = expr.kind() else {
309        return None;
310    };
311    [(left, right), (right, left)].into_iter().find_map(|(low, shifted_high)| {
312        let (difference, low_twos) = word_division_operands(low)?;
313        let SymExprKind::BinOp(SymBinOp::Mul, high_part, flip) = shifted_high.kind() else {
314            return None;
315        };
316        if low_twos != twos {
317            return None;
318        }
319        [(high_part, flip), (flip, high_part)].into_iter().find_map(|(high_part, flip)| {
320            let (a, b) = exact_product_parts(difference, high_part, denominator)?;
321            is_inverse_shift(flip, twos).then_some((a, b, denominator))
322        })
323    })
324}
325
326/// Returns `(a, b)` when `low` is `a * b - r` and `high` is `mul_high(a, b) - lt(a * b, r)` for
327/// `r = mulmod(a, b, d)`.
328///
329/// When `d` is `a` or `b`, construction folds `r` to zero, which also drops the subtraction and
330/// the borrow: `low` is `a * b` and `high` is `mul_high(a, b)`.
331fn exact_product_parts<'a>(
332    low: &'a SymExpr,
333    high: &'a SymExpr,
334    denominator: &SymExpr,
335) -> Option<(&'a SymExpr, &'a SymExpr)> {
336    if let SymExprKind::BinOp(SymBinOp::Sub, lo, remainder) = low.kind()
337        && let SymExprKind::TernOp(SymTernOp::MulMod, a, b, modulus) = remainder.kind()
338        && let SymExprKind::BinOp(SymBinOp::Sub, high_word, borrow) = high.kind()
339        && modulus == denominator
340        && is_product_of(lo, a, b)
341        && is_mul_high_of(high_word, a, b)
342        && is_less_than_word(borrow, lo, remainder)
343    {
344        return Some((a, b));
345    }
346    let SymExprKind::BinOp(SymBinOp::Mul, a, b) = low.kind() else { return None };
347    ((a == denominator || b == denominator) && is_mul_high_of(high, a, b)).then_some((a, b))
348}
349
350fn is_mul_high_of(expr: &SymExpr, a: &SymExpr, b: &SymExpr) -> bool {
351    matches!(
352        expr.kind(),
353        SymExprKind::BinOp(SymBinOp::MulHigh, left, right)
354            if (left == a && right == b) || (left == b && right == a)
355    )
356}
357
358/// Returns whether `expr` is `(0 - twos) / twos + 1`, which is `2**256 / twos` modulo `2**256`.
359fn is_inverse_shift(expr: &SymExpr, twos: &SymExpr) -> bool {
360    let SymExprKind::BinOp(SymBinOp::Add, quotient, one) = expr.kind() else {
361        return false;
362    };
363    one.as_const() == Some(U256::ONE)
364        && word_division_operands(quotient)
365            .is_some_and(|(negated, divisor)| divisor == twos && is_negation_of(negated, twos))
366}
367
368/// Returns `(n, d)` for `n / d`, also in the `ite(d == 0, 0, n / d)` form of the EVM `DIV`.
369pub(super) fn word_division_operands(expr: &SymExpr) -> Option<(&SymExpr, &SymExpr)> {
370    let division = match expr.kind() {
371        SymExprKind::Ite(condition, zero, division) if zero.as_const() == Some(U256::ZERO) => {
372            let (_, denominator) = division.udiv_operands()?;
373            (condition.zero_check_operand() == Some(denominator)).then_some(division)?
374        }
375        _ => expr,
376    };
377    division.udiv_operands()
378}