use crate::Error;
use crate::expr::{Context, OpCode};
use crate::hash::IdMap;
use crate::ops::{BinOp, CmpOp, UnOp};
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
struct Fact {
x: u32,
mask: u64,
value: u64,
}
const MAX_SITES: usize = 512;
fn ones(cx: &Context, i: u32) -> Option<u64> {
let w = cx.wid(i);
(w <= 64).then(|| u64::MAX >> (64 - u32::from(w)))
}
fn fixes(cx: &Context, c: u32, want: bool, out: &mut Vec<Fact>, depth: u32) {
if depth > 16 || cx.wid(c) != 1 || cx.is_const(c) {
return;
}
let n = cx.node(c);
match n.op {
OpCode::Not => fixes(cx, n.a, !want, out, depth + 1),
OpCode::And if want => {
fixes(cx, n.a, true, out, depth + 1);
fixes(cx, n.b, true, out, depth + 1);
}
OpCode::Or if !want => {
fixes(cx, n.a, false, out, depth + 1);
fixes(cx, n.b, false, out, depth + 1);
}
OpCode::Eq | OpCode::Ne => {
out.push(Fact {
x: c,
mask: 1,
value: u64::from(want),
});
if (n.op == OpCode::Eq) != want {
return;
}
let (x, k) = match (cx.const_val(n.a), cx.const_val(n.b)) {
(None, Some(k)) => (n.a, k),
(Some(k), None) => (n.b, k),
_ => return,
};
if let (Some(k), Some(all)) = (k.to_u64(), ones(cx, x)) {
masked(cx, x, all, k, out, depth + 1);
}
}
_ => out.push(Fact {
x: c,
mask: 1,
value: u64::from(want),
}),
}
}
fn masked(cx: &Context, x: u32, mask: u64, value: u64, out: &mut Vec<Fact>, depth: u32) {
if mask == 0 || value & !mask != 0 || cx.is_const(x) {
return;
}
let n = cx.node(x);
let narrow = |src: u32, by: u16| -> Option<(u64, u64)> {
let all = ones(cx, src)?;
let m = mask.checked_shl(u32::from(by))?;
(m & all == m && m >> by == mask).then(|| (m, value << by))
};
if depth < 16 {
match n.op {
OpCode::LShr | OpCode::Extract => {
let by = match n.op {
OpCode::Extract => Some(n.b as u16),
_ => cx.const_val(n.b).and_then(|k| k.to_u64()).map(|k| k as u16),
};
if let Some((m, v)) = by.and_then(|by| narrow(n.a, by)) {
return masked(cx, n.a, m, v, out, depth + 1);
}
}
OpCode::Zext => {
if let Some(inner) = ones(cx, n.a)
&& value & !inner == 0
{
return masked(cx, n.a, mask & inner, value, out, depth + 1);
}
}
OpCode::And => {
let k = cx.const_val(n.b).or_else(|| cx.const_val(n.a));
let y = if cx.is_const(n.b) { n.a } else { n.b };
if let Some(k) = k.and_then(|k| k.to_u64()) {
return masked(cx, y, mask & k, value & k, out, depth + 1);
}
}
_ => {}
}
}
out.push(Fact { x, mask, value });
}
fn put(cx: &mut Context, e: u32, facts: &[Fact]) -> Result<u32, Error> {
if facts.is_empty() {
return Ok(e);
}
let mut merged: Vec<Fact> = Vec::new();
for f in facts {
match merged.iter_mut().find(|m| m.x == f.x) {
Some(m) if (m.value ^ f.value) & m.mask & f.mask != 0 => return Ok(e),
Some(m) => {
m.value |= f.value;
m.mask |= f.mask;
}
None => merged.push(*f),
}
}
let mut more = Vec::new();
for f in &merged {
let n = cx.node(f.x);
if f.mask == 1 && n.width == 1 && matches!(n.op, OpCode::Eq | OpCode::Ne) {
let other = if n.op == OpCode::Eq {
CmpOp::Ne
} else {
CmpOp::Eq
};
let c = cx.c_cmp(other, n.a, n.b)?;
if c != f.x && !merged.iter().any(|m| m.x == c) && cx.wid(c) == 1 && !cx.is_const(c) {
more.push(Fact {
x: c,
mask: 1,
value: f.value ^ 1,
});
}
}
}
merged.extend(more);
let mut repl: IdMap<u32, u32> = IdMap::default();
for f in merged {
let w = cx.wid(f.x);
let Some(all) = ones(cx, f.x) else { continue };
let v = cx.mk_const_u64(w, f.value)?;
let r = if f.mask == all {
v
} else {
let keep = cx.mk_const_u64(w, all & !f.mask)?;
let rest = cx.c_bin(BinOp::And, f.x, keep)?;
cx.c_bin(BinOp::Or, rest, v)?
};
repl.insert(f.x, r);
}
Ok(cx.substitute_ids(&[e], &repl)?[0])
}
pub(super) fn push(cx: &mut Context, root: u32, max_new: u32) -> Result<Option<u32>, Error> {
let start = cx.len() as u32;
let order = cx.post_order_ids(&[root]);
let mut pushed: IdMap<u32, u32> = IdMap::default();
let mut sites = 0usize;
for i in order {
if cx.len() as u32 - start > max_new {
return Ok(None);
}
let n = cx.node(i);
let now = |cx: &mut Context, pushed: &IdMap<u32, u32>, e: u32| -> Result<u32, Error> {
Ok(cx.substitute_ids(&[e], pushed)?[0])
};
let new = match n.op {
OpCode::And if n.width == 1 => {
let (mut fa, mut fb) = (Vec::new(), Vec::new());
fixes(cx, n.a, true, &mut fa, 0);
fixes(cx, n.b, true, &mut fb, 0);
if fa.is_empty() && fb.is_empty() {
continue;
}
let (a, b) = (now(cx, &pushed, n.a)?, now(cx, &pushed, n.b)?);
let b2 = put(cx, b, &fa)?;
if b2 != b {
cx.c_bin(BinOp::And, a, b2)?
} else {
let a2 = put(cx, a, &fb)?;
if a2 == a {
continue;
}
cx.c_bin(BinOp::And, a2, b)?
}
}
OpCode::Select => {
let (mut ft, mut ff) = (Vec::new(), Vec::new());
fixes(cx, n.a, true, &mut ft, 0);
fixes(cx, n.a, false, &mut ff, 0);
if ft.is_empty() && ff.is_empty() {
continue;
}
let c = now(cx, &pushed, n.a)?;
let (t, f) = (now(cx, &pushed, n.b)?, now(cx, &pushed, n.c)?);
let (t2, f2) = (put(cx, t, &ft)?, put(cx, f, &ff)?);
if (t2, f2) == (t, f) {
continue;
}
cx.c_select(c, t2, f2)?
}
OpCode::Mul => {
let zext_of = |e: u32| {
let m = cx.node(e);
(m.op == OpCode::Zext && cx.wid(m.a) == 1).then_some(m.a)
};
let (c, t) = match (zext_of(n.a), zext_of(n.b)) {
(Some(c), _) => (c, n.b),
(None, Some(c)) => (c, n.a),
_ => continue,
};
let mut fc = Vec::new();
fixes(cx, c, true, &mut fc, 0);
if fc.is_empty() {
continue;
}
let t1 = now(cx, &pushed, t)?;
let t2 = put(cx, t1, &fc)?;
if t2 == t1 {
continue;
}
let z = if t == n.b { n.a } else { n.b };
let z = now(cx, &pushed, z)?;
cx.c_bin(BinOp::Mul, z, t2)?
}
_ => continue,
};
pushed.insert(i, new);
sites += 1;
if sites >= MAX_SITES {
break;
}
}
if pushed.is_empty() {
return Ok(None);
}
let r = cx.substitute_ids(&[root], &pushed)?[0];
Ok((r != root).then_some(r))
}
fn most_tested(cx: &mut Context, root: u32) -> Result<Option<u32>, Error> {
let order = cx.post_order_ids(&[root]);
let mut uses: IdMap<u32, u32> = IdMap::default();
for &i in &order {
let n = cx.node(i);
let c = match n.op {
OpCode::Select => n.a,
OpCode::Zext if cx.wid(n.a) == 1 => n.a,
_ => continue,
};
if cx.is_const(c) {
continue;
}
let c = match cx.node(c).op.as_cmp() {
Some(_) => c.min(cx.c_un(UnOp::Not, c)?),
None => c,
};
*uses.entry(c).or_default() += 1;
}
Ok(uses
.into_iter()
.filter(|&(_, k)| k >= 2)
.max_by_key(|&(c, k)| (k, std::cmp::Reverse(c)))
.map(|(c, _)| c))
}
pub(super) fn sides(cx: &mut Context, root: u32) -> Result<Option<(u32, u32, u32)>, Error> {
let Some(c) = most_tested(cx, root)? else {
return Ok(None);
};
let (mut ft, mut ff) = (Vec::new(), Vec::new());
fixes(cx, c, true, &mut ft, 0);
fixes(cx, c, false, &mut ff, 0);
let (t, f) = (put(cx, root, &ft)?, put(cx, root, &ff)?);
Ok((t != root || f != root).then_some((c, t, f)))
}
const MAX_CASES: usize = 2;
#[derive(Clone, Debug, PartialEq, Eq)]
enum Dep {
Open,
Cond(u32),
Of(Vec<u32>),
}
impl Dep {
fn vars(&self) -> Option<&[u32]> {
match self {
Dep::Open => None,
Dep::Cond(v) => Some(std::slice::from_ref(v)),
Dep::Of(s) => Some(s),
}
}
}
pub(super) fn cut(cx: &mut Context, root: u32, fuel: u64) -> Result<Option<u32>, Error> {
let order = cx.post_order_ids(&[root]);
let mut dep: IdMap<u32, Dep> = IdMap::default();
let mut other: IdMap<u32, u32> = IdMap::default();
let mut var_of: IdMap<u32, u32> = IdMap::default();
for &i in &order {
let n = cx.node(i);
if cx.is_const(i) {
dep.insert(i, Dep::Of(Vec::new()));
continue;
}
let mut d = if n.op == OpCode::Sym || n.op as u8 > OpCode::Select as u8 {
None
} else {
Some(Vec::new())
};
for c in n.children() {
match (&mut d, dep[&c].vars()) {
(Some(s), Some(t)) => {
for &v in t {
if let Err(at) = s.binary_search(&v) {
s.insert(at, v);
}
}
if s.len() > MAX_CASES {
d = None;
}
}
_ => d = None,
}
}
let d = match d {
Some(s) => Dep::Of(s),
None if n.width == 1 => match var_of.get(&i) {
Some(&v) => Dep::Cond(v),
None => {
if n.op.as_cmp().is_some() {
let not = cx.c_un(UnOp::Not, i)?;
if not != i {
other.insert(i, not);
var_of.insert(not, i);
}
}
Dep::Cond(i)
}
},
None => Dep::Open,
};
dep.insert(i, d);
}
let piece = |dep: &IdMap<u32, Dep>, i: u32| matches!(&dep[&i], Dep::Of(s) if !s.is_empty());
let mut outer: Vec<u32> = Vec::new();
for &i in &order {
if piece(&dep, i) {
continue;
}
for c in cx.node(i).children() {
if piece(&dep, c) && !outer.contains(&c) {
outer.push(c);
}
}
}
if piece(&dep, root) {
outer.push(root);
}
let mut groups: Vec<(Vec<u32>, Vec<u32>)> = Vec::new();
for &i in &outer {
let Dep::Of(s) = &dep[&i] else { continue };
match groups.iter_mut().find(|(g, _)| g == s) {
Some((_, ps)) => ps.push(i),
None => groups.push((s.clone(), vec![i])),
}
}
let mut repl: IdMap<u32, u32> = IdMap::default();
let mut walked = 0u64;
for (vars, pieces) in groups {
let cases = 1usize << vars.len();
let inner = interior(cx, &dep, &pieces);
let size: usize = inner.iter().map(|&(n, _)| n).sum();
walked += (size * cases) as u64;
if walked > fuel {
break;
}
let (pieces, noisy): (Vec<u32>, Vec<bool>) = pieces
.into_iter()
.zip(inner)
.filter(|&(_, (n, _))| n >= cases + 2)
.map(|(p, (_, noisy))| (p, noisy))
.unzip();
if pieces.is_empty() {
continue;
}
let mut values: Vec<Vec<u32>> = Vec::with_capacity(cases);
let (zero, one) = (cx.mk_const_u64(1, 0)?, cx.mk_const_u64(1, 1)?);
for case in 0..cases {
let mut at: IdMap<u32, u32> = IdMap::default();
for (j, &v) in vars.iter().enumerate() {
let set = case >> j & 1 == 1;
at.insert(v, if set { one } else { zero });
if let Some(&o) = other.get(&v) {
at.insert(o, if set { zero } else { one });
}
}
values.push(cx.substitute_ids(&pieces, &at)?);
}
for (k, &p) in pieces.iter().enumerate() {
if values.iter().any(|vs| !cx.is_const(vs[k])) {
continue;
}
if !noisy[k] && values.iter().any(|vs| vs[k] != values[0][k]) {
continue;
}
let t = table(cx, &vars, |case| values[case][k], 0, 0)?;
if t != p {
repl.insert(p, t);
}
}
}
if repl.is_empty() {
return Ok(None);
}
let r = cx.substitute_ids(&[root], &repl)?[0];
Ok((r != root).then_some(r))
}
fn interior(cx: &Context, dep: &IdMap<u32, Dep>, pieces: &[u32]) -> Vec<(usize, bool)> {
let mut seen: IdMap<u32, ()> = IdMap::default();
pieces
.iter()
.map(|&p| {
seen.clear();
let mut noisy = false;
let mut stack = vec![p];
while let Some(i) = stack.pop() {
if cx.is_const(i)
|| !matches!(dep.get(&i), Some(Dep::Of(_)))
|| seen.insert(i, ()).is_some()
{
continue;
}
let n = cx.node(i);
noisy |= match n.op {
OpCode::Not
| OpCode::And
| OpCode::Or
| OpCode::Xor
| OpCode::Zext
| OpCode::Sext
| OpCode::Extract
| OpCode::Concat
| OpCode::Select => false,
OpCode::Shl | OpCode::LShr => !cx.is_const(n.b),
op => op.as_cmp().is_none(),
};
stack.extend(n.children());
}
(seen.len(), noisy)
})
.collect()
}
fn table(
cx: &mut Context,
vars: &[u32],
value: impl Fn(usize) -> u32 + Copy,
j: usize,
case: usize,
) -> Result<u32, Error> {
if j == vars.len() {
return Ok(value(case));
}
let set = table(cx, vars, value, j + 1, case | 1 << j)?;
let unset = table(cx, vars, value, j + 1, case)?;
cx.c_select(vars[j], set, unset)
}