use std::sync::OnceLock;
use super::{Fin, PassKind, Runner, Step, Stop, finish, worth_building};
use crate::BitVec;
use crate::engine::budget::Counter;
use crate::expr::{Context, OpCode};
use crate::ops::{BinOp, UnOp};
const VARS: [u8; 3] = [0xAA, 0xCC, 0xF0];
const WIDE: usize = 6;
const WIDE_VARS: [u64; WIDE] = [
0xAAAA_AAAA_AAAA_AAAA,
0xCCCC_CCCC_CCCC_CCCC,
0xF0F0_F0F0_F0F0_F0F0,
0xFF00_FF00_FF00_FF00,
0xFFFF_0000_FFFF_0000,
0xFFFF_FFFF_0000_0000,
];
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub(crate) enum T {
Var(u8),
Zero,
Ones,
Not(u16),
Bin(BinOp, u16, u16),
}
pub(crate) struct MinForms {
pub(crate) forms: Vec<(Vec<T>, u8)>,
#[cfg_attr(not(feature = "mba"), allow(dead_code))]
pub(crate) alts: Vec<Vec<Vec<T>>>,
}
pub(crate) const ALTERNATIVES: usize = 8;
pub(crate) fn min_forms() -> &'static MinForms {
static FORMS: OnceLock<MinForms> = OnceLock::new();
FORMS.get_or_init(search)
}
fn search() -> MinForms {
let mut best: Vec<Option<(Vec<T>, u8)>> = vec![None; 256];
let mut alts: Vec<Vec<Vec<T>>> = vec![Vec::new(); 256];
let mut covered: Vec<Vec<u8>> = vec![Vec::new(); 256];
best[0x00] = Some((vec![T::Zero], 0));
best[0xFF] = Some((vec![T::Ones], 0));
for (k, &v) in VARS.iter().enumerate() {
best[v as usize] = Some((vec![T::Var(k as u8)], 0));
}
let concat = |a: &[T], b: &[T], op: BinOp| -> Vec<T> {
let off = a.len() as u16;
let mut out = a.to_vec();
out.extend(b.iter().map(|t| match *t {
T::Not(x) => T::Not(x + off),
T::Bin(o, x, y) => T::Bin(o, x + off, y + off),
other => other,
}));
out.push(T::Bin(op, off - 1, out.len() as u16 - 1));
out
};
let mut size = 1u8;
while best.iter().any(Option::is_none) {
let mut found: Vec<(usize, Vec<T>)> = Vec::new();
for f in 0..256usize {
let Some((tf, sf)) = &best[f] else { continue };
if *sf + 1 == size {
let mut t = tf.clone();
t.push(T::Not(t.len() as u16 - 1));
found.push((!(f as u8) as usize, t));
}
for (g, bg) in best.iter().enumerate().skip(f) {
let Some((tg, sg)) = bg else { continue };
if sf + sg + 1 != size {
continue;
}
for (op, v) in [(BinOp::And, f & g), (BinOp::Or, f | g), (BinOp::Xor, f ^ g)] {
found.push((v, concat(tf, tg, op)));
}
}
}
let fresh: Vec<bool> = best.iter().map(Option::is_none).collect();
let all = |f: usize| -> Vec<&Vec<T>> {
best[f]
.iter()
.map(|(t, _)| t)
.chain(alts[f].iter())
.collect()
};
let mut more: Vec<(usize, Vec<T>)> = Vec::new();
for f in 0..256usize {
let Some((_, sf)) = &best[f] else { continue };
if *sf + 1 == size && fresh[usize::from(!(f as u8))] {
for tf in all(f).into_iter().skip(1) {
let mut t = tf.clone();
t.push(T::Not(t.len() as u16 - 1));
more.push((usize::from(!(f as u8)), t));
}
}
for (g, bg) in best.iter().enumerate().skip(f) {
let Some((_, sg)) = bg else { continue };
if sf + sg + 1 != size {
continue;
}
for (op, v) in [(BinOp::And, f & g), (BinOp::Or, f | g), (BinOp::Xor, f ^ g)] {
if !fresh[v] {
continue;
}
for (i, tf) in all(f).into_iter().enumerate() {
for (j, tg) in all(g).into_iter().enumerate() {
if i > 0 || j > 0 {
more.push((v, concat(tf, tg, op)));
}
}
}
}
}
}
found.extend(more);
for (v, t) in found {
if best[v].is_none() {
covered[v] = subtables(&t);
best[v] = Some((t, size));
} else if fresh[v] && alts[v].len() < 2 * ALTERNATIVES && !alts[v].contains(&t) {
let subs = subtables(&t);
let new = subs.iter().any(|s| !covered[v].contains(s));
if alts[v].len() < ALTERNATIVES && best[v].as_ref().is_some_and(|(b, _)| *b != t)
|| new
{
covered[v].extend(subs);
alts[v].push(t);
}
}
}
size += 1;
}
MinForms {
forms: best
.into_iter()
.map(|b| b.unwrap_or((vec![T::Zero], 0)))
.collect(),
alts,
}
}
pub(crate) fn subtables(t: &[T]) -> Vec<u8> {
let mut vals: Vec<u8> = Vec::with_capacity(t.len());
for n in t {
vals.push(match *n {
T::Var(k) => VARS[usize::from(k)],
T::Zero => 0,
T::Ones => 0xFF,
T::Not(a) => !vals[usize::from(a)],
T::Bin(op, a, b) => {
let (x, y) = (vals[usize::from(a)], vals[usize::from(b)]);
match op {
BinOp::And => x & y,
BinOp::Or => x | y,
_ => x ^ y,
}
}
});
}
let mut out: Vec<u8> = t
.iter()
.zip(&vals)
.take(t.len().saturating_sub(1))
.filter(|(n, _)| matches!(n, T::Not(_) | T::Bin(..)))
.map(|(_, &v)| v)
.collect();
out.sort_unstable();
out.dedup();
out
}
pub(crate) type Info = Option<(Vec<u32>, u8)>;
#[derive(Clone, Copy, Debug)]
pub(crate) struct Wide {
atoms: [u32; WIDE],
len: u8,
tt: u64,
}
impl Wide {
fn atoms(&self) -> &[u32] {
&self.atoms[..usize::from(self.len)]
}
}
fn prune(atoms: Vec<u32>, tt: u8) -> (Vec<u32>, u8) {
let mut keep: Vec<u32> = Vec::new();
for (k, &a) in atoms.iter().enumerate() {
let flip = |i: usize| (tt >> (i ^ (1 << k))) & 1 != (tt >> i) & 1;
if (0..8).any(flip) {
keep.push(a);
}
}
let tt = remap_down(tt, &atoms, &keep);
(keep, tt)
}
fn remap_down(tt: u8, from: &[u32], to: &[u32]) -> u8 {
let mut out = 0u8;
for i in 0..8usize {
let mut j = 0usize;
for (k, a) in to.iter().enumerate() {
let p = from.iter().position(|b| b == a).unwrap_or(0);
j |= ((i >> k) & 1) << p;
}
out |= ((tt >> j) & 1) << i;
}
out
}
fn remap(tt: u8, from: &[u32], to: &[u32]) -> u8 {
let pos: Vec<usize> = from
.iter()
.map(|a| to.iter().position(|b| b == a).unwrap_or(0))
.collect();
let mut out = 0u8;
for i in 0..8usize {
let mut j = 0usize;
for (k, &p) in pos.iter().enumerate() {
j |= ((i >> p) & 1) << k;
}
out |= ((tt >> j) & 1) << i;
}
out
}
fn bitwise_op(op: OpCode) -> bool {
matches!(op, OpCode::And | OpCode::Or | OpCode::Xor | OpCode::Not)
}
fn info_of(r: &mut Runner<'_, '_>, cx: &Context, root: u32) -> Result<Info, Stop> {
let mut stack: Vec<(u32, bool)> = vec![(root, false)];
while let Some((i, expanded)) = stack.pop() {
if r.bitwise.info.contains_key(&i) {
continue;
}
let node = cx.node(i);
let leaf = |i: u32| -> Info {
match cx.const_val(i) {
Some(v) if v.is_zero() => Some((Vec::new(), 0x00)),
Some(v) if v.is_ones() => Some((Vec::new(), 0xFF)),
_ => Some((vec![i], VARS[0])),
}
};
if !bitwise_op(node.op) {
r.bitwise.info.insert(i, leaf(i));
continue;
}
if !expanded {
stack.push((i, true));
for c in node.children() {
if !r.bitwise.info.contains_key(&c) {
stack.push((c, false));
}
}
continue;
}
r.meter.charge(Counter::PassWork, 1)?;
let kids: Vec<Info> = node
.children()
.map(|c| r.bitwise.info[&c].clone())
.collect();
let info = if kids.iter().any(Option::is_none) {
None
} else {
let mut atoms: Vec<u32> = kids
.iter()
.flat_map(|k| k.as_ref().map_or(Vec::new(), |k| k.0.clone()))
.collect();
atoms.sort_unstable();
atoms.dedup();
if atoms.len() > 3 {
None
} else {
let t: Vec<u8> = kids
.iter()
.map(|k| {
let (a, tt) = k.as_ref().map_or((&[][..], 0), |k| (&k.0[..], k.1));
remap(tt, a, &atoms)
})
.collect();
let tt = match node.op {
OpCode::Not => !t[0],
OpCode::And => t[0] & t[1],
OpCode::Or => t[0] | t[1],
_ => t[0] ^ t[1],
};
Some(prune(atoms, tt))
}
};
let info = if info.is_none() {
r.stats.passes.entry("bitwise").or_default().atomized += 1;
leaf(i)
} else {
info
};
r.bitwise.info.insert(i, info);
}
Ok(r.bitwise.info[&root].clone())
}
fn swap_vars(tt: u64, a: usize, b: usize) -> u64 {
let d = (1u32 << b) - (1u32 << a);
let t = ((tt >> d) ^ tt) & WIDE_VARS[a] & !WIDE_VARS[b];
tt ^ t ^ (t << d)
}
fn remap_wide(tt: u64, from: &[u32], to: &[u32]) -> u64 {
let mut tt = tt;
let mut p = to.len();
for (k, a) in from.iter().enumerate().rev() {
while to[p - 1] != *a {
p -= 1;
}
p -= 1;
if p > k {
tt = swap_vars(tt, k, p);
}
}
tt
}
fn prune_wide(atoms: &[u32], tt: u64) -> Wide {
let mut out = Wide {
atoms: [0; WIDE],
len: 0,
tt,
};
for (k, &a) in atoms.iter().enumerate() {
let (v, s) = (WIDE_VARS[k], 1u32 << k);
if (tt & v) >> s | (tt & !v) << s == tt {
continue;
}
let m = usize::from(out.len);
if m < k {
out.tt = swap_vars(out.tt, m, k);
}
out.atoms[m] = a;
out.len += 1;
}
out
}
fn wide_leaf(cx: &Context, i: u32) -> Wide {
let mut w = Wide {
atoms: [0; WIDE],
len: 0,
tt: 0,
};
match cx.const_val(i) {
Some(v) if v.is_zero() => {}
Some(v) if v.is_ones() => w.tt = u64::MAX,
_ => (w.atoms[0], w.len, w.tt) = (i, 1, WIDE_VARS[0]),
}
w
}
fn wide_op(cx: &Context, i: u32, a: Wide, b: Wide) -> Wide {
let mut atoms = [0u32; 2 * WIDE];
let (mut n, mut x, mut y) = (0, a.atoms().iter().peekable(), b.atoms().iter().peekable());
while let Some(&next) = match (x.peek(), y.peek()) {
(Some(&&p), Some(&&q)) if p == q => {
y.next();
x.next()
}
(Some(&&p), Some(&&q)) if q < p => y.next(),
(Some(_), _) => x.next(),
(None, _) => y.next(),
} {
atoms[n] = next;
n += 1;
}
if n > WIDE {
return wide_leaf(cx, i);
}
let atoms = &atoms[..n];
let (ta, tb) = (
remap_wide(a.tt, a.atoms(), atoms),
remap_wide(b.tt, b.atoms(), atoms),
);
let tt = match cx.node(i).op {
OpCode::Not => !ta,
OpCode::And => ta & tb,
OpCode::Or => ta | tb,
_ => ta ^ tb,
};
prune_wide(atoms, tt)
}
fn known_wide(r: &Runner<'_, '_>, cx: &Context, i: u32) -> Option<Wide> {
if !bitwise_op(cx.node(i).op) {
return Some(wide_leaf(cx, i));
}
if let Some(&w) = r.bitwise.wide.get(&i) {
return Some(w);
}
match r.bitwise.info.get(&i) {
Some(Some((atoms, tt)))
if atoms[..] != [i] && atoms.iter().all(|&a| !bitwise_op(cx.node(a).op)) =>
{
let mut w = Wide {
atoms: [0; WIDE],
len: atoms.len() as u8,
tt: u64::from(*tt) * 0x0101_0101_0101_0101,
};
w.atoms[..atoms.len()].copy_from_slice(atoms);
Some(w)
}
_ => None,
}
}
fn wide_of(r: &mut Runner<'_, '_>, cx: &Context, root: u32) -> Result<Wide, Stop> {
if let Some(w) = known_wide(r, cx, root) {
return Ok(w);
}
let mut stack: Vec<(u32, bool)> = vec![(root, false)];
while let Some((i, expanded)) = stack.pop() {
if r.bitwise.wide.contains_key(&i) {
continue;
}
let node = cx.node(i);
if !expanded {
stack.push((i, true));
for c in node.children() {
if known_wide(r, cx, c).is_none() {
stack.push((c, false));
}
}
continue;
}
r.meter.charge(Counter::PassWork, 1)?;
let known = |c: u32| known_wide(r, cx, c).expect("operands come first");
let a = known(node.a);
let b = if node.op == OpCode::Not {
a
} else {
known(node.b)
};
r.bitwise.wide.insert(i, wide_op(cx, i, a, b));
}
Ok(r.bitwise.wide[&root])
}
pub(super) fn emit(
r: &mut Runner<'_, '_>,
cx: &mut Context,
tt: u8,
atoms: &[u32],
) -> Result<u32, Stop> {
let (tmpl, _) = &min_forms().forms[tt as usize];
let w = cx.width_of(atoms.first().copied().unwrap_or(0));
let mut built: Vec<u32> = Vec::with_capacity(tmpl.len());
for t in tmpl {
r.meter.charge(Counter::PassWork, 1)?;
let id = match *t {
T::Var(k) => atoms[k as usize],
T::Zero => r.build(cx, |cx| cx.mk_const(&crate::BitVec::zero(w)))?,
T::Ones => r.build(cx, |cx| cx.mk_const(&crate::BitVec::ones(w)))?,
T::Not(a) => {
let a = built[a as usize];
r.build(cx, |cx| cx.c_un(UnOp::Not, a))?
}
T::Bin(op, a, b) => {
let (a, b) = (built[a as usize], built[b as usize]);
r.build(cx, |cx| cx.c_bin(op, a, b))?
}
};
built.push(id);
}
r.meter.check()?;
Ok(*built.last().unwrap_or(&atoms[0]))
}
const MAX_MASKS: usize = 3;
const MAX_MASKED_REGION: usize = 32;
pub(crate) struct Masked {
atoms: Vec<u32>,
consts: Vec<u32>,
classes: Vec<(BitVec, Vec<u8>)>,
ops: u32,
}
impl Masked {
pub(crate) fn atoms_classes(&self) -> (&[u32], impl Iterator<Item = (&BitVec, u8)>) {
(&self.atoms, self.classes.iter().map(|(m, t)| (m, t[0])))
}
}
pub(in crate::engine) fn masked(
r: &mut Runner<'_, '_>,
cx: &Context,
roots: &[u32],
) -> Result<Option<Masked>, Stop> {
#[derive(Clone, Copy)]
enum Slot {
Atom(usize),
Const(usize),
Op(OpCode, usize, usize),
}
let mut ids = [0u32; MAX_MASKED_REGION];
let mut slots = [Slot::Atom(0); MAX_MASKED_REGION];
let mut len = 0usize;
let (mut atoms, mut consts) = (Vec::with_capacity(3), Vec::with_capacity(2));
let slot_of = |ids: &[u32], i: u32| ids.iter().position(|&j| j == i);
let mut stack = [(0u32, false); 3 * MAX_MASKED_REGION + 2];
let mut top = 0usize;
for &n in roots.iter().rev() {
stack[top] = (n, false);
top += 1;
}
let mut visits = 0usize;
let beyond = loop {
if top == 0 {
break false;
}
top -= 1;
let (i, expanded) = stack[top];
if slot_of(&ids[..len], i).is_some() {
continue;
}
let node = cx.node(i);
if expanded {
let a = slot_of(&ids[..len], node.a).unwrap_or(0);
let b = if node.op == OpCode::Not {
a
} else {
slot_of(&ids[..len], node.b).unwrap_or(0)
};
ids[len] = i;
slots[len] = Slot::Op(node.op, a, b);
len += 1;
continue;
}
visits += 1;
if visits > MAX_MASKED_REGION || r.bitwise.beyond.contains_key(&i) {
break true;
}
if !bitwise_op(node.op) {
let slot = if cx.const_val(i).is_some() {
consts.push(i);
Slot::Const(consts.len() - 1)
} else {
atoms.push(i);
Slot::Atom(atoms.len() - 1)
};
if atoms.len() > 3 || consts.len() > MAX_MASKS + 2 {
break true;
}
ids[len] = i;
slots[len] = slot;
len += 1;
continue;
}
stack[top] = (i, true);
top += 1;
for c in node.children() {
if slot_of(&ids[..len], c).is_none() {
stack[top] = (c, false);
top += 1;
}
}
};
let (ids, slots) = (&ids[..len], &slots[..len]);
if beyond {
if let [n] = roots {
r.bitwise.beyond.insert(*n, ());
}
r.meter.charge(Counter::PassWork, visits as u64)?;
return Ok(None);
}
r.meter.charge(Counter::PassWork, visits as u64)?;
let mut by_index: Vec<usize> = (0..atoms.len()).collect();
by_index.sort_unstable_by_key(|&k| atoms[k]);
let mut var = [0u8; 3];
for (v, &k) in by_index.iter().enumerate() {
var[k] = VARS[v];
}
atoms.sort_unstable();
let w = cx.width_of(roots[0]);
let values: Vec<BitVec> = consts
.iter()
.map(|&c| cx.const_val(c).unwrap_or(BitVec::zero(w)))
.collect();
let mut splits: Vec<BitVec> = Vec::new();
for v in &values {
if !v.is_zero() && !v.is_ones() && !splits.contains(v) {
splits.push(*v);
}
}
if splits.len() > MAX_MASKS {
if let [n] = roots {
r.bitwise.beyond.insert(*n, ());
}
return Ok(None);
}
let mut classes: Vec<(BitVec, Vec<u8>)> = Vec::new();
let mut vals: Vec<u8> = vec![0; slots.len()];
for pattern in 0..1usize << splits.len() {
let mut mask = BitVec::ones(w);
for (k, v) in splits.iter().enumerate() {
let v = if pattern >> k & 1 == 1 {
*v
} else {
BitVec::un_unchecked(UnOp::Not, v)
};
mask = BitVec::bin_unchecked(BinOp::And, &mask, &v);
}
if mask.is_zero() {
continue;
}
r.meter
.charge(Counter::PassWork, slots.len() as u64 / 4 + 1)?;
for (k, slot) in slots.iter().enumerate() {
vals[k] = match *slot {
Slot::Atom(a) => var[a],
Slot::Const(c) => {
if BitVec::bin_unchecked(BinOp::And, &values[c], &mask) == mask {
0xFF
} else {
0x00
}
}
Slot::Op(OpCode::Not, a, _) => !vals[a],
Slot::Op(OpCode::And, a, b) => vals[a] & vals[b],
Slot::Op(OpCode::Or, a, b) => vals[a] | vals[b],
Slot::Op(_, a, b) => vals[a] ^ vals[b],
};
}
let tables: Vec<u8> = roots
.iter()
.map(|&n| vals[slot_of(ids, n).unwrap_or(0)])
.collect();
match classes.iter_mut().find(|(_, t)| *t == tables) {
Some((m, _)) => *m = BitVec::bin_unchecked(BinOp::Or, m, &mask),
None => classes.push((mask, tables)),
}
}
let ops = slots.iter().filter(|s| matches!(s, Slot::Op(..))).count() as u32;
Ok(Some(Masked {
atoms,
consts,
classes,
ops,
}))
}
pub(super) fn equal(
r: &mut Runner<'_, '_>,
cx: &Context,
a: u32,
b: u32,
) -> Result<Option<bool>, Stop> {
if !bitwise_op(cx.node(a).op) && !bitwise_op(cx.node(b).op) {
return Ok(None);
}
let Some(m) = masked(r, cx, &[a, b])? else {
return Ok(None);
};
if m.classes.iter().all(|(_, t)| t[0] == t[1]) {
return Ok(Some(true));
}
if m.classes.iter().any(|(_, t)| t[0] == !t[1]) {
return Ok(Some(false));
}
Ok(None)
}
fn cost(tt: u8) -> u32 {
min_forms().forms[tt as usize]
.0
.iter()
.filter(|t| !matches!(t, T::Var(_)))
.count() as u32
}
#[derive(Clone, Copy)]
enum Split {
And(u8),
Or(u8),
Xor(u8),
Blend(u8, u8),
}
fn masked_step(r: &mut Runner<'_, '_>, cx: &mut Context, n: u32) -> Result<Step, Stop> {
let Some(m) = masked(r, cx, &[n])? else {
return Ok(Step::Normal(Fin::FINAL));
};
if m.consts.is_empty() || m.classes.len() > 2 {
return Ok(Step::Normal(Fin::FINAL));
}
let cheapest = |t: u8| cost(t) + 1;
let floor = match &m.classes[..] {
[(_, t)] => cost(t[0]),
[(_, t), (_, u)] => cheapest(t[0]).min(cheapest(u[0])),
_ => u32::MAX,
};
if floor >= m.ops {
return Ok(Step::Normal(Fin::FINAL));
}
let mut canon = m.atoms.clone();
canon.sort_by(|a, b| cx.order(*a, *b));
let tt = |t: u8| remap(t, &m.atoms, &canon);
let w = cx.width_of(n);
let is_old = |v: &BitVec| {
m.consts
.iter()
.any(|&c| cx.const_val(c).as_ref() == Some(v))
};
let mut best: Option<(u32, Option<(Split, BitVec)>)> = None;
let mut offer = |c: u32, s: Option<(Split, BitVec)>| {
if best.as_ref().is_none_or(|(b, _)| c < *b) {
best = Some((c, s));
}
};
if let [(_, t)] = &m.classes[..] {
offer(cost(tt(t[0])), None);
} else {
for (x, y) in [(0, 1), (1, 0)] {
let (mask, t) = (m.classes[x].0, tt(m.classes[x].1[0]));
let u = tt(m.classes[y].1[0]);
let extra = 1 + u32::from(!is_old(&mask));
if u == 0x00 {
offer(cost(t) + extra, Some((Split::And(t), mask)));
}
if t == 0xFF {
offer(cost(u) + extra, Some((Split::Or(u), mask)));
}
if t == !u {
offer(cost(u) + extra, Some((Split::Xor(u), mask)));
}
offer(
cost(u) + cost(t ^ u) + extra + 1,
Some((Split::Blend(u, t ^ u), mask)),
);
}
}
let Some((estimate, split)) = best else {
return Ok(Step::Normal(Fin::FINAL));
};
if estimate >= m.ops {
return Ok(Step::Normal(Fin::FINAL));
}
let mut bounds = m.atoms.clone();
bounds.extend(&m.consts);
if let Some(f) = worth_building(r, cx, n, &bounds, estimate)? {
r.stats.passes.entry("bitwise").or_default().rejected_cost += 1;
return Ok(Step::Normal(Fin::FINAL.and(f)));
}
let before = cx.len() as u32;
let form = |r: &mut Runner<'_, '_>, cx: &mut Context, t: u8| -> Result<u32, Stop> {
if canon.is_empty() || t == 0x00 || t == 0xFF {
let v = if t == 0xFF {
BitVec::ones(w)
} else {
BitVec::zero(w)
};
r.build(cx, |cx| cx.mk_const(&v))
} else {
emit(r, cx, t, &canon)
}
};
let e = match split {
None => form(r, cx, tt(m.classes[0].1[0]))?,
Some((split, mask)) => {
let k = r.build(cx, |cx| cx.mk_const(&mask))?;
match split {
Split::And(t) => {
let f = form(r, cx, t)?;
r.build(cx, |cx| cx.c_bin(BinOp::And, f, k))?
}
Split::Or(u) => {
let f = form(r, cx, u)?;
r.build(cx, |cx| cx.c_bin(BinOp::Or, f, k))?
}
Split::Xor(u) => {
let f = form(r, cx, u)?;
r.build(cx, |cx| cx.c_bin(BinOp::Xor, f, k))?
}
Split::Blend(u, g) => {
let (f, g) = (form(r, cx, u)?, form(r, cx, g)?);
let gm = r.build(cx, |cx| cx.c_bin(BinOp::And, g, k))?;
r.build(cx, |cx| cx.c_bin(BinOp::Xor, f, gm))?
}
}
}
};
finish(r, cx, PassKind::Bitwise, n, e, before, &bounds, Fin::FINAL)
}
const ONE_ATOM_REGION: usize = 64;
fn one_atom_step(r: &mut Runner<'_, '_>, cx: &mut Context, n: u32) -> Result<Step, Stop> {
let w = cx.width_of(n);
let mut order: Vec<u32> = Vec::new();
let mut seen: crate::hash::IdMap<u32, ()> = crate::hash::IdMap::default();
let mut stack: Vec<(u32, bool)> = vec![(n, false)];
let (mut atom, mut consts, mut ops) = (None, Vec::new(), 0u32);
while let Some((i, expanded)) = stack.pop() {
if expanded {
order.push(i);
continue;
}
if seen.insert(i, ()).is_some() {
continue;
}
if seen.len() > ONE_ATOM_REGION {
r.meter.charge(Counter::PassWork, seen.len() as u64)?;
return Ok(Step::Normal(Fin::FINAL));
}
let node = cx.node(i);
if bitwise_op(node.op) {
ops += 1;
stack.push((i, true));
stack.extend(node.children().map(|c| (c, false)));
} else if cx.const_val(i).is_some() {
consts.push(i);
} else if atom.is_some_and(|a| a != i) {
r.meter.charge(Counter::PassWork, seen.len() as u64)?;
return Ok(Step::Normal(Fin::FINAL));
} else {
atom = Some(i);
}
}
r.meter.charge(Counter::PassWork, 2 * seen.len() as u64)?;
let Some(x) = atom else {
return Ok(Step::Normal(Fin::FINAL));
};
let at = |v: BitVec| -> BitVec {
let mut vals: crate::hash::IdMap<u32, BitVec> = crate::hash::IdMap::default();
vals.insert(x, v);
for &c in &consts {
vals.insert(c, cx.const_val(c).unwrap_or(BitVec::zero(w)));
}
for &i in &order {
let node = cx.node(i);
let v = match node.op {
OpCode::Not => BitVec::un_unchecked(UnOp::Not, &vals[&node.a]),
OpCode::And => BitVec::bin_unchecked(BinOp::And, &vals[&node.a], &vals[&node.b]),
OpCode::Or => BitVec::bin_unchecked(BinOp::Or, &vals[&node.a], &vals[&node.b]),
_ => BitVec::bin_unchecked(BinOp::Xor, &vals[&node.a], &vals[&node.b]),
};
vals.insert(i, v);
}
vals[&n]
};
let b = at(BitVec::zero(w));
let a = BitVec::bin_unchecked(BinOp::Xor, &b, &at(BitVec::ones(w)));
let is_old = |v: &BitVec| consts.iter().any(|&c| cx.const_val(c).as_ref() == Some(v));
let estimate = if a.is_zero() {
1
} else {
let masked = if a.is_ones() {
0
} else {
1 + u32::from(!is_old(&a))
};
let flipped = match (b.is_zero(), b.is_ones()) {
(true, _) => 0,
(_, true) => 1,
_ => 1 + u32::from(!is_old(&b)),
};
masked + flipped
};
if estimate >= ops {
return Ok(Step::Normal(Fin::FINAL));
}
let mut bounds = vec![x];
bounds.extend(&consts);
if let Some(f) = worth_building(r, cx, n, &bounds, estimate)? {
r.stats.passes.entry("bitwise").or_default().rejected_cost += 1;
return Ok(Step::Normal(Fin::FINAL.and(f)));
}
let before = cx.len() as u32;
let e = r.build(cx, |cx| {
let ka = cx.mk_const(&a)?;
let kb = cx.mk_const(&b)?;
let masked = cx.c_bin(BinOp::And, x, ka)?;
cx.c_bin(BinOp::Xor, masked, kb)
})?;
finish(r, cx, PassKind::Bitwise, n, e, before, &bounds, Fin::FINAL)
}
fn write(
r: &mut Runner<'_, '_>,
cx: &mut Context,
n: u32,
atoms: &[u32],
tt: u8,
fin: Fin,
) -> Result<Step, Stop> {
let mut canon = atoms.to_vec();
canon.sort_by(|a, b| cx.order(*a, *b));
let tt_c = remap(tt, atoms, &canon);
if let Some(f) = worth_building(r, cx, n, atoms, cost(tt_c))? {
r.stats.passes.entry("bitwise").or_default().rejected_cost += 1;
return Ok(Step::Normal(fin.and(f)));
}
let before = cx.len() as u32;
let e = if canon.is_empty() {
let w = cx.width_of(n);
let v = if tt == 0 {
BitVec::zero(w)
} else {
BitVec::ones(w)
};
r.build(cx, |cx| cx.mk_const(&v))?
} else {
emit(r, cx, tt_c, &canon)?
};
r.explain_with(|| crate::engine::Explanation::Bitwise {
atoms: atoms.iter().map(|&a| cx.handle(a)).collect(),
table: u64::from(tt),
});
finish(r, cx, PassKind::Bitwise, n, e, before, atoms, fin)
}
const HOIST_NODES: usize = 64;
#[derive(Default)]
struct Low {
konst: u64,
terms: Vec<(u32, u64)>,
}
const LOW_NODES: usize = 64;
fn low_form(cx: &Context, i: u32, k: u64, bits: u16, out: &mut Low) -> bool {
let m = (1u64 << bits) - 1;
let mut todo = vec![(i, k & m)];
let mut seen = 0usize;
while let Some((i, k)) = todo.pop() {
seen += 1;
if seen > LOW_NODES {
return false;
}
if k == 0 {
continue;
}
let n = cx.node(i);
let low = |c: u32| {
cx.const_val(c)
.map(|v| v.limbs().first().copied().unwrap_or(0) & m)
};
let keeps = |x: u32| cx.wid(x) >= bits;
match n.op {
OpCode::Const => {
out.konst = out.konst.wrapping_add(k.wrapping_mul(low(i).unwrap_or(0))) & m
}
OpCode::Add => todo.extend([(n.a, k), (n.b, k)]),
OpCode::Sub => todo.extend([(n.a, k), (n.b, k.wrapping_neg() & m)]),
OpCode::Neg => todo.push((n.a, k.wrapping_neg() & m)),
OpCode::Mul if low(n.b).is_some() => {
todo.push((n.a, k.wrapping_mul(low(n.b).unwrap_or(0)) & m))
}
OpCode::Mul if low(n.a).is_some() => {
todo.push((n.b, k.wrapping_mul(low(n.a).unwrap_or(0)) & m))
}
OpCode::Shl
if cx
.const_val(n.b)
.and_then(|v| v.to_u64())
.is_some_and(|s| s < 64) =>
{
let s = cx.const_val(n.b).and_then(|v| v.to_u64()).unwrap_or(0);
todo.push((n.a, (k << s) & m));
}
OpCode::Extract if n.b == 0 => todo.push((n.a, k)),
OpCode::Zext | OpCode::Sext if keeps(n.a) => todo.push((n.a, k)),
OpCode::And if low(n.b) == Some(m) => todo.push((n.a, k)),
OpCode::And if low(n.a) == Some(m) => todo.push((n.b, k)),
_ => match out.terms.iter_mut().find(|t| t.0 == i) {
Some(t) => t.1 = t.1.wrapping_add(k) & m,
None => out.terms.push((i, k)),
},
}
}
true
}
fn rotation(r: &mut Runner<'_, '_>, cx: &mut Context, n: u32) -> Result<Step, Stop> {
let node = cx.node(n);
let w = node.width;
if !matches!(node.op, OpCode::Or | OpCode::Xor) || !w.is_power_of_two() || w < 2 {
return Ok(Step::Normal(Fin::FINAL));
}
let (l, s) = match (cx.node(node.a).op, cx.node(node.b).op) {
(OpCode::Shl, OpCode::LShr) => (cx.node(node.a), cx.node(node.b)),
(OpCode::LShr, OpCode::Shl) => (cx.node(node.b), cx.node(node.a)),
_ => return Ok(Step::Normal(Fin::FINAL)),
};
let (x, a, b) = (l.a, l.b, s.b);
if s.a != x || cx.const_val(a).is_some() || cx.const_val(b).is_some() {
return Ok(Step::Normal(Fin::FINAL));
}
r.meter.charge(Counter::PassWork, 1)?;
let bits = w.trailing_zeros() as u16;
let mut fin = Fin::FINAL;
for count in [a, b] {
let (f, g) = super::facts(r, cx, count)?;
fin = fin.and(g);
let below = f.is_some_and(|f| (bits..w).all(|i| f.known.known_zero().bit(i) == Some(true)));
if !below {
return Ok(Step::Normal(fin));
}
}
let mut sum = Low::default();
if !(low_form(cx, a, 1, bits, &mut sum) && low_form(cx, b, 1, bits, &mut sum))
|| sum.konst != 0
|| sum.terms.iter().any(|&(_, k)| k != 0)
{
return Ok(Step::Normal(fin));
}
let before = cx.len() as u32;
let e = r.build(cx, |cx| cx.c_bin(BinOp::RotL, x, a))?;
finish(r, cx, PassKind::Bitwise, n, e, before, &[x, a], fin)
}
fn hoist_cast(r: &mut Runner<'_, '_>, cx: &mut Context, n: u32) -> Result<Step, Stop> {
let u = cx.width_of(n);
let mut order: Vec<u32> = Vec::new();
let mut seen: Vec<u32> = Vec::new();
let mut stack: Vec<(u32, bool)> = vec![(n, false)];
let mut kind: Option<(OpCode, crate::Width)> = None;
let mut casts = 0usize;
let mut consts = 0usize;
let mut narrow: Vec<u32> = Vec::new();
while let Some((i, expanded)) = stack.pop() {
if expanded {
order.push(i);
continue;
}
if seen.contains(&i) {
continue;
}
seen.push(i);
if seen.len() > HOIST_NODES {
return Ok(Step::Normal(Fin::FINAL));
}
let node = cx.node(i);
if cx.const_val(i).is_some() {
consts += 1;
continue;
}
match node.op {
OpCode::Zext | OpCode::Sext => {
let wa = cx.width_of(node.a);
match kind {
Some(k) if k != (node.op, wa) => return Ok(Step::Normal(Fin::FINAL)),
_ => kind = Some((node.op, wa)),
}
casts += 1;
narrow.push(node.a);
}
op if bitwise_op(op) => {
stack.push((i, true));
for c in node.children() {
stack.push((c, false));
}
}
_ => return Ok(Step::Normal(Fin::FINAL)),
}
}
let Some((k, w)) = kind else {
return Ok(Step::Normal(Fin::FINAL));
};
if casts < 2 && consts == 0 {
return Ok(Step::Normal(Fin::FINAL));
}
r.meter.charge(Counter::PassWork, order.len() as u64)?;
let wide = |cx: &Context, i: u32| -> Option<BitVec> {
let node = cx.node(i);
if let Some(c) = cx.const_val(i) {
return Some(c);
}
match node.op {
OpCode::Zext | OpCode::Sext => Some(BitVec::zero(u)),
_ => None,
}
};
if k == OpCode::Sext {
for &i in &seen {
if let Some(c) = cx.const_val(i)
&& c.trunc(w).ok().and_then(|t| t.sext(u).ok()) != Some(c)
{
return Ok(Step::Normal(Fin::FINAL));
}
}
}
let before = cx.len() as u32;
let mut low: crate::hash::IdMap<u32, u32> = crate::hash::IdMap::default();
let mut above: crate::hash::IdMap<u32, BitVec> = crate::hash::IdMap::default();
for &i in &seen {
let node = cx.node(i);
if let Some(c) = cx.const_val(i) {
let t = c.trunc(w).map_err(|e| Stop::Error(e.into()))?;
low.insert(i, r.build(cx, |cx| cx.mk_const(&t))?);
above.insert(i, c);
} else if matches!(node.op, OpCode::Zext | OpCode::Sext) {
low.insert(i, node.a);
above.insert(i, BitVec::zero(u));
}
}
for &i in &order {
let node = cx.node(i);
let (a, b) = (low[&node.a], node.b);
let (va, vb) = (
above[&node.a],
wide(cx, node.b).or_else(|| above.get(&node.b).copied()),
);
let (l, v) = match node.op {
OpCode::Not => (
r.build(cx, |cx| cx.c_un(UnOp::Not, a))?,
BitVec::un_unchecked(UnOp::Not, &va),
),
op => {
let bin = op.as_bin().unwrap_or(BinOp::And);
let Some(vb) = vb else {
return Ok(Step::Normal(Fin::FINAL));
};
let lb = low[&b];
(
r.build(cx, |cx| cx.c_bin(bin, a, lb))?,
BitVec::bin_unchecked(bin, &va, &vb),
)
}
};
low.insert(i, l);
above.insert(i, v);
}
let f = low[&n];
let e = if k == OpCode::Sext {
r.build(cx, |cx| cx.c_sext(f, u.bits()))?
} else {
let v = above[&n];
let hi = crate::facts::known::bv_lshr(&v, u32::from(w.bits()));
let span = crate::facts::known::low_mask(u, u32::from(u.bits() - w.bits()));
if hi.is_zero() {
r.build(cx, |cx| cx.c_zext(f, u.bits()))?
} else if hi == span {
r.build(cx, |cx| {
let nf = cx.c_un(UnOp::Not, f)?;
let z = cx.c_zext(nf, u.bits())?;
cx.c_un(UnOp::Not, z)
})?
} else {
super::discard(r, cx, before);
return Ok(Step::Normal(Fin::FINAL));
}
};
narrow.sort_unstable();
narrow.dedup();
finish(r, cx, PassKind::Bitwise, n, e, before, &narrow, Fin::FINAL)
}
fn masked_overlap(r: &mut Runner<'_, '_>, cx: &mut Context, n: u32) -> Result<Step, Stop> {
let node = cx.node(n);
let (join, meet) = match (cx.node(node.a), cx.node(node.b)) {
(j, m) if j.op == OpCode::Or && m.op == OpCode::And => (j, m),
(m, j) if j.op == OpCode::Or && m.op == OpCode::And => (j, m),
_ => return Ok(Step::Normal(Fin::FINAL)),
};
for (x, masked) in [(join.a, join.b), (join.b, join.a)] {
let y = if meet.a == x {
meet.b
} else if meet.b == x {
meet.a
} else {
continue;
};
let field = cx.node(masked);
if field.op != OpCode::And || field.a != y || cx.node(field.b).op != OpCode::Const {
continue;
}
let (fits, fm, fx) = super::within(r, cx, field.b, x)?;
let fin = fm.and(fx);
if !fits {
return Ok(Step::Normal(fin));
}
let before = cx.len() as u32;
let e = r.build(cx, |cx| cx.c_bin(BinOp::Xor, x, masked))?;
return finish(r, cx, PassKind::Bitwise, n, e, before, &[x, masked, y], fin);
}
Ok(Step::Normal(Fin::FINAL))
}
pub(super) fn step(r: &mut Runner<'_, '_>, cx: &mut Context, n: u32) -> Result<Step, Stop> {
if !bitwise_op(cx.node(n).op) {
return Ok(Step::Normal(Fin::FINAL));
}
let hoisted = match hoist_cast(r, cx, n)? {
Step::Normal(f) => f,
done => return Ok(done),
};
let hoisted = match rotation(r, cx, n)? {
Step::Normal(f) => hoisted.and(f),
done => return Ok(done),
};
let hoisted = if cx.node(n).op == OpCode::Xor {
match masked_overlap(r, cx, n)? {
Step::Normal(f) => hoisted.and(f),
done => return Ok(done),
}
} else {
hoisted
};
let Some((atoms, tt)) = info_of(r, cx, n)? else {
return Ok(Step::Normal(hoisted));
};
let first = if atoms == [n] {
match masked_step(r, cx, n)? {
Step::Normal(f) => match one_atom_step(r, cx, n)? {
Step::Normal(g) => Step::Normal(f.and(g)),
done => done,
},
done => done,
}
} else {
write(r, cx, n, &atoms, tt, Fin::FINAL)?
};
let mut fin = match first {
Step::Normal(f) => f.and(hoisted),
done => return Ok(done),
};
if atoms.iter().any(|&a| bitwise_op(cx.node(a).op)) {
let wide = wide_of(r, cx, n)?;
if wide.atoms().len() <= 3 && wide.atoms() != atoms && wide.atoms() != [n] {
match write(r, cx, n, wide.atoms(), wide.tt as u8, fin)? {
Step::Normal(f) => fin = f,
done => return Ok(done),
}
}
}
if !matches!(cx.node(n).op, OpCode::And | OpCode::Or) {
return Ok(Step::Normal(fin));
}
Ok(match super::sort_chain(r, cx, PassKind::Bitwise, n)? {
Step::Normal(f) => Step::Normal(fin.and(f)),
done => done,
})
}
#[cfg(test)]
mod tests {
use super::*;
fn reference(tt: u64, from: &[u32], to: &[u32]) -> u64 {
(0..64).fold(0, |out, i| {
let j = from.iter().enumerate().fold(0, |j, (k, a)| {
let p = to.iter().position(|b| b == a).unwrap();
j | ((i >> p) & 1) << k
});
out | ((tt >> j) & 1) << i
})
}
fn table(state: &mut u64, m: usize) -> u64 {
*state ^= *state << 13;
*state ^= *state >> 7;
*state ^= *state << 17;
(0..64).fold(0, |out, i| out | ((*state >> (i % (1 << m))) & 1) << i)
}
fn subset(ids: &[u32], s: usize) -> Vec<u32> {
(0..ids.len())
.filter(|k| s >> k & 1 == 1)
.map(|k| ids[k])
.collect()
}
#[test]
fn wide_tables_move_between_atom_sets() {
let ids = [3, 5, 8, 9, 12, 20];
let mut state = 0x7769_6465;
for big in 0..64usize {
let to = subset(&ids, big);
for small in (0..64usize).filter(|s| s & !big == 0) {
let from = subset(&ids, small);
for _ in 0..4 {
let tt = table(&mut state, from.len());
assert_eq!(
remap_wide(tt, &from, &to),
reference(tt, &from, &to),
"{from:?} -> {to:?}, {tt:#x}"
);
}
}
let mut tt = table(&mut state, to.len());
while (0..to.len()).any(|k| {
let (v, s) = (WIDE_VARS[k], 1u32 << k);
(tt & v) >> s | (tt & !v) << s == tt
}) {
tt = table(&mut state, to.len());
}
let p = prune_wide(&ids, reference(tt, &to, &ids));
assert_eq!(p.atoms(), &to[..]);
assert_eq!(p.tt, tt, "{to:?}");
}
}
}
#[derive(Default)]
pub(crate) struct State {
pub(crate) info: crate::hash::IdMap<u32, Info>,
pub(crate) wide: crate::hash::IdMap<u32, Wide>,
pub(crate) beyond: crate::hash::IdMap<u32, ()>,
}