Skip to main content

foundry_evm_symbolic/runtime/expr/
expr.rs

1use super::{hashcons::HashConsed, *};
2
3// Boolean selector recovery is an optional expression rewrite. Bound it to one word's worth of
4// unique nodes so adversarial expression trees cannot make construction unbounded.
5const MAX_BITWISE_BOOL_WORD_VISITS: usize = 256;
6const MAX_CONSTANT_DIFFERENCE_VISITS: usize = 256;
7// Storage layout keys `keccak(..) + offset` are assumed not to alias fixed slots or other hash
8// bases only while the offset stays below `2^64`, the bound Solidity's `push` enforces on
9// dynamic array lengths.
10pub(crate) const STORAGE_LAYOUT_OFFSET_BITS: usize = 64;
11
12impl SymExpr {
13    pub(crate) fn select_storage_write(
14        self,
15        cx: &mut SymCx,
16        write_key: Self,
17        write_value: Self,
18        base: Self,
19    ) -> Self {
20        if write_value == base {
21            return base;
22        }
23        let condition = self.storage_key_eq(cx, &write_key);
24        match condition.as_const() {
25            Some(true) => write_value,
26            Some(false) => base,
27            None => Self::ite(cx, condition, write_value, base),
28        }
29    }
30
31    pub(crate) fn storage_key_eq(&self, cx: &mut SymCx, write_key: &Self) -> SymBoolExpr {
32        if let (Some(read), Some(write)) = (self.as_const(), write_key.as_const()) {
33            return SymBoolExpr::constant(cx, read == write);
34        }
35        if let (Some(read_root), Some(write_root)) =
36            (self.storage_mapping_root_slot(cx), write_key.storage_mapping_root_slot(cx))
37            && read_root != write_root
38        {
39            return SymBoolExpr::constant(cx, false);
40        }
41        // The hash assumption only rules out aliasing for small offsets: an offset chosen as
42        // `slot - keccak(..)` reaches any slot, so large offsets keep real word equality.
43        match (self.storage_layout_key(cx), write_key.storage_layout_key(cx)) {
44            (Some((read_base, read_offset)), Some((write_base, write_offset))) => {
45                // On one base, `base + i == base + j` iff `i == j`, so only distinct bases alias.
46                if read_base == write_base {
47                    return SymBoolExpr::eq(cx, read_offset, write_offset);
48                }
49                let large_read_offset = storage_offset_is_large(cx, &read_offset);
50                let large_write_offset = storage_offset_is_large(cx, &write_offset);
51                let large_offset = SymBoolExpr::or(cx, vec![large_read_offset, large_write_offset]);
52                // Large offsets on two concrete hash bases are compared exactly.
53                if large_offset.as_const() != Some(false)
54                    && read_base.as_const().is_some()
55                    && write_base.as_const().is_some()
56                {
57                    return SymBoolExpr::eq(cx, self.clone(), write_key.clone());
58                }
59                let read_base = read_base.storage_base_eq(cx, &write_base);
60                let read_offset = SymBoolExpr::eq(cx, read_offset, write_offset);
61                let same_layout_slot = SymBoolExpr::and(cx, vec![read_base, read_offset]);
62                if large_offset.as_const() == Some(false) {
63                    return same_layout_slot;
64                }
65                let words_eq = SymBoolExpr::eq(cx, self.clone(), write_key.clone());
66                let aliased = SymBoolExpr::and(cx, vec![large_offset, words_eq]);
67                SymBoolExpr::or(cx, vec![same_layout_slot, aliased])
68            }
69            // A constant that is not a hash base or near one is a fixed slot, which a symbolic
70            // hash base only reaches through a large offset.
71            (Some((base, offset)), None) | (None, Some((base, offset)))
72                if base.as_const().is_none()
73                    && (self.as_const().is_some() || write_key.as_const().is_some()) =>
74            {
75                let large_offset = storage_offset_is_large(cx, &offset);
76                if large_offset.as_const() == Some(false) {
77                    return SymBoolExpr::constant(cx, false);
78                }
79                let words_eq = SymBoolExpr::eq(cx, self.clone(), write_key.clone());
80                SymBoolExpr::and(cx, vec![large_offset, words_eq])
81            }
82            _ => SymBoolExpr::eq(cx, self.clone(), write_key.clone()),
83        }
84    }
85
86    /// Compares two storage hash bases, assuming different Keccak preimages never collide.
87    fn storage_base_eq(&self, cx: &mut SymCx, other: &Self) -> SymBoolExpr {
88        // Dynamic array data slots `keccak(slot)` are equal when their slots are.
89        if let (Some(read), Some(write)) =
90            (self.keccak_preimage(cx, 32), other.keccak_preimage(cx, 32))
91        {
92            let read = Self::from_bytes(cx, read[..32].iter().cloned());
93            let write = Self::from_bytes(cx, write[..32].iter().cloned());
94            return read.storage_base_eq(cx, &write);
95        }
96        let (Some(read), Some(write)) =
97            (self.storage_mapping_key(cx), other.storage_mapping_key(cx))
98        else {
99            return SymBoolExpr::eq(cx, self.clone(), other.clone());
100        };
101
102        let key_eq = storage_mapping_key_eq(cx, &read, &write);
103        let slot_eq = read.slot.storage_base_eq(cx, &write.slot);
104        SymBoolExpr::and(cx, vec![key_eq, slot_eq])
105    }
106
107    pub(crate) fn storage_mapping_key(&self, cx: &mut SymCx) -> Option<StorageMappingKey> {
108        let bytes = self.keccak_preimage(cx, 64)?;
109        let key_bytes = &bytes[..32];
110        let preserve_key_bytes = (!key_bytes.iter().all(|byte| byte.as_const().is_some())
111            && word_from_extracted_bytes(key_bytes).is_none())
112        .then(|| key_bytes.to_vec());
113        let key = Self::from_bytes(cx, key_bytes.iter().cloned());
114        let slot = Self::from_bytes(cx, bytes[32..64].iter().cloned());
115        Some(StorageMappingKey { key, key_bytes: preserve_key_bytes, slot })
116    }
117
118    pub(crate) fn storage_mapping_provenance_observed_with(
119        &self,
120        cx: &mut SymCx,
121        mut observed_preimage: impl FnMut(&Self) -> Option<Arc<[Self]>>,
122    ) -> Option<SymbolicMappingProvenance> {
123        let mut current = self.clone();
124        let mut keys = Vec::new();
125        let mut visited = Vec::new();
126        loop {
127            if visited.contains(&current) {
128                return None;
129            }
130            visited.push(current.clone());
131            let bytes = observed_preimage(&current)?;
132            if bytes.len() != 64 {
133                return None;
134            }
135            let key = Self::from_bytes(cx, bytes[..32].iter().cloned());
136            keys.push(key);
137            current = Self::from_bytes(cx, bytes[32..64].iter().cloned());
138            match current.kind() {
139                SymExprKind::Const(root_slot) if observed_preimage(&current).is_none() => {
140                    keys.reverse();
141                    return Some(SymbolicMappingProvenance { root_slot: *root_slot, keys });
142                }
143                SymExprKind::Const(_) | SymExprKind::Keccak { .. } => {}
144                _ => return None,
145            }
146        }
147    }
148
149    fn storage_mapping_root_slot(&self, cx: &mut SymCx) -> Option<U256> {
150        let bytes = self.keccak_preimage(cx, 64)?;
151        let slot = Self::from_bytes(cx, bytes[32..64].iter().cloned());
152        match slot.kind() {
153            SymExprKind::Const(_) if slot.keccak_preimage(cx, 64).is_some() => {
154                slot.storage_mapping_root_slot(cx)
155            }
156            SymExprKind::Const(slot) => Some(*slot),
157            SymExprKind::Keccak { .. } => slot.storage_mapping_root_slot(cx),
158            _ => None,
159        }
160    }
161
162    fn keccak_preimage(&self, cx: &SymCx, len: usize) -> Option<Arc<[Self]>> {
163        match self.kind() {
164            SymExprKind::Keccak { len: hashed, bytes, .. }
165                if hashed.as_const() == Some(U256::from(len)) && bytes.len() >= len =>
166            {
167                Some(bytes.clone())
168            }
169            SymExprKind::Const(hash) => {
170                cx.concrete_keccak_preimage(*hash).filter(|bytes| bytes.len() == len)
171            }
172            _ => None,
173        }
174    }
175
176    fn storage_layout_key(&self, cx: &mut SymCx) -> Option<(Self, Self)> {
177        match self.kind() {
178            SymExprKind::Keccak { .. } => Some((self.clone(), Self::zero(cx))),
179            // Constant folding turns `keccak(7, s) + 1` into an unrecorded constant.
180            SymExprKind::Const(value) => {
181                let hash = cx.concrete_keccak_base(*value, STORAGE_LAYOUT_OFFSET_BITS)?;
182                Some((Self::constant(cx, hash), Self::constant(cx, *value - hash)))
183            }
184            SymExprKind::BinOp(SymBinOp::Add, left, right) => {
185                if let Some((base, offset)) = left.storage_layout_key(cx)
186                    && !right.contains_keccak()
187                {
188                    let offset = Self::binop(cx, SymBinOp::Add, offset, right.clone());
189                    return Some((base, offset));
190                }
191                if let Some((base, offset)) = right.storage_layout_key(cx)
192                    && !left.contains_keccak()
193                {
194                    let offset = Self::binop(cx, SymBinOp::Add, offset, left.clone());
195                    return Some((base, offset));
196                }
197                None
198            }
199            _ => None,
200        }
201    }
202}
203
204pub(crate) struct StorageMappingKey {
205    key: SymExpr,
206    key_bytes: Option<Vec<SymExpr>>,
207    slot: SymExpr,
208}
209
210#[derive(Clone, Debug, PartialEq, Eq)]
211pub(crate) struct SymbolicMappingProvenance {
212    pub(crate) root_slot: U256,
213    pub(crate) keys: Vec<SymExpr>,
214}
215
216fn storage_mapping_key_eq(
217    cx: &mut SymCx,
218    read: &StorageMappingKey,
219    write: &StorageMappingKey,
220) -> SymBoolExpr {
221    if read.key_bytes.is_some() || write.key_bytes.is_some() {
222        let read_owned;
223        let read_bytes = if let Some(bytes) = read.key_bytes.as_deref() {
224            bytes
225        } else {
226            read_owned = read.key.clone().into_byte_exprs(cx);
227            &read_owned
228        };
229        let write_owned;
230        let write_bytes = if let Some(bytes) = write.key_bytes.as_deref() {
231            bytes
232        } else {
233            write_owned = write.key.clone().into_byte_exprs(cx);
234            &write_owned
235        };
236        let byte_equalities = read_bytes
237            .iter()
238            .zip(write_bytes)
239            .map(|(read, write)| {
240                let read = read.byte_term(cx, 31).unwrap_or_else(|| read.clone().low_byte(cx));
241                let write = write.byte_term(cx, 31).unwrap_or_else(|| write.clone().low_byte(cx));
242                SymBoolExpr::eq(cx, read, write)
243            })
244            .collect();
245        SymBoolExpr::and(cx, byte_equalities)
246    } else {
247        SymBoolExpr::eq(cx, read.key.clone(), write.key.clone())
248    }
249}
250
251/// Returns the condition under which a storage layout offset is too large to assume no aliasing.
252fn storage_offset_is_large(cx: &mut SymCx, offset: &SymExpr) -> SymBoolExpr {
253    if offset.unsigned_bits() <= STORAGE_LAYOUT_OFFSET_BITS {
254        return SymBoolExpr::constant(cx, false);
255    }
256    SymBoolExpr::cmp_word_const(cx, SymCmpOp::Uge, offset, U256::ONE << STORAGE_LAYOUT_OFFSET_BITS)
257}
258
259fn masked_expr_matches(candidate: &SymExprKind, target: &SymExpr) -> Option<U256> {
260    match candidate {
261        SymExprKind::BinOp(SymBinOp::And, left, right) if left == target => right.eval(),
262        SymExprKind::BinOp(SymBinOp::And, left, right) if right == target => left.eval(),
263        _ => None,
264    }
265}
266
267fn context_forces_masked_expr(context: &[SymBoolExpr], target: &SymExpr, mask: U256) -> bool {
268    context.iter().any(|condition| match condition.kind() {
269        SymBoolExprKind::Cmp(SymCmpOp::Eq, left, right) => {
270            (left == target && masked_expr_matches(right.kind(), target) == Some(mask))
271                || (right == target && masked_expr_matches(left.kind(), target) == Some(mask))
272        }
273        SymBoolExprKind::And(values) => context_forces_masked_expr(values, target, mask),
274        _ => false,
275    })
276}
277
278pub(crate) fn concrete_expr_bytes(
279    bytes: &[SymExpr],
280    reason: &'static str,
281) -> Result<Vec<u8>, SymbolicError> {
282    bytes
283        .iter()
284        .map(|byte| match byte.as_const() {
285            Some(value) => Ok(value.to::<u8>()),
286            None => Err(SymbolicError::Unsupported(reason)),
287        })
288        .collect()
289}
290
291pub(crate) fn mask_low_bits(mask: U256) -> Option<usize> {
292    let bits = mask.bit_len();
293    (mask == mask_bits(U256::MAX, bits)).then_some(bits)
294}
295
296fn power_of_two_shift(value: U256) -> Option<usize> {
297    if value <= U256::ONE || !value.is_power_of_two() {
298        return None;
299    }
300    Some(value.bit_len() - 1)
301}
302
303pub(in crate::runtime::expr) fn low_masked_source(expr: &SymExpr, bits: usize) -> Option<&SymExpr> {
304    match expr.kind() {
305        // `a & low_mask => a`.
306        SymExprKind::BinOp(SymBinOp::And, left, right)
307            if right.as_const().and_then(mask_low_bits) == Some(bits) =>
308        {
309            Some(left)
310        }
311        _ => None,
312    }
313}
314
315pub(in crate::runtime::expr) fn low_masked_source_any(expr: &SymExpr) -> Option<&SymExpr> {
316    match expr.kind() {
317        // `a & low_mask => a`.
318        SymExprKind::BinOp(SymBinOp::And, left, right)
319            if right.as_const().and_then(mask_low_bits).is_some() =>
320        {
321            Some(left)
322        }
323        _ => None,
324    }
325}
326
327/// Returns `(a, d)` for the rounded product `(a / d) * d` in either operand order.
328pub(crate) fn rounded_product_operands<'a>(
329    left: &'a SymExpr,
330    right: &'a SymExpr,
331) -> Option<(&'a SymExpr, &'a SymExpr)> {
332    [(left, right), (right, left)].into_iter().find_map(|(quotient, factor)| {
333        let (dividend, divisor) = quotient.udiv_operands()?;
334        (divisor == factor).then_some((dividend, divisor))
335    })
336}
337
338/// Returns `a` for the Euclidean sum `(a / d) * d + a % d` in either operand order.
339pub(in crate::runtime) fn euclidean_sum_dividend<'a>(
340    left: &'a SymExpr,
341    right: &'a SymExpr,
342) -> Option<&'a SymExpr> {
343    [(left, right), (right, left)].into_iter().find_map(|(product, remainder)| {
344        let SymExprKind::BinOp(SymBinOp::URem, dividend, divisor) = remainder.kind() else {
345            return None;
346        };
347        let SymExprKind::BinOp(SymBinOp::Mul, left, right) = product.kind() else { return None };
348        (rounded_product_operands(left, right) == Some((dividend, divisor))).then_some(dividend)
349    })
350}
351
352/// Returns `a` for the sum `(a - b) + b` in either operand order.
353///
354/// Word addition and subtraction wrap modulo 2^256, so the terms cancel for every operand.
355fn cancelled_difference_minuend<'a>(left: &'a SymExpr, right: &'a SymExpr) -> Option<&'a SymExpr> {
356    [(left, right), (right, left)].into_iter().find_map(|(difference, term)| {
357        match difference.kind() {
358            SymExprKind::BinOp(SymBinOp::Sub, minuend, subtrahend) if subtrahend == term => {
359                Some(minuend)
360            }
361            _ => None,
362        }
363    })
364}
365
366fn word_from_extracted_bytes(bytes: &[SymExpr]) -> Option<SymExpr> {
367    if bytes.len() < 32 {
368        return None;
369    }
370
371    let source = bytes
372        .iter()
373        .take(32)
374        .enumerate()
375        .find_map(|(idx, byte)| byte.extracted_byte_source(idx))?;
376
377    for (idx, byte) in bytes.iter().take(32).enumerate() {
378        if let Some(byte_source) = byte.extracted_byte_source(idx) {
379            if byte_source != source {
380                return None;
381            }
382            continue;
383        }
384
385        let byte = byte.as_const()?;
386        if source.known_byte(idx) != Some(byte.to::<u8>()) {
387            return None;
388        }
389    }
390    Some(source)
391}
392
393#[derive(Clone, PartialEq, Eq, Hash)]
394pub(crate) struct SymExpr {
395    pub(in crate::runtime::expr) kind: HashConsed<SymExprKind>,
396}
397
398impl fmt::Debug for SymExpr {
399    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
400        self.kind().fmt(f)
401    }
402}
403
404#[derive(Clone, PartialEq, Eq, Hash)]
405pub(in crate::runtime) enum SymExprKind {
406    Const(U256),
407    Var(Symbol),
408    GasLeft(Symbol),
409    Keccak { name: Symbol, len: SymExpr, bytes: Arc<[SymExpr]> },
410    Hash { name: Symbol, algorithm: &'static str, bytes: Arc<[SymExpr]> },
411    Not(SymExpr),
412    BinOp(SymBinOp, SymExpr, SymExpr),
413    TernOp(SymTernOp, SymExpr, SymExpr, SymExpr),
414    Ite(SymBoolExpr, SymExpr, SymExpr),
415}
416
417/// Formats an expression as a tree.
418///
419/// A hash node prints only its name, because the name is a digest of the preimage. Printing the
420/// preimage again would repeat every nested preimage, so a chain of hashes over the previous hash
421/// would grow exponentially.
422impl fmt::Debug for SymExprKind {
423    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
424        match self {
425            Self::Const(value) => f.debug_tuple("Const").field(value).finish(),
426            Self::Var(symbol) => f.debug_tuple("Var").field(symbol).finish(),
427            Self::GasLeft(symbol) => f.debug_tuple("GasLeft").field(symbol).finish(),
428            Self::Keccak { name, len, .. } => f
429                .debug_struct("Keccak")
430                .field("name", name)
431                .field("len", len)
432                .finish_non_exhaustive(),
433            Self::Hash { name, algorithm, .. } => f
434                .debug_struct("Hash")
435                .field("name", name)
436                .field("algorithm", algorithm)
437                .finish_non_exhaustive(),
438            Self::Not(expr) => f.debug_tuple("Not").field(expr).finish(),
439            Self::BinOp(op, left, right) => {
440                f.debug_tuple("BinOp").field(op).field(left).field(right).finish()
441            }
442            Self::TernOp(op, first, second, third) => {
443                f.debug_tuple("TernOp").field(op).field(first).field(second).field(third).finish()
444            }
445            Self::Ite(condition, then, otherwise) => {
446                f.debug_tuple("Ite").field(condition).field(then).field(otherwise).finish()
447            }
448        }
449    }
450}
451
452impl SymExprKind {
453    pub(in crate::runtime) const fn get_var(&self) -> Option<Symbol> {
454        match self {
455            Self::Var(symbol)
456            | Self::GasLeft(symbol)
457            | Self::Keccak { name: symbol, .. }
458            | Self::Hash { name: symbol, .. } => Some(*symbol),
459            _ => None,
460        }
461    }
462
463    pub(in crate::runtime) const fn get_eval_var(&self) -> Option<Symbol> {
464        match self {
465            Self::Var(symbol) | Self::GasLeft(symbol) | Self::Hash { name: symbol, .. } => {
466                Some(*symbol)
467            }
468            _ => None,
469        }
470    }
471}
472
473impl SymExpr {
474    pub(in crate::runtime) fn kind(&self) -> &SymExprKind {
475        self.kind.value()
476    }
477
478    pub(in crate::runtime) fn from_kind(cx: &mut SymCx, kind: SymExprKind) -> Self {
479        cx.mk_expr_kind(kind)
480    }
481
482    pub(crate) fn zero(cx: &mut SymCx) -> Self {
483        Self::constant(cx, U256::ZERO)
484    }
485
486    pub(crate) fn one(cx: &mut SymCx) -> Self {
487        Self::constant(cx, U256::ONE)
488    }
489
490    pub(crate) fn constant(cx: &mut SymCx, value: U256) -> Self {
491        if value.is_zero() {
492            return cx.cached_zero();
493        }
494        if value == U256::ONE {
495            return cx.cached_one();
496        }
497        Self::from_kind(cx, SymExprKind::Const(value))
498    }
499
500    pub(crate) fn var(cx: &mut SymCx, name: &str) -> Self {
501        let symbol = cx.intern(name);
502        Self::get_var(cx, symbol)
503    }
504
505    pub(crate) fn get_var(cx: &mut SymCx, symbol: Symbol) -> Self {
506        Self::from_kind(cx, SymExprKind::Var(symbol))
507    }
508
509    pub(crate) fn gas_left(cx: &mut SymCx, id: usize) -> Self {
510        let symbol = cx.intern(&format!("gasleft_{id}"));
511        Self::from_kind(cx, SymExprKind::GasLeft(symbol))
512    }
513
514    pub(crate) fn not(cx: &mut SymCx, value: Self) -> Self {
515        match value.kind() {
516            SymExprKind::Const(value) => Self::constant(cx, !*value),
517            SymExprKind::Not(value) => value.clone(),
518            _ => Self::from_kind(cx, SymExprKind::Not(value)),
519        }
520    }
521
522    pub(crate) fn binop(cx: &mut SymCx, binop: SymBinOp, left: Self, right: Self) -> Self {
523        match binop {
524            SymBinOp::Add => match (left.kind(), right.kind()) {
525                (SymExprKind::Const(left_value), SymExprKind::Const(right_value)) => {
526                    // `const + const => const`.
527                    Self::constant(cx, binop.eval(*left_value, *right_value))
528                }
529                // `0 + a => a`.
530                (SymExprKind::Const(value), _) if value.is_zero() => right,
531                // `a + 0 => a`.
532                (_, SymExprKind::Const(value)) if value.is_zero() => left,
533                // `bool_word(c) + MAX => ite(c, 0, MAX)`.
534                (SymExprKind::Const(value), _) | (_, SymExprKind::Const(value))
535                    if *value == U256::MAX
536                        && let Some(condition) = if left.as_const() == Some(U256::MAX) {
537                            right.bitwise_bool_word_condition(cx)
538                        } else {
539                            left.bitwise_bool_word_condition(cx)
540                        } =>
541                {
542                    let zero = Self::zero(cx);
543                    let max = Self::constant(cx, U256::MAX);
544                    Self::ite(cx, condition, zero, max)
545                }
546                // `one_bit_word(c) + k => ite(c, k + 1, k)`.
547                (SymExprKind::Const(value), _)
548                    if let Some(condition) = right.bitwise_bool_word_condition(cx) =>
549                {
550                    let incremented = Self::constant(cx, value.wrapping_add(U256::ONE));
551                    let value = Self::constant(cx, *value);
552                    Self::ite(cx, condition, incremented, value)
553                }
554                (_, SymExprKind::Const(value))
555                    if let Some(condition) = left.bitwise_bool_word_condition(cx) =>
556                {
557                    let incremented = Self::constant(cx, value.wrapping_add(U256::ONE));
558                    let value = Self::constant(cx, *value);
559                    Self::ite(cx, condition, incremented, value)
560                }
561                _ => {
562                    let (left, right) = Self::ordered_commutative_operands(left, right);
563                    if let Some(value) = Self::add_with_const_ite(cx, &left, &right) {
564                        value
565                    } else if let Some(value) = Self::add_with_const_ite(cx, &right, &left) {
566                        value
567                    } else if let Some(dividend) = euclidean_sum_dividend(&left, &right) {
568                        // `(a / d) * d + a % d => a`.
569                        dividend.clone()
570                    } else if let Some(minuend) = cancelled_difference_minuend(&left, &right) {
571                        // `(a - b) + b => a`.
572                        minuend.clone()
573                    } else {
574                        Self::from_kind(cx, SymExprKind::BinOp(binop, left, right))
575                    }
576                }
577            },
578            SymBinOp::Sub => match (left.kind(), right.kind()) {
579                (SymExprKind::Const(left_value), SymExprKind::Const(right_value)) => {
580                    // `const - const => const`.
581                    Self::constant(cx, binop.eval(*left_value, *right_value))
582                }
583                // `a - 0 => a`.
584                (_, SymExprKind::Const(value)) if value.is_zero() => left,
585                // `a - a => 0`.
586                _ if left == right => Self::zero(cx),
587                // `(a + b) - a => b` and `(a + b) - b => a`.
588                (SymExprKind::BinOp(SymBinOp::Add, augend, addend), _) if *augend == right => {
589                    addend.clone()
590                }
591                (SymExprKind::BinOp(SymBinOp::Add, augend, addend), _) if *addend == right => {
592                    augend.clone()
593                }
594                // `a - (a - b) => b`.
595                (_, SymExprKind::BinOp(SymBinOp::Sub, minuend, subtrahend)) if *minuend == left => {
596                    subtrahend.clone()
597                }
598                // `a - a % d => (a / d) * d`.
599                (_, SymExprKind::BinOp(SymBinOp::URem, dividend, divisor)) if *dividend == left => {
600                    let quotient = Self::binop(cx, SymBinOp::UDiv, left, divisor.clone());
601                    Self::binop(cx, SymBinOp::Mul, quotient, divisor.clone())
602                }
603                // `bool_word(c) - 1 => ite(c, 0, MAX)`.
604                (_, SymExprKind::Const(value))
605                    if *value == U256::ONE
606                        && let Some(condition) = left.bitwise_bool_word_condition(cx) =>
607                {
608                    let zero = Self::zero(cx);
609                    let max = Self::constant(cx, U256::MAX);
610                    Self::ite(cx, condition, zero, max)
611                }
612                // `k - bool_word(c) => ite(c, k - 1, k)`.
613                (SymExprKind::Const(value), _)
614                    if let Some(condition) = right.bitwise_bool_word_condition(cx) =>
615                {
616                    let decremented = Self::constant(cx, value.wrapping_sub(U256::ONE));
617                    let value = Self::constant(cx, *value);
618                    Self::ite(cx, condition, decremented, value)
619                }
620                _ => Self::from_kind(cx, SymExprKind::BinOp(binop, left, right)),
621            },
622            SymBinOp::Mul => match (left.kind(), right.kind()) {
623                (SymExprKind::Const(left_value), SymExprKind::Const(right_value)) => {
624                    // `const * const => const`.
625                    Self::constant(cx, binop.eval(*left_value, *right_value))
626                }
627                // `0 * a => 0`.
628                (SymExprKind::Const(value), _) | (_, SymExprKind::Const(value))
629                    if value.is_zero() =>
630                {
631                    Self::zero(cx)
632                }
633                // `1 * a => a`.
634                (SymExprKind::Const(value), _) if *value == U256::ONE => right,
635                // `a * 1 => a`.
636                (_, SymExprKind::Const(value)) if *value == U256::ONE => left,
637                _ => {
638                    let (left, right) = Self::ordered_commutative_operands(left, right);
639                    if let Some(condition) = left.direct_bool_word_condition(cx) {
640                        // `bool_word(c) * a => ite(c, a, 0)`.
641                        let zero = Self::zero(cx);
642                        Self::ite(cx, condition, right, zero)
643                    } else if let Some(condition) = right.direct_bool_word_condition(cx) {
644                        // `a * bool_word(c) => ite(c, a, 0)`.
645                        let zero = Self::zero(cx);
646                        Self::ite(cx, condition, left, zero)
647                    } else if let Some(shift) = right.as_const().and_then(power_of_two_shift) {
648                        // `a * 2**n => a << n`.
649                        let shift = Self::constant(cx, U256::from(shift));
650                        Self::binop(cx, SymBinOp::Shl, left, shift)
651                    } else {
652                        Self::from_kind(cx, SymExprKind::BinOp(binop, left, right))
653                    }
654                }
655            },
656            SymBinOp::UDiv | SymBinOp::SDiv => match (left.kind(), right.kind()) {
657                (SymExprKind::Const(left_value), SymExprKind::Const(right_value)) => {
658                    // `const / const => const`.
659                    Self::constant(cx, binop.eval(*left_value, *right_value))
660                }
661                // `a / 0 => 0`.
662                (_, SymExprKind::Const(value)) if value.is_zero() => Self::zero(cx),
663                // `a / 1 => a`.
664                (_, SymExprKind::Const(value)) if *value == U256::ONE => left,
665                // `(a - (a & (2**n - 1))) u/ 2**n => a >> n`.
666                (
667                    SymExprKind::BinOp(SymBinOp::Sub, value, low_bits),
668                    SymExprKind::Const(divisor),
669                ) if binop == SymBinOp::UDiv
670                    && let Some(shift) = power_of_two_shift(*divisor)
671                    && low_masked_source(low_bits, shift) == Some(value) =>
672                {
673                    let shift = Self::constant(cx, U256::from(shift));
674                    Self::binop(cx, SymBinOp::Shr, value.clone(), shift)
675                }
676                // `a u/ 2**n => a >> n`.
677                (_, SymExprKind::Const(divisor))
678                    if binop == SymBinOp::UDiv
679                        && let Some(shift) = power_of_two_shift(*divisor) =>
680                {
681                    let shift = Self::constant(cx, U256::from(shift));
682                    Self::binop(cx, SymBinOp::Shr, left, shift)
683                }
684                _ => Self::from_kind(cx, SymExprKind::BinOp(binop, left, right)),
685            },
686            SymBinOp::URem | SymBinOp::SRem => match (left.kind(), right.kind()) {
687                (SymExprKind::Const(left_value), SymExprKind::Const(right_value)) => {
688                    // `const % const => const`.
689                    Self::constant(cx, binop.eval(*left_value, *right_value))
690                }
691                // `a % 0 => 0`.
692                (_, SymExprKind::Const(value)) if value.is_zero() => Self::zero(cx),
693                // `a % 1 => 0`.
694                (_, SymExprKind::Const(value)) if *value == U256::ONE => Self::zero(cx),
695                // `a u% 2**n => a & (2**n - 1)`.
696                (_, SymExprKind::Const(divisor))
697                    if binop == SymBinOp::URem
698                        && let Some(bits) = power_of_two_shift(*divisor) =>
699                {
700                    Self::and_const(cx, left, mask_bits(U256::MAX, bits))
701                }
702                _ => Self::from_kind(cx, SymExprKind::BinOp(binop, left, right)),
703            },
704            SymBinOp::And => match (left.kind(), right.kind()) {
705                (SymExprKind::Const(left_value), SymExprKind::Const(right_value)) => {
706                    // `const & const => const`.
707                    Self::constant(cx, binop.eval(*left_value, *right_value))
708                }
709                // `0 & a => 0`.
710                (SymExprKind::Const(value), _) | (_, SymExprKind::Const(value))
711                    if value.is_zero() =>
712                {
713                    Self::zero(cx)
714                }
715                // `MAX & a => a`.
716                (SymExprKind::Const(value), _) if *value == U256::MAX => right,
717                // `a & MAX => a`.
718                (_, SymExprKind::Const(value)) if *value == U256::MAX => left,
719                // `a & a => a`.
720                _ if left == right => left,
721                (SymExprKind::Const(mask), _) => Self::and_const(cx, right, *mask),
722                (_, SymExprKind::Const(mask)) => Self::and_const(cx, left, *mask),
723                _ => Self::commutative_binop(cx, binop, left, right),
724            },
725            SymBinOp::Or => match (left.kind(), right.kind()) {
726                (SymExprKind::Const(left_value), SymExprKind::Const(right_value)) => {
727                    // `const | const => const`.
728                    Self::constant(cx, binop.eval(*left_value, *right_value))
729                }
730                // `0 | a => a`.
731                (SymExprKind::Const(value), _) if value.is_zero() => right,
732                // `a | 0 => a`.
733                (_, SymExprKind::Const(value)) if value.is_zero() => left,
734                // `a | a => a`.
735                _ if left == right => left,
736                _ if let Some(value) = Self::or_with_absorbing_ite(cx, &left, right.clone()) => {
737                    value
738                }
739                _ if let Some(value) = Self::or_with_absorbing_ite(cx, &right, left.clone()) => {
740                    value
741                }
742                _ => Self::or(cx, left, right),
743            },
744            SymBinOp::Xor => match (left.kind(), right.kind()) {
745                (SymExprKind::Const(left_value), SymExprKind::Const(right_value)) => {
746                    // `const ^ const => const`.
747                    Self::constant(cx, binop.eval(*left_value, *right_value))
748                }
749                // `0 ^ a => a`.
750                (SymExprKind::Const(value), _) if value.is_zero() => right,
751                // `a ^ 0 => a`.
752                (_, SymExprKind::Const(value)) if value.is_zero() => left,
753                // `a ^ a => 0`.
754                _ if left == right => Self::zero(cx),
755                _ => {
756                    let (left, right) = Self::ordered_commutative_operands(left, right);
757                    // `a ^ (a ^ b) => b`.
758                    if let Some(value) = Self::xor_with_shared_operand(&left, &right)
759                        .or_else(|| Self::xor_with_shared_operand(&right, &left))
760                    {
761                        value
762                    // `a ^ ((a ^ b) * bool_word(c)) => ite(c, b, a)`.
763                    } else if let Some(value) = Self::xor_with_bool_select(cx, &left, &right) {
764                        value
765                    } else if let Some(value) = Self::xor_with_bool_select(cx, &right, &left) {
766                        value
767                    // `a ^ ite(c, b, 0) => ite(c, a ^ b, a)`.
768                    } else if let Some(value) = Self::xor_with_zero_ite(cx, &left, &right) {
769                        value
770                    } else if let Some(value) = Self::xor_with_zero_ite(cx, &right, &left) {
771                        value
772                    } else {
773                        Self::from_kind(cx, SymExprKind::BinOp(binop, left, right))
774                    }
775                }
776            },
777            SymBinOp::Shl => match (left.kind(), right.kind()) {
778                (SymExprKind::Const(left_value), SymExprKind::Const(right_value)) => {
779                    // `const << const => const`.
780                    Self::constant(cx, binop.eval(*left_value, *right_value))
781                }
782                // `a << 0 => a`.
783                (_, SymExprKind::Const(value)) if value.is_zero() => left,
784                // `0 << a => 0`.
785                (SymExprKind::Const(value), _) if value.is_zero() => Self::zero(cx),
786                // `a << 256 => 0`.
787                (_, SymExprKind::Const(value)) if *value >= U256::from(256) => Self::zero(cx),
788                _ => Self::from_kind(cx, SymExprKind::BinOp(binop, left, right)),
789            },
790            SymBinOp::Shr => match (left.kind(), right.kind()) {
791                (SymExprKind::Const(left_value), SymExprKind::Const(right_value)) => {
792                    // `const >> const => const`.
793                    Self::constant(cx, binop.eval(*left_value, *right_value))
794                }
795                // `a >> 0 => a`.
796                (_, SymExprKind::Const(value)) if value.is_zero() => left,
797                // `0 >> a => 0`.
798                (SymExprKind::Const(value), _) if value.is_zero() => Self::zero(cx),
799                (_, SymExprKind::Const(value)) => Self::shr_const(cx, left, *value),
800                _ => Self::from_kind(cx, SymExprKind::BinOp(binop, left, right)),
801            },
802            SymBinOp::Sar => match (left.kind(), right.kind()) {
803                (SymExprKind::Const(left_value), SymExprKind::Const(right_value)) => {
804                    // `const >>s const => const`.
805                    Self::constant(cx, binop.eval(*left_value, *right_value))
806                }
807                // `a >>s 0 => a`.
808                (_, SymExprKind::Const(value)) if value.is_zero() => left,
809                _ => Self::from_kind(cx, SymExprKind::BinOp(binop, left, right)),
810            },
811            SymBinOp::MulHigh => match (left.kind(), right.kind()) {
812                (SymExprKind::Const(left_value), SymExprKind::Const(right_value)) => {
813                    // `mul_high(const, const) => const`.
814                    Self::constant(cx, binop.eval(*left_value, *right_value))
815                }
816                // `mul_high(a, 0 | 1) => 0`.
817                (SymExprKind::Const(value), _) | (_, SymExprKind::Const(value))
818                    if *value <= U256::ONE =>
819                {
820                    Self::zero(cx)
821                }
822                _ => Self::commutative_binop(cx, binop, left, right),
823            },
824        }
825    }
826
827    pub(crate) fn ternop(
828        cx: &mut SymCx,
829        ternop: SymTernOp,
830        left: Self,
831        right: Self,
832        modulus: Self,
833    ) -> Self {
834        if ternop == SymTernOp::MulDiv {
835            return Self::mul_div(cx, left, right, modulus);
836        }
837        match (left.kind(), right.kind(), modulus.kind()) {
838            (_, _, SymExprKind::Const(modulus)) if modulus.is_zero() || *modulus == U256::ONE => {
839                // `addmod/mulmod(a, b, 0) => 0`.
840                Self::zero(cx)
841            }
842            // `mulmod(a, m, m) => 0`, also for `m == 0`.
843            _ if ternop == SymTernOp::MulMod && (left == modulus || right == modulus) => {
844                Self::zero(cx)
845            }
846            (SymExprKind::Const(left), SymExprKind::Const(right), SymExprKind::Const(modulus)) => {
847                // `addmod/mulmod(const, const, const) => const`.
848                Self::constant(cx, ternop.eval(*left, *right, *modulus))
849            }
850            // `addmod/mulmod(a, b, 2**n) => op(a, b) & (2**n - 1)`.
851            (_, _, SymExprKind::Const(modulus))
852                if let Some(bits) = power_of_two_shift(*modulus) =>
853            {
854                let binop = match ternop {
855                    SymTernOp::AddMod => SymBinOp::Add,
856                    SymTernOp::MulMod => SymBinOp::Mul,
857                    SymTernOp::MulDiv => unreachable!("mul_div is built before modular rewrites"),
858                };
859                let value = Self::binop(cx, binop, left, right);
860                Self::and_const(cx, value, mask_bits(U256::MAX, bits))
861            }
862            _ => {
863                // `addmod/mulmod(a, b, m) => addmod/mulmod(ordered(a, b), m)`.
864                let (left, right) = Self::ordered_commutative_operands(left, right);
865                Self::from_kind(cx, SymExprKind::TernOp(ternop, left, right, modulus))
866            }
867        }
868    }
869
870    fn mul_div(cx: &mut SymCx, left: Self, right: Self, denominator: Self) -> Self {
871        match (left.kind(), right.kind(), denominator.kind()) {
872            (
873                SymExprKind::Const(left),
874                SymExprKind::Const(right),
875                SymExprKind::Const(denominator),
876            ) => {
877                // `mul_div(const, const, const) => const`.
878                Self::constant(cx, SymTernOp::MulDiv.eval(*left, *right, *denominator))
879            }
880            // `mul_div(0, b, d) => 0`, `mul_div(a, 0, d) => 0`, `mul_div(a, b, 0) => 0`.
881            (SymExprKind::Const(value), _, _)
882            | (_, SymExprKind::Const(value), _)
883            | (_, _, SymExprKind::Const(value))
884                if value.is_zero() =>
885            {
886                Self::zero(cx)
887            }
888            // `mul_div(a, d, d) => ite(d == 0, 0, a)`.
889            _ if left == denominator || right == denominator => {
890                let other = if left == denominator { right } else { left };
891                let zero = Self::zero(cx);
892                let condition = SymBoolExpr::eq(cx, denominator, zero.clone());
893                Self::ite(cx, condition, zero, other)
894            }
895            _ => {
896                let (left, right) = Self::ordered_commutative_operands(left, right);
897                Self::from_kind(
898                    cx,
899                    SymExprKind::TernOp(SymTernOp::MulDiv, left, right, denominator),
900                )
901            }
902        }
903    }
904
905    pub(crate) fn ite(
906        cx: &mut SymCx,
907        condition: SymBoolExpr,
908        then_expr: Self,
909        else_expr: Self,
910    ) -> Self {
911        match condition.as_const() {
912            // `ite(true, a, b) => a`.
913            Some(true) => then_expr,
914            // `ite(false, a, b) => b`.
915            Some(false) => else_expr,
916            // `ite(c, a, a) => a`.
917            None if then_expr == else_expr => then_expr,
918            // `ite(a == 0, 0, a / a) => a != 0`.
919            None if then_expr.as_const().is_some_and(|value| value.is_zero())
920                && Self::self_div_expr_matches_zero_check(&condition, &else_expr) =>
921            {
922                let condition = condition.not(cx);
923                Self::bool_word(cx, condition)
924            }
925            // `ite(c, 1, bool_word(c)) => bool_word(c)`.
926            None if then_expr.as_const() == Some(U256::ONE)
927                && else_expr.bool_word_condition().as_ref() == Some(&condition) =>
928            {
929                else_expr
930            }
931            // `ite(c, bool_word(c), 0) => bool_word(c)`.
932            None if else_expr.as_const().is_some_and(|value| value.is_zero())
933                && then_expr.bool_word_condition().as_ref() == Some(&condition) =>
934            {
935                then_expr
936            }
937            None => Self::from_kind(cx, SymExprKind::Ite(condition, then_expr, else_expr)),
938        }
939    }
940
941    pub(crate) fn bool_word(cx: &mut SymCx, value: SymBoolExpr) -> Self {
942        let one = Self::one(cx);
943        let zero = Self::zero(cx);
944        Self::ite(cx, value, one, zero)
945    }
946
947    fn self_div_expr_matches_zero_check(cond: &SymBoolExpr, expr: &Self) -> bool {
948        let Some(zero_operand) = cond.zero_check_operand() else { return false };
949        let Some((numerator, denominator)) = expr.udiv_operands() else { return false };
950        numerator == zero_operand && denominator == zero_operand
951    }
952
953    pub(crate) fn keccak_symbol(cx: &mut SymCx, name: Symbol, len: Self, bytes: Vec<Self>) -> Self {
954        Self::from_kind(cx, SymExprKind::Keccak { name, len, bytes: bytes.into() })
955    }
956
957    pub(crate) fn hash_symbol(
958        cx: &mut SymCx,
959        name: Symbol,
960        algorithm: &'static str,
961        bytes: Vec<Self>,
962    ) -> Self {
963        Self::from_kind(cx, SymExprKind::Hash { name, algorithm, bytes: bytes.into() })
964    }
965
966    fn or(cx: &mut SymCx, left: Self, right: Self) -> Self {
967        if let Some(rebuilt) = Self::rebuild_from_or_terms(&left, &right) {
968            // `byte_parts(a) | byte_parts(a) => a`.
969            return rebuilt;
970        }
971        Self::commutative_binop(cx, SymBinOp::Or, left, right)
972    }
973
974    fn or_with_absorbing_ite(cx: &mut SymCx, conditional: &Self, other: Self) -> Option<Self> {
975        let SymExprKind::Ite(condition, then_expr, else_expr) = conditional.kind() else {
976            return None;
977        };
978        if then_expr.as_const().is_some_and(|value| value.is_zero())
979            && else_expr.as_const() == Some(U256::MAX)
980        {
981            return Some(Self::ite(cx, condition.clone(), other, else_expr.clone()));
982        }
983        if then_expr.as_const() == Some(U256::MAX)
984            && else_expr.as_const().is_some_and(|value| value.is_zero())
985        {
986            return Some(Self::ite(cx, condition.clone(), then_expr.clone(), other));
987        }
988        None
989    }
990
991    fn add_with_const_ite(cx: &mut SymCx, other: &Self, conditional: &Self) -> Option<Self> {
992        if other.as_const().is_some() {
993            return None;
994        }
995        let SymExprKind::Ite(condition, then_expr, else_expr) = conditional.kind() else {
996            return None;
997        };
998        if then_expr.as_const().is_none() || else_expr.as_const().is_none() {
999            return None;
1000        }
1001        if !Self::duplicating_branchless_rewrite_fits(other, conditional) {
1002            return None;
1003        }
1004        let then_expr = Self::binop(cx, SymBinOp::Add, other.clone(), then_expr.clone());
1005        let else_expr = Self::binop(cx, SymBinOp::Add, other.clone(), else_expr.clone());
1006        Some(Self::ite(cx, condition.clone(), then_expr, else_expr))
1007    }
1008
1009    fn xor_with_bool_select(cx: &mut SymCx, base: &Self, selector: &Self) -> Option<Self> {
1010        let SymExprKind::BinOp(SymBinOp::Mul, left, right) = selector.kind() else { return None };
1011        let (condition_word, selected) = match left.kind() {
1012            SymExprKind::BinOp(SymBinOp::Xor, delta_left, delta_right) if delta_left == base => {
1013                (right, delta_right.clone())
1014            }
1015            SymExprKind::BinOp(SymBinOp::Xor, delta_left, delta_right) if delta_right == base => {
1016                (right, delta_left.clone())
1017            }
1018            _ => match right.kind() {
1019                SymExprKind::BinOp(SymBinOp::Xor, delta_left, delta_right)
1020                    if delta_left == base =>
1021                {
1022                    (left, delta_right.clone())
1023                }
1024                SymExprKind::BinOp(SymBinOp::Xor, delta_left, delta_right)
1025                    if delta_right == base =>
1026                {
1027                    (left, delta_left.clone())
1028                }
1029                _ => return None,
1030            },
1031        };
1032        let condition = condition_word.bitwise_bool_word_condition(cx)?;
1033        Some(Self::ite(cx, condition, selected, base.clone()))
1034    }
1035
1036    fn xor_with_shared_operand(base: &Self, nested: &Self) -> Option<Self> {
1037        let SymExprKind::BinOp(SymBinOp::Xor, left, right) = nested.kind() else { return None };
1038        if left == base {
1039            Some(right.clone())
1040        } else if right == base {
1041            Some(left.clone())
1042        } else {
1043            None
1044        }
1045    }
1046
1047    fn xor_with_zero_ite(cx: &mut SymCx, base: &Self, conditional: &Self) -> Option<Self> {
1048        let SymExprKind::Ite(condition, then_expr, else_expr) = conditional.kind() else {
1049            return None;
1050        };
1051        if then_expr.as_const().is_some_and(|value| value.is_zero()) {
1052            if !Self::duplicating_branchless_rewrite_fits(base, conditional) {
1053                return None;
1054            }
1055            let selected = Self::binop(cx, SymBinOp::Xor, base.clone(), else_expr.clone());
1056            return Some(Self::ite(cx, condition.clone(), base.clone(), selected));
1057        }
1058        if else_expr.as_const().is_some_and(|value| value.is_zero()) {
1059            if !Self::duplicating_branchless_rewrite_fits(base, conditional) {
1060                return None;
1061            }
1062            let selected = Self::binop(cx, SymBinOp::Xor, base.clone(), then_expr.clone());
1063            return Some(Self::ite(cx, condition.clone(), selected, base.clone()));
1064        }
1065        None
1066    }
1067
1068    /// Checks the occurrence cost of a rewrite that places one operand in both ITE arms.
1069    ///
1070    /// Hash-consing keeps the stored DAG compact, but the rewrite still places a shared operand in
1071    /// both arms for downstream consumers. Count that unfolded result before constructing it so a
1072    /// linear series of branchless operations cannot become exponential.
1073    fn duplicating_branchless_rewrite_fits(operand: &Self, conditional: &Self) -> bool {
1074        let mut counter = UnfoldedNodeCounter::new();
1075        let Some(operand_nodes) = counter.expr_nodes(operand) else {
1076            return false;
1077        };
1078        let Some(conditional_nodes) = counter.expr_nodes(conditional) else {
1079            return false;
1080        };
1081
1082        operand_nodes
1083            .checked_mul(2)
1084            .and_then(|duplicated| conditional_nodes.checked_add(duplicated))
1085            // The rewritten ITE adds at most two operation wrappers around the original arms.
1086            .and_then(|nodes| nodes.checked_add(2))
1087            .is_some_and(|nodes| nodes <= MAX_BRANCHLESS_REWRITE_UNFOLDED_NODES)
1088    }
1089
1090    fn commutative_binop(cx: &mut SymCx, op: SymBinOp, left: Self, right: Self) -> Self {
1091        // `a + b => b + a`.
1092        let (left, right) = Self::ordered_commutative_operands(left, right);
1093        Self::from_kind(cx, SymExprKind::BinOp(op, left, right))
1094    }
1095
1096    pub(in crate::runtime::expr) fn ordered_commutative_operands(
1097        left: Self,
1098        right: Self,
1099    ) -> (Self, Self) {
1100        match left.complexity().cmp(&right.complexity()) {
1101            // Put less complex operands, like constants, on the RHS.
1102            std::cmp::Ordering::Less => (right, left),
1103            std::cmp::Ordering::Greater => (left, right),
1104            std::cmp::Ordering::Equal if right.kind.stable_hash_cmp(&left.kind).is_lt() => {
1105                (right, left)
1106            }
1107            std::cmp::Ordering::Equal => (left, right),
1108        }
1109    }
1110
1111    /// Canonically orders factors that belong to the same symbolic context.
1112    ///
1113    /// Polynomial normalization only needs a stable order within one context, where hash-consed
1114    /// identity is both total and substantially cheaper than rendering structural string keys.
1115    pub(in crate::runtime) fn sort_interned_factors(factors: &mut [Self]) {
1116        factors.sort_unstable_by(|left, right| left.kind.identity_cmp(&right.kind));
1117    }
1118
1119    fn complexity(&self) -> usize {
1120        match self.kind() {
1121            SymExprKind::Const(_) => 0,
1122            SymExprKind::Not(_) => 1,
1123            SymExprKind::BinOp(..) => 2,
1124            SymExprKind::TernOp(..) => 3,
1125            _ => 4,
1126        }
1127    }
1128
1129    fn and_const(cx: &mut SymCx, expr: Self, mask: U256) -> Self {
1130        if mask.is_zero() {
1131            // `a & 0 => 0`.
1132            return Self::zero(cx);
1133        }
1134        if mask == U256::MAX {
1135            // `a & MAX => a`.
1136            return expr;
1137        }
1138
1139        match expr.kind() {
1140            // `const & mask => const`.
1141            SymExprKind::Const(value) => Self::constant(cx, *value & mask),
1142            SymExprKind::BinOp(SymBinOp::Or, left, right) => {
1143                // `(a | b) & mask => (a & mask) | (b & mask)`.
1144                let left = Self::and_const(cx, left.clone(), mask);
1145                let right = Self::and_const(cx, right.clone(), mask);
1146                Self::binop(cx, SymBinOp::Or, left, right)
1147            }
1148            SymExprKind::BinOp(SymBinOp::Shl, _, shift)
1149                if mask_low_bits(mask).is_some_and(|bits| {
1150                    shift
1151                        .as_const()
1152                        .and_then(|shift| usize::try_from(shift).ok())
1153                        .is_some_and(|shift| bits <= shift)
1154                }) =>
1155            {
1156                // `(a << n) & low_mask(n) => 0`.
1157                Self::zero(cx)
1158            }
1159            SymExprKind::BinOp(SymBinOp::And, left, right) => {
1160                if right.as_const() == Some(mask) {
1161                    // `(a & mask) & mask => a & mask`.
1162                    Self::and_const(cx, left.clone(), mask)
1163                } else if left == right {
1164                    // `(a & a) & mask => a & mask`.
1165                    Self::and_const(cx, left.clone(), mask)
1166                } else {
1167                    let mask = Self::constant(cx, mask);
1168                    Self::from_kind(cx, SymExprKind::BinOp(SymBinOp::And, expr, mask))
1169                }
1170            }
1171            _ => {
1172                let mask = Self::constant(cx, mask);
1173                Self::from_kind(cx, SymExprKind::BinOp(SymBinOp::And, expr, mask))
1174            }
1175        }
1176    }
1177
1178    fn shr_const(cx: &mut SymCx, expr: Self, shift: U256) -> Self {
1179        if shift.is_zero() {
1180            // `a >> 0 => a`.
1181            return expr;
1182        }
1183        if shift >= U256::from(256) {
1184            // `a >> 256 => 0`.
1185            return Self::zero(cx);
1186        }
1187
1188        let shift = usize::try_from(shift).expect("shift is less than 256");
1189        if expr.unsigned_bits() <= shift {
1190            // `small(a) >> bits(a) => 0`.
1191            return Self::zero(cx);
1192        }
1193
1194        if let SymExprKind::BinOp(SymBinOp::Shl, inner, left_shift) = expr.kind()
1195            && left_shift.as_const() == Some(U256::from(shift))
1196            && inner.unsigned_bits() <= 256 - shift
1197        {
1198            // `(a << n) >> n => a`.
1199            return inner.clone();
1200        }
1201
1202        if let SymExprKind::BinOp(SymBinOp::Or, left, right) = expr.kind() {
1203            // Distribute only when it collapses part of the OR; expanding broad
1204            // bit-smearing chains eagerly makes SMT CSE much larger.
1205            let left = Self::shr_const(cx, left.clone(), U256::from(shift));
1206            let right = Self::shr_const(cx, right.clone(), U256::from(shift));
1207            if left.as_const().is_some_and(|value| value.is_zero()) {
1208                return right;
1209            }
1210            if right.as_const().is_some_and(|value| value.is_zero()) {
1211                return left;
1212            }
1213        }
1214
1215        let shift = Self::constant(cx, U256::from(shift));
1216        Self::from_kind(cx, SymExprKind::BinOp(SymBinOp::Shr, expr, shift))
1217    }
1218
1219    fn rebuild_from_or_terms(left: &Self, right: &Self) -> Option<Self> {
1220        let mut terms = Vec::new();
1221        left.push_or_terms(&mut terms);
1222        right.push_or_terms(&mut terms);
1223        Self::rebuild_from_extracted_byte_terms(&terms)
1224            .or_else(|| Self::rebuild_from_shifted_word_fragments(&terms))
1225    }
1226
1227    pub(in crate::runtime) fn push_or_terms<'a>(&'a self, terms: &mut Vec<&'a Self>) {
1228        match self.kind() {
1229            SymExprKind::BinOp(SymBinOp::Or, left, right) => {
1230                left.push_or_terms(terms);
1231                right.push_or_terms(terms);
1232            }
1233            _ => terms.push(self),
1234        }
1235    }
1236
1237    fn rebuild_from_extracted_byte_terms(terms: &[&Self]) -> Option<Self> {
1238        if terms.len() <= 1 {
1239            return None;
1240        }
1241
1242        let mut source = None;
1243        let mut seen = [false; 32];
1244        for term in terms {
1245            if term.as_const().is_some_and(|value| value.is_zero()) {
1246                continue;
1247            }
1248            let (term_source, index) = term.extracted_shifted_byte_term()?;
1249            match &source {
1250                Some(source) if source != &term_source => return None,
1251                Some(_) => {}
1252                None => source = Some(term_source),
1253            }
1254            seen[index] = true;
1255        }
1256
1257        let source = source?;
1258        for (index, seen) in seen.into_iter().enumerate() {
1259            if !seen && source.known_byte(index) != Some(0) {
1260                return None;
1261            }
1262        }
1263        Some(source)
1264    }
1265
1266    fn extracted_shifted_byte_term(&self) -> Option<(Self, usize)> {
1267        match self.kind() {
1268            SymExprKind::BinOp(SymBinOp::Shl, byte, shift) => {
1269                let shift = shift.as_const()?;
1270                let Ok(shift) = usize::try_from(shift) else { return None };
1271                if shift % 8 != 0 || shift > 248 {
1272                    return None;
1273                }
1274                let index = 31 - shift / 8;
1275                let source = byte.extracted_unshifted_byte_source(index)?;
1276                Some((source, index))
1277            }
1278            _ => self.extracted_unshifted_byte_source(31).map(|source| (source, 31)),
1279        }
1280    }
1281
1282    fn extracted_unshifted_byte_source(&self, index: usize) -> Option<Self> {
1283        let expr = self.strip_low_byte_mask();
1284        if index == 31 {
1285            return Some(expr.clone());
1286        }
1287        let SymExprKind::BinOp(SymBinOp::Shr, source, shift) = expr.kind() else { return None };
1288        let shift = shift.as_const()?;
1289        (shift == U256::from((31 - index) * 8)).then(|| source.clone())
1290    }
1291
1292    fn rebuild_from_shifted_word_fragments(terms: &[&Self]) -> Option<Self> {
1293        if terms.len() != 2 {
1294            return None;
1295        }
1296
1297        let left_low = terms[0].low_word_fragment();
1298        let right_low = terms[1].low_word_fragment();
1299        let left_high = terms[0].shifted_high_word_fragment();
1300        let right_high = terms[1].shifted_high_word_fragment();
1301        match (left_low, right_low, left_high, right_high) {
1302            (Some((low_source, low_bits)), None, None, Some((high_source, high_bits)))
1303            | (None, Some((low_source, low_bits)), Some((high_source, high_bits)), None)
1304                if low_source == high_source && low_bits == high_bits =>
1305            {
1306                Some(low_source)
1307            }
1308            _ => None,
1309        }
1310    }
1311
1312    fn low_word_fragment(&self) -> Option<(Self, usize)> {
1313        let SymExprKind::BinOp(SymBinOp::And, left, right) = self.kind() else { return None };
1314        let mask = right.as_const()?;
1315        mask_low_bits(mask).map(|bits| (left.clone(), bits))
1316    }
1317
1318    fn shifted_high_word_fragment(&self) -> Option<(Self, usize)> {
1319        let SymExprKind::BinOp(SymBinOp::Shl, value, shift) = self.kind() else { return None };
1320        let bits = shift.as_const().and_then(|shift| usize::try_from(shift).ok())?;
1321        if bits == 0 || bits >= 256 {
1322            return None;
1323        }
1324
1325        let (source, source_shift, width) = value.shifted_low_fragment_source()?;
1326        (source_shift == bits && width == 256 - bits).then_some((source, bits))
1327    }
1328
1329    fn shifted_low_fragment_source(&self) -> Option<(Self, usize, usize)> {
1330        let SymExprKind::BinOp(SymBinOp::And, left, right) = self.kind() else { return None };
1331        let mask = right.as_const()?;
1332        Self::shifted_low_fragment_source_with_mask(left, mask)
1333    }
1334
1335    fn shifted_low_fragment_source_with_mask(
1336        value: &Self,
1337        mask: U256,
1338    ) -> Option<(Self, usize, usize)> {
1339        let width = mask_low_bits(mask)?;
1340        match value.kind() {
1341            SymExprKind::BinOp(SymBinOp::Shr, source, shift) => {
1342                let shift = shift.as_const().and_then(|shift| usize::try_from(shift).ok())?;
1343                Some((source.clone(), shift, width))
1344            }
1345            _ => Some((value.clone(), 0, width)),
1346        }
1347    }
1348
1349    pub(crate) fn low_byte(self, cx: &mut SymCx) -> Self {
1350        if let Some(word) = self.as_const() {
1351            return Self::constant(cx, U256::from(word.byte(0)));
1352        }
1353        let mask = Self::constant(cx, U256::from(0xff));
1354        Self::binop(cx, SymBinOp::And, self, mask)
1355    }
1356
1357    pub(crate) fn into_byte_exprs(self, cx: &mut SymCx) -> Vec<Self> {
1358        SymBytes::word(cx, self).materialize(cx)
1359    }
1360
1361    pub(crate) fn into_bytes(self, cx: &mut SymCx) -> SymBytes {
1362        SymBytes::word(cx, self)
1363    }
1364
1365    pub(crate) fn from_bytes(cx: &mut SymCx, bytes: impl IntoIterator<Item = Self>) -> Self {
1366        let bytes = bytes.into_iter().collect::<Vec<_>>();
1367        if let Ok(concrete) = concrete_expr_bytes(&bytes, "symbolic word bytes") {
1368            let mut word = [0u8; 32];
1369            for (idx, byte) in concrete.into_iter().take(32).enumerate() {
1370                word[idx] = byte;
1371            }
1372            return Self::constant(cx, U256::from_be_bytes(word));
1373        }
1374
1375        if let Some(expr) = word_from_extracted_bytes(&bytes) {
1376            return expr;
1377        }
1378
1379        let mut expr = Self::zero(cx);
1380        for (idx, byte) in bytes.into_iter().take(32).enumerate() {
1381            let shift = (31 - idx) * 8;
1382            let byte = byte.low_byte(cx);
1383            let byte = if shift == 0 {
1384                byte
1385            } else {
1386                let shift = Self::constant(cx, U256::from(shift));
1387                Self::binop(cx, SymBinOp::Shl, byte, shift)
1388            };
1389            expr = Self::binop(cx, SymBinOp::Or, expr, byte);
1390        }
1391        expr
1392    }
1393
1394    pub(crate) fn as_const(&self) -> Option<U256> {
1395        match self.kind() {
1396            SymExprKind::Const(value) => Some(*value),
1397            _ => None,
1398        }
1399    }
1400
1401    pub(crate) fn eval(&self) -> Option<U256> {
1402        self.eval_model_if_complete(&NoopModel).ok().flatten()
1403    }
1404
1405    pub(crate) fn eval_model<M: SymbolicModelLookup + ?Sized>(
1406        &self,
1407        model: &M,
1408    ) -> Result<U256, SymbolicError> {
1409        ModelEvaluator::new(model).eval_word(self)
1410    }
1411
1412    pub(crate) fn eval_model_if_complete<M: SymbolicModelLookup + ?Sized>(
1413        &self,
1414        model: &M,
1415    ) -> Result<Option<U256>, SymbolicError> {
1416        let mut vars = SymbolicVars::default();
1417        self.collect_eval_vars(&mut vars);
1418        if vars.iter().copied().all(|var| model.contains_name(var)) {
1419            self.eval_model(model).map(Some)
1420        } else {
1421            Ok(None)
1422        }
1423    }
1424
1425    /// Evaluates `self` under `model` and records the concrete preimage of every Keccak node it
1426    /// folds, so a hash key pinned by path constraints still compares as a hash base.
1427    pub(crate) fn eval_model_recording_keccak_preimages<M: SymbolicModelLookup + ?Sized>(
1428        &self,
1429        cx: &mut SymCx,
1430        model: &M,
1431    ) -> Result<U256, SymbolicError> {
1432        let mut evaluator = ModelEvaluator::new(model);
1433        let value = evaluator.eval_word(self)?;
1434        let hashes = evaluator
1435            .words
1436            .iter()
1437            .filter(|(expr, _)| matches!(expr.kind(), SymExprKind::Keccak { .. }))
1438            .map(|(expr, hash)| (expr.clone(), *hash))
1439            .collect::<Vec<_>>();
1440        for (expr, hash) in hashes {
1441            let SymExprKind::Keccak { len, bytes, .. } = expr.kind() else {
1442                unreachable!("filtered keccak node")
1443            };
1444            let len = usize::try_from(evaluator.eval_word(len)?).expect("checked keccak length");
1445            let bytes = bytes[..len]
1446                .iter()
1447                .map(|byte| {
1448                    let byte = evaluator.eval_word(byte)? & U256::from(0xff);
1449                    Ok(Self::constant(cx, byte))
1450                })
1451                .collect::<Result<Arc<[Self]>, SymbolicError>>()?;
1452            cx.record_concrete_keccak_preimage(hash, bytes);
1453        }
1454        Ok(value)
1455    }
1456
1457    pub(crate) fn assign_model_value(&self, model: &mut SymbolicModel, value: U256) -> bool {
1458        match self.kind() {
1459            SymExprKind::Const(existing) => *existing == value,
1460            SymExprKind::Var(var) => {
1461                if let Some(existing) = model.get(var) {
1462                    *existing == value
1463                } else {
1464                    model.insert(*var, value);
1465                    true
1466                }
1467            }
1468            SymExprKind::GasLeft(symbol) => {
1469                if let Some(existing) = model.get(symbol) {
1470                    *existing == value
1471                } else {
1472                    model.insert(*symbol, value);
1473                    true
1474                }
1475            }
1476            _ => false,
1477        }
1478    }
1479
1480    pub(crate) fn bool_word_condition(&self) -> Option<SymBoolExpr> {
1481        let SymExprKind::Ite(condition, then_expr, else_expr) = self.kind() else {
1482            return None;
1483        };
1484        Self::bool_word_condition_from_parts(condition, then_expr, else_expr)
1485    }
1486
1487    pub(in crate::runtime) fn bitwise_bool_word_condition(
1488        &self,
1489        cx: &mut SymCx,
1490    ) -> Option<SymBoolExpr> {
1491        let mut pending = vec![self.clone()];
1492        let mut seen_words = HashSet::<Self>::default();
1493        let mut leaf_conditions = IndexSet::<SymBoolExpr>::default();
1494        let mut bit_widths = HashMap::default();
1495        let mut remaining = MAX_BITWISE_BOOL_WORD_VISITS;
1496        while let Some(word) = pending.pop() {
1497            if !seen_words.insert(word.clone()) {
1498                continue;
1499            }
1500            if remaining == 0 {
1501                return None;
1502            }
1503            remaining -= 1;
1504
1505            if let Some(condition) = word.direct_bool_word_condition(cx) {
1506                leaf_conditions.insert(condition);
1507                continue;
1508            }
1509            if let SymExprKind::BinOp(SymBinOp::Or, left, right) = word.kind() {
1510                pending.push(right.clone());
1511                pending.push(left.clone());
1512                continue;
1513            }
1514
1515            if word.unsigned_bits_cached(&mut bit_widths, &mut remaining) == Some(1) {
1516                let zero = Self::zero(cx);
1517                let (word, zero) = Self::ordered_commutative_operands(word, zero);
1518                let zero_check =
1519                    SymBoolExpr::from_kind(cx, SymBoolExprKind::Cmp(SymCmpOp::Eq, word, zero));
1520                leaf_conditions.insert(zero_check.not(cx));
1521                continue;
1522            }
1523            return None;
1524        }
1525
1526        Some(SymBoolExpr::or(cx, leaf_conditions.into_iter().collect()))
1527    }
1528
1529    /// Returns the condition represented by a direct `0`/`1` ITE, preserving its polarity.
1530    ///
1531    /// Unlike [`Self::bitwise_bool_word_condition`], this deliberately does not infer a boolean
1532    /// word from arbitrary one-bit expressions. Callers that run during expression construction
1533    /// use this bounded structural check to avoid recursively sizing a shared expression DAG.
1534    fn direct_bool_word_condition(&self, cx: &mut SymCx) -> Option<SymBoolExpr> {
1535        let SymExprKind::Ite(condition, then_expr, else_expr) = self.kind() else {
1536            return None;
1537        };
1538        match (then_expr.as_const(), else_expr.as_const()) {
1539            (Some(then_value), Some(else_value))
1540                if then_value == U256::ONE && else_value.is_zero() =>
1541            {
1542                Some(condition.clone())
1543            }
1544            (Some(then_value), Some(else_value))
1545                if then_value.is_zero() && else_value == U256::ONE =>
1546            {
1547                Some(condition.clone().not(cx))
1548            }
1549            _ => None,
1550        }
1551    }
1552
1553    fn bool_word_condition_from_parts(
1554        condition: &SymBoolExpr,
1555        then_expr: &Self,
1556        else_expr: &Self,
1557    ) -> Option<SymBoolExpr> {
1558        match (then_expr.as_const(), else_expr.as_const()) {
1559            (Some(then_value), Some(else_value))
1560                if then_value == U256::ONE && else_value.is_zero() =>
1561            {
1562                Some(condition.clone())
1563            }
1564            (Some(then_value), Some(else_value))
1565                if then_value.is_zero() && else_value == U256::ONE =>
1566            {
1567                None
1568            }
1569            _ => None,
1570        }
1571    }
1572
1573    pub(crate) fn into_zero_bool(self, cx: &mut SymCx) -> SymBoolExpr {
1574        match self.kind() {
1575            SymExprKind::Const(value) => SymBoolExpr::constant(cx, value.is_zero()),
1576            SymExprKind::Ite(condition, then_expr, else_expr) => {
1577                match Self::bool_word_condition_from_parts(condition, then_expr, else_expr) {
1578                    Some(condition) => SymBoolExpr::not_bool(cx, condition),
1579                    None => {
1580                        let zero = Self::zero(cx);
1581                        SymBoolExpr::eq(cx, self, zero)
1582                    }
1583                }
1584            }
1585            _ => {
1586                let zero = Self::zero(cx);
1587                SymBoolExpr::eq(cx, self, zero)
1588            }
1589        }
1590    }
1591
1592    pub(crate) fn nonzero_bool(self, cx: &mut SymCx) -> SymBoolExpr {
1593        let zero = self.into_zero_bool(cx);
1594        SymBoolExpr::not_bool(cx, zero)
1595    }
1596
1597    pub(crate) fn as_const_or(&self, reason: &'static str) -> Result<U256, SymbolicError> {
1598        self.as_const().ok_or(SymbolicError::Unsupported(reason))
1599    }
1600
1601    pub(crate) fn as_usize_or(&self, reason: &'static str) -> Result<usize, SymbolicError> {
1602        let value = self.as_const_or(reason)?;
1603        usize::try_from(value).map_err(|_| SymbolicError::Unsupported(reason))
1604    }
1605
1606    pub(crate) fn contains_keccak(&self) -> bool {
1607        self.visit_bool(|expr| matches!(expr.kind(), SymExprKind::Keccak { .. }))
1608    }
1609
1610    pub(crate) fn contains_gasleft(&self) -> bool {
1611        self.visit_bool(|expr| expr.is_raw_gasleft())
1612    }
1613
1614    pub(crate) fn contains_udiv(&self) -> bool {
1615        self.visit_bool(|expr| matches!(expr.kind(), SymExprKind::BinOp(SymBinOp::UDiv, _, _)))
1616    }
1617
1618    pub(crate) fn contains_ite(&self) -> bool {
1619        let mut visited = HashSet::<&Self>::default();
1620        self.contains_ite_cached(&mut visited, false)
1621    }
1622
1623    fn contains_ite_cached<'a>(&'a self, visited: &mut HashSet<&'a Self>, memoize: bool) -> bool {
1624        match self.kind() {
1625            SymExprKind::Const(_) | SymExprKind::Var(_) | SymExprKind::GasLeft(_) => return false,
1626            SymExprKind::Ite(_, _, _) => return true,
1627            _ => {}
1628        }
1629        if memoize && !visited.insert(self) {
1630            return false;
1631        }
1632
1633        match self.kind() {
1634            SymExprKind::Keccak { len, bytes, .. } => {
1635                len.contains_ite_cached(visited, true)
1636                    || bytes.iter().any(|byte| byte.contains_ite_cached(visited, true))
1637            }
1638            SymExprKind::Hash { bytes, .. } => {
1639                bytes.iter().any(|byte| byte.contains_ite_cached(visited, true))
1640            }
1641            SymExprKind::Not(value) => value.contains_ite_cached(visited, true),
1642            SymExprKind::BinOp(_, left, right) => {
1643                left.contains_ite_cached(visited, true) || right.contains_ite_cached(visited, true)
1644            }
1645            SymExprKind::TernOp(_, left, right, modulus) => {
1646                left.contains_ite_cached(visited, true)
1647                    || right.contains_ite_cached(visited, true)
1648                    || modulus.contains_ite_cached(visited, true)
1649            }
1650            SymExprKind::Const(_)
1651            | SymExprKind::Var(_)
1652            | SymExprKind::GasLeft(_)
1653            | SymExprKind::Ite(_, _, _) => unreachable!("leaf expression handled before descent"),
1654        }
1655    }
1656
1657    pub(in crate::runtime) fn udiv_operands(&self) -> Option<(&Self, &Self)> {
1658        match self.kind() {
1659            SymExprKind::BinOp(SymBinOp::UDiv, numerator, denominator) => {
1660                Some((numerator, denominator))
1661            }
1662            _ => None,
1663        }
1664    }
1665
1666    pub(crate) fn collect_eval_vars(&self, vars: &mut SymbolicVars) {
1667        let _ = self.visit::<()>(&mut |expr| {
1668            vars.extend(expr.kind().get_eval_var());
1669            ControlFlow::Continue(())
1670        });
1671    }
1672
1673    pub(crate) fn known_byte(&self, index: usize) -> Option<u8> {
1674        debug_assert!(index < 32);
1675        match self.kind() {
1676            SymExprKind::Const(value) => Some(value.to_be_bytes::<32>()[index]),
1677            SymExprKind::Var(_)
1678            | SymExprKind::GasLeft(_)
1679            | SymExprKind::Keccak { .. }
1680            | SymExprKind::Hash { .. } => None,
1681            SymExprKind::Not(value) => value.known_byte(index).map(|byte| !byte),
1682            SymExprKind::Ite(_, then_expr, else_expr) => {
1683                let then_byte = then_expr.known_byte(index)?;
1684                let else_byte = else_expr.known_byte(index)?;
1685                (then_byte == else_byte).then_some(then_byte)
1686            }
1687            SymExprKind::BinOp(op, left, right) => match op {
1688                SymBinOp::And => match (left.known_byte(index), right.known_byte(index)) {
1689                    (Some(left), Some(right)) => Some(left & right),
1690                    (Some(0), _) | (_, Some(0)) => Some(0),
1691                    _ => None,
1692                },
1693                SymBinOp::Or => Some(left.known_byte(index)? | right.known_byte(index)?),
1694                SymBinOp::Xor => Some(left.known_byte(index)? ^ right.known_byte(index)?),
1695                SymBinOp::Shl => {
1696                    let shift = right.as_const()?;
1697                    if shift >= U256::from(256) {
1698                        return Some(0);
1699                    }
1700                    let shift = usize::try_from(shift).expect("checked byte shift");
1701                    if shift % 8 != 0 {
1702                        return None;
1703                    }
1704                    let source_index = index + shift / 8;
1705                    if source_index >= 32 { Some(0) } else { left.known_byte(source_index) }
1706                }
1707                SymBinOp::Shr => {
1708                    let shift = right.as_const()?;
1709                    if shift >= U256::from(256) {
1710                        return Some(0);
1711                    }
1712                    let shift = usize::try_from(shift).expect("checked byte shift");
1713                    if shift % 8 != 0 {
1714                        return None;
1715                    }
1716                    let byte_shift = shift / 8;
1717                    if index < byte_shift { Some(0) } else { left.known_byte(index - byte_shift) }
1718                }
1719                SymBinOp::Add
1720                | SymBinOp::Sub
1721                | SymBinOp::Mul
1722                | SymBinOp::UDiv
1723                | SymBinOp::URem
1724                | SymBinOp::SDiv
1725                | SymBinOp::SRem
1726                | SymBinOp::Sar
1727                | SymBinOp::MulHigh => None,
1728            },
1729            SymExprKind::TernOp(_, _, _, _) => None,
1730        }
1731    }
1732
1733    pub(crate) fn known_word(&self) -> Option<U256> {
1734        let mut word = [0u8; 32];
1735        for (idx, byte) in word.iter_mut().enumerate() {
1736            *byte = self.known_byte(idx)?;
1737        }
1738        Some(U256::from_be_bytes(word))
1739    }
1740
1741    pub(crate) fn unsigned_bits(&self) -> usize {
1742        let mut bit_widths = HashMap::default();
1743        let mut remaining = usize::MAX;
1744        self.unsigned_bits_cached(&mut bit_widths, &mut remaining).unwrap_or(256)
1745    }
1746
1747    fn unsigned_bits_cached(
1748        &self,
1749        bit_widths: &mut HashMap<Self, usize>,
1750        remaining: &mut usize,
1751    ) -> Option<usize> {
1752        if let Some(bits) = bit_widths.get(self) {
1753            return Some(*bits);
1754        }
1755
1756        let mut pending = vec![(self.clone(), false)];
1757        while let Some((expr, children_visited)) = pending.pop() {
1758            if bit_widths.contains_key(&expr) {
1759                continue;
1760            }
1761            if !children_visited {
1762                if *remaining == 0 {
1763                    return None;
1764                }
1765                *remaining -= 1;
1766                pending.push((expr.clone(), true));
1767                match expr.kind() {
1768                    SymExprKind::BinOp(SymBinOp::And, left, right)
1769                        if right.as_const().is_some() =>
1770                    {
1771                        pending.push((left.clone(), false));
1772                    }
1773                    SymExprKind::BinOp(SymBinOp::Add | SymBinOp::Mul, left, right)
1774                    | SymExprKind::Ite(_, left, right) => {
1775                        pending.push((right.clone(), false));
1776                        pending.push((left.clone(), false));
1777                    }
1778                    SymExprKind::BinOp(SymBinOp::Shl | SymBinOp::Shr, left, right)
1779                        if right
1780                            .as_const()
1781                            .and_then(|shift| usize::try_from(shift).ok())
1782                            .is_some() =>
1783                    {
1784                        pending.push((left.clone(), false));
1785                    }
1786                    SymExprKind::BinOp(SymBinOp::UDiv | SymBinOp::URem, left, _) => {
1787                        pending.push((left.clone(), false));
1788                    }
1789                    SymExprKind::TernOp(SymTernOp::AddMod | SymTernOp::MulMod, _, _, modulus) => {
1790                        pending.push((modulus.clone(), false));
1791                    }
1792                    _ => {}
1793                }
1794                continue;
1795            }
1796
1797            let bits = match expr.kind() {
1798                SymExprKind::Const(value) => value.bit_len().max(1),
1799                SymExprKind::BinOp(SymBinOp::And, left, right) => {
1800                    if let Some(mask) = right.as_const() {
1801                        bit_widths[left].min(mask.bit_len())
1802                    } else {
1803                        256
1804                    }
1805                }
1806                SymExprKind::BinOp(SymBinOp::Add, left, right) => {
1807                    bit_widths[left].max(bit_widths[right]).saturating_add(1).min(256)
1808                }
1809                SymExprKind::BinOp(SymBinOp::Mul, left, right) => {
1810                    match rounded_product_operands(left, right) {
1811                        // `(a / d) * d <= a`, so the rounded product fits the dividend.
1812                        Some((dividend, _)) => bit_widths[dividend],
1813                        None => bit_widths[left].saturating_add(bit_widths[right]).min(256),
1814                    }
1815                }
1816                SymExprKind::BinOp(SymBinOp::Shl, left, right) => right
1817                    .as_const()
1818                    .and_then(|shift| usize::try_from(shift).ok())
1819                    .map_or(256, |shift| bit_widths[left].saturating_add(shift).min(256)),
1820                SymExprKind::BinOp(SymBinOp::Shr, left, right) => right
1821                    .as_const()
1822                    .and_then(|shift| usize::try_from(shift).ok())
1823                    .map_or(256, |shift| bit_widths[left].saturating_sub(shift).max(1)),
1824                SymExprKind::BinOp(SymBinOp::UDiv, left, _) => bit_widths[left],
1825                // `a % d <= a`, and `a % d < d` for a nonzero constant `d`.
1826                SymExprKind::BinOp(SymBinOp::URem, left, right) => match right.as_const() {
1827                    Some(divisor) if !divisor.is_zero() => bit_widths[left].min(divisor.bit_len()),
1828                    _ => bit_widths[left],
1829                },
1830                SymExprKind::TernOp(SymTernOp::AddMod | SymTernOp::MulMod, _, _, modulus) => {
1831                    bit_widths[modulus]
1832                }
1833                SymExprKind::Ite(_, left, right) => bit_widths[left].max(bit_widths[right]),
1834                _ => 256,
1835            };
1836            bit_widths.insert(expr, bits);
1837        }
1838        bit_widths.get(self).copied()
1839    }
1840
1841    pub(crate) fn extracted_byte(&self, cx: &mut SymCx, index: usize) -> Self {
1842        debug_assert!(index < 32);
1843        let shift = Self::constant(cx, U256::from((31 - index) * 8));
1844        let shifted = Self::binop(cx, SymBinOp::Shr, self.clone(), shift);
1845        let mask = Self::constant(cx, U256::from(0xff));
1846        Self::binop(cx, SymBinOp::And, shifted, mask)
1847    }
1848
1849    pub(crate) fn extracted_byte_source(&self, index: usize) -> Option<Self> {
1850        let expr = self.strip_low_byte_mask();
1851        if index == 31 {
1852            return Some(expr.clone());
1853        }
1854        let SymExprKind::BinOp(SymBinOp::Shr, source, shift) = expr.kind() else { return None };
1855        let shift = shift.as_const()?;
1856        (shift == U256::from((31 - index) * 8)).then(|| source.clone())
1857    }
1858
1859    pub(crate) fn strip_low_byte_mask(&self) -> &Self {
1860        match self.kind() {
1861            SymExprKind::BinOp(SymBinOp::And, left, right)
1862                if right.as_const() == Some(U256::from(0xff)) =>
1863            {
1864                left.strip_low_byte_mask()
1865            }
1866            _ => self,
1867        }
1868    }
1869
1870    pub(crate) fn byte_term(&self, cx: &mut SymCx, index: usize) -> Option<Self> {
1871        debug_assert!(index < 32);
1872
1873        match self.kind() {
1874            SymExprKind::Const(value) => {
1875                Some(Self::constant(cx, U256::from(value.to_be_bytes::<32>()[index])))
1876            }
1877            SymExprKind::Var(_)
1878            | SymExprKind::GasLeft(_)
1879            | SymExprKind::Keccak { .. }
1880            | SymExprKind::Hash { .. } => Some(self.extracted_byte(cx, index)),
1881            SymExprKind::Not(value) => {
1882                // Complement within the byte, as a full-word `Not` would set the upper bits.
1883                let value = value.byte_term(cx, index)?;
1884                let mask = Self::constant(cx, U256::from(0xff));
1885                Some(Self::binop(cx, SymBinOp::Xor, value, mask))
1886            }
1887            SymExprKind::Ite(cond, then_expr, else_expr) => {
1888                let then_expr = then_expr.byte_term(cx, index)?;
1889                let else_expr = else_expr.byte_term(cx, index)?;
1890                Some(Self::ite(cx, cond.clone(), then_expr, else_expr))
1891            }
1892            SymExprKind::BinOp(op, left, right) => match op {
1893                SymBinOp::And => Self::binary_byte_term(
1894                    cx,
1895                    left,
1896                    right,
1897                    index,
1898                    SymBinOp::And,
1899                    |byte| byte == 0xff,
1900                    |byte| byte == 0,
1901                ),
1902                SymBinOp::Or => Self::binary_byte_term(
1903                    cx,
1904                    left,
1905                    right,
1906                    index,
1907                    SymBinOp::Or,
1908                    |byte| byte == 0,
1909                    |_| false,
1910                ),
1911                SymBinOp::Xor => Self::binary_byte_term(
1912                    cx,
1913                    left,
1914                    right,
1915                    index,
1916                    SymBinOp::Xor,
1917                    |byte| byte == 0,
1918                    |_| false,
1919                ),
1920                SymBinOp::Shl => {
1921                    let shift = right.eval()?;
1922                    if shift >= U256::from(256) {
1923                        return Some(Self::zero(cx));
1924                    }
1925                    let shift = usize::try_from(shift).expect("checked byte shift");
1926                    if shift % 8 != 0 {
1927                        return None;
1928                    }
1929                    let source_index = index + shift / 8;
1930                    if source_index >= 32 {
1931                        Some(Self::zero(cx))
1932                    } else {
1933                        left.byte_term(cx, source_index)
1934                    }
1935                }
1936                SymBinOp::Shr => {
1937                    let shift = right.eval()?;
1938                    if shift >= U256::from(256) {
1939                        return Some(Self::zero(cx));
1940                    }
1941                    let shift = usize::try_from(shift).expect("checked byte shift");
1942                    if shift % 8 != 0 {
1943                        return None;
1944                    }
1945                    let byte_shift = shift / 8;
1946                    if index < byte_shift {
1947                        Some(Self::zero(cx))
1948                    } else {
1949                        left.byte_term(cx, index - byte_shift)
1950                    }
1951                }
1952                SymBinOp::Add
1953                | SymBinOp::Sub
1954                | SymBinOp::Mul
1955                | SymBinOp::UDiv
1956                | SymBinOp::URem
1957                | SymBinOp::SDiv
1958                | SymBinOp::SRem
1959                | SymBinOp::Sar
1960                | SymBinOp::MulHigh => None,
1961            },
1962            SymExprKind::TernOp(_, _, _, _) => None,
1963        }
1964    }
1965
1966    fn binary_byte_term(
1967        cx: &mut SymCx,
1968        left: &Self,
1969        right: &Self,
1970        index: usize,
1971        op: SymBinOp,
1972        identity: impl Fn(u8) -> bool,
1973        absorbing: impl Fn(u8) -> bool,
1974    ) -> Option<Self> {
1975        let left = left.byte_term(cx, index)?;
1976        let right = right.byte_term(cx, index)?;
1977        match (
1978            left.as_const().map(|value| value.to::<u8>()),
1979            right.as_const().map(|value| value.to::<u8>()),
1980        ) {
1981            (Some(left), _) if absorbing(left) => Some(Self::constant(cx, U256::from(left))),
1982            (_, Some(right)) if absorbing(right) => Some(Self::constant(cx, U256::from(right))),
1983            (Some(left), _) if identity(left) => Some(right),
1984            (_, Some(right)) if identity(right) => Some(left),
1985            _ => Some(Self::binop(cx, op, left, right)),
1986        }
1987    }
1988
1989    pub(crate) fn equality_forces_const(
1990        &self,
1991        value: U256,
1992        expr: &Self,
1993        context: &[SymBoolExpr],
1994    ) -> Option<U256> {
1995        if self == expr {
1996            return Some(value);
1997        }
1998        // `x - c == v`, `c - x == v`, and `x + c == v` pin `x`, as solc's `iszero(sub(x, c))`
1999        // form of `x == c` does.
2000        if let SymExprKind::BinOp(op @ (SymBinOp::Sub | SymBinOp::Add), left, right) = self.kind() {
2001            if let Some(constant) = right.as_const() {
2002                let value = match op {
2003                    SymBinOp::Sub => value.wrapping_add(constant),
2004                    _ => value.wrapping_sub(constant),
2005                };
2006                return left.equality_forces_const(value, expr, context);
2007            }
2008            if *op == SymBinOp::Sub
2009                && let Some(constant) = left.as_const()
2010            {
2011                return right.equality_forces_const(constant.wrapping_sub(value), expr, context);
2012            }
2013        }
2014        self.equality_forces_const_inner(value, expr, context)
2015    }
2016
2017    fn equality_forces_const_inner(
2018        &self,
2019        value: U256,
2020        expr: &Self,
2021        context: &[SymBoolExpr],
2022    ) -> Option<U256> {
2023        let mask = masked_expr_matches(self.kind(), expr)?;
2024        if !(value & !mask).is_zero() || !context_forces_masked_expr(context, expr, mask) {
2025            return None;
2026        }
2027        Some(value)
2028    }
2029
2030    pub(crate) fn nonzero_forces_const(
2031        &self,
2032        target: &Self,
2033        context: &[SymBoolExpr],
2034    ) -> Option<U256> {
2035        match self.kind() {
2036            SymExprKind::Const(_)
2037            | SymExprKind::Var(_)
2038            | SymExprKind::GasLeft(_)
2039            | SymExprKind::Keccak { .. }
2040            | SymExprKind::Hash { .. }
2041            | SymExprKind::Not(_) => None,
2042            SymExprKind::Ite(cond, then_expr, else_expr) => {
2043                if then_expr.eval().is_some_and(|value| !value.is_zero())
2044                    && else_expr.eval().is_some_and(|value| value.is_zero())
2045                {
2046                    cond.forces_expr_const_with_context(target, context)
2047                } else {
2048                    None
2049                }
2050            }
2051            SymExprKind::BinOp(SymBinOp::Or, left, right) => {
2052                if left.eval().is_some_and(|value| value.is_zero()) {
2053                    return right.nonzero_forces_const(target, context);
2054                }
2055                if right.eval().is_some_and(|value| value.is_zero()) {
2056                    return left.nonzero_forces_const(target, context);
2057                }
2058                None
2059            }
2060            SymExprKind::BinOp(SymBinOp::And, left, right) => {
2061                if left.eval().is_some_and(|value| !value.is_zero()) {
2062                    return right.nonzero_forces_const(target, context);
2063                }
2064                if right.eval().is_some_and(|value| !value.is_zero()) {
2065                    return left.nonzero_forces_const(target, context);
2066                }
2067                None
2068            }
2069            SymExprKind::BinOp(SymBinOp::Shl | SymBinOp::Shr, value, shift)
2070                if shift.eval().is_some_and(|shift| shift.is_zero()) =>
2071            {
2072                value.nonzero_forces_const(target, context)
2073            }
2074            SymExprKind::TernOp(_, _, _, _) => None,
2075            SymExprKind::BinOp(_, _, _) => None,
2076        }
2077    }
2078
2079    pub(crate) fn is_raw_gasleft(&self) -> bool {
2080        matches!(self.kind(), SymExprKind::GasLeft(_))
2081    }
2082
2083    pub(crate) fn add_const(cx: &mut SymCx, expr: Self, value: U256) -> Self {
2084        if value.is_zero() {
2085            return expr;
2086        }
2087        match expr.kind() {
2088            SymExprKind::Const(expr) => Self::constant(cx, expr.wrapping_add(value)),
2089            _ => {
2090                let value = Self::constant(cx, value);
2091                Self::binop(cx, SymBinOp::Add, expr, value)
2092            }
2093        }
2094    }
2095
2096    /// Returns a constant `self - other` modulo the EVM word size when it follows from the
2097    /// expression structure on every branch.
2098    pub(crate) fn constant_difference(&self, other: &Self) -> Option<U256> {
2099        let mut differences = HashMap::default();
2100        let mut remaining = MAX_CONSTANT_DIFFERENCE_VISITS;
2101        self.constant_difference_cached(other, &mut differences, &mut remaining)
2102    }
2103
2104    fn constant_difference_cached(
2105        &self,
2106        other: &Self,
2107        differences: &mut HashMap<(Self, Self), Option<U256>>,
2108        remaining: &mut usize,
2109    ) -> Option<U256> {
2110        if self == other {
2111            return Some(U256::ZERO);
2112        }
2113        let key = (self.clone(), other.clone());
2114        if let Some(difference) = differences.get(&key) {
2115            return *difference;
2116        }
2117        *remaining = remaining.checked_sub(1)?;
2118
2119        let difference = match (self.kind(), other.kind()) {
2120            (SymExprKind::Const(left), SymExprKind::Const(right)) => {
2121                Some(left.wrapping_sub(*right))
2122            }
2123            (
2124                SymExprKind::Ite(left_condition, left_then, left_else),
2125                SymExprKind::Ite(right_condition, right_then, right_else),
2126            ) if left_condition == right_condition => {
2127                let then_difference =
2128                    left_then.constant_difference_cached(right_then, differences, remaining)?;
2129                let else_difference =
2130                    left_else.constant_difference_cached(right_else, differences, remaining)?;
2131                (then_difference == else_difference).then_some(then_difference)
2132            }
2133            (SymExprKind::BinOp(SymBinOp::Add, value, constant), _)
2134                if let Some(constant) = constant.as_const() =>
2135            {
2136                value
2137                    .constant_difference_cached(other, differences, remaining)
2138                    .map(|difference| difference.wrapping_add(constant))
2139            }
2140            (SymExprKind::BinOp(SymBinOp::Sub, value, constant), _)
2141                if let Some(constant) = constant.as_const() =>
2142            {
2143                value
2144                    .constant_difference_cached(other, differences, remaining)
2145                    .map(|difference| difference.wrapping_sub(constant))
2146            }
2147            (_, SymExprKind::BinOp(SymBinOp::Add, value, constant))
2148                if let Some(constant) = constant.as_const() =>
2149            {
2150                self.constant_difference_cached(value, differences, remaining)
2151                    .map(|difference| difference.wrapping_sub(constant))
2152            }
2153            (_, SymExprKind::BinOp(SymBinOp::Sub, value, constant))
2154                if let Some(constant) = constant.as_const() =>
2155            {
2156                self.constant_difference_cached(value, differences, remaining)
2157                    .map(|difference| difference.wrapping_add(constant))
2158            }
2159            _ => None,
2160        };
2161        differences.insert(key, difference);
2162        difference
2163    }
2164
2165    /// Visits each distinct word expression once, in depth-first, left-to-right order.
2166    pub(crate) fn visit<B>(
2167        &self,
2168        visitor: &mut impl FnMut(&Self) -> ControlFlow<B>,
2169    ) -> ControlFlow<B> {
2170        visit_unique(Some(self), None, visitor)
2171    }
2172
2173    /// Returns whether any node satisfies `visitor`, visiting each distinct node once.
2174    pub(crate) fn visit_bool(&self, mut visitor: impl FnMut(&Self) -> bool) -> bool {
2175        self.visit(&mut |expr| {
2176            if visitor(expr) { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }
2177        })
2178        .is_break()
2179    }
2180
2181    /// Rewrites each distinct word or nested Boolean node once in bottom-up order.
2182    ///
2183    /// The folder must return the same result for every occurrence of one hash-consed node.
2184    pub(crate) fn fold(
2185        &self,
2186        cx: &mut SymCx,
2187        folder: &mut impl FnMut(&mut SymCx, Self) -> Self,
2188    ) -> Self {
2189        let mut folded = ExpressionFoldCache::default();
2190        self.fold_cached(cx, folder, &mut folded)
2191    }
2192
2193    pub(in crate::runtime::expr) fn fold_cached<'a>(
2194        &'a self,
2195        cx: &mut SymCx,
2196        folder: &mut impl FnMut(&mut SymCx, Self) -> Self,
2197        folded: &mut ExpressionFoldCache<'a>,
2198    ) -> Self {
2199        if let Some(expr) = folded.words.get(self) {
2200            return expr.clone();
2201        }
2202
2203        let expr = match self.kind() {
2204            SymExprKind::Const(_) | SymExprKind::Var(_) | SymExprKind::GasLeft(_) => self.clone(),
2205            SymExprKind::Keccak { name, len, bytes } => {
2206                let len = len.fold_cached(cx, folder, folded);
2207                let bytes = bytes.iter().map(|byte| byte.fold_cached(cx, folder, folded)).collect();
2208                Self::keccak_symbol(cx, *name, len, bytes)
2209            }
2210            SymExprKind::Hash { name, algorithm, bytes } => {
2211                let bytes = bytes.iter().map(|byte| byte.fold_cached(cx, folder, folded)).collect();
2212                Self::hash_symbol(cx, *name, algorithm, bytes)
2213            }
2214            SymExprKind::Not(value) => {
2215                let value = value.fold_cached(cx, folder, folded);
2216                Self::not(cx, value)
2217            }
2218            SymExprKind::BinOp(op, left, right) => {
2219                let left = left.fold_cached(cx, folder, folded);
2220                let right = right.fold_cached(cx, folder, folded);
2221                Self::binop(cx, *op, left, right)
2222            }
2223            SymExprKind::TernOp(op, left, right, modulus) => {
2224                let left = left.fold_cached(cx, folder, folded);
2225                let right = right.fold_cached(cx, folder, folded);
2226                let modulus = modulus.fold_cached(cx, folder, folded);
2227                Self::ternop(cx, *op, left, right, modulus)
2228            }
2229            SymExprKind::Ite(condition, then_expr, else_expr) => {
2230                let condition = condition.fold_exprs_cached(cx, folder, folded);
2231                let then_expr = then_expr.fold_cached(cx, folder, folded);
2232                let else_expr = else_expr.fold_cached(cx, folder, folded);
2233                Self::ite(cx, condition, then_expr, else_expr)
2234            }
2235        };
2236        let expr = folder(cx, expr);
2237        folded.words.insert(self, expr.clone());
2238        expr
2239    }
2240}
2241
2242// Branchless expression rewrites are optional. Bound both the distinct DAG nodes inspected while
2243// deciding whether to rewrite and the unfolded size of the expression they could produce.
2244const MAX_BRANCHLESS_REWRITE_NODES: usize = 256;
2245const MAX_BRANCHLESS_REWRITE_UNFOLDED_NODES: usize = 8 * 1024;
2246
2247struct UnfoldedNodeCounter {
2248    expr_nodes: HashMap<SymExpr, usize>,
2249    bool_nodes: HashMap<SymBoolExpr, usize>,
2250    remaining_unique_nodes: usize,
2251}
2252
2253impl UnfoldedNodeCounter {
2254    fn new() -> Self {
2255        Self {
2256            expr_nodes: HashMap::default(),
2257            bool_nodes: HashMap::default(),
2258            remaining_unique_nodes: MAX_BRANCHLESS_REWRITE_NODES,
2259        }
2260    }
2261
2262    /// Counts unfolded occurrences while memoizing the cost of each distinct expression node.
2263    /// Reusing a cached cost still adds every occurrence, which exposes exponential shared DAGs.
2264    fn expr_nodes(&mut self, expr: &SymExpr) -> Option<usize> {
2265        if let Some(nodes) = self.expr_nodes.get(expr) {
2266            return Some(*nodes);
2267        }
2268        if self.remaining_unique_nodes == 0 {
2269            return None;
2270        }
2271        self.remaining_unique_nodes -= 1;
2272
2273        let nodes = match expr.kind() {
2274            SymExprKind::Const(_) | SymExprKind::Var(_) | SymExprKind::GasLeft(_) => 1,
2275            SymExprKind::Keccak { len, bytes, .. } => {
2276                let mut nodes = 1usize.checked_add(self.expr_nodes(len)?)?;
2277                for byte in bytes.iter() {
2278                    nodes = nodes.checked_add(self.expr_nodes(byte)?)?;
2279                }
2280                nodes
2281            }
2282            SymExprKind::Hash { bytes, .. } => {
2283                let mut nodes = 1usize;
2284                for byte in bytes.iter() {
2285                    nodes = nodes.checked_add(self.expr_nodes(byte)?)?;
2286                }
2287                nodes
2288            }
2289            SymExprKind::Not(value) => 1usize.checked_add(self.expr_nodes(value)?)?,
2290            SymExprKind::BinOp(_, left, right) => {
2291                1usize.checked_add(self.expr_nodes(left)?)?.checked_add(self.expr_nodes(right)?)?
2292            }
2293            SymExprKind::TernOp(_, left, right, modulus) => 1usize
2294                .checked_add(self.expr_nodes(left)?)?
2295                .checked_add(self.expr_nodes(right)?)?
2296                .checked_add(self.expr_nodes(modulus)?)?,
2297            SymExprKind::Ite(condition, then_expr, else_expr) => 1usize
2298                .checked_add(self.bool_nodes(condition)?)?
2299                .checked_add(self.expr_nodes(then_expr)?)?
2300                .checked_add(self.expr_nodes(else_expr)?)?,
2301        };
2302        if nodes > MAX_BRANCHLESS_REWRITE_UNFOLDED_NODES {
2303            return None;
2304        }
2305        self.expr_nodes.insert(expr.clone(), nodes);
2306        Some(nodes)
2307    }
2308
2309    fn bool_nodes(&mut self, expr: &SymBoolExpr) -> Option<usize> {
2310        if let Some(nodes) = self.bool_nodes.get(expr) {
2311            return Some(*nodes);
2312        }
2313        if self.remaining_unique_nodes == 0 {
2314            return None;
2315        }
2316        self.remaining_unique_nodes -= 1;
2317
2318        let nodes = match expr.kind() {
2319            SymBoolExprKind::Const(_) => 1,
2320            SymBoolExprKind::Not(value) => 1usize.checked_add(self.bool_nodes(value)?)?,
2321            SymBoolExprKind::And(values) => {
2322                let mut nodes = 1usize;
2323                for value in values.iter() {
2324                    nodes = nodes.checked_add(self.bool_nodes(value)?)?;
2325                }
2326                nodes
2327            }
2328            SymBoolExprKind::Cmp(_, left, right) => {
2329                1usize.checked_add(self.expr_nodes(left)?)?.checked_add(self.expr_nodes(right)?)?
2330            }
2331        };
2332        if nodes > MAX_BRANCHLESS_REWRITE_UNFOLDED_NODES {
2333            return None;
2334        }
2335        self.bool_nodes.insert(expr.clone(), nodes);
2336        Some(nodes)
2337    }
2338}
2339
2340#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2341pub(crate) enum SymTernOp {
2342    AddMod,
2343    MulMod,
2344    /// `floor(a * b / d)` over the 512-bit product, truncated to 256 bits; zero when `d` is zero.
2345    MulDiv,
2346}
2347
2348impl SymTernOp {
2349    /// Returns the 512-bit SMT functions that combine the operands and then apply the modulus.
2350    pub(crate) const fn smt(self) -> (&'static str, &'static str) {
2351        match self {
2352            Self::AddMod => ("bvadd", "bvurem"),
2353            Self::MulMod => ("bvmul", "bvurem"),
2354            Self::MulDiv => ("bvmul", "bvudiv"),
2355        }
2356    }
2357
2358    pub(crate) fn eval(self, left: U256, right: U256, modulus: U256) -> U256 {
2359        if modulus.is_zero() {
2360            return U256::ZERO;
2361        }
2362        match self {
2363            Self::AddMod => left.add_mod(right, modulus),
2364            Self::MulMod => left.mul_mod(right, modulus),
2365            Self::MulDiv => {
2366                let quotient = left.widening_mul::<256, 4, 512, 8>(right) / U512::from(modulus);
2367                U256::from_limbs_slice(&quotient.as_limbs()[..4])
2368            }
2369        }
2370    }
2371}
2372
2373#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2374pub(crate) enum SymBinOp {
2375    Add,
2376    Sub,
2377    Mul,
2378    UDiv,
2379    URem,
2380    SDiv,
2381    SRem,
2382    And,
2383    Or,
2384    Xor,
2385    Shl,
2386    Shr,
2387    Sar,
2388    /// High word of the 512-bit product.
2389    MulHigh,
2390}
2391
2392impl SymBinOp {
2393    /// Returns the SMT function of a 256-bit operator. The SMT writer emits `MulHigh` itself.
2394    pub(crate) const fn smt(self) -> &'static str {
2395        match self {
2396            Self::MulHigh => unreachable!(),
2397            Self::Add => "bvadd",
2398            Self::Sub => "bvsub",
2399            Self::Mul => "bvmul",
2400            Self::UDiv => "bvudiv",
2401            Self::URem => "bvurem",
2402            Self::SDiv => "bvsdiv",
2403            Self::SRem => "bvsrem",
2404            Self::And => "bvand",
2405            Self::Or => "bvor",
2406            Self::Xor => "bvxor",
2407            Self::Shl => "bvshl",
2408            Self::Shr => "bvlshr",
2409            Self::Sar => "bvashr",
2410        }
2411    }
2412
2413    pub(crate) fn eval(self, left: U256, right: U256) -> U256 {
2414        match self {
2415            Self::Add => left.wrapping_add(right),
2416            Self::Sub => left.wrapping_sub(right),
2417            Self::Mul => left.wrapping_mul(right),
2418            Self::UDiv => {
2419                if right.is_zero() {
2420                    U256::ZERO
2421                } else {
2422                    left / right
2423                }
2424            }
2425            Self::URem => {
2426                if right.is_zero() {
2427                    U256::ZERO
2428                } else {
2429                    left % right
2430                }
2431            }
2432            Self::SDiv => {
2433                if right.is_zero() {
2434                    U256::ZERO
2435                } else {
2436                    I256::from_raw(left).wrapping_div(I256::from_raw(right)).into_raw()
2437                }
2438            }
2439            Self::SRem => {
2440                if right.is_zero() {
2441                    U256::ZERO
2442                } else {
2443                    I256::from_raw(left).wrapping_rem(I256::from_raw(right)).into_raw()
2444                }
2445            }
2446            Self::And => left & right,
2447            Self::Or => left | right,
2448            Self::Xor => left ^ right,
2449            Self::Shl => {
2450                if right >= U256::from(256) {
2451                    U256::ZERO
2452                } else {
2453                    left << usize::try_from(right).expect("checked word shift")
2454                }
2455            }
2456            Self::Shr => {
2457                if right >= U256::from(256) {
2458                    U256::ZERO
2459                } else {
2460                    left >> usize::try_from(right).expect("checked word shift")
2461                }
2462            }
2463            Self::Sar => {
2464                if right >= U256::from(256) {
2465                    left.arithmetic_shr(256)
2466                } else {
2467                    left.arithmetic_shr(usize::try_from(right).expect("checked word shift"))
2468                }
2469            }
2470            Self::MulHigh => {
2471                let product = left.widening_mul::<256, 4, 512, 8>(right);
2472                U256::from_limbs_slice(&product.as_limbs()[4..])
2473            }
2474        }
2475    }
2476}
2477
2478pub(crate) fn keccak_word(cx: &mut SymCx, bytes: Vec<SymExpr>) -> SymExpr {
2479    let len = bytes.len();
2480    let len = SymExpr::constant(cx, U256::from(len));
2481    keccak_word_with_len(cx, bytes, len)
2482}
2483
2484pub(crate) fn keccak_word_with_len(cx: &mut SymCx, bytes: Vec<SymExpr>, len: SymExpr) -> SymExpr {
2485    if let Some(len) = len.as_const()
2486        && let Ok(len) = usize::try_from(len)
2487        && len <= bytes.len()
2488        && let Ok(concrete) = concrete_expr_bytes(&bytes[..len], "symbolic keccak input")
2489    {
2490        let hash = Into::<U256>::into(keccak256(concrete));
2491        cx.record_concrete_keccak_preimage(hash, bytes[..len].to_vec().into());
2492        return SymExpr::constant(cx, hash);
2493    }
2494
2495    let exprs = bytes;
2496    let identity = ExpressionDigests::identity(std::iter::once(&len).chain(&exprs));
2497    let name = stable_symbol(cx, "keccak", identity.as_slice());
2498    SymExpr::keccak_symbol(cx, name, len, exprs)
2499}
2500
2501pub(crate) fn symbolic_hash_word_with_len(
2502    cx: &mut SymCx,
2503    algorithm: &'static str,
2504    bytes: Vec<SymExpr>,
2505    len: SymExpr,
2506) -> SymExpr {
2507    let exprs = bytes;
2508    let identity = ExpressionDigests::identity(std::iter::once(&len).chain(&exprs));
2509    let name = stable_symbol(cx, algorithm, identity.as_slice());
2510    let mut identity = Vec::with_capacity(exprs.len() + 1);
2511    identity.push(len);
2512    identity.extend(exprs);
2513    SymExpr::hash_symbol(cx, name, algorithm, identity)
2514}
2515
2516pub(crate) fn create2_address_word(
2517    cx: &mut SymCx,
2518    state: &mut PathState,
2519    creator: Address,
2520    salt: SymExpr,
2521    initcode: &SymCode,
2522) -> Result<(SymExpr, Address), SymbolicError> {
2523    match (salt.as_const(), initcode.concrete_bytes(cx, "symbolic CREATE2 initcode")) {
2524        (Some(salt), Ok(initcode)) => {
2525            let address = creator.create2_from_code(salt.to_be_bytes::<32>(), &initcode);
2526            Ok((SymExpr::constant(cx, address_word(address)), address))
2527        }
2528        (None, Ok(initcode)) => {
2529            let word = create2_hash_address_word(cx, creator, salt, keccak256(&initcode));
2530            let address = state.world.symbolic_address_slot(word.clone());
2531            Ok((word, address))
2532        }
2533        (_, Err(SymbolicError::Unsupported("symbolic CREATE2 initcode"))) => {
2534            let initcode_bytes = initcode.read_byte_exprs(cx, 0, initcode.len());
2535            let word = symbolic_create2_address_word(
2536                cx,
2537                state,
2538                format!("address:{creator:?}"),
2539                salt,
2540                format!("initcode:{:?}", ExpressionDigests::identity(&initcode_bytes)),
2541            );
2542            let address = state.world.symbolic_address_slot(word.clone());
2543            Ok((word, address))
2544        }
2545        (_, Err(err)) => Err(err),
2546    }
2547}
2548
2549pub(crate) fn compute_create2_address_word(
2550    cx: &mut SymCx,
2551    state: &mut PathState,
2552    deployer: SymExpr,
2553    salt: SymExpr,
2554    init_code_hash: SymExpr,
2555) -> Result<SymExpr, SymbolicError> {
2556    let deployer_concrete = state.constrained_word(cx, &deployer).map(word_to_address);
2557    let salt_concrete = state.constrained_word(cx, &salt);
2558    let init_code_hash_concrete = state.constrained_word(cx, &init_code_hash);
2559
2560    if let (Some(deployer), Some(salt), Some(init_code_hash)) =
2561        (deployer_concrete, salt_concrete, init_code_hash_concrete)
2562    {
2563        let init_code_hash = B256::from(init_code_hash);
2564        let address = deployer.create2(B256::from(salt), init_code_hash);
2565        return Ok(SymExpr::constant(cx, address_word(address)));
2566    }
2567    if let (Some(deployer), Some(init_code_hash)) = (deployer_concrete, init_code_hash_concrete) {
2568        return Ok(create2_hash_address_word(cx, deployer, salt, B256::from(init_code_hash)));
2569    }
2570
2571    let deployer_identity = deployer_identity(deployer_concrete, &deployer);
2572    let init_code_hash_identity = init_code_hash_concrete
2573        .map(|init_code_hash| {
2574            let init_code_hash = B256::from(init_code_hash);
2575            format!("hash:{init_code_hash:?}")
2576        })
2577        .unwrap_or_else(|| {
2578            format!("hash_expr:{:?}", ExpressionDigests::identity([&init_code_hash]))
2579        });
2580
2581    Ok(symbolic_create2_address_word(cx, state, deployer_identity, salt, init_code_hash_identity))
2582}
2583
2584pub(crate) fn compute_create_address_word(
2585    cx: &mut SymCx,
2586    state: &mut PathState,
2587    deployer: SymExpr,
2588    nonce: SymExpr,
2589) -> Result<SymExpr, SymbolicError> {
2590    let deployer_concrete = state.constrained_word(cx, &deployer).map(word_to_address);
2591    let nonce_concrete = state.constrained_word(cx, &nonce);
2592
2593    if let (Some(deployer), Some(nonce)) = (deployer_concrete, nonce_concrete) {
2594        let Ok(nonce) = u64::try_from(nonce) else {
2595            return Err(SymbolicError::Unsupported("symbolic vm.computeCreateAddress nonce"));
2596        };
2597        return Ok(SymExpr::constant(cx, address_word(deployer.create(nonce))));
2598    }
2599
2600    let deployer_identity = deployer_identity(deployer_concrete, &deployer);
2601    Ok(symbolic_create_address_word(cx, state, deployer_identity, nonce))
2602}
2603
2604pub(crate) fn symbolic_create_address_word(
2605    cx: &mut SymCx,
2606    state: &mut PathState,
2607    creator_identity: String,
2608    nonce: SymExpr,
2609) -> SymExpr {
2610    let nonce = ExpressionDigests::identity([&nonce]);
2611    let name =
2612        stable_symbol(cx, "create_address", format!("{creator_identity}:{nonce:?}").as_bytes());
2613    let word = SymExpr::get_var(cx, name);
2614    state.constraints.push(SymBoolExpr::cmp_word_const(cx, SymCmpOp::Ult, &word, U256::ONE << 160));
2615    word
2616}
2617
2618pub(crate) fn symbolic_create2_address_word(
2619    cx: &mut SymCx,
2620    state: &mut PathState,
2621    creator_identity: String,
2622    salt: SymExpr,
2623    initcode_identity: String,
2624) -> SymExpr {
2625    let name = stable_symbol(
2626        cx,
2627        "create2_address",
2628        format!(
2629            "{creator_identity}:{:?}:{initcode_identity}",
2630            ExpressionDigests::identity([&salt])
2631        )
2632        .as_bytes(),
2633    );
2634    let word = SymExpr::get_var(cx, name);
2635    state.constraints.push(SymBoolExpr::cmp_word_const(cx, SymCmpOp::Ult, &word, U256::ONE << 160));
2636    word
2637}
2638
2639/// Builds `keccak256(0xff ++ deployer ++ salt ++ init_code_hash)` cut to an address.
2640///
2641/// The bytes match `abi.encodePacked` of the same values, so a test that predicts the address
2642/// hashes the same preimage and the Keccak equality rewrite relates both.
2643fn create2_hash_address_word(
2644    cx: &mut SymCx,
2645    deployer: Address,
2646    salt: SymExpr,
2647    init_code_hash: B256,
2648) -> SymExpr {
2649    let mut bytes = Vec::with_capacity(85);
2650    bytes.push(SymExpr::constant(cx, U256::from(0xff)));
2651    bytes.extend(deployer.iter().map(|byte| SymExpr::constant(cx, U256::from(*byte))));
2652    bytes.extend((0..32).map(|index| byte_expr(cx, index, &salt)));
2653    bytes.extend(init_code_hash.iter().map(|byte| SymExpr::constant(cx, U256::from(*byte))));
2654    let hash = keccak_word(cx, bytes);
2655    let mask = SymExpr::constant(cx, (U256::ONE << 160) - U256::ONE);
2656    SymExpr::binop(cx, SymBinOp::And, hash, mask)
2657}
2658
2659/// Identifies a deployer in a stable address symbol name.
2660///
2661/// The prefixes keep a concrete address apart from the digest of a symbolic deployer.
2662fn deployer_identity(concrete: Option<Address>, deployer: &SymExpr) -> String {
2663    concrete
2664        .map(|deployer| format!("address:{deployer:?}"))
2665        .unwrap_or_else(|| format!("address_expr:{:?}", ExpressionDigests::identity([deployer])))
2666}
2667
2668#[cfg(test)]
2669mod tests {
2670    use super::*;
2671
2672    // Each level reuses the previous node twice, so a walk without memoization visits 2^64 nodes.
2673    #[test]
2674    fn collect_vars_visits_shared_nodes_once() {
2675        let mut cx = SymCx::new();
2676        let x = SymExpr::var(&mut cx, "x");
2677        let y = SymExpr::var(&mut cx, "y");
2678        let mut expr = x.clone();
2679        for _ in 0..64 {
2680            let product = SymExpr::from_kind(
2681                &mut cx,
2682                SymExprKind::BinOp(SymBinOp::Mul, expr.clone(), y.clone()),
2683            );
2684            expr = SymExpr::from_kind(&mut cx, SymExprKind::BinOp(SymBinOp::Add, expr, product));
2685        }
2686        let condition = SymBoolExpr::eq_word_const(&mut cx, &expr, U256::from(7));
2687
2688        let mut vars = SymbolicVars::default();
2689        expr.collect_eval_vars(&mut vars);
2690        condition.collect_vars(&mut vars);
2691        assert_eq!(
2692            vars.iter().copied().collect::<Vec<_>>(),
2693            [x.kind().get_var().unwrap(), y.kind().get_var().unwrap(),]
2694        );
2695
2696        let mut visited = HashSet::<SymExpr>::default();
2697        let result = condition.visit_exprs::<()>(&mut |node| {
2698            assert!(visited.insert(node.clone()), "shared node visited twice");
2699            ControlFlow::Continue(())
2700        });
2701        assert!(result.is_continue());
2702        let mut visits = 0;
2703        let result = expr.visit(&mut |_| {
2704            visits += 1;
2705            if visits == 2 { ControlFlow::Break(42) } else { ControlFlow::Continue(()) }
2706        });
2707        assert_eq!(result, ControlFlow::Break(42));
2708        assert_eq!(visits, 2);
2709    }
2710}