use super::{Accept, By, Fin, PassKind, Reject, Runner, Step, Stop, discard, facts};
use crate::BitVec;
use crate::engine::budget::Counter;
use crate::expr::{Context, OpCode};
use crate::facts::Facts;
use crate::hash::IdMap;
use crate::invert::monotone::{self, Inner, Order};
use crate::invert::{self, MAX_SPLIT, Oracle, Solved};
use crate::ops::{BinOp, CmpOp};
struct Calls<'x, 'r, 'a> {
r: &'x mut Runner<'r, 'a>,
fin: Fin,
}
impl Oracle for Calls<'_, '_, '_> {
type Err = Stop;
fn facts(&mut self, cx: &mut Context, i: u32) -> Result<Option<Facts>, Stop> {
let (f, fin) = facts(self.r, cx, i)?;
self.fin = self.fin.and(fin);
Ok(f)
}
fn charge(&mut self, units: u64) -> Result<(), Stop> {
self.r.meter.charge(Counter::PassWork, units)?;
Ok(())
}
}
fn count<'x>(r: &'x mut Runner<'_, '_>) -> &'x mut crate::engine::PassCounts {
r.stats.passes.entry(PassKind::Invert.name()).or_default()
}
pub(super) fn step(r: &mut Runner<'_, '_>, cx: &mut Context, n: u32) -> Result<Step, Stop> {
let node = cx.node(n);
let Some(op) = node.op.as_cmp() else {
return Ok(Step::Normal(Fin::FINAL));
};
let before = cx.len() as u32;
let mut o = Calls { r, fin: Fin::FINAL };
let e = if op.is_commutative() {
match cx.const_val(node.b) {
Some(c) => {
let join = cx.node(node.a).op;
if (join == OpCode::Or && c.is_zero()) || (join == OpCode::And && c.is_ones()) {
split(cx, &mut o, op, n, node.a, &c, before)?
} else {
match solve(cx, &mut o, op, node.a, &c)? {
Some(e) => Some(e),
None => match halved(cx, &mut o, op, node.a, &c)? {
Some(e) => Some(e),
None => match masked(cx, &mut o, op, node.a, &c)? {
Some(e) => Some(e),
None => match flag(cx, &mut o, op, n, node.a, &c)? {
Some(e) => Some(e),
None => match narrowed(cx, &mut o, node.a)? {
Some(a) => solve(cx, &mut o, op, a, &c)?,
None => None,
}
.filter(|&e| smaller(cx, e, n)),
},
},
},
}
}
}
None => match cancel(cx, &mut o, op, node.a, node.b)? {
Some(e) => Some(e),
None => match (narrowed(cx, &mut o, node.a)?, narrowed(cx, &mut o, node.b)?) {
(Some(a), Some(b)) => cancel(cx, &mut o, op, a, b)?,
_ => None,
}
.filter(|&e| smaller(cx, e, n)),
},
}
} else {
match (cx.const_val(node.a), cx.const_val(node.b)) {
(_, Some(c)) => match sign_bit(cx, &mut o, op, node.a, &c, false)? {
Some(e) => Some(e),
None => solve_order(cx, &mut o, op, node.a, &c, false)?,
},
(Some(c), None) => match sign_bit(cx, &mut o, op, node.b, &c, true)? {
Some(e) => Some(e),
None => solve_order(cx, &mut o, op, node.b, &c, true)?,
},
(None, None) => cancel_order(cx, &mut o, op, node.a, node.b)?,
}
};
let e = match e {
Some(e) => Some(e),
None => fitted(cx, &mut o, op, n, node.a, node.b)?,
};
let fin = o.fin;
let e = match e {
Some(e) if e != n => e,
_ => {
discard(r, cx, before);
count(r).noop += 1;
return Ok(Step::Normal(fin));
}
};
match r.accept(cx, By::Pass(PassKind::Invert.name()), true, n, e, fin.rel)? {
Accept::Yes => {
count(r).changed += 1;
Ok(Step::To(e, fin))
}
Accept::Vetoed => {
count(r).rejected += 1;
discard(r, cx, before);
Ok(Step::Normal(fin))
}
Accept::Rejected(reason) => {
count(r).rejected += 1;
discard(r, cx, before);
if matches!(reason, Reject::Width | Reject::Verify | Reject::Tripwire) {
r.quarantined_passes.push(PassKind::Invert);
r.stats.quarantined += 1;
}
Ok(Step::Normal(fin))
}
}
}
fn halved(
cx: &mut Context,
o: &mut Calls<'_, '_, '_>,
op: CmpOp,
lhs: u32,
k: &BitVec,
) -> Result<Option<u32>, Stop> {
let node = cx.node(lhs);
let w = node.width;
let zeros = |v: &BitVec| (0..w).take_while(|&i| v.bit(i) == Some(false)).count() as u16;
let (x, t, odd) = match node.op {
OpCode::Mul => {
let (x, c) = match (cx.const_val(node.a), cx.const_val(node.b)) {
(None, Some(c)) => (node.a, c),
(Some(c), None) => (node.b, c),
_ => return Ok(None),
};
(x, zeros(&c), Some(c))
}
OpCode::Shl => match cx.const_val(node.b).and_then(|c| c.to_u64()) {
Some(t) if t < u64::from(w) => (node.a, t as u16, None),
_ => return Ok(None),
},
_ => return Ok(None),
};
if t == 0 || t >= w {
return Ok(None);
}
o.r.meter.charge(Counter::PassWork, 1)?;
if zeros(k) < t {
return Ok(Some(truth(o, cx, op == CmpOp::Ne)?));
}
let m = w - t;
let width = crate::Width::new(m).map_err(|e| Stop::Error(e.into()))?;
let slice = |v: &BitVec| v.extract(t, width).map_err(|e| Stop::Error(e.into()));
let k = slice(k)?;
let odd = match odd {
Some(c) => Some(slice(&c)?),
None => None,
};
let narrow = o.r.build(cx, |cx| {
let low = cx.c_extract(x, 0, m)?;
match odd {
Some(d) if d != BitVec::one(width) => {
let d = cx.mk_const(&d)?;
cx.c_bin(BinOp::Mul, low, d)
}
_ => Ok(low),
}
})?;
Ok(Some(match solve(cx, o, op, narrow, &k)? {
Some(e) => e,
None => compare(o, cx, op, narrow, &k)?,
}))
}
fn masked(
cx: &mut Context,
o: &mut Calls<'_, '_, '_>,
op: CmpOp,
lhs: u32,
k: &BitVec,
) -> Result<Option<u32>, Stop> {
let node = cx.node(lhs);
let constant = |a: u32, b: u32| match (cx.const_val(a), cx.const_val(b)) {
(None, Some(c)) => Some((a, c)),
(Some(c), None) => Some((b, c)),
_ => None,
};
let and = |a: &BitVec, b: &BitVec| BitVec::bin_unchecked(BinOp::And, a, b);
let not = |a: &BitVec| BitVec::un_unchecked(crate::ops::UnOp::Not, a);
let (mut y, mut c, mut k, mut changed) = match node.op {
OpCode::Or => {
let Some((y, m)) = constant(node.a, node.b) else {
return Ok(None);
};
if and(k, &m) != m {
return Ok(Some(truth(o, cx, op == CmpOp::Ne)?));
}
(y, not(&m), and(k, ¬(&m)), true)
}
OpCode::And => {
let Some((y, c)) = constant(node.a, node.b) else {
return Ok(None);
};
if !and(k, ¬(&c)).is_zero() {
return Ok(Some(truth(o, cx, op == CmpOp::Ne)?));
}
(y, c, *k, false)
}
_ => return Ok(None),
};
o.r.meter.charge(Counter::PassWork, 1)?;
loop {
let n = cx.node(y);
match n.op {
OpCode::Extract => {
let wide = cx.width_of(n.a);
let at = BitVec::wrapping_from_u64(wide, u64::from(n.b));
let up = |v: &BitVec| -> Result<BitVec, Stop> {
let z = v.zext(wide).map_err(|e| Stop::Error(e.into()))?;
Ok(BitVec::bin_unchecked(BinOp::Shl, &z, &at))
};
(c, k) = (up(&c)?, up(&k)?);
y = n.a;
}
OpCode::Zext => {
let narrow = cx.width_of(n.a);
let low = |v: &BitVec| v.trunc(narrow).map_err(|e| Stop::Error(e.into()));
let back = low(&k)?
.zext(k.width())
.map_err(|e| Stop::Error(e.into()))?;
if back != k {
return Ok(Some(truth(o, cx, op == CmpOp::Ne)?));
}
(c, k) = (low(&c)?, low(&k)?);
y = n.a;
}
_ => break,
}
changed = true;
}
if !changed {
return Ok(None);
}
let w = c.width().bits();
let set = |i: u16| c.bit(i) == Some(true);
let lo = (0..w).take_while(|&i| !set(i)).count() as u16;
let len = (lo..w).take_while(|&i| set(i)).count() as u16;
if len > 0 && (lo + len..w).all(|i| !set(i)) {
let width = crate::Width::new(len).map_err(|e| Stop::Error(e.into()))?;
let k = k.extract(lo, width).map_err(|e| Stop::Error(e.into()))?;
let field = o.r.build(cx, |cx| cx.c_extract(y, lo, len))?;
return Ok(Some(compare(o, cx, op, field, &k)?));
}
let bits = o.r.build(cx, |cx| {
let c = cx.mk_const(&c)?;
cx.c_bin(BinOp::And, y, c)
})?;
Ok(Some(compare(o, cx, op, bits, &k)?))
}
fn flag(
cx: &mut Context,
o: &mut Calls<'_, '_, '_>,
op: CmpOp,
n: u32,
lhs: u32,
k: &BitVec,
) -> Result<Option<u32>, Stop> {
let w = k.width();
let one = *k == BitVec::one(w);
if w.bits() < 2 || !(one || k.is_zero()) {
return Ok(None);
}
let Some(f) = o.facts(cx, lhs)? else {
return Ok(None);
};
let high = BitVec::un_unchecked(crate::ops::UnOp::Not, &BitVec::one(w));
if BitVec::bin_unchecked(BinOp::And, &f.known.known_zero(), &high) != high {
return Ok(None);
}
let low = o.r.build(cx, |cx| cx.c_extract(lhs, 0, 1))?;
let low = narrowed(cx, o, low)?.unwrap_or(low);
let e = match (op == CmpOp::Eq) == one {
true => low,
false => o.r.build(cx, |cx| cx.c_un(crate::ops::UnOp::Not, low))?,
};
Ok(smaller(cx, e, n).then_some(e))
}
fn narrowed(cx: &mut Context, o: &mut Calls<'_, '_, '_>, s: u32) -> Result<Option<u32>, Stop> {
let node = cx.node(s);
if node.op != OpCode::Extract {
return Ok(None);
}
let Some((e, fin)) = super::casts::narrowed(o.r, cx, node.a, node.b as u16, node.width)? else {
return Ok(None);
};
o.fin = o.fin.and(fin);
Ok((e != s).then_some(e))
}
fn fits(cx: &mut Context, o: &mut Calls<'_, '_, '_>, i: u32) -> Result<u16, Stop> {
let w = cx.wid(i);
Ok(match o.facts(cx, i)? {
Some(f) => w - f.known().leading_known_zeros() as u16,
None => w,
})
}
fn fitted(
cx: &mut Context,
o: &mut Calls<'_, '_, '_>,
op: CmpOp,
n: u32,
a: u32,
b: u32,
) -> Result<Option<u32>, Stop> {
let w = cx.wid(a);
if w <= 1 {
return Ok(None);
}
let k = fits(cx, o, a)?.max(fits(cx, o, b)?).max(1);
if k >= w {
return Ok(None);
}
let Some((x, fx, mut atoms)) = super::casts::narrowed_from(o.r, cx, a, 0, k)? else {
return Ok(None);
};
let Some((y, fy, more)) = super::casts::narrowed_from(o.r, cx, b, 0, k)? else {
return Ok(None);
};
o.fin = o.fin.and(fx).and(fy);
atoms.extend(more);
atoms.sort_unstable();
atoms.dedup();
let op = match op {
CmpOp::Slt => CmpOp::Ult,
CmpOp::Sle => CmpOp::Ule,
op => op,
};
let e = o.r.build(cx, |cx| cx.c_cmp(op, x, y))?;
if e == n {
return Ok(None);
}
match super::ties_smaller(o.r, cx, n, e, &atoms)? {
Ok(()) => Ok(Some(e)),
Err(more) => {
o.fin = o.fin.and(more);
Ok(None)
}
}
}
fn smaller(cx: &Context, e: u32, n: u32) -> bool {
let size = |i: u32| cx.tree_size(cx.handle(i)).unwrap_or(u32::MAX);
size(e) < size(n)
}
fn truth(o: &mut Calls<'_, '_, '_>, cx: &mut Context, v: bool) -> Result<u32, Stop> {
o.r.build(cx, |cx| cx.mk_const(&BitVec::from_bool(v)))
}
fn compare(
o: &mut Calls<'_, '_, '_>,
cx: &mut Context,
op: CmpOp,
x: u32,
v: &BitVec,
) -> Result<u32, Stop> {
let v = *v;
o.r.build(cx, |cx| {
let k = cx.mk_const(&v)?;
cx.c_cmp(op, x, k)
})
}
fn leaves(
cx: &Context,
o: &mut Calls<'_, '_, '_>,
a: u32,
b: u32,
) -> Result<Option<(Vec<u32>, bool)>, Stop> {
let mut out = Vec::new();
let mut seen = false;
let mut stack = vec![b, a];
while let Some(i) = stack.pop() {
o.charge(1)?;
let node = cx.node(i);
if node.op == OpCode::Select {
seen = true;
stack.push(node.c);
stack.push(node.b);
} else if out.contains(&i) {
} else if out.len() >= MAX_SPLIT {
return Ok(None);
} else {
out.push(i);
}
}
Ok(Some((out, seen)))
}
fn relabel(
cx: &mut Context,
o: &mut Calls<'_, '_, '_>,
t: u32,
map: &IdMap<u32, u32>,
) -> Result<u32, Stop> {
if let Some(&x) = map.get(&t) {
return Ok(x);
}
let node = cx.node(t);
debug_assert_eq!(node.op, OpCode::Select);
let (c, p, q) = (node.a, node.b, node.c);
let p = relabel(cx, o, p, map)?;
let q = relabel(cx, o, q, map)?;
o.r.build(cx, |cx| cx.c_select(c, p, q))
}
fn relabelled(
cx: &mut Context,
o: &mut Calls<'_, '_, '_>,
a: u32,
b: u32,
leaves: &[u32],
inners: &[Inner],
) -> Result<(u32, u32), Stop> {
let mut map = IdMap::default();
for (&l, x) in leaves.iter().zip(inners) {
let x = match x {
Inner::Node(x) => *x,
Inner::Const(v) => {
let v = *v;
o.r.build(cx, |cx| cx.mk_const(&v))?
}
};
map.insert(l, x);
}
Ok((relabel(cx, o, a, &map)?, relabel(cx, o, b, &map)?))
}
fn cancel(
cx: &mut Context,
o: &mut Calls<'_, '_, '_>,
op: CmpOp,
a: u32,
b: u32,
) -> Result<Option<u32>, Stop> {
let (mut x, mut y) = (a, b);
let mut peeled = false;
while let Some((p, q)) = invert::cancel_layer(cx, o, x, y)? {
o.charge(1)?;
(x, y) = (p, q);
peeled = true;
}
if !peeled {
while let Some((ls, true)) = leaves(cx, o, x, y)? {
let Some(inners) = invert::cancel_leaves(cx, o, &ls)? else {
break;
};
(x, y) = relabelled(cx, o, x, y, &ls, &inners)?;
peeled = true;
}
}
if !peeled {
return Ok(None);
}
Ok(Some(o.r.build(cx, |cx| cx.c_cmp(op, x, y))?))
}
fn solve(
cx: &mut Context,
o: &mut Calls<'_, '_, '_>,
op: CmpOp,
lhs: u32,
c: &BitVec,
) -> Result<Option<u32>, Stop> {
let mut peels = Vec::new();
let explaining = o.r.explaining();
let solved = invert::solve_eq_peels(cx, o, lhs, c, explaining.then_some(&mut peels))?;
if explaining && solved.is_some() {
let layers = peels
.into_iter()
.map(|(node, l, preimage)| crate::engine::Peel {
node: cx.handle(node),
inner: cx.handle(l.inner),
map: l.map.spelling(),
bijective: l.kind == invert::Kind::Bijective,
preimage,
})
.collect();
o.r.explain_with(|| crate::engine::Explanation::Invert { layers });
}
Ok(match solved {
None => None,
Some(Solved::Const(eq)) => Some(truth(o, cx, eq == (op == CmpOp::Eq))?),
Some(Solved::Eq(x, v)) => Some(compare(o, cx, op, x, &v)?),
})
}
fn cancel_order(
cx: &mut Context,
o: &mut Calls<'_, '_, '_>,
op: CmpOp,
a: u32,
b: u32,
) -> Result<Option<u32>, Stop> {
let Some((mut order, strict)) = Order::of(op) else {
return Ok(None);
};
let (mut x, mut y) = (a, b);
let mut peeled = false;
while let Some((ls, _)) = leaves(cx, o, x, y)? {
let Some((inners, m)) = monotone::cancel_many(cx, o, &ls, order)? else {
break;
};
let (p, q) = relabelled(cx, o, x, y, &ls, &inners)?;
(x, y) = if m.increasing { (p, q) } else { (q, p) };
order = m.input;
peeled = true;
}
if !peeled {
return Ok(None);
}
Ok(Some(o.r.build(cx, |cx| cx.c_cmp(order.cmp(strict), x, y))?))
}
fn sign_bit(
cx: &mut Context,
o: &mut Calls<'_, '_, '_>,
op: CmpOp,
lhs: u32,
c: &BitVec,
const_left: bool,
) -> Result<Option<u32>, Stop> {
let negative = match (op, const_left) {
(CmpOp::Slt, false) if c.is_zero() => true,
(CmpOp::Sle, false) if c.is_ones() => true,
(CmpOp::Sle, true) if c.is_zero() => false,
(CmpOp::Slt, true) if c.is_ones() => false,
_ => return Ok(None),
};
let node = cx.node(lhs);
let w = u64::from(node.width);
let Some(k) = (matches!(node.op, OpCode::RotL | OpCode::RotR | OpCode::Shl))
.then(|| cx.const_val(node.b).and_then(|k| k.to_u64()))
.flatten()
else {
return Ok(None);
};
let bit = match node.op {
OpCode::Shl if k >= w => return Ok(None),
OpCode::RotR => (w - 1 + k % w) % w,
_ => (w - 1 + w - k % w) % w,
};
o.r.meter.charge(Counter::PassWork, 1)?;
let x = node.a;
Ok(Some(o.r.build(cx, |cx| {
let b = cx.c_extract(x, bit as u16, 1)?;
match negative {
true => Ok(b),
false => cx.c_un(crate::ops::UnOp::Not, b),
}
})?))
}
fn solve_order(
cx: &mut Context,
o: &mut Calls<'_, '_, '_>,
op: CmpOp,
lhs: u32,
c: &BitVec,
const_left: bool,
) -> Result<Option<u32>, Stop> {
Ok(match monotone::solve(cx, o, op, lhs, c, const_left)? {
None => None,
Some(monotone::Solved::Const(v)) => Some(truth(o, cx, v)?),
Some(monotone::Solved::Cmp {
op,
x,
t,
const_left,
}) => Some(o.r.build(cx, |cx| {
let t = cx.mk_const(&t)?;
if const_left {
cx.c_cmp(op, t, x)
} else {
cx.c_cmp(op, x, t)
}
})?),
})
}
fn split(
cx: &mut Context,
o: &mut Calls<'_, '_, '_>,
op: CmpOp,
n: u32,
lhs: u32,
c: &BitVec,
before: u32,
) -> Result<Option<u32>, Stop> {
let join = cx.node(lhs).op;
let mut leaves = Vec::new();
let mut stack = vec![lhs];
while let Some(i) = stack.pop() {
o.charge(1)?;
let node = cx.node(i);
if node.op == join {
stack.push(node.b);
stack.push(node.a);
} else if leaves.len() >= MAX_SPLIT {
return Ok(None);
} else {
leaves.push(i);
}
}
let eq = op == CmpOp::Eq;
let mut conj: Vec<(u32, BitVec)> = Vec::new();
let mut solved = false;
for leaf in leaves {
let (x, v) = match invert::solve_eq(cx, o, leaf, c)? {
Some(Solved::Const(false)) => return Ok(Some(truth(o, cx, !eq)?)),
Some(Solved::Const(true)) => {
solved = true;
continue;
}
Some(Solved::Eq(x, v)) => {
solved = true;
(x, v)
}
None => (leaf, *c),
};
match conj.iter().find(|(y, _)| *y == x) {
Some((_, w)) if *w != v => return Ok(Some(truth(o, cx, !eq)?)),
Some(_) => {}
None => conj.push((x, v)),
}
}
if !solved {
return Ok(None);
}
let mut out: Option<u32> = None;
for (x, v) in &conj {
let t = compare(o, cx, op, *x, v)?;
out = Some(match out {
None => t,
Some(acc) => {
let join = if eq { BinOp::And } else { BinOp::Or };
o.r.build(cx, |cx| cx.c_bin(join, acc, t))?
}
});
}
let e = match out {
Some(e) => e,
None => truth(o, cx, eq)?,
};
let tree = |i: u32| cx.meta[i as usize].tree;
if tree(n) == u32::MAX || tree(e) >= tree(n) {
discard(o.r, cx, before);
return Ok(None);
}
Ok(Some(e))
}