bitwright 0.31.6

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
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
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
//! Exact certificates for MBA equalities: finite evaluation tests, each complete for its
//! fragment (design §9). A certificate compares two expressions at a set of points chosen so
//! that agreement there proves agreement everywhere:
//!
//! - **Signature.** Linear MBA with only 0 and all-ones constants inside bitwise parts is
//!   determined by its values at the 2^t corners where every variable is 0 or all-ones.
//! - **Sparse** (single-position for degree 1). A *polynomial MBA* is built with `+ − ·`,
//!   negation, constant left shifts and constants over bitwise functions of the variables
//!   (`& | ^ ~` over variables and constants). Its syntactic degree `d` is the largest number of
//!   bitwise factors (variables count as bitwise) in a product. Writing each variable as
//!   `Σ_j 2^j·x[j]` makes the difference of two such expressions an integer polynomial in the
//!   `t·W` input bits (reduction mod 2^W is a ring homomorphism, so carries need no special
//!   care); after `b² = b` it is multilinear, and each monomial touches at most `d` bit
//!   positions, one per factor. A multilinear function over a commutative ring has a unique
//!   representation, and Möbius inversion recovers each coefficient from its values at points
//!   supported inside the coefficient's monomial. So the two expressions are equal if and only
//!   if they agree at every point where the set bits of all variables together lie in at most
//!   `d` positions: `Σ_{k≤d} C(W,k)·(2^t − 1)^k` points.
//! - **Grid.** Without bitwise operators, two polynomials of degree at most `d_i` in variable
//!   `i` are equal if they agree on `Π_i {0..d_i}`: forward differences there give `α!·h_α` for
//!   the falling-factorial coefficients `h_α`, and `h_α·Π(x_i)_{α_i}` vanishes when `α!·h_α`
//!   does, because `Π(x_i)_{α_i}` is a multiple of `α!`.
//! - **Exhaustive.** Every assignment, when the variables total at most 20 bits.
//! - **Compositional.** Subterms outside the polynomial fragment (right shifts, casts,
//!   arithmetic read by a bitwise operator) become *atoms*, shared between both sides by
//!   structure, by congruence (`f(a) = f(b)` when `a = b`), and by proofs of their definitions.
//!   The two *skeletons* are then compared by one of the tests above, treating atoms as
//!   independent variables: an identity for independent atoms holds for any values of them.
//!   A skeleton that differs proves nothing (the atoms may be dependent): the answer is
//!   unknown, never refuted.
//! - **Known bits.** When those leave the question open, `x op k` (`op` bitwise, `k` a
//!   constant) is read as arithmetic wherever the known bits of `x` cover the bits `k` is 1
//!   at, or those it is 0 at: equal functions, so a verdict on them is one on the question.
//! - **Cases.** Then a variable is split over a few of its bits: those both sides read it
//!   through narrow masks at, or the low bits bitwise operations with constants read. The cases
//!   cover every input, and each is proved on its own.
//!
//! Every test is sized before it runs and charged a block at a time; one over the budget is
//! not run. A polynomial test that would take far longer than reading both sides as
//! polynomials over symbols ([`symbolic_equal`], which only ever proves) tries that first: the
//! verdict is the test's either way, at a fraction of the work when the polynomials are equal.
//! `Refuted` always comes with a concrete input where the two sides differ.

use super::batch::{BLOCK, Kind, Lane, Program, Wide};
use super::expr::{MNode, MOp, MbaExpr};
use super::solve::Verdict;
use crate::engine::CertStats;
use crate::ops::{BinOp, UnOp};
use crate::{BitVec, Width};

/// The hasher of the certificates' own lookup tables (hash-consed nodes, node indices,
/// automaton states): a multiply per word, where the default hasher took most of the time of
/// building a table of nodes. Its output never reaches a result: no table is walked in hash
/// order (the ones whose keys are read are sorted first).
#[derive(Default, Clone, Copy, Debug)]
struct TableHasher(u64);

impl TableHasher {
    #[inline]
    fn add(&mut self, v: u64) {
        self.0 = (self.0.rotate_left(5) ^ v).wrapping_mul(0x517c_c1b7_2722_0a95);
    }
}

impl core::hash::Hasher for TableHasher {
    #[inline]
    fn finish(&self) -> u64 {
        crate::hash::mix64(self.0)
    }
    #[inline]
    fn write(&mut self, bytes: &[u8]) {
        let (words, rest) = bytes.as_chunks::<8>();
        for w in words {
            self.add(u64::from_le_bytes(*w));
        }
        if !rest.is_empty() {
            let mut w = [0u8; 8];
            w[..rest.len()].copy_from_slice(rest);
            self.add(u64::from_le_bytes(w));
        }
    }
    #[inline]
    fn write_u8(&mut self, i: u8) {
        self.add(u64::from(i));
    }
    #[inline]
    fn write_u16(&mut self, i: u16) {
        self.add(u64::from(i));
    }
    #[inline]
    fn write_u32(&mut self, i: u32) {
        self.add(u64::from(i));
    }
    #[inline]
    fn write_u64(&mut self, i: u64) {
        self.add(i);
    }
    #[inline]
    fn write_usize(&mut self, i: usize) {
        self.add(i as u64);
    }
}

/// A table with [`TableHasher`].
type HashMap<K, V> = std::collections::HashMap<K, V, core::hash::BuildHasherDefault<TableHasher>>;

/// Where each node of a hash-consed list is, by content: an open-addressed table of indices
/// into the list. (A table keyed by the nodes themselves holds a copy of each, a hundred
/// bytes an entry, and building it was most of putting two sides in one list.)
#[derive(Debug)]
struct NodeTable {
    /// A node's index plus one; 0: empty. A power of two, at most half full.
    slots: Vec<u32>,
}

impl NodeTable {
    /// A table with room for `nodes` nodes before it grows.
    fn with_room(nodes: usize) -> NodeTable {
        NodeTable {
            slots: vec![0; (2 * nodes.max(8)).next_power_of_two()],
        }
    }

    fn slot_of(&self, node: &MNode) -> usize {
        use core::hash::{Hash, Hasher};
        let mut h = TableHasher::default();
        node.hash(&mut h);
        h.finish() as usize & (self.slots.len() - 1)
    }

    /// The index of `node` in `nodes`, if it is there.
    fn get(&self, nodes: &[MNode], node: &MNode) -> Option<u32> {
        let mask = self.slots.len() - 1;
        let mut at = self.slot_of(node);
        loop {
            match self.slots[at] {
                0 => return None,
                k if nodes[k as usize - 1] == *node => return Some(k - 1),
                _ => at = (at + 1) & mask,
            }
        }
    }

    /// Records node `i` of `nodes` (one that is not in the table).
    fn insert(&mut self, nodes: &[MNode], i: u32) {
        if 2 * (nodes.len() + 1) > self.slots.len() {
            // Twice the room, every node put again.
            self.slots = vec![0; (4 * nodes.len().max(8)).next_power_of_two()];
            for k in 0..nodes.len() as u32 {
                self.place(nodes, k);
            }
        } else {
            self.place(nodes, i);
        }
    }

    fn place(&mut self, nodes: &[MNode], i: u32) {
        let mask = self.slots.len() - 1;
        let mut at = self.slot_of(&nodes[i as usize]);
        while self.slots[at] != 0 {
            at = (at + 1) & mask;
        }
        self.slots[at] = i + 1;
    }

    /// The index of `node` in `nodes`, added at the end if it is not there.
    fn intern(&mut self, nodes: &mut Vec<MNode>, node: MNode) -> u32 {
        if let Some(i) = self.get(nodes, &node) {
            return i;
        }
        nodes.push(node);
        let i = nodes.len() as u32 - 1;
        self.insert(nodes, i);
        i
    }
}

/// The most points one test evaluates, whatever the budget.
pub(crate) const MAX_POINTS: u64 = 1 << 24;

/// The most effort one test may take, whatever the budget: points × nodes × the cost of a lane
/// (1 up to 64 bits, 2 up to 128, 8 above). A larger test is not run and is a stable decline, so
/// whether a node is final never depends on the budget; a test within this cap but over what
/// is left of the budget leaves the node non-final.
pub(crate) const MAX_EFFORT: u64 = 1 << 25;

/// Exhaustive evaluation is a test up to this many variable bits.
pub(crate) const EXHAUSTIVE_BITS: u32 = 20;

/// The signature test takes at most this many variables.
const SIGNATURE_VARS: usize = 16;

/// Points of the refutation sample.
pub(crate) const SAMPLE_POINTS: usize = 64;

/// The most proof attempts per atom when atoms are paired by their definitions.
const PAIR_TRIES: usize = 4;

/// The most bits of one variable a split enumerates (at most `2^SPLIT_BITS` cases).
const SPLIT_BITS: u32 = 4;

/// How deep splits nest (each one on another variable).
const SPLIT_DEPTH: u32 = 2;

/// The most work (node evaluations) one split spends on cases before it declines; like
/// [`MAX_EFFORT`], a decline that does not depend on the budget.
const SPLIT_EFFORT: u64 = MAX_EFFORT;

/// Work charged per node for reading known bits as arithmetic (a transfer of facts costs about
/// as much as evaluating a node at this many points).
pub(crate) const LOWER_COST: u64 = 64;

/// Node evaluations (one lane each, a block at a time) that take about as long as one unit of
/// symbolic work, a monomial operation (measured: 0.3–0.4 ns against 100–400 ns). It decides
/// when the symbolic comparison is worth trying ahead of a test (see [`run`]); the comparison
/// is charged at [`SYMBOLIC_RATE`].
const SYMBOLIC_UNIT: u64 = 1 << 10;

/// Units charged per unit of symbolic work, a monomial operation: what one costs in node
/// evaluations (measured on identical certificates: 208 in instructions and 308 in time; 250
/// to 350 over the bench and `--corpus-diff` corpora), so that a budget bounds the comparison's
/// time as it bounds a test's.
pub(crate) const SYMBOLIC_RATE: u64 = 256;

/// Work accounting for a certificate: units are node evaluations (one per node per point).
pub(crate) trait Meter {
    /// What a failed charge reports.
    type Err;
    /// Units left.
    fn left(&self) -> u64;
    /// Spends `units`.
    fn charge(&mut self, units: u64) -> Result<(), Self::Err>;
}

/// A meter over a plain count (a solver's or a prover's budget).
#[derive(Debug)]
pub(crate) struct Steps {
    pub(crate) left: u64,
    pub(crate) spent: u64,
    /// Where the units this meter consumed are added up, if anywhere: the meters of one
    /// question of the normal-form solver share one, which says what the question spent.
    used: Option<Used>,
}

/// The units consumed by the meters that share it.
pub(crate) type Used = std::rc::Rc<std::cell::Cell<u64>>;

impl Steps {
    pub(crate) fn new(left: u64) -> Steps {
        Steps {
            left,
            spent: 0,
            used: None,
        }
    }

    /// A meter whose consumption is added to `used`.
    pub(crate) fn counted(left: u64, used: &Used) -> Steps {
        Steps {
            left,
            spent: 0,
            used: Some(used.clone()),
        }
    }
}

impl Meter for Steps {
    type Err = ();
    fn left(&self) -> u64 {
        self.left
    }
    fn charge(&mut self, units: u64) -> Result<(), ()> {
        self.spent = self.spent.saturating_add(units);
        if let Some(u) = &self.used {
            u.set(u.get().saturating_add(units.min(self.left)));
        }
        if units > self.left {
            self.left = 0;
            return Err(());
        }
        self.left -= units;
        Ok(())
    }
}

/// The test that decided.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) enum Cert {
    /// The corner signature (constant-free linear MBA).
    Signature,
    /// Single bit positions (degree ≤ 1).
    SingleBit,
    /// At most `d` bit positions (degree `d ≥ 2`).
    Sparse,
    /// The pure-polynomial grid.
    Grid,
    /// Every assignment.
    Exhaustive,
    /// Equal polynomials over symbols (see [`symbolic_equal`]).
    Symbolic,
    /// Bit-serial evaluation over every reachable carry state (see [`carries`]).
    Carries,
}

impl Cert {
    /// A short name, as `CertStats` counts it.
    pub(crate) fn name(self) -> &'static str {
        match self {
            Cert::Signature => "signature",
            Cert::SingleBit => "single_bit",
            Cert::Sparse => "sparse",
            Cert::Grid => "grid",
            Cert::Exhaustive => "exhaustive",
            Cert::Symbolic => "symbolic",
            Cert::Carries => "carries",
        }
    }
}

/// What a certificate found.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Report {
    pub(crate) verdict: Verdict,
    /// The test that proved or refuted the equality (for a compositional proof, the one on the
    /// skeletons).
    pub(crate) cert: Option<Cert>,
    /// Atoms were abstracted.
    pub(crate) compositional: bool,
    /// Decided case by case over a few bits of one variable.
    pub(crate) split: bool,
    /// Decided after bitwise operations with constants that read only known bits were read
    /// as arithmetic.
    pub(crate) known_bits: bool,
    /// Points evaluated, over every test run.
    pub(crate) points: u64,
    /// A test was skipped for lack of budget (more budget might decide).
    pub(crate) over_budget: bool,
    /// Internal inconsistencies seen (a pairing that disagreed at a sample point); never
    /// expected.
    pub(crate) internal: u64,
    /// For `Refuted`: an input where the sides differ (one value per variable).
    pub(crate) counterexample: Option<Vec<BitVec>>,
    /// Node evaluations spent (by [`check`]).
    pub(crate) work: u64,
}

impl Report {
    pub(crate) fn new() -> Report {
        Report {
            verdict: Verdict::Unknown,
            cert: None,
            compositional: false,
            split: false,
            known_bits: false,
            points: 0,
            over_budget: false,
            internal: 0,
            counterexample: None,
            work: 0,
        }
    }
}

// ----- constant folding --------------------------------------------------------------------

/// The value of node `n` from its operands' values.
fn apply(n: &MNode, a: Option<&BitVec>, b: Option<&BitVec>) -> Option<BitVec> {
    let bin = |op: BinOp| Some(BitVec::bin_unchecked(op, a?, b?));
    match n.op {
        MOp::Const(v) => Some(v),
        MOp::Var(_) => None,
        MOp::Add => bin(BinOp::Add),
        MOp::Sub => bin(BinOp::Sub),
        MOp::Mul => bin(BinOp::Mul),
        MOp::And => bin(BinOp::And),
        MOp::Or => bin(BinOp::Or),
        MOp::Xor => bin(BinOp::Xor),
        MOp::Neg => Some(BitVec::un_unchecked(UnOp::Neg, a?)),
        MOp::Not => Some(BitVec::un_unchecked(UnOp::Not, a?)),
        MOp::Shl(k) | MOp::LShr(k) => {
            let a = a?;
            let kv = BitVec::wrapping_from_u64(a.width(), u64::from(k));
            let op = if matches!(n.op, MOp::Shl(_)) {
                BinOp::Shl
            } else {
                BinOp::LShr
            };
            Some(BitVec::bin_unchecked(op, a, &kv))
        }
        MOp::Zext => a?.zext(n.width).ok(),
        MOp::Sext => a?.sext(n.width).ok(),
        MOp::Trunc => a?.trunc(n.width).ok(),
    }
}

/// Per node: its value when it does not depend on any variable.
pub(crate) fn constants(nodes: &[MNode]) -> Vec<Option<BitVec>> {
    let mut cst: Vec<Option<BitVec>> = Vec::with_capacity(nodes.len());
    for n in nodes {
        let k = n.op.arity();
        let a = if k > 0 {
            cst[n.args[0] as usize].as_ref()
        } else {
            None
        };
        let b = if k > 1 {
            cst[n.args[1] as usize].as_ref()
        } else {
            None
        };
        let v = if matches!(n.op, MOp::Var(_)) || (k > 0 && a.is_none()) || (k > 1 && b.is_none()) {
            None
        } else {
            apply(n, a, b)
        };
        cst.push(v);
    }
    cst
}

/// The nodes the root uses.
fn live(m: &MbaExpr) -> Vec<bool> {
    let nodes = m.nodes();
    let mut live = vec![false; nodes.len()];
    if let Some(r) = live.last_mut() {
        *r = true;
    }
    for i in (0..nodes.len()).rev() {
        if live[i] {
            let n = &nodes[i];
            for &k in &n.args[..n.op.arity()] {
                live[k as usize] = true;
            }
        }
    }
    live
}

// ----- profiles --------------------------------------------------------------------------------

/// What the direct tests need to know about one expression.
#[derive(Clone, Debug)]
pub(crate) struct Profile {
    /// The root's width.
    pub(crate) width: Width,
    /// A polynomial MBA at one width: every live node and variable at the root's width, no
    /// right shift or cast of a non-constant, and every operand of `& | ^` a bitwise function
    /// of the variables (or a constant).
    pub(crate) poly: bool,
    /// Constants read by bitwise operators are 0 or all-ones.
    pub(crate) uniform: bool,
    /// Some `& | ^` of a non-constant.
    pub(crate) bitwise: bool,
    /// The syntactic degree (bitwise factors per product).
    pub(crate) degree: u32,
    /// Per variable: the degree in that variable (meaningful without bitwise operators).
    pub(crate) var_degree: Vec<u32>,
    /// Per variable: whether the root depends on it syntactically.
    pub(crate) used: Vec<bool>,
}

/// Degrees saturate here (any degree this high is far beyond what a test can afford).
const DEGREE_CAP: u32 = 1 << 12;

pub(crate) fn profile(m: &MbaExpr) -> Option<Profile> {
    let w = m.width()?;
    let nodes = m.nodes();
    let nv = m.vars().len();
    let live = live(m);
    let cst = constants(nodes);
    let mut local = vec![false; nodes.len()];
    // the bit position offset of a bitwise function of the variables (bit `i` of
    // the node reads the variables' bits `i + shift`), `ANY` for constants. Shifts by
    // constants move it; a bitwise operator takes operands at one offset only, so every bit
    // still reads one position of the variables, which the sparse tests rest on.
    const ANY: i32 = i32::MIN;
    let mut shift = vec![0i32; nodes.len()];
    let mut deg = vec![0u32; nodes.len()];
    // Per node, a row of `nv` degrees (one table, not a vector per node); rows start at zero.
    let mut vdeg: Vec<u32> = vec![0; nodes.len() * nv];
    let (mut poly, mut uniform, mut bitwise) = (true, true, false);
    let mut used = vec![false; nv];
    for (i, n) in nodes.iter().enumerate() {
        if !live[i] {
            continue;
        }
        if cst[i].is_some() {
            local[i] = true;
            shift[i] = ANY;
            continue;
        }
        // A variable narrower than the question is read through casts, which say what its
        // readers can do; one read only through a zero extension is a variable of the
        // polynomial fragment (as `decast` writes narrow variables): the tests enumerate its
        // own bits.
        if n.width != w && !matches!(n.op, MOp::Var(_)) {
            poly = false;
        }
        let a = n.args[0] as usize;
        let b = n.args[1] as usize;
        let narrow_var = matches!(nodes[a].op, MOp::Var(_)) && nodes[a].width < w;
        let wide_var = matches!(nodes[a].op, MOp::Var(_)) && nodes[a].width > w;
        match n.op {
            MOp::Var(v) => {
                local[i] = true;
                deg[i] = 1;
                if (v as usize) < nv {
                    vdeg[i * nv + v as usize] = 1;
                }
                if let Some(u) = used.get_mut(v as usize) {
                    *u = true;
                }
            }
            // Likewise the low bits of a variable wider than the question (as `decast` writes
            // one under a truncation): a variable of the question's width.
            MOp::Trunc if wide_var => {
                local[i] = true;
                deg[i] = 1;
                vdeg.copy_within(a * nv..(a + 1) * nv, i * nv);
            }
            MOp::Zext if narrow_var => {
                local[i] = true;
                deg[i] = 1;
                vdeg.copy_within(a * nv..(a + 1) * nv, i * nv);
            }
            MOp::And | MOp::Or | MOp::Xor => {
                bitwise = true;
                for k in [a, b] {
                    if !local[k] {
                        poly = false;
                    }
                    if let Some(c) = &cst[k]
                        && !(c.is_zero() || c.is_ones())
                    {
                        uniform = false;
                    }
                }
                shift[i] = match (shift[a], shift[b]) {
                    (ANY, s) | (s, ANY) => s,
                    (s, t) if s == t => s,
                    _ => {
                        poly = false;
                        0
                    }
                };
                local[i] = true;
                deg[i] = 1;
            }
            // a shift of a bitwise function is one, at another offset (its
            // vacated bits are constants). Not at the corners, and not without bitwise
            // operators: only the sparse tests take it.
            MOp::Shl(k) | MOp::LShr(k)
                if local[a]
                    && cst[a].is_none()
                    && (matches!(n.op, MOp::LShr(_)) || !matches!(nodes[a].op, MOp::Var(_))) =>
            {
                bitwise = true;
                uniform = false;
                let k = i32::from(k);
                shift[i] = match (n.op, shift[a]) {
                    (_, ANY) => ANY,
                    (MOp::Shl(_), s) => s - k,
                    (_, s) => s + k,
                };
                local[i] = true;
                deg[i] = 1;
            }
            MOp::Not | MOp::Neg | MOp::Shl(_) => {
                local[i] = matches!(n.op, MOp::Not) && local[a];
                shift[i] = shift[a];
                deg[i] = deg[a];
                vdeg.copy_within(a * nv..(a + 1) * nv, i * nv);
            }
            MOp::Add | MOp::Sub => {
                deg[i] = deg[a].max(deg[b]);
                // Operands are earlier nodes: their rows lie before this one's.
                let (before, row) = vdeg.split_at_mut(i * nv);
                for (j, d) in row[..nv].iter_mut().enumerate() {
                    *d = before[a * nv + j].max(before[b * nv + j]);
                }
            }
            MOp::Mul => {
                deg[i] = deg[a].saturating_add(deg[b]).min(DEGREE_CAP);
                let (before, row) = vdeg.split_at_mut(i * nv);
                for (j, d) in row[..nv].iter_mut().enumerate() {
                    *d = before[a * nv + j]
                        .saturating_add(before[b * nv + j])
                        .min(DEGREE_CAP);
                }
            }
            MOp::LShr(_) | MOp::Zext | MOp::Sext | MOp::Trunc | MOp::Const(_) => {
                poly = false;
            }
        }
    }
    let root = nodes.len() - 1;
    Some(Profile {
        width: w,
        poly,
        uniform,
        bitwise,
        degree: deg[root],
        var_degree: vdeg[root * nv..(root + 1) * nv].to_vec(),
        used,
    })
}

// ----- sizes -----------------------------------------------------------------------------------

/// `C(n, k)`, saturating.
fn binom(n: u64, k: u64) -> u128 {
    if k > n {
        return 0;
    }
    let k = k.min(n - k);
    let mut r: u128 = 1;
    for i in 0..k {
        r = r.saturating_mul(u128::from(n - i)) / u128::from(i + 1);
        if r > u128::from(u64::MAX) {
            return u128::MAX;
        }
    }
    r
}

/// Points of the sparse test: `Σ_{k≤d} C(W,k)·(2^t − 1)^k`, saturating.
pub(crate) fn sparse_points(w: u16, t: usize, d: u32) -> u64 {
    let base: u128 = if t >= 64 { u128::MAX } else { (1u128 << t) - 1 };
    let mut total: u128 = 0;
    let mut pow: u128 = 1;
    for k in 0..=u64::from(d).min(u64::from(w)) {
        total = total.saturating_add(binom(u64::from(w), k).saturating_mul(pow));
        pow = pow.saturating_mul(base);
        if total >= u128::from(u64::MAX) {
            return u64::MAX;
        }
    }
    total as u64
}

/// The test chosen for two expressions, its points, and the variables it enumerates.
#[derive(Clone, Debug)]
struct Plan {
    cert: Cert,
    points: u64,
    /// The variables used by either side.
    used: Vec<usize>,
    /// Per used variable: the grid's radix (degree + 1).
    radix: Vec<u64>,
    degree: u32,
}

/// Every complete test that applies to `a` and `b` (same variables and width), in the order
/// ties are broken.
fn plans(a: &MbaExpr, pa: &Profile, pb: &Profile) -> Vec<Plan> {
    let used: Vec<usize> = (0..a.vars().len())
        .filter(|&v| pa.used.get(v) == Some(&true) || pb.used.get(v) == Some(&true))
        .collect();
    let t = used.len();
    let mut out = Vec::new();
    let degree = pa.degree.max(pb.degree);
    if pa.poly && pb.poly && pa.width == pb.width {
        if pa.uniform && pb.uniform && degree <= 1 && t <= SIGNATURE_VARS {
            out.push(Plan {
                cert: Cert::Signature,
                points: 1u64 << t,
                used: used.clone(),
                radix: Vec::new(),
                degree,
            });
        }
        if !pa.bitwise && !pb.bitwise {
            let radix: Vec<u64> = used
                .iter()
                .map(|&v| u64::from(pa.var_degree[v].max(pb.var_degree[v])) + 1)
                .collect();
            let points = radix
                .iter()
                .try_fold(1u64, |acc, &r| acc.checked_mul(r))
                .unwrap_or(u64::MAX);
            out.push(Plan {
                cert: Cert::Grid,
                points,
                used: used.clone(),
                radix,
                degree,
            });
        }
        out.push(Plan {
            cert: if degree <= 1 {
                Cert::SingleBit
            } else {
                Cert::Sparse
            },
            points: sparse_points(pa.width.bits(), t, degree),
            used: used.clone(),
            radix: Vec::new(),
            degree,
        });
    }
    let bits: u32 = used.iter().map(|&v| u32::from(a.vars()[v].bits())).sum();
    if bits <= EXHAUSTIVE_BITS {
        out.push(Plan {
            cert: Cert::Exhaustive,
            points: 1u64 << bits,
            used,
            radix: Vec::new(),
            degree,
        });
    }
    out
}

/// The cheapest complete test for `a` and `b` (same variables and width), if any applies.
fn plan(a: &MbaExpr, pa: &Profile, pb: &Profile) -> Option<Plan> {
    let mut best: Option<Plan> = None;
    for p in plans(a, pa, pb) {
        if best.as_ref().is_none_or(|b| p.points < b.points) {
            best = Some(p);
        }
    }
    best
}

/// Runs one kind of test on `a` and `b` if it applies (for tests: every test, not only the
/// cheapest). A forced sparse test uses degree at least 2. `Some(equal)`.
#[cfg(test)]
pub(crate) fn prove_with(a: &MbaExpr, b: &MbaExpr, cert: Cert) -> Option<bool> {
    let (pa, pb) = (profile(a)?, profile(b)?);
    let mut p = plans(a, &pa, &pb).into_iter().find(|p| {
        p.cert == cert
            || (cert == Cert::Sparse && p.cert == Cert::SingleBit)
            || (cert == Cert::SingleBit && p.cert == Cert::Sparse && p.degree <= 1)
    })?;
    if cert == Cert::Sparse && p.degree < 2 {
        p.degree = 2;
        p.cert = Cert::Sparse;
        p.points = sparse_points(pa.width.bits(), p.used.len(), 2);
    }
    let mut report = Report::new();
    match test(&mut Steps::new(u64::MAX), a, b, &p, &mut report, false).ok()? {
        Run::Equal(_) => Some(true),
        Run::Differ(_) => Some(false),
        _ => None,
    }
}

/// The cheapest direct test on `a` and `b`, with the symbolic comparison tried first where
/// [`run`] tries it or never (for tests): `Some((equal, the test that decided, the input
/// where they differ))`.
#[cfg(test)]
pub(crate) fn direct(
    a: &MbaExpr,
    b: &MbaExpr,
    symbolic: bool,
) -> Option<(bool, Cert, Option<Vec<BitVec>>)> {
    let (pa, pb) = (profile(a)?, profile(b)?);
    let p = plan(a, &pa, &pb)?;
    let mut report = Report::new();
    match test(&mut Steps::new(u64::MAX), a, b, &p, &mut report, symbolic).ok()? {
        Run::Equal(cert) => Some((true, cert, None)),
        Run::Differ(point) => Some((false, p.cert, Some(point))),
        _ => None,
    }
}

// ----- point generators ------------------------------------------------------------------------

/// Enumerates the points of a plan, a block at a time.
struct Points {
    cert: Cert,
    /// Signature, exhaustive: the next point and the total.
    next: u64,
    total: u64,
    /// Grid: the counter and its radix.
    ctr: Vec<u64>,
    radix: Vec<u64>,
    /// Sparse: the width, the size of the current position set, the positions and their
    /// patterns (each a nonzero subset of the used variables).
    width: u16,
    t: usize,
    d: u32,
    k: usize,
    combo: Vec<u16>,
    pats: Vec<u64>,
    done: bool,
}

impl Points {
    fn new(plan: &Plan, width: u16) -> Points {
        Points {
            cert: plan.cert,
            next: 0,
            total: plan.points,
            ctr: vec![0; plan.radix.len()],
            radix: plan.radix.clone(),
            width,
            t: plan.used.len(),
            d: plan.degree,
            k: 0,
            combo: Vec::new(),
            pats: Vec::new(),
            done: plan.points == 0,
        }
    }

    /// Fills up to [`BLOCK`] points into `cols` (one column per variable of the expression;
    /// unused variables stay 0). Returns how many.
    fn fill<L: Lane>(
        &mut self,
        cols: &mut [Vec<L>],
        used: &[usize],
        vars: &[Width],
        masks: &[L::M],
    ) -> usize {
        for c in cols.iter_mut() {
            if c.len() != BLOCK {
                c.clear();
                c.resize(BLOCK, L::default());
            }
        }
        let mut n = 0;
        match self.cert {
            Cert::Signature => {
                while n < BLOCK && !self.done {
                    for (j, &v) in used.iter().enumerate() {
                        cols[v][n] = if self.next >> j & 1 == 1 {
                            L::not(L::default(), masks[v])
                        } else {
                            L::default()
                        };
                    }
                    self.next += 1;
                    self.done = self.next >= self.total;
                    n += 1;
                }
            }
            Cert::Exhaustive => {
                while n < BLOCK && !self.done {
                    let mut rest = self.next;
                    for &v in used {
                        let bits = vars[v].bits();
                        let x = rest & ((1u64 << bits) - 1);
                        rest >>= bits;
                        cols[v][n] = L::small(x, masks[v]);
                    }
                    self.next += 1;
                    self.done = self.next >= self.total;
                    n += 1;
                }
            }
            Cert::Grid => {
                while n < BLOCK && !self.done {
                    for (j, &v) in used.iter().enumerate() {
                        cols[v][n] = L::small(self.ctr[j], masks[v]);
                    }
                    self.done = true;
                    for j in 0..self.ctr.len() {
                        self.ctr[j] += 1;
                        if self.ctr[j] < self.radix[j] {
                            self.done = false;
                            break;
                        }
                        self.ctr[j] = 0;
                    }
                    n += 1;
                }
            }
            Cert::SingleBit | Cert::Sparse => {
                // A column at a time, a run at a time: while the patterns of all positions but
                // the last stay, variable j is their bits plus the last position's bit where
                // the last pattern (counting up) holds j.
                let full = if self.t >= 64 {
                    u64::MAX
                } else {
                    (1u64 << self.t) - 1
                };
                while n < BLOCK && !self.done {
                    let k = self.k;
                    if k == 0 {
                        // The point with no bit set.
                        for &v in used {
                            cols[v][n] = L::default();
                        }
                        n += 1;
                        self.advance_positions();
                        continue;
                    }
                    let p0 = self.pats[k - 1];
                    let run = usize::try_from(full - p0 + 1)
                        .unwrap_or(usize::MAX)
                        .min(BLOCK - n);
                    let last = self.combo[k - 1];
                    for (j, &v) in used.iter().enumerate() {
                        let mut outer = L::default();
                        for s in 0..k - 1 {
                            if self.pats[s] >> j & 1 == 1 {
                                outer = L::or(outer, L::pow2(self.combo[s], masks[v]));
                            }
                        }
                        let with = L::or(outer, L::pow2(last, masks[v]));
                        for (i, c) in cols[v][n..n + run].iter_mut().enumerate() {
                            *c = if (p0 + i as u64) >> j & 1 == 1 {
                                with
                            } else {
                                outer
                            };
                        }
                    }
                    n += run;
                    if p0 + (run as u64 - 1) < full {
                        self.pats[k - 1] = p0 + run as u64;
                    } else {
                        // The last pattern wrapped: carry into the others, then the positions.
                        self.pats[k - 1] = 1;
                        let mut carry = true;
                        for s in (0..k - 1).rev() {
                            if self.pats[s] < full {
                                self.pats[s] += 1;
                                carry = false;
                                break;
                            }
                            self.pats[s] = 1;
                        }
                        if carry {
                            self.advance_positions();
                        }
                    }
                }
            }
            // No points: never planned.
            Cert::Symbolic | Cert::Carries => self.done = true,
        }
        n
    }

    /// With every pattern back at its first: the next set of positions of the same size, or
    /// one more position.
    fn advance_positions(&mut self) {
        // The next set of positions of the same size.
        let (k, w) = (self.k, self.width);
        for s in (0..k).rev() {
            if usize::from(self.combo[s]) < usize::from(w) - k + s {
                self.combo[s] += 1;
                for u in s + 1..k {
                    self.combo[u] = self.combo[u - 1] + 1;
                }
                return;
            }
        }
        // One more position.
        self.k += 1;
        if self.k as u64 > u64::from(self.d) || self.k > usize::from(w) || self.t == 0 {
            self.done = true;
            return;
        }
        self.combo = (0..self.k as u16).collect();
        self.pats = vec![1; self.k];
    }
}

// ----- running a test --------------------------------------------------------------------------

/// The outcome of one test.
enum Run {
    /// Equal everywhere: by the test, or by the symbolic comparison it ran first (see [`run`]).
    Equal(Cert),
    /// A point (one value per variable) where the sides differ.
    Differ(Vec<BitVec>),
    /// Not run: over the budget.
    OverBudget,
    /// Not run: over [`MAX_POINTS`].
    TooBig,
}

/// Runs a planned test. A polynomial test that would take far longer than the symbolic
/// comparison ([`symbolic_equal`]) runs the comparison first: within half the test's time
/// (at [`SYMBOLIC_UNIT`] evaluations per unit of its work) and within what is left, charged
/// at [`SYMBOLIC_RATE`]. It proves only sides that are equal everywhere, which the test would
/// find equal too; one that decides nothing leaves the test to run, or over budget when what
/// is left no longer covers it.
fn run<M: Meter>(
    meter: &mut M,
    a: &MbaExpr,
    b: &MbaExpr,
    plan: &Plan,
    report: &mut Report,
) -> Result<Run, M::Err> {
    test(meter, a, b, plan, report, true)
}

/// [`run`], evaluating in `lanes`.
fn run_lanes<M: Meter>(
    meter: &mut M,
    a: &MbaExpr,
    b: &MbaExpr,
    plan: &Plan,
    report: &mut Report,
    lanes: &mut Lanes<u64>,
) -> Result<Run, M::Err> {
    let progs = Program::new(a, false).zip(Program::new(b, false));
    let mut tested = Tested::default();
    test_with(
        meter,
        [a, b],
        progs.as_ref(),
        plan,
        report,
        true,
        &mut tested,
        Some(lanes),
    )
}

/// [`run`]; without `symbolic`, the planned test alone.
fn test<M: Meter>(
    meter: &mut M,
    a: &MbaExpr,
    b: &MbaExpr,
    plan: &Plan,
    report: &mut Report,
    symbolic: bool,
) -> Result<Run, M::Err> {
    let progs = Program::new(a, false).zip(Program::new(b, false));
    let mut tested = Tested::default();
    let mut lanes = take_lanes();
    let ran = test_with(
        meter,
        [a, b],
        progs.as_ref(),
        plan,
        report,
        symbolic,
        &mut tested,
        Some(&mut lanes),
    );
    give_lanes(lanes);
    ran
}

/// What testing one pair of expressions found that does not depend on the budget, kept while
/// the same pair may be tested again (a later policy that builds the same skeletons): how the
/// symbolic comparison ended and how the evaluation did. A test of the pair again makes the
/// same decisions on what is left of the budget and the same charges, and takes its answers
/// from here instead of working them out again.
#[derive(Default)]
struct Tested {
    symbolic: SymbolicSeen,
    /// The evaluation, once it ran to its end: the number of points of each block (each
    /// charged before it was evaluated), and the first point where the sides differ, if any.
    evaluated: Option<(Vec<u32>, Option<Vec<BitVec>>)>,
}

/// What is known of [`symbolic_equal`] on one pair, whatever its limit: its work goes up
/// check by check the same way under every limit, and it stops at the first check past its own.
#[derive(Default, Clone, Copy)]
enum SymbolicSeen {
    #[default]
    Unasked,
    /// It ended within its limit, after this much work, with this answer: so it does within
    /// any limit that is at least the work, and under a smaller one it is stopped.
    Ended(u64, bool),
    /// It was stopped by this limit (the largest tried): so it is by any limit up to it.
    Stopped(u64),
}

impl SymbolicSeen {
    /// [`symbolic_equal`] on `a` and `b` within `limit`: whether it proved them equal, and
    /// its work when it ended within the limit, or some amount above the limit when it was
    /// stopped (callers read no more of it than that).
    fn equal(&mut self, a: &MbaExpr, b: &MbaExpr, limit: u64) -> (bool, u64) {
        match *self {
            SymbolicSeen::Ended(work, equal) if work <= limit => return (equal, work),
            SymbolicSeen::Ended(work, _) => return (false, work),
            SymbolicSeen::Stopped(l) if limit <= l => return (false, l.saturating_add(1)),
            _ => {}
        }
        let mut work = 0u64;
        let equal = symbolic_equal(a, b, limit, &mut work) == Some(true);
        *self = if work > limit {
            SymbolicSeen::Stopped(limit)
        } else {
            SymbolicSeen::Ended(work, equal)
        };
        (equal, work)
    }
}

/// Lanes kept from one evaluation to the next: the variables' columns and the registers of
/// both sides.
#[derive(Default)]
struct Lanes<L> {
    cols: Vec<Vec<L>>,
    ra: Vec<Vec<L>>,
    rb: Vec<Vec<L>>,
}

/// What the certificates on a thread hand from one to the next instead of allocating it again:
/// the lanes of their evaluations and the rows of a sample. A certificate evaluates dozens of
/// small programs, and each took a vector per register and per variable, and each sample a
/// vector per node.
struct Scratch {
    lanes: Lanes<u64>,
    rows: Vec<Vec<u64>>,
}

/// The most vectors a thread keeps in its [`Scratch`], of each kind (a lane is at most
/// [`BLOCK`] words, a row [`SAMPLE_POINTS`]).
const SCRATCH_VECTORS: usize = 2048;

thread_local! {
    static SCRATCH: std::cell::RefCell<Scratch> = const {
        std::cell::RefCell::new(Scratch {
            lanes: Lanes {
                cols: Vec::new(),
                ra: Vec::new(),
                rb: Vec::new(),
            },
            rows: Vec::new(),
        })
    };
}

/// The thread's lanes (new ones when it has none to give).
fn take_lanes() -> Lanes<u64> {
    SCRATCH
        .try_with(|s| {
            s.try_borrow_mut()
                .map(|mut s| std::mem::take(&mut s.lanes))
                .ok()
        })
        .ok()
        .flatten()
        .unwrap_or_default()
}

/// Hands lanes back to the thread, unless they grew past what it keeps.
fn give_lanes(lanes: Lanes<u64>) {
    if lanes.cols.len() + lanes.ra.len() + lanes.rb.len() > SCRATCH_VECTORS {
        return;
    }
    let _ = SCRATCH.try_with(|s| {
        if let Ok(mut s) = s.try_borrow_mut() {
            s.lanes = lanes;
        }
    });
}

/// Up to `n` empty rows the thread kept.
fn take_rows(n: usize) -> Vec<Vec<u64>> {
    SCRATCH
        .try_with(|s| {
            s.try_borrow_mut()
                .map(|mut s| {
                    let keep = s.rows.len().saturating_sub(n);
                    s.rows.split_off(keep)
                })
                .ok()
        })
        .ok()
        .flatten()
        .unwrap_or_default()
}

/// Hands rows back to the thread, emptied, up to what it keeps.
fn give_rows(rows: &mut Vec<Vec<u64>>) {
    let _ = SCRATCH.try_with(|s| {
        if let Ok(mut s) = s.try_borrow_mut() {
            for mut row in rows.drain(..) {
                if s.rows.len() >= SCRATCH_VECTORS {
                    break;
                }
                row.clear();
                s.rows.push(row);
            }
        }
    });
}

/// [`test`] on sides already compiled (`None`: one has no nodes), with what earlier tests of
/// the same pair found (`tested`), in `lanes` when the caller keeps some.
#[allow(clippy::too_many_arguments)]
fn test_with<M: Meter>(
    meter: &mut M,
    [a, b]: [&MbaExpr; 2],
    progs: Option<&(Program, Program)>,
    plan: &Plan,
    report: &mut Report,
    symbolic: bool,
    tested: &mut Tested,
    lanes: Option<&mut Lanes<u64>>,
) -> Result<Run, M::Err> {
    let Some((pa, pb)) = progs else {
        return Ok(Run::TooBig);
    };
    let kind = Kind::of(pa.widest().max(pb.widest()));
    let per = (pa.len() + pb.len()) as u64;
    let lane = match kind {
        Kind::N64 => 1,
        Kind::N128 => 2,
        Kind::Wide => 8,
    };
    if plan.points > MAX_POINTS || plan.points.saturating_mul(per).saturating_mul(lane) > MAX_EFFORT
    {
        return Ok(Run::TooBig);
    }
    let cost = plan.points.saturating_mul(per);
    if cost > meter.left() {
        report.over_budget = true;
        return Ok(Run::OverBudget);
    }
    // The polynomial tests are planned for polynomial sides only, which the comparison reads;
    // it takes at least a unit per node.
    let cap = (cost.saturating_mul(lane) / (2 * SYMBOLIC_UNIT)).min(meter.left() / SYMBOLIC_RATE);
    if symbolic && plan.cert != Cert::Exhaustive && cap >= per {
        let (equal, work) = tested.symbolic.equal(a, b, cap);
        meter.charge(work.min(cap) * SYMBOLIC_RATE)?;
        if equal {
            return Ok(Run::Equal(Cert::Symbolic));
        }
        if cost > meter.left() {
            report.over_budget = true;
            return Ok(Run::OverBudget);
        }
    }
    // The evaluation again: charged block by block as it was, with the answer it gave.
    if let Some((blocks, differ)) = &tested.evaluated {
        for &n in blocks {
            meter.charge(per * u64::from(n))?;
            report.points += u64::from(n);
        }
        return Ok(match differ {
            Some(point) => Run::Differ(point.clone()),
            None => Run::Equal(plan.cert),
        });
    }
    let width = a.width().map_or(1, |w| w.bits());
    let mut blocks: Vec<u32> = Vec::new();
    let ran = match (kind, lanes) {
        (Kind::N64, Some(l)) => {
            run_in::<u64, M>(meter, a, pa, pb, plan, width, report, l, &mut blocks)
        }
        (Kind::N64, None) => {
            let l = &mut Lanes::default();
            run_in::<u64, M>(meter, a, pa, pb, plan, width, report, l, &mut blocks)
        }
        (Kind::N128, _) => {
            let l = &mut Lanes::default();
            run_in::<u128, M>(meter, a, pa, pb, plan, width, report, l, &mut blocks)
        }
        (Kind::Wide, _) => {
            let l = &mut Lanes::default();
            run_in::<Wide, M>(meter, a, pa, pb, plan, width, report, l, &mut blocks)
        }
    }?;
    let differ = match &ran {
        Run::Differ(point) => Some(point.clone()),
        _ => None,
    };
    tested.evaluated = Some((blocks, differ));
    Ok(ran)
}

/// Evaluates the plan's points on both sides, a block at a time, in `lanes`; the points of
/// each block charged are added to `blocks`.
#[allow(clippy::too_many_arguments)]
fn run_in<L: Lane, M: Meter>(
    meter: &mut M,
    a: &MbaExpr,
    pa: &Program,
    pb: &Program,
    plan: &Plan,
    width: u16,
    report: &mut Report,
    lanes: &mut Lanes<L>,
    blocks: &mut Vec<u32>,
) -> Result<Run, M::Err> {
    let vars = a.vars();
    let masks: Vec<L::M> = vars.iter().map(|&w| L::mask(w)).collect();
    let Lanes { cols, ra, rb } = lanes;
    // A column of zeros per variable: one the plan does not use stays 0, whatever an earlier
    // evaluation left in the lanes.
    cols.resize_with(vars.len(), Vec::new);
    for c in cols.iter_mut() {
        c.clear();
        c.resize(BLOCK, L::default());
    }
    let mut points = Points::new(plan, width);
    let per = (pa.len() + pb.len()) as u64;
    loop {
        let n = points.fill(cols, &plan.used, vars, &masks);
        if n == 0 {
            return Ok(Run::Equal(plan.cert));
        }
        meter.charge(per * n as u64)?;
        report.points += n as u64;
        blocks.push(n as u32);
        pa.run(ra, cols, n);
        pb.run(rb, cols, n);
        let (x, y) = (&ra[pa.root()][..n], &rb[pb.root()][..n]);
        if let Some(p) = (0..n).find(|&p| x[p] != y[p]) {
            let point = vars
                .iter()
                .enumerate()
                .map(|(v, &w)| cols[v][p].to_bv(w))
                .collect();
            return Ok(Run::Differ(point));
        }
    }
}

// ----- the refutation sample -------------------------------------------------------------------

/// The distinct constants of `ms`, sorted, with their neighbours `c ± 1`, `−c` and `~c`: the
/// values a point function or a rare carry pattern is likely to single out.
fn constant_pool(ms: &[&MbaExpr]) -> Vec<BitVec> {
    let mut consts: Vec<BitVec> = ms
        .iter()
        .flat_map(|m| m.nodes().iter())
        .filter_map(|n| match n.op {
            MOp::Const(v) => Some(v),
            _ => None,
        })
        .collect();
    // The first `POOL` distinct values, the constants taken in increasing order: later
    // constants cannot change them, so the walk ends when the pool is full (with many
    // constants it was quadratic in all of them, for entries that were then cut off). A
    // constant met twice adds nothing the second time, and few constants are needed, so they
    // are put in order a stretch at a time: the smallest `STRETCH` of those left, sorted.
    const POOL: usize = 32;
    const STRETCH: usize = 16;
    let mut pool: Vec<BitVec> = Vec::with_capacity(POOL);
    let mut held: HashMap<BitVec, ()> =
        HashMap::with_capacity_and_hasher(2 * POOL, Default::default());
    let mut rest: &mut [BitVec] = &mut consts;
    'fill: while !rest.is_empty() {
        let k = rest.len().min(STRETCH);
        if k < rest.len() {
            rest.select_nth_unstable(k - 1);
        }
        let (stretch, later) = std::mem::take(&mut rest).split_at_mut(k);
        stretch.sort_unstable();
        for c in stretch.iter() {
            let one = BitVec::one(c.width());
            for v in [
                *c,
                BitVec::bin_unchecked(BinOp::Add, c, &one),
                BitVec::bin_unchecked(BinOp::Sub, c, &one),
                BitVec::un_unchecked(UnOp::Neg, c),
                BitVec::un_unchecked(UnOp::Not, c),
            ] {
                if held.insert(v, ()).is_none() {
                    pool.push(v);
                    if pool.len() == POOL {
                        break 'fill;
                    }
                }
            }
        }
        rest = later;
    }
    pool
}

/// SplitMix64 words from `state`.
fn next_word(state: &mut u64) -> u64 {
    *state = state.wrapping_add(0x9e37_79b9_7f4a_7c15);
    let mut z = *state;
    z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
    z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
    z ^ (z >> 31)
}

/// The refutation sample for `ms` over variables `vars`: [`SAMPLE_POINTS`] points (point-major),
/// deterministic in `seed`. Zero, all-ones, one and the signed minimum for every variable; then
/// the constants of the expressions and their neighbours (each variable takes each of them at
/// some point); then points whose set bits lie at one position; then seeded random values.
/// A filter that catches wrong answers early; never evidence.
pub(crate) fn sample_points(vars: &[Width], ms: &[&MbaExpr], seed: u64) -> Vec<Vec<BitVec>> {
    let mut pts = fixed_points(vars, ms);
    seeded_points(vars, seed, &mut pts);
    pts
}

/// The first points of [`sample_points`], which do not depend on the seed: zero, all-ones, one
/// and the signed minimum, the constants and their neighbours, the single positions.
fn fixed_points(vars: &[Width], ms: &[&MbaExpr]) -> Vec<Vec<BitVec>> {
    let pool = constant_pool(ms);
    let fit = |c: &BitVec, w: Width| BitVec::wrapping_from_limbs(w, c.limbs());
    let mut pts: Vec<Vec<BitVec>> = Vec::with_capacity(SAMPLE_POINTS);
    for k in 0..4 {
        pts.push(
            vars.iter()
                .map(|&w| match k {
                    0 => BitVec::zero(w),
                    1 => BitVec::ones(w),
                    2 => BitVec::one(w),
                    _ => BitVec::smin(w),
                })
                .collect(),
        );
    }
    for q in 0..pool.len() {
        pts.push(
            vars.iter()
                .enumerate()
                .map(|(v, &w)| fit(&pool[(q + v) % pool.len()], w))
                .collect(),
        );
    }
    // Single positions: at point `s`, the variables in pattern `s % 3 + 1` (bit `v` for
    // variable `v`, repeating every two variables) have bit `j_s` set, the others are 0.
    for s in 0..8usize {
        let pattern = s % 3 + 1;
        pts.push(
            vars.iter()
                .enumerate()
                .map(|(v, &w)| {
                    let bits = w.bits();
                    let j = [
                        0,
                        1,
                        bits / 2,
                        bits - 1,
                        2,
                        bits / 4,
                        3 * bits / 4,
                        bits.saturating_sub(2),
                    ][s]
                        .min(bits - 1);
                    if pattern >> (v % 2) & 1 == 1 {
                        <Wide as Lane>::pow2(j, w).to_bv(w)
                    } else {
                        BitVec::zero(w)
                    }
                })
                .collect(),
        );
    }
    pts
}

/// The rest of [`sample_points`] after its [`fixed_points`]: seeded random values, up to
/// [`SAMPLE_POINTS`] points in all.
fn seeded_points(vars: &[Width], seed: u64, pts: &mut Vec<Vec<BitVec>>) {
    let mut state = seed;
    while pts.len() < SAMPLE_POINTS {
        pts.push(
            vars.iter()
                .map(|&w| {
                    let limbs: [u64; 8] = std::array::from_fn(|_| next_word(&mut state));
                    BitVec::wrapping_from_limbs(w, &limbs)
                })
                .collect(),
        );
    }
    pts.truncate(SAMPLE_POINTS);
}

/// The first sample point where `a` and `b` differ, if any. `None` when they agree (or cannot
/// be compared).
pub(crate) fn refute(a: &MbaExpr, b: &MbaExpr, points: &[Vec<BitVec>]) -> Option<Vec<BitVec>> {
    let (pa, pb) = (Program::new(a, false)?, Program::new(b, false)?);
    let (va, vb) = (pa.eval_points(points), pb.eval_points(points));
    (0..points.len().min(va.len()).min(vb.len()))
        .find(|&p| va[p] != vb[p])
        .map(|p| points[p].clone())
}

// ----- the certificate -------------------------------------------------------------------------

/// Decides `a == b` (on every input) if one of the tests applies within the budget: the
/// cheapest direct test, else over abstracted atoms, else with known bits read as arithmetic,
/// else case by case. `Refuted` only with a concrete input where they differ; `Unknown` when
/// no test applies, a test is over the budget, or only skeletons over abstracted atoms were
/// found to differ. Expressions over different variables or of different widths are not
/// compared (`Unknown`).
pub(crate) fn prove<M: Meter>(a: &MbaExpr, b: &MbaExpr, meter: &mut M) -> Result<Report, M::Err> {
    // Sums and differences that are bitwise functions, read as such (equal expressions, see
    // `raise_disjoint`): every test below then takes them for what they are.
    let (ra, rb) = (raise_disjoint(a), raise_disjoint(b));
    let (a, b) = (ra.as_ref().unwrap_or(a), rb.as_ref().unwrap_or(b));
    // casts are atoms to the tests below, so a side that spells a value through
    // the low half of another is unrelated to it there, and the tests spend their work on
    // abstractions that cannot decide. Sides with casts are compared without them first
    // (equal expressions, see `decast`), and as they are only when that does not decide.
    let (da, db) = (super::decast::decast(a), super::decast::decast(b));
    let mut report = Report::new();
    // First, sides that are each a constant plus a multiple of every bit of the variables,
    // compared as that (see `bit_linear`): it decides where it applies, for a pass over each
    // side. A sum of products of bitwise functions of one value by constants is one whatever
    // its carries, and the tests below take it for an atom under a mask.
    if let Some(found) = bit_linear(meter, da.as_ref().unwrap_or(a), db.as_ref().unwrap_or(b))? {
        report.cert = Some(Cert::Symbolic);
        match found {
            None => report.verdict = Verdict::Proved,
            Some(point) => {
                report.verdict = Verdict::Refuted;
                report.counterexample = Some(point);
            }
        }
        return Ok(report);
    }
    // Sides that read the same bits of a value the same way (`(s >> 8) & 9` of each) are
    // equal exactly when the values agree on those bits (see `peeled`): without the right
    // shift each is a function of the low bits of its variables, which the tests follow.
    if let Some((pa, pb)) = peeled(a, b) {
        let sub = prove(&pa, &pb, meter)?;
        if sub.verdict != Verdict::Unknown {
            return Ok(sub);
        }
        report.points += sub.points;
        report.over_budget |= sub.over_budget;
        report.internal += sub.internal;
    }
    if da.is_some() || db.is_some() {
        report = prove_at(
            da.as_ref().unwrap_or(a),
            db.as_ref().unwrap_or(b),
            meter,
            0,
            false,
            true,
        )?;
    }
    if report.verdict == Verdict::Unknown {
        report = prove_at(a, b, meter, 0, false, true)?;
    }
    // Still open, and not for lack of budget: a polynomial question over registers read
    // through their low bits, compared as polynomials over symbols with those registers as
    // narrow atoms (`decast_narrow`). Over the masks the question is outside the fragment the
    // polynomial tests and the symbolic comparison decide, and the tests over abstracted atoms
    // leave it open; over the narrow atoms the identity is one the comparison reads. Only the
    // comparison, which is cheap and only ever proves: an evaluation test over the atoms would
    // spend as much as the tests above and decide no more.
    if report.verdict == Verdict::Unknown && !report.over_budget {
        let narrow = |m: &MbaExpr| super::decast::decast_narrow(m).filter(|(_, n)| *n);
        if let (Some((na, _)), Some((nb, _))) = (narrow(a), narrow(b))
            && na.vars() == nb.vars()
            && na.width() == nb.width()
            && symbolic(meter, &na, &nb, &mut report)?
        {
            report.verdict = Verdict::Proved;
            report.cert = Some(Cert::Symbolic);
        }
    }
    // Still open: sides that read the low bits of two values through one mask (`s & k` of
    // each, `k` with no bit from position `j` on) are equal when the values agree modulo
    // `2^j`, which is when `s·2^(W−j)` of each are equal: products by a constant, in the
    // fragment the polynomial tests decide whatever the values are above `j`. Under the mask
    // the two values are atoms of their own to the tests above, unrelated wherever they
    // differ above `j`. Only ever proves.
    if report.verdict == Verdict::Unknown
        && !report.over_budget
        && let Some((la, lb)) = low_read(a, b)
    {
        let sub = prove_at(&la, &lb, meter, SPLIT_DEPTH, true, false)?;
        report.points += sub.points;
        report.over_budget |= sub.over_budget;
        report.internal += sub.internal;
        if sub.verdict == Verdict::Proved {
            report.verdict = Verdict::Proved;
            report.cert = sub.cert;
            report.compositional = sub.compositional;
        }
    }
    // A refutation comes with an input where the sides differ; one without would be a bug
    // (decided nothing).
    if report.verdict == Verdict::Refuted
        && report
            .counterexample
            .as_ref()
            .is_none_or(|p| match a.eval(p) {
                None => true,
                va => va == b.eval(p),
            })
    {
        debug_assert!(false, "a refutation without a counterexample");
        report.verdict = Verdict::Unknown;
        report.counterexample = None;
        report.internal += 1;
    }
    Ok(report)
}

/// For `a = s & k` and `b = t & k` with one constant `k` that has no bit from position `j`
/// on (`j` below the width): `s << (W − j)` and `t << (W − j)`, equal exactly when `s` and
/// `t` agree on their low `j` bits, and then so do `a` and `b`. `None` for other sides.
fn low_read(a: &MbaExpr, b: &MbaExpr) -> Option<(MbaExpr, MbaExpr)> {
    let w = a.width()?;
    if b.width() != Some(w) || a.vars() != b.vars() {
        return None;
    }
    // The root's operand and its constant.
    let parts = |m: &MbaExpr| -> Option<(u32, BitVec)> {
        let nodes = m.nodes();
        let root = nodes.last()?;
        if root.op != MOp::And {
            return None;
        }
        let cst = constants(nodes);
        match (cst[root.args[0] as usize], cst[root.args[1] as usize]) {
            (None, Some(k)) => Some((root.args[0], k)),
            (Some(k), None) => Some((root.args[1], k)),
            _ => None,
        }
    };
    let ((sa, ka), (sb, kb)) = (parts(a)?, parts(b)?);
    if ka != kb {
        return None;
    }
    let j = (ka.limbs().iter().enumerate())
        .filter(|&(_, &l)| l != 0)
        .map(|(i, &l)| i as u32 * 64 + 64 - l.leading_zeros())
        .max()?;
    let bits = u32::from(w.bits());
    if j >= bits {
        return None;
    }
    let shifted = |m: &MbaExpr, s: u32| -> Option<MbaExpr> {
        let mut out = MbaExpr::new(m.vars().to_vec());
        for n in &m.nodes()[..=s as usize] {
            match n.op {
                MOp::Zext | MOp::Sext | MOp::Trunc => {
                    out.push_cast(n.op, n.args[0], n.width).ok()?
                }
                op => out.push(op, &n.args[..op.arity()]).ok()?,
            };
        }
        out.push(MOp::Shl((bits - j) as u16), &[s]).ok()?;
        Some(out)
    };
    Some((shifted(a, sa)?, shifted(b, sb)?))
}

/// `a` and `b` without what both read their values through, when that includes a right
/// shift: the two values, each under the mask of the bits read. From the roots inward, while
/// both sides apply the same step (a right shift by one count, `&`, `|` or `^` with one
/// constant, a complement, a cast to one width), the bits of the operand that reach the root
/// are followed; each step is a one-to-one function of those bits, so the sides are equal at
/// an input exactly when the two operands agree there on the mask (a proof of either is one of
/// the other, and so is a counterexample). `None` when no right shift is passed, or nothing is
/// left to compare.
fn peeled(a: &MbaExpr, b: &MbaExpr) -> Option<(MbaExpr, MbaExpr)> {
    let (na, nb) = (a.nodes(), b.nodes());
    let (mut ia, mut ib) = (na.len().checked_sub(1)?, nb.len().checked_sub(1)?);
    let w = na[ia].width;
    if w != nb[ib].width || w.bits() > 64 || a.vars() != b.vars() {
        return None;
    }
    let ones = |w: Width| {
        if w.bits() == 64 {
            u64::MAX
        } else {
            (1u64 << w.bits()) - 1
        }
    };
    let konst = |n: &[MNode], i: u32| match n[i as usize].op {
        MOp::Const(c) => c.to_u64(),
        _ => None,
    };
    // An operand and a constant, in either order.
    let with = |n: &[MNode], i: usize| -> Option<(usize, u64)> {
        let [x, y] = n[i].args;
        match (konst(n, x), konst(n, y)) {
            (None, Some(c)) => Some((x as usize, c)),
            (Some(c), None) => Some((y as usize, c)),
            _ => None,
        }
    };
    let (mut mask, mut shifted) = (ones(w), false);
    loop {
        let (x, y) = (na[ia], nb[ib]);
        if x.width != y.width || x.width.bits() > 64 {
            break;
        }
        match (x.op, y.op) {
            (MOp::LShr(j), MOp::LShr(k)) if j == k => {
                mask = mask << j & ones(x.width);
                shifted = true;
                (ia, ib) = (x.args[0] as usize, y.args[0] as usize);
            }
            (MOp::Not, MOp::Not) => (ia, ib) = (x.args[0] as usize, y.args[0] as usize),
            (MOp::Trunc, MOp::Trunc) | (MOp::Zext, MOp::Zext) => {
                let (p, q) = (x.args[0] as usize, y.args[0] as usize);
                if na[p].width != nb[q].width || na[p].width.bits() > 64 {
                    break;
                }
                mask &= ones(na[p].width);
                (ia, ib) = (p, q);
            }
            (MOp::And | MOp::Or | MOp::Xor, op) if op == x.op => {
                let (Some((p, c)), Some((q, d))) = (with(na, ia), with(nb, ib)) else {
                    break;
                };
                if c != d {
                    break;
                }
                mask &= match op {
                    MOp::And => c,
                    MOp::Or => !c,
                    _ => u64::MAX,
                };
                (ia, ib) = (p, q);
            }
            _ => break,
        }
    }
    if !shifted || mask == 0 {
        return None;
    }
    // Each side up to its operand, under the mask.
    let under = |m: &MbaExpr, at: usize| -> Option<MbaExpr> {
        let mut out = MbaExpr::new(m.vars().to_vec());
        for n in &m.nodes()[..=at] {
            match n.op {
                MOp::Zext | MOp::Sext | MOp::Trunc => out.push_cast(n.op, n.args[0], n.width),
                _ => out.push(n.op, &n.args[..n.op.arity()]),
            }
            .ok()?;
        }
        let w = m.nodes()[at].width;
        let k = out
            .push(MOp::Const(BitVec::wrapping_from_u64(w, mask)), &[])
            .ok()?;
        out.push(MOp::And, &[at as u32, k]).ok()?;
        Some(out)
    };
    Some((under(a, ia)?, under(b, ib)?))
}

/// The most bits of variables [`bit_linear`] takes.
const LINEAR_BITS: usize = 256;

/// A value as `k + Σ dᵢ·bᵢ` over the bits `bᵢ` of the variables, modulo `2^w`.
#[derive(Clone, PartialEq, Eq)]
struct BitLinear {
    k: u64,
    d: Vec<u64>,
}

/// A value each bit of which is a constant, a bit of a variable or its complement: bit `j` is
/// `alpha[j] ^ b` for the variable bit `b = src[j]` where `has[j]`, else `alpha[j]`.
struct BitAffine {
    alpha: u64,
    has: u64,
    src: [u16; 64],
}

impl BitLinear {
    /// The form as a [`BitAffine`], when each variable bit it reads sets or clears one bit
    /// of its own and the constant left has none of those: no carry, so every bit is the
    /// constant's or one variable bit's (`k + 2^p·b` with bit `p` of `k` clear is `k | b << p`;
    /// `k − 2^p·b` is `(k − 2^p) + 2^p·~b`).
    fn affine(&self, ones: u64) -> Option<BitAffine> {
        let mut out = BitAffine {
            alpha: 0,
            has: 0,
            src: [0; 64],
        };
        let mut k = self.k;
        for (i, &d) in self.d.iter().enumerate() {
            if d == 0 {
                continue;
            }
            let neg = d.wrapping_neg() & ones;
            let (p, minus) = if d.is_power_of_two() {
                (d.trailing_zeros(), false)
            } else if neg.is_power_of_two() {
                (neg.trailing_zeros(), true)
            } else {
                return None;
            };
            let bit = 1u64 << p;
            if out.has & bit != 0 {
                return None;
            }
            out.has |= bit;
            out.src[p as usize] = i as u16;
            if minus {
                out.alpha |= bit;
                k = k.wrapping_sub(bit) & ones;
            }
        }
        // The top bit's multiple is its own negation: the bit is the variable bit's
        // complement where the constant has it set.
        let top = ones ^ (ones >> 1);
        if out.has & k & top != 0 {
            out.alpha |= top;
            k ^= top;
        }
        if k & out.has != 0 {
            return None;
        }
        out.alpha |= k;
        Some(out)
    }
}

/// The most variable bits [`BitLinear::low`] takes the residues of a form over.
const LOW_BITS: usize = 10;

/// The most runs of ones [`BitLinear::masked`] takes a mask apart into.
const MASK_RUNS: usize = 8;

impl BitLinear {
    /// The form's value modulo `2^n` (its low `n` bits) as a form, when it is one: the
    /// multiples that are not 0 modulo `2^n` belong to at most [`LOW_BITS`] variable bits,
    /// and over every value of those the residue is a constant plus one term for each (no
    /// carry out of the low bits that depends on two of them at once). A product of a masked
    /// value by a constant has such a residue wherever the mask keeps few low bits.
    fn low(&self, n: usize, wn: usize, ones: u64) -> Option<BitLinear> {
        if n >= wn {
            return Some(self.clone());
        }
        let m = (1u64 << n) - 1;
        let at: Vec<usize> = (0..self.d.len()).filter(|&i| self.d[i] & m != 0).collect();
        if at.len() > LOW_BITS {
            return None;
        }
        let base = self.k & m;
        let each: Vec<u64> = at
            .iter()
            .map(|&i| (self.k.wrapping_add(self.d[i]) & m).wrapping_sub(base) & ones)
            .collect();
        for set in 0u32..1 << at.len() {
            let (mut sum, mut form) = (self.k, base);
            for (j, &i) in at.iter().enumerate() {
                if set >> j & 1 == 1 {
                    sum = sum.wrapping_add(self.d[i]);
                    form = form.wrapping_add(each[j]);
                }
            }
            if sum & m != form & ones {
                return None;
            }
        }
        let mut out = BitLinear {
            k: base,
            d: vec![0; self.d.len()],
        };
        for (j, &i) in at.iter().enumerate() {
            out.d[i] = each[j];
        }
        Some(out)
    }

    /// The form under the constant mask `c`, as a form: for each run of ones `[a, b)` of the
    /// mask, the low `b` bits less the low `a` bits (see [`low`](BitLinear::low)).
    fn masked(&self, c: u64, wn: usize, ones: u64) -> Option<BitLinear> {
        let mut out = BitLinear {
            k: 0,
            d: vec![0; self.d.len()],
        };
        let (mut left, mut runs) = (c & ones, 0);
        while left != 0 {
            runs += 1;
            if runs > MASK_RUNS {
                return None;
            }
            let a = left.trailing_zeros() as usize;
            let b = a + (left >> a).trailing_ones() as usize;
            let (hi, lo) = (self.low(b, wn, ones)?, self.low(a, wn, ones)?);
            out.k = out.k.wrapping_add(hi.k).wrapping_sub(lo.k) & ones;
            for (o, (h, l)) in out.d.iter_mut().zip(hi.d.iter().zip(&lo.d)) {
                *o = o.wrapping_add(*h).wrapping_sub(*l) & ones;
            }
            left = if b >= 64 { 0 } else { left >> b << b };
        }
        Some(out)
    }
}

impl BitAffine {
    fn linear(&self, bits: usize, ones: u64) -> BitLinear {
        let mut out = BitLinear {
            k: self.alpha & ones,
            d: vec![0; bits],
        };
        let mut left = self.has & ones;
        while left != 0 {
            let p = left.trailing_zeros();
            left &= left - 1;
            let bit = 1u64 << p;
            let d = &mut out.d[self.src[p as usize] as usize];
            // `1 ^ b` is `1 − b`.
            *d = match self.alpha & bit != 0 {
                true => d.wrapping_sub(bit),
                false => d.wrapping_add(bit),
            } & ones;
        }
        out
    }
}

/// Whether `a` and `b` are equal, where each is a constant plus a multiple of every bit of
/// the variables modulo the width: `None` when a side is not read as one, `Some(None)` when
/// they are equal, `Some(Some(point))` with an input where they differ.
///
/// Sums, differences, negations, complements, left shifts and products by a constant keep
/// such a form whatever it is. `& | ^` and a right shift take operands every bit of which is a
/// constant, a variable bit or its complement (a form that sets or clears one bit for each
/// variable bit it reads, with no carry), and give one: two bits over the same variable bit
/// combine to it, its complement or a constant. A form with carries under `& | ^` with a
/// constant is read by the mask's fields, where its low bits are a form (a product by a
/// constant with its low byte masked off: `(x & m)·c & −256`). Two forms are the same function exactly when
/// their constants and multiples are the same (at zero, and at each single variable bit), so
/// the comparison decides, at 64 bits or fewer and up to [`LINEAR_BITS`] bits of variables.
/// One unit of work per node read and 16 variable bits, where it decides.
fn bit_linear<M: Meter>(
    meter: &mut M,
    a: &MbaExpr,
    b: &MbaExpr,
) -> Result<Option<Option<Vec<BitVec>>>, M::Err> {
    let (Some(w), Some(wb)) = (a.width(), b.width()) else {
        return Ok(None);
    };
    if w != wb || w.bits() > 64 || a.vars() != b.vars() {
        return Ok(None);
    }
    let bits = a.vars().len() * usize::from(w.bits());
    if bits == 0 || bits > LINEAR_BITS {
        return Ok(None);
    }
    // A unit per node read and 16 variable bits; it gives up at the first node without a
    // form.
    let per = (bits / 16 + 1) as u64;
    if (a.nodes().len() + b.nodes().len()) as u64 * per > meter.left() {
        return Ok(None);
    }
    let read = std::cell::Cell::new(0u64);
    let wn = usize::from(w.bits());
    let ones = if wn == 64 { u64::MAX } else { (1u64 << wn) - 1 };
    let form = |m: &MbaExpr| -> Option<BitLinear> {
        let nodes = m.nodes();
        let live = live(m);
        let mut forms: Vec<Option<BitLinear>> = Vec::with_capacity(nodes.len());
        for (at, n) in nodes.iter().enumerate() {
            // A node the root does not read is not read here either.
            if !live[at] {
                forms.push(None);
                continue;
            }
            read.set(read.get() + 1);
            let arg = |j: usize| forms[n.args[j] as usize].as_ref();
            let zip = |x: &BitLinear, y: &BitLinear, f: fn(u64, u64) -> u64| BitLinear {
                k: f(x.k, y.k) & ones,
                d: x.d
                    .iter()
                    .zip(&y.d)
                    .map(|(&p, &q)| f(p, q) & ones)
                    .collect(),
            };
            let scale = |x: &BitLinear, c: u64| BitLinear {
                k: x.k.wrapping_mul(c) & ones,
                d: x.d.iter().map(|&p| p.wrapping_mul(c) & ones).collect(),
            };
            let konst = |x: &BitLinear| x.d.iter().all(|&p| p == 0).then_some(x.k);
            let f = (|| match n.op {
                _ if n.width != w => None,
                MOp::Const(c) => Some(BitLinear {
                    k: c.to_u64()? & ones,
                    d: vec![0; bits],
                }),
                MOp::Var(v) => {
                    let mut d = vec![0; bits];
                    for j in 0..wn {
                        d[v as usize * wn + j] = 1u64 << j;
                    }
                    Some(BitLinear { k: 0, d })
                }
                MOp::Add => Some(zip(arg(0)?, arg(1)?, u64::wrapping_add)),
                MOp::Sub => Some(zip(arg(0)?, arg(1)?, u64::wrapping_sub)),
                MOp::Neg => Some(scale(arg(0)?, u64::MAX)),
                // `~x` is `−x − 1`.
                MOp::Not => {
                    let mut x = scale(arg(0)?, u64::MAX);
                    x.k = x.k.wrapping_sub(1) & ones;
                    Some(x)
                }
                MOp::Shl(s) => Some(scale(arg(0)?, 1u64.checked_shl(u32::from(s))?)),
                MOp::Mul => {
                    let (x, y) = (arg(0)?, arg(1)?);
                    match (konst(x), konst(y)) {
                        (Some(c), _) => Some(scale(y, c)),
                        (_, Some(c)) => Some(scale(x, c)),
                        _ => None,
                    }
                }
                MOp::LShr(s) => {
                    let x = arg(0)?.affine(ones)?;
                    let s = u32::from(s);
                    let mut out = BitAffine {
                        alpha: x.alpha.checked_shr(s)?,
                        has: x.has.checked_shr(s)?,
                        src: [0; 64],
                    };
                    for j in 0..wn.saturating_sub(s as usize) {
                        out.src[j] = x.src[j + s as usize];
                    }
                    Some(out.linear(bits, ones))
                }
                MOp::And | MOp::Or | MOp::Xor => {
                    let (fx, fy) = (arg(0)?, arg(1)?);
                    let (Some(x), Some(y)) = (fx.affine(ones), fy.affine(ones)) else {
                        // A form with carries, under a constant: its fields (see `masked`).
                        let (l, c) = match (konst(fx), konst(fy)) {
                            (None, Some(c)) => (fx, c),
                            (Some(c), None) => (fy, c),
                            _ => return None,
                        };
                        let m = l.masked(c, wn, ones)?;
                        let k = BitLinear {
                            k: c,
                            d: vec![0; bits],
                        };
                        return Some(match n.op {
                            MOp::And => m,
                            // `x | c` is `x − (x & c) + c`; `x ^ c` is `x + c − 2·(x & c)`.
                            MOp::Or => zip(&zip(l, &m, u64::wrapping_sub), &k, u64::wrapping_add),
                            _ => zip(
                                &zip(l, &k, u64::wrapping_add),
                                &scale(&m, 2),
                                u64::wrapping_sub,
                            ),
                        });
                    };
                    let mut out = BitAffine {
                        alpha: 0,
                        has: 0,
                        src: [0; 64],
                    };
                    let op = |p: bool, q: bool| match n.op {
                        MOp::And => p & q,
                        MOp::Or => p | q,
                        _ => p ^ q,
                    };
                    for j in 0..wn {
                        let bit = 1u64 << j;
                        let (hx, hy) = (x.has & bit != 0, y.has & bit != 0);
                        let (ax, ay) = (x.alpha & bit != 0, y.alpha & bit != 0);
                        if hx && hy && x.src[j] != y.src[j] {
                            return None;
                        }
                        // The bit where the variable bit is 0, and where it is 1.
                        let at0 = op(ax, ay);
                        let at1 = op(ax ^ hx, ay ^ hy);
                        if at0 {
                            out.alpha |= bit;
                        }
                        if at0 != at1 {
                            out.has |= bit;
                            out.src[j] = if hx { x.src[j] } else { y.src[j] };
                        }
                    }
                    Some(out.linear(bits, ones))
                }
                MOp::Zext | MOp::Sext | MOp::Trunc => None,
            })();
            // The root reads it, so has no form either.
            forms.push(Some(f?));
        }
        forms.pop().flatten()
    };
    // The shorter side first: an answer is a few nodes, and where it has no form the
    // question's is not computed.
    let swap = a.nodes().len() > b.nodes().len();
    let (first, second) = if swap { (b, a) } else { (a, b) };
    let f1 = form(first);
    let f2 = f1.as_ref().and_then(|_| form(second));
    // Charged where it decides: giving up is a walk to the first node without a form, within
    // what the meter had left for the whole.
    let (Some(f1), Some(f2)) = (f1, f2) else {
        return Ok(None);
    };
    meter.charge(read.get() * per)?;
    let (fa, fb) = if swap { (f2, f1) } else { (f1, f2) };
    if fa == fb {
        return Ok(Some(None));
    }
    // Where they differ: at zero, or at the one variable bit whose multiples do.
    let mut point = vec![BitVec::zero(w); a.vars().len()];
    if fa.k == fb.k
        && let Some(i) = (0..bits).find(|&i| fa.d[i] != fb.d[i])
    {
        point[i / wn] = BitVec::wrapping_from_u64(w, 1u64 << (i % wn));
    }
    Ok(Some(Some(point)))
}

/// The most changes of variable [`prove`] asks about (atoms tried, most read first).
const CHANGE_TRIES: usize = 2;

/// Whether a change of variable decided `a == b` (see [`changes_of_variable`]), into `report`;
/// what the questions spent is added to it either way.
fn changed<M: Meter>(
    a: &MbaExpr,
    b: &MbaExpr,
    meter: &mut M,
    report: &mut Report,
) -> Result<bool, M::Err> {
    for change in changes_of_variable(a, b) {
        let sub = prove_at(&change.a, &change.b, meter, 0, false, false)?;
        report.points += sub.points;
        report.over_budget |= sub.over_budget;
        report.internal += sub.internal;
        match sub.verdict {
            Verdict::Proved => {
                report.verdict = Verdict::Proved;
                report.cert = sub.cert;
                report.compositional = sub.compositional;
                report.split = sub.split;
                report.known_bits = sub.known_bits;
                return Ok(true);
            }
            Verdict::Refuted => {
                // Back to the original variable: its value is the inverse at the point.
                let Some(p) = sub.counterexample else {
                    return Ok(false);
                };
                let Some(x) = change.inverse.eval(&p) else {
                    return Ok(false);
                };
                let mut orig = p;
                orig[change.var as usize] = x;
                report.verdict = Verdict::Refuted;
                report.cert = sub.cert;
                report.counterexample = Some(orig);
                return Ok(true);
            }
            _ if sub.over_budget => return Ok(false),
            _ => {}
        }
    }
    Ok(false)
}

/// A question over a changed variable (see [`changes_of_variable`]).
pub(crate) struct Change {
    pub(crate) a: MbaExpr,
    pub(crate) b: MbaExpr,
    /// The variable replaced (its slot now holds the atom).
    pub(crate) var: u32,
    /// The original variable as a function of the new one (in its slot).
    pub(crate) inverse: MbaExpr,
}

/// One link of a chain from an atom down to a variable: how a node is made from the one below.
#[derive(Clone, Copy, Debug)]
enum Link {
    /// `u ^ c`.
    Xor(BitVec),
    /// `u + c` (and `u − c` as `u + (−c)`).
    Add(BitVec),
    /// `c − u`.
    RevSub(BitVec),
    /// `u · c` for an odd `c`.
    Mul(BitVec),
    /// `−u`.
    Neg,
    /// `~u`.
    Not,
}

impl Link {
    /// The node below, from the node `v` it makes: the inverse of the link.
    fn undo(&self, out: &mut MbaExpr, v: u32) -> Option<u32> {
        let w = out.nodes()[v as usize].width;
        let konst = |out: &mut MbaExpr, c: BitVec| out.push(MOp::Const(c), &[]).ok();
        match *self {
            Link::Xor(c) => {
                let k = konst(out, c)?;
                out.push(MOp::Xor, &[v, k]).ok()
            }
            Link::Add(c) => {
                let k = konst(out, BitVec::un_unchecked(UnOp::Neg, &c))?;
                out.push(MOp::Add, &[v, k]).ok()
            }
            Link::RevSub(c) => {
                let k = konst(out, c)?;
                out.push(MOp::Sub, &[k, v]).ok()
            }
            Link::Mul(c) => {
                let k = konst(out, crate::invert::mul_inverse(&c)?)?;
                debug_assert_eq!(out.nodes()[k as usize].width, w);
                out.push(MOp::Mul, &[v, k]).ok()
            }
            Link::Neg => out.push(MOp::Neg, &[v]).ok(),
            Link::Not => out.push(MOp::Not, &[v]).ok(),
        }
    }
}

/// The question `a == b` with a variable `x` replaced by a bijection of an atom: for an
/// arithmetic node read by a bitwise operator (an atom to the tests) that is a chain of
/// invertible links over `x` alone (`^ c`, `+ c`, `− c`, `c −`, `· odd`, `−`, `~`), say
/// `t = (x ^ c) + k`, both sides are rewritten over `t` in `x`'s slot: `x` is `(t − k) ^ c`, every
/// node of the chain the matching inverse of `t`, the atom `t` itself. As `x ↦ t` is a bijection
/// of the variable's values, the sides are equal everywhere exactly when the rewritten ones are,
/// and an input where those differ gives one where these do (`x` the inverse at it).
///
/// The tests read an atom and the variable inside it as independent, so a side that reads both
/// (`(x ^ c)·m` beside bitwise functions of `t`, or `k' − (x ^ c)`, which is `~t` when
/// `k + k' = −1`) differs from its answer over them though not over `x`. Over `t` the chain reads
/// `t` and its inverses: arithmetic of `t` alone, which the tests take as it is, and a semi-linear
/// question over `t` is decided at its single bits. Candidates most read first.
pub(crate) fn changes_of_variable(a: &MbaExpr, b: &MbaExpr) -> Vec<Change> {
    let Some(w) = a.width() else {
        return Vec::new();
    };
    if a.vars() != b.vars() || b.width() != Some(w) {
        return Vec::new();
    }
    // Both sides in one hash-consed list, so a chain node of one is found in the other.
    let total = a.nodes().len() + b.nodes().len();
    let mut nodes: Vec<MNode> = Vec::with_capacity(total);
    let mut intern = NodeTable::with_room(total);
    let mut roots = [0u32; 2];
    for (side, m) in [a, b].into_iter().enumerate() {
        let mut map: Vec<u32> = Vec::with_capacity(m.nodes().len());
        for n in m.nodes() {
            let mut node = *n;
            for k in 0..n.op.arity() {
                node.args[k] = map[n.args[k] as usize];
            }
            if commutative(&node.op) && node.args[0] > node.args[1] {
                node.args.swap(0, 1);
            }
            map.push(intern.intern(&mut nodes, node));
        }
        let Some(&r) = map.last() else {
            return Vec::new();
        };
        roots[side] = r;
    }
    let cst = constants(&nodes);
    // Arithmetic nodes read by a bitwise operator, with how often.
    let bitwise = |op: MOp| matches!(op, MOp::And | MOp::Or | MOp::Xor);
    let arith = |op: MOp| matches!(op, MOp::Add | MOp::Sub | MOp::Mul | MOp::Neg);
    let mut reads: HashMap<u32, usize> = HashMap::default();
    for n in &nodes {
        if bitwise(n.op) || n.op == MOp::Not {
            for &k in &n.args[..n.op.arity()] {
                if arith(nodes[k as usize].op) && cst[k as usize].is_none() {
                    *reads.entry(k).or_default() += 1;
                }
            }
        }
    }
    // Each one's chain down to a variable, top first.
    let chain = |top: u32| -> Option<(u32, Vec<(u32, Link)>)> {
        let mut links = Vec::new();
        let mut cur = top;
        for _ in 0..16 {
            let n = nodes[cur as usize];
            if n.width != w {
                return None;
            }
            let c = |k: usize| cst[n.args[k] as usize];
            let (link, next) = match n.op {
                MOp::Var(x) => return Some((x, links)),
                MOp::Add => match (c(0), c(1)) {
                    (Some(k), None) => (Link::Add(k), n.args[1]),
                    (None, Some(k)) => (Link::Add(k), n.args[0]),
                    _ => return None,
                },
                MOp::Sub => match (c(0), c(1)) {
                    (Some(k), None) => (Link::RevSub(k), n.args[1]),
                    (None, Some(k)) => (Link::Add(BitVec::un_unchecked(UnOp::Neg, &k)), n.args[0]),
                    _ => return None,
                },
                MOp::Xor => match (c(0), c(1)) {
                    (Some(k), None) => (Link::Xor(k), n.args[1]),
                    (None, Some(k)) => (Link::Xor(k), n.args[0]),
                    _ => return None,
                },
                MOp::Mul => match (c(0), c(1)) {
                    (Some(k), None) | (None, Some(k)) if k.bit(0) == Some(true) => {
                        let u = if c(0).is_some() { n.args[1] } else { n.args[0] };
                        (Link::Mul(k), u)
                    }
                    _ => return None,
                },
                MOp::Neg => (Link::Neg, n.args[0]),
                MOp::Not => (Link::Not, n.args[0]),
                _ => return None,
            };
            links.push((cur, link));
            cur = next;
        }
        None
    };
    let mut cands: Vec<(usize, u32)> = reads.iter().map(|(&k, &n)| (n, k)).collect();
    cands.sort_by_key(|&(n, k)| (std::cmp::Reverse(n), k));
    let mut out: Vec<Change> = Vec::new();
    for (_, top) in cands {
        if out.len() == CHANGE_TRIES {
            break;
        }
        let Some((x, links)) = chain(top) else {
            continue;
        };
        if out.iter().any(|c| c.var == x) || a.vars()[x as usize] != w {
            continue;
        }
        let rebuild = |root: u32| -> Option<MbaExpr> {
            let mut m = MbaExpr::new(a.vars().to_vec());
            // The chain over `t`, top down: the atom is `t`, each node below the inverse of
            // its link applied to the one above.
            let mut map: HashMap<u32, u32> = HashMap::default();
            let mut v = m.push(MOp::Var(x), &[]).ok()?;
            for &(node, link) in &links {
                map.insert(node, v);
                v = link.undo(&mut m, v)?;
            }
            // `v` is now `x` as a function of `t`.
            let mut stack: Vec<(u32, bool)> = vec![(root, false)];
            while let Some((i, expanded)) = stack.pop() {
                if map.contains_key(&i) {
                    continue;
                }
                let n = nodes[i as usize];
                if let MOp::Var(y) = n.op
                    && y == x
                {
                    map.insert(i, v);
                    continue;
                }
                if !expanded {
                    stack.push((i, true));
                    for &k in &n.args[..n.op.arity()] {
                        stack.push((k, false));
                    }
                    continue;
                }
                let args: Vec<u32> = n.args[..n.op.arity()].iter().map(|k| map[k]).collect();
                let id = match n.op {
                    MOp::Zext | MOp::Sext | MOp::Trunc => m.push_cast(n.op, args[0], n.width),
                    op => m.push(op, &args),
                }
                .ok()?;
                map.insert(i, id);
            }
            // The root must be the last node.
            let r = map[&root];
            if r as usize + 1 != m.nodes().len() {
                let n = m.nodes()[r as usize];
                let zero = m.push(MOp::Const(BitVec::zero(n.width)), &[]).ok()?;
                m.push(MOp::Add, &[r, zero]).ok()?;
            }
            Some(m)
        };
        let (Some(ca), Some(cb)) = (rebuild(roots[0]), rebuild(roots[1])) else {
            continue;
        };
        let mut inverse = MbaExpr::new(a.vars().to_vec());
        let Some(mut v) = inverse.push(MOp::Var(x), &[]).ok() else {
            continue;
        };
        let mut ok = true;
        for &(_, link) in &links {
            match link.undo(&mut inverse, v) {
                Some(u) => v = u,
                None => ok = false,
            }
        }
        if !ok {
            continue;
        }
        out.push(Change {
            a: ca,
            b: cb,
            var: x,
            inverse,
        });
    }
    out
}

/// What the cheapest direct test on `a` and `b` costs in node evaluations, when one applies
/// and is not too big to run: a complete test, so one that runs decides the question.
pub(crate) fn direct_cost(a: &MbaExpr, b: &MbaExpr) -> Option<u64> {
    if a.vars() != b.vars() || a.width().is_none() || a.width() != b.width() {
        return None;
    }
    let (pa, pb) = (profile(a)?, profile(b)?);
    let p = plan(a, &pa, &pb)?;
    let (qa, qb) = (Program::new(a, false)?, Program::new(b, false)?);
    let per = (qa.len() + qb.len()) as u64;
    let lane = match Kind::of(qa.widest().max(qb.widest())) {
        Kind::N64 => 1,
        Kind::N128 => 2,
        Kind::Wide => 8,
    };
    (p.points <= MAX_POINTS && p.points.saturating_mul(per).saturating_mul(lane) <= MAX_EFFORT)
        .then(|| p.points.saturating_mul(per))
}

/// [`prove`] within `depth` splits; `lowered`: known bits were already read as arithmetic;
/// `change`: a change of variable may be tried (see [`changes_of_variable`]).
fn prove_at<M: Meter>(
    a: &MbaExpr,
    b: &MbaExpr,
    meter: &mut M,
    depth: u32,
    lowered: bool,
    change: bool,
) -> Result<Report, M::Err> {
    let mut report = Report::new();
    if a.vars() != b.vars() || a.width().is_none() || a.width() != b.width() {
        return Ok(report);
    }
    if a == b {
        report.verdict = Verdict::Proved;
        return Ok(report);
    }
    let (Some(pa), Some(pb)) = (profile(a), profile(b)) else {
        return Ok(report);
    };
    // Abstraction never makes a polynomial test smaller; only a non-polynomial side needs it.
    let mut compose = true;
    let poly = pa.poly && pb.poly;
    let direct = plan(a, &pa, &pb);
    // A polynomial pair no test fits (or can afford, below): maybe the same polynomial.
    if direct.is_none() && poly && symbolic(meter, a, b, &mut report)? {
        report.verdict = Verdict::Proved;
        report.cert = Some(Cert::Symbolic);
        return Ok(report);
    }
    if let Some(p) = direct {
        match run(meter, a, b, &p, &mut report)? {
            Run::Equal(cert) => {
                report.verdict = Verdict::Proved;
                report.cert = Some(cert);
                return Ok(report);
            }
            Run::Differ(point) => {
                report.verdict = Verdict::Refuted;
                report.cert = Some(p.cert);
                report.counterexample = Some(point);
                return Ok(report);
            }
            Run::OverBudget | Run::TooBig => {
                compose = !poly;
                if poly && symbolic(meter, a, b, &mut report)? {
                    report.verdict = Verdict::Proved;
                    report.cert = Some(Cert::Symbolic);
                    return Ok(report);
                }
            }
        }
    }
    if compose {
        let mut cmp = Compose::new(a, b);
        cmp.prove(meter, &mut report)?;
        cmp.recycle();
    }
    // The same question with the constants bitwise operators put on left shifts read inside
    // the shifts (equal expressions, see `shifts_inward`), over atoms again: before the
    // readings below, which cost more.
    if compose
        && depth == 0
        && !lowered
        && report.verdict == Verdict::Unknown
        && !report.over_budget
    {
        let (sa, sb) = (shifts_inward(a), shifts_inward(b));
        if sa.is_some() || sb.is_some() {
            let (sa, sb) = (sa.as_ref().unwrap_or(a), sb.as_ref().unwrap_or(b));
            let mut sub = Report::new();
            let mut cmp = Compose::new(sa, sb);
            cmp.prove(meter, &mut sub)?;
            cmp.recycle();
            report.points += sub.points;
            report.over_budget |= sub.over_budget;
            report.internal += sub.internal;
            if sub.verdict == Verdict::Proved {
                report.verdict = Verdict::Proved;
                report.cert = sub.cert;
                return Ok(report);
            }
        }
    }
    // Arithmetic read bitwise without products, which the atoms left open: bit-serially,
    // exactly.
    let carried = compose
        && report.verdict == Verdict::Unknown
        && !report.over_budget
        && carries(meter, a, b, &mut report)?;
    if carried {
        return Ok(report);
    }
    // Undecided for lack of budget: more budget may decide it directly; nothing more is spent.
    if report.verdict != Verdict::Unknown || report.over_budget {
        return Ok(report);
    }
    // The same question over an atom that is a bijection of one variable, in that variable's
    // place (see `changes_of_variable`): before the readings below, which split and lower
    // the question as it is and cost more.
    let ch = change && changed(a, b, meter, &mut report)?;
    if ch {
        return Ok(report);
    }
    // The same question with known bits read as arithmetic (equal functions, so a verdict on
    // them is one on `a` and `b`, at the same points); it splits too.
    if !lowered && (lowerable(a) || lowerable(b)) {
        let units = (a.nodes().len() + b.nodes().len()) as u64 * LOWER_COST;
        if units > meter.left() {
            report.over_budget = true;
            return Ok(report);
        }
        meter.charge(units)?;
        let (la, lb) = (lower_known_bits(a), lower_known_bits(b));
        if la.is_some() || lb.is_some() {
            let la = la.unwrap_or_else(|| a.clone());
            let lb = lb.unwrap_or_else(|| b.clone());
            let sub = prove_at(&la, &lb, meter, depth, true, false)?;
            report.points += sub.points;
            report.over_budget |= sub.over_budget;
            report.internal += sub.internal;
            if sub.verdict != Verdict::Unknown {
                report.verdict = sub.verdict;
                report.cert = sub.cert;
                report.compositional = sub.compositional;
                report.split = sub.split;
                report.known_bits = true;
                report.counterexample = sub.counterexample;
            }
            return Ok(report);
        }
    }
    if depth < SPLIT_DEPTH {
        split(a, b, meter, depth, &mut report)?;
    }
    Ok(report)
}

/// `m` with each bitwise operation of a left shift and a constant read inside the shift:
/// `(t << k) & c` as `(t & (c >> k)) << k`, and `(t << k) | c` and `(t << k) ^ c` as
/// `((t | (c >> k)) << k) + low` and `((t ^ (c >> k)) << k) + low` with `low` the low `k`
/// bits of `c` (the shifted value has none of them, so the sum carries nothing). Equal
/// expressions. A shift read by a bitwise operator is an atom to the tests; inside the shift
/// the operator reads `t`, and where `t` is a bitwise function the shift is a product of one
/// by a constant, which they follow. `None` when there is none.
pub(crate) fn shifts_inward(m: &MbaExpr) -> Option<MbaExpr> {
    use crate::facts::known::{bv_and, bv_lshr, bv_not, bv_shl};
    let nodes = m.nodes();
    let cst = constants(nodes);
    let mut out = MbaExpr::new(m.vars().to_vec());
    let mut map: Vec<u32> = Vec::with_capacity(nodes.len());
    let mut changed = false;
    for (i, n) in nodes.iter().enumerate() {
        let rewritten = (|| {
            if !matches!(n.op, MOp::And | MOp::Or | MOp::Xor) || cst[i].is_some() {
                return None;
            }
            let (s, c) = (0..2).find_map(|k| {
                let (s, c) = (n.args[k] as usize, n.args[1 - k] as usize);
                match (nodes[s].op, cst[c]) {
                    (MOp::Shl(by), Some(v)) if cst[s].is_none() => Some(((s, by), v)),
                    _ => None,
                }
            })?;
            let (s, by) = s;
            let w = n.width;
            if nodes[s].width != w || by == 0 || by >= w.bits() {
                return None;
            }
            let ones = BitVec::ones(w);
            let low = bv_and(&c, &bv_not(&bv_shl(&ones, u32::from(by))));
            let inner = out.push(MOp::Const(bv_lshr(&c, u32::from(by))), &[]).ok()?;
            let t = map[nodes[s].args[0] as usize];
            let read = out.push(n.op, &[t, inner]).ok()?;
            let shifted = out.push(MOp::Shl(by), &[read]).ok()?;
            if n.op == MOp::And || low.is_zero() {
                return Some(shifted);
            }
            let low = out.push(MOp::Const(low), &[]).ok()?;
            out.push(MOp::Add, &[shifted, low]).ok()
        })();
        let at = match rewritten {
            Some(at) => {
                changed = true;
                at
            }
            None => {
                let mut args = [0u32; 2];
                for (k, a) in args.iter_mut().enumerate().take(n.op.arity()) {
                    *a = map[n.args[k] as usize];
                }
                match n.op {
                    MOp::Zext | MOp::Sext | MOp::Trunc => {
                        out.push_cast(n.op, args[0], n.width).ok()?
                    }
                    op => out.push(op, &args[..op.arity()]).ok()?,
                }
            }
        };
        map.push(at);
    }
    changed.then_some(out)
}

/// Whether `m` has a bitwise operation with exactly one constant operand (see
/// [`lower_known_bits`]).
pub(crate) fn lowerable(m: &MbaExpr) -> bool {
    let nodes = m.nodes();
    let konst = |i: u32| {
        nodes
            .get(i as usize)
            .is_some_and(|n| matches!(n.op, MOp::Const(_)))
    };
    nodes.iter().any(|n| {
        matches!(n.op, MOp::And | MOp::Or | MOp::Xor) && konst(n.args[0]) != konst(n.args[1])
    })
}

/// `m` with every `x op k` (`op` bitwise, `k` a constant) read as arithmetic where the bits of
/// `x` that are known (by the transfer functions of [`Facts`](crate::Facts)) cover the bits `k`
/// is 1 at, or those it is 0 at. With `z` and `o` the known-zero and known-one bits of `x`:
///
/// - `k` inside the known bits: `x & k = k & o`, `x | k = x + (k & z)`,
///   `x ^ k = x + (k & z) − (k & o)`;
/// - `~k` inside them: `x & k = x − (~k & o)`, `x | k = k | o`,
///   `x ^ k = (~k & o) − (~k & z) − 1 − x` (that is, `~x ^ ~k`).
///
/// `None` when there is none.
pub(crate) fn lower_known_bits(m: &MbaExpr) -> Option<MbaExpr> {
    use crate::Facts;
    use crate::facts::known::{bv_and, bv_not, bv_or};
    let nodes = m.nodes();
    let cst = constants(nodes);
    let candidate = |n: &MNode| {
        matches!(n.op, MOp::And | MOp::Or | MOp::Xor)
            && cst[n.args[0] as usize].is_some() != cst[n.args[1] as usize].is_some()
    };
    if !nodes.iter().any(candidate) {
        return None;
    }
    let mut facts: Vec<Facts> = Vec::with_capacity(nodes.len());
    let mut out = MbaExpr::new(m.vars().to_vec());
    let mut map: Vec<u32> = Vec::with_capacity(nodes.len());
    let mut changed = false;
    for n in nodes {
        let fa = |k: usize| facts.get(n.args[k] as usize).copied();
        let f = match n.op {
            MOp::Const(v) => Some(Facts::constant(&v)),
            MOp::Var(_) => Some(Facts::top(n.width)),
            // `a + a` is `a << 1` (the shift knows the low bit).
            MOp::Add if n.args[0] == n.args[1] => {
                let one = Facts::constant(&BitVec::one(n.width));
                Facts::apply_bin(BinOp::Shl, &fa(0)?, &one).ok()
            }
            MOp::Add | MOp::Sub | MOp::Mul | MOp::And | MOp::Or | MOp::Xor => {
                let op = match n.op {
                    MOp::Add => BinOp::Add,
                    MOp::Sub => BinOp::Sub,
                    MOp::Mul => BinOp::Mul,
                    MOp::And => BinOp::And,
                    MOp::Or => BinOp::Or,
                    _ => BinOp::Xor,
                };
                Facts::apply_bin(op, &fa(0)?, &fa(1)?).ok()
            }
            MOp::Neg => Facts::apply_un(UnOp::Neg, &fa(0)?).ok(),
            MOp::Not => Facts::apply_un(UnOp::Not, &fa(0)?).ok(),
            MOp::Shl(k) | MOp::LShr(k) => {
                let op = if matches!(n.op, MOp::Shl(_)) {
                    BinOp::Shl
                } else {
                    BinOp::LShr
                };
                let amount = Facts::constant(&BitVec::wrapping_from_u64(n.width, u64::from(k)));
                Facts::apply_bin(op, &fa(0)?, &amount).ok()
            }
            MOp::Zext => fa(0)?.zext(n.width).ok(),
            MOp::Sext => fa(0)?.sext(n.width).ok(),
            MOp::Trunc => fa(0)?.extract(0, n.width).ok(),
        }?;
        let args: Vec<u32> = n.args[..n.op.arity()]
            .iter()
            .map(|&x| map[x as usize])
            .collect();
        // The rewrite: `c` alone, `x + c`, or `c − x`.
        let mut rewrite: Option<(Option<bool>, BitVec, u32)> = None;
        if candidate(n) {
            let (x, k) = match cst[n.args[0] as usize] {
                Some(k) => (1, k),
                None => (0, cst[n.args[1] as usize]?),
            };
            let kb = facts[n.args[x] as usize].known();
            let (z, o) = (kb.known_zero(), kb.known_one());
            let unknown = bv_not(&kb.known());
            let nk = bv_not(&k);
            let sub = |a: &BitVec, b: &BitVec| BitVec::bin_unchecked(BinOp::Sub, a, b);
            let one = BitVec::one(n.width);
            if bv_and(&k, &unknown).is_zero() {
                rewrite = Some(match n.op {
                    MOp::And => (None, bv_and(&k, &o), args[x]),
                    MOp::Or => (Some(true), bv_and(&k, &z), args[x]),
                    _ => (Some(true), sub(&bv_and(&k, &z), &bv_and(&k, &o)), args[x]),
                });
            } else if bv_and(&nk, &unknown).is_zero() {
                rewrite = Some(match n.op {
                    MOp::And => (
                        Some(true),
                        sub(&BitVec::zero(n.width), &bv_and(&nk, &o)),
                        args[x],
                    ),
                    MOp::Or => (None, bv_or(&k, &o), args[x]),
                    _ => (
                        Some(false),
                        sub(&sub(&bv_and(&nk, &o), &bv_and(&nk, &z)), &one),
                        args[x],
                    ),
                });
            }
        }
        let r = match rewrite {
            Some((form, c, x)) => {
                changed = true;
                let c = out.push(MOp::Const(c), &[]).ok()?;
                match form {
                    None => c,
                    Some(true) => out.push(MOp::Add, &[x, c]).ok()?,
                    Some(false) => out.push(MOp::Sub, &[c, x]).ok()?,
                }
            }
            None => match n.op {
                MOp::Zext | MOp::Sext | MOp::Trunc => out.push_cast(n.op, args[0], n.width).ok()?,
                op => out.push(op, &args).ok()?,
            },
        };
        facts.push(f);
        map.push(r);
    }
    changed.then_some(out)
}

/// `m` with every sum of two bitwise terms that can share no set bit read as their `|`, and
/// every difference `a − b` of two where `b` can have a bit only where `a` has it read as
/// `a ^ b`: no carry and no borrow, so the same value at every input. A bitwise term here is
/// a constant or a node made by `& | ^ ~` (or by a sum or difference so read), also through a
/// zero extension or a truncation; the bits are what those operators, the constants and the
/// constant shifts fix.
///
/// The arena's normal forms and the obfuscators both write such a function with `+` and `−`
/// (`(~x & m) + k` for `(~x & m) | k`, `c − (x & m)` for `c ^ (x & m)`), and under a mask it is
/// then arithmetic under a bitwise operator: an atom to the tests, unrelated to `x`, where
/// the bitwise function is a term they decide at single bit positions. A sum with an operand
/// that is no bitwise term stays a sum (`(x << 4) + (y & 15)` is linear as it is). `None`
/// when there is none.
pub(crate) fn raise_disjoint(m: &MbaExpr) -> Option<MbaExpr> {
    // Every certificate asks this of both sides first; up to 64 bits the known bits are
    // machine words.
    if m.nodes().iter().all(|n| n.width.bits() <= 64) {
        let raised = raise_disjoint_words(m);
        debug_assert_eq!(
            raised,
            raise_disjoint_any(m),
            "sums read over words differ from sums read over values"
        );
        return raised;
    }
    raise_disjoint_any(m)
}

/// [`raise_disjoint`] when no node is wider than 64 bits: the same known bits, as words, and
/// the expression rebuilt only when a sum or difference is read otherwise.
fn raise_disjoint_words(m: &MbaExpr) -> Option<MbaExpr> {
    let nodes = m.nodes();
    let word = |v: &BitVec| <u64 as Lane>::from_bv(v);
    // The known-zero and known-one bits of each node, and whether it is a bitwise term.
    let mut bits: Vec<(u64, u64)> = Vec::with_capacity(nodes.len());
    let mut term: Vec<bool> = Vec::with_capacity(nodes.len());
    // Per node: 0 as it is, 1 read as `|`, 2 read as `^`.
    let mut read: Vec<u8> = Vec::with_capacity(nodes.len());
    let mut changed = false;
    for n in nodes {
        let at = |k: usize| bits[n.args[k] as usize];
        let terms = |k: usize| term[n.args[k] as usize];
        let or = |(za, oa): (u64, u64), (zb, ob): (u64, u64)| (za & zb, oa | ob);
        let xor = |(za, oa): (u64, u64), (zb, ob): (u64, u64)| {
            ((za & zb) | (oa & ob), (za & ob) | (oa & zb))
        };
        let width = n.width.bits();
        let ones = <u64 as Lane>::mask(n.width);
        let (as_op, known, is_term) = match n.op {
            MOp::Const(v) => (0, (!word(&v) & ones, word(&v)), true),
            MOp::Not => (0, (at(0).1, at(0).0), true),
            MOp::And => {
                let ((za, oa), (zb, ob)) = (at(0), at(1));
                (0, (za | zb, oa & ob), true)
            }
            MOp::Or => (0, or(at(0), at(1)), true),
            MOp::Xor => (0, xor(at(0), at(1)), true),
            MOp::Zext => {
                let (z, o) = at(0);
                let low = <u64 as Lane>::mask(nodes[n.args[0] as usize].width);
                (0, (z | (ones & !low), o), terms(0))
            }
            MOp::Trunc => {
                let (z, o) = at(0);
                (0, (z & ones, o & ones), terms(0))
            }
            MOp::Shl(k) => {
                let (z, o) = at(0);
                let shl = |x: u64| if k >= width { 0 } else { (x << k) & ones };
                let low = !shl(ones) & ones;
                (0, (shl(z) | low, shl(o)), false)
            }
            MOp::LShr(k) => {
                let (z, o) = at(0);
                let lshr = |x: u64| if k >= width { 0 } else { x >> k };
                let high = !lshr(ones) & ones;
                (0, (lshr(z) | high, lshr(o)), false)
            }
            // No bit set in both: no carry.
            MOp::Add if terms(0) && terms(1) && (at(0).0 | at(1).0) == ones => {
                (1, or(at(0), at(1)), true)
            }
            // The subtrahend's bits all among the minuend's: no borrow.
            MOp::Sub if terms(0) && terms(1) && (at(0).1 | at(1).0) == ones => {
                (2, xor(at(0), at(1)), true)
            }
            _ => (0, (0, 0), false),
        };
        changed |= as_op != 0;
        bits.push(known);
        term.push(is_term);
        read.push(as_op);
    }
    if !changed {
        return None;
    }
    let mut out = MbaExpr::new(m.vars().to_vec());
    for (n, &as_op) in nodes.iter().zip(&read) {
        let op = match as_op {
            1 => MOp::Or,
            2 => MOp::Xor,
            _ => n.op,
        };
        match op {
            MOp::Zext | MOp::Sext | MOp::Trunc => out.push_cast(op, n.args[0], n.width).ok()?,
            op => out.push(op, &n.args[..n.op.arity()]).ok()?,
        };
    }
    Some(out)
}

/// [`raise_disjoint`] at any width.
fn raise_disjoint_any(m: &MbaExpr) -> Option<MbaExpr> {
    use crate::facts::known::{bv_and, bv_lshr, bv_not, bv_or, bv_shl};
    let nodes = m.nodes();
    // The known-zero and known-one bits of each node, and whether it is a bitwise term.
    let mut bits: Vec<(BitVec, BitVec)> = Vec::with_capacity(nodes.len());
    let mut term: Vec<bool> = Vec::with_capacity(nodes.len());
    let mut out = MbaExpr::new(m.vars().to_vec());
    let mut map: Vec<u32> = Vec::with_capacity(nodes.len());
    let mut changed = false;
    for n in nodes {
        let at = |k: usize| bits[n.args[k] as usize];
        let terms = |k: usize| term[n.args[k] as usize];
        let or = |(za, oa): (BitVec, BitVec), (zb, ob): (BitVec, BitVec)| {
            (bv_and(&za, &zb), bv_or(&oa, &ob))
        };
        let xor = |(za, oa): (BitVec, BitVec), (zb, ob): (BitVec, BitVec)| {
            (
                bv_or(&bv_and(&za, &zb), &bv_and(&oa, &ob)),
                bv_or(&bv_and(&za, &ob), &bv_and(&oa, &zb)),
            )
        };
        let unknown = (BitVec::zero(n.width), BitVec::zero(n.width));
        let ones = BitVec::ones(n.width);
        let (op, known, is_term) = match n.op {
            MOp::Const(v) => (n.op, (bv_not(&v), v), true),
            MOp::Not => (n.op, (at(0).1, at(0).0), true),
            MOp::And => {
                let ((za, oa), (zb, ob)) = (at(0), at(1));
                (n.op, (bv_or(&za, &zb), bv_and(&oa, &ob)), true)
            }
            MOp::Or => (n.op, or(at(0), at(1)), true),
            MOp::Xor => (n.op, xor(at(0), at(1)), true),
            MOp::Zext => {
                let (z, o) = at(0);
                let low = BitVec::ones(z.width()).zext(n.width).ok()?;
                let z = bv_or(&z.zext(n.width).ok()?, &bv_not(&low));
                (n.op, (z, o.zext(n.width).ok()?), terms(0))
            }
            MOp::Trunc => {
                let (z, o) = at(0);
                let known = (z.trunc(n.width).ok()?, o.trunc(n.width).ok()?);
                (n.op, known, terms(0))
            }
            MOp::Shl(k) => {
                let (z, o) = at(0);
                let k = u32::from(k);
                let low = bv_not(&bv_shl(&ones, k));
                (n.op, (bv_or(&bv_shl(&z, k), &low), bv_shl(&o, k)), false)
            }
            MOp::LShr(k) => {
                let (z, o) = at(0);
                let k = u32::from(k);
                let high = bv_not(&bv_lshr(&ones, k));
                (n.op, (bv_or(&bv_lshr(&z, k), &high), bv_lshr(&o, k)), false)
            }
            // No bit set in both: no carry.
            MOp::Add if terms(0) && terms(1) && bv_or(&at(0).0, &at(1).0).is_ones() => {
                (MOp::Or, or(at(0), at(1)), true)
            }
            // The subtrahend's bits all among the minuend's: no borrow.
            MOp::Sub if terms(0) && terms(1) && bv_or(&at(0).1, &at(1).0).is_ones() => {
                (MOp::Xor, xor(at(0), at(1)), true)
            }
            _ => (n.op, unknown, false),
        };
        changed |= op != n.op;
        let args: Vec<u32> = n.args[..n.op.arity()]
            .iter()
            .map(|&x| map[x as usize])
            .collect();
        let r = match op {
            MOp::Zext | MOp::Sext | MOp::Trunc => out.push_cast(op, args[0], n.width).ok()?,
            op => out.push(op, &args).ok()?,
        };
        bits.push(known);
        term.push(is_term);
        map.push(r);
    }
    changed.then_some(out)
}

/// A variable both sides read only as `v & M` (constant masks `M`, at most [`SPLIT_BITS`]
/// bits together), and those bits: the sides depend on nothing else of it.
fn narrow_var(a: &MbaExpr, b: &MbaExpr) -> Option<(u32, Vec<u32>)> {
    let nv = a.vars().len();
    let mut masks: Vec<Option<BitVec>> = vec![None; nv];
    let mut wide = vec![false; nv];
    for m in [a, b] {
        let nodes = m.nodes();
        let live = live(m);
        let cst = constants(nodes);
        if let Some(MOp::Var(v)) = m.root().map(|r| nodes[r as usize].op) {
            *wide.get_mut(v as usize)? = true;
        }
        for (i, n) in nodes.iter().enumerate() {
            if !live[i] {
                continue;
            }
            let args = &n.args[..n.op.arity()];
            for (k, &arg) in args.iter().enumerate() {
                let MOp::Var(v) = nodes[arg as usize].op else {
                    continue;
                };
                let mask = match n.op {
                    MOp::And => cst[args[1 - k] as usize],
                    _ => None,
                };
                let (Some(slot), Some(flag)) =
                    (masks.get_mut(v as usize), wide.get_mut(v as usize))
                else {
                    return None;
                };
                match mask {
                    Some(c) => {
                        *slot = Some(match slot {
                            Some(x) => BitVec::bin_unchecked(BinOp::Or, x, &c),
                            None => c,
                        })
                    }
                    None => *flag = true,
                }
            }
        }
    }
    (0..nv)
        .filter_map(|v| {
            let mask = masks[v].filter(|_| !wide[v])?;
            let bits: Vec<u32> = (0..mask.width().bits())
                .filter(|&j| mask.bit(j).unwrap_or(false))
                .map(u32::from)
                .collect();
            (bits.len() as u32 <= SPLIT_BITS).then_some((v as u32, bits))
        })
        .min_by_key(|(_, bits)| bits.len())
}

/// A variable whose low `j` bits (`1 ≤ j ≤` [`SPLIT_BITS`], `j` below its width) are all
/// that bitwise operations with constants read of arithmetic over it: `t op k` with `t` built
/// from variables and constants by `+ − · neg <<`, whose low `j` bits depend only on theirs, and
/// `k` all zeros or all ones above bit `j`. Once those bits are known, so are the bits `k`
/// reads (see [`lower_known_bits`]). The variable with the fewest, and that many.
fn low_var(a: &MbaExpr, b: &MbaExpr) -> Option<(u32, u32)> {
    use crate::facts::known::{bv_not, leading_zeros};
    let nv = a.vars().len();
    let mut need: Vec<u32> = vec![0; nv];
    for m in [a, b] {
        let nodes = m.nodes();
        let live = live(m);
        let cst = constants(nodes);
        // Per node: the variables it is arithmetic over (`None` when it reads one otherwise).
        let mut arith: Vec<Option<u64>> = Vec::with_capacity(nodes.len());
        for (i, n) in nodes.iter().enumerate() {
            let args = &n.args[..n.op.arity()];
            let vars = match n.op {
                _ if cst[i].is_some() => Some(0),
                MOp::Var(x) if x < 64 => Some(1u64 << x),
                MOp::Add | MOp::Sub | MOp::Mul | MOp::Neg | MOp::Shl(_) => args
                    .iter()
                    .try_fold(0u64, |acc, &x| Some(acc | arith[x as usize]?)),
                _ => None,
            };
            arith.push(vars);
        }
        for (i, n) in nodes.iter().enumerate() {
            if !live[i] || !matches!(n.op, MOp::And | MOp::Or | MOp::Xor) {
                continue;
            }
            let (x, k) = match (cst[n.args[0] as usize], cst[n.args[1] as usize]) {
                (None, Some(k)) => (n.args[0], k),
                (Some(k), None) => (n.args[1], k),
                _ => continue,
            };
            let bits = u32::from(k.width().bits());
            let len = |c: &BitVec| bits - leading_zeros(c);
            let j = len(&k).min(len(&bv_not(&k)));
            if j == 0 || j > SPLIT_BITS || j >= bits {
                continue;
            }
            let Some(mut set) = arith[x as usize] else {
                continue;
            };
            while set != 0 {
                let v = set.trailing_zeros() as usize;
                if let Some(nj) = need.get_mut(v) {
                    *nj = (*nj).max(j);
                }
                set &= set - 1;
            }
        }
    }
    (0..nv)
        .filter(|&v| need[v] > 0)
        .min_by_key(|&v| (need[v], v))
        .map(|v| (v as u32, need[v]))
}

/// How a split replaces its variable in one case.
#[derive(Copy, Clone, Debug)]
enum Case {
    /// By a constant.
    Value(BitVec),
    /// By `(v << j) + b`: onto the values whose low `j` bits are `b`, as `v` ranges over all.
    Low(u16, BitVec),
}

impl Case {
    /// The variable's value in this case where the specialized sides take `x`.
    fn value(&self, x: &BitVec) -> BitVec {
        match *self {
            Case::Value(c) => c,
            Case::Low(j, b) => BitVec::bin_unchecked(
                BinOp::Add,
                &crate::facts::known::bv_shl(x, u32::from(j)),
                &b,
            ),
        }
    }
}

/// The variable to split on and its cases: one both sides read only through masks of a few
/// bits (each assignment of those bits), else one whose low bits are what bitwise operations
/// with constants read ([`low_var`]; each value of them).
fn cases(a: &MbaExpr, b: &MbaExpr) -> Option<(u32, Vec<Case>)> {
    if let Some((v, bits)) = narrow_var(a, b) {
        let w = *a.vars().get(v as usize)?;
        let cases = (0..1u64 << bits.len())
            .map(|case| {
                let mut value = BitVec::zero(w);
                for (j, &pos) in bits.iter().enumerate() {
                    if case >> j & 1 == 1 {
                        let one = crate::facts::known::bv_shl(&BitVec::one(w), pos);
                        value = BitVec::bin_unchecked(BinOp::Or, &value, &one);
                    }
                }
                Case::Value(value)
            })
            .collect();
        return Some((v, cases));
    }
    let (v, j) = low_var(a, b)?;
    let w = *a.vars().get(v as usize)?;
    let cases = (0..1u64 << j)
        .map(|low| Case::Low(j as u16, BitVec::wrapping_from_u64(w, low)))
        .collect();
    Some((v, cases))
}

/// `m` with variable `v` replaced as `case` says (the variables unchanged).
fn specialize(m: &MbaExpr, v: u32, case: &Case) -> Option<MbaExpr> {
    let mut out = MbaExpr::new(m.vars().to_vec());
    let mut map: Vec<u32> = Vec::with_capacity(m.nodes().len());
    for n in m.nodes() {
        let args: Vec<u32> = n.args[..n.op.arity()]
            .iter()
            .map(|&x| map.get(x as usize).copied())
            .collect::<Option<_>>()?;
        let r = match (n.op, case) {
            (MOp::Var(x), Case::Value(c)) if x == v => out.push(MOp::Const(*c), &[]),
            (MOp::Var(x), Case::Low(j, b)) if x == v => {
                let x = out.push(n.op, &[]).ok()?;
                let hi = out.push(MOp::Shl(*j), &[x]).ok()?;
                let lo = out.push(MOp::Const(*b), &[]).ok()?;
                out.push(MOp::Add, &[hi, lo])
            }
            (MOp::Zext | MOp::Sext | MOp::Trunc, _) => out.push_cast(n.op, args[0], n.width),
            (op, _) => out.push(op, &args),
        };
        map.push(r.ok()?);
    }
    Some(out)
}

/// [`split`] alone, at the top (for tests: the cases, whatever the direct tests would say).
#[cfg(test)]
pub(crate) fn by_cases(a: &MbaExpr, b: &MbaExpr) -> Report {
    let mut report = Report::new();
    let _ = split(a, b, &mut Steps::new(u64::MAX), 0, &mut report);
    report
}

/// Decides `a == b` case by case over a few bits of one variable ([`cases`]): when both read
/// it only through masks, each assignment of the masked bits is a case (the variable replaced
/// by that constant, which folds away); when bitwise operations with constants read only its
/// low bits, each value of those is a case (the variable replaced by `(v << j) + b`, which
/// makes those operations read known bits). Each case is proved on its own; the cases cover
/// every input. Proved when every case is; refuted by a case's counterexample (the variable
/// set to its value in that case). Declines (unknown) when a case is undecided or the cases
/// spend more than [`SPLIT_EFFORT`].
fn split<M: Meter>(
    a: &MbaExpr,
    b: &MbaExpr,
    meter: &mut M,
    depth: u32,
    report: &mut Report,
) -> Result<(), M::Err> {
    let Some((v, cases)) = cases(a, b) else {
        return Ok(());
    };
    let mut last = None;
    let mut spent = 0u64;
    for case in &cases {
        if spent > SPLIT_EFFORT {
            return Ok(());
        }
        let (Some(sa), Some(sb)) = (specialize(a, v, case), specialize(b, v, case)) else {
            return Ok(());
        };
        let before = meter.left();
        let sub = prove_at(&sa, &sb, meter, depth + 1, false, false)?;
        spent = spent.saturating_add(before.saturating_sub(meter.left()));
        report.points += sub.points;
        report.over_budget |= sub.over_budget;
        report.internal += sub.internal;
        report.compositional |= sub.compositional;
        report.known_bits |= sub.known_bits;
        match sub.verdict {
            Verdict::Proved => last = sub.cert.or(last),
            Verdict::Refuted => {
                let Some(mut point) = sub.counterexample else {
                    return Ok(());
                };
                if let Some(x) = point.get_mut(v as usize) {
                    *x = case.value(x);
                }
                report.verdict = Verdict::Refuted;
                report.cert = sub.cert;
                report.split = true;
                report.counterexample = Some(point);
                return Ok(());
            }
            Verdict::Unknown => return Ok(()),
        }
    }
    report.verdict = Verdict::Proved;
    report.cert = last;
    report.split = true;
    Ok(())
}

/// A skeleton comparison: its verdict, if a test ran, and for `Refuted` the input.
type Compared = (Option<Verdict>, Option<Vec<BitVec>>);

/// How a node takes part in a skeleton.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum Role {
    /// Its value does not depend on any variable.
    Const,
    Var,
    /// `& | ^` (a bitwise function of its operands, which are read bitwise).
    Bitwise,
    /// `~`: bitwise under a bitwise reader, `−1 − a` otherwise.
    Not,
    /// `+ − · neg <<`: polynomial, but an atom when read by a bitwise operator.
    Arith,
    /// A right shift or a cast: always an atom.
    Opaque,
}

/// How a node is read.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
enum Ctx {
    Arith,
    Bitwise,
}

/// Which nodes a skeleton abstracts.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum Policy {
    /// Only where the fragment requires it (opaque nodes, arithmetic read bitwise).
    Minimal,
    /// The atoms of [`Minimal`](Self::Minimal), each read as its class's bitwise
    /// representative where it has one (see [`Linear`](Self::Linear)), operators with
    /// constants included: equal to the atom at every input, over atoms of earlier classes,
    /// so the skeleton has fewer independent atoms and stays semi-linear where it was. Two
    /// atoms that are complements (`k − t` and `t + (−1 − k)`, both read bitwise) are one atom
    /// and its complement: a semi-linear question over that one atom, which the single-bit
    /// test decides, where as two independent atoms the skeletons differ.
    Reps,
    /// The same atoms, read closer to their definitions: an atom whose class has a bitwise
    /// representative (a member that is a bitwise function of atoms of earlier classes and of
    /// variables, proved equal to it) is that function, and a bitwise function of atoms read
    /// arithmetically is its integer expansion `−a_∅ + Σ_T a_T·AND_T` (Möbius over its table,
    /// exact at every width) with each lone atom `AND_{a} = a` as its definition. Both are
    /// equal to the node at every input, so an identity of the skeletons for independent atoms
    /// is one of the expressions: `~a | ~b` read arithmetically is `−1 − (a & b)`, and
    /// `a | b` with `a = −(x ^ y)` is `−(x ^ y) + b − (a & b)`.
    Linear,
    /// Also every node below the root whose class is abstracted somewhere.
    Classes,
    /// Also the root, when its class is abstracted somewhere.
    Everything,
    /// The atoms of [`Minimal`](Self::Minimal), each an atom wherever it is read below the
    /// root: a value a bitwise operator reads that the same side also adds or scales
    /// (`(p & x) + (p | y) − p` over a `p` that is a sum) is one variable in both places.
    /// Read as its definition where it is added, as `Minimal` does, it is unrelated there to
    /// the variable it is under the bitwise operators, and the skeletons differ; with every
    /// abstracted class an atom (`Classes`) the sums compared are atoms themselves.
    Shared,
}

/// Both sides in one hash-consed DAG, with classes of nodes proved equal.
struct Compose {
    nodes: Vec<MNode>,
    cst: Vec<Option<BitVec>>,
    role: Vec<Role>,
    root_a: u32,
    root_b: u32,
    vars: Vec<Width>,
    /// Union-find parents.
    parent: Vec<u32>,
    /// Per class root: some member is abstracted (opaque, or arithmetic read bitwise).
    abstracted: Vec<bool>,
    /// Per class root: the variable among its members.
    var_member: Vec<Option<u32>>,
    /// Nodes abstracted wherever they are read, and operands of opaque nodes.
    forced: Vec<bool>,
    /// The two sides' nodes come first; the others are synthetic (complements of atoms,
    /// bitwise forms found at the sample), evaluated and paired like them but on neither side.
    sides: usize,
    intern: NodeTable,
    /// Per class root: its bitwise representative, if any (see [`Policy::Linear`]).
    rep: Vec<Option<u32>>,
    /// The sample points, and per node a digest of its value at each (the value itself up to
    /// 64 bits).
    points: Vec<Vec<BitVec>>,
    digests: Vec<Vec<u64>>,
    /// When the values fit in 64 bits, each skeleton is checked against its side's values
    /// before a test decides on it ([`Compose::agrees`]): the number of nodes whose values the
    /// check reads (those there were when it was last set up; nodes added since have none
    /// to it).
    checked: Option<usize>,
    /// The classes [`Policy::Shared`] reads as atoms in the comparison under way.
    shared: Vec<u32>,
}

/// A pair of skeletons one comparison built, with what it found: a later policy that builds
/// the same pair for the same two nodes (nothing was paired in between) is compared from here.
struct Pair {
    sx: Vec<SkelNode>,
    sy: Vec<SkelNode>,
    slots: Vec<(Slot, Width)>,
    /// `None`: the skeletons are not both polynomial expressions at the nodes' width.
    built: Option<Built>,
}

/// The skeletons of a [`Pair`] as expressions, and what does not depend on the budget.
struct Built {
    a: MbaExpr,
    b: MbaExpr,
    progs: Option<(Program, Program)>,
    /// They agree with their nodes at the sample.
    agreed: bool,
    /// The cheapest direct test, if any applies (asked only of skeletons that agree).
    plan: Option<Plan>,
    tested: Tested,
}

/// A node's width and its sample values, as a table key (hashed four words abreast).
#[derive(PartialEq, Eq)]
struct RowKey<'a>(u16, &'a [u64]);

impl core::hash::Hash for RowKey<'_> {
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        const K: u64 = 0x517c_c1b7_2722_0a95;
        let mut h = [u64::from(self.0), 1, 2, 3];
        let (fours, rest) = self.1.as_chunks::<4>();
        for c in fours {
            for (x, &d) in h.iter_mut().zip(c) {
                *x = (x.rotate_left(5) ^ d).wrapping_mul(K);
            }
        }
        for (x, &d) in h.iter_mut().zip(rest) {
            *x = (x.rotate_left(5) ^ d).wrapping_mul(K);
        }
        state.write_u64(h[0] ^ h[1].rotate_left(16) ^ h[2].rotate_left(32) ^ h[3].rotate_left(48));
        state.write_usize(self.1.len());
    }
}

/// The most distinct leaves of a bitwise function expanded by [`Policy::Linear`] (a table of
/// `2^k` entries), and of a bitwise form looked for at the sample.
const LINEAR_LEAVES: usize = 5;

fn commutative(op: &MOp) -> bool {
    matches!(op, MOp::Add | MOp::Mul | MOp::And | MOp::Or | MOp::Xor)
}

/// The index of node `i` read in `ctx`, in a table with two entries per node.
#[inline]
fn read_slot(i: u32, ctx: Ctx) -> usize {
    2 * i as usize + usize::from(ctx == Ctx::Bitwise)
}

/// The skeleton node built for each node and context, by [`read_slot`].
struct SkelMemo(Vec<u32>);

impl SkelMemo {
    const NONE: u32 = u32::MAX;

    fn new(nodes: usize) -> SkelMemo {
        SkelMemo(vec![Self::NONE; 2 * nodes])
    }

    #[inline]
    fn contains(&self, i: u32, ctx: Ctx) -> bool {
        self.0[read_slot(i, ctx)] != Self::NONE
    }

    #[inline]
    fn get(&self, i: u32, ctx: Ctx) -> Option<u32> {
        let v = self.0[read_slot(i, ctx)];
        (v != Self::NONE).then_some(v)
    }

    #[inline]
    fn insert(&mut self, i: u32, ctx: Ctx, at: u32) {
        self.0[read_slot(i, ctx)] = at;
    }
}

impl Compose {
    fn new(a: &MbaExpr, b: &MbaExpr) -> Compose {
        // Room for both sides and the nodes added to them (complements, bitwise forms).
        let total = a.nodes().len() + b.nodes().len();
        let mut nodes: Vec<MNode> = Vec::with_capacity(total + total / 2);
        let mut intern = NodeTable::with_room(total + total / 2);
        let mut roots = [0u32; 2];
        for (side, m) in [a, b].into_iter().enumerate() {
            let mut map: Vec<u32> = Vec::with_capacity(m.nodes().len());
            for n in m.nodes() {
                let mut node = *n;
                for k in 0..n.op.arity() {
                    node.args[k] = map[n.args[k] as usize];
                }
                if commutative(&node.op) && node.args[0] > node.args[1] {
                    node.args.swap(0, 1);
                }
                map.push(intern.intern(&mut nodes, node));
            }
            roots[side] = map.last().copied().unwrap_or(0);
        }
        let cst = constants(&nodes);
        let role: Vec<Role> = nodes
            .iter()
            .zip(&cst)
            .map(|(n, c)| Self::role_of(n, c.is_some()))
            .collect();
        let len = nodes.len();
        let var_member = nodes
            .iter()
            .enumerate()
            .map(|(i, n)| matches!(n.op, MOp::Var(_)).then_some(i as u32))
            .collect();
        let mut c = Compose {
            nodes,
            cst,
            role,
            root_a: roots[0],
            root_b: roots[1],
            vars: a.vars().to_vec(),
            parent: (0..len as u32).collect(),
            abstracted: vec![false; len],
            var_member,
            forced: vec![false; len],
            sides: len,
            intern,
            rep: Vec::new(),
            points: Vec::new(),
            digests: Vec::new(),
            checked: None,
            shared: Vec::new(),
        };
        c.mark_forced();
        c.add_complements();
        c
    }

    fn role_of(node: &MNode, konst: bool) -> Role {
        match node.op {
            _ if konst => Role::Const,
            MOp::Var(_) => Role::Var,
            MOp::And | MOp::Or | MOp::Xor => Role::Bitwise,
            MOp::Not => Role::Not,
            MOp::Add | MOp::Sub | MOp::Mul | MOp::Neg | MOp::Shl(_) => Role::Arith,
            _ => Role::Opaque,
        }
    }

    /// A node over existing ones (hash-consed), on neither side.
    fn push_node(&mut self, mut node: MNode) -> u32 {
        if commutative(&node.op) && node.args[0] > node.args[1] {
            node.args.swap(0, 1);
        }
        if let Some(i) = self.intern.get(&self.nodes, &node) {
            return i;
        }
        let i = self.nodes.len() as u32;
        let k = node.op.arity();
        let a = if k > 0 {
            self.cst[node.args[0] as usize]
        } else {
            None
        };
        let b = if k > 1 {
            self.cst[node.args[1] as usize]
        } else {
            None
        };
        let c = if (k > 0 && a.is_none()) || (k > 1 && b.is_none()) {
            None
        } else {
            apply(&node, a.as_ref(), b.as_ref())
        };
        self.role.push(Self::role_of(&node, c.is_some()));
        self.nodes.push(node);
        self.cst.push(c);
        self.parent.push(i);
        self.abstracted.push(false);
        self.var_member.push(None);
        self.forced.push(false);
        self.intern.insert(&self.nodes, i);
        i
    }

    /// `~a` for every atom `a`, so atoms that are complements of each other (`x − 1` and `−x`)
    /// meet at the sample, where they are paired and proved like any others.
    fn add_complements(&mut self) {
        for i in 0..self.sides {
            if self.forced[i] && matches!(self.role[i], Role::Arith | Role::Opaque) {
                let width = self.nodes[i].width;
                self.push_node(MNode {
                    op: MOp::Not,
                    width,
                    args: [i as u32, 0],
                });
            }
        }
    }

    /// Marks the nodes abstracted wherever they are read (opaque nodes, arithmetic read by a
    /// bitwise operator) and the operands of opaque nodes (definitions compared on their own).
    fn mark_forced(&mut self) {
        let mut seen = vec![false; 2 * self.nodes.len()];
        let mut stack = vec![(self.root_a, Ctx::Arith), (self.root_b, Ctx::Arith)];
        while let Some((i, ctx)) = stack.pop() {
            if std::mem::replace(&mut seen[read_slot(i, ctx)], true) {
                continue;
            }
            let n = self.nodes[i as usize];
            let args = &n.args[..n.op.arity()];
            match self.role[i as usize] {
                Role::Const | Role::Var => {}
                Role::Opaque => {
                    self.forced[i as usize] = true;
                    self.abstracted[i as usize] = true;
                    // The operand is compared as a definition of its own.
                    self.forced[args[0] as usize] = true;
                    stack.push((args[0], Ctx::Arith));
                }
                Role::Arith => {
                    if ctx == Ctx::Bitwise {
                        self.forced[i as usize] = true;
                        self.abstracted[i as usize] = true;
                    }
                    stack.extend(args.iter().map(|&k| (k, Ctx::Arith)));
                }
                Role::Bitwise => stack.extend(args.iter().map(|&k| (k, Ctx::Bitwise))),
                Role::Not => stack.push((args[0], ctx)),
            }
        }
    }

    fn find(&mut self, mut i: u32) -> u32 {
        while self.parent[i as usize] != i {
            let p = self.parent[i as usize];
            self.parent[i as usize] = self.parent[p as usize];
            i = p;
        }
        i
    }

    fn union(&mut self, a: u32, b: u32) {
        let (ra, rb) = (self.find(a), self.find(b));
        if ra == rb {
            return;
        }
        // The smaller index is the root, so a class is named by its first member.
        let (root, child) = if ra < rb { (ra, rb) } else { (rb, ra) };
        self.parent[child as usize] = root;
        self.abstracted[root as usize] |= self.abstracted[child as usize];
        if self.var_member[root as usize].is_none() {
            self.var_member[root as usize] = self.var_member[child as usize];
        }
    }

    /// Proves the two roots equal: evaluates every node at the refutation sample, pairs atoms
    /// (structure, congruence, proofs of their definitions), then compares the skeletons.
    fn prove<M: Meter>(&mut self, meter: &mut M, report: &mut Report) -> Result<(), M::Err> {
        report.compositional = true;
        // The sample, over the union of both sides.
        let mut all = MbaExpr::new(self.vars.clone());
        for n in &self.nodes {
            let r = match n.op {
                MOp::Zext | MOp::Sext | MOp::Trunc => all.push_cast(n.op, n.args[0], n.width),
                op => all.push(op, &n.args[..n.op.arity()]),
            };
            if r.is_err() {
                return Ok(());
            }
        }
        let Some(prog) = Program::new(&all, true) else {
            return Ok(());
        };
        let units = (prog.len() * SAMPLE_POINTS) as u64;
        if units > meter.left() {
            report.over_budget = true;
            return Ok(());
        }
        meter.charge(units)?;
        report.points += SAMPLE_POINTS as u64;
        // The sample's first points do not depend on its seed, and the seed is a hash of the
        // union of both sides, which costs more than evaluating the union at the sample. So
        // the sides are compared at those points first: where they differ there, that point
        // is the first of the whole sample where they do, and the refutation is the one the
        // whole sample gives, without its seed or its other points.
        let (ra, rb) = (self.root_a as usize, self.root_b as usize);
        let mut points = fixed_points(&self.vars, &[&all]);
        let fixed = points.len();
        let mut digests = digests(&prog, &points, self.nodes.len());
        if let Some(p) = (0..fixed).find(|&p| digests[ra][p] != digests[rb][p]) {
            // A real input where the sides differ.
            report.verdict = Verdict::Refuted;
            report.counterexample = Some(points[p].clone());
            give_rows(&mut digests);
            return Ok(());
        }
        let seed = crate::hash::combine(all.key()[0], all.key()[1]);
        seeded_points(&self.vars, seed, &mut points);
        if points.len() > fixed {
            // The other points' values, after the fixed points' in each row.
            let mut rest = self::digests(&prog, &points[fixed..], self.nodes.len());
            for (row, more) in digests.iter_mut().zip(&rest) {
                row.extend_from_slice(more);
            }
            give_rows(&mut rest);
        }
        if let Some(p) = (fixed..points.len()).find(|&p| digests[ra][p] != digests[rb][p]) {
            // A real input where the sides differ.
            report.verdict = Verdict::Refuted;
            report.counterexample = Some(points[p].clone());
            give_rows(&mut digests);
            return Ok(());
        }
        let values = prog.widest() <= 64;
        self.points = points;
        self.digests = digests;
        if values {
            self.checked = Some(self.digests.len());
        }
        // Group nodes by width and sample values; pair within groups, operands first. Only
        // the groups of the forced nodes are paired: per node its group, if it has one.
        const NO_GROUP: u32 = u32::MAX;
        let (group, count) = {
            let row = |i: usize| RowKey(self.nodes[i].width.bits(), &self.digests[i]);
            let mut ids: HashMap<RowKey<'_>, u32> = HashMap::default();
            for i in (0..self.nodes.len()).filter(|&i| self.forced[i]) {
                let next = ids.len() as u32;
                ids.entry(row(i)).or_insert(next);
            }
            let group: Vec<u32> = (0..self.nodes.len())
                .map(|i| ids.get(&row(i)).copied().unwrap_or(NO_GROUP))
                .collect();
            (group, ids.len())
        };
        let mut groups: Vec<Vec<u32>> = vec![Vec::new(); count];
        for i in 0..self.nodes.len() as u32 {
            let g = group[i as usize];
            if self.role[i as usize] == Role::Const || g == NO_GROUP {
                continue;
            }
            let peers = std::mem::take(&mut groups[g as usize]);
            for (tries, &m) in peers.iter().enumerate() {
                if self.find(m) == self.find(i) {
                    break;
                }
                if tries >= PAIR_TRIES {
                    break;
                }
                if self.equal_defs(meter, report, i, m)? {
                    self.union(i, m);
                    break;
                }
            }
            groups[g as usize] = peers;
            groups[g as usize].push(i);
        }
        // Atoms that are bitwise functions of the leaves of their definitions, at 64 bits or
        // fewer (where a digest is the value).
        self.compute_reps();
        if values {
            self.bitwise_forms(meter, report)?;
            self.compute_reps();
            self.checked = Some(self.digests.len());
        }
        // Every class agrees at the sample (a pairing that does not is a bug: decline).
        for i in 0..self.nodes.len() as u32 {
            let r = self.find(i);
            if self.digests[r as usize] != self.digests[i as usize] {
                report.internal += 1;
                return Ok(());
            }
        }
        if self.find(self.root_a) == self.find(self.root_b) {
            report.verdict = Verdict::Proved;
            return Ok(());
        }
        let mut seen: Vec<Pair> = Vec::new();
        for policy in [
            Policy::Minimal,
            Policy::Reps,
            Policy::Linear,
            Policy::Classes,
            Policy::Everything,
            Policy::Shared,
        ] {
            let (a, b) = (self.root_a, self.root_b);
            match self.compare(meter, report, a, b, policy, &mut seen)? {
                (Some(Verdict::Proved), _) => {
                    report.verdict = Verdict::Proved;
                    return Ok(());
                }
                (Some(Verdict::Refuted), point) => {
                    report.verdict = Verdict::Refuted;
                    report.counterexample = point;
                    return Ok(());
                }
                _ => {}
            }
        }
        Ok(())
    }

    /// Whether nodes `i` and `m` (of one width, agreeing at the sample) are proved equal: opaque
    /// nodes by congruence, others by comparing their definitions' skeletons.
    fn equal_defs<M: Meter>(
        &mut self,
        meter: &mut M,
        report: &mut Report,
        i: u32,
        m: u32,
    ) -> Result<bool, M::Err> {
        let (ni, nm) = (self.nodes[i as usize], self.nodes[m as usize]);
        let (oi, om) = (
            self.role[i as usize] == Role::Opaque,
            self.role[m as usize] == Role::Opaque,
        );
        if oi || om {
            return Ok(oi
                && om
                && ni.op == nm.op
                && ni.width == nm.width
                && self.find(ni.args[0]) == self.find(nm.args[0]));
        }
        let mut seen: Vec<Pair> = Vec::new();
        for policy in [
            Policy::Minimal,
            Policy::Reps,
            Policy::Linear,
            Policy::Classes,
            Policy::Everything,
            Policy::Shared,
        ] {
            if self.compare(meter, report, i, m, policy, &mut seen)?.0 == Some(Verdict::Proved) {
                return Ok(true);
            }
        }
        Ok(false)
    }

    /// Compares the skeletons of nodes `x` and `y` under `policy` with a direct test. `Refuted`
    /// (with the input where they differ, in the original variables) only when no atom got a
    /// variable of its own: then the skeletons equal the expressions at every input.
    ///
    /// `seen` holds the pairs of skeletons already compared for these two nodes (by earlier
    /// policies, with nothing paired in between). A policy that builds one of them again is
    /// compared from what was found then: the same decisions on what is left of the budget,
    /// the same charges, the same answer.
    fn compare<M: Meter>(
        &mut self,
        meter: &mut M,
        report: &mut Report,
        x: u32,
        y: u32,
        policy: Policy,
        seen: &mut Vec<Pair>,
    ) -> Result<Compared, M::Err> {
        let mut lanes = take_lanes();
        // `Policy::Shared` reads an atom through its class's representative as the classes
        // stand now (the representatives the other policies read are those of the whole
        // pairing, set once it is over, and are left as they are).
        let reps = (policy == Policy::Shared).then(|| {
            let reps = std::mem::take(&mut self.rep);
            self.compute_reps();
            reps
        });
        let out = self.compare_in(meter, report, x, y, policy, seen, &mut lanes);
        if let Some(reps) = reps {
            self.rep = reps;
        }
        give_lanes(lanes);
        out
    }

    /// Ends the comparison: its sample's rows go back to the thread.
    fn recycle(mut self) {
        give_rows(&mut self.digests);
    }

    /// [`Compose::compare`], evaluating in `lanes`.
    #[allow(clippy::too_many_arguments)]
    fn compare_in<M: Meter>(
        &mut self,
        meter: &mut M,
        report: &mut Report,
        x: u32,
        y: u32,
        policy: Policy,
        seen: &mut Vec<Pair>,
        lanes: &mut Lanes<u64>,
    ) -> Result<Compared, M::Err> {
        let mut vm = VarMap::default();
        if policy == Policy::Shared {
            // The classes that are atoms as the fragment requires it, from the skeletons
            // that policy builds.
            self.shared.clear();
            let mut probe = VarMap::default();
            if self.skeleton(x, Policy::Minimal, &mut probe).is_none()
                || self.skeleton(y, Policy::Minimal, &mut probe).is_none()
            {
                return Ok((None, None));
            }
            for &(slot, _) in &probe.slots {
                if let Slot::Class(c) = slot {
                    self.shared.push(c);
                }
            }
            if self.shared.is_empty() {
                return Ok((None, None));
            }
        }
        let (sx, sy) = if policy == Policy::Linear {
            (
                self.linear_skeleton(x, &mut vm),
                self.linear_skeleton(y, &mut vm),
            )
        } else {
            (
                self.skeleton(x, policy, &mut vm),
                self.skeleton(y, policy, &mut vm),
            )
        };
        let (Some(sx), Some(sy)) = (sx, sy) else {
            return Ok((None, None));
        };
        let w = self.nodes[x as usize].width;
        let at = seen
            .iter()
            .position(|p| p.slots == vm.slots && p.sx == sx && p.sy == sy);
        let pair = match at {
            Some(at) => &mut seen[at],
            None => {
                let built = self.built(&vm, &sx, &sy, x, y, lanes);
                seen.push(Pair {
                    sx,
                    sy,
                    slots: vm.slots.clone(),
                    built,
                });
                let last = seen.len() - 1;
                &mut seen[last]
            }
        };
        let Some(Built {
            a,
            b,
            progs,
            agreed,
            plan,
            tested,
        }) = pair.built.as_mut()
        else {
            return Ok((None, None));
        };
        let (a, b): (&MbaExpr, &MbaExpr) = (a, b);
        // A skeleton is its side's value wherever its variables take their nodes' values: at
        // the sample it must be. One that is not would be a bug; decline.
        if !*agreed {
            report.internal += 1;
            return Ok((None, None));
        }
        let Some(p) = plan.as_ref() else {
            let sym = symbolic_seen(meter, a, b, report, &mut tested.symbolic)?;
            if sym {
                report.cert = Some(Cert::Symbolic);
                return Ok((Some(Verdict::Proved), None));
            }
            if policy == Policy::Linear {
                let e = self.eliminate(meter, report, &mut vm, [a, b], w, lanes);
                return e;
            }
            return Ok((None, None));
        };
        let direct = test_with(
            meter,
            [a, b],
            progs.as_ref(),
            p,
            report,
            true,
            tested,
            Some(lanes),
        )?;
        if matches!(direct, Run::TooBig | Run::OverBudget) {
            let sym = symbolic_seen(meter, a, b, report, &mut tested.symbolic)?;
            if sym {
                report.cert = Some(Cert::Symbolic);
                return Ok((Some(Verdict::Proved), None));
            }
        }
        if policy == Policy::Linear
            && vm.abstracted
            && matches!(direct, Run::Differ(_) | Run::TooBig)
        {
            let e = self.eliminate(meter, report, &mut vm, [a, b], w, lanes);
            return e;
        }
        Ok(match direct {
            Run::Equal(cert) => {
                report.cert = Some(cert);
                (Some(Verdict::Proved), None)
            }
            Run::Differ(point) if !vm.abstracted => {
                // Back to the original variables (the others stay 0).
                let mut orig: Vec<BitVec> = self.vars.iter().map(|&w| BitVec::zero(w)).collect();
                for (k, &(slot, _)) in vm.slots.iter().enumerate() {
                    if let Slot::Orig(v) = slot {
                        orig[v as usize] = point[k];
                    }
                }
                (Some(Verdict::Refuted), Some(orig))
            }
            Run::Differ(_) => (Some(Verdict::Unknown), None),
            Run::OverBudget | Run::TooBig => (None, None),
        })
    }

    /// The skeletons `sx` and `sy` of nodes `x` and `y` as expressions over `vm`'s variables,
    /// compiled, checked against the sample and planned: what a comparison of them needs that
    /// the budget has no part in. `None` unless both are polynomial expressions.
    fn built(
        &mut self,
        vm: &VarMap,
        sx: &[SkelNode],
        sy: &[SkelNode],
        x: u32,
        y: u32,
        lanes: &mut Lanes<u64>,
    ) -> Option<Built> {
        let w = self.nodes[x as usize].width;
        let (a, b) = (vm.expr(sx, w)?, vm.expr(sy, w)?);
        let (pa, pb) = (profile(&a)?, profile(&b)?);
        if !(pa.poly && pb.poly) {
            return None;
        }
        let progs = Program::new(&a, false).zip(Program::new(&b, false));
        let agreed = self.agrees(vm, [(&a, x), (&b, y)], progs.as_ref(), lanes);
        let plan = if agreed { plan(&a, &pa, &pb) } else { None };
        Some(Built {
            a,
            b,
            progs,
            agreed,
            plan,
            tested: Tested::default(),
        })
    }

    /// Whether the skeletons agree with their nodes at the sample (when its values are kept):
    /// each variable of `vm` takes its node's or class's value at each point. A value the
    /// sample did not keep (a node the evaluation left out) checks nothing. Evaluated a batch
    /// of points at a time where that computes what [`MbaExpr::eval`] does, else point by
    /// point (debug builds check that both agree).
    fn agrees(
        &mut self,
        vm: &VarMap,
        sides: [(&MbaExpr, u32); 2],
        progs: Option<&(Program, Program)>,
        lanes: &mut Lanes<u64>,
    ) -> bool {
        let Some(kept) = self.checked else {
            return true;
        };
        let class_root: Vec<u32> = vm
            .slots
            .iter()
            .map(|&(slot, _)| match slot {
                Slot::Class(c) => self.find(c),
                Slot::Orig(_) => 0,
            })
            .collect();
        let (points, digests) = (&self.points, &self.digests[..kept]);
        match self.agrees_batched(vm, sides, progs, points, digests, &class_root, lanes) {
            Some(ok) => {
                debug_assert_eq!(
                    ok,
                    self.agrees_pointwise(vm, sides, points, digests, &class_root),
                    "the batched sample check differs from the pointwise one"
                );
                ok
            }
            None => self.agrees_pointwise(vm, sides, points, digests, &class_root),
        }
    }

    /// [`Compose::agrees`] point by point, with [`MbaExpr::eval`]: it stops at the first point
    /// where a variable has no value.
    fn agrees_pointwise(
        &self,
        vm: &VarMap,
        sides: [(&MbaExpr, u32); 2],
        points: &[Vec<BitVec>],
        digests: &[Vec<u64>],
        class_root: &[u32],
    ) -> bool {
        for (p, point) in points.iter().enumerate() {
            let inputs: Option<Vec<BitVec>> = vm
                .slots
                .iter()
                .zip(class_root)
                .map(|(&(slot, sw), &c)| match slot {
                    Slot::Orig(v) => point.get(v as usize).copied(),
                    Slot::Class(_) => digests
                        .get(c as usize)
                        .and_then(|d| d.get(p))
                        .map(|&v| BitVec::wrapping_from_u64(sw, v)),
                })
                .collect();
            let Some(inputs) = inputs else {
                return true;
            };
            for (skel, node) in sides {
                let w = self.nodes[node as usize].width;
                let Some(want) = digests
                    .get(node as usize)
                    .and_then(|d| d.get(p))
                    .map(|&v| BitVec::wrapping_from_u64(w, v))
                else {
                    continue;
                };
                if skel.eval(&inputs) != Some(want) {
                    return false;
                }
            }
        }
        true
    }

    /// [`Compose::agrees`] with the batched evaluator, over the points where every variable has
    /// a value (the pointwise check stops at the first one where a class's value was not kept,
    /// and those are the first `n` points). `None` where it might not compute what
    /// [`MbaExpr::eval`] does: an original variable without a value or of another width, a
    /// skeleton whose variables are not the map's, a cast, or anything wider than 64 bits.
    /// `progs`: the skeletons compiled (`None`: one has no nodes).
    #[allow(clippy::too_many_arguments)]
    fn agrees_batched(
        &self,
        vm: &VarMap,
        sides: [(&MbaExpr, u32); 2],
        progs: Option<&(Program, Program)>,
        points: &[Vec<BitVec>],
        digests: &[Vec<u64>],
        class_root: &[u32],
        lanes: &mut Lanes<u64>,
    ) -> Option<bool> {
        let mut n = points.len();
        for (&(slot, sw), &c) in vm.slots.iter().zip(class_root) {
            if sw.bits() > 64 {
                return None;
            }
            match slot {
                Slot::Orig(v) => {
                    let valued =
                        |p: &Vec<BitVec>| p.get(v as usize).is_some_and(|x| x.width() == sw);
                    if !points.iter().all(valued) {
                        return None;
                    }
                }
                Slot::Class(_) => n = n.min(digests.get(c as usize).map_or(0, Vec::len)),
            }
        }
        let compiled = progs.map(|(pa, pb)| [pa, pb]);
        let mut progs: [Option<(&Program, u32, Width)>; 2] = [None, None];
        for (side, (skel, node)) in sides.into_iter().enumerate() {
            let w = self.nodes[node as usize].width;
            let fits = skel.width() == Some(w)
                && skel.vars().len() == vm.slots.len()
                && skel
                    .vars()
                    .iter()
                    .zip(&vm.slots)
                    .all(|(&v, &(_, sw))| v == sw)
                && !skel
                    .nodes()
                    .iter()
                    .any(|m| matches!(m.op, MOp::Zext | MOp::Sext | MOp::Trunc));
            if !fits {
                return None;
            }
            let prog = compiled?[side];
            if prog.widest() > 64 {
                return None;
            }
            progs[side] = Some((prog, node, w));
        }
        // Each variable's values at the first `n` points, as lanes (a class's value reduced to
        // the variable's width, as `BitVec::wrapping_from_u64` does).
        let Lanes {
            cols: inputs,
            ra: regs,
            ..
        } = lanes;
        if inputs.len() < vm.slots.len() {
            inputs.resize_with(vm.slots.len(), Vec::new);
        }
        for ((&(slot, sw), &c), col) in vm.slots.iter().zip(class_root).zip(inputs.iter_mut()) {
            col.clear();
            match slot {
                Slot::Orig(v) => col.extend(
                    points[..n]
                        .iter()
                        .map(|p| <u64 as Lane>::from_bv(&p[v as usize])),
                ),
                Slot::Class(_) => {
                    let m = <u64 as Lane>::mask(sw);
                    col.extend(digests[c as usize][..n].iter().map(|&x| x & m));
                }
            }
        }
        let inputs = &inputs[..vm.slots.len()];
        for (prog, node, w) in progs.iter().flatten() {
            let Some(want) = digests.get(*node as usize) else {
                continue;
            };
            let upto = n.min(want.len());
            if upto == 0 {
                continue;
            }
            prog.run(regs, inputs, upto);
            let m = <u64 as Lane>::mask(*w);
            let got = &regs[prog.root()][..upto];
            if got.iter().zip(&want[..upto]).any(|(&g, &d)| g != d & m) {
                return Some(false);
            }
        }
        Some(true)
    }

    /// Under [`Policy::Linear`], when the skeletons differ over independent atoms: an atom
    /// that a side reads only as `γ·v` in all (its class variable `v`: the side is its value
    /// at `v = 0` plus `γ·v` for every value of every variable, proved by a direct test, `γ`
    /// read at one point) stands for `γ` times its definition there, exactly. So `9·(a & −2) +
    /// 8·(a & 1) − 7·a − …` with `a = (x ^ y) + 1`, whose parts of `a` add up to `a`, meets a
    /// form in `x` and `y` alone. Then the sides are compared directly.
    fn eliminate<M: Meter>(
        &mut self,
        meter: &mut M,
        report: &mut Report,
        vm: &mut VarMap,
        sides: [&MbaExpr; 2],
        w: Width,
        lanes: &mut Lanes<u64>,
    ) -> Result<Compared, M::Err> {
        // The definitions of the atoms with class variables (arithmetic ones), skeletons first,
        // so every expression has the final variables.
        let mut defs: Vec<(u32, Vec<SkelNode>)> = Vec::new();
        let mut k = 0;
        while k < vm.slots.len() && defs.len() < 4 {
            if let Slot::Class(c) = vm.slots[k].0
                // (a class is named by its first member: none comes before `c`)
                && let Some(i) = (c..self.nodes.len() as u32)
                    .find(|&i| self.role[i as usize] == Role::Arith && self.find(i) == c)
                && let Some(d) = self.linear_skeleton(i, vm)
            {
                defs.push((k as u32, d));
            }
            k += 1;
        }
        let [a0, b0] = sides;
        // The sides again over every variable.
        let widen = |m: &MbaExpr, n: usize| -> Option<MbaExpr> {
            let mut out = MbaExpr::new(vec![w; n]);
            for node in m.nodes() {
                out.push(node.op, &node.args[..node.op.arity()]).ok()?;
            }
            Some(out)
        };
        let n = vm.slots.len();
        if vm.slots.iter().any(|&(_, sw)| sw != w) {
            return Ok((None, None));
        }
        let (Some(mut a), Some(mut b)) = (widen(a0, n), widen(b0, n)) else {
            return Ok((None, None));
        };
        let defs: Vec<(u32, MbaExpr)> = defs
            .iter()
            .filter_map(|(k, d)| Some((*k, vm.expr(d, w)?)))
            .collect();
        let zero = {
            let mut z = MbaExpr::new(vec![w; n]);
            z.push(MOp::Const(BitVec::zero(w)), &[]).ok();
            z
        };
        let mut changed = false;
        for (k, d) in &defs {
            for side in [&mut a, &mut b] {
                if !side.nodes().iter().any(|m| m.op == MOp::Var(*k)) {
                    continue;
                }
                let Some(s0) = substitute_var(side, *k, &zero) else {
                    continue;
                };
                // γ, read at the point where only `v` is 1.
                let mut at = vec![BitVec::zero(w); n];
                let (Some(v0), Some(v1)) = (side.eval(&at), {
                    at[*k as usize] = BitVec::one(w);
                    side.eval(&at)
                }) else {
                    continue;
                };
                let gamma = BitVec::bin_unchecked(BinOp::Sub, &v1, &v0);
                // t = s0 + γ·v.
                let mut t = s0.clone();
                let r0 = t.nodes().len() as u32 - 1;
                let (Ok(v), Ok(g)) = (t.push(MOp::Var(*k), &[]), t.push(MOp::Const(gamma), &[]))
                else {
                    continue;
                };
                let (Ok(m), true) = (t.push(MOp::Mul, &[v, g]), true) else {
                    continue;
                };
                if t.push(MOp::Add, &[r0, m]).is_err() {
                    continue;
                }
                let (Some(ps), Some(pt)) = (profile(side), profile(&t)) else {
                    continue;
                };
                if !(ps.poly && pt.poly) {
                    continue;
                }
                let linear = match plan(side, &ps, &pt) {
                    Some(p) => match run_lanes(meter, side, &t, &p, report, lanes)? {
                        Run::Equal(_) => true,
                        Run::Differ(_) => false,
                        Run::TooBig | Run::OverBudget => symbolic(meter, side, &t, report)?,
                    },
                    None => symbolic(meter, side, &t, report)?,
                };
                if !linear {
                    continue;
                }
                if let Some(e) = substitute_var(&t, *k, d) {
                    *side = e;
                    changed = true;
                }
            }
        }
        if !changed {
            return Ok((None, None));
        }
        let (Some(pa), Some(pb)) = (profile(&a), profile(&b)) else {
            return Ok((None, None));
        };
        if !(pa.poly && pb.poly) {
            return Ok((None, None));
        }
        let Some(p) = plan(&a, &pa, &pb) else {
            return Ok(if symbolic(meter, &a, &b, report)? {
                report.cert = Some(Cert::Symbolic);
                (Some(Verdict::Proved), None)
            } else {
                (None, None)
            });
        };
        Ok(match run_lanes(meter, &a, &b, &p, report, lanes)? {
            Run::Equal(cert) => {
                report.cert = Some(cert);
                (Some(Verdict::Proved), None)
            }
            Run::Differ(_) => (Some(Verdict::Unknown), None),
            Run::OverBudget | Run::TooBig => {
                if symbolic(meter, &a, &b, report)? {
                    report.cert = Some(Cert::Symbolic);
                    (Some(Verdict::Proved), None)
                } else {
                    (None, None)
                }
            }
        })
    }

    /// The nodes a bitwise function rooted at `k` reads (walking `& | ^ ~`): variables,
    /// constants and atoms.
    fn bitwise_leaves(&self, k: u32) -> Vec<u32> {
        let mut out = Vec::new();
        let mut seen = vec![false; self.nodes.len()];
        let mut stack = vec![k];
        while let Some(i) = stack.pop() {
            if std::mem::replace(&mut seen[i as usize], true) {
                continue;
            }
            let n = self.nodes[i as usize];
            match self.role[i as usize] {
                Role::Bitwise | Role::Not => stack.extend(n.args[..n.op.arity()].iter().copied()),
                _ => out.push(i),
            }
        }
        out
    }

    /// Per class of atoms: a member that is a bitwise function (`& | ^ ~`) of variables,
    /// constants and atoms of classes named by earlier nodes, if one is, as its representative.
    /// Classes only refer to earlier ones, so reading atoms through representatives ends.
    fn compute_reps(&mut self) {
        self.rep = vec![None; self.nodes.len()];
        for k in 0..self.nodes.len() as u32 {
            if !matches!(self.role[k as usize], Role::Bitwise | Role::Not) {
                continue;
            }
            let c = self.find(k);
            if !self.abstracted[c as usize] || self.rep[c as usize].is_some() {
                continue;
            }
            let leaves = self.bitwise_leaves(k);
            let earlier = leaves.iter().all(|&l| match self.role[l as usize] {
                Role::Const | Role::Var => true,
                _ => self.find(l) < c,
            });
            if earlier {
                self.rep[c as usize] = Some(k);
            }
        }
    }

    /// The representative of atom `i`'s class, if it has one other than `i`.
    fn rep_of(&mut self, i: u32) -> Option<u32> {
        let c = self.find(i);
        self.rep
            .get(c as usize)
            .copied()
            .flatten()
            .filter(|&r| r != i)
    }

    /// The variables and atoms (by node) the definition of arithmetic node `y` reads, each
    /// class once: at most [`LINEAR_LEAVES`], else `None`.
    fn def_leaves(&mut self, y: u32) -> Option<Vec<u32>> {
        let mut out: Vec<u32> = Vec::new();
        let mut classes: Vec<u32> = Vec::new();
        let mut seen = vec![false; 2 * self.nodes.len()];
        let n = self.nodes[y as usize];
        let mut stack: Vec<(u32, Ctx)> = n.args[..n.op.arity()]
            .iter()
            .map(|&k| (k, Ctx::Arith))
            .collect();
        while let Some((i, ctx)) = stack.pop() {
            if std::mem::replace(&mut seen[read_slot(i, ctx)], true) {
                continue;
            }
            let n = self.nodes[i as usize];
            let leaf = match self.role[i as usize] {
                Role::Const => continue,
                Role::Var | Role::Opaque => true,
                Role::Arith => ctx == Ctx::Bitwise,
                Role::Bitwise | Role::Not => false,
            };
            if leaf {
                let c = self.find(i);
                if !classes.contains(&c) {
                    if out.len() == LINEAR_LEAVES {
                        return None;
                    }
                    classes.push(c);
                    out.push(i);
                }
                continue;
            }
            let sub = match self.role[i as usize] {
                Role::Bitwise => Ctx::Bitwise,
                Role::Not => ctx,
                _ => Ctx::Arith,
            };
            stack.extend(n.args[..n.op.arity()].iter().map(|&k| (k, sub)));
        }
        // And the variables the atoms among them are defined over, while there is room: a
        // subterm can be a bitwise function of an atom and the variables inside it together
        // (`−(a & x)` with `a = −(x & y)` is `(a & ~x) | (x & y)`).
        let mut stack: Vec<u32> = out
            .iter()
            .copied()
            .filter(|&l| self.role[l as usize] == Role::Arith)
            .collect();
        let mut seen = vec![false; self.nodes.len()];
        while let Some(i) = stack.pop() {
            if std::mem::replace(&mut seen[i as usize], true) {
                continue;
            }
            let n = self.nodes[i as usize];
            if self.role[i as usize] == Role::Var {
                let c = self.find(i);
                if !classes.contains(&c) && out.len() < LINEAR_LEAVES {
                    classes.push(c);
                    out.push(i);
                }
                continue;
            }
            stack.extend(n.args[..n.op.arity()].iter().copied());
        }
        Some(out)
    }

    /// Bitwise forms: for each atom (arithmetic read bitwise) whose bits at every sample point
    /// are one function of the bits of the leaves of its definition, that function as nodes
    /// (its algebraic normal form), paired with the atom once proved equal (`(e − 1 & d) − e`
    /// is `~(e − 1) | d`). The digests are values here (64 bits or fewer), and grow with the
    /// nodes.
    fn bitwise_forms<M: Meter>(
        &mut self,
        meter: &mut M,
        report: &mut Report,
    ) -> Result<(), M::Err> {
        let atoms: Vec<u32> = (0..self.sides as u32)
            .filter(|&i| self.forced[i as usize] && self.role[i as usize] == Role::Arith)
            .collect();
        for y in atoms {
            if self.rep_of(y).is_some() || self.find(y) != y {
                continue;
            }
            let Some(leaves) = self.def_leaves(y) else {
                continue;
            };
            if leaves.is_empty() {
                continue;
            }
            let w = self.nodes[y as usize].width;
            let digests = &self.digests;
            let points = digests[y as usize].len();
            let units = (points * leaves.len()) as u64;
            if units > meter.left() {
                report.over_budget = true;
                return Ok(());
            }
            meter.charge(units)?;
            let (mut seen, mut ones) = (0u64, 0u64);
            let mut fits = true;
            'points: for (p, &v) in digests[y as usize].iter().enumerate().take(points) {
                for j in 0..u32::from(w.bits()) {
                    let e = leaves.iter().enumerate().fold(0u32, |e, (t, &l)| {
                        e | (((digests[l as usize][p] >> j) & 1) as u32) << t
                    });
                    let bit = (v >> j) & 1;
                    if seen >> e & 1 == 1 {
                        if ones >> e & 1 != bit {
                            fits = false;
                            break 'points;
                        }
                    } else {
                        seen |= 1 << e;
                        ones |= bit << e;
                    }
                }
            }
            if !fits {
                continue;
            }
            let root = self.anf_nodes(ones, &leaves, w);
            self.extend_digests();
            if self.digests[root as usize] != self.digests[y as usize]
                || self.find(root) == self.find(y)
            {
                continue;
            }
            if self.equal_defs(meter, report, y, root)? {
                self.union(y, root);
            }
        }
        Ok(())
    }

    /// The function with table `t` over `leaves` (entry `e` for leaf `j` at bit `j` of `e`) as
    /// nodes: the xor of the conjunctions of its algebraic normal form.
    fn anf_nodes(&mut self, t: u64, leaves: &[u32], w: Width) -> u32 {
        let k = leaves.len();
        let mut a: Vec<bool> = (0..1usize << k).map(|e| t >> e & 1 == 1).collect();
        for b in 0..k {
            for e in 0..1usize << k {
                if e >> b & 1 == 1 {
                    a[e] ^= a[e ^ 1 << b];
                }
            }
        }
        let mut acc: Option<u32> = None;
        for (e, &on) in a.iter().enumerate().skip(1) {
            if !on {
                continue;
            }
            let mut c: Option<u32> = None;
            for (j, &l) in leaves.iter().enumerate() {
                if e >> j & 1 == 1 {
                    c = Some(match c {
                        None => l,
                        Some(x) => self.push_node(MNode {
                            op: MOp::And,
                            width: w,
                            args: [x, l],
                        }),
                    });
                }
            }
            if let Some(c) = c {
                acc = Some(match acc {
                    None => c,
                    Some(x) => self.push_node(MNode {
                        op: MOp::Xor,
                        width: w,
                        args: [x, c],
                    }),
                });
            }
        }
        let zero = self.push_node(MNode {
            op: MOp::Const(BitVec::zero(w)),
            width: w,
            args: [0, 0],
        });
        let x = acc.unwrap_or(zero);
        if a[0] {
            self.push_node(MNode {
                op: MOp::Not,
                width: w,
                args: [x, 0],
            })
        } else {
            x
        }
    }

    /// Digests (values, at 64 bits or fewer) of the nodes added since they were computed: only
    /// constants and `& | ^ ~` are added.
    fn extend_digests(&mut self) {
        let points = self.digests.first().map_or(0, Vec::len);
        for i in self.digests.len()..self.nodes.len() {
            let n = self.nodes[i];
            let bits = n.width.bits();
            let mask = if bits >= 64 {
                u64::MAX
            } else {
                (1u64 << bits) - 1
            };
            let digests = &self.digests;
            let col = |k: u32, p: usize| digests[k as usize].get(p).copied().unwrap_or(0);
            let v: Vec<u64> = (0..points)
                .map(|p| match n.op {
                    MOp::Const(c) => c.limbs().first().copied().unwrap_or(0) & mask,
                    MOp::And => col(n.args[0], p) & col(n.args[1], p),
                    MOp::Or => col(n.args[0], p) | col(n.args[1], p),
                    MOp::Xor => col(n.args[0], p) ^ col(n.args[1], p),
                    MOp::Not => !col(n.args[0], p) & mask,
                    _ => 0,
                })
                .collect();
            self.digests.push(v);
        }
    }

    /// The integer expansion of the bitwise function at `i` (read arithmetically) over its
    /// leaves, when it reads an atom (see [`Policy::Linear`]): atoms are read through their
    /// representatives, and only 0 and all-ones constants are allowed.
    fn expansion(&mut self, i: u32) -> Option<Expansion> {
        let w = self.nodes[i as usize].width;
        // The leaves, by class, and the internal nodes in post-order.
        let mut leaves: Vec<(u32, u32)> = Vec::new();
        let mut post: Vec<u32> = Vec::new();
        let mut state = vec![false; self.nodes.len()];
        let mut stack: Vec<(u32, bool)> = vec![(i, false)];
        let mut atom = false;
        while let Some((k, done)) = stack.pop() {
            if done {
                post.push(k);
                continue;
            }
            if std::mem::replace(&mut state[k as usize], true) {
                continue;
            }
            let n = self.nodes[k as usize];
            match self.role[k as usize] {
                Role::Const => {
                    let c = self.cst[k as usize]?;
                    if !(c.is_zero() || c.is_ones()) {
                        return None;
                    }
                    post.push(k);
                }
                Role::Bitwise | Role::Not => {
                    stack.push((k, true));
                    stack.extend(n.args[..n.op.arity()].iter().map(|&a| (a, false)));
                }
                Role::Var | Role::Arith | Role::Opaque => {
                    if self.role[k as usize] != Role::Var
                        && let Some(r) = self.rep_of(k)
                    {
                        // Read through its representative.
                        stack.push((k, true));
                        stack.push((r, false));
                        continue;
                    }
                    atom |= self.role[k as usize] != Role::Var;
                    let c = self.find(k);
                    if !leaves.iter().any(|&(_, lc)| lc == c) {
                        if leaves.len() == LINEAR_LEAVES {
                            return None;
                        }
                        leaves.push((k, c));
                    }
                    post.push(k);
                }
            }
        }
        if !atom {
            return None;
        }
        let k = leaves.len();
        let full: u64 = if k == 6 {
            u64::MAX
        } else {
            (1u64 << (1u32 << k)) - 1
        };
        let column = |j: usize| {
            (0..1u64 << k)
                .filter(|e| e >> j & 1 == 1)
                .fold(0u64, |t, e| t | 1 << e)
        };
        let mut table: HashMap<u32, u64> = HashMap::default();
        for &n in &post {
            let node = self.nodes[n as usize];
            let v = match self.role[n as usize] {
                Role::Const => {
                    if self.cst[n as usize]?.is_zero() {
                        0
                    } else {
                        full
                    }
                }
                Role::Var | Role::Arith | Role::Opaque => match self.rep_of(n) {
                    Some(r) if self.role[n as usize] != Role::Var => *table.get(&r)?,
                    _ => {
                        let c = self.find(n);
                        column(leaves.iter().position(|&(_, lc)| lc == c)?)
                    }
                },
                Role::Not => !*table.get(&node.args[0])? & full,
                Role::Bitwise => {
                    let (a, b) = (*table.get(&node.args[0])?, *table.get(&node.args[1])?);
                    match node.op {
                        MOp::And => a & b,
                        MOp::Or => a | b,
                        _ => a ^ b,
                    }
                }
            };
            table.insert(n, v);
        }
        let t = *table.get(&i)?;
        // Möbius: a_T = Σ_{U⊆T} (−1)^{|T|−|U|}·f(U).
        let mut a: Vec<i64> = (0..1usize << k).map(|e| (t >> e & 1) as i64).collect();
        for b in 0..k {
            for e in 0..1usize << k {
                if e >> b & 1 == 1 {
                    a[e] -= a[e ^ 1 << b];
                }
            }
        }
        let konst = BitVec::wrapping_from_i128(w, -i128::from(a[0]));
        let mut terms = Vec::new();
        for (e, &c) in a.iter().enumerate().skip(1) {
            if c == 0 {
                continue;
            }
            let members: Vec<u32> = (0..k)
                .filter(|&j| e >> j & 1 == 1)
                .map(|j| leaves[j].0)
                .collect();
            let reads: Vec<(u32, Ctx)> = if let [l] = members.as_slice() {
                // A lone atom is its definition; an opaque one stays an atom.
                let ctx = if self.role[*l as usize] == Role::Arith {
                    Ctx::Arith
                } else {
                    Ctx::Bitwise
                };
                vec![(*l, ctx)]
            } else {
                members.iter().map(|&l| (l, Ctx::Bitwise)).collect()
            };
            terms.push((BitVec::wrapping_from_i128(w, i128::from(c)), reads));
        }
        Some(Expansion {
            width: w,
            konst,
            terms,
        })
    }

    /// The skeleton of node `root` under [`Policy::Linear`].
    fn linear_skeleton(&mut self, root: u32, vm: &mut VarMap) -> Option<Vec<SkelNode>> {
        enum Item {
            Visit(u32, Ctx),
            Finish(u32, Ctx),
            Alias(u32, u32),
            Expand(u32, usize),
        }
        let mut out: Vec<SkelNode> = Vec::new();
        let mut memo = SkelMemo::new(self.nodes.len());
        let mut plans: Vec<Expansion> = Vec::new();
        let mut stack = vec![Item::Visit(root, Ctx::Arith)];
        while let Some(item) = stack.pop() {
            match item {
                Item::Visit(i, ctx) => {
                    if memo.contains(i, ctx) {
                        continue;
                    }
                    let n = self.nodes[i as usize];
                    if let Some(c) = self.cst[i as usize] {
                        out.push(SkelNode::Const(c));
                        memo.insert(i, ctx, out.len() as u32 - 1);
                        continue;
                    }
                    if let MOp::Var(x) = n.op {
                        out.push(SkelNode::Var(vm.orig(x, n.width)));
                        memo.insert(i, ctx, out.len() as u32 - 1);
                        continue;
                    }
                    let role = self.role[i as usize];
                    if role == Role::Opaque || (role == Role::Arith && ctx == Ctx::Bitwise) {
                        if ctx == Ctx::Bitwise
                            && let Some(r) = self.rep_of(i)
                        {
                            stack.push(Item::Alias(i, r));
                            stack.push(Item::Visit(r, Ctx::Bitwise));
                            continue;
                        }
                        let c = self.find(i);
                        let v = match self.var_member[c as usize] {
                            Some(vi) => match self.nodes[vi as usize].op {
                                MOp::Var(x) => vm.orig(x, n.width),
                                _ => return None,
                            },
                            None => vm.class(c, n.width),
                        };
                        out.push(SkelNode::Var(v));
                        memo.insert(i, ctx, out.len() as u32 - 1);
                        continue;
                    }
                    if role == Role::Bitwise
                        && ctx == Ctx::Arith
                        && let Some(e) = self.expansion(i)
                    {
                        stack.push(Item::Expand(i, plans.len()));
                        for (_, reads) in &e.terms {
                            stack.extend(reads.iter().map(|&(l, c)| Item::Visit(l, c)));
                        }
                        plans.push(e);
                        continue;
                    }
                    let sub = match role {
                        Role::Bitwise => Ctx::Bitwise,
                        Role::Not => ctx,
                        _ => Ctx::Arith,
                    };
                    stack.push(Item::Finish(i, ctx));
                    stack.extend(n.args[..n.op.arity()].iter().map(|&k| Item::Visit(k, sub)));
                }
                Item::Finish(i, ctx) => {
                    let n = self.nodes[i as usize];
                    let sub = match self.role[i as usize] {
                        Role::Bitwise => Ctx::Bitwise,
                        Role::Not => ctx,
                        _ => Ctx::Arith,
                    };
                    let mut args = [0u32; 2];
                    for (k, &a) in n.args[..n.op.arity()].iter().enumerate() {
                        args[k] = memo.get(a, sub)?;
                    }
                    out.push(SkelNode::Op(n.op, args));
                    memo.insert(i, ctx, out.len() as u32 - 1);
                }
                Item::Alias(i, r) => {
                    let v = memo.get(r, Ctx::Bitwise)?;
                    memo.insert(i, Ctx::Bitwise, v);
                }
                Item::Expand(i, e) => {
                    let plan = &plans[e];
                    let mut acc: Option<u32> = None;
                    for (c, reads) in &plan.terms {
                        let mut t = memo.get(reads[0].0, reads[0].1)?;
                        for r in &reads[1..] {
                            let x = memo.get(r.0, r.1)?;
                            out.push(SkelNode::Op(MOp::And, [t, x]));
                            t = out.len() as u32 - 1;
                        }
                        if *c != BitVec::one(plan.width) {
                            out.push(SkelNode::Const(*c));
                            out.push(SkelNode::Op(MOp::Mul, [t, out.len() as u32 - 1]));
                            t = out.len() as u32 - 1;
                        }
                        acc = Some(match acc {
                            None => t,
                            Some(a) => {
                                out.push(SkelNode::Op(MOp::Add, [a, t]));
                                out.len() as u32 - 1
                            }
                        });
                    }
                    // The expansion's own node: a lone term with coefficient 1 and no
                    // constant is its leaf's node, pushed long before (not the last one).
                    let result = match acc {
                        Some(a) if plan.konst.is_zero() => a,
                        _ => {
                            out.push(SkelNode::Const(plan.konst));
                            let k = out.len() as u32 - 1;
                            match acc {
                                Some(a) => {
                                    out.push(SkelNode::Op(MOp::Add, [a, k]));
                                    out.len() as u32 - 1
                                }
                                None => k,
                            }
                        }
                    };
                    memo.insert(i, Ctx::Arith, result);
                }
            }
        }
        let r = memo.get(root, Ctx::Arith)? as usize;
        out.truncate(r + 1);
        Some(out)
    }

    /// Whether node `i`, read in `ctx`, is an atom of a skeleton under `policy`.
    fn atom(&mut self, i: u32, ctx: Ctx, root: bool, policy: Policy) -> bool {
        match self.role[i as usize] {
            Role::Const | Role::Var => false,
            Role::Opaque => true,
            role => {
                if role == Role::Arith && ctx == Ctx::Bitwise {
                    return true;
                }
                let c = self.find(i);
                match policy {
                    Policy::Minimal | Policy::Reps | Policy::Linear => false,
                    Policy::Classes => !root && self.abstracted[c as usize],
                    Policy::Everything => self.abstracted[c as usize],
                    // (Not a bitwise member of such a class: it is what the class is read
                    // as, see `Policy::Reps`.)
                    Policy::Shared => role == Role::Arith && !root && self.shared.contains(&c),
                }
            }
        }
    }

    /// The skeleton of node `root` (read as a term): atoms become variables of `vm`, one per
    /// class (the class's own variable when it has one).
    fn skeleton(&mut self, root: u32, policy: Policy, vm: &mut VarMap) -> Option<Vec<SkelNode>> {
        let mut out: Vec<SkelNode> = Vec::with_capacity(16);
        let mut memo = SkelMemo::new(self.nodes.len());
        let mut stack: Vec<(u32, Ctx, bool)> = Vec::with_capacity(16);
        stack.push((root, Ctx::Arith, false));
        // Under `Policy::Reps`, atoms read as their representative: the atom's skeleton is the
        // representative's (whose leaves are of earlier classes, so this ends).
        let mut alias: HashMap<u32, u32> = HashMap::default();
        while let Some((i, ctx, expanded)) = stack.pop() {
            if memo.contains(i, ctx) {
                continue;
            }
            // (The node's fields are read where they are: a node is 96 bytes, copied per
            // visit otherwise.)
            let (width, args_of) = {
                let n = &self.nodes[i as usize];
                (n.width, n.args)
            };
            if expanded && let Some(&r) = alias.get(&i) {
                let at = memo.get(r, ctx)?;
                memo.insert(i, ctx, at);
                continue;
            }
            if !expanded {
                if let Some(c) = self.cst[i as usize] {
                    out.push(SkelNode::Const(c));
                } else if matches!(policy, Policy::Reps | Policy::Shared)
                    && self.atom(i, ctx, i == root, policy)
                    && let Some(r) = self.rep_of(i)
                {
                    alias.insert(i, r);
                    stack.push((i, ctx, true));
                    stack.push((r, ctx, false));
                    continue;
                } else if self.atom(i, ctx, i == root, policy) {
                    let c = self.find(i);
                    let v = match self.var_member[c as usize] {
                        Some(vi) => match self.nodes[vi as usize].op {
                            MOp::Var(x) => vm.orig(x, width),
                            _ => return None,
                        },
                        None => vm.class(c, width),
                    };
                    out.push(SkelNode::Var(v));
                } else if let MOp::Var(x) = self.nodes[i as usize].op {
                    let v = vm.orig(x, width);
                    out.push(SkelNode::Var(v));
                } else {
                    let sub = match self.role[i as usize] {
                        Role::Bitwise => Ctx::Bitwise,
                        Role::Not => ctx,
                        _ => Ctx::Arith,
                    };
                    stack.push((i, ctx, true));
                    let arity = self.nodes[i as usize].op.arity();
                    for &k in &args_of[..arity] {
                        stack.push((k, sub, false));
                    }
                    continue;
                }
                memo.insert(i, ctx, out.len() as u32 - 1);
                continue;
            }
            let sub = match self.role[i as usize] {
                Role::Bitwise => Ctx::Bitwise,
                Role::Not => ctx,
                _ => Ctx::Arith,
            };
            let op = self.nodes[i as usize].op;
            let mut args = [0u32; 2];
            for (k, &a) in args_of[..op.arity()].iter().enumerate() {
                args[k] = memo.get(a, sub)?;
            }
            out.push(SkelNode::Op(op, args));
            memo.insert(i, ctx, out.len() as u32 - 1);
        }
        // The root is the last node built for it.
        let r = memo.get(root, Ctx::Arith)? as usize;
        out.truncate(r + 1);
        Some(out)
    }
}

// ----- carries -------------------------------------------------------------------------------

/// The most state bits (carries and shifted-out bits) a bit-serial comparison keeps.
const CARRY_BITS: u32 = 32;

/// The largest left shift a bit-serial comparison follows (its last bits are state).
const CARRY_SHIFT: u16 = 8;

/// One node of a bit-serial circuit: how its bit at a position is made.
#[derive(Copy, Clone)]
enum Serial {
    Const(BitVec),
    Var(u32),
    /// A variable narrower than the circuit, zero-extended: its bit below its width, else 0.
    VarBelow(u32, u16),
    Not(usize),
    And(usize, usize),
    Or(usize, usize),
    Xor(usize, usize),
    /// `a + b + carry` (`sub`: `a + ~b + carry`, the carry starting at 1); the carry's state bit.
    Add(usize, usize, bool, u32),
    /// `~a + carry`, the carry starting at 1.
    Neg(usize, u32),
    /// `a << k`: the last `k` bits of `a` from state bit `at` on.
    Shl(usize, u16, u32),
}

/// Bit-serial comparison of expressions built from `+ − neg ~ & | ^`, constants, left shifts by
/// at most [`CARRY_SHIFT`] and products by a constant below `2^(CARRY_SHIFT + 1)` or its
/// negation (a sum of shifts), every node and variable of one width. Bit `j` of such an
/// expression depends only on bits `0..=j` of the variables (they are T-functions), through a
/// few bits of state: each addition's carry and each shift's last bits. So it is a finite
/// automaton reading one bit of every variable per position; walking every reachable state
/// through every input bit combination at every position, the two sides agree everywhere or a
/// path gives an input where they differ. Exact at the width, whatever carries propagate
/// (`(y + y) & y & −y` is 0: no bit of `y` both follows a set bit and has none below it). Up to
/// [`CARRY_BITS`] bits of state and six variables; charged as node evaluations. A variable
/// narrower than the width read only through a zero extension (as `decast` writes narrow
/// variables) is one whose bits above its width are 0, and one wider read only through a
/// truncation is read at the positions the sides have.
pub(crate) fn carries<M: Meter>(
    meter: &mut M,
    a: &MbaExpr,
    b: &MbaExpr,
    report: &mut Report,
) -> Result<bool, M::Err> {
    let Some(w) = a.width() else {
        return Ok(false);
    };
    let t = a.vars().len();
    if b.width() != Some(w) || a.vars() != b.vars() || t > 6 {
        return Ok(false);
    }
    // Both sides as one circuit (live nodes only, equal ones once: they share their state).
    let mut circuit: Vec<Serial> = Vec::new();
    let mut state = 0u32;
    let mut roots = [0usize; 2];
    let mut interned: HashMap<(MOp, [usize; 2]), usize> = HashMap::default();
    for (side, m) in [a, b].into_iter().enumerate() {
        let live = live(m);
        let mut map: Vec<usize> = vec![usize::MAX; m.nodes().len()];
        for (i, n) in m.nodes().iter().enumerate() {
            if !live[i] {
                continue;
            }
            if n.width != w {
                // A narrow variable is read through its zero extension (below).
                if matches!(n.op, MOp::Var(_)) {
                    continue;
                }
                return Ok(false);
            }
            if n.op == MOp::Zext {
                let arg = m.nodes()[n.args[0] as usize];
                let MOp::Var(v) = arg.op else {
                    return Ok(false);
                };
                circuit.push(Serial::VarBelow(v, arg.width.bits()));
                map[i] = circuit.len() - 1;
                continue;
            }
            // The low bits of a variable wider than the sides (as `decast` writes one under
            // a truncation): the variable, read at the positions there are.
            if n.op == MOp::Trunc {
                let MOp::Var(v) = m.nodes()[n.args[0] as usize].op else {
                    return Ok(false);
                };
                circuit.push(Serial::Var(v));
                map[i] = circuit.len() - 1;
                continue;
            }
            let mut key = [0usize; 2];
            for (k, slot) in key.iter_mut().enumerate().take(n.op.arity()) {
                *slot = map[n.args[k] as usize];
            }
            if commutative(&n.op) && key[0] > key[1] {
                key.swap(0, 1);
            }
            if let Some(&c) = interned.get(&(n.op, key)) {
                map[i] = c;
                continue;
            }
            let x = |k: usize| key[k];
            let s = match n.op {
                MOp::Const(c) => Serial::Const(c),
                MOp::Var(v) => Serial::Var(v),
                MOp::Not => Serial::Not(x(0)),
                MOp::And => Serial::And(x(0), x(1)),
                MOp::Or => Serial::Or(x(0), x(1)),
                MOp::Xor => Serial::Xor(x(0), x(1)),
                MOp::Add | MOp::Sub => {
                    state += 1;
                    Serial::Add(x(0), x(1), n.op == MOp::Sub, state - 1)
                }
                MOp::Neg => {
                    state += 1;
                    Serial::Neg(x(0), state - 1)
                }
                // `t << 0` is `t` (a shift keeps its last `k` bits as state: none here).
                MOp::Shl(0) => {
                    map[i] = x(0);
                    interned.insert((n.op, key), map[i]);
                    continue;
                }
                MOp::Shl(k) if k <= CARRY_SHIFT => {
                    state += u32::from(k);
                    Serial::Shl(x(0), k, state - u32::from(k))
                }
                // `t·c` for a constant `c` (or `−c`) of few low bits: the sum of `t << i` over
                // its set bits (negated), whichever of the two takes fewer state bits.
                MOp::Mul => {
                    let (t, c) = match (&circuit[x(0)], &circuit[x(1)]) {
                        (_, Serial::Const(c)) => (x(0), *c),
                        (Serial::Const(c), _) => (x(1), *c),
                        _ => return Ok(false),
                    };
                    // The state bits of the expansion: the shifts' amounts and one per add.
                    let bits = |c: &BitVec| {
                        c.to_u64()
                            .filter(|&v| v < 1u64 << (u32::from(CARRY_SHIFT) + 1))
                            .map(|v| {
                                (0..=u32::from(CARRY_SHIFT))
                                    .filter(|&i| v >> i & 1 == 1)
                                    .map(|i| i + 1)
                                    .sum::<u32>()
                                    .saturating_sub(1)
                            })
                    };
                    let neg = BitVec::un_unchecked(UnOp::Neg, &c);
                    let (c, negate) = match (bits(&c), bits(&neg)) {
                        (Some(p), Some(n)) if n + 1 < p => (neg, true),
                        (Some(_), _) => (c, false),
                        (None, Some(_)) => (neg, true),
                        (None, None) => return Ok(false),
                    };
                    let v = c.to_u64().unwrap_or(0);
                    let mut acc: Option<usize> = None;
                    for i in 0..=CARRY_SHIFT {
                        if v >> i & 1 == 0 {
                            continue;
                        }
                        let part = if i == 0 {
                            t
                        } else {
                            state += u32::from(i);
                            circuit.push(Serial::Shl(t, i, state - u32::from(i)));
                            circuit.len() - 1
                        };
                        acc = Some(match acc {
                            None => part,
                            Some(a) => {
                                state += 1;
                                circuit.push(Serial::Add(a, part, false, state - 1));
                                circuit.len() - 1
                            }
                        });
                    }
                    let Some(acc) = acc else {
                        // A product by 0 is 0.
                        circuit.push(Serial::Const(BitVec::zero(w)));
                        map[i] = circuit.len() - 1;
                        interned.insert((n.op, key), map[i]);
                        continue;
                    };
                    if state > CARRY_BITS {
                        return Ok(false);
                    }
                    if negate {
                        state += 1;
                        Serial::Neg(acc, state - 1)
                    } else {
                        map[i] = acc;
                        interned.insert((n.op, key), acc);
                        continue;
                    }
                }
                _ => return Ok(false),
            };
            if state > CARRY_BITS {
                return Ok(false);
            }
            circuit.push(s);
            map[i] = circuit.len() - 1;
            interned.insert((n.op, key), map[i]);
        }
        roots[side] = map[nodes_root(m)];
    }
    // The initial state: carries of subtractions and negations are 1.
    let mut init = 0u64;
    for s in &circuit {
        match *s {
            Serial::Add(_, _, true, at) | Serial::Neg(_, at) => init |= 1 << at,
            _ => {}
        }
    }
    let inputs = 1u64 << t;
    let mut layer: Vec<u64> = vec![init];
    // Per position: each state's predecessor and input (for a counterexample).
    let mut trail: Vec<HashMap<u64, (u64, u64)>> = Vec::new();
    let mut bits = vec![false; circuit.len()];
    // The states that occur are usually few, so the test is sized as it goes: past
    // [`MAX_EFFORT`] in all it is a stable decline (the same states occur whatever the budget);
    // a position over what is left of the budget is not run.
    let mut effort = 0u64;
    for j in 0..w.bits() {
        let units = (layer.len() as u64) * inputs * circuit.len() as u64;
        effort = effort.saturating_add(units);
        if effort > MAX_EFFORT {
            return Ok(false);
        }
        if units > meter.left() {
            report.over_budget = true;
            return Ok(false);
        }
        meter.charge(units)?;
        report.points += layer.len() as u64 * inputs;
        let mut next: HashMap<u64, (u64, u64)> = HashMap::default();
        for &st in &layer {
            for x in 0..inputs {
                let mut out = st;
                for (k, s) in circuit.iter().enumerate() {
                    bits[k] = match *s {
                        Serial::Const(c) => c.bit(j).unwrap_or(false),
                        Serial::Var(v) => x >> v & 1 == 1,
                        Serial::VarBelow(v, n) => j < n && x >> v & 1 == 1,
                        Serial::Not(p) => !bits[p],
                        Serial::And(p, q) => bits[p] & bits[q],
                        Serial::Or(p, q) => bits[p] | bits[q],
                        Serial::Xor(p, q) => bits[p] ^ bits[q],
                        Serial::Add(p, q, sub, at) => {
                            let (u, v, c) = (bits[p], bits[q] ^ sub, st >> at & 1 == 1);
                            let carry = (u & v) | (u & c) | (v & c);
                            out = (out & !(1 << at)) | (u64::from(carry) << at);
                            u ^ v ^ c
                        }
                        Serial::Neg(p, at) => {
                            let (u, c) = (!bits[p], st >> at & 1 == 1);
                            out = (out & !(1 << at)) | (u64::from(u & c) << at);
                            u ^ c
                        }
                        Serial::Shl(p, k, at) => {
                            // Bit j − k of the operand is the oldest kept; the current one
                            // enters.
                            let hist = (st >> at) & ((1u64 << k) - 1);
                            let oldest = hist >> (k - 1) & 1 == 1;
                            let newer = ((hist << 1) | u64::from(bits[p])) & ((1u64 << k) - 1);
                            out = (out & !(((1u64 << k) - 1) << at)) | (newer << at);
                            oldest
                        }
                    };
                }
                if bits[roots[0]] != bits[roots[1]] {
                    // An input where the sides differ: bits along the path, 0 above.
                    let mut vals = vec![0u64; t];
                    let mut cur = (st, x);
                    for pos in (0..=usize::from(j)).rev() {
                        for (v, val) in vals.iter_mut().enumerate() {
                            *val |= (cur.1 >> v & 1) << pos;
                        }
                        if pos > 0 {
                            cur = trail[pos - 1][&cur.0];
                        }
                    }
                    if w.bits() > 64 {
                        // Only positions below 64 are rebuilt: undecided rather than wrong.
                        return Ok(false);
                    }
                    report.verdict = Verdict::Refuted;
                    report.cert = Some(Cert::Carries);
                    report.counterexample = Some(
                        vals.iter()
                            .zip(a.vars())
                            .map(|(&v, &vw)| BitVec::wrapping_from_u64(vw, v))
                            .collect(),
                    );
                    return Ok(true);
                }
                next.entry(out).or_insert((st, x));
            }
        }
        layer = next.keys().copied().collect();
        layer.sort_unstable();
        trail.push(next);
    }
    report.verdict = Verdict::Proved;
    report.cert = Some(Cert::Carries);
    Ok(true)
}

/// The root of `m` (its last node).
fn nodes_root(m: &MbaExpr) -> usize {
    m.nodes().len().saturating_sub(1)
}

// ----- symbolic ------------------------------------------------------------------------------

/// The most monomials a symbolic expansion keeps (more: it decides nothing).
const SYMBOLIC_TERMS: usize = 4096;

/// A polynomial over symbols: monomials (symbol ids, sorted, repeated for powers) with
/// coefficients of one width.
#[derive(Clone, Debug, PartialEq, Eq)]
struct SymPoly(std::collections::BTreeMap<Vec<u32>, BitVec>);

impl SymPoly {
    fn constant(c: BitVec) -> SymPoly {
        let mut m = std::collections::BTreeMap::new();
        if !c.is_zero() {
            m.insert(Vec::new(), c);
        }
        SymPoly(m)
    }

    fn symbol(s: u32, w: Width) -> SymPoly {
        let mut m = std::collections::BTreeMap::new();
        m.insert(vec![s], BitVec::one(w));
        SymPoly(m)
    }

    fn add_term(&mut self, m: Vec<u32>, c: &BitVec) {
        if c.is_zero() {
            return;
        }
        match self.0.entry(m) {
            std::collections::btree_map::Entry::Vacant(v) => {
                v.insert(*c);
            }
            std::collections::btree_map::Entry::Occupied(mut o) => {
                let s = BitVec::bin_unchecked(BinOp::Add, o.get(), c);
                if s.is_zero() {
                    o.remove();
                } else {
                    *o.get_mut() = s;
                }
            }
        }
    }

    fn add(&self, o: &SymPoly, k: &BitVec) -> SymPoly {
        let mut out = self.clone();
        for (m, c) in &o.0 {
            out.add_term(m.clone(), &BitVec::bin_unchecked(BinOp::Mul, c, k));
        }
        out
    }

    fn mul(&self, o: &SymPoly) -> Option<SymPoly> {
        if self.0.len().saturating_mul(o.0.len()) > SYMBOLIC_TERMS * 4 {
            return None;
        }
        let mut out = SymPoly(std::collections::BTreeMap::new());
        for (m, c) in &self.0 {
            for (n, d) in &o.0 {
                let mut mn: Vec<u32> = m.iter().chain(n).copied().collect();
                mn.sort_unstable();
                out.add_term(mn, &BitVec::bin_unchecked(BinOp::Mul, c, d));
            }
        }
        (out.0.len() <= SYMBOLIC_TERMS).then_some(out)
    }
}

/// Whether `a` and `b` are the same polynomial over symbols: variables; the conjunctions of the
/// leaves of a bitwise function whose constants are 0 or all-ones, which it is read as by its
/// integer expansion (`x | y` is `x + y − (x & y)`, every bit alike); one leaf under a mask,
/// for a bitwise function of that leaf and constants (`f(0)` plus the leaf under the bits it
/// sets, less the leaf under the bits it clears); and any other bitwise subterm, one symbol by
/// its structure. Equal polynomials are equal functions, whatever the
/// symbols' values (so for their actual ones); unequal ones decide nothing. `None` past
/// [`SYMBOLIC_TERMS`], or once `work` is past `limit`. Work: one unit per monomial operation.
pub(crate) fn symbolic_equal(a: &MbaExpr, b: &MbaExpr, limit: u64, work: &mut u64) -> Option<bool> {
    let w = a.width()?;
    if b.width()? != w || a.vars() != b.vars() {
        return None;
    }
    // Both sides in one hash-consed table, so equal subterms are one symbol.
    let total = a.nodes().len() + b.nodes().len();
    let mut canon = NodeTable::with_room(total);
    let mut nodes: Vec<MNode> = Vec::with_capacity(total);
    let mut roots = [0u32; 2];
    for (side, m) in [a, b].into_iter().enumerate() {
        let mut map: Vec<u32> = Vec::with_capacity(m.nodes().len());
        for n in m.nodes() {
            let mut k = *n;
            for i in 0..n.op.arity() {
                k.args[i] = map[n.args[i] as usize];
            }
            if commutative(&k.op) && k.args[0] > k.args[1] {
                k.args.swap(0, 1);
            }
            map.push(canon.intern(&mut nodes, k));
        }
        roots[side] = *map.last()?;
    }
    let cst = constants(&nodes);
    let bitwise = |op: &MOp| matches!(op, MOp::And | MOp::Or | MOp::Xor | MOp::Not);
    // Symbols: variables by index, conjunctions by their leaf set, others by node.
    let mut symbols: HashMap<(u8, Vec<u32>), u32> = HashMap::default();
    let mut symbol = |kind: u8, key: Vec<u32>| {
        let n = symbols.len() as u32;
        *symbols.entry((kind, key)).or_insert(n)
    };
    let mut polys: Vec<Option<SymPoly>> = vec![None; nodes.len()];
    for i in 0..nodes.len() {
        let n = nodes[i];
        // The operands' polynomials, read in place (a copy of each per use was most of the
        // comparison's time on sums).
        let arg = |k: usize| polys[n.args[k] as usize].as_ref();
        let p = if let Some(c) = cst[i] {
            SymPoly::constant(c)
        } else {
            match n.op {
                MOp::Var(v) => SymPoly::symbol(symbol(0, vec![v]), w),
                MOp::Add => arg(0)?.add(arg(1)?, &BitVec::one(w)),
                MOp::Sub => arg(0)?.add(arg(1)?, &BitVec::ones(w)),
                MOp::Neg => SymPoly::constant(BitVec::zero(w)).add(arg(0)?, &BitVec::ones(w)),
                MOp::Shl(k) => {
                    let s = crate::facts::known::bv_shl(&BitVec::one(w), u32::from(k));
                    SymPoly::constant(BitVec::zero(w)).add(arg(0)?, &s)
                }
                MOp::Mul => {
                    let (x, y) = (arg(0)?, arg(1)?);
                    *work = work.saturating_add((x.0.len() * y.0.len()) as u64);
                    if *work > limit {
                        return None;
                    }
                    x.mul(y)?
                }
                MOp::And | MOp::Or | MOp::Xor | MOp::Not => {
                    // The bitwise function's leaves: variables and non-bitwise subterms.
                    let mut leaves: Vec<u32> = Vec::new();
                    let mut uniform = true;
                    let mut stack = vec![i as u32];
                    let mut seen: HashMap<u32, ()> = HashMap::default();
                    while let Some(k) = stack.pop() {
                        if seen.insert(k, ()).is_some() {
                            continue;
                        }
                        let m = nodes[k as usize];
                        if let Some(c) = cst[k as usize] {
                            uniform &= c.is_zero() || c.is_ones();
                        } else if bitwise(&m.op) {
                            stack.extend(m.args[..m.op.arity()].iter().copied());
                        } else if !leaves.contains(&k) {
                            leaves.push(k);
                        }
                    }
                    leaves.sort_unstable();
                    let expansion = if uniform && leaves.len() <= 6 {
                        // Its table over the leaves, then its Möbius expansion.
                        let t = leaves.len();
                        let full: u64 = if t == 6 {
                            u64::MAX
                        } else {
                            (1u64 << (1u32 << t)) - 1
                        };
                        let mut table: HashMap<u32, u64> = HashMap::default();
                        let mut order: Vec<u32> = seen.keys().copied().collect();
                        order.sort_unstable();
                        for &k in &order {
                            let m = nodes[k as usize];
                            let v = if let Some(c) = cst[k as usize] {
                                if c.is_zero() { 0 } else { full }
                            } else if let Some(j) = leaves.iter().position(|&l| l == k) {
                                (0..1u64 << t)
                                    .filter(|e| e >> j & 1 == 1)
                                    .fold(0u64, |acc, e| acc | 1 << e)
                            } else {
                                let x = |a: usize| table.get(&m.args[a]).copied();
                                match m.op {
                                    MOp::Not => !x(0)? & full,
                                    MOp::And => x(0)? & x(1)?,
                                    MOp::Or => x(0)? | x(1)?,
                                    _ => x(0)? ^ x(1)?,
                                }
                            };
                            table.insert(k, v);
                        }
                        let f = *table.get(&(i as u32))?;
                        let mut coef: Vec<i64> =
                            (0..1usize << t).map(|e| (f >> e & 1) as i64).collect();
                        for bit in 0..t {
                            for e in 0..1usize << t {
                                if e >> bit & 1 == 1 {
                                    coef[e] -= coef[e ^ 1 << bit];
                                }
                            }
                        }
                        // The leaves' own polynomials, as symbols where they are not variables.
                        let mut leaf_sym: Vec<u32> = Vec::with_capacity(t);
                        for &l in &leaves {
                            leaf_sym.push(match nodes[l as usize].op {
                                MOp::Var(v) => symbol(0, vec![v]),
                                _ => symbol(2, vec![l]),
                            });
                        }
                        let mut p =
                            SymPoly::constant(BitVec::wrapping_from_i128(w, -i128::from(coef[0])));
                        for (e, &c) in coef.iter().enumerate().skip(1) {
                            if c == 0 {
                                continue;
                            }
                            let c = BitVec::wrapping_from_i128(w, i128::from(c));
                            if e.count_ones() == 1 {
                                // A lone leaf is its own value: its polynomial.
                                let l = leaves[e.trailing_zeros() as usize];
                                p = p.add(polys[l as usize].as_ref()?, &c);
                                continue;
                            }
                            let mut set: Vec<u32> = (0..t)
                                .filter(|&j| e >> j & 1 == 1)
                                .map(|j| leaf_sym[j])
                                .collect();
                            set.sort_unstable();
                            p.add_term(vec![symbol(1, set)], &c);
                        }
                        Some(p)
                    } else if let ([l], true) = (&leaves[..], w.bits() <= 64) {
                        // One leaf under constants: each bit is a constant, the leaf's bit or
                        // its complement, so the value is `f(0)` plus the leaf's bits that set
                        // one less those that clear one. The leaf under each of the two masks
                        // is a symbol (the leaf itself under every bit), whatever spelled it:
                        // `m − (~t & m)` and `t & m` are one polynomial.
                        let ones = if w.bits() == 64 {
                            u64::MAX
                        } else {
                            (1u64 << w.bits()) - 1
                        };
                        let mut at: HashMap<u32, (u64, u64)> = HashMap::default();
                        let mut order: Vec<u32> = seen.keys().copied().collect();
                        order.sort_unstable();
                        for &k in &order {
                            let m = nodes[k as usize];
                            let v = if let Some(c) = cst[k as usize] {
                                let c = c.to_u64()?;
                                (c, c)
                            } else if k == *l {
                                (0, ones)
                            } else {
                                let x = |a: usize| at.get(&m.args[a]).copied();
                                match m.op {
                                    MOp::Not => {
                                        let a = x(0)?;
                                        (!a.0 & ones, !a.1 & ones)
                                    }
                                    MOp::And => (x(0)?.0 & x(1)?.0, x(0)?.1 & x(1)?.1),
                                    MOp::Or => (x(0)?.0 | x(1)?.0, x(0)?.1 | x(1)?.1),
                                    _ => (x(0)?.0 ^ x(1)?.0, x(0)?.1 ^ x(1)?.1),
                                }
                            };
                            at.insert(k, v);
                        }
                        let (f0, f1) = *at.get(&(i as u32))?;
                        let leaf = match nodes[*l as usize].op {
                            MOp::Var(v) => symbol(0, vec![v]),
                            _ => symbol(2, vec![*l]),
                        };
                        let mut p = SymPoly::constant(BitVec::wrapping_from_u64(w, f0));
                        for (mask, c) in [(f1 & !f0, BitVec::one(w)), (f0 & !f1, BitVec::ones(w))] {
                            if mask == ones {
                                p = p.add(polys[*l as usize].as_ref()?, &c);
                            } else if mask != 0 {
                                let key = vec![leaf, mask as u32, (mask >> 32) as u32];
                                p.add_term(vec![symbol(3, key)], &c);
                            }
                        }
                        Some(p)
                    } else {
                        None
                    };
                    // A non-variable leaf stands for its own polynomial only through its
                    // symbol; the whole is one symbol when it is not expanded.
                    expansion.unwrap_or_else(|| SymPoly::symbol(symbol(2, vec![i as u32]), w))
                }
                _ => SymPoly::symbol(symbol(2, vec![i as u32]), w),
            }
        };
        *work = work.saturating_add(p.0.len() as u64 + 1);
        if *work > limit {
            return None;
        }
        polys[i] = Some(p);
    }
    let (pa, pb) = (
        polys[roots[0] as usize].as_ref()?,
        polys[roots[1] as usize].as_ref()?,
    );
    Some(pa == pb)
}

/// [`symbolic_equal`] within what is left of `meter`, charged [`SYMBOLIC_RATE`] units per unit
/// of its work: true only for a proof. Stopped by the budget, it reports over budget (more
/// might decide). It decides the pair it is given, which may be a step toward the question (a
/// pairing of atoms, an elimination), so it records no verdict: the caller that proves the
/// question does.
fn symbolic<M: Meter>(
    meter: &mut M,
    a: &MbaExpr,
    b: &MbaExpr,
    report: &mut Report,
) -> Result<bool, M::Err> {
    symbolic_seen(meter, a, b, report, &mut SymbolicSeen::Unasked)
}

/// [`symbolic`], with what earlier comparisons of the same pair found (see [`Tested`]).
fn symbolic_seen<M: Meter>(
    meter: &mut M,
    a: &MbaExpr,
    b: &MbaExpr,
    report: &mut Report,
    seen: &mut SymbolicSeen,
) -> Result<bool, M::Err> {
    let limit = meter.left() / SYMBOLIC_RATE;
    let (equal, work) = seen.equal(a, b, limit);
    if work > limit {
        report.over_budget = true;
    }
    meter.charge(work.min(limit) * SYMBOLIC_RATE)?;
    Ok(equal)
}

/// `m` with variable `v` read as `by` (over the same variables): `by`'s nodes, then `m`'s
/// nodes that its root uses, `v` mapped to `by`'s root.
fn substitute_var(m: &MbaExpr, v: u32, by: &MbaExpr) -> Option<MbaExpr> {
    let nodes = m.nodes();
    let live = live(m);
    let mut out = MbaExpr::new(m.vars().to_vec());
    let mut map_by: Vec<u32> = Vec::with_capacity(by.nodes().len());
    for n in by.nodes() {
        let mut args = [0u32; 2];
        let k = n.op.arity();
        for (to, &a) in args.iter_mut().zip(&n.args[..k]) {
            *to = map_by[a as usize];
        }
        map_by.push(out.push(n.op, &args[..k]).ok()?);
    }
    let by_root = *map_by.last()?;
    let mut map: Vec<u32> = vec![0; nodes.len()];
    let mut last = by_root;
    for (i, n) in nodes.iter().enumerate() {
        if !live[i] {
            continue;
        }
        last = match n.op {
            MOp::Var(x) if x == v => by_root,
            op => {
                let mut args = [0u32; 2];
                let k = op.arity();
                for (to, &a) in args.iter_mut().zip(&n.args[..k]) {
                    *to = map[a as usize];
                }
                out.push(op, &args[..k]).ok()?
            }
        };
        map[i] = last;
    }
    // The root is the last node (a root that is `v` itself is `by`'s root, pushed last when
    // nothing else is live).
    if last as usize + 1 != out.nodes().len() {
        return None;
    }
    Some(out)
}

/// A bitwise function read arithmetically, as `konst + Σ c·(leaves read so, and-ed)`.
struct Expansion {
    width: Width,
    konst: BitVec,
    terms: Vec<(BitVec, Vec<(u32, Ctx)>)>,
}

/// A skeleton node before its variables are numbered.
#[derive(Clone, Debug, PartialEq)]
enum SkelNode {
    Const(BitVec),
    Var(u32),
    Op(MOp, [u32; 2]),
}

/// The variables of a pair of skeletons: original variables and atom classes.
#[derive(Default)]
struct VarMap {
    slots: Vec<(Slot, Width)>,
    /// Some atom class got a variable of its own.
    abstracted: bool,
}

#[derive(Copy, Clone, PartialEq, Eq)]
enum Slot {
    Orig(u32),
    Class(u32),
}

impl VarMap {
    fn get(&mut self, s: Slot, w: Width) -> u32 {
        if let Some(i) = self.slots.iter().position(|&(t, _)| t == s) {
            return i as u32;
        }
        self.slots.push((s, w));
        self.slots.len() as u32 - 1
    }

    fn orig(&mut self, v: u32, w: Width) -> u32 {
        self.get(Slot::Orig(v), w)
    }

    fn class(&mut self, c: u32, w: Width) -> u32 {
        self.abstracted = true;
        self.get(Slot::Class(c), w)
    }

    /// The skeleton as an expression over every variable of the map, all of width `w`.
    fn expr(&self, s: &[SkelNode], w: Width) -> Option<MbaExpr> {
        if self.slots.iter().any(|&(_, sw)| sw != w) {
            return None;
        }
        let mut m = MbaExpr::new(vec![w; self.slots.len()]);
        for n in s {
            match n {
                SkelNode::Const(c) => m.push(MOp::Const(*c), &[]),
                SkelNode::Var(v) => m.push(MOp::Var(*v), &[]),
                SkelNode::Op(op, args) => m.push(*op, &args[..op.arity()]),
            }
            .ok()?;
        }
        Some(m)
    }
}

/// Per node of `prog` (every node kept): a digest of its value at each point (the value itself
/// up to 64 bits). Equal values give equal digests.
fn digests(prog: &Program, points: &[Vec<BitVec>], nodes: usize) -> Vec<Vec<u64>> {
    match Kind::of(prog.widest()) {
        Kind::N64 => {
            // The values are the digests: when every node has its own register in order (a
            // program that kept every node), the registers themselves, not a copy of each.
            let n = points.len();
            if n > 0 && nodes == prog.len() && (0..nodes).all(|i| prog.reg_of(i) == Some(i)) {
                let nv = points.first().map_or(0, Vec::len);
                let inputs: Vec<Vec<u64>> = (0..nv)
                    .map(|v| {
                        points
                            .iter()
                            .map(|p| <u64 as Lane>::from_bv(&p[v]))
                            .collect()
                    })
                    .collect();
                let mut regs: Vec<Vec<u64>> = take_rows(nodes);
                prog.run(&mut regs, &inputs, n);
                if regs.len() == nodes && regs.iter().all(|r| r.len() == n) {
                    return regs;
                }
            }
            digests_in::<u64>(prog, points, nodes, |x| *x)
        }
        Kind::N128 => digests_in::<u128>(prog, points, nodes, |x| {
            crate::hash::combine(*x as u64, (*x >> 64) as u64)
        }),
        Kind::Wide => digests_in::<Wide>(prog, points, nodes, |x| {
            x.0.iter().fold(0x5eed, |h, &l| crate::hash::combine(h, l))
        }),
    }
}

fn digests_in<L: Lane>(
    prog: &Program,
    points: &[Vec<BitVec>],
    nodes: usize,
    digest: impl Fn(&L) -> u64,
) -> Vec<Vec<u64>> {
    let n = points.len();
    let nv = points.first().map_or(0, Vec::len);
    let inputs: Vec<Vec<L>> = (0..nv)
        .map(|v| points.iter().map(|p| L::from_bv(&p[v])).collect())
        .collect();
    let mut regs: Vec<Vec<L>> = Vec::new();
    prog.run(&mut regs, &inputs, n);
    (0..nodes)
        .map(|i| match prog.reg_of(i) {
            Some(r) => regs[r][..n].iter().map(&digest).collect(),
            None => Vec::new(),
        })
        .collect()
}

// ----- the native prover -----------------------------------------------------------------------

/// bitwright's own exact equivalence checks as an [`EquivalenceProver`]: the refutation sample,
/// then the cheapest certificate that applies (the corner signature, single bit positions, at
/// most `d` bit positions for degree `d`, the pure-polynomial grid, exhaustive evaluation; equal
/// polynomials over symbols first where that test would take far longer), over abstracted
/// atoms when a side leaves the polynomial fragment. The same checks are the evidence gate's
/// own, so an engine needs this prover only when its host uses the MBA module directly.
///
/// Work is counted in node evaluations against [`MbaBudget::steps`], the symbolic comparison
/// at 256 per monomial operation (what one costs) and within what is left; a certificate over
/// the budget is not run, and one stopped by it is not finished (`Unknown`). `Refuted` comes
/// with a concrete counterexample.
///
/// ```
/// use bitwright::mba::{EquivalenceProver, MOp, MbaBudget, MbaExpr, NativeProver, Verdict};
/// use bitwright::Width;
///
/// // (x & y)·(x | y) + (x & ~y)·(~x & y) == x·y, a degree-2 identity, at 64 bits: the same
/// // polynomial over x, y and x & y, so it takes none of the degree-2 test's 18,337 points.
/// let w = Width::W64;
/// let mut a = MbaExpr::new(vec![w, w]);
/// let (x, y) = (a.push(MOp::Var(0), &[])?, a.push(MOp::Var(1), &[])?);
/// let (and, or) = (a.push(MOp::And, &[x, y])?, a.push(MOp::Or, &[x, y])?);
/// let p = a.push(MOp::Mul, &[and, or])?;
/// let (nx, ny) = (a.push(MOp::Not, &[x])?, a.push(MOp::Not, &[y])?);
/// let (l, r) = (a.push(MOp::And, &[x, ny])?, a.push(MOp::And, &[nx, y])?);
/// let q = a.push(MOp::Mul, &[l, r])?;
/// a.push(MOp::Add, &[p, q])?;
/// let mut b = MbaExpr::new(vec![w, w]);
/// let (x, y) = (b.push(MOp::Var(0), &[])?, b.push(MOp::Var(1), &[])?);
/// b.push(MOp::Mul, &[x, y])?;
/// let prover = NativeProver::default();
/// assert_eq!(prover.prove_equal(&a, &b, &MbaBudget::default()), Verdict::Proved);
/// assert_eq!((prover.stats().symbolic, prover.stats().sparse), (1, 0));
/// # Ok::<(), bitwright::mba::MbaError>(())
/// ```
///
/// [`EquivalenceProver`]: super::EquivalenceProver
/// [`MbaBudget::steps`]: super::MbaBudget::steps
#[derive(Debug, Default)]
pub struct NativeProver {
    stats: std::sync::Mutex<CertStats>,
}

impl NativeProver {
    /// A prover with zeroed counters.
    pub fn new() -> NativeProver {
        NativeProver::default()
    }

    /// What it has decided so far, and how.
    pub fn stats(&self) -> CertStats {
        self.stats.lock().map_or_else(|e| *e.into_inner(), |g| *g)
    }
}

impl super::EquivalenceProver for NativeProver {
    fn id(&self) -> &str {
        "bitwright.native.v2"
    }

    fn prove_equal(&self, a: &MbaExpr, b: &MbaExpr, budget: &super::MbaBudget) -> Verdict {
        let report = check(a, b, budget.steps);
        if let Ok(mut s) = self.stats.lock() {
            s.record(&report);
        }
        report.verdict
    }
}

/// The refutation sample, then [`prove`], under a budget of `steps` node evaluations (the
/// report says how many it spent).
pub(crate) fn check(a: &MbaExpr, b: &MbaExpr, steps: u64) -> Report {
    let mut meter = Steps::new(steps);
    let mut report = Report::new();
    if a.vars() != b.vars() || a.width().is_none() || a.width() != b.width() {
        return report;
    }
    let units = ((a.nodes().len() + b.nodes().len()) * SAMPLE_POINTS) as u64;
    if meter.charge(units).is_err() {
        report.over_budget = true;
        return report;
    }
    report.points += SAMPLE_POINTS as u64;
    report.work = meter.spent;
    let seed = crate::hash::combine(a.key()[0], b.key()[1]);
    let points = sample_points(a.vars(), &[a, b], seed);
    if let Some(p) = refute(a, b, &points) {
        report.verdict = Verdict::Refuted;
        report.counterexample = Some(p);
        return report;
    }
    let mut r = match prove(a, b, &mut meter) {
        Ok(mut r) => {
            r.points += report.points;
            r
        }
        Err(()) => {
            report.over_budget = true;
            report
        }
    };
    r.work = meter.spent;
    r
}

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

    /// The sparse points in their order, written out directly: for each number of positions
    /// `k` up to `d`, each set of `k` bit positions in increasing lexicographic order, each
    /// assignment of nonzero patterns (subsets of the `t` variables) to them, the last position
    /// fastest; variable `j` has the bits of the positions whose pattern holds it.
    fn reference(w: u16, t: usize, d: u32) -> Vec<Vec<u64>> {
        let mut out = vec![vec![0u64; t]];
        for k in 1..=(d as usize).min(usize::from(w)) {
            let mut combo: Vec<u16> = (0..k as u16).collect();
            loop {
                let mut pats = vec![1u64; k];
                loop {
                    out.push(
                        (0..t)
                            .map(|j| {
                                combo
                                    .iter()
                                    .zip(&pats)
                                    .filter(|&(_, &p)| p >> j & 1 == 1)
                                    .fold(0u64, |x, (&pos, _)| x | 1 << pos)
                            })
                            .collect(),
                    );
                    let mut s = k;
                    loop {
                        if s == 0 {
                            break;
                        }
                        s -= 1;
                        pats[s] += 1;
                        if pats[s] < 1 << t {
                            break;
                        }
                        pats[s] = 1;
                        if s == 0 {
                            s = usize::MAX;
                            break;
                        }
                    }
                    if s == usize::MAX {
                        break;
                    }
                }
                // The next combination.
                let mut s = k;
                let mut moved = false;
                while s > 0 {
                    s -= 1;
                    if usize::from(combo[s]) < usize::from(w) - k + s {
                        combo[s] += 1;
                        for u in s + 1..k {
                            combo[u] = combo[u - 1] + 1;
                        }
                        moved = true;
                        break;
                    }
                }
                if !moved {
                    break;
                }
            }
        }
        out
    }

    #[test]
    fn sparse_points_are_the_ones_written_out() {
        for (w, t, d) in [
            (4u16, 1usize, 1u32),
            (4, 2, 2),
            (5, 3, 2),
            (8, 2, 3),
            (6, 4, 2),
            (3, 2, 5),
            (7, 1, 3),
            // Runs of the last pattern longer than a block (2^9 - 1 = 511 > 256).
            (3, 9, 1),
            (2, 9, 2),
        ] {
            let plan = Plan {
                cert: if d <= 1 {
                    Cert::SingleBit
                } else {
                    Cert::Sparse
                },
                points: sparse_points(w, t, d),
                used: (0..t).collect(),
                radix: Vec::new(),
                degree: d,
            };
            let width = Width::new(w).unwrap();
            let vars = vec![width; t];
            let masks: Vec<u64> = vars.iter().map(|&v| <u64 as Lane>::mask(v)).collect();
            let mut cols: Vec<Vec<u64>> = vec![Vec::new(); t];
            let mut points = Points::new(&plan, w);
            let mut got: Vec<Vec<u64>> = Vec::new();
            loop {
                let n = points.fill(&mut cols, &plan.used, &vars, &masks);
                if n == 0 {
                    break;
                }
                got.extend((0..n).map(|p| cols.iter().map(|c| c[p]).collect::<Vec<u64>>()));
            }
            let want = reference(w, t, d);
            assert_eq!(got.len() as u64, plan.points, "w {w} t {t} d {d}");
            assert_eq!(got, want, "w {w} t {t} d {d}");
        }
    }
}

// right shifts of bitwise functions in the polynomial fragment.
#[cfg(test)]
mod shift_tests {
    use super::*;

    fn var(m: &mut MbaExpr, v: u32) -> u32 {
        m.push(MOp::Var(v), &[]).unwrap()
    }
    fn k(m: &mut MbaExpr, v: u64) -> u32 {
        m.push(MOp::Const(BitVec::wrapping_from_u64(Width::W64, v)), &[])
            .unwrap()
    }
    fn report(a: &MbaExpr, b: &MbaExpr) -> Report {
        prove(a, b, &mut Steps::new(1 << 24)).unwrap_or_else(|()| Report::new())
    }

    #[test]
    fn a_shifted_bitwise_function_at_its_own_offset_is_in_the_fragment() {
        // `((~(x & K) >> 24) & 0xffff) << 24` is `~(x & K) & 0xffff000000`: bits `24..40` of
        // one function of `x`, at offset 0 again.
        let mut a = MbaExpr::new(vec![Width::W64]);
        let x = var(&mut a, 0);
        let c = k(&mut a, 0x1_4000_0000);
        let t = a.push(MOp::And, &[x, c]).unwrap();
        let n = a.push(MOp::Not, &[t]).unwrap();
        let s = a.push(MOp::LShr(24), &[n]).unwrap();
        let m = k(&mut a, 0xffff);
        let s = a.push(MOp::And, &[s, m]).unwrap();
        let s = a.push(MOp::Shl(24), &[s]).unwrap();
        let hi = k(&mut a, 0xff_ff00_0000);
        let u = a.push(MOp::And, &[t, hi]).unwrap();
        a.push(MOp::Add, &[s, u]).unwrap();
        let mut b = MbaExpr::new(vec![Width::W64]);
        k(&mut b, 0xff_ff00_0000);
        let p = profile(&a).unwrap();
        assert!(p.poly && !p.uniform && p.degree == 1, "{p:?}");
        assert_eq!(report(&a, &b).verdict, Verdict::Proved);
    }

    #[test]
    fn bitwise_operands_at_different_offsets_are_not_one_position() {
        // `(x >> 1) & x` is zero wherever `x` has at most one bit set, and not zero at 3:
        // reading it as one position per bit would prove it zero.
        let mut a = MbaExpr::new(vec![Width::W64]);
        let x = var(&mut a, 0);
        let s = a.push(MOp::LShr(1), &[x]).unwrap();
        a.push(MOp::And, &[s, x]).unwrap();
        let mut b = MbaExpr::new(vec![Width::W64]);
        k(&mut b, 0);
        assert!(!profile(&a).unwrap().poly);
        assert_ne!(report(&a, &b).verdict, Verdict::Proved);
    }
}