use super::{Fin, PassKind, Runner, Step, Stop, finish_within};
use crate::engine::budget::Counter;
use crate::expr::{Context, OpCode};
use crate::hash::IdMap;
use crate::ops::BinOp;
use crate::prove::{self, Outcome, Unknown};
use crate::{BitVec, SymbolKey, Width};
const MAX_CONE: usize = 512;
const MAX_PROOFS: usize = 2;
const MAX_AIG_NODES: usize = 1 << 15;
const SHARED_PROPAGATIONS: u64 = 1 << 14;
const ASKED_PROPAGATIONS: u64 = 1 << 17;
const _: () = assert!(SHARED_PROPAGATIONS <= ASKED_PROPAGATIONS);
const MAX_UNDECIDED: u32 = 8;
const PROPAGATION_RATE: u64 = 4;
const MIN_OWN: usize = 8;
#[derive(Clone, Copy)]
pub(super) struct Read {
pub n: u32,
pub s: u32,
pub lo: u16,
pub len: u16,
pub k: u16,
pub apart: bool,
}
fn count<'x>(r: &'x mut Runner<'_, '_>) -> &'x mut crate::engine::PassCounts {
r.stats.passes.entry(PassKind::Carries.name()).or_default()
}
fn word(op: OpCode) -> bool {
matches!(
op,
OpCode::Add
| OpCode::Sub
| OpCode::Mul
| OpCode::And
| OpCode::Or
| OpCode::Xor
| OpCode::Neg
| OpCode::Not
)
}
fn ones(bits: u16) -> u64 {
if bits >= 64 {
u64::MAX
} else {
(1 << bits) - 1
}
}
fn low(v: &BitVec) -> u64 {
v.limbs()[0]
}
struct Cone {
nodes: Vec<u32>,
offsets: Vec<u16>,
compares: bool,
}
fn cone(cx: &Context, n: u32) -> Cone {
let mut nodes = vec![n];
let mut seen = super::Lease::new(cx.len());
seen.insert(n, 0);
let mut cuts: Vec<u16> = Vec::new();
let mut compares = false;
let mut at = 0;
while at < nodes.len() && nodes.len() < MAX_CONE {
let i = nodes[at];
at += 1;
let node = cx.node(i);
compares |= node.op == OpCode::Ult
|| (node.op == OpCode::Extract
&& node.b > 0
&& matches!(cx.node(node.a).op, OpCode::Add | OpCode::Sub));
match node.op {
OpCode::Extract => {
cuts.extend([node.b as u16, node.b as u16 + node.width]);
}
OpCode::Shl | OpCode::LShr => {
if let Some(k) = cx.const_val(node.b).and_then(|k| k.to_u64()) {
cuts.extend(u16::try_from(k).ok());
}
}
OpCode::And if node.width <= 64 => {
for c in [node.a, node.b] {
if let Some(m) = cx.const_val(c).map(|m| m.limbs()[0]) {
let k = m.trailing_ones();
if k > 0 && k < u32::from(node.width) && m >> k == 0 {
cuts.push(k as u16);
}
}
}
}
_ => {}
}
for c in node.children() {
if !seen.insert(c, 0) {
nodes.push(c);
}
}
}
cuts.retain(|&k| k > 0 && k < 64);
cuts.sort_unstable();
cuts.dedup();
let mut offsets = cuts.clone();
for (x, &a) in cuts.iter().enumerate() {
offsets.extend(cuts[x..].iter().map(|&b| a + b).filter(|&k| k < 64));
}
offsets.sort_unstable();
offsets.dedup();
Cone {
nodes,
offsets,
compares,
}
}
fn holds_compare(cx: &Context, i: u32, memo: &mut super::Lease) -> bool {
if let Some(v) = memo.get(i) {
return v != 0;
}
memo.insert(i, 0);
let node = cx.node(i);
let v = node.op == OpCode::Ult || node.children().any(|c| holds_compare(cx, c, memo));
memo.insert(i, u32::from(v));
v
}
fn own(cx: &Context, cone: &Cone, below: &[u32]) -> (Vec<u32>, u64) {
let mut seen = super::Lease::new(cx.len());
let mut met = 0usize;
let mut stack = below.to_vec();
while let Some(i) = stack.pop() {
if met >= 4 * MAX_CONE {
break;
}
if !seen.insert(i, 0) {
met += 1;
stack.extend(cx.node(i).children());
}
}
let nodes = cone
.nodes
.iter()
.copied()
.filter(|i| {
matches!(
cx.node(*i).op,
OpCode::Add | OpCode::Sub | OpCode::Ult | OpCode::Eq
) && !seen.contains(*i)
})
.collect();
(nodes, (met + cone.nodes.len()) as u64)
}
fn opaque(cx: &Context, i: u32) -> bool {
let node = cx.node(i);
let shift = |c: u32| {
cx.const_val(c).is_some_and(|v| {
let v = v.limbs()[0] & ones(node.width.min(64));
let n = v.wrapping_neg() & ones(node.width.min(64));
v.is_power_of_two() || n.is_power_of_two()
})
};
match node.op {
OpCode::Mul => node.width > 64 || !(shift(node.a) || shift(node.b)),
OpCode::Shl | OpCode::LShr | OpCode::AShr => !cx.is_const(node.b),
_ => false,
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
struct Word {
a: u32,
with: Option<(BinOp, u32)>,
wide: bool,
k: u64,
}
impl Word {
fn node(a: u32) -> Self {
Word {
a,
with: None,
wide: false,
k: 0,
}
}
fn operands(&self) -> impl Iterator<Item = u32> {
core::iter::once(self.a).chain(self.with.map(|(_, b)| b))
}
fn value(&self, w: u16, x: u64, y: u64) -> u64 {
let v = match self.with {
None => x,
Some((BinOp::Sub, _)) => x.wrapping_sub(y),
Some(_) => x.wrapping_add(y),
};
v.wrapping_add(self.k) & ones(if self.wide { 64 } else { w })
}
fn build(&self, cx: &mut Context, a: u32, b: Option<u32>) -> Result<u32, crate::Error> {
let w = if self.wide { 64 } else { cx.wid(a) };
let mut e = cx.c_zext(a, w)?;
if let (Some((op, _)), Some(b)) = (self.with, b) {
let y = cx.c_zext(b, w)?;
e = cx.c_bin(op, e, y)?;
}
if self.k != 0 {
let k = cx.mk_const_u64(w, self.k)?;
e = cx.c_bin(BinOp::Add, e, k)?;
}
Ok(e)
}
}
type Asked = (Outcome, u64, u64, Vec<u32>);
fn asked(
cx: &Context,
(s, lo): (u32, u16),
(word, o): (&Word, u16),
len: u16,
uncut: Option<&IdMap<u32, ()>>,
propagations: u64,
) -> Result<Option<Asked>, crate::Error> {
let mut scx = Context::new();
let mut pre: Vec<(u32, u32)> = Vec::new();
if let Some(uncut) = uncut {
let mut seen = super::Lease::new(cx.len());
let mut stack: Vec<u32> = word.operands().skip(1).chain([word.a, s]).collect();
let mut key = 0u64;
while let Some(i) = stack.pop() {
if seen.insert(i, 0) {
continue;
}
if !opaque(cx, i) || uncut.contains_key(&i) {
stack.extend(cx.node(i).children());
continue;
}
let k = loop {
let k = SymbolKey::U64(key);
key += 1;
if cx.find_symbol(&k).is_none() {
break k;
}
};
let e = scx.symbol(k, cx.width_of(i))?;
pre.push((i, scx.id(e)?));
}
}
let roots: Vec<_> = core::iter::once(s)
.chain(word.operands())
.map(|i| cx.handle(i))
.collect();
let both = match scx.import_mapped(cx, &roots, &pre) {
Ok(both) => both,
Err(crate::Error::Unsupported(_)) => return Ok(None),
Err(e) => return Err(e),
};
let jw = Width::new(len)?;
let lhs = scx.extract(both[0], lo, jw)?;
let (a, b) = (
scx.id(both[1])?,
both.get(2).map(|&b| scx.id(b)).transpose()?,
);
let made = word.build(&mut scx, a, b)?;
let rhs = scx.extract(scx.handle(made), o, jw)?;
let cfg = prove::Config::default()
.with_simplify(false)
.with_certificate(false)
.with_samples(256)
.with_max_nodes(MAX_AIG_NODES)
.with_max_conflicts(u64::MAX)
.with_max_propagations(propagations.min(ASKED_PROPAGATIONS))
.with_carry_save_multiplication(true)
.with_xor3_encoding(true);
let grown = scx.len();
let cfg1 = cfg
.with_shared_sums(true)
.with_max_propagations(propagations.min(SHARED_PROPAGATIONS));
let mut q = prove::Question::equal(&mut scx, lhs, rhs, &cfg1)?;
let mut out = q.solve(&mut scx, cfg1.limits())?;
let mut early: Option<(usize, u64)> = None;
if let Outcome::Unknown(Unknown::Budget { .. }) = &out {
let rest = propagations - q.stats().propagations.min(propagations);
if rest != 0 && q.stats().rewritten {
early = Some((q.stats().nodes, q.stats().propagations));
let cfg2 = cfg.with_samples(0).with_max_propagations(rest);
q = prove::Question::equal(&mut scx, lhs, rhs, &cfg2)?;
out = q.solve(&mut scx, cfg2.limits())?;
} else if rest != 0 {
let limits = prove::Limits {
conflicts: u64::MAX,
propagations: rest,
};
out = q.solve(&mut scx, limits)?;
}
}
let grown = scx.len() - grown;
let mut stats = q.stats();
let mut nodes = match &out {
Outcome::Unknown(Unknown::TooLarge { nodes }) => *nodes,
_ => stats.nodes,
};
nodes += grown;
if let Some((n, p)) = early {
nodes += n;
stats.propagations += p;
}
Ok(Some((
out,
nodes as u64,
stats.propagations,
pre.into_iter().map(|(i, _)| i).collect(),
)))
}
enum Said {
Proved,
Refuted,
Undecided,
}
fn shape(cx: &Context, own: &[u32], lo: u16, o: u16, len: u16) -> u64 {
let mix = |h: u64, x: u64| {
let mut z = (h ^ x).wrapping_add(0x9e37_79b9_7f4a_7c15);
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
z ^ (z >> 31)
};
let sig = |i: u32| {
let node = cx.node(i);
let top = mix(node.op as u64, u64::from(node.width));
node.children().fold(top, |h, c| {
let kid = cx.node(c);
let v = cx.const_val(c).map_or(0, |v| v.limbs()[0]);
h.wrapping_add(mix(mix(kid.op as u64, u64::from(kid.width)), v))
})
};
let bits = u64::from(lo) << 32 | u64::from(o) << 16 | u64::from(len);
own.iter().fold(mix(bits, own.len() as u64), |h, &i| {
h.wrapping_add(mix(sig(i), 1))
})
}
#[allow(clippy::too_many_arguments)]
fn proved(
r: &mut Runner<'_, '_>,
cx: &Context,
cone: &Cone,
(s, lo): (u32, u16),
(word, o): (&Word, u16),
len: u16,
class: usize,
cap: u64,
) -> Result<Result<Said, Fin>, Stop> {
let (proofs, undecided) = r.carries.fits[class];
if undecided >= MAX_UNDECIDED + proofs {
return Ok(Err(Fin::PROVISIONAL));
}
let below: Vec<u32> = word.operands().collect();
let (own, walked) = own(cx, cone, &below);
r.meter.charge(Counter::PassWork, walked)?;
let hard = own
.iter()
.filter(|i| r.carries.hard.contains_key(i))
.count();
let shape = shape(cx, &own, lo, o, len);
if (own.len() >= MIN_OWN && 4 * hard >= 3 * own.len())
|| (2 * own.len() >= MIN_OWN && r.carries.shapes.contains_key(&shape))
{
return Ok(Ok(Said::Undecided));
}
let mut cut = true;
let mut failed: Vec<u32> = Vec::new();
loop {
let left = r.meter.left_in(|b| b.pass_work);
let propagations = cap.min(left.saturating_sub(MAX_AIG_NODES as u64) / PROPAGATION_RATE);
if propagations == 0 {
return Ok(Err(Fin::capped(crate::engine::Exhausted::PassWork)));
}
let Some((out, nodes, taken, fresh)) = asked(
cx,
(s, lo),
(word, o),
len,
cut.then_some(&r.carries.uncut),
propagations,
)
.map_err(Stop::Error)?
else {
return Ok(Ok(Said::Undecided));
};
let cost = nodes
.saturating_add(taken.saturating_mul(PROPAGATION_RATE))
.min(left);
r.meter.charge(Counter::PassWork, cost)?;
if !fresh.is_empty() && matches!(out, Outcome::Refuted(_)) {
cut = false;
failed = fresh;
continue;
}
if !matches!(out, Outcome::Refuted(_)) {
r.carries.uncut.extend(failed.drain(..).map(|i| (i, ())));
}
let c = count(r);
c.proofs += 1;
return Ok(match out {
Outcome::Proved(_) => {
c.proved += 1;
r.carries.fits[class].0 += 1;
Ok(Said::Proved)
}
Outcome::Refuted(_) => {
c.refuted += 1;
Ok(Said::Refuted)
}
Outcome::Unknown(Unknown::Budget { .. }) if propagations < cap => {
c.unknown += 1;
Err(Fin::capped(crate::engine::Exhausted::PassWork))
}
Outcome::Unknown(why) => {
c.unknown += 1;
if cap == ASKED_PROPAGATIONS {
r.carries.fits[class].1 += 1;
if why.is_budget() {
r.carries.shapes.insert(shape, ());
r.carries.hard.extend(own.into_iter().map(|i| (i, ())));
}
}
Ok(Said::Undecided)
}
});
}
}
pub(super) fn held(cx: &mut Context, e: u32, w: u16, k: u16) -> Result<u32, crate::Error> {
let e = cx.c_zext(e, w)?;
if k == 0 {
return Ok(e);
}
let by = cx.mk_const(&BitVec::wrapping_from_u64(Width::new(w)?, u64::from(k)))?;
cx.c_bin(BinOp::Shl, e, by)
}
#[derive(Clone, Copy)]
struct Fit {
compares: bool,
tree: u32,
b: u32,
o: u16,
}
const MADE_PER_UNIT: u64 = 4;
const MAX_MADE: usize = 1;
const MADE_PROPAGATIONS: u64 = 1 << 12;
const MIN_MADE: u16 = 4;
fn plus(cx: &Context, i: u32) -> Option<(u32, u64)> {
let node = cx.node(i);
if node.op != OpCode::Add || node.width > 64 {
return None;
}
match (cx.const_val(node.a), cx.const_val(node.b)) {
(None, Some(c)) => Some((node.a, low(&c))),
(Some(c), None) => Some((node.b, low(&c))),
_ => None,
}
}
fn constant(
z: impl Fn(usize) -> u64,
own: &[u64],
o: u16,
len: u16,
consts: &[u64],
) -> Option<u64> {
let mask = ones(len);
let d = |k: usize| own[k].wrapping_sub(z(k) >> o) & mask;
let (d2, d3) = (d(2), d(3));
let step = d2.wrapping_sub(d3) & mask;
if step != 0 && (o == 0 || consts.is_empty() || (step != 1 && step != mask)) {
return None;
}
if (0..own.len()).all(|k| d(k) == d2) {
return Some(d2 << o);
}
if o == 0 || consts.is_empty() {
return None;
}
let lows = ones(o);
'hi: for hi in [d2, d2.wrapping_sub(1) & mask] {
let up = hi.wrapping_add(1) & mask;
let (mut most, mut least) = (None::<u64>, None::<u64>);
for k in 0..own.len() {
let (x, l) = (d(k), z(k) & lows);
if x == hi {
most = Some(most.map_or(l, |m| m.max(l)));
} else if x == up {
least = Some(least.map_or(l, |m| m.min(l)));
} else {
continue 'hi;
}
}
let (Some(most), Some(least)) = (most, least) else {
continue;
};
if most >= least {
continue;
}
let (from, to) = (lows + 1 - least, lows - most);
let c = consts
.iter()
.map(|&c| c & lows)
.filter(|c| (from..=to).contains(c))
.min();
if let Some(c) = c {
return Some(hi << o | c);
}
}
None
}
fn made(
r: &Runner<'_, '_>,
cx: &Context,
cone: &Cone,
read: Read,
own: &[u64],
offsets: &[u16],
) -> (Vec<(Word, u16)>, u64) {
let Read { n, s, len, .. } = read;
let mut consts: Vec<u64> = Vec::new();
for &i in &cone.nodes {
let node = cx.node(i);
if node.width > 64 {
continue;
}
match node.op {
OpCode::Add => consts.extend(plus(cx, i).map(|(_, c)| c)),
OpCode::Sub => consts.extend(
cx.const_val(node.b)
.map(|c| low(&c).wrapping_neg() & ones(node.width)),
),
_ => {}
}
}
consts.sort_unstable();
consts.dedup();
let base = terms(cx, s).0;
let mut memo = super::Lease::new(cx.len());
let tree = |i: u32| cx.meta[i as usize].tree;
let mut found: Vec<(u32, Word, u16)> = Vec::new();
let mut work = 0u64;
for &b in &cone.nodes {
let node = cx.node(b);
let bw = node.width;
if b == n || !word(node.op) || bw > 64 {
continue;
}
let (x, k0) = terms(cx, b);
let narrow = (x != base).then_some(Word {
a: x,
with: None,
wide: false,
k: k0,
});
let wider = if bw == 64 {
None
} else if let Some((x, k0)) = plus(cx, b) {
Some(Word {
a: x,
with: None,
wide: true,
k: k0,
})
} else if matches!(node.op, OpCode::Add | OpCode::Sub) {
let op = if node.op == OpCode::Add {
BinOp::Add
} else {
BinOp::Sub
};
Some(Word {
a: node.a,
with: Some((op, node.b)),
wide: true,
k: 0,
})
} else {
None
};
let values = |w: Word| {
let vy = match w.with {
Some((_, y)) => Some(r.samples.get(&y)?),
None => None,
};
Some((w, r.samples.get(&w.a)?, vy))
};
let (narrow, wider) = (narrow.and_then(values), wider.and_then(values));
for &o in offsets {
if o >= bw || u32::from(o) + u32::from(len) > 64 {
continue;
}
let wide = o + len > bw;
let Some((mut w, va, vy)) = (if wide { wider } else { narrow }) else {
continue;
};
work += 1;
let z = |k: usize| w.value(bw, low(&va[k]), vy.map_or(0, |v| low(&v[k])));
let Some(c) = constant(z, own, o, len, &consts) else {
continue;
};
w.k = w.k.wrapping_add(c) & ones(if wide { 64 } else { bw });
let plain = !wide && (c == 0 || (o > 0 && (len < MIN_MADE || w.k & ones(o) == 0)));
if plain || (w.k == 0 && w.with.is_none()) {
continue;
}
if w.operands().any(|i| holds_compare(cx, i, &mut memo)) {
continue;
}
found.push((w.operands().map(tree).sum(), w, o));
}
}
found.sort_by(|x, y| {
(x.1.wide, x.0, x.1.with.is_some())
.cmp(&(y.1.wide, y.0, y.1.with.is_some()))
.then_with(|| cx.order(x.1.a, y.1.a))
.then_with(|| match (x.1.with, y.1.with) {
(Some((p, i)), Some((q, j))) => (p as u8).cmp(&(q as u8)).then(cx.order(i, j)),
_ => core::cmp::Ordering::Equal,
})
.then((x.2, x.1.k).cmp(&(y.2, y.1.k)))
});
found.dedup_by(|x, y| x.1 == y.1 && x.2 == y.2);
(found.into_iter().map(|f| (f.1, f.2)).collect(), work)
}
fn terms(cx: &Context, mut i: u32) -> (u32, u64) {
let mut k = 0u64;
while let Some((x, c)) = plus(cx, i) {
k = k.wrapping_add(c);
i = x;
}
(i, k)
}
pub(super) fn fitted(
r: &mut Runner<'_, '_>,
cx: &mut Context,
read: Read,
) -> Result<Result<Step, Fin>, Stop> {
let Read {
n,
s,
lo,
len,
k,
apart,
} = read;
let w = cx.wid(n);
let ws = cx.wid(s);
if len == 0
|| u32::from(lo) + u32::from(len) > u32::from(ws)
|| w > 64
|| ws > 64
|| r.carries.unfit.contains_key(&n)
{
return Ok(Err(Fin::FINAL));
}
if !r.late && r.carries.waiting.contains_key(&n) {
return Ok(Err(r.hold()));
}
let cone = cone(cx, s);
r.meter.charge(Counter::PassWork, cone.nodes.len() as u64)?;
if !cone.compares {
return Ok(Err(Fin::FINAL));
}
r.sample(cx, s)?;
let mask = ones(len);
let own: Vec<u64> = r.samples[&s].iter().map(|v| low(v) >> lo & mask).collect();
let direct = if n == s {
cx.node(n).children().collect::<Vec<_>>()
} else {
vec![s]
};
let mut offsets: Vec<u16> = core::iter::once(0)
.chain(cone.offsets.iter().copied())
.flat_map(|o| [o, o + lo])
.filter(|&o| o < 64)
.collect();
offsets.sort_unstable();
offsets.dedup();
let mut fits: Vec<Fit> = Vec::new();
let mut memo = super::Lease::new(cx.len());
for &b in &cone.nodes {
let bw = cx.wid(b);
if b == n || !word(cx.node(b).op) || bw > 64 {
continue;
}
let Some(of) = r.samples.get(&b) else {
continue;
};
for &o in &offsets {
if (o == lo && direct.contains(&b)) || u32::from(o) + u32::from(len) > u32::from(bw) {
continue;
}
if of
.iter()
.zip(&own)
.all(|(v, &x)| (low(v) >> o ^ x) & mask == 0)
{
let compares = holds_compare(cx, b, &mut memo);
let tree = cx.meta[b as usize].tree;
fits.push(Fit {
compares,
tree,
b,
o,
});
}
}
}
fits.sort_unstable_by(|x, y| {
(x.compares, x.tree)
.cmp(&(y.compares, y.tree))
.then_with(|| cx.order(x.b, y.b))
.then(x.o.cmp(&y.o))
});
let mut fin = Fin::FINAL;
let mut open = true;
for &Fit { b, o, .. } in fits.iter().take(MAX_PROOFS) {
let cap = ASKED_PROPAGATIONS;
match proved(
r,
cx,
&cone,
(s, lo),
(&Word::node(b), o),
len,
usize::from(apart),
cap,
)? {
Ok(Said::Proved) => {
let before = cx.len() as u32;
let e = r.build(cx, |cx| {
let e = cx.c_extract(b, o, len)?;
held(cx, e, w, k)
})?;
let step = finish_within(r, cx, PassKind::Carries, n, e, before, &[b], fin, 2)?;
return Ok(Ok(step));
}
Ok(Said::Refuted) => {}
Ok(Said::Undecided) => {
open = false;
break;
}
Err(more) => fin = fin.and(more),
}
}
let (proofs, undecided) = r.carries.fits[usize::from(apart)];
if open && undecided < MAX_UNDECIDED + proofs {
let (words, work) = made(r, cx, &cone, read, &own, &offsets);
r.meter
.charge(Counter::PassWork, work.div_ceil(MADE_PER_UNIT))?;
let words = if r.late {
words
} else {
if !words.is_empty() {
r.carries.waiting.insert(n, ());
fin = fin.and(r.hold());
}
Vec::new()
};
for (word, o) in words.into_iter().take(MAX_MADE) {
let cap = MADE_PROPAGATIONS;
match proved(
r,
cx,
&cone,
(s, lo),
(&word, o),
len,
usize::from(apart),
cap,
)? {
Ok(Said::Proved) => {
let before = cx.len() as u32;
let e = r.build(cx, |cx| {
let made = word.build(cx, word.a, word.with.map(|(_, b)| b))?;
let e = cx.c_extract(made, o, len)?;
held(cx, e, w, k)
})?;
let stops: Vec<u32> = word.operands().collect();
match finish_within(r, cx, PassKind::Carries, n, e, before, &stops, fin, 1)? {
Step::Normal(f) => fin = fin.and(f),
step => return Ok(Ok(step)),
}
}
Ok(Said::Refuted) => {}
Ok(Said::Undecided) => break,
Err(more) => fin = fin.and(more),
}
}
}
if fin.done {
r.carries.unfit.insert(n, ());
}
Ok(Err(fin))
}