cverif 0.0.0

Verifies that compiled machine code faithfully matches its C source
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
//! Bit-vector prover: bit-blasts [`crate::term`] terms into the CDCL solver and
//! decides validity of boolean terms under assumptions.

use crate::sat::{Lit, SatResult, Solver};
use crate::term::{Env, Node, T, Terms, mask};
use std::collections::HashMap;

#[derive(Clone, Debug)]
pub enum Verdict {
    /// The goal holds for every input satisfying the assumptions.
    Proved,
    /// A concrete input satisfying the assumptions and violating the goal.
    Refuted(Box<Env>),
    /// The solver ran out of budget.
    Unknown,
}

struct LoadByte {
    addr: T,
    addr_bits: Vec<Lit>,
    val: Vec<Lit>,
}

pub struct Prover {
    sat: Solver,
    tt: Lit,
    bits: HashMap<T, Vec<Lit>>,
    and_cache: HashMap<(Lit, Lit), Lit>,
    xor_cache: HashMap<(Lit, Lit), Lit>,
    syms: Vec<(u32, Vec<Lit>)>,
    loads: HashMap<u32, Vec<LoadByte>>,
    load_index: HashMap<(u32, T), usize>,
    cache: HashMap<(Vec<T>, T), Verdict>,
    /// Conflict budget per query.
    pub budget: u64,
    pub queries: u64,
    pub sat_calls: u64,
}

impl Default for Prover {
    fn default() -> Self {
        Self::new()
    }
}

impl Prover {
    pub fn new() -> Prover {
        let mut sat = Solver::new();
        let v = sat.new_var();
        let tt = Lit::new(v, false);
        sat.add_clause(&[tt]);
        Prover {
            sat,
            tt,
            bits: HashMap::new(),
            and_cache: HashMap::new(),
            xor_cache: HashMap::new(),
            syms: Vec::new(),
            loads: HashMap::new(),
            load_index: HashMap::new(),
            cache: HashMap::new(),
            budget: 300_000,
            queries: 0,
            sat_calls: 0,
        }
    }

    // ----- gates ----------------------------------------------------------

    fn fresh(&mut self) -> Lit {
        Lit::new(self.sat.new_var(), false)
    }

    fn konst(&self, b: bool) -> Lit {
        if b { self.tt } else { !self.tt }
    }

    fn and(&mut self, a: Lit, b: Lit) -> Lit {
        let (tt, ff) = (self.tt, !self.tt);
        if a == ff || b == ff || a == !b {
            return ff;
        }
        if a == tt || a == b {
            return b;
        }
        if b == tt {
            return a;
        }
        let key = if a < b { (a, b) } else { (b, a) };
        if let Some(&o) = self.and_cache.get(&key) {
            return o;
        }
        let o = self.fresh();
        self.sat.add_clause(&[!o, a]);
        self.sat.add_clause(&[!o, b]);
        self.sat.add_clause(&[o, !a, !b]);
        self.and_cache.insert(key, o);
        o
    }

    fn or(&mut self, a: Lit, b: Lit) -> Lit {
        !self.and(!a, !b)
    }

    fn xor(&mut self, a: Lit, b: Lit) -> Lit {
        let (tt, ff) = (self.tt, !self.tt);
        if a == ff {
            return b;
        }
        if b == ff {
            return a;
        }
        if a == tt {
            return !b;
        }
        if b == tt {
            return !a;
        }
        if a == b {
            return ff;
        }
        if a == !b {
            return tt;
        }
        let neg = a.is_neg() ^ b.is_neg();
        let (pa, pb) = (Lit::new(a.var(), false), Lit::new(b.var(), false));
        let key = if pa < pb { (pa, pb) } else { (pb, pa) };
        let o = match self.xor_cache.get(&key) {
            Some(&o) => o,
            None => {
                let o = self.fresh();
                self.sat.add_clause(&[!o, pa, pb]);
                self.sat.add_clause(&[!o, !pa, !pb]);
                self.sat.add_clause(&[o, !pa, pb]);
                self.sat.add_clause(&[o, pa, !pb]);
                self.xor_cache.insert(key, o);
                o
            }
        };
        if neg { !o } else { o }
    }

    fn mux(&mut self, c: Lit, a: Lit, b: Lit) -> Lit {
        let (tt, ff) = (self.tt, !self.tt);
        if c == tt || a == b {
            return a;
        }
        if c == ff {
            return b;
        }
        if a == tt && b == ff {
            return c;
        }
        if a == ff && b == tt {
            return !c;
        }
        if a == tt {
            return self.or(c, b);
        }
        if a == ff {
            return self.and(!c, b);
        }
        if b == tt {
            return self.or(!c, a);
        }
        if b == ff {
            return self.and(c, a);
        }
        let o = self.fresh();
        self.sat.add_clause(&[!c, !a, o]);
        self.sat.add_clause(&[!c, a, !o]);
        self.sat.add_clause(&[c, !b, o]);
        self.sat.add_clause(&[c, b, !o]);
        self.sat.add_clause(&[!a, !b, o]);
        self.sat.add_clause(&[a, b, !o]);
        o
    }

    fn adder(&mut self, x: &[Lit], y: &[Lit], mut carry: Lit) -> (Vec<Lit>, Lit) {
        let mut out = Vec::with_capacity(x.len());
        for (&a, &b) in x.iter().zip(y) {
            let axb = self.xor(a, b);
            out.push(self.xor(axb, carry));
            let t1 = self.and(a, b);
            let t2 = self.and(axb, carry);
            carry = self.or(t1, t2);
        }
        (out, carry)
    }

    fn add(&mut self, x: &[Lit], y: &[Lit]) -> Vec<Lit> {
        let ff = !self.tt;
        self.adder(x, y, ff).0
    }

    fn sub(&mut self, x: &[Lit], y: &[Lit]) -> Vec<Lit> {
        let ny: Vec<Lit> = y.iter().map(|&l| !l).collect();
        let tt = self.tt;
        self.adder(x, &ny, tt).0
    }

    fn negate(&mut self, x: &[Lit]) -> Vec<Lit> {
        let zero = vec![!self.tt; x.len()];
        self.sub(&zero, x)
    }

    /// x <u y
    fn ult(&mut self, x: &[Lit], y: &[Lit]) -> Lit {
        let ny: Vec<Lit> = y.iter().map(|&l| !l).collect();
        let tt = self.tt;
        // x - y borrows iff no carry out of x + ~y + 1.
        !self.adder(x, &ny, tt).1
    }

    fn eq(&mut self, x: &[Lit], y: &[Lit]) -> Lit {
        let mut acc = self.tt;
        for (&a, &b) in x.iter().zip(y) {
            let d = self.xor(a, b);
            acc = self.and(acc, !d);
        }
        acc
    }

    fn mux_vec(&mut self, c: Lit, a: &[Lit], b: &[Lit]) -> Vec<Lit> {
        a.iter().zip(b).map(|(&x, &y)| self.mux(c, x, y)).collect()
    }

    fn mul(&mut self, x: &[Lit], y: &[Lit]) -> Vec<Lit> {
        let w = x.len();
        let ff = !self.tt;
        let mut acc = vec![ff; w];
        for i in 0..w {
            if y[i] == ff {
                continue;
            }
            let mut row = vec![ff; w];
            for j in i..w {
                row[j] = self.and(x[j - i], y[i]);
            }
            acc = self.add(&acc, &row);
        }
        acc
    }

    fn mul_const(&mut self, x: &[Lit], c: u64) -> Vec<Lit> {
        let w = x.len();
        let ff = !self.tt;
        let m = mask(w as u8);
        let c = c & m;
        let nc = c.wrapping_neg() & m;
        let (c, negate) = if nc.count_ones() < c.count_ones() {
            (nc, true)
        } else {
            (c, false)
        };
        let mut acc = vec![ff; w];
        for i in 0..w {
            if c >> i & 1 == 1 {
                let mut row = vec![ff; w];
                row[i..w].copy_from_slice(&x[..w - i]);
                acc = self.add(&acc, &row);
            }
        }
        if negate { self.negate(&acc) } else { acc }
    }

    fn any(&mut self, x: &[Lit]) -> Lit {
        let mut acc = !self.tt;
        for &l in x {
            acc = self.or(acc, l);
        }
        acc
    }

    /// Shift by a variable amount.  `kind`: 0 = shl, 1 = lshr, 2 = ashr.
    fn shift(&mut self, x: &[Lit], amt: &[Lit], kind: u8) -> Vec<Lit> {
        let w = x.len();
        let fill = if kind == 2 { x[w - 1] } else { !self.tt };
        let stages = usize::BITS as usize - (w - 1).leading_zeros() as usize;
        let mut cur = x.to_vec();
        for (s, &a) in amt.iter().enumerate().take(stages) {
            let d = 1usize << s;
            let mut next = Vec::with_capacity(w);
            for i in 0..w {
                let shifted = if kind == 0 {
                    if i >= d { cur[i - d] } else { fill }
                } else if i + d < w {
                    cur[i + d]
                } else {
                    fill
                };
                next.push(self.mux(a, shifted, cur[i]));
            }
            cur = next;
        }
        // Amounts >= w (for non power-of-two widths this also needs the in-range check).
        let mut over = self.any(&amt[stages.min(amt.len())..]);
        if !w.is_power_of_two() {
            let wbits: Vec<Lit> = (0..amt.len())
                .map(|i| self.konst(i < 64 && (w as u64) >> i & 1 == 1))
                .collect();
            let lt = self.ult(amt, &wbits);
            over = self.or(over, !lt);
        }
        let fillv = vec![fill; w];
        self.mux_vec(over, &fillv, &cur)
    }

    /// Unsigned division with q = 0 when the divisor is zero.
    fn udiv(&mut self, a: &[Lit], b: &[Lit]) -> Vec<Lit> {
        let w = a.len();
        let ff = !self.tt;
        let q: Vec<Lit> = (0..w).map(|_| self.fresh()).collect();
        let r: Vec<Lit> = (0..w).map(|_| self.fresh()).collect();
        let nz = self.any(b);
        // In 2w bits: q * b + r == a, and r < b, when b != 0.
        let ext = |v: &[Lit]| {
            let mut e = v.to_vec();
            e.resize(2 * w, ff);
            e
        };
        let (q2, b2, r2, a2) = (ext(&q), ext(b), ext(&r), ext(a));
        let prod = self.mul(&q2, &b2);
        let sum = self.add(&prod, &r2);
        for i in 0..2 * w {
            let d = self.xor(sum[i], a2[i]);
            self.sat.add_clause(&[!nz, !d]);
        }
        let lt = self.ult(&r, b);
        self.sat.add_clause(&[!nz, lt]);
        for &l in &q {
            self.sat.add_clause(&[nz, !l]);
        }
        q
    }

    fn sdiv(&mut self, a: &[Lit], b: &[Lit]) -> Vec<Lit> {
        let w = a.len();
        let (sa, sb) = (a[w - 1], b[w - 1]);
        let na = self.negate(a);
        let nb = self.negate(b);
        let ua = self.mux_vec(sa, &na, a);
        let ub = self.mux_vec(sb, &nb, b);
        let q = self.udiv(&ua, &ub);
        let nq = self.negate(&q);
        let neg = self.xor(sa, sb);
        self.mux_vec(neg, &nq, &q)
    }

    // ----- term translation -------------------------------------------------

    pub fn children_of(n: &Node) -> Vec<T> {
        match n {
            Node::Const(_) | Node::Sym(_) => vec![],
            Node::Sum(ts, _) => ts.iter().map(|x| x.0).collect(),
            Node::Mul(a, b)
            | Node::UDiv(a, b)
            | Node::SDiv(a, b)
            | Node::And(a, b)
            | Node::Or(a, b)
            | Node::Xor(a, b)
            | Node::Shl(a, b)
            | Node::LShr(a, b)
            | Node::AShr(a, b)
            | Node::Eq(a, b)
            | Node::Ult(a, b)
            | Node::Slt(a, b)
            | Node::Concat(a, b) => vec![*a, *b],
            Node::Ite(c, a, b) => vec![*c, *a, *b],
            Node::Not(a) | Node::Extract(a, _) | Node::ZExt(a) | Node::SExt(a) | Node::Load(_, a) | Node::Clz(a) => {
                vec![*a]
            }
        }
    }

    pub fn blast(&mut self, tm: &mut Terms, root: T) -> Vec<Lit> {
        let mut stack = vec![root];
        while let Some(&t) = stack.last() {
            if self.bits.contains_key(&t) {
                stack.pop();
                continue;
            }
            let missing: Vec<T> = Self::children_of(tm.node(t))
                .into_iter()
                .filter(|k| !self.bits.contains_key(k))
                .collect();
            if !missing.is_empty() {
                stack.extend(missing);
                continue;
            }
            let b = self.blast_node(tm, t);
            debug_assert_eq!(b.len(), tm.width(t) as usize);
            self.bits.insert(t, b);
            stack.pop();
        }
        self.bits[&root].clone()
    }

    fn load_byte(&mut self, tm: &mut Terms, mem: u32, addr: T) -> Vec<Lit> {
        if let Some(&i) = self.load_index.get(&(mem, addr)) {
            return self.loads[&mem][i].val.clone();
        }
        let addr_bits = self.blast(tm, addr);
        let val: Vec<Lit> = (0..8).map(|_| self.fresh()).collect();
        // Functional consistency with every earlier byte of this snapshot that may alias.
        let n = self.loads.get(&mem).map_or(0, |v| v.len());
        for i in 0..n {
            let (oaddr, obits, oval) = {
                let o = &self.loads[&mem][i];
                (o.addr, o.addr_bits.clone(), o.val.clone())
            };
            if tm.const_diff(addr, oaddr).is_some_and(|d| d != 0) {
                continue;
            }
            let same = self.eq(&addr_bits, &obits);
            for k in 0..8 {
                let d = self.xor(val[k], oval[k]);
                self.sat.add_clause(&[!same, !d]);
            }
        }
        let list = self.loads.entry(mem).or_default();
        list.push(LoadByte {
            addr,
            addr_bits,
            val: val.clone(),
        });
        self.load_index.insert((mem, addr), list.len() - 1);
        val
    }

    fn blast_node(&mut self, tm: &mut Terms, t: T) -> Vec<Lit> {
        let w = tm.width(t) as usize;
        let ff = !self.tt;
        let node = tm.node(t).clone();
        let get = |s: &Self, x: T| s.bits[&x].clone();
        match node {
            Node::Const(v) => (0..w).map(|i| self.konst(v >> i & 1 == 1)).collect(),
            Node::Sym(id) => {
                let b: Vec<Lit> = (0..w).map(|_| self.fresh()).collect();
                self.syms.push((id, b.clone()));
                b
            }
            Node::Sum(ts, k) => {
                let mut acc: Vec<Lit> = (0..w).map(|i| self.konst(k >> i & 1 == 1)).collect();
                for &(x, c) in ts.iter() {
                    let xb = get(self, x);
                    let m = mask(w as u8);
                    if c & m == m {
                        acc = self.sub(&acc, &xb);
                    } else {
                        let p = self.mul_const(&xb, c);
                        acc = self.add(&acc, &p);
                    }
                }
                acc
            }
            Node::Mul(a, b) => {
                let (a, b) = (get(self, a), get(self, b));
                self.mul(&a, &b)
            }
            Node::UDiv(a, b) => {
                let (a, b) = (get(self, a), get(self, b));
                self.udiv(&a, &b)
            }
            Node::SDiv(a, b) => {
                let (a, b) = (get(self, a), get(self, b));
                self.sdiv(&a, &b)
            }
            Node::And(a, b) => {
                let (a, b) = (get(self, a), get(self, b));
                a.iter().zip(&b).map(|(&x, &y)| self.and(x, y)).collect()
            }
            Node::Or(a, b) => {
                let (a, b) = (get(self, a), get(self, b));
                a.iter().zip(&b).map(|(&x, &y)| self.or(x, y)).collect()
            }
            Node::Xor(a, b) => {
                let (a, b) = (get(self, a), get(self, b));
                a.iter().zip(&b).map(|(&x, &y)| self.xor(x, y)).collect()
            }
            Node::Not(a) => get(self, a).iter().map(|&l| !l).collect(),
            Node::Shl(a, b) => {
                let (a, b) = (get(self, a), get(self, b));
                self.shift(&a, &b, 0)
            }
            Node::LShr(a, b) => {
                let (a, b) = (get(self, a), get(self, b));
                self.shift(&a, &b, 1)
            }
            Node::AShr(a, b) => {
                let (a, b) = (get(self, a), get(self, b));
                self.shift(&a, &b, 2)
            }
            Node::Eq(a, b) => {
                let (a, b) = (get(self, a), get(self, b));
                vec![self.eq(&a, &b)]
            }
            Node::Ult(a, b) => {
                let (a, b) = (get(self, a), get(self, b));
                vec![self.ult(&a, &b)]
            }
            Node::Slt(a, b) => {
                let (mut a, mut b) = (get(self, a), get(self, b));
                let n = a.len();
                a[n - 1] = !a[n - 1];
                b[n - 1] = !b[n - 1];
                vec![self.ult(&a, &b)]
            }
            Node::Ite(c, a, b) => {
                let (c, a, b) = (get(self, c)[0], get(self, a), get(self, b));
                self.mux_vec(c, &a, &b)
            }
            Node::Extract(a, lo) => get(self, a)[lo as usize..lo as usize + w].to_vec(),
            Node::ZExt(a) => {
                let mut b = get(self, a);
                b.resize(w, ff);
                b
            }
            Node::SExt(a) => {
                let mut b = get(self, a);
                let s = *b.last().unwrap();
                b.resize(w, s);
                b
            }
            Node::Concat(h, l) => {
                let mut b = get(self, l);
                b.extend(get(self, h));
                b
            }
            Node::Load(mem, addr) => {
                let mut out = Vec::with_capacity(w);
                for i in 0..(w / 8) as u64 {
                    let a = tm.add_const(addr, i);
                    out.extend(self.load_byte(tm, mem, a));
                }
                out
            }
            Node::Clz(a) => {
                let a = get(self, a);
                // count = number of leading zero bits; scan from the top.
                let mut count = vec![ff; w];
                let mut seen = ff;
                for i in (0..a.len()).rev() {
                    // Still in the leading-zero run after this bit iff no one seen and this bit is 0.
                    seen = self.or(seen, a[i]);
                    let inc = !seen;
                    // count += inc
                    let mut carry = inc;
                    for c in count.iter_mut() {
                        let s = self.xor(*c, carry);
                        carry = self.and(*c, carry);
                        *c = s;
                    }
                }
                count
            }
        }
    }

    // ----- queries ------------------------------------------------------------

    fn model(&self, tm: &Terms) -> Env {
        let val = |bits: &[Lit]| -> u64 {
            let mut v = 0u64;
            for (i, l) in bits.iter().enumerate() {
                if self.sat.model_value(l.var()) != l.is_neg() {
                    v |= 1 << i;
                }
            }
            v
        };
        let mut env = Env::default();
        for (id, bits) in &self.syms {
            env.syms.insert(*id, val(bits));
        }
        for (mem, list) in &self.loads {
            for b in list {
                env.mem.insert((*mem, val(&b.addr_bits)), val(&b.val) as u8);
            }
        }
        let _ = tm;
        env
    }

    /// Is `goal` true for every input satisfying all `assumptions`?
    pub fn prove(&mut self, tm: &mut Terms, assumptions: &[T], goal: T) -> Verdict {
        self.queries += 1;
        if tm.is_true(goal) || assumptions.contains(&goal) {
            return Verdict::Proved;
        }
        let mut key: Vec<T> = assumptions.iter().copied().filter(|&a| !tm.is_true(a)).collect();
        key.sort_unstable();
        key.dedup();
        if key.iter().any(|&a| tm.is_false(a)) {
            return Verdict::Proved;
        }
        if let Some(v) = self.cache.get(&(key.clone(), goal)) {
            return v.clone();
        }
        let mut lits = Vec::with_capacity(key.len() + 1);
        for &a in &key {
            lits.push(self.blast(tm, a)[0]);
        }
        let g = self.blast(tm, goal)[0];
        lits.push(!g);
        self.sat_calls += 1;
        let v = match self.sat.solve(&lits, self.budget) {
            SatResult::Unsat => Verdict::Proved,
            SatResult::Sat => Verdict::Refuted(Box::new(self.model(tm))),
            SatResult::Unknown => Verdict::Unknown,
        };
        self.cache.insert((key, goal), v.clone());
        v
    }

    /// Can all `conds` hold at once?  None if the solver gave up.
    pub fn satisfiable(&mut self, tm: &mut Terms, conds: &[T]) -> Option<bool> {
        let f = tm.fals();
        match self.prove(tm, conds, f) {
            Verdict::Proved => Some(false),
            Verdict::Refuted(_) => Some(true),
            Verdict::Unknown => None,
        }
    }

    pub fn stats(&self) -> String {
        let (c, d, p) = self.sat.stats();
        format!(
            "{} queries, {} SAT calls, {} vars, {} clauses, {} conflicts, {} decisions, {} propagations",
            self.queries,
            self.sat_calls,
            self.sat.num_vars(),
            self.sat.num_clauses(),
            c,
            d,
            p
        )
    }
}

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

    fn valid(tm: &mut Terms, p: &mut Prover, g: T) -> bool {
        matches!(p.prove(tm, &[], g), Verdict::Proved)
    }

    #[test]
    fn arithmetic_identities() {
        let mut tm = Terms::new();
        let mut p = Prover::new();
        let x = tm.sym("x", 32);
        let y = tm.sym("y", 32);
        // (x ^ y) + 2*(x & y) == x + y
        let xo = tm.xor(x, y);
        let an = tm.and(x, y);
        let an2 = tm.scale(an, 2);
        let lhs = tm.add(xo, an2);
        let rhs = tm.add(x, y);
        let g = tm.eq(lhs, rhs);
        assert!(valid(&mut tm, &mut p, g));
        // x - y == x + ~y + 1 is settled by the normaliser or the solver.
        let ny = tm.not(y);
        let s = tm.add(x, ny);
        let s = tm.add_const(s, 1);
        let d = tm.sub(x, y);
        let g = tm.eq(s, d);
        assert!(valid(&mut tm, &mut p, g));
        // x < y is not valid, and the counterexample really is one.
        let g = tm.ult(x, y);
        match p.prove(&mut tm, &[], g) {
            Verdict::Refuted(env) => assert_eq!(tm.eval(g, &env, &mut HashMap::new()), 0),
            v => panic!("expected refutation, got {v:?}"),
        }
    }

    #[test]
    fn division_and_shifts() {
        let mut tm = Terms::new();
        let mut p = Prover::new();
        // (x / y) * y <= x when y != 0 (8 bits: multiplier reasoning is hard for SAT)
        let x8 = tm.sym("x8", 8);
        let y8 = tm.sym("y8", 8);
        let q = tm.udiv(x8, y8);
        let qy = tm.mul(q, y8);
        let z = tm.konst(8, 0);
        let nz = tm.ne(y8, z);
        let le = tm.ule(qy, x8);
        let v = p.prove(&mut tm, &[nz], le);
        assert!(matches!(v, Verdict::Proved), "{v:?}");
        let x = tm.sym("x", 16);
        // x / 8 == x >> 3
        let c8 = tm.konst(16, 8);
        let d = tm.udiv(x, c8);
        let s = tm.lshr_c(x, 3);
        let g = tm.eq(d, s);
        assert!(valid(&mut tm, &mut p, g));
        // signed: -32768 / -1 == -32768 under the ARM convention
        let a = tm.konst(16, 0x8000);
        let b = tm.konst(16, 0xffff);
        let d = tm.sdiv(a, b);
        assert_eq!(tm.as_const(d), Some(0x8000));
        // variable shifts: (x << n) >> n == x & (0xffff >> n) for n < 16
        let n = tm.sym("n", 16);
        let c16 = tm.konst(16, 16);
        let inr = tm.ult(n, c16);
        let l = tm.shl(x, n);
        let l = tm.lshr(l, n);
        let ones = tm.konst(16, 0xffff);
        let m = tm.lshr(ones, n);
        let r = tm.and(x, m);
        let g = tm.eq(l, r);
        assert!(matches!(p.prove(&mut tm, &[inr], g), Verdict::Proved));
    }

    #[test]
    fn memory_consistency() {
        let mut tm = Terms::new();
        let mut p = Prover::new();
        let a = tm.sym("a", 32);
        let b = tm.sym("b", 32);
        let la = tm.load(0, a, 4);
        let lb = tm.load(0, b, 4);
        let same = tm.eq(a, b);
        let g = tm.eq(la, lb);
        assert!(matches!(p.prove(&mut tm, &[same], g), Verdict::Proved));
        assert!(matches!(p.prove(&mut tm, &[], g), Verdict::Refuted(_)));
        // Overlapping loads: byte 1 of load32(a) is load8(a + 1).
        let a1 = tm.add_const(a, 1);
        let l1 = tm.load(0, a1, 1);
        let ex = tm.extract(la, 8, 8);
        assert_eq!(l1, ex);
    }

    #[test]
    fn evaluator_agrees_with_solver() {
        // For random small terms, the solver's model must evaluate consistently.
        let mut tm = Terms::new();
        let mut p = Prover::new();
        let x = tm.sym("x", 8);
        let y = tm.sym("y", 8);
        let ops: Vec<T> = {
            let mut v = vec![x, y];
            let s = tm.add(x, y);
            let m = tm.mul(x, y);
            let d = tm.sdiv(x, y);
            let u = tm.udiv(x, y);
            let sh = tm.shl(x, y);
            let sr = tm.ashr(x, y);
            let lr = tm.lshr(x, y);
            let c = tm.clz(x);
            v.extend([s, m, d, u, sh, sr, lr, c]);
            v
        };
        for (i, &a) in ops.iter().enumerate() {
            for &b in &ops[i + 1..] {
                let g = tm.eq(a, b);
                if let Verdict::Refuted(env) = p.prove(&mut tm, &[], g) {
                    let mut memo = HashMap::new();
                    assert_ne!(
                        tm.eval(a, &env, &mut memo),
                        tm.eval(b, &env, &mut memo),
                        "{} vs {}",
                        tm.show(a),
                        tm.show(b)
                    );
                }
            }
        }
        // Exhaustively compare evaluator and solver on one op pair via the solver proving
        // a tautology that depends on division semantics: sdiv(x, 1) == x.
        let one = tm.konst(8, 1);
        let d = tm.sdiv(x, one);
        assert_eq!(d, x);
        let neg1 = tm.konst(8, 0xff);
        let d = tm.sdiv(x, neg1);
        let n = tm.neg(x);
        let g = tm.eq(d, n);
        assert!(valid(&mut tm, &mut p, g));
    }
}