bitwright 0.32.4

Hash-consed fixed-width bit-vector expressions: exact evaluation, bit-level facts, and verified simplification.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
//! CoBRA (Coefficient-Based Reduction of MBA) change-of-basis decomposition for linear and
//! semi-linear Mixed Boolean-Arithmetic polynomials over `Z / 2^P Z`.
//!
//! Given conjunction (Möbius) coefficients `alpha[S]` (`∅ ≠ S ⊆ {0..s-1}`) modulo `2^prec`,
//! iteratively eliminates top-degree monomials against a library of minimal 1-, 2-, and 3-input
//! Boolean basis functions (with `f(0) = 0`) and multi-literal clauses, using lookahead alignment
//! on lower-degree shared subsets so overlapping arbitrary-coefficient terms (`5*(x^y) + 7*(x|z)
//! - 5*(y|z)`) unmix cleanly in `O(k)` basis steps.

use std::sync::OnceLock;

use crate::BitVec;
use crate::engine::pass::bitwise::min_forms;
use crate::ops::{BinOp, UnOp};

/// Maximum atom support handled by dense CoBRA Möbius tables (`2^10 = 1024` subsets).
pub(crate) const MAX_COBRA_ATOMS: usize = 10;

/// Maximum basis terms emitted before bailing out (prevents pathological blowup on random tables).
const MAX_BASIS_TERMS: usize = 48;

/// One Boolean basis element over support indices `0..s` (every variant satisfies `f(0, …, 0) = 0`,
/// except `Not` which wraps an inner `f(0) = 0` basis element after constant trading).
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum BasisOp {
    /// Single input `x_i`.
    Var(usize),
    /// Minimal 2-input Boolean function (`tt8` in `min_forms()` over `[vars[0], vars[1], 0]`).
    Table2 { vars: [usize; 2], tt8: u8 },
    /// Minimal 3-input Boolean function (`tt8` in `min_forms()` over `vars`).
    Table3 { vars: [usize; 3], tt8: u8 },
    /// Multi-literal conjunction `⋀_k (if neg_mask >> k & 1 == 1 { ~x_{vars[k]} } else { x_{vars[k]} })`
    /// with at least one positive literal (`neg_mask != (1 << vars.len()) - 1`).
    ClauseAnd { vars: Vec<usize>, neg_mask: u16 },
    /// Multi-way disjunction `⋁_k x_{vars[k]}` (`vars.len() >= 4`).
    OrAll { vars: Vec<usize> },
    /// Bitwise complement `~inner` (produced when trading the constant offset against a term).
    Not(Box<BasisOp>),
}

impl BasisOp {
    /// Estimated gate count (excluding leaf atoms).
    pub(crate) fn gate_cost(&self) -> u32 {
        match self {
            BasisOp::Var(_) => 0,
            BasisOp::Table2 { tt8, .. } | BasisOp::Table3 { tt8, .. } => {
                u32::from(min_forms().forms[usize::from(*tt8)].1)
            }
            BasisOp::ClauseAnd { vars, neg_mask } => {
                let ands = (vars.len() as u32).saturating_sub(1);
                let negs = neg_mask.count_ones();
                // Multiple negated inputs fold by De Morgan into `~(a | b | ...)` (`k` gates total).
                ands + negs.min(2)
            }
            BasisOp::OrAll { vars } => (vars.len() as u32).saturating_sub(1),
            BasisOp::Not(inner) => match inner.as_ref() {
                BasisOp::Table2 { tt8, .. } | BasisOp::Table3 { tt8, .. } => {
                    u32::from(min_forms().forms[usize::from(!*tt8)].1)
                }
                _ => inner.gate_cost() + 1,
            },
        }
    }

    /// The function written with `g`'s gates: the one lowering the engine's linear-MBA pass
    /// and the normal-form renderer share, each over its own nodes.
    pub(crate) fn lower<G: Gates>(&self, g: &mut G) -> Result<u32, G::Err> {
        match self {
            BasisOp::Var(i) => g.input(*i),
            BasisOp::Table2 { vars, tt8 } => table2(g, vars, *tt8),
            BasisOp::Table3 { vars, tt8 } => table3(g, vars, *tt8),
            BasisOp::ClauseAnd { vars, neg_mask } => {
                // The positive literals and-ed, the negated ones or-ed under one `~`.
                let (mut pos, mut neg) = (None, None);
                for (bit, &v) in vars.iter().enumerate() {
                    let a = g.input(v)?;
                    if (*neg_mask >> bit) & 1 == 1 {
                        neg = Some(match neg {
                            None => a,
                            Some(x) => g.or(x, a)?,
                        });
                    } else {
                        pos = Some(match pos {
                            None => a,
                            Some(x) => g.and(x, a)?,
                        });
                    }
                }
                let neg = match neg {
                    Some(o) => Some(g.not(o)?),
                    None => None,
                };
                match (pos, neg) {
                    (Some(p), Some(n)) => g.and(p, n),
                    (Some(x), None) | (None, Some(x)) => Ok(x),
                    // (No pivot has fewer than two atoms.)
                    (None, None) => g.ones(),
                }
            }
            BasisOp::OrAll { vars } => {
                let Some((&v0, rest)) = vars.split_first() else {
                    // The empty disjunction (never built: an `OrAll` has four inputs or more).
                    let ones = g.ones()?;
                    return g.not(ones);
                };
                let mut acc = g.input(v0)?;
                for &v in rest {
                    let a = g.input(v)?;
                    acc = g.or(acc, a)?;
                }
                Ok(acc)
            }
            BasisOp::Not(inner) => match inner.as_ref() {
                // A table's complement is the complemented table, at its own minimal size.
                BasisOp::Table2 { vars, tt8 } => table2(g, vars, !*tt8),
                BasisOp::Table3 { vars, tt8 } => table3(g, vars, !*tt8),
                other => {
                    let x = other.lower(g)?;
                    g.complement(x)
                }
            },
        }
    }
}

/// The gates a basis function is written with (see [`BasisOp::lower`]); `Err` declines.
pub(crate) trait Gates {
    type Err;
    /// Input `i` of the decomposition.
    fn input(&mut self, i: usize) -> Result<u32, Self::Err>;
    /// The minimal form of the 3-input truth table `tt8` over `args`.
    fn table(&mut self, tt8: u8, args: [u32; 3]) -> Result<u32, Self::Err>;
    fn and(&mut self, a: u32, b: u32) -> Result<u32, Self::Err>;
    fn or(&mut self, a: u32, b: u32) -> Result<u32, Self::Err>;
    fn not(&mut self, a: u32) -> Result<u32, Self::Err>;
    /// All ones (the empty conjunction).
    fn ones(&mut self) -> Result<u32, Self::Err>;
    /// The complement of a basis function that is no table: `~a` unless the builder knows a
    /// cheaper form of it.
    fn complement(&mut self, a: u32) -> Result<u32, Self::Err> {
        self.not(a)
    }
}

/// A 2-input table, its first input in the unused third place.
fn table2<G: Gates>(g: &mut G, vars: &[usize; 2], tt8: u8) -> Result<u32, G::Err> {
    let (a0, a1) = (g.input(vars[0])?, g.input(vars[1])?);
    g.table(tt8, [a0, a1, a0])
}

fn table3<G: Gates>(g: &mut G, vars: &[usize; 3], tt8: u8) -> Result<u32, G::Err> {
    let args = [g.input(vars[0])?, g.input(vars[1])?, g.input(vars[2])?];
    g.table(tt8, args)
}

/// Precomputed 2-var and 3-var Boolean basis templates with `f(0) = 0` and non-zero top Möbius.
struct BasisEntry {
    tt8: u8,
    ops: u8,
    mobius: [i8; 8],
}

struct BasisLibrary {
    two: Vec<BasisEntry>,
    three: Vec<BasisEntry>,
}

fn library() -> &'static BasisLibrary {
    static LIB: OnceLock<BasisLibrary> = OnceLock::new();
    LIB.get_or_init(|| {
        let forms = min_forms();
        let mut two = Vec::new();
        for t4 in 1u8..16 {
            if t4 & 1 != 0 {
                continue;
            }
            // Must depend on both input 0 and input 1.
            if (t4 & 0x5) == ((t4 >> 1) & 0x5) || (t4 & 0x3) == ((t4 >> 2) & 0x3) {
                continue;
            }
            let mut m = [0i8; 8];
            for (q, slot) in m.iter_mut().enumerate().take(4) {
                *slot = ((t4 >> q) & 1) as i8;
            }
            for b in 0..2 {
                for q in 0..4usize {
                    if (q >> b) & 1 == 1 {
                        m[q] -= m[q ^ (1 << b)];
                    }
                }
            }
            if m[3] == 0 {
                continue;
            }
            let tt8 = t4 | (t4 << 4);
            let ops = forms.forms[usize::from(tt8)].1;
            two.push(BasisEntry {
                tt8,
                ops,
                mobius: m,
            });
        }

        let mut three = Vec::new();
        for tt8 in 1u8..=254 {
            if tt8 & 1 != 0 {
                continue;
            }
            // Must depend on all three inputs 0, 1, 2.
            if (tt8 & 0x55) == ((tt8 >> 1) & 0x55)
                || (tt8 & 0x33) == ((tt8 >> 2) & 0x33)
                || (tt8 & 0x0F) == ((tt8 >> 4) & 0x0F)
            {
                continue;
            }
            let ops = forms.forms[usize::from(tt8)].1;
            if ops > 4 {
                continue;
            }
            let mut m = [0i8; 8];
            for (q, slot) in m.iter_mut().enumerate() {
                *slot = ((tt8 >> q) & 1) as i8;
            }
            for b in 0..3 {
                for q in 0..8usize {
                    if (q >> b) & 1 == 1 {
                        m[q] -= m[q ^ (1 << b)];
                    }
                }
            }
            if m[7] == 0 {
                continue;
            }
            three.push(BasisEntry {
                tt8,
                ops,
                mobius: m,
            });
        }
        BasisLibrary { two, three }
    })
}

fn low_mask(w: crate::Width, bits: u32) -> BitVec {
    let wb = u32::from(w.bits());
    if bits == 0 {
        BitVec::zero(w)
    } else if bits >= wb {
        BitVec::ones(w)
    } else {
        let mut limbs = [0u64; 8];
        let full = (bits / 64) as usize;
        for slot in limbs.iter_mut().take(full) {
            *slot = u64::MAX;
        }
        let rem = bits % 64;
        if rem > 0 {
            limbs[full] = (1u64 << rem) - 1;
        }
        BitVec::wrapping_from_limbs(w, &limbs)
    }
}

fn single_bit(w: crate::Width, pos: u32) -> BitVec {
    let mut limbs = [0u64; 8];
    if pos < u32::from(w.bits()) {
        limbs[(pos / 64) as usize] = 1u64 << (pos % 64);
    }
    BitVec::wrapping_from_limbs(w, &limbs)
}

fn signed_bv(w: crate::Width, v: i8) -> BitVec {
    if v >= 0 {
        BitVec::wrapping_from_u64(w, v as u64)
    } else {
        BitVec::un_unchecked(UnOp::Neg, &BitVec::wrapping_from_u64(w, (-v) as u64))
    }
}

fn odd_inverse_3(w: crate::Width) -> BitVec {
    let three = BitVec::wrapping_from_u64(w, 3);
    let two = BitVec::wrapping_from_u64(w, 2);
    let mut inv = BitVec::one(w);
    for _ in 0..9 {
        let prod = BitVec::bin_unchecked(BinOp::Mul, &three, &inv);
        let factor = BitVec::bin_unchecked(BinOp::Sub, &two, &prod);
        inv = BitVec::bin_unchecked(BinOp::Mul, &inv, &factor);
    }
    inv
}

fn trailing_zeros(v: &BitVec) -> u32 {
    let wb = u32::from(v.width().bits());
    for (i, &limb) in v.limbs().iter().enumerate() {
        let base = (i as u32) * 64;
        if base >= wb {
            break;
        }
        if limb != 0 {
            return (base + limb.trailing_zeros()).min(wb);
        }
    }
    wb
}

/// Solves `w * lead ≡ target (mod 2^prec)` for nonzero `target` masked to `pmask`.
fn solve_weights(
    w: crate::Width,
    prec: u32,
    pmask: &BitVec,
    target: &BitVec,
    lead: i8,
) -> Vec<BitVec> {
    let abs_lead = lead.unsigned_abs();
    let rhs = if lead < 0 {
        BitVec::bin_unchecked(BinOp::And, &BitVec::un_unchecked(UnOp::Neg, target), pmask)
    } else {
        *target
    };
    match abs_lead {
        1 => vec![rhs],
        3 => {
            let inv3 = odd_inverse_3(w);
            vec![BitVec::bin_unchecked(
                BinOp::And,
                &BitVec::bin_unchecked(BinOp::Mul, &rhs, &inv3),
                pmask,
            )]
        }
        2 => {
            if rhs.bit(0).unwrap_or(false) || prec < 2 {
                return Vec::new();
            }
            let shift1 = BitVec::one(w);
            let w0 = BitVec::bin_unchecked(BinOp::LShr, &rhs, &shift1);
            let hi = single_bit(w, prec - 1);
            vec![w0, BitVec::bin_unchecked(BinOp::Xor, &w0, &hi)]
        }
        4 => {
            if rhs.bit(0).unwrap_or(false) || rhs.bit(1).unwrap_or(false) || prec < 3 {
                return Vec::new();
            }
            let shift2 = BitVec::wrapping_from_u64(w, 2);
            let w0 = BitVec::bin_unchecked(BinOp::LShr, &rhs, &shift2);
            let step = single_bit(w, prec - 2);
            let mut out = Vec::with_capacity(4);
            let mut cur = w0;
            for _ in 0..4 {
                out.push(BitVec::bin_unchecked(BinOp::And, &cur, pmask));
                cur = BitVec::bin_unchecked(BinOp::Add, &cur, &step);
            }
            out
        }
        _ => Vec::new(),
    }
}

fn scale_cost(c: &BitVec, prec: u32, pmask: &BitVec) -> u32 {
    let w = c.width();
    let one = BitVec::one(w);
    if *c == one || *c == *pmask {
        return 0;
    }
    let neg_c = BitVec::bin_unchecked(BinOp::And, &BitVec::un_unchecked(UnOp::Neg, c), pmask);
    for cand in [c, &neg_c] {
        let tz = trailing_zeros(cand);
        if tz > 0 && tz < prec && *cand == single_bit(w, tz) {
            return 1;
        }
    }
    2
}

/// Spends `n` units of `work`; `None` (and nothing left) where it does not cover them.
fn spend(work: &mut u64, n: u64) -> Option<()> {
    match work.checked_sub(n) {
        Some(left) => {
            *work = left;
            Some(())
        }
        None => {
            *work = 0;
            None
        }
    }
}

/// The coefficients a residual at subset `sub_q` could line up with: those of the active
/// higher monomials `q2` (`q2 ⊃ sub_q`, `q2` not inside `pivot_q`), in order. `live` lists the
/// subsets whose coefficient is not zero: only those are read, a unit of `work` each (`None`
/// where that runs out).
fn others(
    alpha: &[BitVec],
    live: &[u32],
    pivot_q: usize,
    sub_q: usize,
    work: &mut u64,
) -> Option<Vec<BitVec>> {
    let above = &live[live.partition_point(|&q| q as usize <= sub_q)..];
    spend(work, above.len().max(1) as u64)?;
    let mut found: Vec<BitVec> = above
        .iter()
        .map(|&q2| q2 as usize)
        .filter(|&q2| (q2 & !pivot_q) != 0 && (q2 & sub_q) == sub_q)
        .map(|q2| alpha[q2])
        .collect();
    found.sort_unstable();
    found.dedup();
    Some(found)
}

/// Whether a residual coefficient `rem` lines up with one of `others` (see [`others`]), so
/// that a later step absorbs it: it is one of them, its negation, or twice either.
fn aligns_with_other(others: &[BitVec], rem: &BitVec, pmask: &BitVec) -> bool {
    if others.is_empty() {
        return false;
    }
    let w = rem.width();
    let neg_rem = BitVec::bin_unchecked(BinOp::And, &BitVec::un_unchecked(UnOp::Neg, rem), pmask);
    let two = BitVec::wrapping_from_u64(w, 2);
    let dbl = BitVec::bin_unchecked(
        BinOp::And,
        &BitVec::bin_unchecked(BinOp::Mul, rem, &two),
        pmask,
    );
    let neg_dbl = BitVec::bin_unchecked(BinOp::And, &BitVec::un_unchecked(UnOp::Neg, &dbl), pmask);
    [*rem, neg_rem, dbl, neg_dbl]
        .iter()
        .any(|v| others.binary_search(v).is_ok())
}

/// Decomposes conjunction coefficients `alpha[0 .. 1 << s]` (`alpha[0]` ignored; pass `konst`
/// separately) over `s` atoms (`1 <= s <= MAX_COBRA_ATOMS`) modulo `2^prec`.
///
/// Returns `Some(terms)` with `Σ_k weight_k · op_k ≡ Σ_{q>0} alpha[q] · AND_q (mod 2^prec)`.
///
/// `work` is what it may spend, a unit per coefficient it reads, and is left with what it did
/// not (the caller charges the difference): `None` where it runs out. A pivot over three
/// atoms tries every library entry and weight against the others' coefficients, so a
/// decomposition over ten atoms can read millions of them.
pub(crate) fn decompose(
    s: usize,
    w: crate::Width,
    prec: u32,
    alpha_in: &[BitVec],
    work: &mut u64,
) -> Option<Vec<(BasisOp, BitVec)>> {
    if s == 0 || s > MAX_COBRA_ATOMS || prec == 0 || alpha_in.len() != (1usize << s) {
        return None;
    }
    spend(work, 1 << s)?;
    let pmask = low_mask(w, prec);
    let mut alpha: Vec<BitVec> = alpha_in
        .iter()
        .enumerate()
        .map(|(q, c)| {
            if q == 0 {
                BitVec::zero(w)
            } else {
                BitVec::bin_unchecked(BinOp::And, c, &pmask)
            }
        })
        .collect();

    let mut terms: Vec<(BasisOp, BitVec)> = Vec::new();
    let lib = library();
    // The subsets whose coefficient is not zero, as each pivot finds them.
    let mut live: Vec<u32> = Vec::new();

    loop {
        spend(work, 1 << s)?;
        // Find maximum cardinality among remaining nonzero subsets, breaking ties by fewest
        // trailing zeros (odd coefficients first: unique modular lifts).
        let mut pivot: Option<(u32, u32, usize)> = None;
        live.clear();
        for (q, c) in alpha.iter().enumerate().skip(1) {
            if c.is_zero() {
                continue;
            }
            live.push(q as u32);
            let d = (q as u32).count_ones();
            let tz = trailing_zeros(c);
            let key = (d, u32::MAX - tz, usize::MAX - q);
            if pivot.is_none_or(|best| key > best) {
                pivot = Some(key);
            }
        }
        let Some((d, _, inv_q)) = pivot else {
            break;
        };
        if terms.len() >= MAX_BASIS_TERMS {
            return None;
        }
        let q_star = usize::MAX - inv_q;
        let d_usize = d as usize;

        if d_usize == 1 {
            let v = q_star.trailing_zeros() as usize;
            let weight = alpha[q_star];
            alpha[q_star] = BitVec::zero(w);
            push_term(&mut terms, BasisOp::Var(v), weight, &pmask);
            continue;
        }

        let mut vars = Vec::with_capacity(d_usize);
        for v in 0..s {
            if (q_star >> v) & 1 == 1 {
                vars.push(v);
            }
        }

        if d_usize == 2 || d_usize == 3 {
            let sub_len = 1usize << d_usize;
            let mut idx = [0usize; 8];
            for (u, slot) in idx.iter_mut().enumerate().take(sub_len) {
                let mut gq = 0usize;
                for (bit, &v) in vars.iter().enumerate() {
                    if (u >> bit) & 1 == 1 {
                        gq |= 1 << v;
                    }
                }
                *slot = gq;
            }

            // What a residual at each proper subset could line up with, read once for the
            // pivot (every entry and weight below asks).
            let mut beside: [Vec<BitVec>; 8] = Default::default();
            for u in 1..sub_len - 1 {
                beside[u] = others(&alpha, &live, q_star, idx[u], work)?;
            }
            let entries = if d_usize == 2 { &lib.two } else { &lib.three };
            let target = alpha[q_star];
            let full_u = sub_len - 1;
            let mut best: Option<(u32, u8, [i8; 8], BitVec)> = None;

            for entry in entries {
                let lead = entry.mobius[full_u];
                for weight in solve_weights(w, prec, &pmask, &target, lead) {
                    if weight.is_zero() {
                        continue;
                    }
                    spend(work, sub_len as u64)?;
                    let mut rem_cost = 0u32;
                    for u in 1..full_u {
                        let mu = entry.mobius[u];
                        let cur = alpha[idx[u]];
                        let rem = if mu == 0 {
                            cur
                        } else {
                            let delta =
                                BitVec::bin_unchecked(BinOp::Mul, &weight, &signed_bv(w, mu));
                            BitVec::bin_unchecked(
                                BinOp::And,
                                &BitVec::bin_unchecked(BinOp::Sub, &cur, &delta),
                                &pmask,
                            )
                        };
                        if !rem.is_zero() && !aligns_with_other(&beside[u], &rem, &pmask) {
                            rem_cost += 2 + ((u as u32).count_ones() - 1);
                        }
                    }
                    let score = u32::from(entry.ops) + scale_cost(&weight, prec, &pmask) + rem_cost;
                    if best.as_ref().is_none_or(|b| score < b.0) {
                        best = Some((score, entry.tt8, entry.mobius, weight));
                    }
                }
            }

            let Some((_, tt8, mob, weight)) = best else {
                // Fallback: raw conjunction `AND_{q_star}`.
                alpha[q_star] = BitVec::zero(w);
                push_term(
                    &mut terms,
                    BasisOp::ClauseAnd { vars, neg_mask: 0 },
                    target,
                    &pmask,
                );
                continue;
            };

            for u in 1..sub_len {
                let mu = mob[u];
                if mu == 0 {
                    continue;
                }
                let delta = BitVec::bin_unchecked(BinOp::Mul, &weight, &signed_bv(w, mu));
                alpha[idx[u]] = BitVec::bin_unchecked(
                    BinOp::And,
                    &BitVec::bin_unchecked(BinOp::Sub, &alpha[idx[u]], &delta),
                    &pmask,
                );
            }
            let op = if d_usize == 2 {
                BasisOp::Table2 {
                    vars: [vars[0], vars[1]],
                    tt8,
                }
            } else {
                BasisOp::Table3 {
                    vars: [vars[0], vars[1], vars[2]],
                    tt8,
                }
            };
            push_term(&mut terms, op, weight, &pmask);
            continue;
        }

        // `d >= 4`: test multi-way `OrAll` and negated-literal `ClauseAnd` against plain `AND_{q*}`.
        // (The sub-cube is read at most four times.)
        spend(work, 4 << d_usize)?;
        let target = alpha[q_star];
        let neg_target = BitVec::bin_unchecked(
            BinOp::And,
            &BitVec::un_unchecked(UnOp::Neg, &target),
            &pmask,
        );

        // 1. Check `OrAll(vars)`: `m[U] = (-1)^{|U|-1}`, so `m[q*] = (-1)^{d-1}`.
        let or_weight = if d_usize % 2 == 1 { target } else { neg_target };
        let sub_len = 1usize << d_usize;
        let map_sub = |u: usize| -> usize {
            let mut gq = 0usize;
            for (bit, &v) in vars.iter().enumerate() {
                if (u >> bit) & 1 == 1 {
                    gq |= 1 << v;
                }
            }
            gq
        };
        let mut before_nnz = 0usize;
        let mut or_after_nnz = 0usize;
        for u in 1..sub_len {
            let gq = map_sub(u);
            if !alpha[gq].is_zero() {
                before_nnz += 1;
            }
            let expected = if (u as u32).count_ones() % 2 == 1 {
                or_weight
            } else {
                BitVec::bin_unchecked(
                    BinOp::And,
                    &BitVec::un_unchecked(UnOp::Neg, &or_weight),
                    &pmask,
                )
            };
            if alpha[gq] != expected {
                or_after_nnz += 1;
            }
        }
        if or_after_nnz + 2 <= before_nnz {
            for u in 1..sub_len {
                let gq = map_sub(u);
                let delta = if (u as u32).count_ones() % 2 == 1 {
                    or_weight
                } else {
                    BitVec::bin_unchecked(
                        BinOp::And,
                        &BitVec::un_unchecked(UnOp::Neg, &or_weight),
                        &pmask,
                    )
                };
                alpha[gq] = BitVec::bin_unchecked(
                    BinOp::And,
                    &BitVec::bin_unchecked(BinOp::Sub, &alpha[gq], &delta),
                    &pmask,
                );
            }
            push_term(&mut terms, BasisOp::OrAll { vars }, or_weight, &pmask);
            continue;
        }

        // 2. Check `ClauseAnd` with negated literals (`alpha[q* \ {v}] == -alpha[q*]`).
        let mut neg_mask = 0u16;
        for (bit, &v) in vars.iter().enumerate() {
            if alpha[q_star ^ (1 << v)] == neg_target {
                neg_mask |= 1u16 << bit;
            }
        }
        let all_bits = (1u16 << d_usize) - 1;
        if neg_mask != 0 && neg_mask != all_bits {
            let pos_mask = all_bits ^ neg_mask;
            let clause_w = if neg_mask.count_ones().is_multiple_of(2) {
                target
            } else {
                neg_target
            };
            let neg_clause_w = BitVec::bin_unchecked(
                BinOp::And,
                &BitVec::un_unchecked(UnOp::Neg, &clause_w),
                &pmask,
            );
            let mut clause_after_nnz = 0usize;
            for u in 1..sub_len {
                let u16_mask = u as u16;
                let gq = map_sub(u);
                if (u16_mask & pos_mask) == pos_mask {
                    let expected = if (u16_mask & neg_mask).count_ones().is_multiple_of(2) {
                        clause_w
                    } else {
                        neg_clause_w
                    };
                    if alpha[gq] != expected {
                        clause_after_nnz += 1;
                    }
                } else if !alpha[gq].is_zero() {
                    clause_after_nnz += 1;
                }
            }
            if clause_after_nnz < before_nnz {
                for u in 1..sub_len {
                    let u16_mask = u as u16;
                    if (u16_mask & pos_mask) != pos_mask {
                        continue;
                    }
                    let gq = map_sub(u);
                    let delta = if (u16_mask & neg_mask).count_ones().is_multiple_of(2) {
                        clause_w
                    } else {
                        neg_clause_w
                    };
                    alpha[gq] = BitVec::bin_unchecked(
                        BinOp::And,
                        &BitVec::bin_unchecked(BinOp::Sub, &alpha[gq], &delta),
                        &pmask,
                    );
                }
                push_term(
                    &mut terms,
                    BasisOp::ClauseAnd { vars, neg_mask },
                    clause_w,
                    &pmask,
                );
                continue;
            }
        }

        // 3. Plain conjunction `AND_{q*}`.
        alpha[q_star] = BitVec::zero(w);
        push_term(
            &mut terms,
            BasisOp::ClauseAnd { vars, neg_mask: 0 },
            target,
            &pmask,
        );
    }

    Some(terms)
}

fn push_term(terms: &mut Vec<(BasisOp, BitVec)>, op: BasisOp, weight: BitVec, pmask: &BitVec) {
    if weight.is_zero() {
        return;
    }
    if let Some((_, existing)) = terms.iter_mut().find(|(o, _)| *o == op) {
        *existing = BitVec::bin_unchecked(
            BinOp::And,
            &BitVec::bin_unchecked(BinOp::Add, existing, &weight),
            pmask,
        );
        if existing.is_zero() {
            terms.retain(|(_, w)| !w.is_zero());
        }
        return;
    }
    terms.push((op, weight));
}

/// For unmasked (`FULL`) decompositions `konst + Σ c_i · B_i`, if `konst == c_i` for some term,
/// `c + c · B = (-c) · (~B)` eliminates the constant (`-7 - 7·(x | y) = 7·~(x | y)`).
pub(crate) fn trade_unmasked_constant(konst: &mut BitVec, terms: &mut [(BasisOp, BitVec)]) {
    if konst.is_zero() {
        return;
    }
    if let Some(i) = terms.iter().position(|(_, c)| *c == *konst) {
        let neg_c = BitVec::un_unchecked(UnOp::Neg, &terms[i].1);
        let old_op = core::mem::replace(&mut terms[i].0, BasisOp::Var(0));
        terms[i].0 = match old_op {
            BasisOp::Not(inner) => *inner,
            other => BasisOp::Not(Box::new(other)),
        };
        terms[i].1 = neg_c;
        *konst = BitVec::zero(konst.width());
    }
}