cverif 0.0.3

Verifies that compiled machine code faithfully matches its C source
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
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
//! Binary-to-binary comparison: are two machine-code images observably equivalent?
//!
//! Both sides are executed symbolically from the same machine state.  For every function the
//! two images define under the same name, the paths of the old code are explored and the new
//! code is run under the same path condition; at every external call, at a trap and at the
//! return the observable state must be the same: the result, the memory the caller can reach,
//! the calls made and their arguments, the accesses to peripheral registers, the callee-saved
//! registers and the stack pointer.
//!
//! Two things a source would supply are missing and are replaced by explicit rules:
//!
//! * **Addresses.**  The two images lay their data out differently.  The new image runs in the
//!   address space of the old one: the address of every data access it makes is translated by
//!   symbol (`g + 4` of the new image is `g + 4` of the old one), and data only the new image
//!   has lives in a window of its own.  Pointer *values* (results, arguments, stored words)
//!   are equal when they designate the same symbol and offset, the same function, or constant
//!   strings with the same contents.
//! * **Signatures.**  r0-r3 and the stack are all potential arguments; r0 and r1 are both
//!   potential results.  A difference confined to a register that may be dead (a `void`
//!   function leaves garbage in r0) is a class of its own or a stated condition, never
//!   silently dropped.  See [`Assumptions`].

use crate::c::ast::{Program, VOID};
use crate::image::{Image, Segment, SymKind};
use crate::sym::{Ctx, R, Stop};
use crate::term::{Env, Node, T};
use crate::thumb::exec::{Callee, Exit, Machine, Remap, image_init};
use crate::verify::{Options as VerifyOptions, Status, model_runtime_call, run_jobs, verify};
use std::cell::RefCell;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::fmt::Write as _;
use std::sync::Arc;
use std::time::Instant;

// ----- options ----------------------------------------------------------------------

/// What the comparison takes for granted where machine code alone does not say.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Assumptions {
    /// The stack pointer is 8-byte aligned at function entry (AAPCS public interface).
    pub sp_aligned: bool,
    /// A register or stack word that the two images pass with different values to a function
    /// neither of them defines is not an argument of that function.  Off by default: such a
    /// function is then reported as MAY-DIFFER.
    pub ext_arity: bool,
    /// A function whose r1 differs at return does not return a 64-bit value, unless a caller
    /// in one of the images reads r1 after calling it.
    pub ret32: bool,
    /// A function whose effects are the same and whose r0 differs at return returns nothing,
    /// unless a caller in one of the images reads r0 after calling it.
    pub void_r0: bool,
    /// The stack at and above the entry stack pointer is the caller's.  Machine code does not
    /// say how many stack arguments a function has (those it owns and may overwrite), so every
    /// word there counts as visible to the caller: the two versions must leave the same values.
    pub caller_stack: bool,
}

impl Default for Assumptions {
    fn default() -> Self {
        Assumptions {
            sp_aligned: true,
            ext_arity: false,
            ret32: true,
            void_r0: false,
            caller_stack: true,
        }
    }
}

impl Assumptions {
    /// Name, whether it is in force, and what it means.
    pub fn list(&self) -> Vec<(&'static str, bool, &'static str)> {
        vec![
            (
                "sp-aligned",
                self.sp_aligned,
                "the stack pointer is 8-byte aligned at function entry",
            ),
            (
                "ext-arity",
                self.ext_arity,
                "an argument register or stack word passed with different values to a function neither image defines is not one of its arguments (each use is listed)",
            ),
            (
                "ret32",
                self.ret32,
                "a function whose r1 differs at return does not return a 64-bit value, unless a caller in the images reads r1",
            ),
            (
                "void-r0",
                self.void_r0,
                "a function with the same effects whose r0 differs at return returns nothing, unless a caller in the images reads r0",
            ),
            (
                "caller-stack",
                self.caller_stack,
                "the stack at and above the entry stack pointer belongs to the caller (the number of stack arguments is unknown): a store there is a difference unless both versions leave the same value",
            ),
        ]
    }

    pub fn set(&mut self, name: &str, on: bool) -> Result<(), String> {
        match name {
            "sp-aligned" => self.sp_aligned = on,
            "ext-arity" => self.ext_arity = on,
            "ret32" => self.ret32 = on,
            "void-r0" => self.void_r0 = on,
            "caller-stack" => self.caller_stack = on,
            _ => {
                return Err(format!(
                    "unknown assumption `{name}` (known: sp-aligned, ext-arity, ret32, void-r0, caller-stack)"
                ));
            }
        }
        Ok(())
    }
}

/// Assumptions of the model itself: they cannot be switched off.
pub const MODEL_ASSUMPTIONS: [&str; 7] = [
    "a callee does not read an argument register that some caller leaves holding what an earlier call clobbered, nor a stack word some caller never wrote",
    "a call that is the last instruction of a function does not return",
    "results are returned in r0 (r0:r1); r4-r11 and sp are compared as outputs, r2, r3, r12 and the flags are not",
    "pointers received from the caller do not point into the function's own stack frame or its stack arguments",
    "behaviour does not depend on the numeric value of addresses: a value that designates the same symbol and offset in both images is the same pointer",
    "an access whose address has a constant part inside an object is an access to that object",
    "only constant addresses inside the peripheral ranges (--mmio) are volatile; other memory is compared by its contents at each call and at return",
];

#[derive(Clone, Debug, Default)]
pub struct Options {
    pub verify: VerifyOptions,
    pub assume: Assumptions,
    /// Explain every reported difference: the two values as expressions, where they differ,
    /// and the code of both versions.
    pub explain: bool,
}

// ----- results ----------------------------------------------------------------------

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Verdict {
    /// Proved observably equivalent for every machine state (under the listed conditions).
    Equivalent,
    /// The same except in a place that may be dead: r0 at return (dead if the function returns
    /// nothing), an argument word at a call (dead if the callee takes fewer arguments), a frame
    /// slot a callee can reach (dead if it lies outside the object the callee was given).
    MayDiffer(String),
    /// Provably different, with an input that shows it.
    Different(String),
    /// No difference found, but exploration hit a limit.
    Bounded(String),
    /// The prover gave up.
    Inconclusive(String),
    /// Something the comparison does not model.
    Unsupported(String),
    /// Only the new image has the function.
    Added,
    /// Only the old image has the function.
    Removed,
}

#[derive(Clone, Debug)]
pub struct FuncDiff {
    pub name: String,
    /// (address, size) in the old and in the new image.
    pub old: Option<(u32, u32)>,
    pub new: Option<(u32, u32)>,
    pub verdict: Verdict,
    /// The code bytes are identical.
    pub same_code: bool,
    /// Conditions the verdict depends on.
    pub conditions: Vec<String>,
    /// Functions it calls that are assumed equivalent and are not proved so: (name, status).
    pub modulo: Vec<(String, String)>,
    /// The verdict was obtained with the functions it calls inlined on both sides.
    pub inlined: bool,
    /// How the source was used (three-way mode).
    pub via_source: Option<String>,
    pub paths: usize,
    pub millis: u128,
    /// With `Options::explain`: the difference in detail and both listings.
    pub explanation: Option<String>,
}

impl FuncDiff {
    pub fn label(&self) -> &'static str {
        match &self.verdict {
            Verdict::Equivalent if self.same_code && self.old.map(|o| o.0) != self.new.map(|n| n.0) => "MOVED",
            Verdict::Equivalent if self.same_code => "IDENTICAL",
            Verdict::Equivalent => "EQUIVALENT",
            Verdict::MayDiffer(_) => "MAY-DIFFER",
            Verdict::Different(_) => "DIFFERENT",
            Verdict::Bounded(_) => "BOUNDED",
            Verdict::Inconclusive(_) => "INCONCLUSIVE",
            Verdict::Unsupported(_) => "UNSUPPORTED",
            Verdict::Added => "ADDED",
            Verdict::Removed => "REMOVED",
        }
    }

    /// Equivalent, whatever the code looks like.
    pub fn is_equivalent(&self) -> bool {
        self.verdict == Verdict::Equivalent
    }

    pub fn detail(&self) -> String {
        let mut parts: Vec<String> = Vec::new();
        match &self.verdict {
            Verdict::MayDiffer(s)
            | Verdict::Different(s)
            | Verdict::Bounded(s)
            | Verdict::Inconclusive(s)
            | Verdict::Unsupported(s) => parts.push(s.clone()),
            _ => {}
        }
        if !self.modulo.is_empty() {
            let l: Vec<String> = self.modulo.iter().map(|(n, s)| format!("{n} ({s})")).collect();
            parts.push(format!("modulo {}", l.join(", ")));
        }
        if !self.conditions.is_empty() {
            parts.push(format!("if {}", self.conditions.join("; ")));
        }
        if let Some(s) = &self.via_source {
            parts.push(format!("[{s}]"));
        }
        parts.join("  ")
    }
}

#[derive(Clone, Debug, Default)]
pub struct Comparison {
    pub funcs: Vec<FuncDiff>,
    /// Data objects both images define, and those whose initial contents differ.
    pub data_checked: usize,
    pub data: Vec<(String, String)>,
    pub data_added: Vec<String>,
    pub data_removed: Vec<String>,
    pub assume: Assumptions,
    pub with_source: bool,
}

impl Comparison {
    /// Something provably differs.
    pub fn differs(&self) -> bool {
        !self.data.is_empty() || self.funcs.iter().any(|f| matches!(f.verdict, Verdict::Different(_)))
    }

    /// Some function differs unless a register or stack slot is dead, which nothing shows.
    pub fn may_differ(&self) -> bool {
        self.funcs.iter().any(|f| matches!(f.verdict, Verdict::MayDiffer(_)))
    }

    pub fn func(&self, name: &str) -> Option<&FuncDiff> {
        self.funcs.iter().find(|f| f.name == name)
    }

    pub fn count(&self, label: &str) -> usize {
        self.funcs.iter().filter(|f| f.label() == label).count()
    }

    pub fn render(&self) -> String {
        let mut o = String::new();
        let width = self.funcs.iter().map(|f| f.name.len()).max().unwrap_or(8);
        for f in &self.funcs {
            let size = |x: Option<(u32, u32)>| x.map_or("-".to_string(), |x| x.1.to_string());
            let mut line = format!(
                "{:<12} {:<width$}  {:>5} -> {:<5} bytes  {:>4} paths  {:>6} ms",
                f.label(),
                f.name,
                size(f.old),
                size(f.new),
                f.paths,
                f.millis
            );
            let d = f.detail();
            if !d.is_empty() {
                line.push_str("  ");
                line.push_str(&d);
            }
            let _ = writeln!(o, "{}", line.trim_end());
            if let Some(e) = &f.explanation {
                for l in e.lines() {
                    let _ = writeln!(o, "    {l}");
                }
            }
        }
        for (n, what) in &self.data {
            let _ = writeln!(o, "{:<12} {n}: {what}", "DATA");
        }
        for n in &self.data_added {
            let _ = writeln!(o, "{:<12} {n}: only in the new image", "DATA");
        }
        for n in &self.data_removed {
            let _ = writeln!(o, "{:<12} {n}: only in the old image", "DATA");
        }
        let _ = writeln!(o);
        let eq = self.funcs.iter().filter(|f| f.is_equivalent()).count();
        let names = |l: &str| -> String {
            let v: Vec<&str> = self
                .funcs
                .iter()
                .filter(|f| f.label() == l)
                .map(|f| f.name.as_str())
                .collect();
            if v.is_empty() {
                String::new()
            } else {
                format!(": {}", v.join(", "))
            }
        };
        let _ = writeln!(
            o,
            "functions:       {eq} equivalent ({} identical, {} moved), {} different{}",
            self.count("IDENTICAL"),
            self.count("MOVED"),
            self.count("DIFFERENT"),
            names("DIFFERENT")
        );
        let _ = writeln!(
            o,
            "                 {} may differ (in a register or stack slot that may be dead){}",
            self.count("MAY-DIFFER"),
            names("MAY-DIFFER")
        );
        let _ = writeln!(
            o,
            "                 {} bounded, {} inconclusive, {} unsupported, {} added{}, {} removed{}",
            self.count("BOUNDED"),
            self.count("INCONCLUSIVE"),
            self.count("UNSUPPORTED"),
            self.count("ADDED"),
            names("ADDED"),
            self.count("REMOVED"),
            names("REMOVED")
        );
        let _ = writeln!(
            o,
            "data objects:    {} compared, {} differ, {} added, {} removed",
            self.data_checked,
            self.data.len(),
            self.data_added.len(),
            self.data_removed.len()
        );
        let _ = writeln!(
            o,
            "mode:            {}",
            if self.with_source {
                "three-way (both images against the source, then against each other)"
            } else {
                "machine code against machine code, no source"
            }
        );
        let _ = writeln!(o, "assumptions:");
        for (name, on, what) in self.assume.list() {
            let _ = writeln!(o, "  {} {name:<10} {what}", if on { "[x]" } else { "[ ]" });
        }
        for what in MODEL_ASSUMPTIONS {
            let _ = writeln!(o, "  [x] {:<10} {what}", "(model)");
        }
        let _ = writeln!(
            o,
            "verdict:         {}",
            if self.differs() {
                "DIFFERENT - the two images do not behave the same"
            } else if self.may_differ() {
                "MAY DIFFER - the images differ in registers or stack slots that nothing shows to be dead"
            } else if self
                .funcs
                .iter()
                .all(|f| f.is_equivalent() || matches!(f.verdict, Verdict::Added | Verdict::Removed))
            {
                "EQUIVALENT - every function both images define is proved equivalent"
            } else {
                "no difference proved"
            }
        );
        o
    }

    pub fn json(&self, old: &str, new: &str) -> String {
        let mut o = String::new();
        let _ = writeln!(o, "{{");
        let _ = writeln!(o, "  \"type\": \"compare\",");
        let _ = writeln!(o, "  \"old\": {},", json_str(old));
        let _ = writeln!(o, "  \"new\": {},", json_str(new));
        let _ = writeln!(o, "  \"with_source\": {},", self.with_source);
        let _ = writeln!(o, "  \"different\": {},", self.differs());
        let _ = writeln!(o, "  \"may_differ\": {},", self.may_differ());
        let _ = writeln!(o, "  \"assumptions\": {{");
        let l = self.assume.list();
        for (i, (name, on, _)) in l.iter().enumerate() {
            let _ = writeln!(
                o,
                "    {}: {on}{}",
                json_str(name),
                if i + 1 < l.len() { "," } else { "" }
            );
        }
        let _ = writeln!(o, "  }},");
        let list = |v: Vec<String>| format!("[{}]", v.join(", "));
        let _ = writeln!(
            o,
            "  \"model_assumptions\": {},",
            list(MODEL_ASSUMPTIONS.iter().map(|s| json_str(s)).collect())
        );
        let _ = writeln!(o, "  \"functions\": [");
        for (i, f) in self.funcs.iter().enumerate() {
            let at = |x: Option<(u32, u32)>| match x {
                Some((a, s)) => format!("{{\"addr\": {a}, \"size\": {s}}}"),
                None => "null".into(),
            };
            let reason = match &f.verdict {
                Verdict::MayDiffer(s)
                | Verdict::Different(s)
                | Verdict::Bounded(s)
                | Verdict::Inconclusive(s)
                | Verdict::Unsupported(s) => json_str(s),
                _ => "null".into(),
            };
            let _ = writeln!(
                o,
                "    {{\"name\": {}, \"status\": {}, \"reason\": {reason}, \"old\": {}, \"new\": {}, \"same_code\": {}, \"inlined\": {}, \"conditions\": {}, \"modulo\": {}, \"source\": {}, \"explanation\": {}, \"paths\": {}, \"millis\": {}}}{}",
                json_str(&f.name),
                json_str(f.label()),
                at(f.old),
                at(f.new),
                f.same_code,
                f.inlined,
                list(f.conditions.iter().map(|s| json_str(s)).collect()),
                list(
                    f.modulo
                        .iter()
                        .map(|(n, s)| format!("{{\"name\": {}, \"status\": {}}}", json_str(n), json_str(s)))
                        .collect()
                ),
                f.via_source.as_ref().map_or("null".into(), |s| json_str(s)),
                f.explanation.as_ref().map_or("null".into(), |s| json_str(s)),
                f.paths,
                f.millis,
                if i + 1 < self.funcs.len() { "," } else { "" }
            );
        }
        let _ = writeln!(o, "  ],");
        let _ = writeln!(
            o,
            "  \"data\": {{\"compared\": {}, \"different\": {}, \"added\": {}, \"removed\": {}}},",
            self.data_checked,
            list(
                self.data
                    .iter()
                    .map(|(n, w)| format!("{{\"name\": {}, \"what\": {}}}", json_str(n), json_str(w)))
                    .collect()
            ),
            list(self.data_added.iter().map(|s| json_str(s)).collect()),
            list(self.data_removed.iter().map(|s| json_str(s)).collect()),
        );
        let _ = writeln!(o, "  \"summary\": {{");
        let labels = [
            "IDENTICAL",
            "MOVED",
            "EQUIVALENT",
            "MAY-DIFFER",
            "DIFFERENT",
            "BOUNDED",
            "INCONCLUSIVE",
            "UNSUPPORTED",
            "ADDED",
            "REMOVED",
        ];
        for (i, l) in labels.iter().enumerate() {
            let _ = writeln!(
                o,
                "    {}: {}{}",
                json_str(l),
                self.count(l),
                if i + 1 < labels.len() { "," } else { "" }
            );
        }
        let _ = writeln!(o, "  }}");
        let _ = writeln!(o, "}}");
        o
    }
}

fn json_str(s: &str) -> String {
    let mut o = String::with_capacity(s.len() + 2);
    o.push('"');
    for c in s.chars() {
        match c {
            '"' => o.push_str("\\\""),
            '\\' => o.push_str("\\\\"),
            '\n' => o.push_str("\\n"),
            '\r' => o.push_str("\\r"),
            '\t' => o.push_str("\\t"),
            c if (c as u32) < 0x20 => {
                let _ = write!(o, "\\u{:04x}", c as u32);
            }
            c => o.push(c),
        }
    }
    o.push('"');
    o
}

// ----- address correspondence -----------------------------------------------------------

/// A data object of the new image.
#[derive(Clone, Debug)]
struct ObjMap {
    start: u32,
    size: u32,
    /// Address of the object of the same name in the old image.
    to: Option<u32>,
    /// Accesses are redirected to the old image's object (writable data, or read-only data
    /// with the same contents); otherwise the object lives in the new image's own window.
    direct: bool,
    /// A pointer into the object is the same value as a pointer into the old image's object:
    /// writable data, or read-only data with the same contents up to pointers.
    same: bool,
}

/// How addresses of the new image translate into the address space of the old one.
#[derive(Debug, Default)]
struct Layout {
    objs: Vec<ObjMap>,
    /// Fake addresses of undefined symbols: (new, old).
    ext: Vec<(u32, u32)>,
    /// Segments of the new image: (address, size, writable).
    segs: Vec<(u32, u32, bool)>,
    /// Offset of the window that holds what only the new image has.
    delta: u32,
    /// Read-only memory in the common address space: (address, size).
    rom: Vec<(u32, u32)>,
}

/// Most values a pointer read from a constant table may take for it to be followed.
const MAX_TABLE_VALUES: usize = 32;

/// Every value `t` can take on the current path, if there are few.
fn enumerate(ctx: &mut Ctx, t: T, max: usize) -> Option<Vec<u32>> {
    if let Some(k) = ctx.tm.as_const(t) {
        return Some(vec![k as u32]);
    }
    let mut values: Vec<u32> = Vec::new();
    let mut known = ctx.tm.fals();
    loop {
        match ctx.check(known) {
            Ok(()) => break,
            Err(Some(env)) => {
                let v = ctx.tm.eval(t, &env, &mut Default::default());
                if values.contains(&(v as u32)) || values.len() >= max {
                    return None;
                }
                values.push(v as u32);
                let k = ctx.tm.konst(32, v);
                let e = ctx.tm.eq(t, k);
                known = ctx.tm.or(known, e);
            }
            Err(None) => return None,
        }
    }
    // A model need not say anything about a term the question did not mention: keep the
    // values the path allows.
    values.retain(|&v| {
        let k = ctx.tm.konst(32, v as u64);
        let ne = ctx.tm.ne(t, k);
        !ctx.implied(ne)
    });
    values.sort_unstable();
    Some(values)
}

/// An address with a symbolic part and a constant part below this is a pointer plus a field
/// offset, not an indexed object, even if an image is loaded at address zero.
const SMALL_OFFSET: u32 = 0x1000;

impl Layout {
    /// Where an access of the new image at constant address `k` goes.
    fn access(&self, k: u32) -> Option<u32> {
        for &(b, a) in &self.ext {
            if k.wrapping_sub(b) < 16 {
                return Some(a.wrapping_add(k - b));
            }
        }
        if let Some(o) = self.objs.iter().find(|o| k.wrapping_sub(o.start) < o.size) {
            return Some(match o.to {
                Some(a) if o.direct => a.wrapping_add(k - o.start),
                _ => k.wrapping_add(self.delta),
            });
        }
        let seg = self.segs.iter().find(|s| k.wrapping_sub(s.0) < s.1)?;
        // Writable memory no symbol names (a heap, a stack area) is taken to be laid out alike.
        Some(if seg.2 { k } else { k.wrapping_add(self.delta) })
    }

    /// The old image's address for a pointer value of the new image into a named object.
    fn value(&self, k: u32) -> Option<u32> {
        for &(b, a) in &self.ext {
            if k.wrapping_sub(b) < 16 {
                return Some(a.wrapping_add(k - b));
            }
        }
        let o = self.objs.iter().find(|o| k.wrapping_sub(o.start) < o.size)?;
        o.to.filter(|_| o.same).map(|a| a.wrapping_add(k - o.start))
    }

    fn translate(&self, ctx: &mut Ctx, addr: T) -> T {
        if ctx.region(addr).is_some() {
            return addr;
        }
        if let Node::Ite(c, x, y) = *ctx.tm.node(addr) {
            let (x, y) = (self.translate(ctx, x), self.translate(ctx, y));
            return ctx.tm.ite(c, x, y);
        }
        let (ts, k) = ctx.tm.linear(addr);
        let k = k as u32;
        if ts.is_empty() || k >= SMALL_OFFSET {
            match self.access(k) {
                Some(n) if n != k => return ctx.tm.add_const(addr, n.wrapping_sub(k) as u64),
                Some(_) => return addr,
                None => {}
            }
        }
        // A pointer read from a constant table of the new image: one of a few addresses of
        // the new image, each translated on its own.
        if ts.is_empty() || !self.reads_rom(ctx, addr) {
            return addr;
        }
        let Some(values) = enumerate(ctx, addr, MAX_TABLE_VALUES) else {
            return addr;
        };
        let to = |k: u32| self.access(k).unwrap_or(k);
        let Some((&last, rest)) = values.split_last() else {
            return addr;
        };
        let mut out = ctx.tm.konst(32, to(last) as u64);
        for &k in rest.iter().rev() {
            let (kt, nt) = (ctx.tm.konst(32, k as u64), ctx.tm.konst(32, to(k) as u64));
            let c = ctx.tm.eq(addr, kt);
            out = ctx.tm.ite(c, nt, out);
        }
        out
    }

    /// Does the value come out of read-only memory (a load whose address has its constant
    /// part there)?
    fn reads_rom(&self, ctx: &Ctx, t: T) -> bool {
        let mut seen = HashSet::new();
        let mut stack = vec![t];
        while let Some(x) = stack.pop() {
            if !seen.insert(x) {
                continue;
            }
            if seen.len() > 4000 {
                return false;
            }
            let n = ctx.tm.node(x);
            if let Node::Load(epoch, a) = n
                && *epoch < crate::sym::UNINIT_EPOCH
            {
                let k = ctx.tm.linear(*a).1 as u32;
                if self.rom.iter().any(|r| k.wrapping_sub(r.0) < r.1) {
                    return true;
                }
            }
            stack.extend(crate::bv::Prover::children_of(n));
        }
        false
    }
}

/// A named thing of an image: a data object or a function.
#[derive(Clone, Debug)]
struct Named {
    name: String,
    file: Option<String>,
    addr: u32,
    size: u32,
    writable: bool,
}

/// Named data objects of an image.
fn objects(img: &Image) -> Vec<Named> {
    let mut syms: Vec<&crate::image::Symbol> = img
        .symbols
        .iter()
        .filter(|s| s.kind != SymKind::Func && !s.name.is_empty() && !s.name.starts_with('$'))
        .collect();
    syms.sort_by_key(|s| s.addr);
    let mut out = Vec::new();
    for (i, s) in syms.iter().enumerate() {
        let Some(seg) = img.segment_at(s.addr) else { continue };
        let end = seg.addr + seg.data.len() as u32;
        let size = if s.size > 0 {
            s.size.min(end - s.addr)
        } else if s.kind == SymKind::Object {
            // No size recorded (a symbol table from `nm`): up to the next symbol.
            syms[i + 1..]
                .iter()
                .map(|n| n.addr)
                .find(|&a| a > s.addr)
                .unwrap_or(end)
                .min(end)
                - s.addr
        } else {
            continue;
        };
        if size > 0 {
            out.push(Named {
                name: s.name.clone(),
                file: s.file.clone(),
                addr: s.addr,
                size,
                writable: seg.writable,
            });
        }
    }
    out
}

/// Pair the named things of the two images: (name to show, index in `a`, index in `b`).
/// A name that occurs once on each side is a pair.  Several things of the same name (statics
/// of different files) are told apart by the file they come from when the image records it,
/// and otherwise paired in address order if there are as many on each side.
fn pair_up(a: &[Named], b: &[Named]) -> Vec<(String, usize, usize)> {
    let group = |l: &[Named]| {
        let mut m: BTreeMap<String, Vec<usize>> = BTreeMap::new();
        for (i, x) in l.iter().enumerate() {
            m.entry(x.name.clone()).or_default().push(i);
        }
        for v in m.values_mut() {
            v.sort_by_key(|&i| l[i].addr);
        }
        m
    };
    let (ga, gb) = (group(a), group(b));
    let mut out = Vec::new();
    for (name, va) in &ga {
        let Some(vb) = gb.get(name) else { continue };
        if va.len() == 1 && vb.len() == 1 {
            out.push((name.clone(), va[0], vb[0]));
            continue;
        }
        let base = |f: &Option<String>| f.as_ref().map(|f| f.rsplit('/').next().unwrap_or(f).to_string());
        let once =
            |l: &[Named], v: &[usize], f: &Option<String>| v.iter().filter(|&&i| base(&l[i].file) == *f).count() == 1;
        let (mut ra, mut rb) = (va.clone(), vb.clone());
        for &i in va {
            let f = base(&a[i].file);
            if f.is_some()
                && once(a, va, &f)
                && once(b, vb, &f)
                && let Some(&j) = vb.iter().find(|&&j| base(&b[j].file) == f)
            {
                out.push((format!("{name} ({})", f.unwrap()), i, j));
                ra.retain(|&x| x != i);
                rb.retain(|&x| x != j);
            }
        }
        if ra.len() == rb.len() {
            for (n, (&i, &j)) in ra.iter().zip(&rb).enumerate() {
                out.push((format!("{name} (#{})", n + 1), i, j));
            }
        }
    }
    out
}

/// Code the compiler made out of parts of functions: no public interface, always followed.
fn is_fragment(name: &str) -> bool {
    name.starts_with("OUTLINED_FUNCTION_")
        || [".constprop.", ".isra.", ".part.", ".cold", ".lto_priv.", ".localalias"]
            .iter()
            .any(|p| name.contains(p))
}

/// The NUL-terminated constant at a read-only address.
fn rom_str(img: &Image, k: u32) -> Option<&[u8]> {
    let s = img.segment_at(k).filter(|s| !s.writable)?;
    let rest = &s.data[(k - s.addr) as usize..];
    let n = rest.iter().position(|&c| c == 0)?;
    Some(&rest[..n])
}

/// Do constants `ka` (old image) and `kb` (new image) designate the same thing?
fn same_const(a: &Image, b: &Image, layout: &Layout, ka: u32, kb: u32) -> bool {
    if let Some(m) = layout.value(kb) {
        return m == ka;
    }
    if let Some(fb) = b.func_at(kb & !1) {
        return (ka ^ kb) & 1 == 0 && a.func_at(ka & !1).is_some_and(|fa| fa.name == fb.name);
    }
    // A pointer into an object of the new image that has no equal in the old one.
    if ka != kb
        && layout.objs.iter().any(|o| kb.wrapping_sub(o.start) < o.size)
        && b.segment_at(kb).is_some_and(|s| s.writable)
    {
        return false;
    }
    // Constants in read-only memory are the same if they hold the same string.
    match (rom_str(a, ka), rom_str(b, kb)) {
        (Some(x), Some(y)) => x == y,
        (None, None) => ka == kb,
        _ => false,
    }
}

/// First place where the contents of two objects differ, words that are pointers to the same
/// thing being equal: (offset, old, new).
fn first_difference(a: &Image, b: &Image, layout: &Layout, x: &[u8], y: &[u8]) -> Option<(usize, u32, u32)> {
    let mut off = 0usize;
    while off < x.len().min(y.len()) {
        let n = if off.is_multiple_of(4) && off + 4 <= x.len() {
            4
        } else {
            1
        };
        let (xs, ys) = (&x[off..off + n], &y[off..off + n]);
        if xs != ys {
            let word = |s: &[u8]| s.iter().rev().fold(0u32, |v, &b| (v << 8) | b as u32);
            let (wa, wb) = (word(xs), word(ys));
            let pointers = n == 4
                && (a.segment_at(wa & !1).is_some() || a.externals.contains_key(&(wa & !1)))
                && same_const(a, b, layout, wa, wb);
            if !pointers {
                return Some((off, wa, wb));
            }
        }
        off += n;
    }
    None
}

struct Space<'a> {
    a: &'a Image,
    b: &'a Image,
    /// Data as each machine reads it, in the common address space.
    da: Arc<Image>,
    db: Arc<Image>,
    layout: Arc<Layout>,
    /// Functions both images define: name -> entry in each.
    paired: BTreeMap<String, [u32; 2]>,
    /// Entry -> name of the paired functions of each image.
    fn_key: [HashMap<u32, String>; 2],
    /// Data objects both images define: (name, old, new).
    obj_pairs: Vec<(String, Named, Named)>,
    /// Names each image leaves undefined.
    ext_names: [HashSet<String>; 2],
    mmio: Vec<(u32, u32)>,
    /// Lowest and highest address of the segments of both images.
    span: (u32, u32),
    /// With `Options::explain`: the reported differences (message, detail).
    explain: bool,
    notes: std::sync::Mutex<Vec<(String, String)>>,
}

fn funcs_of(img: &Image) -> Vec<Named> {
    let mut v: Vec<Named> = img
        .symbols
        .iter()
        .filter(|s| s.kind == SymKind::Func && !s.name.is_empty() && !is_fragment(&s.name))
        .filter(|s| img.segment_at(s.addr).is_some_and(|g| g.exec))
        .map(|s| Named {
            name: s.name.clone(),
            file: s.file.clone(),
            addr: s.addr,
            size: s.size,
            writable: false,
        })
        .collect();
    v.sort_by(|x, y| (&x.name, x.addr).cmp(&(&y.name, y.addr)));
    v.dedup_by(|x, y| x.name == y.name && x.addr == y.addr);
    v
}

impl<'a> Space<'a> {
    fn new(a: &'a Image, b: &'a Image, mmio: &[(u32, u32)]) -> Space<'a> {
        let (oa, ob) = (objects(a), objects(b));
        // Labels the compiler numbers are not names: such constants compare by contents.
        let obj_pairs: Vec<(String, Named, Named)> = pair_up(&oa, &ob)
            .into_iter()
            .filter(|p| !p.0.starts_with(".L"))
            .map(|(n, i, j)| (n, oa[i].clone(), ob[j].clone()))
            .collect();
        let mut layout = Layout::default();
        for o in &ob {
            let peer = obj_pairs
                .iter()
                .find(|p| p.2.addr == o.addr && p.2.name == o.name)
                .map(|p| &p.1);
            let same = peer.is_some_and(|p| p.size == o.size && a.read(p.addr, p.size) == b.read(o.addr, o.size));
            let direct = peer.is_some_and(|p| (o.writable && p.writable) || (!o.writable && !p.writable && same));
            layout.objs.push(ObjMap {
                start: o.addr,
                size: o.size,
                to: peer.map(|p| p.addr),
                direct,
                same: direct,
            });
        }
        // Smaller objects first, so that a symbol covering a whole area does not hide them.
        layout.objs.sort_by_key(|o| (o.size, o.start));
        // Read-only objects that differ only in pointers to the same things are the same.
        for _ in 0..4 {
            let more: Vec<usize> = (0..layout.objs.len())
                .filter(|&i| {
                    let o = &layout.objs[i];
                    !o.same
                        && o.to
                            .is_some_and(|to| match (a.read(to, o.size), b.read(o.start, o.size)) {
                                (Some(x), Some(y)) => {
                                    oa.iter().any(|p| p.addr == to && p.size == o.size)
                                        && first_difference(a, b, &layout, x, y).is_none()
                                }
                                _ => false,
                            })
                })
                .collect();
            if more.is_empty() {
                break;
            }
            for i in more {
                layout.objs[i].same = true;
            }
        }
        let ext_a: HashMap<&str, u32> = a.externals.iter().map(|(a, n)| (n.as_str(), *a)).collect();
        for (addr, name) in &b.externals {
            if let Some(&to) = ext_a.get(name.as_str()) {
                layout.ext.push((*addr, to));
            }
        }
        layout.ext.sort();
        layout.segs = b
            .segments
            .iter()
            .map(|s| (s.addr, s.data.len() as u32, s.writable))
            .collect();
        // Initialised data as stored in the load image (startup code copies it to RAM).
        let stored = |img: &Image| -> Vec<Segment> {
            img.segments
                .iter()
                .filter_map(|s| {
                    let at = s.load_addr?;
                    let free = (0..s.data.len() as u32)
                        .step_by(4)
                        .all(|o| img.segment_at(at + o).is_none());
                    free.then(|| Segment {
                        name: format!("{} (load image)", s.name),
                        addr: at,
                        data: s.data.clone(),
                        writable: false,
                        exec: false,
                        load_addr: None,
                    })
                })
                .collect()
        };
        let (stored_a, stored_b) = (stored(a), stored(b));
        layout
            .segs
            .extend(stored_b.iter().map(|s| (s.addr, s.data.len() as u32, false)));
        // A window for what only the new image has: clear of everything either image uses.
        let mut used: Vec<(u32, u32)> = mmio.to_vec();
        for img in [a, b] {
            used.extend(
                img.segments
                    .iter()
                    .map(|s| (s.addr, s.addr + (s.data.len() as u32).saturating_sub(1))),
            );
            used.extend(img.externals.keys().map(|&e| (e, e + 15)));
        }
        used.extend(
            stored_a
                .iter()
                .chain(&stored_b)
                .map(|s| (s.addr, s.addr + (s.data.len() as u32).saturating_sub(1))),
        );
        layout.delta = (1..256u32)
            .map(|d| d << 24)
            .find(|&d| {
                b.segments.iter().all(|s| {
                    let lo = s.addr.wrapping_add(d);
                    let hi = lo.wrapping_add((s.data.len() as u32).saturating_sub(1));
                    hi >= lo && used.iter().all(|&(ulo, uhi)| hi < ulo || lo > uhi)
                })
            })
            .unwrap_or(0x7000_0000);
        let clone = |s: &Segment, shift: u32| Segment {
            name: s.name.clone(),
            addr: s.addr.wrapping_add(shift),
            data: s.data.clone(),
            writable: s.writable,
            exec: s.exec,
            load_addr: None,
        };
        let da = Image {
            segments: a.segments.iter().chain(&stored_a).map(|s| clone(s, 0)).collect(),
            ..Default::default()
        };
        let mut db = Image {
            segments: da.segments.iter().map(|s| clone(s, 0)).collect(),
            ..Default::default()
        };
        db.segments
            .extend(b.segments.iter().chain(&stored_b).map(|s| clone(s, layout.delta)));
        layout.rom = db
            .segments
            .iter()
            .filter(|s| !s.writable)
            .map(|s| (s.addr, s.data.len() as u32))
            .collect();
        // Functions.
        let (fa, fb) = (funcs_of(a), funcs_of(b));
        let mut paired = BTreeMap::new();
        let mut fn_key = [HashMap::new(), HashMap::new()];
        for (name, i, j) in pair_up(&fa, &fb) {
            fn_key[0].insert(fa[i].addr, name.clone());
            fn_key[1].insert(fb[j].addr, name.clone());
            paired.insert(name, [fa[i].addr, fb[j].addr]);
        }
        Space {
            a,
            b,
            da: Arc::new(da),
            db: Arc::new(db),
            layout: Arc::new(layout),
            paired,
            fn_key,
            obj_pairs,
            ext_names: [
                a.externals.values().cloned().collect(),
                b.externals.values().cloned().collect(),
            ],
            mmio: mmio.to_vec(),
            span: a.segments.iter().chain(&b.segments).fold((u32::MAX, 0), |(lo, hi), s| {
                (lo.min(s.addr), hi.max(s.addr + s.data.len() as u32))
            }),
            explain: false,
            notes: Default::default(),
        }
    }

    fn image(&self, side: usize) -> &'a Image {
        if side == 0 { self.a } else { self.b }
    }

    fn data(&self, side: usize) -> &Arc<Image> {
        if side == 0 { &self.da } else { &self.db }
    }

    fn translate(&self, side: usize, ctx: &mut Ctx, addr: T) -> T {
        if side == 0 {
            addr
        } else {
            self.layout.translate(ctx, addr)
        }
    }

    /// Does the constant lie inside one of the images?
    fn is_address(&self, k: u32) -> bool {
        self.span.0 <= k && k <= self.span.1 && (self.a.segment_at(k).is_some() || self.b.segment_at(k).is_some())
    }

    fn same_const(&self, ka: u32, kb: u32) -> bool {
        same_const(self.a, self.b, &self.layout, ka, kb)
    }

    /// Are the two values the same without further proof: the same term, or pointers to the
    /// same thing in their respective images?
    fn corr(&self, ctx: &Ctx, va: T, vb: T) -> bool {
        if va == vb {
            // The same number is not the same pointer if the images hold different things there.
            return match ctx.tm.as_const(va) {
                Some(k) if ctx.tm.width(va) == 32 && self.is_address(k as u32) => self.same_const(k as u32, k as u32),
                _ => true,
            };
        }
        if ctx.tm.width(va) != 32 || ctx.tm.width(vb) != 32 {
            return false;
        }
        if let (Node::Ite(c1, x1, y1), Node::Ite(c2, x2, y2)) = (ctx.tm.node(va), ctx.tm.node(vb))
            && c1 == c2
        {
            return self.corr(ctx, *x1, *x2) && self.corr(ctx, *y1, *y2);
        }
        let ((ta, ka), (tb, kb)) = (ctx.tm.linear(va), ctx.tm.linear(vb));
        if ta != tb {
            return false;
        }
        let (ka, kb) = (ka as u32, kb as u32);
        if !ta.is_empty() && (ka < SMALL_OFFSET || kb < SMALL_OFFSET) {
            return ka == kb;
        }
        self.same_const(ka, kb)
    }
}

// ----- comparison of one function ---------------------------------------------------------

const NORETURN: &[&str] = &[
    "abort",
    "exit",
    "_exit",
    "_Exit",
    "__assert_fail",
    "__assert_func",
    "__builtin_abort",
];

/// Argument words considered at a call: r0-r3 and four words of stack.
const ARG_WORDS: usize = 8;

struct Job<'a> {
    sp: &'a Space<'a>,
    entry: [u32; 2],
    regs: [[T; 16]; 2],
    lr0: T,
    stack: Vec<(u32, T)>,
    /// Follow every call into the code of the image instead of matching calls one to one.
    inline: bool,
    /// Compare the stack at and above the entry stack pointer (assumption `caller-stack`).
    caller_stack: bool,
}

/// What the paths of one function establish beyond the verdict.
#[derive(Default)]
struct Facts {
    /// Functions of the images called as one shared event.
    calls: BTreeSet<String>,
    saw_internal: RefCell<bool>,
    ret0_diff: Option<String>,
    ret1_diff: bool,
    /// Argument words that differ at a call: callee -> mask of words it must not read, and
    /// the first such difference.
    needs: BTreeMap<String, (u8, BTreeMap<u8, String>)>,
    /// Argument words some call leaves holding garbage: the callee does not read them.
    dead: BTreeSet<(String, u8)>,
    /// A frame slot a callee can reach holds different values.
    slot_diff: Option<String>,
    /// Input words (bit i: word i) the observable behaviour depends on: always, through the
    /// result in r0, through r1.
    in_always: u8,
    in_r0: u8,
    in_r1: u8,
    /// Input words passed on in word `.1` of a call to `.0`.
    in_arg: BTreeSet<(String, u8, u8)>,
    /// Results of calls (symbol ids) the behaviour depends on, likewise.
    ret_always: BTreeSet<u32>,
    ret_r0: BTreeSet<u32>,
    ret_r1: BTreeSet<u32>,
    ret_arg: BTreeSet<(String, u8, u32)>,
    /// Result symbols: id -> (callee, is the high word).
    ret_syms: HashMap<u32, (String, bool)>,
    inputs: HashMap<T, u8>,
    memo: HashMap<T, (u8, Arc<BTreeSet<u32>>)>,
}

impl Facts {
    /// The input words and call results a term depends on.
    fn deps(&mut self, ctx: &Ctx, t: T) -> (u8, Arc<BTreeSet<u32>>) {
        if let Some(d) = self.memo.get(&t) {
            return d.clone();
        }
        let d = match ctx.tm.node(t) {
            Node::Sym(id) => {
                let mut s = BTreeSet::new();
                if self.ret_syms.contains_key(id) {
                    s.insert(*id);
                }
                (self.inputs.get(&t).copied().unwrap_or(0), Arc::new(s))
            }
            n => {
                let mut mask = 0u8;
                let mut set: Option<Arc<BTreeSet<u32>>> = None;
                for c in crate::bv::Prover::children_of(n) {
                    let (m, s) = self.deps(ctx, c);
                    mask |= m;
                    if !s.is_empty() {
                        set = Some(match set {
                            None => s,
                            Some(old) if s.is_subset(&old) => old,
                            Some(old) => Arc::new(old.union(&s).copied().collect()),
                        });
                    }
                }
                (mask, set.unwrap_or_default())
            }
        };
        self.memo.insert(t, d.clone());
        d
    }

    fn always(&mut self, ctx: &Ctx, t: T) {
        let (m, s) = self.deps(ctx, t);
        self.in_always |= m;
        self.ret_always.extend(s.iter().copied());
    }
}

fn witness(ctx: &Ctx, env: &Env) -> String {
    let mut items: Vec<(String, u64)> = env
        .syms
        .iter()
        .map(|(id, v)| (ctx.tm.sym_name(*id).to_string(), *v))
        .filter(|(n, _)| {
            let b = n.as_bytes();
            (b.len() <= 3 && b[0] == b'r' && b[1..].iter().all(u8::is_ascii_digit))
                || n.starts_with("stk")
                || n.starts_with("ret")
                || n.starts_with("io")
        })
        .collect();
    items.sort_by(|x, y| (x.0.len(), &x.0).cmp(&(y.0.len(), &y.0)));
    let mut parts: Vec<String> = items.iter().map(|(n, v)| format!("{n}={v:#x}")).collect();
    let mut mem: Vec<(u64, u8)> = env
        .mem
        .iter()
        .filter(|((m, _), _)| *m < 0x8000_0000)
        .map(|((_, a), v)| (*a, *v))
        .collect();
    mem.sort();
    for (a, v) in mem.iter().take(8) {
        parts.push(format!("mem[{a:#x}]={v:#04x}"));
    }
    if parts.is_empty() {
        "any input".into()
    } else {
        parts.join(" ")
    }
}

/// Are two observable values the same?  None if they are; otherwise how they differ, with
/// an input that tells them apart.
fn difference(ctx: &mut Ctx, sp: &Space, va: T, vb: T, what: &str) -> R<Option<String>> {
    if sp.corr(ctx, va, vb) {
        return Ok(None);
    }
    if ctx.tm.width(va) != ctx.tm.width(vb) {
        return Ok(Some("different sizes".into()));
    }
    // Pointers read from constant tables: each value the new one can take must designate
    // what the old one then designates.
    if ctx.tm.as_const(vb).is_none()
        && sp.layout.reads_rom(ctx, vb)
        && let Some(values) = enumerate(ctx, vb, MAX_TABLE_VALUES)
    {
        let mut all = true;
        for k in values {
            let kt = ctx.tm.konst(32, k as u64);
            let c = ctx.tm.eq(vb, kt);
            ctx.pc.push(c);
            let ka = enumerate(ctx, va, 2).filter(|v| v.len() == 1).map(|v| v[0]);
            ctx.pc.pop();
            match ka {
                Some(ka) if sp.same_const(ka, k) => {}
                Some(ka) if sp.is_address(ka) || sp.is_address(k) => {
                    return Ok(Some(format!(
                        "old gives {ka:#x}, new gives {k:#x}, which do not designate the same thing in the two images"
                    )));
                }
                _ => {
                    all = false;
                    break;
                }
            }
        }
        if all {
            return Ok(None);
        }
    }
    if let (Some(x), Some(y)) = (ctx.tm.as_const(va), ctx.tm.as_const(vb))
        && (sp.is_address(x as u32) || sp.is_address(y as u32))
    {
        return Ok(Some(format!(
            "old gives {x:#x}, new gives {y:#x}, which do not designate the same thing in the two images"
        )));
    }
    let e = ctx.tm.eq(va, vb);
    match ctx.check(e) {
        Ok(()) => Ok(None),
        Err(Some(env)) => {
            let mut memo = Default::default();
            let (x, y) = (ctx.tm.eval(va, &env, &mut memo), ctx.tm.eval(vb, &env, &mut memo));
            let how = format!("old gives {x:#x}, new gives {y:#x} for {}", witness(ctx, &env));
            if sp.explain {
                let note = explain_terms(ctx, sp, va, vb, &env);
                sp.notes
                    .lock()
                    .unwrap_or_else(|e| e.into_inner())
                    .push((format!("{what}: {how}"), note));
            }
            Ok(Some(how))
        }
        Err(None) => Err(Stop::Inconclusive(format!("{what}: prover gave up"))),
    }
}

/// The two values that differ as expressions over the inputs, with their values under the
/// counterexample and the places where the expressions part.
fn explain_terms(ctx: &Ctx, sp: &Space, va: T, vb: T, env: &Env) -> String {
    use crate::explain::{Dag, Names, Printer, Style, show_val};
    let (dag, ids) = Dag::from_terms(&ctx.tm, &[va, vb], Some(env));
    let names = Names::new(sp.a, None);
    let pr = Printer::new(&dag, &names, &ids, Style::default());
    let val = |n: u32| match dag.val(n) {
        Some(v) => format!("  = {}", show_val(v, dag.width(n))),
        None => String::new(),
    };
    let mut o = String::new();
    let _ = writeln!(o, "old: {}{}", pr.expr(ids[0]), val(ids[0]));
    let _ = writeln!(o, "new: {}{}", pr.expr(ids[1]), val(ids[1]));
    let d = pr.diff(ids[0], ids[1]);
    if !(d.holes.len() == 1 && d.skeleton == d.holes[0].label) {
        let _ = writeln!(o, "differ in: {}", d.skeleton);
        for h in &d.holes {
            let v = |v: Option<u64>| v.map_or(String::new(), |v| format!("  = {}", show_val(v, h.width)));
            let _ = writeln!(o, "  {} old: {}{}", h.label, h.source, v(h.source_val));
            let _ = writeln!(o, "  {} new: {}{}", h.label, h.binary, v(h.binary_val));
        }
    }
    let lets: Vec<_> = pr.lets().into_iter().filter(|l| o.contains(&l.name)).collect();
    if !lets.is_empty() {
        let _ = writeln!(o, "where:");
        for l in lets {
            let v = l
                .value
                .map_or(String::new(), |v| format!("  = {}", show_val(v, l.width)));
            let _ = writeln!(o, "  {} = {}{v}", l.name, l.text);
        }
    }
    o
}

/// Prove two observable values equal, or report the input that tells them apart.
fn prove_same(ctx: &mut Ctx, sp: &Space, va: T, vb: T, what: &str) -> R<()> {
    match difference(ctx, sp, va, vb, what)? {
        None => Ok(()),
        Some(how) => Err(Stop::Mismatch(format!("{what}: {how}"), None)),
    }
}

fn classify(job: &Job, side: usize, facts: &Facts, addr: u32) -> Callee {
    let (img, other) = (job.sp.image(side), 1 - side);
    if let Some(name) = img.externals.get(&addr) {
        return Callee::External(name.clone());
    }
    let Some(s) = img.func_at(addr) else {
        return Callee::Internal;
    };
    if is_fragment(&s.name) {
        return Callee::Internal;
    }
    // A function the other image leaves undefined is a call there: it is one here.
    if job.sp.ext_names[other].contains(&s.name) {
        return Callee::External(s.name.clone());
    }
    if let Some(key) = job.sp.fn_key[side].get(&addr) {
        *facts.saw_internal.borrow_mut() = true;
        if !job.inline {
            return Callee::External(key.clone());
        }
    }
    Callee::Internal
}

/// libgcc's Thumb-1 switch dispatchers (see `verify::model_switch_helper`).
fn switch_helper(ctx: &mut Ctx, image: &Image, m: &mut Machine, name: &str, count: &mut usize) -> R<bool> {
    let (esize, signed) = match name {
        "__gnu_thumb1_case_sqi" => (1u32, true),
        "__gnu_thumb1_case_uqi" => (1, false),
        "__gnu_thumb1_case_shi" => (2, true),
        "__gnu_thumb1_case_uhi" => (2, false),
        "__gnu_thumb1_case_si" => (4, true),
        _ => return Ok(false),
    };
    let ret = m.resume_pc();
    let idx = m.regs[0];
    let mut found = None;
    for i in 0..1024u32 {
        let k = ctx.tm.konst(32, i as u64);
        let e = ctx.tm.eq(idx, k);
        if ctx.branch(e)? {
            found = Some(i);
            break;
        }
    }
    let Some(i) = found else {
        return Err(Stop::Unsupported(format!(
            "switch table with more than 1024 entries at {ret:#x}"
        )));
    };
    let base = if esize == 4 { (ret + 3) & !3 } else { ret };
    let eaddr = base + esize * i;
    let Some(bytes) = image.read_const(eaddr, esize) else {
        return Err(Stop::Unsupported(format!(
            "switch table entry outside the image at {eaddr:#x}"
        )));
    };
    let mut v = 0u32;
    for (j, &b) in bytes.iter().enumerate() {
        v |= (b as u32) << (8 * j);
    }
    let target = match (esize, signed) {
        (4, _) => base.wrapping_add(v),
        (1, true) => ret.wrapping_add((v as u8 as i8 as i32 as u32) << 1),
        (2, true) => ret.wrapping_add((v as u16 as i16 as i32 as u32) << 1),
        _ => ret.wrapping_add(v << 1),
    };
    *count += 1;
    m.resume_at(ctx, 1000 + *count, target);
    Ok(true)
}

/// A memory helper with a known length is a plain memory effect (see `verify::model_mem_call`).
fn mem_call(ctx: &mut Ctx, job: &Job, side: usize, m: &mut Machine, name: &str, count: &mut usize) -> bool {
    use crate::c::exec::{MAX_MEM_INLINE, mem_fill};
    let (r0, r1, r2) = (m.regs[0], m.regs[1], m.regs[2]);
    let zero = ctx.tm.konst(32, 0);
    let (dst, arg, len, fill) = match name {
        "memset" => (r0, r1, r2, true),
        "__aeabi_memset" | "__aeabi_memset4" | "__aeabi_memset8" => (r0, r2, r1, true),
        "__aeabi_memclr" | "__aeabi_memclr4" | "__aeabi_memclr8" => (r0, zero, r1, true),
        "memcpy" | "__aeabi_memcpy" | "__aeabi_memcpy4" | "__aeabi_memcpy8" => (r0, r1, r2, false),
        _ => return false,
    };
    let Some(n) = ctx.unique_value(len).filter(|&n| n <= MAX_MEM_INLINE) else {
        return false;
    };
    let n = n as u32;
    let to = job.sp.translate(side, ctx, dst);
    // Peripheral registers are not plain memory.
    let periph = |ctx: &Ctx, t: T| {
        ctx.tm.as_const(t).is_some_and(|a| {
            let (a, end) = (a as u32, (a as u32).wrapping_add(n.max(1) - 1));
            job.sp.mmio.iter().any(|&(lo, hi)| a <= hi && end >= lo)
        })
    };
    if periph(ctx, to) {
        return false;
    }
    if fill {
        let byte = ctx.tm.trunc(arg, 8);
        mem_fill(ctx, &mut m.mem, to, byte, n);
    } else {
        let from = job.sp.translate(side, ctx, arg);
        if periph(ctx, from) {
            return false;
        }
        let data = job.sp.data(side).clone();
        let mut chunks = Vec::new();
        let mut off = 0;
        while off < n {
            let sz = if n - off >= 4 { 4u8 } else { 1 };
            let a = ctx.tm.add_const(from, off as u64);
            let mut init = image_init(&data, m.mem.epoch, None);
            chunks.push((off, sz, ctx.mem_read(&m.mem, a, sz, &mut init)));
            off += sz as u32;
        }
        for (off, sz, v) in chunks {
            let a = ctx.tm.add_const(to, off as u64);
            ctx.mem_write(&mut m.mem, a, sz, v);
        }
    }
    *count += 1;
    let ret = if name.starts_with("__aeabi") { None } else { Some(dst) };
    m.finish_call(ctx, 1000 + *count, ret, None);
    true
}

/// Run one machine up to its next observable exit.
fn run_side(ctx: &mut Ctx, job: &Job, facts: &Facts, side: usize, m: &mut Machine, helpers: &mut usize) -> R<Exit> {
    let image = job.sp.image(side);
    let cl = |addr: u32| classify(job, side, facts, addr);
    let who = if side == 0 { "old image" } else { "new image" };
    loop {
        let e = match m.run(ctx, image, job.lr0, &cl) {
            Ok(e) => e,
            // A machine that breaks the rules on its own: the old code is the reference, so
            // nothing can be said if it does; the new code differs if only it does.
            Err(Stop::Mismatch(why, env)) => {
                let why = format!("{who}: {}", why.replacen("binary ", "", 1));
                return Err(if side == 0 {
                    Stop::Unsupported(why)
                } else {
                    Stop::Mismatch(why, env)
                });
            }
            Err(Stop::Unsupported(why)) => return Err(Stop::Unsupported(format!("{who}: {why}"))),
            Err(e) => return Err(e),
        };
        if let Exit::Call { name } = &e {
            if switch_helper(ctx, image, m, name, helpers)? {
                continue;
            }
            if model_runtime_call(ctx, m, name, helpers) || mem_call(ctx, job, side, m, name, helpers) {
                continue;
            }
        }
        return Ok(e);
    }
}

/// Is `pc`, the return address of a call, past the end of the function that makes the call?
/// The compiler then knew that the callee does not return.
fn last_insn(img: &Image, pc: u32) -> bool {
    let site = pc.wrapping_sub(1);
    img.is_data_in_code(pc)
        || img.symbols.iter().any(|s| {
            s.kind == SymKind::Func && s.size > 0 && site.wrapping_sub(s.addr) < s.size && pc - s.addr >= s.size
        })
}

fn describe(e: &Exit) -> String {
    match e {
        Exit::Return => "returns".into(),
        Exit::Trap => "traps".into(),
        Exit::Call { name } => format!("calls {name}"),
        Exit::Cut(a) => format!("stops at {a:#x}"),
        Exit::Asm { name, .. } => format!("executes `{name}`"),
    }
}

/// The state of the two machines at an observable point.
struct Pair {
    m: [Machine; 2],
    /// Peripheral accesses already compared.
    io_pos: usize,
    /// Lowest frame offset (from the entry stack pointer) of a stack object whose address a
    /// callee holds.
    escaped: Option<i64>,
}

/// Peripheral accesses and caller-visible memory since the last observable point.
fn compare_effects(ctx: &mut Ctx, job: &Job, facts: &mut Facts, p: &mut Pair, what: &str) -> R<()> {
    let sp = job.sp;
    let n = p.m[0].io.len().max(p.m[1].io.len());
    for i in p.io_pos..n {
        let show = |ctx: &Ctx, a: &crate::thumb::exec::VolAccess| {
            format!(
                "{} {} byte(s) at {}",
                if a.write { "writes" } else { "reads" },
                a.size,
                ctx.tm.show(a.addr)
            )
        };
        match (p.m[0].io.get(i).cloned(), p.m[1].io.get(i).cloned()) {
            (Some(x), Some(y)) => {
                if x.write != y.write || x.size != y.size || x.addr != y.addr {
                    return Err(Stop::Mismatch(
                        format!(
                            "peripheral access #{} {what}: old {}, new {}",
                            i + 1,
                            show(ctx, &x),
                            show(ctx, &y)
                        ),
                        None,
                    ));
                }
                if x.write {
                    let at = ctx.tm.show(x.addr);
                    prove_same(
                        ctx,
                        sp,
                        x.val,
                        y.val,
                        &format!("value written to the peripheral register at {at} {what}"),
                    )?;
                    facts.always(ctx, x.val);
                    facts.always(ctx, y.val);
                }
            }
            (Some(x), None) => {
                return Err(Stop::Mismatch(
                    format!("peripheral access {what}: old {}, new does not", show(ctx, &x)),
                    None,
                ));
            }
            (None, Some(y)) => {
                return Err(Stop::Mismatch(
                    format!("peripheral access {what}: new {}, old does not", show(ctx, &y)),
                    None,
                ));
            }
            (None, None) => {}
        }
    }
    p.io_pos = n;
    let mut seen: HashSet<(T, u8)> = HashSet::new();
    let entries: Vec<(T, u8)> = p.m[0]
        .mem
        .world
        .iter()
        .chain(p.m[1].mem.world.iter())
        .map(|w| (w.addr, w.size))
        .collect();
    for (addr, size) in entries {
        if !seen.insert((addr, size)) || ctx.region(addr).is_some() {
            continue;
        }
        let mut ia = image_init(&sp.da, p.m[0].mem.epoch, None);
        let va = ctx.read_world(&p.m[0].mem.world, addr, size, &mut ia);
        let mut ib = image_init(&sp.db, p.m[1].mem.epoch, None);
        let vb = ctx.read_world(&p.m[1].mem.world, addr, size, &mut ib);
        let at = ctx.tm.show(addr);
        if va != vb && (ctx.mentions_private(va) || ctx.mentions_private(vb)) {
            return Err(Stop::Unsupported(format!(
                "{what}: a stack address is stored at {at} (the extent of stack objects is unknown without the source)"
            )));
        }
        prove_same(ctx, sp, va, vb, &format!("{what}: {size}-byte value stored at {at}"))?;
        for t in [addr, va, vb] {
            facts.always(ctx, t);
        }
    }
    Ok(())
}

/// Slots of the frame at or above offset `from` that either machine has written.
fn frame_slots(ctx: &mut Ctx, job: &Job, p: &Pair, from: i64) -> Vec<(T, u8)> {
    let sp0 = job.regs[0][13];
    let mut out: Vec<(T, u8)> = Vec::new();
    for m in &p.m {
        let Some(log) = m.mem.private.get(&sp0) else { continue };
        for w in log {
            let keep = match ctx.tm.const_diff(w.addr, sp0) {
                Some(d) => d as u32 as i32 as i64 + w.size as i64 > from,
                None => true,
            };
            if keep && !out.contains(&(w.addr, w.size)) {
                out.push((w.addr, w.size));
            }
        }
    }
    out
}

/// The stack at and above the entry stack pointer when the function is left: without a
/// signature there is no telling the function's own stack arguments from its caller's frame,
/// so whatever either version stored there has to be the same in both.
fn compare_caller_stack(ctx: &mut Ctx, job: &Job, p: &Pair, what: &str) -> R<()> {
    if !job.caller_stack {
        return Ok(());
    }
    let sp0 = job.regs[0][13];
    for (addr, size) in frame_slots(ctx, job, p, 0) {
        let va = frame_read(ctx, job, p, 0, addr, size);
        let vb = frame_read(ctx, job, p, 1, addr, size);
        if va == vb {
            continue;
        }
        let at = match ctx.tm.const_diff(addr, sp0) {
            Some(d) => format!("entry sp+{}", d as u32 as i32),
            None => ctx.tm.show(addr),
        };
        prove_same(
            ctx,
            job.sp,
            va,
            vb,
            &format!("{what}: {size}-byte value in the caller's stack at {at} (assumption caller-stack)"),
        )?;
    }
    Ok(())
}

/// Values a frame slot holds when it keeps a register saved at entry.
fn saved_regs(job: &Job) -> Vec<T> {
    (4..=11)
        .flat_map(|r| [job.regs[0][r], job.regs[1][r]])
        .chain([job.lr0])
        .collect()
}

fn frame_read(ctx: &mut Ctx, job: &Job, p: &Pair, side: usize, addr: T, size: u8) -> T {
    let data = job.sp.data(side).clone();
    let mut init = image_init(&data, p.m[side].mem.epoch, None);
    ctx.mem_read(&p.m[side].mem, addr, size, &mut init)
}

/// The two machines are at a call to `name`: compare what the callee can observe.
fn compare_call(ctx: &mut Ctx, job: &Job, facts: &mut Facts, p: &mut Pair, name: &str) -> R<()> {
    let sp = job.sp;
    let sp0 = job.regs[0][13];
    for i in 0..ARG_WORDS {
        let (ta, tb) = if i < 4 {
            (p.m[0].regs[i], p.m[1].regs[i])
        } else {
            let off = 4 * (i as u64 - 4);
            let (aa, ab) = (
                ctx.tm.add_const(p.m[0].regs[13], off),
                ctx.tm.add_const(p.m[1].regs[13], off),
            );
            (frame_read(ctx, job, p, 0, aa, 4), frame_read(ctx, job, p, 1, ab, 4))
        };
        for t in [ta, tb] {
            let (m, s) = facts.deps(ctx, t);
            if m != 0 {
                facts.in_arg.insert((name.to_string(), i as u8, m));
            }
            for &id in s.iter() {
                facts.ret_arg.insert((name.to_string(), i as u8, id));
            }
        }
        if i < 4 && (ctx.region(ta).is_some() || ctx.region(tb).is_some()) {
            if ta == tb {
                // The callee gets the address of a stack object.
                let off = match ctx.tm.const_diff(ta, sp0) {
                    Some(d) => d as u32 as i32 as i64,
                    None => i64::MIN,
                };
                p.escaped = Some(p.escaped.map_or(off, |e| e.min(off)));
                continue;
            }
            if ctx.region(ta).is_some() && ctx.region(tb).is_some() {
                return Err(Stop::Unsupported(format!(
                    "the address of a stack object is passed to {name} and the two frames are laid out differently (the extent of stack objects is unknown without the source)"
                )));
            }
        }
        if sp.corr(ctx, ta, tb) {
            continue;
        }
        // What an earlier call clobbered, or stack nobody wrote, is not an argument.
        let garbage = |ctx: &Ctx, t: T| match ctx.tm.node(t) {
            Node::Sym(id) => ctx.tm.sym_name(*id).starts_with("clob"),
            Node::Load(epoch, _) => *epoch == crate::sym::UNINIT_EPOCH,
            _ => false,
        };
        if garbage(ctx, ta) || garbage(ctx, tb) {
            for j in i..if i < 4 { i + 1 } else { ARG_WORDS } {
                facts.dead.insert((name.to_string(), j as u8));
            }
            continue;
        }
        let word = if i < 4 {
            format!("r{i}")
        } else {
            format!("sp[{}]", 4 * (i - 4))
        };
        let known = facts.needs.get(name).is_some_and(|n| n.0 >> i & 1 != 0);
        if known {
            continue;
        }
        let what = format!("{word} at the call to {name}");
        if let Some(how) = difference(ctx, sp, ta, tb, &what)? {
            let n = facts.needs.entry(name.to_string()).or_default();
            n.0 |= 1 << i;
            n.1.insert(i as u8, format!("{what}: {how}"));
        }
    }
    // What the callee reaches may itself hold the address of a stack object further down.
    while let Some(from) = p.escaped {
        let mut lowest = from;
        for (addr, size) in frame_slots(ctx, job, p, from) {
            for side in 0..2 {
                let v = frame_read(ctx, job, p, side, addr, size);
                if size == 4 && ctx.region(v).is_some() {
                    lowest = lowest.min(match ctx.tm.const_diff(v, sp0) {
                        Some(d) => d as u32 as i32 as i64,
                        None => i64::MIN,
                    });
                }
            }
        }
        if lowest == from {
            break;
        }
        p.escaped = Some(lowest);
    }
    if let Some(from) = p.escaped {
        // The callee may read the frame: it must hold the same values at the same places.
        if p.m[0].regs[13] != p.m[1].regs[13] {
            return Err(Stop::Unsupported(format!(
                "the address of a stack object is known to {name} and the two frames are laid out differently (the extent of stack objects is unknown without the source)"
            )));
        }
        let saved = saved_regs(job);
        for (addr, size) in frame_slots(ctx, job, p, from) {
            let (va, vb) = (
                frame_read(ctx, job, p, 0, addr, size),
                frame_read(ctx, job, p, 1, addr, size),
            );
            if sp.corr(ctx, va, vb) {
                continue;
            }
            // A slot that holds a saved register in one frame only: not the same frame.
            if saved.contains(&va) != saved.contains(&vb) {
                return Err(Stop::Unsupported(format!(
                    "the address of a stack object is known to {name} and the two frames are laid out differently (the extent of stack objects is unknown without the source)"
                )));
            }
            if facts.slot_diff.is_some() {
                continue;
            }
            let what = format!(
                "{size} byte(s) of the frame at {} that {name} can reach",
                ctx.tm.show(addr)
            );
            if let Some(how) = difference(ctx, sp, va, vb, &what)? {
                facts.slot_diff = Some(format!("{what}: {how}"));
            }
        }
    }
    Ok(())
}

/// Both machines continue after call number `k`, to `name`.
fn after_call(ctx: &mut Ctx, job: &Job, facts: &mut Facts, p: &mut Pair, name: &str, k: usize) {
    let lo = ctx.named_sym(&format!("ret{k}:lo:{name}"), 32);
    let hi = ctx.named_sym(&format!("ret{k}:hi:{name}"), 32);
    for (t, high) in [(lo, false), (hi, true)] {
        if let Node::Sym(id) = *ctx.tm.node(t) {
            facts.ret_syms.insert(id, (name.to_string(), high));
        }
    }
    // What the callee may have done to the frame, before the machines forget what lies below
    // their stack pointers.
    let slots = match p.escaped {
        Some(from) => frame_slots(ctx, job, p, from),
        None => Vec::new(),
    };
    for (side, m) in p.m.iter_mut().enumerate() {
        m.finish_call(ctx, 2000 * side + k, Some(lo), Some(hi));
        m.mem.world.clear();
        m.mem.epoch = k as u32 + 1;
    }
    // Every slot the callee can reach holds a new value, the same in both frames; the slots
    // that hold a register saved at entry are not objects of the program.
    let saved = saved_regs(job);
    for (n, (addr, size)) in slots.into_iter().enumerate() {
        let cur = frame_read(ctx, job, p, 0, addr, size);
        if saved.contains(&cur) {
            continue;
        }
        let v = ctx.named_sym(&format!("esc{k}.{n}"), size * 8);
        for m in p.m.iter_mut() {
            ctx.mem_write(&mut m.mem, addr, size, v);
        }
    }
}

fn run_path(ctx: &mut Ctx, job: &Job, facts: &mut Facts) -> R<()> {
    let sp = job.sp;
    let mk = |ctx: &mut Ctx, side: usize| {
        let mut m = Machine::new(ctx, job.entry[side], job.regs[side]);
        let layout = sp.layout.clone();
        m.remap = Some(Remap {
            addr: if side == 0 {
                Arc::new(|_: &mut Ctx, t: T| t)
            } else {
                Arc::new(move |ctx: &mut Ctx, t: T| layout.translate(ctx, t))
            },
            data: sp.data(side).clone(),
        });
        m.mmio = sp.mmio.clone();
        m.stack_top = job.stack.iter().map(|a| a.0 + 4).max().unwrap_or(0);
        // The garbage one machine finds below its stack pointer is not the other's.
        m.clobbers = (side as u32) << 20;
        for &(off, v) in &job.stack {
            let a = ctx.tm.add_const(job.regs[side][13], off as u64);
            ctx.mem_write(&mut m.mem, a, 4, v);
        }
        m
    };
    let mut p = Pair {
        m: [mk(ctx, 0), mk(ctx, 1)],
        io_pos: 0,
        escaped: None,
    };
    let mut helpers = [0usize, 2000];
    let mut k = 0usize;
    loop {
        let [ma, mb] = &mut p.m;
        let ea = run_side(ctx, job, facts, 0, ma, &mut helpers[0])?;
        let eb = run_side(ctx, job, facts, 1, mb, &mut helpers[1])?;
        match (&ea, &eb) {
            (Exit::Return, Exit::Return) => {
                compare_effects(ctx, job, facts, &mut p, "at return")?;
                compare_caller_stack(ctx, job, &p, "at return")?;
                for r in (4..=11).chain([13]) {
                    let (fa, fb) = (p.m[0].regs[r], p.m[1].regs[r]);
                    if fa == job.regs[0][r] && fb == job.regs[1][r] {
                        continue;
                    }
                    let name = if r == 13 { "sp".to_string() } else { format!("r{r}") };
                    prove_same(ctx, sp, fa, fb, &format!("callee-saved register {name} at return"))?;
                }
                // A register both sides leave holding what a call clobbered is no result.
                let garbage = |ctx: &Ctx, t: T| matches!(ctx.tm.node(t), Node::Sym(id) if ctx.tm.sym_name(*id).starts_with("clob"));
                let (a0, b0) = (p.m[0].regs[0], p.m[1].regs[0]);
                if facts.ret0_diff.is_none()
                    && !(garbage(ctx, a0) && garbage(ctx, b0))
                    && let Some(how) = difference(ctx, sp, a0, b0, "r0 at return")?
                {
                    facts.ret0_diff = Some(format!("r0 at return: {how}"));
                }
                let (a1, b1) = (p.m[0].regs[1], p.m[1].regs[1]);
                if !facts.ret1_diff && !(garbage(ctx, a1) && garbage(ctx, b1)) && !sp.corr(ctx, a1, b1) {
                    let e = ctx.tm.eq(a1, b1);
                    facts.ret1_diff = !ctx.implied(e);
                }
                for t in [a0, b0] {
                    let (m, s) = facts.deps(ctx, t);
                    facts.in_r0 |= m;
                    facts.ret_r0.extend(s.iter().copied());
                }
                for t in [a1, b1] {
                    let (m, s) = facts.deps(ctx, t);
                    facts.in_r1 |= m;
                    facts.ret_r1.extend(s.iter().copied());
                }
                break;
            }
            (Exit::Trap, Exit::Trap) => {
                compare_effects(ctx, job, facts, &mut p, "at trap")?;
                compare_caller_stack(ctx, job, &p, "at trap")?;
                break;
            }
            (Exit::Call { name: na }, Exit::Call { name: nb }) if na == nb => {
                let what = format!("at call #{} ({na})", k + 1);
                if let (Some(ta), Some(tb)) = (p.m[0].indirect.take(), p.m[1].indirect.take()) {
                    prove_same(ctx, sp, ta, tb, &format!("target of the call through a pointer {what}"))?;
                    facts.always(ctx, ta);
                    facts.always(ctx, tb);
                }
                compare_effects(ctx, job, facts, &mut p, &what)?;
                compare_call(ctx, job, facts, &mut p, na)?;
                if sp.paired.contains_key(na.as_str()) {
                    facts.calls.insert(na.clone());
                }
                if NORETURN.contains(&na.as_str()) || (0..2).any(|s| last_insn(sp.image(s), p.m[s].resume_pc())) {
                    break;
                }
                after_call(ctx, job, facts, &mut p, na, k);
                k += 1;
            }
            (
                Exit::Asm {
                    name: na,
                    arg: aa,
                    out: oa,
                },
                Exit::Asm {
                    name: nb,
                    arg: ab,
                    out: ob,
                },
            ) if na == nb && aa.is_some() == ab.is_some() && oa.is_some() == ob.is_some() => {
                // A system instruction: the same one on both sides, with everything observable
                // done before it in place, the same value written and the same unknown value read.
                let what = format!("at `{na}` (event #{})", k + 1);
                compare_effects(ctx, job, facts, &mut p, &what)?;
                if let (Some(va), Some(vb)) = (*aa, *ab) {
                    prove_same(ctx, sp, va, vb, &format!("value written {what}"))?;
                }
                if let (Some(ra), Some(rb)) = (*oa, *ob) {
                    let v = ctx.named_sym(&format!("ret{k}:asm:{na}"), 32);
                    p.m[0].regs[ra as usize] = v;
                    p.m[1].regs[rb as usize] = v;
                }
                k += 1;
            }
            _ => {
                return Err(Stop::Mismatch(
                    format!(
                        "after {k} matching call(s): old {}, new {}",
                        describe(&ea),
                        describe(&eb)
                    ),
                    None,
                ));
            }
        }
    }
    for c in ctx.pc.clone() {
        facts.always(ctx, c);
    }
    Ok(())
}

/// Result of comparing one function in one mode.
struct Raw {
    verdict: Verdict,
    facts: Facts,
    inline: bool,
    paths: usize,
    millis: u128,
}

fn analyse(sp: &Space, entry: [u32; 2], inline: bool, opts: &Options) -> Raw {
    let v = &opts.verify;
    let start = Instant::now();
    let mut ctx = Ctx::new(v.limits);
    if v.check_solver {
        ctx.prover = crate::bv::Prover::new_checked();
    }
    let mut deadline = start + v.time_limit;
    if let Some(d) = v.deadline {
        deadline = deadline.min(d);
    }
    ctx.set_budget(v.work_limit, v.max_terms, Some(deadline));
    ctx.prover.rom = sp
        .db
        .segments
        .iter()
        .filter(|s| !s.writable)
        .map(|s| (s.addr, s.data.clone()))
        .collect();
    let mut facts = Facts::default();
    let mut shared = [0 as T; 16];
    for (i, r) in shared.iter_mut().enumerate().take(13) {
        *r = ctx.named_sym(&format!("r{i}"), 32);
        if i < 4 {
            facts.inputs.insert(*r, 1 << i);
        }
    }
    shared[13] = ctx.private_base("SP0");
    shared[14] = ctx.named_sym("LR0", 32);
    shared[15] = ctx.tm.konst(32, 0);
    let mut regs = [shared, shared];
    for (side, r) in regs.iter_mut().enumerate() {
        if let Some(sb) = sp.image(side).static_base {
            r[9] = ctx.tm.konst(32, sb as u64);
        }
    }
    let mut stack = Vec::new();
    for i in 0..8u32 {
        let s = ctx.named_sym(&format!("stk{}", 4 * i), 32);
        if i < 4 {
            facts.inputs.insert(s, 1 << (4 + i));
        }
        stack.push((4 * i, s));
    }
    let bits = if opts.assume.sp_aligned { 3 } else { 2 };
    let low = ctx.tm.extract(shared[13], 0, bits);
    let z = ctx.tm.konst(bits, 0);
    let pre = vec![ctx.tm.eq(low, z)];
    let job = Job {
        sp,
        entry,
        regs,
        lr0: shared[14],
        stack,
        inline,
        caller_stack: opts.assume.caller_stack,
    };
    let mut verdict = Verdict::Equivalent;
    let mut bounded: Option<String> = None;
    let mut inconclusive: Option<String> = None;
    let mut explored = 0usize;
    let mut paths = 0usize;
    let mut best_paths = 0usize;
    let mut steps = 0u64;
    let step_budget = v.work_limit.saturating_mul(10).max(200_000);
    let max_depth = v.limits.max_depth;
    let mut schedule: Vec<usize> = [1, 2, 3, 4, 6, 8, 12, 16, 24, 32]
        .into_iter()
        .filter(|&d| d < max_depth)
        .collect();
    schedule.push(max_depth);
    'rounds: for (round, &depth) in schedule.iter().enumerate() {
        ctx.limits.max_depth = depth;
        ctx.decisions.clear();
        let mut depth_hit = false;
        inconclusive = None;
        paths = 0;
        loop {
            ctx.restart(&pre);
            explored += 1;
            match run_path(&mut ctx, &job, &mut facts) {
                Ok(()) => paths += 1,
                Err(Stop::Undefined) | Err(Stop::Halt) => {}
                Err(Stop::Truncated(why)) => {
                    if why == "branch depth limit" {
                        depth_hit = true;
                    } else {
                        bounded.get_or_insert(why);
                    }
                }
                Err(Stop::Inconclusive(why)) => match ctx.check_deadline() {
                    Err(Stop::Truncated(limit)) => {
                        bounded.get_or_insert(limit);
                    }
                    _ => {
                        inconclusive.get_or_insert(why);
                    }
                },
                Err(Stop::Mismatch(why, _)) => {
                    verdict = Verdict::Different(why);
                    break 'rounds;
                }
                Err(Stop::Unsupported(why)) => {
                    verdict = Verdict::Unsupported(why);
                    break 'rounds;
                }
            }
            best_paths = best_paths.max(paths);
            // Instructions on constants build no terms and cost the work budget nothing.
            steps += ctx.steps;
            if steps > step_budget {
                bounded.get_or_insert_with(|| "step budget".into());
                break 'rounds;
            }
            if let Err(Stop::Truncated(limit)) = ctx.check_deadline() {
                bounded.get_or_insert(limit);
                break 'rounds;
            }
            if explored >= v.limits.max_paths {
                bounded.get_or_insert_with(|| "path limit".into());
                break 'rounds;
            }
            if !ctx.next_path() {
                break;
            }
        }
        if !depth_hit {
            break;
        }
        if round + 1 == schedule.len() {
            bounded.get_or_insert_with(|| format!("loop bound ({depth} branches per path)"));
        }
    }
    let paths = paths.max(best_paths);
    if verdict == Verdict::Equivalent {
        if let Some(why) = inconclusive {
            verdict = Verdict::Inconclusive(why);
        } else if let Some(why) = bounded {
            verdict = Verdict::Bounded(format!("{why}; {paths} paths compared"));
        }
    }
    Raw {
        verdict,
        facts,
        inline,
        paths,
        millis: start.elapsed().as_millis(),
    }
}

/// The verdict covers every path: what the paths established can be relied upon.
fn complete(v: &Verdict) -> bool {
    matches!(v, Verdict::Equivalent)
}

// ----- data ---------------------------------------------------------------------------

fn compare_data(sp: &Space, out: &mut Comparison) {
    // Labels and what the compiler generates (switch tables) are no objects of the program:
    // the code that uses them is compared.
    let local = |n: &str| {
        n.starts_with(".L") || n.starts_with("__") || n.starts_with("CSWTCH.") || n.starts_with("switch.table")
    };
    for (name, x, y) in &sp.obj_pairs {
        if local(name) {
            continue;
        }
        out.data_checked += 1;
        if x.size != y.size {
            out.data.push((
                name.clone(),
                format!("size {} in the old image, {} in the new", x.size, y.size),
            ));
            continue;
        }
        let (Some(xs), Some(ys)) = (sp.a.read(x.addr, x.size), sp.b.read(y.addr, y.size)) else {
            continue;
        };
        if let Some((off, wa, wb)) = first_difference(sp.a, sp.b, &sp.layout, xs, ys) {
            out.data.push((
                name.clone(),
                format!("initial contents differ at offset {off}: old {wa:#x}, new {wb:#x}"),
            ));
        }
    }
    let (oa, ob) = (objects(sp.a), objects(sp.b));
    let only = |l: &[Named], other: &[Named]| -> Vec<String> {
        let mut v: Vec<String> = l
            .iter()
            .filter(|o| !local(&o.name) && !other.iter().any(|p| p.name == o.name))
            .map(|o| o.name.clone())
            .collect();
        v.sort();
        v.dedup();
        v
    };
    out.data_removed = only(&oa, &ob);
    out.data_added = only(&ob, &oa);
}

// ----- the whole comparison -----------------------------------------------------------------

/// Compare two images.  With `src` (the source parsed for the old and for the new image) every
/// function is first verified against the source on both sides.
pub fn compare(a: &Image, b: &Image, src: Option<(&Program, &Program)>, opts: &Options) -> Comparison {
    let mut sp = Space::new(a, b, &opts.verify.mmio);
    sp.explain = opts.explain;
    let mut out = Comparison {
        assume: opts.assume.clone(),
        with_source: src.is_some(),
        ..Default::default()
    };
    compare_data(&sp, &mut out);
    let wanted = |n: &str| opts.verify.only.is_empty() || opts.verify.only.iter().any(|o| o == n);

    // Three-way: both images against the source.
    let mut by_source: HashMap<String, (Verdict, String)> = HashMap::new();
    let mut voids: HashMap<String, bool> = HashMap::new();
    // Functions the source has that match it on both sides as far as they were explored, or
    // on which the source check said nothing: (no mismatch, some bound).
    let mut in_source: HashMap<String, (bool, bool)> = HashMap::new();
    let mut src_diff: HashMap<String, (String, &'static str)> = HashMap::new();
    if let Some((pa, pb)) = src {
        let (ra, rb) = (verify(pa, a, &opts.verify), verify(pb, b, &opts.verify));
        for f in pa.funcs.iter().filter(|f| f.body.is_some()) {
            voids.insert(f.name.to_string(), f.ty.ret == VOID);
        }
        for fa in &ra.funcs {
            let Some(fb) = rb.funcs.iter().find(|f| f.name == fa.name) else {
                continue;
            };
            let r = match (&fa.status, &fb.status) {
                (Status::Proved, Status::Proved) => (Verdict::Equivalent, "both match the source".to_string()),
                // One side does not match the source.  The source side follows calls, so the
                // difference may lie in a callee: the machine code is compared as well.
                (Status::Proved, Status::Mismatch(why)) => {
                    src_diff.insert(
                        fa.name.clone(),
                        (
                            format!("the new image does not match the source: {why}"),
                            "old matches the source",
                        ),
                    );
                    continue;
                }
                (Status::Mismatch(why), Status::Proved) => {
                    src_diff.insert(
                        fa.name.clone(),
                        (
                            format!("the old image does not match the source: {why}"),
                            "new matches the source",
                        ),
                    );
                    continue;
                }
                (x, y) => {
                    let mismatch = matches!(x, Status::Mismatch(_)) || matches!(y, Status::Mismatch(_));
                    let ok = |s: &Status| matches!(s, Status::Proved | Status::Bounded(_));
                    in_source.insert(fa.name.clone(), (!mismatch, ok(x) && ok(y)));
                    continue;
                }
            };
            by_source.insert(fa.name.clone(), r);
        }
    }

    // Machine code against machine code, for everything the source did not settle.
    let names: Vec<&String> = sp
        .paired
        .keys()
        .filter(|n| wanted(n) && !by_source.contains_key(*n))
        .collect();
    let run = |which: &[u32], inline: bool| -> Vec<Raw> {
        run_jobs(which, opts.verify.jobs, |i| {
            let n = names[i as usize];
            analyse(&sp, sp.paired[n], inline, opts)
        })
    };
    let all: Vec<u32> = (0..names.len() as u32).collect();
    let mut raw: Vec<Raw> = run(&all, false);
    let mut notes: Vec<Option<String>> = vec![None; names.len()];
    // A difference found while calls were matched one to one may only be a difference in which
    // calls are made: decide with the callees followed on both sides.
    let redo = |raw: &mut Vec<Raw>, notes: &mut Vec<Option<String>>, which: Vec<u32>| {
        let again = run(&which, true);
        for (i, r) in which.into_iter().zip(again) {
            let i = i as usize;
            let decisive = complete(&r.verdict) || matches!(r.verdict, Verdict::Different(_));
            // Tried: what the call-by-call comparison established stands otherwise.
            notes[i] = Some(String::new());
            if decisive {
                raw[i] = r;
            } else if !matches!(raw[i].verdict, Verdict::Different(_)) {
                // Keep the call-by-call result and what it says about the callees.
            } else {
                let Verdict::Different(old) = &raw[i].verdict else {
                    unreachable!()
                };
                let why = match &r.verdict {
                    Verdict::Bounded(w) | Verdict::Inconclusive(w) | Verdict::Unsupported(w) => w.clone(),
                    _ => String::new(),
                };
                let msg =
                    format!("differs when calls are matched one to one ({old}); with the callees followed: {why}");
                raw[i].verdict = match &r.verdict {
                    Verdict::Bounded(_) => Verdict::Bounded(msg),
                    Verdict::Unsupported(_) => Verdict::Unsupported(msg),
                    _ => Verdict::Inconclusive(msg),
                };
                raw[i].inline = true;
            }
        }
    };
    let first: Vec<u32> = all
        .iter()
        .copied()
        .filter(|&i| {
            let r = &raw[i as usize];
            !complete(&r.verdict) && *r.facts.saw_internal.borrow()
        })
        .collect();
    if !first.is_empty() {
        redo(&mut raw, &mut notes, first);
    }

    // Which argument words each function reads, and whose results are read.
    let index: HashMap<&str, usize> = names.iter().enumerate().map(|(i, n)| (n.as_str(), i)).collect();
    let solve = |raw: &[Raw]| -> (Vec<u8>, Vec<[bool; 2]>) {
        let n = raw.len();
        let mut uses = vec![0u8; n];
        let mut read = vec![[false; 2]; n];
        let reads = |uses: &[u8], callee: &str, word: u8| match index.get(callee) {
            Some(&j) => uses[j] >> word & 1 != 0,
            None => true,
        };
        loop {
            let mut changed = false;
            for (i, r) in raw.iter().enumerate() {
                let f = &r.facts;
                let mut u = if complete(&r.verdict) {
                    f.in_always | f.in_r0
                } else {
                    0xff
                };
                if read[i][1] {
                    u |= f.in_r1;
                }
                for (callee, word, mask) in &f.in_arg {
                    if reads(&uses, callee, *word) {
                        u |= mask;
                    }
                }
                if u != uses[i] {
                    uses[i] = u;
                    changed = true;
                }
                let mut hit: Vec<u32> = f.ret_always.iter().copied().collect();
                if read[i][0] {
                    hit.extend(f.ret_r0.iter().copied());
                }
                if read[i][1] {
                    hit.extend(f.ret_r1.iter().copied());
                }
                // Only what a callee is known to read shows that a result is read.
                for (callee, word, id) in &f.ret_arg {
                    if index
                        .get(callee.as_str())
                        .is_some_and(|&j| complete(&raw[j].verdict) && uses[j] >> word & 1 != 0)
                    {
                        hit.push(*id);
                    }
                }
                for id in hit {
                    let (callee, high) = &f.ret_syms[&id];
                    if let Some(&j) = index.get(callee.as_str())
                        && !read[j][*high as usize]
                    {
                        read[j][*high as usize] = true;
                        changed = true;
                    }
                }
            }
            if !changed {
                return (uses, read);
            }
        }
    };
    let (mut uses, mut read) = solve(&raw);
    // Argument words some call site shows the callee does not read.
    let dead_of = |raw: &[Raw], callee: &str| -> u8 {
        let m = raw
            .iter()
            .flat_map(|r| r.facts.dead.iter())
            .filter(|d| d.0 == callee)
            .fold(0u8, |m, d| m | 1 << d.1);
        // Arguments fill r0-r3 before the stack, and only r1 or r3 can be skipped (to align
        // a 64-bit argument): a callee that does not read r0 reads nothing, one that does
        // not read r2 reads no stack word.
        if m & 1 != 0 {
            0xff
        } else if m & 4 != 0 {
            m | 0xf8
        } else {
            m
        }
    };
    // Words of a call to `callee` that differ and that it may read.
    let live = |raw: &[Raw], uses: &[u8], callee: &str, mask: u8| -> u8 {
        let mask = mask & !dead_of(raw, callee);
        match index.get(callee) {
            Some(&j) => mask & uses[j],
            None => mask,
        }
    };
    for _ in 0..names.len() {
        // A function that passes different values in a word its callee reads is decided with
        // the callee followed.
        let again: Vec<u32> = all
            .iter()
            .copied()
            .filter(|&i| {
                let r = &raw[i as usize];
                !r.inline
                    && notes[i as usize].is_none()
                    && complete(&r.verdict)
                    && r.facts.needs.iter().any(|(callee, (mask, _))| {
                        index.contains_key(callee.as_str()) && live(&raw, &uses, callee, *mask) != 0
                    })
            })
            .collect();
        if again.is_empty() {
            break;
        }
        redo(&mut raw, &mut notes, again);
        (uses, read) = solve(&raw);
    }

    // Verdicts.
    let mut diffs: Vec<FuncDiff> = Vec::new();
    // Functions whose only possible difference is r0 at return.
    let mut r0_only: HashSet<String> = HashSet::new();
    for (i, n) in names.iter().enumerate() {
        let r = &raw[i];
        let [ea, eb] = sp.paired[*n];
        let size = |img: &Image, e: u32| img.func_at(e).map_or(0, |s| s.size);
        let (sa, sb) = (size(a, ea), size(b, eb));
        let mut d = FuncDiff {
            name: (*n).clone(),
            old: Some((ea, sa)),
            new: Some((eb, sb)),
            verdict: r.verdict.clone(),
            same_code: sa == sb && sa > 0 && a.read(ea, sa) == b.read(eb, sb),
            conditions: Vec::new(),
            modulo: Vec::new(),
            inlined: r.inline,
            via_source: None,
            paths: r.paths,
            millis: r.millis,
            explanation: None,
        };
        // A difference seen on an explored path stands even if other paths hit a bound.
        if complete(&r.verdict) || matches!(r.verdict, Verdict::Bounded(_)) {
            let f = &r.facts;
            let mut hard: Option<String> = None;
            let mut weak: Vec<String> = Vec::new();
            for (callee, (mask, whys)) in &f.needs {
                let mask = live(&raw, &uses, callee, *mask);
                if mask == 0 {
                    continue;
                }
                let why = &whys[&(mask.trailing_zeros() as u8)];
                let words: Vec<String> = (0..ARG_WORDS)
                    .filter(|w| mask >> w & 1 != 0)
                    .map(|w| {
                        if w < 4 {
                            format!("r{w}")
                        } else {
                            format!("sp[{}]", 4 * (w - 4))
                        }
                    })
                    .collect();
                if opts.assume.ext_arity {
                    d.conditions
                        .push(format!("{callee} does not read {}", words.join(", ")));
                } else {
                    weak.push(format!(
                        "{why} (not a difference if {callee} does not read {})",
                        words.join(", ")
                    ));
                }
            }
            if let Some(why) = &f.slot_diff {
                weak.push(format!("{why} (not a difference outside the object it was given)"));
            }
            if let Some(why) = &f.ret0_diff {
                let known = voids.get(n.as_str()).copied();
                if read[i][0] {
                    hard = Some(format!("{why} (callers read the result)"));
                } else if known == Some(true) {
                    d.via_source = Some("returns void in the source".into());
                } else if known == Some(false) {
                    hard = Some(why.clone());
                } else if opts.assume.void_r0 {
                    d.conditions.push("it returns nothing (r0 differs at return)".into());
                } else {
                    if weak.is_empty() {
                        r0_only.insert((*n).clone());
                    }
                    weak.push(format!("{why} (not a difference if it returns nothing)"));
                }
            }
            if f.ret1_diff && hard.is_none() {
                if read[i][1] {
                    hard = Some("r1 differs at return and callers read it".into());
                } else if !opts.assume.ret32 {
                    weak.push("r1 differs at return (not a difference unless it returns a 64-bit value)".into());
                } else if !voids.contains_key(n.as_str()) {
                    d.conditions
                        .push("it does not return a 64-bit value (r1 differs at return)".into());
                }
            }
            if let Some(why) = hard {
                d.verdict = Verdict::Different(why);
            } else if !weak.is_empty() {
                d.verdict = Verdict::MayDiffer(weak.join("; "));
            }
        }
        match in_source.get(n.as_str()) {
            Some(&(true, bounded)) => match &d.verdict {
                // Without a mismatch against the source the input that tells the two apart
                // may be one for which the source has no defined behaviour.
                Verdict::Different(why) | Verdict::MayDiffer(why) => {
                    let why = format!(
                        "the machine code differs ({why}), possibly only where the source is undefined: neither image is shown to differ from the source"
                    );
                    d.verdict = if bounded {
                        Verdict::Bounded(format!("{why}; both match it as far as explored"))
                    } else {
                        Verdict::Inconclusive(why)
                    };
                }
                Verdict::Equivalent => {}
                _ if bounded => {
                    d.verdict = Verdict::Bounded("both images match the source as far as explored".into());
                }
                _ => {}
            },
            Some(&(false, _)) => d.via_source = Some("differs from the source".into()),
            None => {}
        }
        diffs.push(d);
    }
    // Callees assumed equivalent that are not proved so.
    let status: HashMap<String, &'static str> = diffs
        .iter()
        .map(|d| (d.name.clone(), d.label()))
        .chain(by_source.iter().map(|(n, v)| {
            (
                n.clone(),
                if v.0 == Verdict::Equivalent {
                    "EQUIVALENT"
                } else {
                    "DIFFERENT"
                },
            )
        }))
        .chain(src_diff.keys().map(|n| (n.clone(), "DIFFERENT")))
        .collect();
    for (i, d) in diffs.iter_mut().enumerate() {
        let f = &raw[i].facts;
        if !matches!(d.verdict, Verdict::Equivalent | Verdict::MayDiffer(_)) || !complete(&raw[i].verdict) {
            continue;
        }
        // Results the function hands on (its own result, an argument) rather than reads.
        let forwarded: BTreeSet<&str> = f
            .ret_r0
            .iter()
            .chain(f.ret_r1.iter())
            .chain(f.ret_arg.iter().map(|x| &x.2))
            .filter(|id| !f.ret_syms[*id].1)
            .map(|id| f.ret_syms[id].0.as_str())
            .collect();
        for callee in &f.calls {
            if *callee == d.name {
                continue;
            }
            match status.get(callee.as_str()).copied() {
                Some("EQUIVALENT" | "IDENTICAL" | "MOVED") | None => {}
                Some("MAY-DIFFER") if r0_only.contains(callee) && !forwarded.contains(callee.as_str()) => {}
                Some(s) => d.modulo.push((callee.clone(), s.to_string())),
            }
        }
    }
    for d in diffs.iter_mut() {
        let Some((why, how)) = src_diff.get(&d.name) else {
            continue;
        };
        if d.verdict == Verdict::Equivalent && d.modulo.iter().any(|m| m.1 == "DIFFERENT") {
            d.via_source = Some("differs from the source only through what it calls".into());
        } else {
            d.verdict = Verdict::Different(why.clone());
            d.via_source = Some(how.to_string());
            d.modulo.clear();
            d.conditions.clear();
        }
    }
    for (n, (v, how)) in by_source {
        let [ea, eb] = sp.paired.get(&n).copied().unwrap_or([0, 0]);
        let at = |img: &Image, e: u32| img.func_at(e).or_else(|| img.func(&n)).map(|s| (s.addr, s.size));
        let (old, new) = (at(a, ea), at(b, eb));
        diffs.push(FuncDiff {
            same_code: match (old, new) {
                (Some(x), Some(y)) => x.1 == y.1 && x.1 > 0 && a.read(x.0, x.1) == b.read(y.0, y.1),
                _ => false,
            },
            name: n,
            old,
            new,
            verdict: v,
            conditions: Vec::new(),
            modulo: Vec::new(),
            inlined: false,
            via_source: Some(how),
            paths: 0,
            millis: 0,
            explanation: None,
        });
    }
    // Functions only one image has.
    let (fa, fb) = (funcs_of(a), funcs_of(b));
    for (side, list) in [(0, &fa), (1, &fb)] {
        for f in list.iter() {
            if !wanted(&f.name) || sp.fn_key[side].contains_key(&f.addr) {
                continue;
            }
            let at = Some((f.addr, f.size));
            diffs.push(FuncDiff {
                name: f.name.clone(),
                old: if side == 0 { at } else { None },
                new: if side == 1 { at } else { None },
                verdict: if side == 0 { Verdict::Removed } else { Verdict::Added },
                same_code: false,
                conditions: Vec::new(),
                modulo: Vec::new(),
                inlined: false,
                via_source: None,
                paths: 0,
                millis: 0,
                explanation: None,
            });
        }
    }
    diffs.sort_by(|x, y| {
        let key = |d: &FuncDiff| (d.old.or(d.new).map_or(0, |x| x.0), d.old.is_none());
        key(x).cmp(&key(y)).then(x.name.cmp(&y.name))
    });
    if opts.explain {
        let notes = std::mem::take(&mut *sp.notes.lock().unwrap_or_else(|e| e.into_inner()));
        let (na, nb) = (crate::explain::Names::new(a, None), crate::explain::Names::new(b, None));
        for d in diffs.iter_mut() {
            let (Verdict::Different(why) | Verdict::MayDiffer(why)) = &d.verdict else {
                continue;
            };
            let mut o = String::new();
            if let Some((_, note)) = notes.iter().find(|n| why.contains(&n.0)) {
                o.push_str(note);
            }
            for (label, image, names, at) in [("old", a, &na, d.old), ("new", b, &nb, d.new)] {
                if let Some((addr, size)) = at {
                    let _ = writeln!(o, "{label} code:");
                    o.push_str(&crate::explain::binary::listing(
                        image,
                        names,
                        addr & !1,
                        (addr & !1) + size,
                    ));
                }
            }
            d.explanation = Some(o);
        }
    }
    out.funcs = diffs;
    out
}