smtlite 0.2.0

A small, pure-Rust QF_BV SMT solver: bitvector expressions bit-blasted to CNF and solved by a self-contained DPLL core.
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
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
//! The bit-blaster: lower a `Bv` DAG (and asserted 1-bit constraints) to CNF.
//!
//! Each bit of each node becomes a SAT literal; operations are encoded with Tseitin gates
//! (AND/OR/XOR), arithmetic with ripple-carry adders, and unsigned comparison via the
//! carry-out of `a + ¬b + 1` (which is 1 iff `a ≥ b`). Shared subgraphs are memoised on the
//! `Rc` pointer so a value used twice is encoded once. Bit vectors are little-endian:
//! index 0 is the least-significant bit.
//!
//! Pointer sharing is not the only sharing that matters. Terms built twice from the same
//! inputs - a caller's `x == y` and a theory lemma's `y == x`, say - are distinct `Rc`s with
//! one meaning, and encoding them as two circuits makes the solver *prove* they agree. That
//! is cheap for a CDCL solver and exponential for this learning-free DPLL, so the blaster
//! also interning **structurally**: each distinct (operation, width, parameters, canonical
//! child) shape maps to the first circuit built for it, with commutative operands normalized.
//! Two structurally identical terms therefore share one SAT encoding, and a lemma that
//! restates an asserted equality resolves by unit propagation instead of a search.
//!
//! A wall-clock deadline and a clause cap bound the blast itself, not only the search over its
//! result: once either trips, [`Blaster::encode`] hands back width-correct dummy literals
//! instead of clauses, and the caller bails to `Unknown` before any solve sees them.

use std::collections::HashMap;
use std::rc::Rc;
use std::time::Instant;

use crate::bv::{Bv, Cmp, Node, Op};
use crate::sat::Cnf;

/// The structural identity of a term: what it is made of, not which `Rc` holds it.
///
/// Children are canonical ids, so two terms are one shape exactly when their operands are
/// one shape. Commutative operations are normalized by sorting their child ids, which is
/// why `a == b` and `b == a` land on the same key.
#[derive(Clone, PartialEq, Eq, Hash)]
struct ShapeKey {
    tag: u8,
    width: u32,
    /// The leaf value, shift/rotate amount, comparison kind, or flags - meaning depends on `tag`.
    arg: u128,
    kids: Vec<usize>,
}

/// The `Op` discriminant for a [`ShapeKey`].
fn op_tag(op: Op) -> u128 {
    match op {
        Op::And => 0,
        Op::Or => 1,
        Op::Xor => 2,
        Op::Add => 3,
        Op::Sub => 4,
        Op::Mul => 5,
        Op::Udiv => 6,
        Op::Urem => 7,
        Op::Sdiv => 8,
        Op::Srem => 9,
    }
}

/// The `Cmp` discriminant for a [`ShapeKey`].
fn cmp_tag(cmp: Cmp) -> u128 {
    match cmp {
        Cmp::Eq => 0,
        Cmp::Ne => 1,
        Cmp::Ult => 2,
        Cmp::Ule => 3,
        Cmp::Slt => 4,
        Cmp::Sle => 5,
    }
}

pub(crate) struct Blaster<'b> {
    pub cnf: Cnf<'b>,
    true_lit: i32,
    memo: HashMap<usize, Vec<i32>>,
    /// Canonical id per `Rc` pointer: the structural dedup cache for term shapes.
    canon: HashMap<usize, usize>,
    /// The intern table: one canonical id per distinct [`ShapeKey`].
    shapes: HashMap<ShapeKey, usize>,
    /// Bit literals per canonical id: the circuit-sharing cache.
    struct_memo: HashMap<usize, Vec<i32>>,
    /// Bit literals for each named variable id, so a model can be read back.
    pub var_bits: HashMap<usize, Vec<i32>>,
    /// Optional wall-clock deadline checked while blasting, so the encode phase degrades to
    /// dummies instead of burning unbounded time before the search's own deadline check.
    pub deadline: Option<Instant>,
}

impl<'b> Blaster<'b> {
    pub fn new(bump: &'b bumpalo::Bump) -> Self {
        let mut cnf = Cnf::new(bump);
        let true_lit = cnf.new_var();
        cnf.add_clause(&[true_lit]); // pin it true, so its negation is a constant false
        Self {
            cnf,
            true_lit,
            memo: HashMap::new(),
            canon: HashMap::new(),
            shapes: HashMap::new(),
            struct_memo: HashMap::new(),
            var_bits: HashMap::new(),
            deadline: None,
        }
    }

    /// Has the wall-clock deadline elapsed? Callers must treat an over-the-clock blaster as
    /// producing garbage: its results are width-correct dummy literals, to be bailed out of
    /// before any solve sees them.
    fn over(&self) -> bool {
        self.deadline.is_some_and(|d| Instant::now() >= d)
    }

    fn t(&self) -> i32 {
        self.true_lit
    }
    fn f(&self) -> i32 {
        -self.true_lit
    }

    /// Allocate the SAT bits for a declared variable up front, so it reads back in a model even
    /// when no constraint mentions it. Idempotent per `id`: a repeat call keeps the original bits.
    pub fn declare_var(&mut self, id: usize, width: u32) {
        if self.var_bits.contains_key(&id) {
            return;
        }
        let bits: Vec<i32> = (0..width).map(|_| self.cnf.new_var()).collect();
        self.var_bits.insert(id, bits);
    }

    /// The canonical id of a term's shape, interning it on first sight.
    ///
    /// The traversal is cached per `Rc` pointer, so a shared DAG is walked once. Children
    /// are canonicalized first, which is what makes the key structural rather than
    /// pointer-identity; commutative operands are sorted so `a == b` and `b == a` intern
    /// to one id.
    fn canon_id(&mut self, bv: &Bv) -> usize {
        let ptr = Rc::as_ptr(&bv.0) as usize;
        if let Some(&id) = self.canon.get(&ptr) {
            return id;
        }
        let width = bv.width();
        let (tag, arg, kids) = match &*bv.0 {
            Node::Const(_, v) => (0, *v, Vec::new()),
            Node::Var(_, id) => (1, *id as u128, Vec::new()),
            Node::Not(x) => (2, 0, vec![self.canon_id(x)]),
            Node::Neg(x) => (3, 0, vec![self.canon_id(x)]),
            Node::Bin(op, x, y) => {
                let (mut l, mut r) = (self.canon_id(x), self.canon_id(y));
                if matches!(op, Op::And | Op::Or | Op::Xor | Op::Add | Op::Mul) && l > r {
                    std::mem::swap(&mut l, &mut r);
                }
                (4, op_tag(*op), vec![l, r])
            }
            Node::ShlC(x, k) => (5, *k as u128, vec![self.canon_id(x)]),
            Node::ShrC(x, k, arith) => (
                6,
                (*k as u128) | ((u128::from(*arith)) << 32),
                vec![self.canon_id(x)],
            ),
            Node::ShlV(x, k) => (7, 0, vec![self.canon_id(x), self.canon_id(k)]),
            Node::ShrV(x, k, arith) => (
                8,
                u128::from(*arith),
                vec![self.canon_id(x), self.canon_id(k)],
            ),
            Node::RotC(x, k, left) => (
                9,
                (*k as u128) | ((u128::from(*left)) << 32),
                vec![self.canon_id(x)],
            ),
            Node::RotV(x, k, left) => (
                10,
                u128::from(*left),
                vec![self.canon_id(x), self.canon_id(k)],
            ),
            Node::Compare(cmp, x, y) => {
                let (mut l, mut r) = (self.canon_id(x), self.canon_id(y));
                if matches!(cmp, Cmp::Eq | Cmp::Ne) && l > r {
                    std::mem::swap(&mut l, &mut r);
                }
                (11, cmp_tag(*cmp), vec![l, r])
            }
            Node::Zext(x, to) => (12, *to as u128, vec![self.canon_id(x)]),
            Node::Sext(x, to) => (13, *to as u128, vec![self.canon_id(x)]),
            Node::Extract(x, hi, lo) => (
                14,
                ((*hi as u128) << 32) | (*lo as u128),
                vec![self.canon_id(x)],
            ),
            Node::Concat(hi, lo) => (15, 0, vec![self.canon_id(hi), self.canon_id(lo)]),
            Node::Ite(c, t, e) => (
                16,
                0,
                vec![self.canon_id(c), self.canon_id(t), self.canon_id(e)],
            ),
        };
        let key = ShapeKey {
            tag,
            width,
            arg,
            kids,
        };
        let next = self.shapes.len();
        let id = *self.shapes.entry(key).or_insert(next);
        self.canon.insert(ptr, id);
        id
    }

    /// `a ∧ b`, folded when an operand is the pinned-true/false literal or the
    /// operands are the same/opposite literal.
    ///
    /// The fold is not cosmetic: every adder's carry-in is the constant false
    /// literal and the ripple chain threads it, so without folding each full
    /// adder costs five clauses where two suffice. Arithmetic circuits here
    /// are built almost entirely out of gates with a constant on one side
    /// (adder carries, `const_bits`, the zero-filled high half of a shift), so
    /// the whole family shrinks with it.
    fn and(&mut self, a: i32, b: i32) -> i32 {
        let (t, f) = (self.true_lit, -self.true_lit);
        if a == t {
            return b;
        }
        if b == t {
            return a;
        }
        if a == f || b == f {
            return f;
        }
        if a == b {
            return a;
        }
        if a == -b {
            return f;
        }
        let o = self.cnf.new_var();
        self.cnf.add_clause(&[-o, a]);
        self.cnf.add_clause(&[-o, b]);
        self.cnf.add_clause(&[o, -a, -b]);
        o
    }
    fn or(&mut self, a: i32, b: i32) -> i32 {
        let (t, f) = (self.true_lit, -self.true_lit);
        if a == t || b == t {
            return t;
        }
        if a == f {
            return b;
        }
        if b == f {
            return a;
        }
        if a == b {
            return a;
        }
        if a == -b {
            return t;
        }
        let o = self.cnf.new_var();
        self.cnf.add_clause(&[o, -a]);
        self.cnf.add_clause(&[o, -b]);
        self.cnf.add_clause(&[-o, a, b]);
        o
    }
    fn xor(&mut self, a: i32, b: i32) -> i32 {
        let (t, f) = (self.true_lit, -self.true_lit);
        if a == f {
            return b;
        }
        if b == f {
            return a;
        }
        if a == t {
            return -b;
        }
        if b == t {
            return -a;
        }
        if a == b {
            return f;
        }
        if a == -b {
            return t;
        }
        let o = self.cnf.new_var();
        self.cnf.add_clause(&[-o, -a, -b]);
        self.cnf.add_clause(&[-o, a, b]);
        self.cnf.add_clause(&[o, -a, b]);
        self.cnf.add_clause(&[o, a, -b]);
        o
    }

    fn full_adder(&mut self, a: i32, b: i32, cin: i32) -> (i32, i32) {
        let axb = self.xor(a, b);
        let sum = self.xor(axb, cin);
        let ab = self.and(a, b);
        let axb_cin = self.and(axb, cin);
        let cout = self.or(ab, axb_cin);
        (sum, cout)
    }

    fn add_bits(&mut self, a: &[i32], b: &[i32], cin: i32) -> (Vec<i32>, i32) {
        let mut carry = cin;
        let mut out = Vec::with_capacity(a.len());
        for i in 0..a.len() {
            let (s, c) = self.full_adder(a[i], b[i], carry);
            out.push(s);
            carry = c;
        }
        (out, carry)
    }

    /// Unsigned `a < b`: NOT the carry-out of `a + ¬b + 1`.
    fn ult_bits(&mut self, a: &[i32], b: &[i32]) -> i32 {
        let not_b: Vec<i32> = b.iter().map(|&l| -l).collect();
        let (_, cout) = self.add_bits(a, &not_b, self.t());
        -cout
    }

    fn eq_bits(&mut self, a: &[i32], b: &[i32]) -> i32 {
        let mut acc = self.t();
        for i in 0..a.len() {
            let x = self.xor(a[i], b[i]);
            acc = self.and(acc, -x); // -x is XNOR (bits equal)
        }
        acc
    }

    /// Encode a value to its bit literals (LSB first).
    ///
    /// This is the memoization entry every node routes through, so it is also where the bounds
    /// take effect: once the deadline has elapsed or the clause cap has cut generation off, the
    /// blaster hands back width-correct pinned-false dummies instead of encoding. Dummies are
    /// memoised like any result, and every caller bails to `Unknown` before a solve, so they
    /// never reach the solver.
    pub fn encode(&mut self, bv: &Bv) -> Vec<i32> {
        let key = Rc::as_ptr(&bv.0) as usize;
        if let Some(bits) = self.memo.get(&key) {
            return bits.clone();
        }
        // Pointer-identity sharing first (cheapest), then structural sharing: terms
        // built separately from the same inputs are one circuit.
        let shape = self.canon_id(bv);
        if let Some(bits) = self.struct_memo.get(&shape) {
            self.memo.insert(key, bits.clone());
            return bits.clone();
        }
        let bits = if self.over() || self.cnf.full {
            vec![self.f(); bv.width() as usize]
        } else {
            self.encode_node(bv)
        };
        self.memo.insert(key, bits.clone());
        self.struct_memo.insert(shape, bits.clone());
        bits
    }

    fn encode_node(&mut self, bv: &Bv) -> Vec<i32> {
        let w = bv.width() as usize;
        match &*bv.0 {
            Node::Const(_, v) => (0..w)
                .map(|i| {
                    if (v >> i) & 1 == 1 {
                        self.t()
                    } else {
                        self.f()
                    }
                })
                .collect(),
            Node::Var(_, id) => {
                // Bits are normally pre-allocated by `declare_var`; allocate on demand only if a
                // variable reaches the blaster without that (keeps `encode` usable on its own).
                match self.var_bits.get(id) {
                    Some(bits) => bits.clone(),
                    None => {
                        let bits: Vec<i32> = (0..w).map(|_| self.cnf.new_var()).collect();
                        self.var_bits.insert(*id, bits.clone());
                        bits
                    }
                }
            }
            Node::Not(a) => self.encode(a).iter().map(|&l| -l).collect(),
            Node::Neg(a) => {
                let ab: Vec<i32> = self.encode(a).iter().map(|&l| -l).collect();
                let zero = vec![self.f(); w];
                self.add_bits(&ab, &zero, self.t()).0 // ¬a + 1
            }
            Node::Bin(op, a, b) => {
                // Unsigned division (and remainder) by a power of two is a
                // re-indexing of the dividend's bits: no divider at all. The
                // restoring divider would charge O(w^2) clauses for a `>> k`
                // the program is about to do anyway, and `Bv` already folds a
                // wholly constant pair, so this fires only when the dividend
                // is symbolic.
                if matches!(op, Op::Udiv | Op::Urem)
                    && let Some(c) = b.as_const()
                    && c.is_power_of_two()
                {
                    let ab = self.encode(a);
                    let k = c.trailing_zeros() as usize;
                    let f = self.f();
                    return (0..w)
                        .map(|i| match op {
                            Op::Udiv if i + k < w => ab[i + k],
                            Op::Udiv => f,
                            _ if i < k => ab[i],
                            _ => f,
                        })
                        .collect();
                }
                let (ab, bb) = (self.encode(a), self.encode(b));
                // Division trims statically-zero high bits: an engine that
                // widens a `u64` to `u128` by zero-extension hands over an
                // operand whose top half is the pinned-false literal, and the
                // wide restoring divider would spend four times the gates
                // proving that a < 2^64. With `k` such bits on both operands,
                // both the quotient and the remainder fit in `w - k` bits, so
                // the divider runs at that width and the result is
                // zero-extended. A zero divisor is the one case the narrow
                // circuit answers differently at the wider width (all-ones
                // rather than all-ones-narrow zero-extended; the remainder is
                // the *whole* dividend), so it is muxed back in.
                if matches!(op, Op::Udiv | Op::Urem) {
                    let f = self.f();
                    let k = known_zero_high(&ab, f).min(known_zero_high(&bb, f));
                    if k > 0 && k < w {
                        let n = w - k;
                        let (q, r) = self.udivrem_bits(&ab[..n], &bb[..n]);
                        let mut wide = if matches!(op, Op::Udiv) { q } else { r };
                        wide.resize(w, f);
                        let bzero = self.eq_bits(&bb[..n], &vec![f; n]);
                        let on_zero = if matches!(op, Op::Udiv) {
                            vec![self.t(); w]
                        } else {
                            ab.clone()
                        };
                        return self.mux_vec(bzero, &on_zero, &wide);
                    }
                }
                match op {
                    Op::And => (0..w).map(|i| self.and(ab[i], bb[i])).collect(),
                    Op::Or => (0..w).map(|i| self.or(ab[i], bb[i])).collect(),
                    Op::Xor => (0..w).map(|i| self.xor(ab[i], bb[i])).collect(),
                    Op::Add => self.add_bits(&ab, &bb, self.f()).0,
                    Op::Sub => {
                        let not_b: Vec<i32> = bb.iter().map(|&l| -l).collect();
                        self.add_bits(&ab, &not_b, self.t()).0
                    }
                    Op::Mul => self.mul_bits(&ab, &bb),
                    Op::Udiv => self.udivrem_bits(&ab, &bb).0,
                    Op::Urem => self.udivrem_bits(&ab, &bb).1,
                    Op::Sdiv => self.sdiv_bits(&ab, &bb),
                    Op::Srem => self.srem_bits(&ab, &bb),
                }
            }
            Node::ShlC(a, k) => {
                let ab = self.encode(a);
                let k = *k as usize;
                (0..w)
                    .map(|i| if i < k { self.f() } else { ab[i - k] })
                    .collect()
            }
            Node::ShrC(a, k, arith) => {
                let ab = self.encode(a);
                let k = *k as usize;
                let fill = if *arith { ab[w - 1] } else { self.f() };
                (0..w)
                    .map(|i| if i + k < w { ab[i + k] } else { fill })
                    .collect()
            }
            Node::ShlV(a, k) => {
                let ab = self.encode(a);
                let kb = self.encode(k);
                self.shift_var_bits(&ab, &kb, ShKind::Left)
            }
            Node::ShrV(a, k, arith) => {
                let ab = self.encode(a);
                let kb = self.encode(k);
                let kind = if *arith {
                    ShKind::Aright
                } else {
                    ShKind::Lright
                };
                self.shift_var_bits(&ab, &kb, kind)
            }
            Node::RotC(a, k, left) => {
                let ab = self.encode(a);
                rot_const(&ab, *k, *left)
            }
            Node::RotV(a, k, left) => {
                let ab = self.encode(a);
                let kb = self.encode(k);
                self.rot_var_bits(&ab, &kb, *left)
            }
            Node::Compare(c, a, b) => {
                let (ab, bb) = (self.encode(a), self.encode(b));
                let bit = match c {
                    Cmp::Eq => self.eq_bits(&ab, &bb),
                    Cmp::Ne => -self.eq_bits(&ab, &bb),
                    Cmp::Ult => self.ult_bits(&ab, &bb),
                    Cmp::Ule => {
                        let lt = self.ult_bits(&ab, &bb);
                        let eq = self.eq_bits(&ab, &bb);
                        self.or(lt, eq)
                    }
                    Cmp::Slt => self.slt_bits(&ab, &bb),
                    Cmp::Sle => {
                        let lt = self.slt_bits(&ab, &bb);
                        let eq = self.eq_bits(&ab, &bb);
                        self.or(lt, eq)
                    }
                };
                vec![bit]
            }
            Node::Zext(a, _) => {
                let mut bits = self.encode(a);
                bits.resize(w, self.f());
                bits
            }
            Node::Sext(a, _) => {
                let ab = self.encode(a);
                let sign = *ab.last().unwrap_or(&self.f());
                let mut bits = ab.clone();
                bits.resize(w, sign);
                bits
            }
            Node::Extract(a, hi, lo) => {
                let ab = self.encode(a);
                ab[*lo as usize..=*hi as usize].to_vec()
            }
            Node::Concat(hi, lo) => {
                let mut bits = self.encode(lo);
                bits.extend(self.encode(hi));
                bits
            }
            Node::Ite(cond, then, els) => {
                let c = self.encode(cond)[0];
                let (tb, eb) = (self.encode(then), self.encode(els));
                (0..w)
                    .map(|i| {
                        let a = self.and(c, tb[i]);
                        let b = self.and(-c, eb[i]);
                        self.or(a, b)
                    })
                    .collect()
            }
        }
    }

    /// Signed `a < b`: flip the sign bits, then compare unsigned.
    fn slt_bits(&mut self, a: &[i32], b: &[i32]) -> i32 {
        let top = a.len() - 1;
        let mut aa = a.to_vec();
        let mut bb = b.to_vec();
        aa[top] = -aa[top];
        bb[top] = -bb[top];
        self.ult_bits(&aa, &bb)
    }

    /// Schoolbook multiply, truncated to the operand width.
    fn mul_bits(&mut self, a: &[i32], b: &[i32]) -> Vec<i32> {
        let w = a.len();
        let mut acc = vec![self.f(); w];
        for (j, &bj) in b.iter().enumerate() {
            // One outer iteration emits O(w) clauses, so the deadline is worth a look here.
            if self.over() {
                return vec![self.f(); w];
            }
            let mut partial = vec![self.f(); w];
            for i in 0..(w - j) {
                partial[i + j] = self.and(a[i], bj);
            }
            acc = self.add_bits(&acc, &partial, self.f()).0;
        }
        acc
    }

    // ---- Division ----------------------------------------------------------------

    /// A 2:1 mux on two literals: `c ? t : e`.
    fn mux(&mut self, c: i32, t: i32, e: i32) -> i32 {
        let (tl, fl) = (self.true_lit, -self.true_lit);
        if c == tl {
            return t;
        }
        if c == fl {
            return e;
        }
        if t == e {
            return t;
        }
        if t == tl && e == fl {
            return c;
        }
        if t == fl && e == tl {
            return -c;
        }
        // The one-sided constant forms, as their two-gate equivalents.
        if t == tl {
            return self.or(c, e); // c ∨ e
        }
        if e == fl {
            return self.and(c, t); // c ∧ t
        }
        if t == fl {
            return self.and(-c, e); // ¬c ∧ e
        }
        if e == tl {
            return self.or(-c, t); // ¬c ∨ t
        }
        let a = self.and(c, t);
        let b = self.and(-c, e);
        self.or(a, b)
    }

    /// Bitwise mux of two equal-length bit vectors.
    fn mux_vec(&mut self, c: i32, t: &[i32], e: &[i32]) -> Vec<i32> {
        let mut out = Vec::with_capacity(t.len());
        for i in 0..t.len() {
            let (ti, ei) = (t[i], e[i]);
            out.push(self.mux(c, ti, ei));
        }
        out
    }

    /// Bit literals for the constant `v`, zero-extended (or truncated) to `w` bits.
    fn const_bits(&mut self, v: u64, w: usize) -> Vec<i32> {
        (0..w)
            .map(|i| {
                if (v >> i) & 1 == 1 {
                    self.t()
                } else {
                    self.f()
                }
            })
            .collect()
    }

    /// Two's-complement absolute value: `sign ? -a : a`.
    fn abs_bits(&mut self, a: &[i32]) -> Vec<i32> {
        let w = a.len();
        let sign = a[w - 1];
        let na: Vec<i32> = a.iter().map(|&l| -l).collect();
        let zero = vec![self.f(); w];
        let neg = self.add_bits(&na, &zero, self.t()).0;
        self.mux_vec(sign, &neg, a)
    }

    /// Radix-2 restoring division: `(quotient, remainder)` of unsigned `a / b`.
    ///
    /// Each step shifts one dividend bit into a `w+1`-bit remainder and conditionally subtracts
    /// `b`. The carry-out of `rem + ¬b + 1` is exactly `rem >= b`, so a single adder per step
    /// yields both the difference and the comparison - no separate comparator is needed.
    ///
    /// A zero divisor needs no special case: `rem >= 0` always holds, so every quotient bit is 1
    /// (all-ones, SMT-LIB `bvudiv`) and the remainder ends up holding `a` (SMT-LIB `bvurem`).
    fn udivrem_bits(&mut self, a: &[i32], b: &[i32]) -> (Vec<i32>, Vec<i32>) {
        let w = a.len();
        let mut rem = vec![self.f(); w + 1]; // one extra bit: the shifted-in bit always fits
        let mut bext = b.to_vec();
        bext.push(self.f()); // zero-extend b to w+1 so the adder widths match
        let not_b: Vec<i32> = bext.iter().map(|&l| -l).collect();
        let mut quot = vec![self.f(); w];
        for i in (0..w).rev() {
            // One division step emits O(w) clauses, so the deadline is worth a look here. The
            // dummies match the *return* width - two w-bit vectors - not the internal w+1: a
            // w+1 remainder would blow the index arithmetic of callers like `srem_bits`.
            if self.over() {
                return (vec![self.f(); w], vec![self.f(); w]);
            }
            // Fold the next dividend bit in. Little-endian, so it is *less* significant than
            // everything in `rem`: index 0, the rest slides up - `rem << 1 | a[i]` reversed.
            let mut shifted = Vec::with_capacity(w + 1);
            shifted.push(a[i]);
            shifted.extend_from_slice(&rem[0..w]);
            rem = shifted;
            let (diff, carry) = self.add_bits(&rem, &not_b, self.t());
            let ge = carry; // carry-out of rem + ¬b + 1  ==  rem >= b
            rem = self.mux_vec(ge, &diff, &rem);
            quot[i] = ge;
        }
        // The invariant rem < b <= 2^w - 1 keeps the remainder inside the low w bits.
        (quot, rem[0..w].to_vec())
    }

    /// Signed division: divide the magnitudes, then re-apply the sign (SMT-LIB `bvsdiv`).
    fn sdiv_bits(&mut self, a: &[i32], b: &[i32]) -> Vec<i32> {
        let w = a.len();
        let (aa, bb) = (self.abs_bits(a), self.abs_bits(b));
        let (q, _) = self.udivrem_bits(&aa, &bb);
        let nq: Vec<i32> = q.iter().map(|&l| -l).collect();
        let zero = vec![self.f(); w];
        let neg_q = self.add_bits(&nq, &zero, self.t()).0;
        let sign = self.xor(a[w - 1], b[w - 1]);
        let quotient = self.mux_vec(sign, &neg_q, &q);
        // A zero divisor yields all-ones for a non-negative dividend, and 1 otherwise.
        let bzero = self.eq_bits(b, &vec![self.f(); w]);
        let one = self.const_bits(1, w);
        let all_ones = vec![self.t(); w];
        let on_zero = self.mux_vec(a[w - 1], &one, &all_ones);
        self.mux_vec(bzero, &on_zero, &quotient)
    }

    /// Signed remainder, taking the sign of the **dividend** (SMT-LIB `bvsrem` - C's `%`).
    fn srem_bits(&mut self, a: &[i32], b: &[i32]) -> Vec<i32> {
        let w = a.len();
        let (aa, bb) = (self.abs_bits(a), self.abs_bits(b));
        let (_, r) = self.udivrem_bits(&aa, &bb);
        let nr: Vec<i32> = r.iter().map(|&l| -l).collect();
        let zero = vec![self.f(); w];
        let neg_r = self.add_bits(&nr, &zero, self.t()).0;
        let rem = self.mux_vec(a[w - 1], &neg_r, &r);
        // A zero divisor yields the dividend.
        let bzero = self.eq_bits(b, &vec![self.f(); w]);
        self.mux_vec(bzero, a, &rem)
    }

    // ---- Symbolic shifts and rotates ---------------------------------------------

    /// Barrel shifter for a symbolic amount: `stages` conditionally shift by 1, 2, 4, ...
    ///
    /// An amount at or beyond the width does **not** wrap - every bit takes the fill (zero for
    /// `<<`/`>>u`, the sign bit for `>>s`), which is SMT-LIB shift semantics as opposed to a
    /// rotate's.
    fn shift_var_bits(&mut self, a: &[i32], k: &[i32], kind: ShKind) -> Vec<i32> {
        let w = a.len();
        let f = self.f();
        let stages = shift_stages(w);
        let mut cur = a.to_vec();
        for j in 0..stages {
            // One barrel stage emits O(w) clauses, so the deadline is worth a look here.
            if self.over() {
                return vec![f; w];
            }
            // k narrower than the barrel: its higher bits are zero, so those stages never fire.
            let Some(&sel) = k.get(j) else { break };
            let sh = 1usize << j;
            let mut moved = Vec::with_capacity(w);
            for i in 0..w {
                moved.push(match kind {
                    ShKind::Left => {
                        if i >= sh {
                            cur[i - sh]
                        } else {
                            f
                        }
                    }
                    ShKind::Lright => {
                        if i + sh < w {
                            cur[i + sh]
                        } else {
                            f
                        }
                    }
                    ShKind::Aright => {
                        if i + sh < w {
                            cur[i + sh]
                        } else {
                            cur[w - 1]
                        }
                    }
                });
            }
            cur = self.mux_vec(sel, &moved, &cur);
        }
        // `k >= w` replaces the entire result with the fill value.
        let mut overflow = f;
        for &bit in k.iter().skip(stages) {
            overflow = self.or(overflow, bit);
        }
        if stages > 0 && (1usize << stages) != w {
            // The width is not a power of two, so an amount below 2^stages can still reach it.
            let low: Vec<i32> = (0..stages)
                .map(|j| k.get(j).copied().unwrap_or(f))
                .collect();
            let wbits = self.const_bits(w as u64, stages);
            let ge = -self.ult_bits(&low, &wbits);
            overflow = self.or(overflow, ge);
        }
        let fill = match kind {
            ShKind::Aright => a[w - 1],
            ShKind::Left | ShKind::Lright => f,
        };
        let mut out = Vec::with_capacity(w);
        for &c in &cur {
            out.push(self.mux(overflow, fill, c));
        }
        out
    }

    /// Barrel rotator for a symbolic amount. A rotate is periodic in the width and never has a
    /// fill, so unlike a shift it has no out-of-range case to handle.
    fn rot_var_bits(&mut self, a: &[i32], k: &[i32], left: bool) -> Vec<i32> {
        let w = a.len();
        let f = self.f();
        let stages = shift_stages(w);
        if stages == 0 {
            return a.to_vec(); // width 1: every rotation is the identity
        }
        let amount: Vec<i32> = if (1usize << stages) == w {
            // Power-of-two width: the low `stages` bits already are `k mod w`.
            (0..stages)
                .map(|j| k.get(j).copied().unwrap_or(f))
                .collect()
        } else {
            // Otherwise reduce the amount modulo the width explicitly. The divider runs at the
            // wider operand rather than truncating `k` to `w` bits: `k mod w` depends on every bit
            // of `k`, and truncating is wrong whenever `w` does not divide `2^w` (w=5, k=32
            // truncates to 0, but 32 mod 5 = 2).
            let m = w.max(k.len());
            let mut kext = k.to_vec();
            kext.resize(m, f);
            let wc = self.const_bits(w as u64, m);
            let (_, r) = self.udivrem_bits(&kext, &wc);
            r[0..stages].to_vec() // r < w <= 2^stages, so it fits in `stages` bits
        };
        let mut cur = a.to_vec();
        // `amount` is exactly `stages` bits in both branches, so this walks the barrel one
        // stage at a time.
        for (j, &sel) in amount.iter().enumerate() {
            // One barrel stage emits O(w) clauses, so the deadline is worth a look here.
            if self.over() {
                return vec![f; w];
            }
            let sh = (1usize << j) % w;
            let mut rotated = Vec::with_capacity(w);
            for i in 0..w {
                rotated.push(if left {
                    cur[(i + w - sh) % w]
                } else {
                    cur[(i + sh) % w]
                });
            }
            cur = self.mux_vec(sel, &rotated, &cur);
        }
        cur
    }

    /// Require a 1-bit value to be true, as a unit clause on its single literal.
    ///
    /// # Panics
    ///
    /// Panics if `bv` is not 1 bit wide.
    pub fn assert_true(&mut self, bv: &Bv) {
        assert_eq!(
            bv.width(),
            1,
            "a constraint must be 1 bit, got {}",
            bv.width()
        );
        let bits = self.encode(bv);
        self.cnf.add_clause(&[bits[0]]);
    }
}

/// How many high bits of an encoded operand are the pinned-false literal -
/// statically known zero, no search involved.
///
/// A zero-extension (`concat(0, x)`) and a constant mask both encode their
/// high zeros to exactly this literal, so this is the cheap static range
/// information the blaster can act on: `u128` arithmetic whose operands are
/// widened `u64`s is really 64-bit arithmetic, and here it can be blasted as
/// such.
fn known_zero_high(bits: &[i32], f: i32) -> usize {
    bits.iter().rev().take_while(|&&l| l == f).count()
}

/// Which way a symbolic shift moves, and therefore what it fills vacated bits with.
#[derive(Clone, Copy, PartialEq, Eq)]
enum ShKind {
    Left,
    Lright,
    Aright,
}

/// The number of barrel stages needed to reach every amount below `w`: the smallest `s` with
/// `2^s >= w`. Width 1 needs none; 8 needs 3; 64 needs 6.
fn shift_stages(w: usize) -> usize {
    let mut stages = 0;
    let mut span = 1usize;
    while span < w {
        span <<= 1;
        stages += 1;
    }
    stages
}

/// Rotate a bit vector by a constant amount - a pure re-indexing, costing no gates.
fn rot_const(a: &[i32], k: u32, left: bool) -> Vec<i32> {
    let w = a.len();
    let sh = (k as usize) % w;
    (0..w)
        .map(|i| {
            if left {
                a[(i + w - sh) % w]
            } else {
                a[(i + sh) % w]
            }
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::bv::Node;

    /// A symbolic operand: a `Var` node, the shape every conformance proof must keep.
    fn var(w: u32, id: usize) -> Bv {
        Bv::wrap(Node::Var(w, id))
    }

    /// How many clauses blasting `bv` emits, not counting the blaster's pinned-true unit.
    ///
    /// This is the direct measurement behind the coverage guards in tests/ops.rs: an operation
    /// on symbolic operands must produce a circuit of this order, while the same operation on
    /// constant operands folds at construction and produces none of it.
    fn circuit_size(bv: &Bv) -> usize {
        let bump = bumpalo::Bump::new();
        let mut b = Blaster::new(&bump);
        b.encode(bv);
        b.cnf.clauses.len() - 1
    }

    #[test]
    fn symbolic_operands_generate_the_real_circuits() {
        let (x, y) = (var(64, 0), var(64, 1));

        let measured: [(&str, usize); 7] = [
            ("udiv64", circuit_size(&x.udiv(&y))),
            ("sdiv64", circuit_size(&x.sdiv(&y))),
            ("mul64", circuit_size(&x.mul(&y))),
            ("shl_var64", circuit_size(&x.shl_var(&y))),
            ("rot_var64", circuit_size(&x.rotl_var(&y))),
            ("sgt64", circuit_size(&x.sgt(&y))),
            (
                "rot_var5 (modulo-divider path)",
                circuit_size(&var(5, 0).rotl_var(&var(5, 1))),
            ),
        ];
        for (name, n) in &measured {
            println!("{name}: {n} clauses");
        }

        // Floors at well under half the measured size: enough to catch a circuit vanishing
        // into a fold, loose enough not to churn on innocent encoding tweaks. A drop to a
        // handful of clauses would mean the operands folded and nothing was encoded.
        for (name, n) in measured {
            let floor = match name {
                "udiv64" => 50_000,
                "sdiv64" => 50_000,
                "mul64" => 35_000,
                "shl_var64" => 2_000,
                "rot_var64" => 1_500,
                "sgt64" => 500,
                // The gate-level constant folding shrank the halves of every
                // adder, so this path measured 334 after it (was ~430). The
                // floor only has to separate "real circuit" from "folded to
                // nothing", not pin the encoding.
                "rot_var5 (modulo-divider path)" => 200,
                _ => unreachable!(),
            };
            assert!(
                n >= floor,
                "{name} blasted only {n} clauses (floor {floor}) - did the operands fold?"
            );
        }
    }

    /// A symbolic dividend over a *literal* power-of-two divisor is a bit
    /// re-indexing, not a divider: `x / 2^k` is `x >> k` and `x % 2^k` keeps the
    /// low `k` bits, both built from the dividend's own literals. The two
    /// operands are asserted to be the same nodes, so this pins the encoding
    /// and not just the clause count.
    #[test]
    fn a_literal_power_of_two_divisor_blasts_no_divider() {
        let x = var(64, 0);
        assert_eq!(circuit_size(&x.udiv(&Bv::val(1024, 64))), 0);
        assert_eq!(circuit_size(&x.urem(&Bv::val(1024, 64))), 0);
        // A non-power-of-two literal still builds a divider, so the arm is
        // specific rather than "any constant divisor" - but the gate-level
        // constant folding makes it a much cheaper one: 34k clauses at 64 bits
        // against 106k for two symbolic operands, and the same 34k at 128 bits
        // when the dividend's top half is a zero-extension.
        let general = circuit_size(&x.udiv(&Bv::val(1000, 64)));
        assert!(
            general > 10_000,
            "a literal non-power-of-two still builds a divider"
        );
        assert!(
            general < 50_000,
            "constant folding shrank the constant-divisor divider"
        );
    }

    /// The static-range trim: a `u128` division whose operands are widened
    /// `u64`s has a statically-zero top half, so the divider runs at 64 bits and
    /// the result is zero-extended. Before the trim this cost 327k clauses at
    /// 128 bits; the narrow circuit is 106k, and the trim adds only the
    /// zero-divisor mux on top.
    #[test]
    fn a_zero_extended_division_runs_at_the_narrow_width() {
        let z = Bv::val(0, 64);
        let (x, y) = (var(64, 0), var(64, 1));
        let narrow = circuit_size(&x.udiv(&y));
        let wide = circuit_size(&z.concat(&x).udiv(&z.concat(&y)));
        assert!(
            wide < narrow * 2,
            "zero-extended 128-bit divide blasted {wide} clauses against {narrow} at 64 bits"
        );
        // The literal divisor case does not even pay for the wide divider: the
        // narrow circuit plus the zero-divisor mux, nothing more.
        let literal = circuit_size(&x.udiv(&Bv::val(1000, 64)));
        let wide_literal = circuit_size(&z.concat(&x).udiv(&Bv::val(1000, 128)));
        assert!(
            wide_literal < literal + 1_000,
            "zero-extended literal divide blasted {wide_literal} against {literal} at 64 bits"
        );
    }

    #[test]
    fn constant_operands_fold_to_no_circuit_at_all() {
        // The failure mode the conformance suite guards against: the same wide operation on
        // constant operands folds at construction and blasts nothing - a "proof" over it
        // would assert a constant against a constant.
        let folded = Bv::val(u64::MAX, 64).udiv(&Bv::val(7, 64));
        assert!(folded.as_const().is_some());
        assert_eq!(circuit_size(&folded), 0);
    }
}