use super::{Counter, Runner, Stop};
use crate::expr::{Context, OpCode};
use crate::hash::IdMap;
use crate::ops::{BinOp, CmpOp, UnOp};
const MAX_LEAVES: usize = 32;
const MAX_FREE_BITS: usize = 32;
const MAX_HALF_BITS: usize = 16;
const MAX_SOLUTIONS: usize = 4;
const MAX_GROUP_BITS: usize = 4;
const MAX_SMALL_NODES: usize = 48;
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct BitKey {
word: u32,
bit: u16,
}
#[derive(Copy, Clone, Debug)]
struct SmallTable {
bits: [BitKey; 2],
n_bits: u8,
vals: [u64; 4],
}
#[derive(Clone, Debug)]
struct Group128 {
bits: Vec<BitKey>,
vals: Vec<u128>,
}
pub(in crate::engine::pass) fn reduce(
r: &mut Runner<'_, '_>,
cx: &mut Context,
root: u32,
) -> Result<Option<u32>, Stop> {
let Some((a, b, ca, cb, want_eq)) = extract_128_eq(cx, root) else {
return Ok(None);
};
let key = (a, b, ((cb as u128) << 64) | (ca as u128));
if let Some(&cached) = r.mba.bit_tables.get(&key) {
return Ok(match cached {
Some(eq_node) if want_eq => Some(eq_node),
Some(eq_node) => Some(r.build(cx, |cx| cx.c_un(UnOp::Not, eq_node))?),
None => None,
});
}
let solved = if let Some(res) = solve_pair(r, cx, a, b, ca, cb)? {
Some(res)
} else {
solve_pair(r, cx, b, a, cb, ca)?
};
r.mba.bit_tables.insert(key, solved);
let Some(eq_node) = solved else {
return Ok(None);
};
if want_eq {
Ok(Some(eq_node))
} else {
Ok(Some(r.build(cx, |cx| cx.c_un(UnOp::Not, eq_node))?))
}
}
fn extract_128_eq(cx: &Context, root: u32) -> Option<(u32, u32, u64, u64, bool)> {
let n = cx.node(root);
if n.width != 1 {
return None;
}
match n.op {
OpCode::Eq | OpCode::Ne => {
let want_eq = n.op == OpCode::Eq;
let (lhs, k) = match (cx.const_val(n.a), cx.const_val(n.b)) {
(None, Some(k)) => (n.a, k.to_u64()?),
(Some(k), None) => (n.b, k.to_u64()?),
_ => return None,
};
if cx.wid(lhs) != 64 {
return None;
}
let (or_node, inverted) = match (cx.node(lhs).op, k) {
(OpCode::Or, 0) => (lhs, false),
(OpCode::Not, u64::MAX) if cx.node(cx.node(lhs).a).op == OpCode::Or => {
(cx.node(lhs).a, false)
}
(OpCode::And, u64::MAX) => {
let an = cx.node(lhs);
let (na, nb) = (cx.node(an.a), cx.node(an.b));
if na.op == OpCode::Not && nb.op == OpCode::Not {
let (ea, ca) = zero_test_64(cx, na.a)?;
let (eb, cb) = zero_test_64(cx, nb.a)?;
return Some((ea, eb, ca, cb, want_eq));
}
return None;
}
_ => return None,
};
let _ = inverted;
let on = cx.node(or_node);
let (ea, ca) = zero_test_64(cx, on.a)?;
let (eb, cb) = zero_test_64(cx, on.b)?;
Some((ea, eb, ca, cb, want_eq))
}
OpCode::And => {
let (ea, ca) = eq_const_64(cx, n.a, true)?;
let (eb, cb) = eq_const_64(cx, n.b, true)?;
Some((ea, eb, ca, cb, true))
}
OpCode::Or => {
let (ea, ca) = eq_const_64(cx, n.a, false)?;
let (eb, cb) = eq_const_64(cx, n.b, false)?;
Some((ea, eb, ca, cb, false))
}
_ => None,
}
}
fn eq_const_64(cx: &Context, i: u32, is_eq: bool) -> Option<(u32, u64)> {
let n = cx.node(i);
if (is_eq && n.op != OpCode::Eq) || (!is_eq && n.op != OpCode::Ne) {
return None;
}
let (lhs, k) = match (cx.const_val(n.a), cx.const_val(n.b)) {
(None, Some(k)) => (n.a, k.to_u64()?),
(Some(k), None) => (n.b, k.to_u64()?),
_ => return None,
};
if cx.wid(lhs) != 64 {
return None;
}
if cx.node(lhs).op == OpCode::Add {
return Some((lhs, k));
}
None
}
fn zero_test_64(cx: &Context, mut x: u32) -> Option<(u32, u64)> {
let mut target = 0u64;
for _ in 0..6 {
let n = cx.node(x);
if n.width != 64 {
return None;
}
match n.op {
OpCode::Xor => {
if let Some(k) = cx.const_val(n.b).and_then(|v| v.to_u64()) {
target ^= k;
x = n.a;
} else if let Some(k) = cx.const_val(n.a).and_then(|v| v.to_u64()) {
target ^= k;
x = n.b;
} else {
break;
}
}
OpCode::Not => {
target = !target;
x = n.a;
}
OpCode::Sub => {
if let Some(k) = cx.const_val(n.b).and_then(|v| v.to_u64()) {
target = target.wrapping_add(k);
x = n.a;
} else if let Some(k) = cx.const_val(n.a).and_then(|v| v.to_u64()) {
target = k.wrapping_sub(target);
x = n.b;
} else {
break;
}
}
OpCode::Add => {
return Some((x, target));
}
_ => break,
}
}
(cx.node(x).op == OpCode::Add).then_some((x, target))
}
fn flatten_add_only(cx: &Context, root: u32, max_terms: usize) -> Option<(Vec<u32>, u64)> {
let mut stack = vec![root];
let mut out = Vec::new();
let mut bias = 0u64;
let mut steps = 0usize;
while let Some(i) = stack.pop() {
steps += 1;
if steps > max_terms * 4 {
return None;
}
if let Some(k) = cx.const_val(i).and_then(|v| v.to_u64()) {
bias = bias.wrapping_add(k);
continue;
}
let n = cx.node(i);
if n.op == OpCode::Add && n.width == 64 {
stack.push(n.b);
stack.push(n.a);
} else {
if out.len() >= max_terms {
return None;
}
out.push(i);
}
}
Some((out, bias))
}
fn flatten_hi_sum(cx: &Context, root: u32, max_terms: usize) -> Option<(Vec<(u32, bool)>, u64)> {
let mut stack = vec![(root, false)];
let mut out = Vec::new();
let mut bias = 0u64;
let mut steps = 0usize;
while let Some((i, neg)) = stack.pop() {
steps += 1;
if steps > max_terms * 6 {
return None;
}
if let Some(k) = cx.const_val(i).and_then(|v| v.to_u64()) {
bias = if neg {
bias.wrapping_sub(k)
} else {
bias.wrapping_add(k)
};
continue;
}
let n = cx.node(i);
if n.width != 64 {
return None;
}
match n.op {
OpCode::Add => {
stack.push((n.b, neg));
stack.push((n.a, neg));
}
OpCode::Sub => {
stack.push((n.b, !neg));
stack.push((n.a, neg));
}
OpCode::Neg => {
stack.push((n.a, !neg));
}
_ => {
if out.len() >= max_terms {
return None;
}
out.push((i, neg));
}
}
}
Some((out, bias))
}
fn peel_bit(cx: &Context, cond: u32) -> Option<Result<(BitKey, bool), bool>> {
let mut cur = cond;
let mut pol = true;
let (mut word, mut bit): (u32, u16) = loop {
let n = cx.node(cur);
if let Some(v) = cx.const_val(cur) {
if n.width == 1 {
return Some(Err((!v.is_zero()) == pol));
}
return None;
}
match n.op {
OpCode::Not if n.width == 1 => {
pol = !pol;
cur = n.a;
}
OpCode::Eq | OpCode::Ne => {
let (lhs, k) = match (cx.const_val(n.a), cx.const_val(n.b)) {
(None, Some(k)) => (n.a, k.to_u64()?),
(Some(k), None) => (n.b, k.to_u64()?),
_ => return None,
};
let is_eq = n.op == OpCode::Eq;
if cx.wid(lhs) == 1 {
if k == 0 {
if is_eq {
pol = !pol;
}
cur = lhs;
continue;
} else if k == 1 {
if !is_eq {
pol = !pol;
}
cur = lhs;
continue;
}
return None;
}
let ln = cx.node(lhs);
if ln.op == OpCode::And {
let (src, mask) = match (cx.const_val(ln.a), cx.const_val(ln.b)) {
(None, Some(m)) => (ln.a, m.to_u64()?),
(Some(m), None) => (ln.b, m.to_u64()?),
_ => return None,
};
if mask.is_power_of_two() && (k == 0 || k == mask) {
let bit_on = (k == mask) == is_eq;
if !bit_on {
pol = !pol;
}
break (src, mask.trailing_zeros() as u16);
} else {
return None;
}
} else if ln.op == OpCode::LShr
&& let Some(sh) = cx.const_val(ln.b).and_then(|v| v.to_u64())
&& sh + 1 == u64::from(ln.width)
&& (k == 0 || k == 1)
{
let bit_on = (k == 1) == is_eq;
if !bit_on {
pol = !pol;
}
break (ln.a, sh as u16);
} else {
return None;
}
}
OpCode::Slt | OpCode::Sle | OpCode::Ult | OpCode::Ule => {
let (w, b, p) = crate::expr::field::bit_literal(cx, cur);
if w == cur {
return None;
}
if !p {
pol = !pol;
}
break (w, b);
}
OpCode::Extract if n.width == 1 => {
break (n.a, n.b as u16);
}
_ => return None,
}
};
for _ in 0..16 {
let n = cx.node(word);
let w = n.width;
if bit >= w {
return None;
}
if let Some(v) = cx.const_val(word).and_then(|v| v.to_u64()) {
return Some(Err((((v >> bit) & 1) != 0) == pol));
}
match n.op {
OpCode::Extract => {
bit += n.b as u16;
word = n.a;
}
OpCode::Zext => {
let sw = cx.wid(n.a);
if bit < sw {
word = n.a;
} else {
return Some(Err(!pol));
}
}
OpCode::Sext => {
let sw = cx.wid(n.a);
bit = bit.min(sw - 1);
word = n.a;
}
OpCode::LShr => {
let Some(s) = cx.const_val(n.b).and_then(|v| v.to_u64()) else {
break;
};
if u64::from(bit) + s < u64::from(w) {
bit += s as u16;
word = n.a;
} else {
return Some(Err(!pol));
}
}
OpCode::Shl => {
let Some(s) = cx.const_val(n.b).and_then(|v| v.to_u64()) else {
break;
};
if u64::from(bit) >= s {
bit -= s as u16;
word = n.a;
} else {
return Some(Err(!pol));
}
}
OpCode::And => {
let (src, m) = match (cx.const_val(n.a), cx.const_val(n.b)) {
(None, Some(m)) => (n.a, m.to_u64()?),
(Some(m), None) => (n.b, m.to_u64()?),
_ => break,
};
if (m >> bit) & 1 == 1 {
word = src;
} else {
return Some(Err(!pol));
}
}
OpCode::Or => {
let (src, m) = match (cx.const_val(n.a), cx.const_val(n.b)) {
(None, Some(m)) => (n.a, m.to_u64()?),
(Some(m), None) => (n.b, m.to_u64()?),
_ => break,
};
if (m >> bit) & 1 == 0 {
word = src;
} else {
return Some(Err(pol));
}
}
OpCode::Xor => {
let (src, m) = match (cx.const_val(n.a), cx.const_val(n.b)) {
(None, Some(m)) => (n.a, m.to_u64()?),
(Some(m), None) => (n.b, m.to_u64()?),
_ => break,
};
if (m >> bit) & 1 == 1 {
pol = !pol;
}
word = src;
}
OpCode::Not => {
pol = !pol;
word = n.a;
}
OpCode::RotL | OpCode::RotR if w <= 64 => {
let Some(s) = cx.const_val(n.b).and_then(|v| v.to_u64()) else {
break;
};
let wu = u64::from(w);
let s = (s % wu) as u16;
bit = if n.op == OpCode::RotL {
(bit + w - s) % w
} else {
(bit + s) % w
};
word = n.a;
}
_ => break,
}
}
Some(Ok((BitKey { word, bit }, pol)))
}
fn eval_small_table(cx: &Context, root: u32) -> Option<SmallTable> {
if cx.wid(root) > 64 {
return None;
}
let mut bits = [BitKey { word: 0, bit: 0 }; 2];
let mut n_bits = 0usize;
let mut visited = 0usize;
let mut seen: Vec<u32> = Vec::new();
let mut stack = vec![root];
while let Some(i) = stack.pop() {
if seen.contains(&i) {
continue;
}
seen.push(i);
visited += 1;
if visited > MAX_SMALL_NODES {
return None;
}
let n = cx.node(i);
if n.width > 64 {
return None;
}
if cx.const_val(i).is_some() {
continue;
}
if n.width == 1 && let Some(res) = peel_bit(cx, i) {
if let Ok((bk, _)) = res
&& !bits[..n_bits].contains(&bk)
{
if n_bits == 2 {
return None;
}
bits[n_bits] = bk;
n_bits += 1;
}
continue;
}
match n.op {
OpCode::Select => {
stack.push(n.a);
stack.push(n.b);
stack.push(n.c);
}
OpCode::Add
| OpCode::Sub
| OpCode::Mul
| OpCode::Shl
| OpCode::LShr
| OpCode::And
| OpCode::Or
| OpCode::Xor
| OpCode::Concat
| OpCode::Eq
| OpCode::Ne
| OpCode::Ult
| OpCode::Ule
| OpCode::Slt
| OpCode::Sle => {
stack.push(n.a);
stack.push(n.b);
}
OpCode::Not | OpCode::Neg | OpCode::Zext | OpCode::Sext | OpCode::Extract => {
stack.push(n.a);
}
_ => return None,
}
}
if n_bits == 2 && bits[0] > bits[1] {
bits.swap(0, 1);
}
let mut vals = [0u64; 4];
let mut memo: Vec<(u32, u64)> = Vec::with_capacity(seen.len());
for (assign, slot) in vals.iter_mut().enumerate().take(1usize << n_bits) {
memo.clear();
let v = eval_node(cx, root, &bits[..n_bits], assign, &mut memo, 0)?;
*slot = v;
}
Some(SmallTable {
bits,
n_bits: n_bits as u8,
vals,
})
}
fn eval_node(
cx: &Context,
i: u32,
bits: &[BitKey],
assign: usize,
memo: &mut Vec<(u32, u64)>,
depth: u8,
) -> Option<u64> {
if depth > 40 {
return None;
}
if let Some(&(_, v)) = memo.iter().find(|&&(id, _)| id == i) {
return Some(v);
}
let n = cx.node(i);
let w = n.width;
if w == 0 || w > 64 {
return None;
}
let mask = u64::MAX >> (64 - w);
let val = if let Some(k) = cx.const_val(i) {
k.to_u64()? & mask
} else if w == 1 && let Some(res) = peel_bit(cx, i) {
match res {
Err(c) => u64::from(c),
Ok((bk, pol)) => {
let pos = bits.iter().position(|&k| k == bk)?;
let bit_val = ((assign >> pos) & 1) != 0;
u64::from(bit_val == pol)
}
}
} else {
match n.op {
OpCode::Select => {
let c = eval_node(cx, n.a, bits, assign, memo, depth + 1)?;
if c != 0 {
eval_node(cx, n.b, bits, assign, memo, depth + 1)?
} else {
eval_node(cx, n.c, bits, assign, memo, depth + 1)?
}
}
OpCode::Add => {
let a = eval_node(cx, n.a, bits, assign, memo, depth + 1)?;
let b = eval_node(cx, n.b, bits, assign, memo, depth + 1)?;
a.wrapping_add(b) & mask
}
OpCode::Sub => {
let a = eval_node(cx, n.a, bits, assign, memo, depth + 1)?;
let b = eval_node(cx, n.b, bits, assign, memo, depth + 1)?;
a.wrapping_sub(b) & mask
}
OpCode::Mul => {
let a = eval_node(cx, n.a, bits, assign, memo, depth + 1)?;
let b = eval_node(cx, n.b, bits, assign, memo, depth + 1)?;
a.wrapping_mul(b) & mask
}
OpCode::Shl => {
let a = eval_node(cx, n.a, bits, assign, memo, depth + 1)?;
let b = eval_node(cx, n.b, bits, assign, memo, depth + 1)?;
if b >= u64::from(w) { 0 } else { (a << b) & mask }
}
OpCode::LShr => {
let a = eval_node(cx, n.a, bits, assign, memo, depth + 1)?;
let b = eval_node(cx, n.b, bits, assign, memo, depth + 1)?;
if b >= u64::from(w) { 0 } else { (a >> b) & mask }
}
OpCode::And => {
let a = eval_node(cx, n.a, bits, assign, memo, depth + 1)?;
let b = eval_node(cx, n.b, bits, assign, memo, depth + 1)?;
(a & b) & mask
}
OpCode::Or => {
let a = eval_node(cx, n.a, bits, assign, memo, depth + 1)?;
let b = eval_node(cx, n.b, bits, assign, memo, depth + 1)?;
(a | b) & mask
}
OpCode::Xor => {
let a = eval_node(cx, n.a, bits, assign, memo, depth + 1)?;
let b = eval_node(cx, n.b, bits, assign, memo, depth + 1)?;
(a ^ b) & mask
}
OpCode::Not => {
let a = eval_node(cx, n.a, bits, assign, memo, depth + 1)?;
(!a) & mask
}
OpCode::Neg => {
let a = eval_node(cx, n.a, bits, assign, memo, depth + 1)?;
a.wrapping_neg() & mask
}
OpCode::Zext => eval_node(cx, n.a, bits, assign, memo, depth + 1)? & mask,
OpCode::Sext => {
let sw = cx.wid(n.a);
let a = eval_node(cx, n.a, bits, assign, memo, depth + 1)?;
let sign = (a >> (sw - 1)) & 1;
let ext = if sign != 0 {
a | (!0u64 << sw)
} else {
a
};
ext & mask
}
OpCode::Extract => {
let a = eval_node(cx, n.a, bits, assign, memo, depth + 1)?;
(a >> n.b) & mask
}
OpCode::Concat => {
let hi = eval_node(cx, n.a, bits, assign, memo, depth + 1)?;
let lo = eval_node(cx, n.b, bits, assign, memo, depth + 1)?;
let lw = cx.wid(n.b);
((hi << lw) | lo) & mask
}
OpCode::Eq => {
let a = eval_node(cx, n.a, bits, assign, memo, depth + 1)?;
let b = eval_node(cx, n.b, bits, assign, memo, depth + 1)?;
u64::from(a == b)
}
OpCode::Ne => {
let a = eval_node(cx, n.a, bits, assign, memo, depth + 1)?;
let b = eval_node(cx, n.b, bits, assign, memo, depth + 1)?;
u64::from(a != b)
}
OpCode::Ult => {
let a = eval_node(cx, n.a, bits, assign, memo, depth + 1)?;
let b = eval_node(cx, n.b, bits, assign, memo, depth + 1)?;
u64::from(a < b)
}
OpCode::Ule => {
let a = eval_node(cx, n.a, bits, assign, memo, depth + 1)?;
let b = eval_node(cx, n.b, bits, assign, memo, depth + 1)?;
u64::from(a <= b)
}
OpCode::Slt | OpCode::Sle => {
let aw = cx.wid(n.a);
let shift = 64 - aw;
let a = (eval_node(cx, n.a, bits, assign, memo, depth + 1)? << shift) as i64;
let b = (eval_node(cx, n.b, bits, assign, memo, depth + 1)? << shift) as i64;
u64::from(if n.op == OpCode::Slt { a < b } else { a <= b })
}
_ => return None,
}
};
memo.push((i, val));
Some(val)
}
enum CarryTerm {
SumLt(u32, u32),
NotLt(u32, u32),
}
fn parse_carry(cx: &Context, term: u32) -> Option<CarryTerm> {
let n = cx.node(term);
if n.op != OpCode::Zext || n.width != 64 || cx.wid(n.a) != 1 {
return None;
}
let cmp = cx.node(n.a);
if cmp.op != OpCode::Ult || cx.wid(cmp.a) != 64 {
return None;
}
let lhs = cmp.a;
let rhs = cmp.b;
if cx.node(lhs).op == OpCode::Not {
return Some(CarryTerm::NotLt(cx.node(lhs).a, rhs));
}
if cx.node(rhs).op == OpCode::Not {
return None;
}
Some(CarryTerm::SumLt(lhs, rhs))
}
fn expr_leaf_mask(
cx: &Context,
x: u32,
leaf_ids: &[u32],
absorbed_bias: Option<(usize, u64)>,
const_leaf: Option<(usize, u64)>,
) -> Option<u64> {
let (terms, bias) = flatten_add_only(cx, x, leaf_ids.len() + 2)?;
let mut mask = 0u64;
let mut expected_bias = 0u64;
for t in terms {
let idx = leaf_ids.iter().position(|&id| id == t)?;
if (mask >> idx) & 1 != 0 {
return None;
}
mask |= 1u64 << idx;
if let Some((a_idx, a_bias)) = absorbed_bias
&& idx == a_idx
{
expected_bias = expected_bias.wrapping_add(a_bias);
}
}
if bias == expected_bias {
return Some(mask);
}
if let Some((c_idx, c_val)) = const_leaf
&& (mask >> c_idx) & 1 == 0
&& bias == expected_bias.wrapping_add(c_val)
{
return Some(mask | (1u64 << c_idx));
}
None
}
fn solve_pair(
r: &mut Runner<'_, '_>,
cx: &mut Context,
lo_expr: u32,
hi_expr: u32,
c_lo: u64,
c_hi: u64,
) -> Result<Option<u32>, Stop> {
let Some((lo_raw, lo_bias)) = flatten_add_only(cx, lo_expr, MAX_LEAVES) else {
return Ok(None);
};
if lo_raw.len() < 4 || lo_raw.len() > MAX_LEAVES {
return Ok(None);
}
for i in 0..lo_raw.len() {
if lo_raw[i + 1..].contains(&lo_raw[i]) {
return Ok(None);
}
}
let Some((hi_raw, hi_bias)) = flatten_hi_sum(cx, hi_expr, MAX_LEAVES * 4) else {
return Ok(None);
};
let mut carry_candidates: Vec<(u32, CarryTerm)> = Vec::new();
let mut hi_other: Vec<(u32, bool)> = Vec::new();
for (t, neg) in hi_raw {
if !neg && let Some(ct) = parse_carry(cx, t) {
carry_candidates.push((t, ct));
} else {
hi_other.push((t, neg));
}
}
if carry_candidates.len() + 1 < lo_raw.len() {
return Ok(None);
}
let mut lo_tables: Vec<SmallTable> = Vec::with_capacity(lo_raw.len() + 1);
for &leaf in &lo_raw {
let Some(tbl) = eval_small_table(cx, leaf) else {
return Ok(None);
};
lo_tables.push(tbl);
}
let mut absorbed_bias: Option<(usize, u64)> = None;
let mut const_leaf: Option<(usize, u64)> = None;
if lo_bias != 0 {
'find_absorb: for (_, ct) in &carry_candidates {
let ops = match *ct {
CarryTerm::SumLt(a, b) | CarryTerm::NotLt(a, b) => [a, b],
};
for op in ops {
if let Some((ts, b)) = flatten_add_only(cx, op, 2)
&& ts.len() == 1
&& b == lo_bias
&& let Some(idx) = lo_raw.iter().position(|&id| id == ts[0])
{
absorbed_bias = Some((idx, lo_bias));
let len = 1usize << lo_tables[idx].n_bits;
for v in &mut lo_tables[idx].vals[..len] {
*v = v.wrapping_add(lo_bias);
}
break 'find_absorb;
}
}
}
if absorbed_bias.is_none() {
if lo_raw.len() >= MAX_LEAVES {
return Ok(None);
}
const_leaf = Some((lo_raw.len(), lo_bias));
lo_tables.push(SmallTable {
bits: [BitKey { word: 0, bit: 0 }; 2],
n_bits: 0,
vals: [lo_bias, 0, 0, 0],
});
}
}
let m = lo_tables.len();
let full_mask = (1u64 << m) - 1;
let mut active: Vec<u64> = (0..m).map(|i| 1u64 << i).collect();
let mut used = vec![false; carry_candidates.len()];
let mut parsed_carries: Vec<Option<(u64, u64)>> = Vec::with_capacity(carry_candidates.len());
let complement_leaf = |cx: &Context, x: u32| -> Option<usize> {
let xt = eval_small_table(cx, x)?;
let len = 1usize << xt.n_bits;
lo_tables.iter().enumerate().position(|(_, lt)| {
lt.n_bits == xt.n_bits
&& lt.bits[..xt.n_bits as usize] == xt.bits[..xt.n_bits as usize]
&& (0..len).all(|a| !lt.vals[a] == xt.vals[a])
})
};
for (_, ct) in &carry_candidates {
let pair = match *ct {
CarryTerm::SumLt(sum, part) => {
if let (Some(sm), Some(pm)) = (
expr_leaf_mask(cx, sum, &lo_raw, absorbed_bias, const_leaf),
expr_leaf_mask(cx, part, &lo_raw, absorbed_bias, const_leaf),
) && pm != 0
&& (sm & pm) == pm
&& sm != pm
{
Some((sm ^ pm, pm))
} else if let (Some(k), Some(ym)) = (
complement_leaf(cx, sum),
expr_leaf_mask(cx, part, &lo_raw, absorbed_bias, const_leaf),
) && ym != 0
&& ((ym >> k) & 1) == 0
{
Some((1u64 << k, ym))
} else {
None
}
}
CarryTerm::NotLt(x, y) => {
if let (Some(xm), Some(ym)) = (
expr_leaf_mask(cx, x, &lo_raw, absorbed_bias, const_leaf),
expr_leaf_mask(cx, y, &lo_raw, absorbed_bias, const_leaf),
) && xm != 0
&& ym != 0
&& (xm & ym) == 0
{
Some((xm, ym))
} else {
None
}
}
};
parsed_carries.push(pair);
}
loop {
let mut merged_any = false;
for (idx, pair) in parsed_carries.iter().enumerate() {
if used[idx] {
continue;
}
let Some((u, v)) = *pair else { continue };
let Some(pu) = active.iter().position(|&c| c == u) else {
continue;
};
let Some(pv) = active.iter().position(|&c| c == v) else {
continue;
};
if pu == pv {
continue;
}
used[idx] = true;
let combined = u | v;
if pu > pv {
active.swap_remove(pu);
active[pv] = combined;
} else {
active.swap_remove(pv);
active[pu] = combined;
}
merged_any = true;
}
if !merged_any {
break;
}
}
if active.len() != 1 || active[0] != full_mask {
return Ok(None);
}
for (idx, &(term, _)) in carry_candidates.iter().enumerate() {
if !used[idx] {
hi_other.push((term, false));
}
}
let mut hi_tables: Vec<(SmallTable, bool)> = Vec::with_capacity(hi_other.len());
for (term, neg) in hi_other {
let Some(tbl) = eval_small_table(cx, term) else {
return Ok(None);
};
hi_tables.push((tbl, neg));
}
let unify = build_bit_unification(cx, &lo_tables, &hi_tables);
let mut lo_128: Vec<(SmallTable, bool)> = lo_tables
.into_iter()
.map(|t| (apply_unification(t, &unify), false))
.collect();
let hi_128: Vec<(SmallTable, bool)> = hi_tables
.into_iter()
.map(|(t, neg)| (apply_unification(t, &unify), neg))
.collect();
let mut base128: u128 = (hi_bias as u128) << 64;
let mut groups: Vec<Group128> = Vec::new();
let mut add_table = |tbl: SmallTable, is_hi: bool, neg: bool| -> bool {
let n = tbl.n_bits as usize;
if n == 0 {
let v = if is_hi {
let h = if neg { tbl.vals[0].wrapping_neg() } else { tbl.vals[0] };
(h as u128) << 64
} else {
tbl.vals[0] as u128
};
base128 = base128.wrapping_add(v);
return true;
}
let tbl_bits = &tbl.bits[..n];
let mut vals = Vec::with_capacity(1 << n);
for &raw in &tbl.vals[..(1usize << n)] {
let v = if is_hi {
let h = if neg { raw.wrapping_neg() } else { raw };
(h as u128) << 64
} else {
raw as u128
};
vals.push(v);
}
let mut hits: Vec<usize> = Vec::new();
for (gi, g) in groups.iter().enumerate() {
if tbl_bits.iter().any(|b| g.bits.contains(b)) {
hits.push(gi);
}
}
if hits.is_empty() {
groups.push(Group128 {
bits: tbl_bits.to_vec(),
vals,
});
return true;
}
let mut merged_bits: Vec<BitKey> = tbl_bits.to_vec();
for &gi in &hits {
for &b in &groups[gi].bits {
if !merged_bits.contains(&b) {
merged_bits.push(b);
}
}
}
if merged_bits.len() > MAX_GROUP_BITS {
return false;
}
merged_bits.sort();
let mut merged_vals = vec![0u128; 1 << merged_bits.len()];
let map_tbl: Vec<usize> = tbl_bits
.iter()
.map(|b| merged_bits.iter().position(|x| x == b).unwrap_or(0))
.collect();
for (a, slot) in merged_vals.iter_mut().enumerate() {
let mut ta = 0usize;
for (k, &pos) in map_tbl.iter().enumerate() {
ta |= ((a >> pos) & 1) << k;
}
*slot = slot.wrapping_add(vals[ta]);
}
for &gi in &hits {
let g = &groups[gi];
let map_g: Vec<usize> = g
.bits
.iter()
.map(|b| merged_bits.iter().position(|x| x == b).unwrap_or(0))
.collect();
for (a, slot) in merged_vals.iter_mut().enumerate() {
let mut ga = 0usize;
for (k, &pos) in map_g.iter().enumerate() {
ga |= ((a >> pos) & 1) << k;
}
*slot = slot.wrapping_add(g.vals[ga]);
}
}
for &gi in hits.iter().rev() {
groups.swap_remove(gi);
}
groups.push(Group128 {
bits: merged_bits,
vals: merged_vals,
});
true
};
for (t, _) in lo_128.drain(..) {
if !add_table(t, false, false) {
return Ok(None);
}
}
for (t, neg) in hi_128 {
if !add_table(t, true, neg) {
return Ok(None);
}
}
let target128 = (((c_hi as u128) << 64) | (c_lo as u128)).wrapping_sub(base128);
let total_bits: usize = groups.iter().map(|g| g.bits.len()).sum();
if total_bits > MAX_FREE_BITS {
return solve_carry_split(r, cx, &groups, target128);
}
let Some(sols) = run_mitm(r, &groups, target128)? else {
return Ok(None);
};
emit_solutions(r, cx, &groups, &sols, None)
}
fn build_bit_unification(
cx: &Context,
lo_tables: &[SmallTable],
hi_tables: &[(SmallTable, bool)],
) -> IdMap<BitKey, (BitKey, bool)> {
let mut words: Vec<u32> = Vec::new();
let mut note = |t: &SmallTable| {
for b in &t.bits[..t.n_bits as usize] {
if !words.contains(&b.word) {
words.push(b.word);
}
}
};
for t in lo_tables {
note(t);
}
for (t, _) in hi_tables {
note(t);
}
let mut map: IdMap<BitKey, (BitKey, bool)> = IdMap::default();
if words.len() < 2 {
return map;
}
let low32_origin = |cx: &Context, x: u32| -> Option<u32> {
let n = cx.node(x);
match n.op {
OpCode::Zext if cx.wid(n.a) == 32 => {
let inner = cx.node(n.a);
if inner.op == OpCode::Extract && inner.b == 0 {
Some(inner.a)
} else {
Some(n.a)
}
}
OpCode::And if n.width == 64 => {
let (src, m) = match (cx.const_val(n.a), cx.const_val(n.b)) {
(None, Some(m)) => (n.a, m.to_u64()?),
(Some(m), None) => (n.b, m.to_u64()?),
_ => return None,
};
(m == 0xffffffff).then_some(src)
}
_ => None,
}
};
let word32_origin = |cx: &Context, x: u32| -> u32 {
let n = cx.node(x);
if n.op == OpCode::Extract && n.b == 0 && n.width == 32 {
n.a
} else {
x
}
};
let mut add_words: Vec<(u32, u32, u64)> = Vec::new();
for &w in &words {
let n = cx.node(w);
if n.op == OpCode::Add
&& let Some((lhs, k)) = match (cx.const_val(n.a), cx.const_val(n.b)) {
(None, Some(k)) => Some((n.a, k.to_u64().unwrap_or(0))),
(Some(k), None) => Some((n.b, k.to_u64().unwrap_or(0))),
_ => None,
}
{
if n.width == 64
&& let Some(orig) = low32_origin(cx, lhs)
{
add_words.push((w, orig, k));
} else if n.width <= 64 {
add_words.push((w, lhs, k));
}
}
}
for &(w_add, orig, k) in &add_words {
let nw = cx.wid(w_add);
let tz = if k == 0 { nw } else { (k.trailing_zeros() as u16).min(nw) };
for &other in &words {
if other == w_add {
continue;
}
let on = cx.node(other);
if nw == 64
&& on.width == 32
&& on.op == OpCode::Add
&& let Some((olhs, ok)) = match (cx.const_val(on.a), cx.const_val(on.b)) {
(None, Some(v)) => Some((on.a, v.to_u64().unwrap_or(0))),
(Some(v), None) => Some((on.b, v.to_u64().unwrap_or(0))),
_ => None,
}
&& word32_origin(cx, olhs) == orig
&& (ok as u32) == (k as u32)
{
for b in 0..32u16 {
map.entry(BitKey { word: other, bit: b })
.or_insert((BitKey { word: w_add, bit: b }, false));
}
}
let same_base = other == orig || (nw == 64 && on.width == 32 && word32_origin(cx, other) == orig);
if same_base {
let lim = tz.min(on.width.saturating_sub(1));
for b in 0..=lim {
if b < tz {
map.entry(BitKey { word: other, bit: b })
.or_insert((BitKey { word: w_add, bit: b }, false));
} else if b == tz && b < on.width && k != 0 {
map.entry(BitKey { word: other, bit: b })
.or_insert((BitKey { word: w_add, bit: b }, true));
}
}
}
}
}
map
}
fn apply_unification(mut t: SmallTable, map: &IdMap<BitKey, (BitKey, bool)>) -> SmallTable {
if map.is_empty() || t.n_bits == 0 {
return t;
}
let n = t.n_bits as usize;
let mut flip_mask = 0usize;
for (k, bit_slot) in t.bits.iter_mut().enumerate().take(n) {
if let Some(&(dst, flip)) = map.get(bit_slot) {
*bit_slot = dst;
if flip {
flip_mask |= 1 << k;
}
}
}
if flip_mask != 0 {
let old = t.vals;
for a in 0..(1usize << n) {
t.vals[a] = old[a ^ flip_mask];
}
}
if n == 2 && t.bits[0] == t.bits[1] {
t.vals[1] = t.vals[3];
t.n_bits = 1;
} else if n == 2 && t.bits[0] > t.bits[1] {
t.bits.swap(0, 1);
t.vals.swap(1, 2);
}
t
}
fn solve_carry_split(
r: &mut Runner<'_, '_>,
cx: &mut Context,
groups: &[Group128],
target128: u128,
) -> Result<Option<u32>, Stop> {
let Some(first_word) = groups.first().and_then(|g| g.bits.first()).map(|b| b.word) else {
return Ok(None);
};
if !groups
.iter()
.all(|g| g.bits.iter().all(|b| b.word == first_word))
{
return Ok(None);
}
let wn = cx.node(first_word);
if wn.width != 64 || wn.op != OpCode::Add {
return Ok(None);
}
let Some((lhs, k64)) = (match (cx.const_val(wn.a), cx.const_val(wn.b)) {
(None, Some(k)) => k.to_u64().map(|v| (wn.a, v)),
(Some(k), None) => k.to_u64().map(|v| (wn.b, v)),
_ => None,
}) else {
return Ok(None);
};
let ln = cx.node(lhs);
let is_low32 = (ln.op == OpCode::Zext && cx.wid(ln.a) == 32)
|| (ln.op == OpCode::And
&& cx
.const_val(ln.b)
.or_else(|| cx.const_val(ln.a))
.and_then(|v| v.to_u64())
== Some(0xffffffff));
if !is_low32 {
return Ok(None);
}
let lo32 = k64 as u32;
let hi32 = k64 >> 32;
let mut all_valid: Vec<(u32, u64)> = Vec::new();
let carry_cases: &[u64] = if lo32 == 0 { &[0] } else { &[0, 1] };
for &carry in carry_cases {
let hi_val = hi32.wrapping_add(carry);
let mut sub_groups: Vec<Group128> = Vec::new();
let mut sub_base = 0u128;
for g in groups {
let mut free_idx = Vec::new();
let mut fixed_mask = 0usize;
for (k, b) in g.bits.iter().enumerate() {
if b.bit >= 32 {
if ((hi_val >> (b.bit - 32)) & 1) != 0 {
fixed_mask |= 1 << k;
}
} else {
free_idx.push(k);
}
}
if free_idx.is_empty() {
sub_base = sub_base.wrapping_add(g.vals[fixed_mask]);
} else {
let sub_bits: Vec<BitKey> = free_idx.iter().map(|&k| g.bits[k]).collect();
let mut sub_vals = Vec::with_capacity(1 << free_idx.len());
for a in 0..(1usize << free_idx.len()) {
let mut orig_a = fixed_mask;
for (j, &k) in free_idx.iter().enumerate() {
if (a >> j) & 1 != 0 {
orig_a |= 1 << k;
}
}
sub_vals.push(g.vals[orig_a]);
}
sub_groups.push(Group128 {
bits: sub_bits,
vals: sub_vals,
});
}
}
let free_total: usize = sub_groups.iter().map(|g| g.bits.len()).sum();
if free_total > MAX_FREE_BITS {
return Ok(None);
}
let mut low_mask = 0u32;
for g in &sub_groups {
for b in &g.bits {
low_mask |= 1u32 << b.bit;
}
}
if low_mask != u32::MAX {
return Ok(None);
}
let Some(sols) = run_mitm(r, &sub_groups, target128.wrapping_sub(sub_base))? else {
return Ok(None);
};
for sol in sols {
let mut w32 = 0u32;
for (g, &a) in sub_groups.iter().zip(&sol) {
for (k, b) in g.bits.iter().enumerate() {
if (a >> k) & 1 != 0 {
w32 |= 1u32 << b.bit;
}
}
}
let valid = if carry == 1 { w32 < lo32 } else { w32 >= lo32 };
if valid {
all_valid.push((w32, (hi_val << 32) | u64::from(w32)));
if all_valid.len() > MAX_SOLUTIONS {
return Ok(None);
}
}
}
}
if all_valid.is_empty() {
return Ok(Some(r.build(cx, |cx| cx.mk_const_u64(1, 0))?));
}
let mut acc: Option<u32> = None;
for &(w32, full64) in &all_valid {
let eq = if ln.op == OpCode::Zext && cx.wid(ln.a) == 32 {
let y_val = u64::from(w32.wrapping_sub(lo32));
r.build(cx, |cx| {
let k = cx.mk_const_u64(32, y_val)?;
cx.c_cmp(CmpOp::Eq, ln.a, k)
})?
} else {
r.build(cx, |cx| {
let k = cx.mk_const_u64(64, full64)?;
cx.c_cmp(CmpOp::Eq, first_word, k)
})?
};
acc = Some(match acc {
None => eq,
Some(prev) => r.build(cx, |cx| cx.c_bin(BinOp::Or, prev, eq))?,
});
}
Ok(acc)
}
fn run_mitm(
r: &mut Runner<'_, '_>,
groups: &[Group128],
mut target128: u128,
) -> Result<Option<Vec<Vec<usize>>>, Stop> {
let mut norm: Vec<Vec<u128>> = Vec::with_capacity(groups.len());
for g in groups {
let v0 = g.vals[0];
target128 = target128.wrapping_sub(v0);
norm.push(g.vals.iter().map(|v| v.wrapping_sub(v0)).collect());
}
let mut order: Vec<usize> = (0..groups.len()).collect();
order.sort_by_key(|&i| core::cmp::Reverse(groups[i].bits.len()));
let mut left_idx: Vec<usize> = Vec::new();
let mut right_idx: Vec<usize> = Vec::new();
let (mut n_left, mut n_right) = (0usize, 0usize);
for gi in order {
let b = groups[gi].bits.len();
if n_left <= n_right && n_left + b <= MAX_HALF_BITS {
left_idx.push(gi);
n_left += b;
} else if n_right + b <= MAX_HALF_BITS {
right_idx.push(gi);
n_right += b;
} else if n_left + b <= MAX_HALF_BITS {
left_idx.push(gi);
n_left += b;
} else {
return Ok(None);
}
}
let work_cost = (((1u64 << n_left) + (1u64 << n_right)) / 4).max(64);
if work_cost > r.meter.left_in(|b| b.pass_work) / 2 {
return Ok(None);
}
r.meter.charge(Counter::PassWork, work_cost)?;
let n_l = 1usize << n_left;
let mut left_sums: Vec<u128> = Vec::with_capacity(n_l);
left_sums.push(0);
for &gi in &left_idx {
let vals = &norm[gi];
let prev_len = left_sums.len();
for &delta in &vals[1..] {
for j in 0..prev_len {
let s = left_sums[j].wrapping_add(delta);
left_sums.push(s);
}
}
}
let tab_bits = (n_left + 1).max(4);
let tab_size = 1usize << tab_bits;
let tab_mask = tab_size - 1;
let shift = 64 - tab_bits;
let mut table: Vec<u32> = vec![u32::MAX; tab_size];
for (idx, &sum) in left_sums.iter().enumerate() {
let mut slot = ((sum as u64).wrapping_mul(0x9e3779b97f4a7c15) >> shift) as usize;
while table[slot] != u32::MAX {
slot = (slot + 1) & tab_mask;
}
table[slot] = idx as u32;
}
let n_r = 1usize << n_right;
let mut right_sums: Vec<u128> = Vec::with_capacity(n_r);
right_sums.push(0);
for &gi in &right_idx {
let vals = &norm[gi];
let prev_len = right_sums.len();
for &delta in &vals[1..] {
for j in 0..prev_len {
let s = right_sums[j].wrapping_add(delta);
right_sums.push(s);
}
}
}
let mut solutions: Vec<Vec<usize>> = Vec::new();
for (r_state, &sum_r) in right_sums.iter().enumerate() {
let need = target128.wrapping_sub(sum_r);
let mut slot = ((need as u64).wrapping_mul(0x9e3779b97f4a7c15) >> shift) as usize;
loop {
let entry = table[slot];
if entry == u32::MAX {
break;
}
if left_sums[entry as usize] == need {
if solutions.len() >= MAX_SOLUTIONS {
return Ok(None);
}
let mut sol = vec![0usize; groups.len()];
let mut l_code = entry as usize;
for &gi in &left_idx {
let b = groups[gi].bits.len();
sol[gi] = l_code & ((1 << b) - 1);
l_code >>= b;
}
let mut r_code = r_state;
for &gi in &right_idx {
let b = groups[gi].bits.len();
sol[gi] = r_code & ((1 << b) - 1);
r_code >>= b;
}
solutions.push(sol);
}
slot = (slot + 1) & tab_mask;
}
}
Ok(Some(solutions))
}
fn emit_solutions(
r: &mut Runner<'_, '_>,
cx: &mut Context,
groups: &[Group128],
sols: &[Vec<usize>],
_extra: Option<()>,
) -> Result<Option<u32>, Stop> {
if sols.is_empty() {
return Ok(Some(r.build(cx, |cx| cx.mk_const_u64(1, 0))?));
}
let mut disj: Option<u32> = None;
for sol in sols {
let mut by_word: Vec<(u32, u64, u64)> = Vec::new(); for (g, &a) in groups.iter().zip(sol) {
for (k, bk) in g.bits.iter().enumerate() {
let bit_val = ((a >> k) & 1) as u64;
if let Some(entry) = by_word.iter_mut().find(|e| e.0 == bk.word) {
entry.1 |= 1u64 << bk.bit;
entry.2 |= bit_val << bk.bit;
} else {
by_word.push((bk.word, 1u64 << bk.bit, bit_val << bk.bit));
}
}
}
let mut conj: Option<u32> = None;
for (word, mask, val) in by_word {
let w = cx.wid(word);
if w == 0 || w > 64 {
return Ok(None);
}
let all = u64::MAX >> (64 - w);
let eq = r.build(cx, |cx| {
let lhs = if mask == all {
word
} else {
let m = cx.mk_const_u64(w, mask)?;
cx.c_bin(BinOp::And, word, m)?
};
let rhs = cx.mk_const_u64(w, val)?;
cx.c_cmp(CmpOp::Eq, lhs, rhs)
})?;
conj = Some(match conj {
None => eq,
Some(prev) => r.build(cx, |cx| cx.c_bin(BinOp::And, prev, eq))?,
});
}
let Some(c) = conj else { continue };
disj = Some(match disj {
None => c,
Some(prev) => r.build(cx, |cx| cx.c_bin(BinOp::Or, prev, c))?,
});
}
Ok(disj)
}
#[cfg(test)]
mod tests {
use crate::engine::{Budget, Engine, Run, Strategy};
use crate::mba::MbaConfig;
use crate::{BitVec, Context, ParseOptions, View, Width};
fn run_sweep(expr: &str) -> (Context, crate::Expr) {
let mut cx = Context::new();
let e = cx.parse(expr, &ParseOptions::width(Width::W64)).unwrap();
let strategy = Strategy::deobfuscate()
.with_mba(MbaConfig::default().with_opaque_sweep(true));
let engine = Engine::builder()
.builtin()
.strategy(strategy)
.build()
.unwrap();
let out = engine
.run(&mut cx, &[e], Run::default().with_per_call(Budget::fuel(1 << 18)))
.unwrap();
(cx, out.roots[0].expr)
}
#[test]
fn solves_128bit_bit_table_guard_unique_and_unsat() {
let w: [u128; 8] = [
0x3_123456789abcdef0u128,
0x5_fedcba9876543211u128,
0x2_0f1e2d3c4b5a6978u128,
0x7_a1b2c3d4e5f60718u128,
0x4_9081726354453627u128,
0x6_1122334455667789u128,
0x1_8877665544332211u128,
0x3_deadbeefcafebabeu128,
];
let x_sol: u8 = 0xa5;
let mut target = 0u128;
for (b, &wb) in w.iter().enumerate() {
if (x_sol >> b) & 1 != 0 {
target = target.wrapping_add(wb);
}
}
let mk_group = |k: usize| {
let w00 = 0u128;
let w01 = w[2 * k];
let w10 = w[2 * k + 1];
let w11 = w01.wrapping_add(w10);
let lo = format!(
"select(extract<{}, 1>(x:8), select(extract<{}, 1>(x:8), {:#x}:64, {:#x}), select(extract<{}, 1>(x:8), {:#x}:64, {:#x}))",
2 * k,
2 * k + 1,
w11 as u64,
w01 as u64,
2 * k + 1,
w10 as u64,
w00 as u64
);
let hi = format!(
"select(extract<{}, 1>(x:8), select(extract<{}, 1>(x:8), {:#x}:64, {:#x}), select(extract<{}, 1>(x:8), {:#x}:64, {:#x}))",
2 * k,
2 * k + 1,
(w11 >> 64) as u64,
(w01 >> 64) as u64,
2 * k + 1,
(w10 >> 64) as u64,
(w00 >> 64) as u64
);
(lo, hi)
};
let (l0, h0) = mk_group(0);
let (l1, h1) = mk_group(1);
let (l2, h2) = mk_group(2);
let (l3, h3) = mk_group(3);
let src_unique = format!(
"let %0 = {l0}; let %1 = {l1}; let %2 = {l2}; let %3 = {l3}; \
let %4 = %0 + %1; let %5 = %2 + %3; let %6 = %4 + %5; \
let %7 = ({h0}) + ({h1}) + ({h2}) + ({h3}) + zext<64>(%4 <u %0) + zext<64>(%5 <u %2) + zext<64>(%6 <u %4); \
((%6 ^ {:#x}) | (%7 ^ {:#x})) == 0",
target as u64,
(target >> 64) as u64
);
let (mut cx, out) = run_sweep(&src_unique);
for v in 0..=255u64 {
let got = cx
.eval(&[out], &[("x".into(), BitVec::from_u64(Width::W8, v).unwrap())][..])
.unwrap()[0];
assert_eq!(!got.is_zero(), v == u64::from(x_sol), "mismatch at x={v}");
}
assert!(cx.dag_size(&[out], 10).is_ok());
let unsat_target = target ^ 1;
let src_unsat = format!(
"let %0 = {l0}; let %1 = {l1}; let %2 = {l2}; let %3 = {l3}; \
let %4 = %0 + %1; let %5 = %2 + %3; let %6 = %4 + %5; \
let %7 = ({h0}) + ({h1}) + ({h2}) + ({h3}) + zext<64>(%4 <u %0) + zext<64>(%5 <u %2) + zext<64>(%6 <u %4); \
((%6 ^ {:#x}) | (%7 ^ {:#x})) == 0",
unsat_target as u64,
(unsat_target >> 64) as u64
);
let (cx2, out2) = run_sweep(&src_unsat);
assert!(matches!(cx2.view(out2).unwrap(), View::Const(v) if v.is_zero()));
let src_missing_carry = format!(
"let %0 = {l0}; let %1 = {l1}; let %2 = {l2}; let %3 = {l3}; \
let %4 = %0 + %1; let %5 = %2 + %3; let %6 = %4 + %5; \
let %7 = ({h0}) + ({h1}) + ({h2}) + ({h3}) + zext<64>(%4 <u %0) + zext<64>(%5 <u %2); \
((%6 ^ {:#x}) | (%7 ^ {:#x})) == 0",
target as u64,
(target >> 64) as u64
);
let (mut cx3, out3) = run_sweep(&src_missing_carry);
let orig3 = cx3.parse(&src_missing_carry, &ParseOptions::width(Width::W64)).unwrap();
for v in 0..=255u64 {
let env = [("x".into(), BitVec::from_u64(Width::W8, v).unwrap())];
let vals = cx3.eval(&[orig3, out3], &env[..]).unwrap();
assert_eq!(vals[0], vals[1], "unsound rewrite at x={v}");
}
}
#[test]
fn solves_pushed_complement_carry_guard() {
let w: [u128; 8] = [
0x2_0123456789abcdefu128,
0x6_fedcba9876543210u128,
0x1_13579bdf02468aceu128,
0x4_eca86420fdb97531u128,
0x5_0f0e0d0c0b0a0908u128,
0x3_f0f1f2f3f4f5f6f7u128,
0x7_1020304050607080u128,
0x2_8070605040302010u128,
];
let x_sol: u8 = 0x5c;
let mut target = 0u128;
for (b, &wb) in w.iter().enumerate() {
if (x_sol >> b) & 1 != 0 {
target = target.wrapping_add(wb);
}
}
let mk_group = |k: usize| {
let w00 = 0u128;
let w01 = w[2 * k];
let w10 = w[2 * k + 1];
let w11 = w01.wrapping_add(w10);
let lo = format!(
"select(extract<{}, 1>(x:8), select(extract<{}, 1>(x:8), {:#x}:64, {:#x}), select(extract<{}, 1>(x:8), {:#x}:64, {:#x}))",
2 * k, 2 * k + 1, w11 as u64, w01 as u64, 2 * k + 1, w10 as u64, w00 as u64
);
let lo_not = format!(
"select(extract<{}, 1>(x:8), select(extract<{}, 1>(x:8), {:#x}:64, {:#x}), select(extract<{}, 1>(x:8), {:#x}:64, {:#x}))",
2 * k, 2 * k + 1, !(w11 as u64), !(w01 as u64), 2 * k + 1, !(w10 as u64), !(w00 as u64)
);
let hi = format!(
"select(extract<{}, 1>(x:8), select(extract<{}, 1>(x:8), {:#x}:64, {:#x}), select(extract<{}, 1>(x:8), {:#x}:64, {:#x}))",
2 * k, 2 * k + 1, (w11 >> 64) as u64, (w01 >> 64) as u64, 2 * k + 1, (w10 >> 64) as u64, (w00 >> 64) as u64
);
(lo, lo_not, hi)
};
let (l0, ln0, h0) = mk_group(0);
let (l1, _, h1) = mk_group(1);
let (l2, ln2, h2) = mk_group(2);
let (l3, _, h3) = mk_group(3);
let src = format!(
"let %0 = {l0}; let %1 = {l1}; let %2 = {l2}; let %3 = {l3}; \
let %4 = %0 + %1; let %5 = %2 + %3; let %6 = %4 + %5; \
let %7 = ({h0}) + ({h1}) + ({h2}) + ({h3}) + zext<64>({ln0} <u %1) + zext<64>({ln2} <u %3) + zext<64>(~%4 <u %5); \
((%6 ^ {:#x}) | (%7 ^ {:#x})) == 0",
target as u64,
(target >> 64) as u64
);
let (mut cx, out) = run_sweep(&src);
for v in 0..=255u64 {
let got = cx
.eval(&[out], &[("x".into(), BitVec::from_u64(Width::W8, v).unwrap())][..])
.unwrap()[0];
assert_eq!(!got.is_zero(), v == u64::from(x_sol), "mismatch at x={v}");
}
assert!(cx.dag_size(&[out], 10).is_ok());
}
}