wazabin-qcode 0.3.0

Typed SSA-style p-code IR for binary analysis, modelled after Ghidra's p-code
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
//! The central arena for all IR state: [`Context`].

use crate::value::QCodeMut;
use std::{borrow::Cow, fmt::Display};

use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};

use crate::{
    assumption::{Certainty, KnownContradiction, PassName, Proposition, Truth, Violation},
    error::{Error, ErrorTy, Result},
    pass_scope,
    space::{LocalMemorySpaceId, MemorySpaceId, Space, SpaceId, SpaceStore},
    types::TypeManager,
    value::{
        BasicBlock, BlockParamRef, FunctionBody, FunctionId, FunctionRef, Instruction, ModuleView,
        QCodeView, TempId, TempSpaceId, ValueId,
        block::{BlockId, BlockRef, EdgeData, EdgeId},
        block_param::{BlockParam, BlockParamId},
        insn::{InstructionId, InstructionRef, Mnemonic, PCodeOpId},
        literal::{LiteralId, LiteralRef},
        registry::ValueRegistry,
        varnode::{Varnode, VarnodeId, VarnodeRef, register::RegisterId},
    },
};
use jstd::registry::{self, Identified, Registry};

/// The central arena that owns all IR state.
///
/// `Context` is the single source of truth for every value (instructions,
/// varnodes, literals, blocks, functions), every memory space, and the
/// bidirectional maps that let you look up values by name or by machine
/// address.
///
/// # Usage
///
/// Create a context with [`Context::new`] and pass `&mut` references to a
/// [`Builder`](crate::builder::Builder) when constructing IR, or to analysis
/// passes when transforming it.
///
/// ```rust
/// use qcode::context::Context;
///
/// let ctx = Context::new();
/// // `ctx.shared.default_space` is the RAM space created by `new`.
/// let _ram = ctx.shared.default_space;
/// ```
///
/// # Lifetime parameter `'str`
///
/// The `'str` lifetime is the lifetime of interned string data used for names
/// and space identifiers. When names are owned (e.g. generated names), they
/// are stored as `Cow::Owned`; when they are borrowed from source data they are
/// `Cow::Borrowed` and must outlive the context.
#[derive(Default, Clone, serde::Serialize)]
pub struct Context<'str> {
    /// Module-shared IR state: everything that is **not** per-function interface
    /// or body storage (regimes 1–3 of the context-split design — architecture,
    /// interners, module maps, truths). Reached today behind `&mut Context`;
    /// [`Context::split()`](Self) (stage 5b-ii c.2) will hand it out as a frozen
    /// `&Shared` view while the bodies registry is borrowed mutably.
    pub shared: Shared<'str>,

    /// Per-function *interface* storage — the caller-reasoning surface (name,
    /// address, kind, external-ness, signature) held in lockstep with
    /// [`bodies`](Self::bodies) under the same [`FunctionId`] space. Never checked
    /// out: a co-checked-out callee answers interface queries from here.
    #[serde(default)]
    pub interfaces: Registry<FunctionId, crate::value::function::FunctionInterface<'str>>,

    /// Per-function *body* storage. Each function owns its instruction/block/param/
    /// edge arenas; the composite-ID accessors ([`Context::instruction`] etc.)
    /// route through here. A checked-out function's body is moved out of its slot
    /// (leaving an empty body); its [`interface`](Self::interfaces) stays put, so
    /// callers always read the real interface.
    pub bodies: Registry<FunctionId, FunctionBody<'str>>,
}

#[derive(serde::Deserialize)]
struct ContextWire<'str> {
    shared: Shared<'str>,
    #[serde(default)]
    interfaces: Registry<FunctionId, crate::value::function::FunctionInterface<'str>>,
    bodies: Registry<FunctionId, FunctionBody<'str>>,
}

impl<'de, 'str> serde::Deserialize<'de> for Context<'str> {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let ContextWire {
            shared,
            interfaces,
            mut bodies,
        } = ContextWire::deserialize(deserializer)?;
        if interfaces.len() != bodies.len() {
            return Err(serde::de::Error::custom(
                "function body/interface registries drifted",
            ));
        }
        for mut body in bodies.iter_mut() {
            let id = body.id;
            body.rehydrate_id(id);
        }
        Ok(Self {
            shared,
            interfaces,
            bodies,
        })
    }
}

/// Module-shared IR state: regimes 1–3 of the context-split design (see
/// `docs/plans/context-split/00-overview.md`). Holds the frozen architecture
/// (spaces, registers, memory image), the append-interned value arenas
/// (literals, bytes, varnodes, types) inside [`values`](Self::values), and the
/// phase-mutable module maps (names, truths, discoveries, call
/// sites). Everything here is reachable through a frozen `&Shared` view; nothing
/// per-function-body lives here.
#[derive(Default, Clone, serde::Serialize, serde::Deserialize)]
pub struct Shared<'str> {
    pub default_space: SpaceId,

    /// A mapping of space ids to their corresponding [`Space`]s.
    pub(crate) spaces: Registry<SpaceId, Space>,

    /// A mapping of pcode ops to their names
    pub pcode_ops: Registry<PCodeOpId, Box<str>>,

    /// A mapping of names to spaces
    pub named_spaces: HashMap<Box<str>, SpaceId>,

    /// Global reverse name map for module-scoped values (functions, varnodes,
    /// spaces, p-code ops, byte blobs), used to keep their name hints unique and
    /// resolve them by name. Block/instruction/param/Temp names are **not** here — they
    /// live in each [`FunctionBody`](crate::value::FunctionBody)'s own [`NameTable`], so
    /// those namespaces stay independent across functions (see [`NameTable`]).
    pub(crate) name_map: NameTable<'str>,

    /// A mapping of register IDs to their corresponding value IDs
    pub registers: HashMap<RegisterId, VarnodeId>,

    /// The values available in the context, indexed by their ID
    pub values: ValueRegistry<'str>,

    /// Type registry: owns all [`Type`](crate::types::Type) objects and hands out [`TypeId`](crate::types::TypeId)s.
    pub types: TypeManager,

    /// Whether the binary's per-segment protection flags are authoritative
    /// (the `memory_protections` pass has run). Until then the lifter treats
    /// every mapped byte as potentially executable (default r/x); once known,
    /// [`Context::assume_executable`] narrows to the real flags reported by
    /// the loaded binary. Serialized so a reloaded snapshot keeps the
    /// established state.
    #[serde(default)]
    pub(crate) protections_known: bool,

    /// The binary format's primary entrypoint, when the loader supplied one.
    /// Analysis passes use this for narrow loader-shaped recognizers such as
    /// CRT startup recovery without depending on a binary-format crate.
    #[serde(default)]
    pub(crate) primary_entrypoint: Option<u64>,

    /// Code addresses discovered by lifting or analysis but not yet lifted.
    /// `qcode_analysis` cannot call the lifter (one-way crate dependency), so
    /// passes that resolve new targets (e.g. the jump-table pass) record them
    /// here; the `lift_new_addresses` pass drains them and lifts the code into
    /// the (clean) IR. Rides through clone (so it survives checkpoint+replay
    /// rounds) and serialization.
    #[serde(default)]
    pub(crate) discoveries: crate::discovery::DiscoveryQueue,

    /// The operating system of the loaded binary, stamped by the loader from the
    /// binary format (PE → Windows, ELF → Linux). Platform-gated passes — e.g.
    /// TEB seeding, which only applies to Windows — read it. `Unknown` for
    /// synthetic contexts.
    #[serde(default)]
    pub(crate) target_os: TargetOs,

    /// Library names the loaded binary links against (ELF `DT_NEEDED` sonames,
    /// PE import-directory DLL names), stamped by the loader alongside
    /// `target_os`, or seeded via `--assume-libs` when the format reports none.
    /// Serialized so reloaded snapshots re-run prototype-table selection
    /// correctly. Empty for synthetic contexts.
    #[serde(default)]
    pub(crate) linked_libraries: Vec<String>,

    /// Entry addresses of functions the user asked to skip optimizing (via the
    /// `--ignore` flag). Such functions are still lifted, but every per-function
    /// analysis pass skips them. Rides through clone so it survives the
    /// checkpoint+replay rounds, and through serialization so a saved session
    /// keeps honoring the request.
    #[serde(default)]
    pub(crate) ignored_functions: HashSet<u64>,

    /// Register effect the opt-in `AssumeCallingConvention` hypothesis assigns to
    /// indirect / unresolved calls (see
    /// [`Proposition::AssumeCallingConvention`](crate::assumption::Proposition::AssumeCallingConvention)).
    /// `None` unless the `assume_calling_convention` pass has installed it this
    /// round — the hypothesis is off by default. Recomputed each pipeline round
    /// from the calling convention, so it is not serialized (and a replay clone
    /// starts empty, the pass reinstalling it).
    #[serde(skip)]
    pub(crate) assumed_call_convention: Option<crate::assumption::AssumedCallEffect>,
}

/// Lets [`Space::from_id`] resolve against a bare `&Shared`, matching the
/// pre-existing `AsShared` call shape.
impl SpaceStore for Shared<'_> {
    fn spaces(&self) -> &Registry<SpaceId, Space> {
        &self.spaces
    }
}

/// Lets [`Space::from_id`] resolve against a `&Context` directly.
impl SpaceStore for Context<'_> {
    fn spaces(&self) -> &Registry<SpaceId, Space> {
        &self.shared.spaces
    }
}

impl<'str> Shared<'str> {
    /// The value id currently bound to the module-global `name`, if any.
    /// Shared-only mirror of [`Context::get_named`].
    pub fn get_named(&self, name: &str) -> Option<ValueId> {
        self.name_map.get(name)
    }

    /// The varnode `id`. Shared-only accessor (varnodes live in the interners).
    pub fn varnode(&self, id: VarnodeId) -> &crate::value::Varnode<'str> {
        &self.values.varnodes[id]
    }

    /// The space `id`. Shared-only accessor (spaces are frozen architecture).
    pub fn space(&self, id: SpaceId) -> &Space {
        &self.spaces[id]
    }

    /// Iterates over every space registered in this module, in id order, each
    /// paired with its [`SpaceId`].
    pub fn spaces(&self) -> impl Iterator<Item = Identified<SpaceId, &Space>> + '_ {
        self.spaces.iter()
    }

    /// An interned integer constant of the given byte width, as a [`ValueId`].
    /// Shared-only mirror of [`Context::get_const`] returning the id directly
    /// (the `LiteralRef` wrapper needs a whole `&Context`).
    pub fn get_const(&self, value: u64, size: usize) -> ValueId {
        let type_id = self.types.get_or_make_int(size);
        ValueId::Literal(self.values.get_or_make_typed_literal(value, type_id, size))
    }

    /// The id of the user p-code op called `name`, registering it if the module
    /// has none by that name.
    ///
    /// SLEIGH's ops keep their specification ids, so a name is looked up before
    /// it is appended and an op is never registered twice.
    pub fn pcode_op(&mut self, name: &str) -> PCodeOpId {
        if let Some(op) = self.pcode_ops.iter().find(|op| op.as_ref() == name) {
            return op.id;
        }
        self.pcode_ops.push(Box::from(name))
    }

    /// The id of the reserved [`VM_INTERRUPT`](crate::value::insn::VM_INTERRUPT)
    /// op, registering it on first use.
    pub fn vm_interrupt_op(&mut self) -> PCodeOpId {
        self.pcode_op(crate::value::insn::VM_INTERRUPT)
    }

    /// A `bool`-typed constant (`true`/`false`), byte-stored. Shared-only mirror
    /// of [`Context::get_bool_const`] returning the id directly.
    pub fn get_bool_const(&self, value: bool) -> ValueId {
        let type_id = self.types.get_or_make_bool();
        ValueId::Literal(
            self.values
                .get_or_make_typed_literal(u64::from(value), type_id, 1),
        )
    }

    /// A typed constant literal. Shared-only mirror of
    /// [`Context::get_typed_const`] returning the id directly.
    pub fn get_typed_const(&self, value: u64, type_id: crate::types::TypeId) -> ValueId {
        let size = self.types.size_of(type_id);
        ValueId::Literal(self.values.get_or_make_typed_literal(value, type_id, size))
    }

    /// An opaque `Array(i8, len)` byte-blob constant, as a [`ValueId`].
    /// Shared-only mirror of [`Context::get_bytes`] returning the id directly.
    pub fn get_bytes(&self, data: Vec<u8>) -> ValueId {
        let i8_ty = self.types.get_or_make_int(1);
        let type_id = self.types.get_or_make_array(i8_ty, data.len());
        ValueId::Bytes(
            self.values
                .bytes
                .push(crate::value::Bytes { data, type_id }),
        )
    }

    /// The forced rendering mode for a `Bytes` blob, or
    /// [`BytesDisplay::Auto`](crate::value::BytesDisplay::Auto) if unset.
    /// Shared-only mirror of [`Context::bytes_display`] (the override map lives in
    /// the interners), for the `&Shared`-backed [`BytesRef`](crate::value::BytesRef).
    pub fn bytes_display(&self, id: crate::value::BytesId) -> crate::value::BytesDisplay {
        self.values
            .bytes_display
            .get(&id)
            .copied()
            .unwrap_or_default()
    }

    /// Like [`get_bytes`](Self::get_bytes) but with an explicit array/sequence
    /// [`TypeId`](crate::types::TypeId). Shared-only mirror of [`Context::get_typed_bytes`] returning
    /// the id directly.
    pub fn get_typed_bytes(&self, data: Vec<u8>, type_id: crate::types::TypeId) -> ValueId {
        ValueId::Bytes(
            self.values
                .bytes
                .push(crate::value::Bytes { data, type_id }),
        )
    }

    /// The recorded [`Truth`] of `prop`, if any. Shared-only
    /// mirror of [`Context::truth`] (truths live in the phase-mutable shared
    /// maps), for `&Shared`-served pass reads.
    pub fn truth(&self, prop: Proposition) -> Option<Truth> {
        self.values.truths.get(&prop).copied()
    }

    /// The cached [`AssumedCallEffect`](crate::assumption::AssumedCallEffect) for
    /// the opt-in `AssumeCallingConvention` hypothesis, if the
    /// `assume_calling_convention` pass installed one this round. Shared-only
    /// accessor so the `&Shared`-served mem2reg / alias register classifier can
    /// consult it. `None` when the hypothesis is inactive.
    pub fn assumed_call_convention(&self) -> Option<&crate::assumption::AssumedCallEffect> {
        self.assumed_call_convention.as_ref()
    }

    /// Iterate every varnode as a [`VarnodeRef`]. Shared-only mirror of
    /// [`Context::varnodes`] (varnodes live in the interners).
    pub fn varnodes(&self) -> impl Iterator<Item = crate::value::VarnodeRef<'str, '_>> + '_ {
        self.values
            .varnodes
            .iter()
            .map(move |v| crate::value::Varnode::from_id(self, v.id))
    }

    /// Number of varnodes. Shared-only mirror of [`Context::varnode_count`];
    /// append-only, so an unchanged value means an unchanged varnode set.
    pub fn varnode_count(&self) -> usize {
        self.values.varnodes.len()
    }

    /// The stored [`TypeId`](crate::types::TypeId) of a **shared-leaf** value (literal, bytes, or
    /// varnode-with-override). Shared-only mirror of [`Context::stored_type_of`]:
    /// instruction/block-param/block/function ids live in function bodies and are
    /// out of a `&Shared`'s reach, so they return `None` here (callers route those
    /// through the body). Matches the actual call pattern, where only shared-leaf
    /// ids are passed to the shared path.
    pub fn stored_type_of(&self, id: ValueId) -> Option<crate::types::TypeId> {
        match id {
            ValueId::Literal(lid) => Some(self.values.literals[lid].type_id),
            ValueId::Bytes(bid) => Some(self.values.bytes[bid].type_id),
            ValueId::Varnode(vid) => self.values.varnode_types.get(&vid).copied(),
            ValueId::Poison(pid) => Some(self.values.poisons[pid].type_id),
            ValueId::Instruction(_)
            | ValueId::BlockParam(_)
            | ValueId::BasicBlock(_)
            | ValueId::Temp(_)
            | ValueId::Function(_) => None,
        }
    }
}

/// The operating system of a loaded binary, inferred from its container format.
/// The enum now lives in the leaf `wazabin_binary` crate (next to the container
/// parsers); re-exported here so `qcode::context::TargetOs` keeps resolving.
pub use wazabin_binary::TargetOs;

impl<'str> Context<'str> {
    /// Creates a new, empty context with a single default RAM space.
    ///
    /// The default space has a word size of 1 byte and an address size of 8
    /// bytes (suitable for 64-bit architectures). Its [`SpaceId`] is stored in
    /// `Context::default_space`.
    pub fn new() -> Self {
        let mut ctx = Self::default();
        // SPACE_CONST = SpaceId(0): virtual space for constant/immediate values
        ctx.shared.spaces.push(Space::new(Some("const"), 1, 8));
        // default RAM space (SpaceId(1)); temp spaces start at SpaceId(2)
        let default_space = Space::new(Some("ram"), 1, 8);
        ctx.shared.default_space = ctx.shared.spaces.push(default_space);
        ctx
    }

    /// Returns the [`SpaceId`] for the named space, or `None` if it has not
    /// been registered.
    pub fn try_get_space(&self, name: &str) -> Option<SpaceId> {
        self.shared.named_spaces.get(name).copied()
    }

    /// Resolve a space by name for textual lowering: an already-registered named
    /// space, the default space when its name matches (the default `ram` space is
    /// not in `named_spaces`), or a freshly-registered RAM space otherwise. Used
    /// by the canonical `load(space:size, ptr)` / `store(...)` lowering.
    pub fn get_or_make_named_space(&mut self, name: &str) -> SpaceId {
        if let Some(id) = self.try_get_space(name) {
            return id;
        }
        let default_id = self.shared.default_space;
        if self.shared.spaces[default_id].name.as_deref() == Some(name) {
            return default_id;
        }
        let default = &self.shared.spaces[self.shared.default_space];
        let space = Space::new(Some(name), default.word_size, default.addr_size);
        self.add_space(space)
    }

    /// Adds a space to the context, registering its name, and returns its ID.
    pub fn add_space(&mut self, space: Space) -> SpaceId {
        let name_key: Option<Box<str>> = space.name.clone();
        let id = self.shared.spaces.push(space);
        if let Some(name) = name_key {
            self.shared.named_spaces.insert(name, id);
        }
        id
    }

    /// Returns the number of spaces registered in this context.
    pub fn space_count(&self) -> usize {
        self.shared.spaces.len()
    }

    /// Iterates over every space registered in this context, in id order, each
    /// paired with its [`SpaceId`].
    pub fn spaces(&self) -> impl Iterator<Item = Identified<SpaceId, &Space>> + '_ {
        self.shared.spaces()
    }

    pub fn set_primary_entrypoint(&mut self, entrypoint: Option<u64>) {
        self.shared.primary_entrypoint = entrypoint;
    }

    pub fn primary_entrypoint(&self) -> Option<u64> {
        self.shared.primary_entrypoint
    }

    /// Record the set of function entry addresses whose optimization the user
    /// asked to skip (`--ignore`). Per-function passes consult
    /// [`Context::is_function_ignored`] and skip these functions.
    pub fn set_ignored_functions(&mut self, addrs: HashSet<u64>) {
        self.shared.ignored_functions = addrs;
    }

    /// The function entry addresses whose optimization is being skipped.
    pub fn ignored_functions(&self) -> &HashSet<u64> {
        &self.shared.ignored_functions
    }

    /// Whether the function at `addr` was marked ignored (`--ignore`). A `None`
    /// address (synthetic functions with no entry) is never ignored.
    pub fn is_function_ignored(&self, addr: Option<u64>) -> bool {
        addr.is_some_and(|a| self.shared.ignored_functions.contains(&a))
    }

    /// Records the loaded binary's operating system (set by the loader from the
    /// container format).
    pub fn set_target_os(&mut self, os: TargetOs) {
        self.shared.target_os = os;
    }

    /// The loaded binary's operating system, or [`TargetOs::Unknown`].
    pub fn target_os(&self) -> TargetOs {
        self.shared.target_os
    }

    /// Records the library names the binary links against (set by the loader
    /// from the container format, or by `--assume-libs`).
    pub fn set_linked_libraries(&mut self, libs: Vec<String>) {
        self.shared.linked_libraries = libs;
    }

    /// Library names the loaded binary links against (ELF `DT_NEEDED` sonames,
    /// PE import DLL names). Empty when unknown.
    pub fn linked_libraries(&self) -> &[String] {
        &self.shared.linked_libraries
    }

    /// Replaces the spaces registry wholesale. Intended for initialization from a pre-built spec.
    pub fn load_spaces(&mut self, spaces: registry::Registry<SpaceId, Space>) {
        self.shared.spaces = spaces;
    }

    /// Mark the binary's memory protections as established (the
    /// `memory_protections` pass has run), so executability checks narrow from the
    /// permissive default to the real per-segment flags.
    pub fn mark_protections_known(&mut self) {
        self.shared.protections_known = true;
    }

    /// Whether the binary's per-segment protection flags are authoritative.
    pub fn protections_known(&self) -> bool {
        self.shared.protections_known
    }

    /// The lifter's pre-decode executability gate, modeling executability as a
    /// [`Proposition::ExecutableMemory`]. Returns whether `addr` should be lifted:
    ///
    /// - protections not yet established → optimistic default r/x (`true`);
    ///   the binary's segment flags are *not* consulted in this case;
    /// - protections known and the region is executable → `true`;
    /// - protections known and the region is non-executable (or unmapped) →
    ///   `false` (skip), recording the proven fact
    ///   `ExecutableMemory{start, end} = false` for the whole containing segment
    ///   of a mapped-but-non-executable target.
    ///
    /// The proposition is keyed by the containing segment, not the individual
    /// address, so repeated skips in the same non-executable region collapse to a
    /// single truth-map entry rather than one per byte.
    ///
    /// A *known* value for the containing region (a proven fact, or a user
    /// override seeded as known) wins over the raw segment flags, so the user can
    /// force a region executable or non-executable from the Assumptions panel.
    pub fn assume_executable(
        &mut self,
        binary: &dyn wazabin_binary::BinaryFormat,
        addr: u64,
    ) -> bool {
        let bounds = binary.segment_bounds(addr);
        if let Some((start, end)) = bounds
            && let Some(known) = self.known(Proposition::ExecutableMemory { start, end })
        {
            return known;
        }
        if !self.shared.protections_known || binary.is_executable(addr) {
            return true;
        }
        if let Some((start, end)) = bounds {
            self.set_known(Proposition::ExecutableMemory { start, end }, false);
        }
        false
    }

    /// Record a discovered code address (typed: a new function or a block within
    /// an existing function) for the `lift_new_addresses` pass to lift.
    pub fn discover(&mut self, discovery: crate::discovery::Discovery) -> bool {
        self.shared.discoveries.insert(discovery)
    }

    /// Convenience for the common case: the jump-table pass resolved a branch in
    /// the function at `func_entry` to `target`, a block within that function.
    ///
    /// `source_block` is the address of the block ending in the indirect branch,
    /// so the lifter can connect a real CFG edge from it to `target` in the clean
    /// IR (the resolution is otherwise only reflected in the disposable optimized
    /// clone, which would leave the target an orphan that function-splitting and
    /// reachability cannot follow).
    pub fn discover_code(&mut self, func_entry: u64, source_block: u64, target: u64) {
        self.shared.discoveries.insert(
            crate::discovery::Discovery::block(target, func_entry)
                .with_edge_kind(crate::discovery::EdgeKind::JumpTableTarget)
                .from_block_addr(source_block)
                .with_provenance(crate::discovery::DiscoveryProvenance::Optimization {
                    pass: "handle_jump_tables".to_string(),
                    assumption: None,
                }),
        );
    }

    /// Remove and return every pending discovery, leaving the queue empty.
    pub fn drain_discoveries(&mut self) -> Vec<crate::discovery::Discovery> {
        self.shared.discoveries.drain()
    }

    /// Iterate pending discoveries without consuming them.
    pub fn discoveries(&self) -> impl Iterator<Item = &crate::discovery::Discovery> + '_ {
        self.shared.discoveries.iter()
    }

    /// True if there are no pending discoveries.
    pub fn has_no_discoveries(&self) -> bool {
        self.shared.discoveries.is_empty()
    }

    /// Every code address lifted in this context, as portable [`CodeSeed`]s. Used
    /// to export a "code map" that pre-seeds a later run of the same binary.
    ///
    /// [`CodeSeed`]: crate::discovery::CodeSeed
    pub fn lifted_code_seeds(&self) -> Vec<crate::discovery::CodeSeed> {
        self.shared.discoveries.lifted_seeds()
    }

    /// Enqueue exported [`CodeSeed`]s as pending discoveries so the lifter reaches
    /// them in its first pass. Call before lifting begins; seeds whose key already
    /// has a terminal outcome are ignored by the queue.
    ///
    /// [`CodeSeed`]: crate::discovery::CodeSeed
    pub fn seed_code(&mut self, seeds: impl IntoIterator<Item = crate::discovery::CodeSeed>) {
        for seed in seeds {
            self.shared.discoveries.insert(seed.into_discovery());
        }
    }

    pub fn mark_discovery_lifted(&mut self, key: crate::discovery::DiscoveryKey) {
        self.shared.discoveries.mark_lifted(key);
    }

    pub fn mark_discovery_failed(
        &mut self,
        key: crate::discovery::DiscoveryKey,
        reason: impl Into<String>,
    ) {
        self.shared.discoveries.mark_failed(key, reason);
    }

    pub fn mark_discovery_skipped(
        &mut self,
        key: crate::discovery::DiscoveryKey,
        reason: impl Into<String>,
    ) {
        self.shared.discoveries.mark_skipped(key, reason);
    }

    /// Returns the [`BlockId`] for a block at `addr`, creating one if needed.
    ///
    /// The newly created block is named after the address in hex and registered
    /// in the address map.
    pub fn get_or_make_block(&mut self, addr: u64, func: FunctionId) -> BlockId {
        let mut addresses = crate::address_index::AddressIndex::analyze(self);
        self.get_or_make_block_indexed(&mut addresses, addr, func)
    }

    /// Indexed construction variant of [`get_or_make_block`](Self::get_or_make_block).
    /// The caller owns `addresses` for the duration of its lifting/lowering
    /// operation and threads it through every address-bearing mutation.
    #[track_caller]
    pub fn get_or_make_block_indexed(
        &mut self,
        addresses: &mut crate::address_index::AddressIndex,
        addr: u64,
        func: FunctionId,
    ) -> BlockId {
        use crate::address_index::AddressTarget;

        if let Some(AddressTarget::Function(owner)) = addresses.get(addr) {
            assert_eq!(
                owner, func,
                "cannot create a block at an address owned by another function"
            );
        }
        let existing = match addresses.get(addr) {
            Some(AddressTarget::Block(block)) => Some(block),
            Some(AddressTarget::Function(function)) => FunctionBody::from_id(self, function)
                .root()
                .map(|root| root.id),
            None => None,
        };
        match existing {
            Some(block) => {
                // The address resolves to a block that does not *start* there:
                // it absorbed the address when a straight-line run was folded
                // into one basic block. Something branches here after all, so
                // the run has to be broken back up.
                //
                // Only within one function: a block id is local to its arena,
                // so handing a caller in another function a block from this one
                // would be unrepresentable as a branch target. That case falls
                // through to the cross-arena report below, which says so.
                if self.block(block).address != Some(addr)
                    && block.func == func
                    && self.block(block).extra_addresses.contains(&addr)
                {
                    return self.split_block_at_address(addresses, block, addr);
                }
                if block.func != func {
                    let stored = FunctionBody::from_id(self, block.func);
                    let requested = FunctionBody::from_id(self, func);
                    // Blocks are stored in per-function arenas now; ownership is
                    // encoded by the qualified block id rather than a field on
                    // `BasicBlock`.
                    let parent = Some(block.func);
                    let caller = std::panic::Location::caller();
                    let detail = format!(
                        "cannot reuse a block stored in another function arena: block={block:?} address=0x{addr:x}; stored={:?} name={:?} entry={:?} parent={parent:?}; requested={:?} name={:?} entry={:?}; caller={caller}",
                        block.func,
                        stored.name(),
                        stored.address(),
                        func,
                        requested.name(),
                        requested.address(),
                    );
                    log::error!(
                        target: "qcode::arena",
                        "{detail}\nbacktrace:\n{}",
                        std::backtrace::Backtrace::force_capture()
                    );
                    panic!("{detail}");
                }
                block
            }
            None => {
                BasicBlock::make(self, func)
                    .with_address_indexed(addresses, addr)
                    .id
            }
        }
    }

    /// Re-establishes `addr` as the start of a block of its own, when it is
    /// currently *interior* to `block` — one of the addresses `block` absorbed.
    ///
    /// # Why this discards code instead of moving it
    ///
    /// The obvious split copies the instructions from `addr` onward into the
    /// new block. That is only sound while a block's instructions still
    /// correspond, one run at a time, to the guest instructions they came from
    /// — and they do not: a discovered block is optimized in place, so stores
    /// have been forwarded and dead computation removed *across* the guest
    /// instruction boundaries. There is no longer an instruction that "is" the
    /// start of `addr`.
    ///
    /// So neither half's code survives the split. Both blocks are emptied and
    /// keep only their place in the graph: `block` keeps its identity, so every
    /// branch already targeting it stays valid, and the new block takes `addr`.
    /// An empty block carrying an address is already this module's request to
    /// lift it, so the code comes back from the guest bytes — which are the
    /// only faithful source for it — the next time control reaches either half.
    pub fn split_block_at_address(
        &mut self,
        addresses: &mut crate::address_index::AddressIndex,
        block: BlockId,
        addr: u64,
    ) -> BlockId {
        // `addr` is a branch target, and stays one: a later run through here
        // must not fold across it and undo this split.
        addresses.mark_boundary(addr);
        let tail = BasicBlock::make(self, block.func).id;

        // Emptying `block` drops its terminator, and with it every outgoing
        // edge; the successors are rebuilt when it is lifted again.
        self.bodies[block.func].clear_block_instructions(block);

        // `addr` and everything else absorbed into `block` stop being its, and
        // the index stops pointing at it for them: whichever half covers each
        // address is settled by lifting, not guessed at here.
        let absorbed = std::mem::take(&mut self.block_mut(block).extra_addresses);
        for absorbed_addr in absorbed {
            addresses.forget(absorbed_addr);
        }
        BasicBlock::from_id_mut(self, tail)
            .in_function(block.func)
            .with_address_indexed(addresses, addr);
        tail
    }

    /// Moves `insn` and everything after it into a fresh block of the same
    /// function, leaving `block` unterminated for the caller to end. See
    /// [`FunctionBody::split_block_before`].
    pub fn split_block_before(&mut self, block: BlockId, insn: InstructionId) -> BlockId {
        self.bodies[block.func].split_block_before(block, insn)
    }

    /// Borrows one function body and creates the concrete body-local builder
    /// positioned at `block`.
    pub fn builder(&mut self, block: BlockId) -> crate::builder::Builder<'str, '_> {
        let body = &mut self.bodies[block.func];
        crate::builder::Builder::new(body, &self.shared, &self.interfaces, block)
    }

    /// Test/API convenience for preparing a machine-address block before
    /// narrowing construction to its body-local builder.
    pub fn builder_at(&mut self, address: u64) -> crate::builder::Builder<'str, '_> {
        use crate::address_index::AddressTarget;

        let mut addresses = crate::address_index::AddressIndex::analyze(self);
        let block = match addresses.get(address) {
            Some(AddressTarget::Function(function)) => self.bodies[function]
                .root_id()
                .map(|local| BlockId::new(function, local))
                .unwrap_or_else(|| {
                    self.get_or_make_block_indexed(&mut addresses, address, function)
                }),
            Some(AddressTarget::Block(block)) => block,
            None => {
                let function = FunctionBody::make(self, Cow::Owned(format!("blk_{address:x}")))
                    .expect("anonymous host function")
                    .id;
                self.get_or_make_block_indexed(&mut addresses, address, function)
            }
        };
        let mut builder = self.builder(block);
        builder.set_address(address);
        builder
    }

    /// The forced rendering mode for a `Bytes` blob, or
    /// [`BytesDisplay::Auto`](crate::value::BytesDisplay::Auto) if unset.
    pub fn bytes_display(&self, id: crate::value::BytesId) -> crate::value::BytesDisplay {
        self.shared
            .values
            .bytes_display
            .get(&id)
            .copied()
            .unwrap_or_default()
    }

    /// Force how a `Bytes` blob renders as a `b"..."` literal everywhere.
    /// Setting [`BytesDisplay::Auto`](crate::value::BytesDisplay::Auto) clears
    /// any existing override.
    pub fn set_bytes_display(
        &mut self,
        id: crate::value::BytesId,
        mode: crate::value::BytesDisplay,
    ) {
        if mode == crate::value::BytesDisplay::Auto {
            self.shared.values.bytes_display.remove(&id);
        } else {
            self.shared.values.bytes_display.insert(id, mode);
        }
    }

    /// Returns a list of all live blocks in the context (across all functions).
    pub fn block_ids(&self) -> Vec<BlockId> {
        self.functions().flat_map(|f| f.block_ids()).collect()
    }

    /// Returns all live instructions across all functions in stable logical-ID
    /// order. Function arenas iterate in dense physical order, so this explicit
    /// sort preserves the observable whole-context order across compaction.
    pub fn instruction_ids(&self) -> Vec<InstructionId> {
        let mut ids: Vec<_> = self.functions().flat_map(|f| f.instruction_ids()).collect();
        ids.sort_unstable();
        ids
    }

    /// Returns a list of all functions in the context.
    pub fn function_ids(&self) -> Vec<FunctionId> {
        self.interfaces.iter().map(|i| i.id).collect()
    }

    /// Mints a fresh, uniquely-named anonymous function and returns its id.
    ///
    /// A block must be born into some function's arena; this hands out a host
    /// for standalone blocks (tests, the raw-hex/bare-block lift paths, and the
    /// pyqcode API that build a block without an enclosing function).
    pub fn anon_function(&mut self) -> FunctionId {
        let name = self.get_unique_name(std::borrow::Cow::Borrowed("anon"));
        crate::value::FunctionBody::make(self, name)
            .expect("unique anon function name")
            .id
    }

    /// `(issued_ids, removed_ids)` across every function's instruction arena.
    pub fn instruction_arena_stats(&self) -> (usize, usize) {
        let mut total = 0;
        let mut dead = 0;
        for f in self.bodies.iter() {
            total += f.insns.issued_len();
            dead += f.insns.issued_len() - f.insns.len();
        }
        (total, dead)
    }

    /// Aggregate issued/live/dead and structural capacity for every body arena.
    ///
    /// This is the stable reporting surface used by the Stage 7 before/after
    /// probe. Keeping the aggregation here avoids exposing arena internals to
    /// measurement binaries.
    pub fn body_arena_stats(&self) -> crate::value::BodyArenaStats {
        let mut total = crate::value::BodyArenaStats::default();
        for body in self.bodies.iter() {
            total.add_assign(body.arena_stats());
        }
        total
    }

    /// Releases body-arena capacity retained from peak analysis churn in every
    /// function (see [`FunctionBody::shrink_to_fit`](crate::value::FunctionBody::shrink_to_fit)).
    ///
    /// Purely an allocator hint: IDs, ordering, and rendered IR are unchanged.
    /// Called once at explicit end-of-mutation boundaries such as pipeline
    /// convergence; nothing depends on it running.
    pub fn shrink_bodies_to_fit(&mut self) {
        for mut body in self.bodies.iter_mut() {
            body.shrink_to_fit();
        }
    }

    /// Iterates over all the (live) instructions in the context.
    pub fn instructions(&self) -> impl Iterator<Item = InstructionRef<'str, '_>> + '_ {
        self.instruction_ids()
            .into_iter()
            .map(move |id| Instruction::from_id(self, id))
    }

    /// Iterates over all the (live) blocks in the context.
    pub fn blocks(&self) -> impl Iterator<Item = BlockRef<'str, '_>> + '_ {
        self.block_ids()
            .into_iter()
            .map(move |id| BlockRef::from_id(self, id))
    }

    /// Iterates over all the functions in the context
    pub fn functions(&self) -> FunctionIter<'str, '_> {
        FunctionIter {
            ctx: self,
            inner: self.bodies.iter(),
        }
    }

    /// Iterates over all the functions in the context
    /// alias for `functions()`
    pub fn iter(&self) -> FunctionIter<'str, '_> {
        self.functions()
    }

    pub fn varnodes(&self) -> impl Iterator<Item = VarnodeRef<'str, '_>> + '_ {
        self.shared.varnodes()
    }

    /// Number of varnodes in the context. The varnode registry is append-only, so
    /// this is monotonic and an unchanged value means an unchanged varnode set —
    /// used to validate caches keyed on the register/varnode layout (e.g. the
    /// alias `RegisterBase` in the analysis layer).
    pub fn varnode_count(&self) -> usize {
        self.shared.varnode_count()
    }

    /// Removes a CFG edge, unlinking it from both incident blocks' edge sets and
    /// physically dropping its payload. The module-path (function-qualified)
    /// spelling of [`FunctionBody::remove_cfg_edge`].
    pub fn remove_cfg_edge(&mut self, func: FunctionId, edge_id: EdgeId) {
        self.bodies[func].remove_cfg_edge(edge_id);
    }

    /// Relocate every block in `olds` into `target`'s own arena. The originals
    /// remain owned by their source functions until deletion; only the clones are
    /// rostered in `target`, so ownership and storage never diverge. This is the storage
    /// mover [`split_function_at`](Self::split_function_at) uses to make a split-off
    /// tail self-stored.
    ///
    /// A pure storage move: the resulting IR is semantically identical. Every
    /// relocated block is deep-cloned into `target` (preserving instruction types,
    /// machine addresses, and labels), all intra-set value/block references are
    /// remapped to the clones, the incident CFG edges are rebuilt between the new
    /// blocks (and their unmoved neighbours), the block addresses and the function
    /// root are re-pointed, and the originals are deleted. `target`'s reverse-use
    /// map is rebuilt from its live instructions afterwards.
    ///
    /// Assumes the relocated set is closed (the caller strips every cross-function
    /// CFG edge and rewrites foreign terminator targets to `TailCall`s first): every
    /// reference from a relocated block resolves to another relocated block, an
    /// unmoved block of `target`, or a shared value; a reference into a *third*
    /// function is a bug upstream, and debug builds assert against it.
    pub fn rehome_owned_blocks(
        &mut self,
        addresses: &mut crate::address_index::AddressIndex,
        target: FunctionId,
        olds: &[BlockId],
    ) -> HashMap<BlockId, BlockId> {
        // Body-local temporary values and spaces move with blocks that reference
        // them. Collect the exact dependency closure first: operand/origin temps,
        // explicit load/store spaces, and pointer provenance carried by types.
        let mut needed_temps: HashSet<TempId> = HashSet::default();
        let mut needed_temp_spaces: HashSet<TempSpaceId> = HashSet::default();
        for &old in olds {
            for &param_local in &self.block(old).params {
                let param = self.block_param(BlockParamId::new(old.func, param_local));
                if let Some(crate::value::LocalValueId::Temp(temp)) = param.origin {
                    needed_temps.insert(TempId::new(old.func, temp));
                }
                if let Some(MemorySpaceId::Temp(space)) = self.shared.types.space_of(param.type_id)
                {
                    needed_temp_spaces.insert(space);
                }
            }
            for &insn_local in &self.block(old).instructions {
                let insn = self.instruction(InstructionId::new(old.func, insn_local));
                for arg in insn.mnemonic().args() {
                    if let crate::value::LocalValueId::Temp(temp) = arg {
                        needed_temps.insert(TempId::new(old.func, temp));
                    }
                }
                let explicit_space = match insn.mnemonic() {
                    Mnemonic::Load(load) => Some(load.space),
                    Mnemonic::Store(store) => Some(store.space),
                    _ => None,
                };
                if let Some(LocalMemorySpaceId::Temp(space)) = explicit_space {
                    needed_temp_spaces.insert(TempSpaceId::new(old.func, space));
                }
                if let Some(MemorySpaceId::Temp(space)) = self.shared.types.space_of(insn.type_id) {
                    needed_temp_spaces.insert(space);
                }
            }
        }
        for &temp in &needed_temps {
            let data = &self.bodies[temp.func].temps[temp.local];
            needed_temp_spaces.insert(TempSpaceId::new(temp.func, data.space));
        }

        let mut needed_temp_spaces: Vec<_> = needed_temp_spaces.into_iter().collect();
        needed_temp_spaces.sort_unstable();
        let mut temp_space_map: HashMap<TempSpaceId, TempSpaceId> = HashMap::default();
        for old in needed_temp_spaces {
            if old.func == target {
                continue;
            }
            let space = self.bodies[old.func].temp_spaces[old.local].clone();
            let new = self.bodies[target].push_temp_space(space);
            temp_space_map.insert(old, new);
        }

        let mut needed_temps: Vec<_> = needed_temps.into_iter().collect();
        needed_temps.sort_unstable();
        let mut value_map: HashMap<ValueId, ValueId> = HashMap::default();
        for old in needed_temps {
            if old.func == target {
                continue;
            }
            let mut temp = self.bodies[old.func].temps[old.local].clone();
            temp.space = temp_space_map[&TempSpaceId::new(old.func, temp.space)].local;
            if let Some(name) = temp.name.take() {
                temp.name = Some(self.bodies[target].names.unique(name));
            }
            let new = self.bodies[target].push_temp(temp);
            value_map.insert(ValueId::Temp(old), ValueId::Temp(new));
        }

        // Phase 1: structurally clone every block into `target`, accumulating the
        // remaining old -> new value and block maps.
        let mut block_map: HashMap<BlockId, BlockId> = HashMap::default();
        for &old in olds {
            let new = BasicBlock::clone_block_into(self, old, target, &mut value_map);
            block_map.insert(old, new);
        }

        // Phase 2: with the full map known, remap the clones' operands and block
        // targets (this resolves forward references between relocated blocks). The
        // cloned terminators still hold their source block's local targets, so the
        // remap needs the *old* arena (`old.func`) to qualify them before lookup.
        for (&old, &new) in &block_map {
            let old_params = self.block(old).params.clone();
            let new_params = self.block(new).params.clone();
            for (old_local, new_local) in old_params.into_iter().zip(new_params) {
                let old_param = BlockParamId::new(old.func, old_local);
                let new_param = BlockParamId::new(new.func, new_local);
                let type_id = remap_rehomed_type(
                    self,
                    self.block_param(new_param).type_id,
                    target,
                    &temp_space_map,
                );
                self.block_param_mut(new_param).type_id = type_id;
                let Some(origin) = self.block_param(new_param).origin else {
                    continue;
                };
                let qualified = origin.qualify(old.func);
                let remapped = value_map.get(&qualified).copied().unwrap_or(qualified);
                debug_assert!(
                    remapped.owning_function().is_none_or(|f| f == target),
                    "rehome: relocated block param {old_param:?} has an origin in another \
                     function ({qualified:?}); the relocated set is not closed",
                );
                self.block_param_mut(new_param).origin = Some(remapped.localize(new.func));
            }

            let insns = self.block(new).instructions.clone();
            for insn_local in insns {
                let insn_id = InstructionId::new(new.func, insn_local);
                let type_id = remap_rehomed_type(
                    self,
                    self.instruction(insn_id).type_id,
                    target,
                    &temp_space_map,
                );
                self.instruction_mut(insn_id).type_id = type_id;
                let mut mnemonic = self.instruction(insn_id).mnemonic().clone();
                let mut pairs = Vec::new();
                for arg in mnemonic.args() {
                    // The clone still holds its *source* arena's bare-local operands,
                    // so qualify with `old.func` to look them up and re-localize the
                    // mapped replacement against the clone's own arena (`new.func`).
                    let qualified = arg.qualify(old.func);
                    if let Some(&new_val) = value_map.get(&qualified) {
                        pairs.push((arg, new_val.localize(new.func)));
                    } else if let Some(new_lit) =
                        remap_symbolic_block_literal(&self.shared.values.literals, arg, &block_map)
                    {
                        pairs.push((arg, new_lit));
                    } else {
                        // An operand not in the map must resolve to `target` itself
                        // (an unmoved own block) or to a shared value — never into a
                        // third function. A cross-function data dependence would mean
                        // the split left the set non-closed (a bug upstream).
                        debug_assert!(
                            qualified.owning_function().is_none_or(|f| f == target),
                            "rehome: relocated block references a value in another \
                             function ({qualified:?}); the relocated set is not closed",
                        );
                    }
                }
                crate::value::block::substitute_operands(&mut mnemonic, &pairs);
                remap_rehomed_memory_space(&mut mnemonic, old.func, target, &temp_space_map);
                remap_block_targets(&mut mnemonic, old.func, new.func, &block_map);
                *self.instruction_mut(insn_id).mnemonic_mut() = mnemonic;
            }
        }

        // Phase 3: rebuild every CFG edge incident to a relocated block, retargeting
        // the moved endpoint(s) to the clone. Collect the incident edge ids first
        // (an edge between two relocated blocks appears in both edge sets — the set
        // dedups it).
        // A block's edge set holds bare body-local `EdgeId`s; recover the storing
        // function from the incident block itself (its own `id.func`).
        let mut incident: HashSet<(FunctionId, EdgeId)> = HashSet::default();
        for &old in olds {
            incident.extend(self.block(old).edges.iter().map(|&e| (old.func, e)));
        }
        let mut incident: Vec<_> = incident.into_iter().collect();
        incident.sort_unstable();
        for (edge_func, edge) in incident {
            let EdgeData { from, to } = *self.edge(edge_func, edge);
            let from = BlockId::new(edge_func, from);
            let to = BlockId::new(edge_func, to);
            let new_from = block_map.get(&from).copied().unwrap_or(from);
            let new_to = block_map.get(&to).copied().unwrap_or(to);
            self.add_cfg_edge(new_from, new_to);
        }

        // Phase 4: move each block's machine address onto its clone, and re-point
        // the address index at the clone in place. We know exactly which addresses
        // moved and where, so this replaces a full `addresses.refresh(self)`
        // (O(all blocks + all functions)) with an O(moved blocks) update — the
        // per-split cost that otherwise made lifting quadratic in the grown IR.
        for &old in olds {
            let Some(addr) = self.block(old).address else {
                continue;
            };
            let new = block_map[&old];
            let extra = self.block(old).extra_addresses.clone();
            addresses.rehome_block(addr, old, new);
            for &e in &extra {
                addresses.rehome_block(e, old, new);
            }
            self.block_mut(new).extra_addresses = extra;
            self.block_mut(new).address = Some(addr);
        }

        // Phase 5: delete the originals (unlinks their old edges, physically
        // removes their instructions and physical block payloads).
        for &old in olds {
            BasicBlock::from_id_mut(self, old).delete();
        }

        // Phase 6: rebuild `target`'s reverse-use map from its live instructions,
        // since phase 2 rewrote operands in place.
        self.rebuild_users(target);
        block_map
    }

    /// The function registered at `block`'s machine address, if any. Registration
    /// is the entry-boundary signal even while the function is a rootless stub:
    /// Path A never adopts a foreign-storage block merely because addresses match.
    fn function_registered_at_block(
        &self,
        addresses: &crate::address_index::AddressIndex,
        block: BlockId,
    ) -> Option<FunctionId> {
        self.block(block)
            .address
            .and_then(|addr| addresses.function_at(addr))
    }

    /// Blocks reachable from `block` along CFG edges, stopping at any *other*
    /// function's entry (the tail-call boundary). `block` itself is always included.
    /// The walk is owner-agnostic: it crosses blocks regardless of which function
    /// currently owns them (an absorbed tail is owned by the function that absorbed
    /// it, not by `g`), exactly like the settle's `claimed_from`. `g` is the function
    /// the tail is being reclaimed into, so `g`'s own entry (which is `block`) is not
    /// a boundary. Deterministically ordered (by machine address, then id) so the
    /// storage relocation that follows assigns ids reproducibly.
    fn split_tail(
        &self,
        addresses: &crate::address_index::AddressIndex,
        block: BlockId,
        g: FunctionId,
    ) -> Vec<BlockId> {
        let mut seen: HashSet<BlockId> = HashSet::default();
        seen.insert(block);
        let mut queue = vec![block];
        while let Some(b) = queue.pop() {
            let succs: Vec<BlockId> = BasicBlock::from_id(self, b)
                .successors()
                .map(|(_, s)| s)
                .collect();
            for s in succs {
                if seen.contains(&s) {
                    continue;
                }
                // A different function's entry is a tail-call boundary — never
                // crossed. `g`'s own entry is `block` (already seen), so this stops
                // only at *foreign* entries.
                if let Some(entry_func) = self.function_registered_at_block(addresses, s)
                    && entry_func != g
                {
                    continue;
                }
                seen.insert(s);
                queue.push(s);
            }
        }
        let mut tail: Vec<BlockId> = seen.into_iter().collect();
        tail.sort_unstable_by_key(|&b| (self.block(b).address, b.local, b.func));
        tail
    }

    /// Split at `block`, returning the function `G` whose entry is `block`. This is
    /// the strict-locality construction verb (context-split ruling 2): a control
    /// transfer that lands mid-function is modelled as a *function split* — never a
    /// foreign block reference.
    ///
    /// Concretely it: (i) reuses the function already registered at `block`'s address
    /// (a stub minted by a `call`, which may already have adopted `block` as its
    /// root) or mints a conventional `fn_<addr>` (synthesized interface, unknown ABI
    /// — the optimization pipeline derives its purity/clobber/ABI facts later);
    /// (ii) extracts the tail reachable from `block`, stopping at other function
    /// entries (`split_tail`), and reassigns it to `G` (an
    /// absorbed tail may currently be owned by the function that absorbed it);
    /// (iii) rewrites every terminator that statically targeted `block` — in the
    /// absorbing function and in any already-lifted caller — into a function-level
    /// [`TailCall`](crate::value::insn::TailCall) (`G` for an unconditional `Branch`;
    /// a fresh intra-function trampoline block ending in a `TailCall` for a
    /// conditional `CBranch` arm), strips every cross-function CFG edge incident to
    /// the moved tail, and rewrites any foreign back-edge out of the tail the same
    /// way; (iv) relocates the tail into `G`'s own arena
    /// ([`rehome_owned_blocks`](Self::rehome_owned_blocks)) so `G` is self-stored.
    /// Afterwards no foreign block reference and no cross-function edge survives.
    ///
    /// `block` must carry a machine address.
    pub fn split_function_at(&mut self, block: BlockId) -> FunctionId {
        let mut addresses = crate::address_index::AddressIndex::analyze(self);
        self.split_function_at_indexed(&mut addresses, block)
    }

    /// Indexed construction variant of
    /// [`split_function_at`](Self::split_function_at).
    pub fn split_function_at_indexed(
        &mut self,
        addresses: &mut crate::address_index::AddressIndex,
        block: BlockId,
    ) -> FunctionId {
        use crate::value::insn::{Branch, CBranch, Callee, TailCall};

        let addr = self
            .block(block)
            .address
            .expect("split_function_at: block has no machine address");

        // G: reuse an existing function at this address (a call-minted stub that
        // may carry a symbol name), else mint a conventional one. A block already
        // stored elsewhere at this address is not adopted; relocation below creates
        // and roots a self-stored clone.
        let g = match addresses.function_at(addr) {
            Some(existing) => existing,
            None => FunctionBody::make_at_addr_indexed(self, addresses, addr, None).id,
        };

        // Promote mid-tail landings to their own functions before carving the tail.
        // A *retained* block (one outside the tail) that branches into the middle of
        // the tail is, per strict-locality (ruling 2), a function boundary: that
        // target is a distinct entry. If we left it in this tail the storage move
        // below would relocate it out of the retained predecessor's arena while its
        // `Branch` still named the old local index — a dangling terminator that a
        // later pass dereferences as a dead block. Splitting at the landing first
        // registers it as an entry, so the recursive split rewrites every
        // predecessor branch (retained and in-tail) into a `TailCall`, and the tail
        // walk below then stops at it cleanly. Iterated to a fixpoint because each
        // promotion can expose another; it terminates because every promotion
        // registers a new entry and so strictly shrinks future tails.
        loop {
            let tail_set: HashSet<BlockId> =
                self.split_tail(addresses, block, g).into_iter().collect();
            let mut promote: Option<BlockId> = None;
            'scan: for b in self.block_ids() {
                if tail_set.contains(&b) {
                    // An in-tail predecessor moves with the tail — no boundary.
                    continue;
                }
                let Some(mnemonic) = BasicBlock::from_id(self, b)
                    .instructions()
                    .last()
                    .map(|t| t.mnemonic().clone())
                else {
                    continue;
                };
                let targets = match &mnemonic {
                    Mnemonic::Branch(Branch { target, .. }) => vec![*target],
                    Mnemonic::CBranch(CBranch {
                        success_block,
                        failure_block,
                        ..
                    }) => vec![*success_block, *failure_block],
                    _ => vec![],
                };
                for t in targets {
                    let tid = BlockId::new(b.func, t);
                    // `block` itself is already handled by the terminator-rewrite
                    // below (its retained callers become `TailCall(g)`); only
                    // *mid*-tail landings need a fresh split.
                    if tid == block || !tail_set.contains(&tid) {
                        continue;
                    }
                    // A landing whose reach re-enters `block` (it shares an SCC with
                    // the entry) is still promoted: the recursive split's own tail
                    // walk stops at `g`'s registered entry (G was minted above, so
                    // `addr` is registered), so the entry is never relocated — the
                    // SCC simply becomes mutually tail-calling functions. Skipping
                    // it instead would leave any *retained* predecessor's branch
                    // naming the landing's old local index after the storage move —
                    // a dangling terminator dereferenced as a dead block later.
                    promote = Some(tid);
                    break 'scan;
                }
            }
            match promote {
                Some(tid) => {
                    self.split_function_at_indexed(addresses, tid);
                }
                None => break,
            }
        }

        // The tail is computed on the pre-split CFG (cross-function edges intact) so
        // the reach walk is exact — matching the settle's `claimed_from`.
        let mut tail = self.split_tail(addresses, block, g);
        let mut tail_set: HashSet<BlockId> = tail.iter().copied().collect();

        // Every function that currently owns a tail block loses those blocks; record
        // them so their `instruction_addrs` can be rebuilt afterwards.
        let mut prev_owners: HashSet<FunctionId> = HashSet::default();
        for &b in &tail {
            // Ownership is derived from the storing arena (`b.func`).
            prev_owners.insert(b.func);
        }

        // Treat the tail as G-owned while computing boundary rewrites, without
        // ever adopting its foreign-storage blocks into G's roster/root. The
        // physical move below is the only supported ownership transition.
        let effective_owner = |_ctx: &Context, candidate: BlockId| {
            if tail_set.contains(&candidate) {
                Some(g)
            } else {
                // Ownership is derived from the storing arena.
                Some(candidate.func)
            }
        };

        // Resolve a static terminator target to the foreign function whose *entry* it
        // is, from the perspective of `owner`.
        let foreign_entry =
            |ctx: &Context, target: BlockId, owner: FunctionId| -> Option<FunctionId> {
                let callee = if target == block {
                    g
                } else {
                    ctx.function_registered_at_block(addresses, target)?
                };
                (callee != owner).then_some(callee)
            };

        // Collect terminator rewrites: (a) any terminator that statically targets
        // `block` (G's new entry) — the origin's own branch into the tail and any
        // already-lifted caller; (b) any terminator in the moved tail whose target
        // is now a foreign entry (a boundary tail-call, or a back-edge into the
        // origin's retained entry). Both must become function-level `TailCall`s.
        let mut tail_calls: Vec<(InstructionId, FunctionId)> = Vec::new();
        // (terminator, owner_block, callee, the arm's local target that triggered
        // this cond-call). The arm target is recorded so the rewrite below repoints
        // exactly that arm — it must never re-derive the decision via `foreign_entry`
        // with a different `owner` than the scan used (the scan's `owner` is the
        // tail block's *effective* owner `g`; the storing arena differs), which would
        // silently skip the rewrite and strand the operand.
        let mut cond_calls: Vec<(
            InstructionId,
            BlockId,
            FunctionId,
            crate::value::LocalBlockId,
        )> = Vec::new();
        let relevant: Vec<BlockId> = self.block_ids();
        for b in relevant {
            let Some(owner) = effective_owner(self, b) else {
                continue;
            };
            let Some((term_id, mnemonic)) = BasicBlock::from_id(self, b)
                .instructions()
                .last()
                .map(|t| (t.id, t.mnemonic().clone()))
            else {
                continue;
            };
            // Terminator targets are bare body-local indices in the block's own
            // arena (`b.func`); qualify to recover the full `BlockId`.
            match mnemonic {
                Mnemonic::Branch(Branch { target, .. }) => {
                    if let Some(callee) = foreign_entry(self, BlockId::new(b.func, target), owner) {
                        tail_calls.push((term_id, callee));
                    }
                }
                Mnemonic::CBranch(CBranch {
                    success_block,
                    failure_block,
                    ..
                }) => {
                    if let Some(callee) =
                        foreign_entry(self, BlockId::new(b.func, success_block), owner)
                    {
                        cond_calls.push((term_id, b, callee, success_block));
                    }
                    if let Some(callee) =
                        foreign_entry(self, BlockId::new(b.func, failure_block), owner)
                    {
                        cond_calls.push((term_id, b, callee, failure_block));
                    }
                }
                _ => {}
            }
        }

        for (insn, callee) in tail_calls {
            self.replace_instruction_mnemonic(
                insn,
                Mnemonic::TailCall(TailCall {
                    target: Callee::Real(callee),
                    args: vec![],
                }),
            );
        }
        for (insn, owner_block, callee, arm_target) in cond_calls {
            // The trampoline is a fresh block of `owner_block`'s storing arena.
            let tramp = BasicBlock::make(self, owner_block.func).id;
            (self).builder(tramp).push_tail_call(callee);
            self.add_cfg_edge(owner_block, tramp);

            // A trampoline is a fresh block of the storing arena. When its
            // predecessor is a *tail* block (about to relocate into `g`), the
            // trampoline must relocate with it: otherwise the storage move below
            // rewrites the predecessor's arm to a tramp that stays behind in the
            // old arena — a dangling terminator target dereferenced later. Join
            // it to the moved set (its `TailCall` names a function, not a block,
            // so it carries no intra-tail reference to remap).
            if tail_set.contains(&owner_block) {
                tail.push(tramp);
                tail_set.insert(tramp);
            }

            let Mnemonic::CBranch(mut cb) = self.instruction(insn).mnemonic().clone() else {
                continue;
            };
            // Repoint exactly the arm the scan resolved to a foreign entry, matched
            // by its recorded local target. Re-deriving via `foreign_entry` here
            // would use the storing arena as `owner` instead of the scan's effective
            // owner `g` and could disagree — silently skipping the rewrite.
            let tramp_local = tramp.localize(insn.func);
            if cb.success_block == arm_target {
                cb.success_block = tramp_local;
            }
            if cb.failure_block == arm_target {
                cb.failure_block = tramp_local;
            }
            self.replace_instruction_mnemonic(insn, Mnemonic::CBranch(cb));
        }

        // Strip every cross-function CFG edge incident to a moved tail block; the
        // reach walk already stopped at these boundaries, so removing them cannot
        // change ownership — it only closes each function's graph over its own
        // blocks (a precondition of the storage relocation below).
        // Owner of a block during the move: `g` for any block in the (now
        // trampoline-augmented) moved set, else its storing arena. Inlined rather
        // than reusing the `effective_owner` closure so `tail_set` is free to have
        // grown trampolines above (the closure borrows it immutably).
        let moved_owner = |candidate: BlockId| {
            if tail_set.contains(&candidate) {
                g
            } else {
                candidate.func
            }
        };
        let mut stale: HashSet<(FunctionId, EdgeId)> = HashSet::default();
        for &b in &tail {
            for edge in self.block(b).edges.iter().copied() {
                let &EdgeData { from, to } = self.edge(b.func, edge);
                let from = BlockId::new(b.func, from);
                let to = BlockId::new(b.func, to);
                let cross = moved_owner(from) != moved_owner(to);
                let touches_tail = tail_set.contains(&from) || tail_set.contains(&to);
                if cross && touches_tail {
                    stale.insert((b.func, edge));
                }
            }
        }
        let mut stale: Vec<_> = stale.into_iter().collect();
        stale.sort_unstable();
        for (func, edge) in stale {
            self.remove_cfg_edge(func, edge);
        }

        // Storage move: relocate the tail into G's own arena (self-stored). The set
        // is now closed (all cross-function edges stripped, foreign targets rewritten
        // to `TailCall`s), so the relocation's closure assumptions hold.
        let moved = self.rehome_owned_blocks(addresses, g, &tail);
        self.bodies[g].set_root_id(Some(moved[&block].local));

        // Rebuild `instruction_addrs` on G and on every function that lost blocks.
        self.recompute_instruction_addrs(g);
        for owner in prev_owners {
            if owner != g {
                self.recompute_instruction_addrs(owner);
            }
        }

        g
    }

    /// Rebuild `func`'s `instruction_addrs` from the machine addresses of the
    /// instructions in its current blocks.
    fn recompute_instruction_addrs(&mut self, func: FunctionId) {
        let blocks = FunctionBody::from_id(self, func).block_ids();
        let mut addrs = std::collections::BTreeSet::new();
        for b in blocks {
            for insn in BasicBlock::from_id(self, b).instructions() {
                if let Some(a) = insn.address() {
                    addrs.insert(a);
                }
            }
        }
        self.bodies[func].instruction_addrs = addrs;
    }

    /// Rebuild `func`'s reverse-use map (`users`) from scratch by scanning its live
    /// instructions' operands. Mirrors the per-operand recording in
    /// [`Context::push_insn`](crate::context::Context::push_insn).
    fn rebuild_users(&mut self, func: FunctionId) {
        let live: Vec<InstructionId> = FunctionBody::from_id(self, func).instruction_ids();
        let users = &mut self.bodies[func].users;
        users.clear();
        for id in live {
            let args = self.bodies[func].insns[id.local].mnemonic().args();
            let users = &mut self.bodies[func].users;
            for arg in args {
                users.entry(arg).or_default().push(id.localize(func));
            }
        }
    }

    /// Assumes `prop` is true. Returns `false` (and records nothing) if the
    /// proposition is already assumed or known false; returns `true` if it was
    /// recorded or already held with the same polarity (idempotent). The
    /// recording pass is taken from [`pass_scope`].
    pub fn assume_true(&mut self, prop: Proposition) -> bool {
        self.assume(prop, true)
    }

    /// Assumes `prop` is false. Mirror of [`assume_true`](Self::assume_true).
    pub fn assume_false(&mut self, prop: Proposition) -> bool {
        self.assume(prop, false)
    }

    fn assume(&mut self, prop: Proposition, value: bool) -> bool {
        match self.shared.values.truths.get(&prop) {
            Some(t) => t.value == value,
            None => {
                self.shared.values.truths.insert(
                    prop,
                    Truth {
                        value,
                        certainty: Certainty::Assumed,
                        pass: PassName(pass_scope::current_pass()),
                    },
                );
                true
            }
        }
    }

    /// Records `prop = value` as proven, overriding any assumption. If this
    /// contradicts an existing assumption, a [`Violation`] is recorded — the
    /// checkpoint+replay driver's signal to discard this working copy.
    /// Contradicting an existing *known* fact is a logic error.
    ///
    /// Returns `true` if the fact is *novel* (no prior truth, or it overturned
    /// an assumption): the driver replays when a round produced novel facts.
    pub fn set_known(&mut self, prop: Proposition, value: bool) -> bool {
        let pass = PassName(pass_scope::current_pass());
        let novel = match self.shared.values.truths.get(&prop) {
            Some(prior) => {
                // Proving the opposite of an already-*known* fact (e.g. a user
                // override the analysis disproves) is not a replay signal: record
                // it as a hard contradiction and keep the original known value so
                // the driver can surface an error and terminate.
                if prior.certainty == Certainty::Known && prior.value != value {
                    self.shared
                        .values
                        .known_contradictions
                        .push(KnownContradiction {
                            prop,
                            known: prior.value,
                            proven: value,
                            known_pass: prior.pass,
                            proven_pass: pass,
                        });
                    return false;
                }
                if prior.certainty == Certainty::Assumed && prior.value != value {
                    self.shared.values.violations.push(Violation {
                        prop,
                        assumed: prior.value,
                        assuming_pass: prior.pass,
                        asserting_pass: pass,
                    });
                    true
                } else {
                    false
                }
            }
            None => true,
        };
        self.shared.values.truths.insert(
            prop,
            Truth {
                value,
                certainty: Certainty::Known,
                pass,
            },
        );
        novel
    }

    /// Seeds a proven fact carried over from an earlier checkpoint+replay
    /// round. Unlike [`set_known`](Self::set_known) this is not "novel": it
    /// must not retrigger a replay, and seeding over an existing entry is a
    /// logic error (seed before any pass runs).
    ///
    /// `pass` is the identity of the pass that originally proved the fact (as
    /// harvested from [`known_facts`](Self::known_facts)), preserved across the
    /// round boundary so the converged context still names the proving pass
    /// rather than the re-seeding driver.
    pub fn seed_known(&mut self, prop: Proposition, value: bool, pass: PassName) {
        let prior = self.shared.values.truths.insert(
            prop,
            Truth {
                value,
                certainty: Certainty::Known,
                pass,
            },
        );
        debug_assert!(prior.is_none(), "seeding {prop:?} over an existing truth");
    }

    /// The recorded [`Truth`] of `prop`, if any.
    pub fn truth(&self, prop: Proposition) -> Option<Truth> {
        self.shared.values.truths.get(&prop).copied()
    }

    /// Install (or clear) the cached effect backing the opt-in
    /// `AssumeCallingConvention` hypothesis — see
    /// [`Shared::assumed_call_convention`](crate::context::Shared::assumed_call_convention).
    /// The `assume_calling_convention` pass calls this alongside recording
    /// [`Proposition::AssumeCallingConvention`].
    pub fn set_assumed_call_convention(
        &mut self,
        effect: Option<crate::assumption::AssumedCallEffect>,
    ) {
        self.shared.assumed_call_convention = effect;
    }

    /// The cached [`AssumedCallEffect`](crate::assumption::AssumedCallEffect), if
    /// the hypothesis is active this round. Mirror of
    /// [`Shared::assumed_call_convention`](crate::context::Shared::assumed_call_convention).
    pub fn assumed_call_convention(&self) -> Option<&crate::assumption::AssumedCallEffect> {
        self.shared.assumed_call_convention.as_ref()
    }

    /// The proven value of `prop`: `Some` only for *known* entries.
    pub fn known(&self, prop: Proposition) -> Option<bool> {
        self.truth(prop)
            .filter(|t| t.certainty == Certainty::Known)
            .map(|t| t.value)
    }

    /// Iterates over every recorded truth (assumed and known).
    pub fn truths(&self) -> impl Iterator<Item = (Proposition, Truth)> + '_ {
        self.shared.values.truths.iter().map(|(&p, &t)| (p, t))
    }

    /// Iterates over the proven facts, for the replay driver to harvest into
    /// the next round's [`seed_known`](Self::seed_known) calls.
    pub fn known_facts(&self) -> impl Iterator<Item = (Proposition, bool, PassName)> + '_ {
        self.truths()
            .filter(|(_, t)| t.certainty == Certainty::Known)
            .map(|(p, t)| (p, t.value, t.pass))
    }

    /// The violations recorded this round (proven facts that contradicted an
    /// assumption). Non-empty means derived IR may be wrong: replay.
    pub fn violations(&self) -> &[Violation] {
        &self.shared.values.violations
    }

    /// Facts proven this round that contradicted an existing *known* fact (e.g. a
    /// user override the analysis disproved). Non-empty means the analysis cannot
    /// honor the forced value; the driver surfaces this as a hard error.
    pub fn known_contradictions(&self) -> &[KnownContradiction] {
        &self.shared.values.known_contradictions
    }

    /// Returns the raw `u64` backing value of the literal `id`.
    pub fn get_literal_value(&self, id: LiteralId) -> u64 {
        self.shared.values.literals[id].value
    }

    /// Returns an immutable reference to the instruction identified by `id`.
    pub fn get_insn(&self, id: InstructionId) -> InstructionRef<'str, '_> {
        InstructionRef::from_id(self, id)
    }

    /// The function *body* `fid` (context-split stage 5a bridging accessor).
    ///
    /// Names the owning function explicitly so IR reads route through the body's
    /// function-local raw accessors — `ctx.body(fid).block(id)` in place of the
    /// globally routed `BasicBlock::from_id(ctx, id)`. This is the module-scope
    /// (`&Context`) obtain-form; a function pass reaches the same body accessors
    /// through its checked-out host. After the stage-4 `func`-strip only this
    /// obtain step changes (the caller already holds `&FunctionBody`); the
    /// `.block(id)` call on the result is unchanged.
    pub fn body(&self, fid: FunctionId) -> &crate::value::FunctionBody<'str> {
        &self.bodies[fid]
    }

    /// The function *body* `fid`, mutably (see [`Context::body`]).
    pub fn body_mut(&mut self, fid: FunctionId) -> &mut crate::value::FunctionBody<'str> {
        &mut self.bodies[fid]
    }

    // ----- Composite-id arena routing (moved off `ValueRegistry` in the
    // context-split reshape: function bodies now live in `Context.bodies`, so the
    // accessors that route a `(FunctionId, Local)` id to its arena are inherent on
    // `Context`). Each reads/writes `self.bodies[id.func]`. -----

    /// Appends an instruction to `func`'s body and records all its operands in the
    /// `users` map.
    ///
    /// # Immutability invariant
    ///
    /// Instructions are considered immutable after this call. If you alter the
    /// operands of an instruction after insertion the `users` map will be stale.
    /// Rewrite operands through [`replace_all_uses_with`](Self::replace_all_uses_with)
    /// instead.
    pub fn push_insn(&mut self, func: FunctionId, insn: Instruction<'str>) -> InstructionId {
        let args = insn.mnemonic().args();
        let local = self.bodies[func].insns.push(insn);
        let id = InstructionId::new(func, local);
        for arg in args {
            self.bodies[func]
                .users
                .entry(arg)
                .or_default()
                .push(id.localize(func));
        }
        id
    }

    /// Borrows the instruction `id`, routing through its owning function's arena.
    pub fn instruction(&self, id: InstructionId) -> &Instruction<'str> {
        &self.bodies[id.func].insns[id.local]
    }

    /// Mutably borrows the instruction `id`.
    pub fn instruction_mut(&mut self, id: InstructionId) -> &mut Instruction<'str> {
        &mut self.bodies[id.func].insns[id.local]
    }

    /// Whether `id` currently names a live instruction payload.
    pub fn contains_instruction(&self, id: InstructionId) -> bool {
        Into::<usize>::into(id.func) < self.bodies.len()
            && self.bodies[id.func].insns.contains(id.local)
    }

    /// Borrows the basic block `id`.
    pub fn block(&self, id: BlockId) -> &BasicBlock<'str> {
        &self.bodies[id.func].blocks[id.local]
    }

    /// Mutably borrows the basic block `id`.
    pub fn block_mut(&mut self, id: BlockId) -> &mut BasicBlock<'str> {
        &mut self.bodies[id.func].blocks[id.local]
    }

    /// Whether `id` currently names a live block payload.
    pub fn contains_block(&self, id: BlockId) -> bool {
        Into::<usize>::into(id.func) < self.bodies.len()
            && self.bodies[id.func].blocks.contains(id.local)
    }

    /// Borrows the block parameter `id`.
    pub fn block_param(&self, id: BlockParamId) -> &BlockParam<'str> {
        &self.bodies[id.func].params[id.local]
    }

    /// Mutably borrows the block parameter `id`.
    pub fn block_param_mut(&mut self, id: BlockParamId) -> &mut BlockParam<'str> {
        &mut self.bodies[id.func].params[id.local]
    }

    /// Whether `id` currently names a live block-parameter payload.
    pub fn contains_block_param(&self, id: BlockParamId) -> bool {
        Into::<usize>::into(id.func) < self.bodies.len()
            && self.bodies[id.func].params.contains(id.local)
    }

    /// Borrows the CFG edge `id`, stored in function `func`'s edge arena.
    pub fn edge(&self, func: FunctionId, id: EdgeId) -> &EdgeData {
        &self.bodies[func].edges[id]
    }

    /// Mutably borrows the CFG edge `id`, stored in function `func`'s edge arena.
    pub fn edge_mut(&mut self, func: FunctionId, id: EdgeId) -> &mut EdgeData {
        &mut self.bodies[func].edges[id]
    }

    /// Returns the instructions that use `value` as an operand, read from
    /// `value`'s owning function. For an SSA def (instruction/param) that is the
    /// complete user set (all uses are intra-function). For a shared value
    /// (literal/bytes/varnode) there is no single owner, so this returns `&[]`.
    pub fn users_of(&self, value: ValueId) -> Vec<InstructionId> {
        match value.owning_function() {
            Some(func) => self.bodies[func].users_of(value),
            None => Vec::new(),
        }
    }

    /// Whether anything uses `value`, without building the user list to ask.
    pub fn has_users(&self, value: ValueId) -> bool {
        match value.owning_function() {
            Some(func) => self.bodies[func].has_users(value),
            None => false,
        }
    }

    pub fn push_block(&mut self, func: FunctionId, block: BasicBlock<'str>) -> BlockId {
        let local = self.bodies[func].blocks.push(block);
        let id = BlockId::new(func, local);
        // A block is born owned by the function whose arena stores it.
        self.bodies[func].roster.push(local);
        id
    }

    pub fn push_block_param(&mut self, func: FunctionId, param: BlockParam<'str>) -> BlockParamId {
        let local = self.bodies[func].params.push(param);
        BlockParamId::new(func, local)
    }

    pub fn push_edge(&mut self, func: FunctionId, edge: EdgeData) -> EdgeId {
        self.bodies[func].edges.push(edge)
    }

    /// Push a function's interface and body in lockstep, returning the shared
    /// [`FunctionId`]. Both registries must always grow together.
    pub fn push_function(
        &mut self,
        interface: crate::value::function::FunctionInterface<'str>,
        body: FunctionBody<'str>,
    ) -> FunctionId {
        let expected = FunctionId::from(self.bodies.len());
        assert_eq!(
            body.id(),
            expected,
            "function body id does not match its registry slot"
        );
        let id = self.bodies.push(body);
        let iid = self.interfaces.push(interface);
        debug_assert_eq!(
            Into::<usize>::into(id),
            Into::<usize>::into(iid),
            "function body/interface registries drifted"
        );
        id
    }

    /// Returns an immutable reference to the varnode mapped to the named
    /// register `id`.
    pub fn get_register(&self, id: RegisterId) -> VarnodeRef<'str, '_> {
        Varnode::from_id(self, self.shared.registers[&id])
    }

    /// Creates a [`Value`](crate::value::Value) representing an integer constant of the given byte width.
    pub fn get_const(&self, value: u64, size: usize) -> LiteralRef<'str, '_> {
        let type_id = self.shared.types.get_or_make_int(size);
        let id = self
            .shared
            .values
            .get_or_make_typed_literal(value, type_id, size);
        LiteralRef::from_id(self, id)
    }

    /// Creates a `bool`-typed constant (`true`/`false`), byte-stored with value
    /// `1`/`0`. This is the only way to mint a `bool` literal.
    pub fn get_bool_const(&self, value: bool) -> LiteralRef<'str, '_> {
        let type_id = self.shared.types.get_or_make_bool();
        let id = self
            .shared
            .values
            .get_or_make_typed_literal(u64::from(value), type_id, 1);
        LiteralRef::from_id(self, id)
    }

    /// Mints a fresh typed **poison** value of the given [`TypeId`](crate::types::TypeId). Never
    /// deduped: each call yields a distinct poison so GVN keeps them in separate
    /// congruence classes (see [`poison`](crate::value::poison)).
    pub fn get_poison(&self, type_id: crate::types::TypeId) -> ValueId {
        ValueId::Poison(self.shared.values.push_poison(type_id))
    }

    /// Creates a typed constant literal.
    ///
    /// Unlike [`get_const`](Self::get_const) this accepts an arbitrary [`TypeId`](crate::types::TypeId),
    /// allowing StackAddress constants (e.g. the stack base) to preserve their
    /// type through constant folding.
    pub fn get_typed_const(
        &self,
        value: u64,
        type_id: crate::types::TypeId,
    ) -> LiteralRef<'str, '_> {
        let size = self.shared.types.size_of(type_id);
        let id = self
            .shared
            .values
            .get_or_make_typed_literal(value, type_id, size);
        LiteralRef::from_id(self, id)
    }

    /// Creates an opaque byte-blob constant from a little-endian, memory-order
    /// byte vector.
    ///
    /// The blob is typed as an `Array(i8, data.len())`. Unlike numeric literals,
    /// byte blobs are **not interned**: every call produces a fresh
    /// [`BytesId`](crate::value::BytesId). Use this for constants wider than a
    /// `u64` (SSE/AVX pools, wide stack/memory reads, coalesced constant stores).
    pub fn get_bytes(&self, data: Vec<u8>) -> crate::value::BytesRef<'str, '_> {
        let i8_ty = self.shared.types.get_or_make_int(1);
        let type_id = self.shared.types.get_or_make_array(i8_ty, data.len());
        self.get_typed_bytes(data, type_id)
    }

    /// Like [`get_bytes`](Self::get_bytes) but stamps the blob with an explicit
    /// array/sequence [`TypeId`](crate::types::TypeId) instead of the default `Array(i8, len)`. Mints
    /// through the `&self` append path (no post-hoc `type_id` write), so a
    /// checked-out function pass reading through a [`BodyView`](crate::value::BodyView) can materialize a
    /// typed constant array without mutable access to the shared registry.
    pub fn get_typed_bytes(
        &self,
        data: Vec<u8>,
        type_id: crate::types::TypeId,
    ) -> crate::value::BytesRef<'str, '_> {
        let id = self
            .shared
            .values
            .bytes
            .push(crate::value::Bytes { data, type_id });
        crate::value::BytesRef::from_id(self, id)
    }

    /// Returns the [`TypeId`](crate::types::TypeId) of any [`ValueId`] in this context.
    ///
    /// Varnodes are typed as `Int(varnode.size())`. Blocks, functions, and other
    /// non-data values return `Int(0)`.
    pub fn type_of(&self, id: ValueId) -> crate::types::TypeId {
        match id {
            ValueId::Literal(lid) => self.shared.values.literals[lid].type_id,
            ValueId::Bytes(bid) => self.shared.values.bytes[bid].type_id,
            ValueId::Instruction(iid) => self.instruction(iid).type_id,
            ValueId::BlockParam(pid) => self.block_param(pid).type_id,
            ValueId::Varnode(vid) => {
                if let Some(&ty) = self.shared.values.varnode_types.get(&vid) {
                    return ty;
                }
                let size = self.shared.values.varnodes[vid].size_bytes();
                self.shared.types.get_or_make_int(size)
            }
            ValueId::Temp(id) => self
                .shared
                .types
                .get_or_make_int(self.bodies[id.func].temps[id.local].size),
            ValueId::Poison(pid) => self.shared.values.poisons[pid].type_id,
            // Exhaustive on purpose: a new ValueId variant must decide its type
            // here rather than silently inheriting the zero-width fallback.
            ValueId::BasicBlock(_) | ValueId::Function(_) => self.shared.types.get_or_make_int(0),
        }
    }

    /// Returns the stored [`TypeId`](crate::types::TypeId) for value kinds that carry one directly.
    ///
    /// Unlike [`Context::type_of`], this never interns fallback integer types,
    /// so it works from immutable formatting and parsing paths. Varnodes,
    /// blocks, and functions return `None`.
    pub fn stored_type_of(&self, id: ValueId) -> Option<crate::types::TypeId> {
        match id {
            ValueId::Literal(lid) => Some(self.shared.values.literals[lid].type_id),
            ValueId::Bytes(bid) => Some(self.shared.values.bytes[bid].type_id),
            ValueId::Instruction(iid) => Some(self.instruction(iid).type_id),
            ValueId::BlockParam(pid) => Some(self.block_param(pid).type_id),
            ValueId::Varnode(vid) => self.shared.values.varnode_types.get(&vid).copied(),
            ValueId::Poison(pid) => Some(self.shared.values.poisons[pid].type_id),
            ValueId::Temp(_) => None,
            ValueId::BasicBlock(_) | ValueId::Function(_) => None,
        }
    }

    /// Gives `varnode` a global type override, replacing the default
    /// `Int(size)`. Used to type ambient register globals — e.g. the `FS_OFFSET`
    /// segment base as `PtrTo<TEB>` — so every use across all functions reads the
    /// richer type. Pass a type whose size matches the varnode's width.
    pub fn set_varnode_type(&mut self, varnode: VarnodeId, type_id: crate::types::TypeId) {
        self.shared.values.varnode_types.insert(varnode, type_id);
    }

    /// Return all instructions that use `value` as an operand.
    ///
    /// For an SSA value (instruction result or block param) this is the complete
    /// user set, read from its owning function. For a shared value
    /// (literal/bytes/varnode) it is `&[]` — those have no owning function and
    /// their uses are tracked per using-function; use
    /// [`users_across_functions`](Self::users_across_functions) to find them.
    pub fn users(&self, value: impl Into<ValueId>) -> Vec<InstructionId> {
        self.users_of(value.into())
    }

    /// Every instruction across all functions that uses `value` as an operand.
    /// Unlike [`users`](Self::users) this scans every function, so it answers a
    /// shared value (literal/bytes/varnode) whose uses span functions. Off the
    /// hot path (allocates); prefer [`users`](Self::users) for an SSA value.
    pub fn users_across_functions(&self, value: impl Into<ValueId>) -> Vec<InstructionId> {
        let value = value.into();
        if value.owning_function().is_some() {
            self.users_of(value)
        } else {
            self.functions().flat_map(|f| f.users_of(value)).collect()
        }
    }

    // ---- module read/mint surface (context-split stage 5b-ii Pin A) ----------
    //
    // Module-scope read accessors and type-minting verbs, mirrored on the
    // checked-out `BodyMut` pass host, so the module walker and the
    // module-scope GVN sub-passes read/mint over `&mut Context` directly.
    // `function{,_mut}` alias the existing `body{,_mut}`.

    /// A `Copy` read view over the whole module (for the mutation refs' reads).
    pub fn view(&self) -> ModuleView<'_, 'str> {
        ModuleView::new(self)
    }
    /// The module's shared IR state ([`Shared`]) — the module-path twin of
    /// [`ModuleView::shared`]/[`BodyMut::shr`](crate::value::util::body_mut::BodyMut::shr), so a `&mut Context` module walker and
    /// a checked-out pass spell shared-data reads identically (context-split
    /// stage 5b-ii item #1).
    pub fn shr(&self) -> &Shared<'str> {
        &self.shared
    }
    /// The owning function's storage (read). Alias of [`body`](Self::body).
    pub fn function(&self, f: FunctionId) -> &FunctionBody<'str> {
        &self.bodies[f]
    }
    /// The owning function's storage (write). Alias of [`body_mut`](Self::body_mut).
    pub fn function_mut(&mut self, f: FunctionId) -> &mut FunctionBody<'str> {
        &mut self.bodies[f]
    }

    /// A read [`BlockRef`] over `id`, module-routed.
    pub fn block_ref(&self, id: BlockId) -> BlockRef<'str, '_, ModuleView<'_, 'str>> {
        self.view().block_ref(id)
    }
    /// A read [`InstructionRef`] over `id`, module-routed.
    pub fn insn_ref(&self, id: InstructionId) -> InstructionRef<'str, '_, ModuleView<'_, 'str>> {
        self.view().insn_ref(id)
    }
    /// A read [`BlockParamRef`] over `id`.
    pub fn param_ref(&self, id: BlockParamId) -> BlockParamRef<'str, '_, ModuleView<'_, 'str>> {
        self.view().param_ref(id)
    }
    /// A read [`FunctionRef`] over `id`, module-routed.
    pub fn function_ref(&self, id: FunctionId) -> FunctionRef<'str, '_, ModuleView<'_, 'str>> {
        self.view().function_ref(id)
    }

    /// Mint an `Int(size)`-typed instruction with `mnemonic` into `func`'s arena.
    pub fn push_mnemonic(
        &mut self,
        func: FunctionId,
        mnemonic: Mnemonic,
        size: usize,
    ) -> InstructionId {
        let type_id = self.shared.types.get_or_make_int(size);
        self.push_insn(func, Instruction::new(type_id, mnemonic))
    }

    /// Mint an instruction with `mnemonic` and explicit result `type_id` into
    /// `func`'s arena.
    pub fn push_mnemonic_with_type(
        &mut self,
        func: FunctionId,
        mnemonic: Mnemonic,
        type_id: crate::types::TypeId,
    ) -> InstructionId {
        self.push_insn(func, Instruction::new(type_id, mnemonic))
    }

    /// Mint a fresh empty block into `func`'s arena, owned (arena membership) and
    /// rostered. The module-scope mint of a fresh empty block.
    pub fn make_block(&mut self, func: FunctionId) -> BlockId {
        self.push_block(func, BasicBlock::detached())
    }

    /// Register `name` for `id` in the table that owns its kind (function-local
    /// for block/insn/param/Temp, global otherwise).
    pub fn register_local_name(
        &mut self,
        id: ValueId,
        name: Cow<'str, str>,
        old_name: Option<&str>,
    ) -> Result<()> {
        let existing = match id.name_scope_function() {
            Some(func) => self
                .function(func)
                .names
                .get(&name)
                .map(|id| id.qualify(func)),
            None => self.get_named(&name),
        };
        if let Some(existing) = existing {
            return if existing == id {
                Ok(())
            } else {
                Err(Error::spanless(ErrorTy::DuplicateName(name.to_string())))
            };
        }
        match id.name_scope_function() {
            Some(func) => self
                .function_mut(func)
                .names
                .register(name, id.localize(func), old_name),
            None => self.update_name(name, id, old_name),
        }
    }

    /// Registers an address in a caller-owned construction index.
    pub(crate) fn set_address_indexed(
        &mut self,
        addresses: &mut crate::address_index::AddressIndex,
        addr: u64,
        id: ValueId,
    ) -> crate::error::Result<()> {
        let target = match id {
            ValueId::Function(id) => crate::address_index::AddressTarget::Function(id),
            ValueId::BasicBlock(id) => crate::address_index::AddressTarget::Block(id),
            _ => unreachable!("only functions and blocks have module addresses"),
        };
        addresses.register(self, addr, target)
    }

    /// Changes the name of a value, in the name table that owns its kind
    /// (function-local for block/instruction/param/Temp, global otherwise).
    pub fn update_name(
        &mut self,
        name: Cow<'str, str>,
        id: ValueId,
        old_name: Option<&str>,
    ) -> Result<()> {
        match id.name_scope_function() {
            Some(func) => self.bodies[func]
                .names
                .register(name, id.localize(func), old_name),
            None => self.shared.name_map.register(name, id, old_name),
        }
    }

    /// Resolve `name` in the table that owns `id`'s kind (function-local for
    /// block/instruction/param/Temp, global otherwise). Used by the rename path to
    /// check for a conflict in the correct namespace, and by passes that mint a
    /// unique name for a known SSA value.
    pub fn get_named_in_scope(&self, id: ValueId, name: &str) -> Option<ValueId> {
        match id.name_scope_function() {
            Some(func) => self.bodies[func].names.get(name).map(|id| id.qualify(func)),
            None => self.shared.name_map.get(name),
        }
    }

    /// Remove `name` from the name map, keeping the [`get_unique_name`](crate::context::Context::get_unique_name) suffix
    /// hint exact: if `name` is a generated `base_<n>` suffix, lower `base`'s hint
    /// so the freed suffix is reconsidered on the next call (a naive first-free
    /// scan would reuse it, and the hint must not skip it). Un-suffixed names are
    /// Attempts to get a value ID by its *global* name (function/varnode/space/
    /// p-code/bytes). Block/instruction/param/Temp names are function-scoped and are
    /// resolved through their owning [`FunctionBody`] (see [`NameTable`]); this
    /// returns `None` for them.
    pub fn get_named(&self, name: &str) -> Option<ValueId> {
        self.shared.name_map.get(name)
    }

    /// Gets a unique **global** name (functions, varnodes, spaces, …), appending
    /// a numeric suffix until free. For a block/instruction/param/Temp name, use
    /// [`get_unique_name_in`](Self::get_unique_name_in) so uniqueness is checked
    /// against the owning function's table.
    pub fn get_unique_name(&mut self, name: Cow<'str, str>) -> Cow<'str, str> {
        self.shared.name_map.unique(name)
    }

    /// Gets a unique name within `func`'s function-local name table (for block,
    /// instruction, block-param, and Temp names). Two functions may thus reuse the same
    /// name independently.
    pub fn get_unique_name_in(&mut self, func: FunctionId, name: Cow<'str, str>) -> Cow<'str, str> {
        self.bodies[func].names.unique(name)
    }
}

/// A name → value reverse map with amortized unique-name minting.
///
/// The context keeps one **global** table for module-scoped values (functions,
/// varnodes, spaces, p-code ops, byte blobs); each [`FunctionBody`]
/// keeps its **own** table for its block/instruction/param/Temp names. Keeping those
/// namespaces independent is a prerequisite for running function passes in
/// parallel: a worker mints names against its function's table with no global
/// lock and no cross-function collisions. Two functions may each name a block
/// `loop` — they render correctly because a value's own `name` field is the
/// source of truth; this table only enforces uniqueness and resolves by name.
#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct NameTable<'str, Id = ValueId> {
    /// name → the value that holds it.
    map: HashMap<Cow<'str, str>, Id>,
    /// Per-base "next suffix to try" lower-bound hints for [`unique`](Self::unique),
    /// so probing resumes instead of rescanning from `0`. A derived cache: rides
    /// through `clone` but is not serialized (see [`Context::get_unique_name`]).
    #[serde(skip)]
    suffix_hint: HashMap<String, u32>,
}

impl<Id> Default for NameTable<'_, Id> {
    fn default() -> Self {
        Self {
            map: HashMap::default(),
            suffix_hint: HashMap::default(),
        }
    }
}

impl<'str, Id: Copy + Eq> NameTable<'str, Id> {
    pub(crate) fn entries(&self) -> impl Iterator<Item = (&str, Id)> + '_ {
        self.map.iter().map(|(name, &value)| (name.as_ref(), value))
    }

    /// The value currently holding `name`, if any.
    pub fn get(&self, name: &str) -> Option<Id> {
        self.map.get(name).copied()
    }

    /// Whether `name` is taken.
    pub fn contains(&self, name: &str) -> bool {
        self.map.contains_key(name)
    }

    /// Register `name` for `id`, forgetting `old_name` first. Errors if `name`
    /// is already taken (callers pre-check via [`get`](Self::get), so this only
    /// fires defensively).
    pub fn register(&mut self, name: Cow<'str, str>, id: Id, old_name: Option<&str>) -> Result<()> {
        if let Some(old_name) = old_name {
            self.forget(old_name);
        }
        match self.map.insert(name.clone(), id) {
            Some(_) => Err(Error::spanless(ErrorTy::DuplicateName(name.to_string()))),
            None => Ok(()),
        }
    }

    /// Remove `name`, keeping the [`unique`](Self::unique) suffix hint exact: if
    /// `name` is a generated `base_<n>` suffix, lower `base`'s hint so the freed
    /// suffix is reconsidered next time.
    pub fn forget(&mut self, name: &str) {
        self.map.remove(name);
        if let Some((base, suffix)) = split_generated_suffix(name)
            && let Some(hint) = self.suffix_hint.get_mut(base)
        {
            *hint = (*hint).min(suffix);
        }
    }

    /// A free name derived from `name`: the bare name if untaken, else the first
    /// free `name_<n>`. Resumes suffix probing from a cached lower bound so
    /// minting many like-named values stays ~O(1) amortized; the chosen suffix is
    /// identical to a naive first-free scan from `1`.
    pub fn unique(&mut self, name: Cow<'str, str>) -> Cow<'str, str> {
        use std::fmt::Write as _;

        if !self.map.contains_key(&name) {
            return name;
        }
        let base: &str = &name;
        let mut suffix = self.suffix_hint.get(base).copied().unwrap_or(1).max(1);
        let mut unique_name = format!("{base}_{suffix}");
        while self.map.contains_key(unique_name.as_str()) {
            suffix += 1;
            unique_name.clear();
            let _ = write!(unique_name, "{base}_{suffix}");
        }
        self.suffix_hint.insert(base.to_string(), suffix);
        Cow::Owned(unique_name)
    }
}

/// Split a generated unique name into its base and numeric suffix, i.e. the
/// inverse of the `format!("{base}_{suffix}")` in [`NameTable::unique`]:
/// `"tmp_7"` → `Some(("tmp", 7))`. Returns `None` for names with no `_<digits>`
/// tail (a bare base, or a name whose tail is empty/non-numeric/overflows).
fn split_generated_suffix(name: &str) -> Option<(&str, u32)> {
    let (base, digits) = name.rsplit_once('_')?;
    if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    Some((base, digits.parse().ok()?))
}

/// Rebind pointer provenance carried by a result/parameter type when its
/// temporary space was cloned into another function arena.
fn remap_rehomed_type(
    ctx: &Context<'_>,
    type_id: crate::types::TypeId,
    target: FunctionId,
    temp_space_map: &HashMap<TempSpaceId, TempSpaceId>,
) -> crate::types::TypeId {
    let Some(MemorySpaceId::Temp(old_space)) = ctx.shared.types.space_of(type_id) else {
        return type_id;
    };
    let Some(&new_space) = temp_space_map.get(&old_space) else {
        debug_assert_eq!(
            old_space.func, target,
            "rehome: result type references unmapped foreign temporary space {old_space:?}"
        );
        return type_id;
    };
    ctx.shared.types.get_or_make_space_address(
        ctx.shared.types.size_of(type_id),
        MemorySpaceId::Temp(new_space),
    )
}

/// Rebind the explicit memory space stored by load/store mnemonics. Operand
/// remapping does not see this field because it is not a `LocalValueId`.
fn remap_rehomed_memory_space(
    mnemonic: &mut Mnemonic,
    old_func: FunctionId,
    target: FunctionId,
    temp_space_map: &HashMap<TempSpaceId, TempSpaceId>,
) {
    let remap = |space: &mut LocalMemorySpaceId| {
        let LocalMemorySpaceId::Temp(old_local) = *space else {
            return;
        };
        let old = TempSpaceId::new(old_func, old_local);
        if let Some(&new) = temp_space_map.get(&old) {
            *space = LocalMemorySpaceId::Temp(new.local);
        } else {
            debug_assert_eq!(
                old_func, target,
                "rehome: mnemonic references unmapped foreign temporary space {old:?}"
            );
        }
    };
    match mnemonic {
        Mnemonic::Load(load) => remap(&mut load.space),
        Mnemonic::Store(store) => remap(&mut store.space),
        _ => {}
    }
}

/// Retarget a terminator's static block targets through `block_map` (used by
/// [`Context::rehome_owned_blocks`] to point relocated branches at the clones).
/// Value operands are handled separately via [`Mnemonic::replace_value`]; this
/// only rewrites the block targets, which are not value operands.
///
/// Targets are stored as bare body-local indices. A freshly cloned instruction
/// still holds its *source* block's local index (`old_func`-relative, strict IR
/// locality ⇒ a terminator's target shares its arena); this qualifies with
/// `old_func`, looks the full [`BlockId`] up in `block_map`, and re-localizes the
/// mapped clone against its new arena `new_func`.
/// Re-point a relocated block's symbolic block literal at the block's clone.
///
/// [`SymbolicRef::Block`] carries an *absolute* [`BlockId`], so it is the one
/// construct in the IR that can name a block in another function — every other
/// operand and terminator target is a bare body-local id qualified by its
/// reader's own arena, making a cross-function reference unrepresentable. A
/// re-home therefore has to rewrite these by hand: phase 5 deletes the originals,
/// so a literal left naming the pre-move block dangles into a deleted arena slot.
///
/// Returns `None` (leave the operand alone) unless `arg` is a symbolic block
/// literal whose target actually moved. Symbolic literals are not intern-cached
/// (see [`LiteralInterner::push_literal`]), so minting a replacement cannot alias
/// another user of the original.
///
/// [`LiteralInterner::push_literal`]: crate::value::interner::LiteralInterner::push_literal
fn remap_symbolic_block_literal(
    literals: &crate::value::interner::LiteralInterner,
    arg: crate::value::LocalValueId,
    block_map: &HashMap<BlockId, BlockId>,
) -> Option<crate::value::LocalValueId> {
    use crate::value::literal::SymbolicRef;

    let crate::value::LocalValueId::Literal(lid) = arg else {
        return None;
    };
    let literal = literals[lid].clone();
    let Some(SymbolicRef::Block(old_block)) = literal.symbolic else {
        return None;
    };
    let &new_block = block_map.get(&old_block)?;
    let new_lit = literals.push_literal(crate::value::literal::Literal {
        symbolic: Some(SymbolicRef::Block(new_block)),
        ..literal
    });
    Some(crate::value::LocalValueId::Literal(new_lit))
}

fn remap_block_targets(
    mnemonic: &mut Mnemonic,
    old_func: FunctionId,
    new_func: FunctionId,
    block_map: &HashMap<BlockId, BlockId>,
) {
    let remap = |b: &mut crate::value::LocalBlockId| {
        if let Some(&new) = block_map.get(&BlockId::new(old_func, *b)) {
            *b = new.localize(new_func);
        }
    };
    match mnemonic {
        Mnemonic::Branch(branch) => remap(&mut branch.target),
        Mnemonic::CBranch(cbranch) => {
            remap(&mut cbranch.success_block);
            remap(&mut cbranch.failure_block);
        }
        _ => {}
    }
}

impl Display for Context<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.functions().try_for_each(|fun| fun.fmt(f))?;

        self.blocks()
            .filter(|block| block.parent().is_none())
            .try_for_each(|block| block.fmt(f))
    }
}

pub struct FunctionIter<'str, 'ctx> {
    ctx: &'ctx Context<'str>,
    inner: registry::Iter<'ctx, FunctionId, FunctionBody<'str>>,
}

impl<'str, 'ctx> Iterator for FunctionIter<'str, 'ctx> {
    type Item = FunctionRef<'str, 'ctx>;

    fn next(&mut self) -> Option<Self::Item> {
        let ctx = self.ctx;
        self.inner.next().map(|f| FunctionRef::from_id(ctx, f.id))
    }
}

impl<'str, 'ctx> IntoIterator for &'ctx Context<'str> {
    type Item = FunctionRef<'str, 'ctx>;
    type IntoIter = FunctionIter<'str, 'ctx>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::value::{
        BasicBlock, FunctionBody, ValueId,
        insn::{Binary, Binop, Call, Callee, IntBinop, Load, Mnemonic},
    };
    use wazabin_qcode_macro::qcode;

    fn make_fn_with_blocks(ctx: &mut Context<'static>, name: &'static str, n: usize) -> FunctionId {
        // The function must exist before its blocks so they are born into its arena.
        let f = FunctionBody::make(ctx, name.into()).unwrap().id;
        for _ in 0..n {
            BasicBlock::make(ctx, f);
        }
        f
    }

    #[test]
    #[should_panic(expected = "cannot reuse a block stored in another function arena")]
    fn get_or_make_block_rejects_foreign_storage_at_address() {
        let mut ctx = Context::new();
        let a = FunctionBody::make(&mut ctx, "address_owner".into())
            .unwrap()
            .id;
        let b = FunctionBody::make(&mut ctx, "address_requester".into())
            .unwrap()
            .id;
        BasicBlock::make(&mut ctx, a).with_address(0x1000);

        ctx.get_or_make_block(0x1000, b);
    }

    #[test]
    #[should_panic(expected = "cannot create a block at an address owned by another function")]
    fn get_or_make_block_rejects_foreign_function_address_without_root() {
        let mut ctx = Context::new();
        FunctionBody::make_at_addr(&mut ctx, 0x1000, None);
        let requester = FunctionBody::make(&mut ctx, "address_requester".into())
            .unwrap()
            .id;

        ctx.get_or_make_block(0x1000, requester);
    }

    #[test]
    fn functions_iter_yields_all_functions() {
        let mut ctx = Context::new();
        let alpha = make_fn_with_blocks(&mut ctx, "alpha", 1);
        let beta = make_fn_with_blocks(&mut ctx, "beta", 1);

        let names: Vec<_> = ctx.functions().map(|f| f.name().to_string()).collect();
        assert!(names.contains(&"alpha".to_string()));
        assert!(names.contains(&"beta".to_string()));
        assert_eq!(names.len(), 2);
        assert_eq!(ctx.function_ids(), vec![alpha, beta]);
        assert_eq!(ctx.function_ids().len(), ctx.interfaces.len());
    }

    #[test]
    fn body_view_reads_match_module_reads() {
        use crate::value::{BodyView, FunctionId, FunctionRef, ModuleView, QCodeView};

        let mut ctx = Context::new();
        qcode!(
            ctx,
            "
            fn foo:
                <bb1>
                    if i8 1 goto <bb2> else goto <bb3>;
                <bb2>
                    goto <bb3>;
                <bb3>
                    return at 0;
            "
        );
        let fid = FunctionBody::from_name(&ctx, "foo").unwrap().id();
        let fid = ValueId::as_function(fid).unwrap();

        // A structural snapshot read entirely through a `QCodeView` — function name,
        // and per (address-then-index ordered) block: name, successor block names,
        // instruction opcodes, and param count. Both hosts route through the same
        // ref code, so equal snapshots prove the `Checked` routing.
        type Snap = (String, Vec<(String, Vec<String>, Vec<String>, usize)>);
        fn snapshot<'a, 'str: 'a>(view: impl QCodeView<'a, 'str>, fid: FunctionId) -> Snap {
            let f = FunctionRef::new(view, fid);
            let blocks = f
                .blocks()
                .map(|b| {
                    let name = b.name().unwrap_or("?").to_string();
                    let mut succ: Vec<String> = b
                        .successors()
                        .map(|(_, s)| BlockRef::new(view, s).name().unwrap_or("?").to_string())
                        .collect();
                    succ.sort();
                    let ops: Vec<String> =
                        b.instructions().map(|i| i.opcode().to_string()).collect();
                    (name, succ, ops, b.num_params())
                })
                .collect();
            (f.name().to_string(), blocks)
        }

        let module_snap = snapshot(ModuleView::new(&ctx), fid);
        assert!(!module_snap.1.is_empty(), "sanity: foo has blocks");

        // A `BodyView` over the body borrowed in place must read identically to
        // the module path — both route through the same ref code.
        let checked = BodyView::new(&ctx.bodies[fid], &ctx.shared, &ctx.interfaces);
        let checked_snap = snapshot(checked, fid);
        assert_eq!(
            module_snap, checked_snap,
            "reads through BodyView must match the module reads"
        );
    }

    #[test]
    fn body_mut_mut_matches_module_mut() {
        use crate::value::{
            BlockParam, FunctionId, FunctionRef, InstructionId, Renameable,
            block::BlockId,
            block_param::BlockParamId,
            util::{base_ref::BaseRef, body_mut::BodyMut},
        };

        fn build(mut ctx: &mut Context<'static>) -> (FunctionId, BlockId, BlockId, InstructionId) {
            qcode!(
                ctx,
                "
                varnode i64 x;
                fn foo:
                    <entry>
                        %a = load(x:8, &x);
                        %b = load(x:8, &x);
                        goto <bb1>;
                    <bb1>
                        return at %a;
                "
            );
            let fid = foo;
            let entry = FunctionRef::from_id(ctx, fid).root().unwrap().id;
            let bb1 = FunctionRef::from_id(ctx, fid)
                .blocks()
                .map(|b| b.id)
                .find(|&b| b != entry)
                .unwrap();
            let insns = BasicBlock::from_id(ctx, entry).instruction_ids();
            (fid, entry, bb1, insns[0])
        }

        // Give `bb1` a parameter to resize; identical setup on both paths.
        fn add_param(ctx: &mut Context<'static>, bb1: BlockId) -> BlockParamId {
            BasicBlock::from_id_mut(ctx, bb1).push_param(8).id
        }

        // Structural snapshot: per block, (name, comment, param sizes, opcodes,
        // sorted successor names).
        type MSnap = Vec<(String, Option<String>, Vec<usize>, Vec<String>, Vec<String>)>;
        fn snap(ctx: &Context, fid: FunctionId) -> MSnap {
            FunctionRef::from_id(ctx, fid)
                .blocks()
                .map(|b| {
                    let name = b.name().unwrap_or("?").to_string();
                    let comment = b.comment().map(str::to_string);
                    let params: Vec<usize> = b.params().map(|p| p.size()).collect();
                    let ops: Vec<String> =
                        b.instructions().map(|i| i.opcode().to_string()).collect();
                    let mut succ: Vec<String> = b
                        .successors()
                        .map(|(_, s)| {
                            BasicBlock::from_id(ctx, s)
                                .name()
                                .unwrap_or("?")
                                .to_string()
                        })
                        .collect();
                    succ.sort();
                    (name, comment, params, ops, succ)
                })
                .collect()
        }

        // ---- (a) mutate on the module directly (the reference behaviour) ------
        let mut ctx_a = Context::new();
        let (fid, entry, bb1, a) = build(&mut ctx_a);
        let param = add_param(&mut ctx_a, bb1);
        let b = BasicBlock::from_id(&ctx_a, entry).instruction_ids()[1];
        BasicBlock::from_id_mut(&mut ctx_a, entry).set_comment(Some("c".into()));
        BasicBlock::from_id_mut(&mut ctx_a, entry)
            .rename("start".into())
            .unwrap();
        let e = ctx_a.add_cfg_edge(entry, bb1);
        ctx_a.remove_cfg_edge(entry.func, e);
        ctx_a.replace_instruction(a, ValueId::Instruction(b));
        BlockParam::from_id_mut(&mut ctx_a, param).set_size(4);
        let snap_a = snap(&ctx_a, fid);

        // ---- (b) the same mutations via a checked-out host -------------------
        let mut ctx_b = Context::new();
        let (fid_b, entry_b, bb1_b, a_b) = build(&mut ctx_b);
        let param_b = add_param(&mut ctx_b, bb1_b);
        let b_b = BasicBlock::from_id(&ctx_b, entry_b).instruction_ids()[1];

        {
            let mut host = BodyMut::new(&mut ctx_b.bodies[fid_b], &ctx_b.shared, &ctx_b.interfaces);
            let mut r = BaseRef::new(host.reborrow(), entry_b);
            r.set_comment(Some("c".into()));
            let mut r = BaseRef::new(host.reborrow(), entry_b);
            r.rename("start".into()).unwrap();
            let e = host.add_cfg_edge(entry_b, bb1_b);
            host.remove_cfg_edge(e);
            host.replace_instruction(a_b, ValueId::Instruction(b_b));
            let mut r = BaseRef::new(host.reborrow(), param_b);
            r.set_size(4);
        }
        let snap_b = snap(&ctx_b, fid_b);

        assert_eq!(
            snap_a, snap_b,
            "mutations through a pass-scoped host must match the module-path mutations"
        );
    }

    #[test]
    fn into_iterator_for_context_matches_functions() {
        let mut ctx = Context::new();
        make_fn_with_blocks(&mut ctx, "f1", 1);
        make_fn_with_blocks(&mut ctx, "f2", 1);

        let via_method: Vec<_> = ctx.functions().map(|f| f.id()).collect();
        let via_into: Vec<_> = (&ctx).into_iter().map(|f| f.id()).collect();
        assert_eq!(via_method, via_into);
    }

    #[test]
    fn blocks_iter_yields_all_blocks() {
        let mut ctx = Context::new();
        make_fn_with_blocks(&mut ctx, "g", 3);

        let count = ctx.blocks().count();
        assert_eq!(count, 3);
    }

    #[test]
    fn instructions_iter_yields_all_instructions() {
        let mut ctx = Context::new();

        qcode!(
            ctx,
            "
            varnode i64 ptr;

            <block>
                store(ptr:8, &ptr <- i64 0x1234);
                return at ptr;
            "
        );

        let count = ctx.instructions().count();
        assert!(count >= 1, "expected at least one instruction, got {count}");
    }

    #[test]
    fn move_insn_before_preserves_id_and_supports_arbitrary_anchors() {
        let mut ctx = Context::new();
        qcode!(
            ctx,
            "
            fn f:
                <source>
                    %a = i64 0x1 + i64 0x2;
                    %free = i64 0x5 + i64 0x6;
                    goto <target>;
                <target>
                    %b = i64 0x3 + i64 0x4;
                    %consumer = %a + %b;
                    return %consumer;
            "
        );

        assert!(ctx.users(a).contains(&consumer));
        ctx.move_insn_before(a, b);

        assert!(ctx.contains_instruction(a), "moving keeps the ID live");
        assert_eq!(ctx.get_insn(a).parent().map(|block| block.id), Some(target));
        assert!(
            !BasicBlock::from_id(&ctx, source)
                .instruction_ids()
                .contains(&a)
        );
        assert_eq!(
            BasicBlock::from_id(&ctx, target).instruction_ids()[..3],
            [a, b, consumer]
        );
        assert!(
            ctx.users(a).contains(&consumer),
            "moving preserves use-map entries"
        );

        // The anchor may be any instruction, including one in the same block.
        ctx.move_insn_before(b, a);
        assert_eq!(
            BasicBlock::from_id(&ctx, target).instruction_ids()[..3],
            [b, a, consumer]
        );

        // A terminator is also a valid destination anchor.
        let return_id = *BasicBlock::from_id(&ctx, target)
            .instruction_ids()
            .last()
            .unwrap();
        ctx.move_insn_before(free, return_id);
        assert_eq!(
            BasicBlock::from_id(&ctx, target).instruction_ids()[..4],
            [b, a, consumer, free]
        );
    }

    #[test]
    fn remove_instruction_removes_from_block() {
        let mut ctx = Context::new();
        qcode!(
            ctx,
            "
            varnode i64 x;
            <block>
                %a = load(x:8, &x);
                %b = load(x:8, &x);
                return at %a;
            "
        );
        let block_ref = BasicBlock::from_id(&ctx, block);
        let ids = block_ref.instruction_ids();
        let load_a = ids[0];
        let original_len = ids.len();

        ctx.remove_instruction(load_a);

        let remaining = BasicBlock::from_id(&ctx, block).instruction_ids();
        assert_eq!(remaining.len(), original_len - 1);
        assert!(!remaining.contains(&load_a));
    }

    #[test]
    fn remove_instruction_drops_payload() {
        let mut ctx = Context::new();
        qcode!(
            ctx,
            "
            varnode i64 x;
            <block>
                %a = load(x:8, &x);
                return at %a;
            "
        );
        let load_id = BasicBlock::from_id(&ctx, block).instruction_ids()[0];

        ctx.remove_instruction(load_id);

        assert!(!ctx.contains_instruction(load_id));
    }

    #[test]
    fn remove_instruction_frees_name() {
        let mut ctx = Context::new();
        qcode!(
            ctx,
            "
            varnode i64 x;
            <block>
                %a = load(x:8, &x);
                return at %a;
            "
        );
        let load_id = BasicBlock::from_id(&ctx, block).instruction_ids()[0];
        // Instruction names are function-scoped, so resolve in the owner's table.
        assert!(
            ctx.get_named_in_scope(load_id.into(), "a").is_some(),
            "name should be in map before removal"
        );

        ctx.remove_instruction(load_id);

        assert!(
            ctx.get_named_in_scope(load_id.into(), "a").is_none(),
            "name should be gone after removal"
        );
        assert!(!ctx.contains_instruction(load_id));
    }

    #[test]
    fn remove_instruction_frees_name_for_reuse() {
        let mut ctx = Context::new();
        qcode!(
            ctx,
            "
            varnode i64 x;
            <block>
                %a = load(x:8, &x);
                return at %a;
            "
        );
        let load_id = BasicBlock::from_id(&ctx, block).instruction_ids()[0];

        ctx.remove_instruction(load_id);

        // Building another instruction named %a should succeed now.
        qcode!(
            ctx,
            "
            varnode i64 y;
            <block2>
                %a = load(y:8, &y);
                return at %a;
            "
        );
        let a2 = BasicBlock::from_id(&ctx, block2).instruction_ids()[0];
        assert!(
            ctx.get_named_in_scope(a2.into(), "a").is_some(),
            "name should be reusable after removal"
        );
    }

    #[test]
    fn remove_instruction_updates_users_map() {
        let mut ctx = Context::new();
        qcode!(
            ctx,
            "
            varnode i64 x;
            <block>
                %a = load(x:8, &x);
                %b = %a + i64 1;
                return at %b;
            "
        );
        let ids = BasicBlock::from_id(&ctx, block).instruction_ids();
        let load_id = ids[0];
        let add_id = ids[1];

        assert!(
            ctx.users(load_id).contains(&add_id),
            "add should be a user of load before removal"
        );

        ctx.remove_instruction(add_id);

        assert!(
            ctx.users(load_id).is_empty(),
            "load should have no users after add is removed"
        );
    }

    #[test]
    fn removed_instruction_is_absent_and_not_iterated() {
        // Stable IDs survive payload compaction, while the removed payload itself must
        // disappear so stale operands never pollute a whole-program scan.
        // Regression: a removed ram load kept showing up in the alias pass's pointer
        // scan, faking a "pointer used in two spaces" invariant break.
        let mut ctx = Context::new();
        qcode!(
            ctx,
            "
            varnode i64 x;
            <block>
                %a = load(x:8, &x);
                %dead = %a + i64 1;
                return at i64 0;
            "
        );
        let ids = BasicBlock::from_id(&ctx, block).instruction_ids();
        let dead_id = ids[1]; // %dead, unused

        assert!(
            ctx.instructions().any(|i| i.id == dead_id),
            "the instruction is iterated while live"
        );

        ctx.remove_instruction(dead_id);

        assert!(!ctx.contains_instruction(dead_id));
        assert!(
            !ctx.instructions().any(|i| i.id == dead_id),
            "a deleted instruction must not be yielded by ctx.instructions()"
        );
    }

    #[test]
    fn replace_instruction_mnemonic_rewrites_callind_users() {
        let mut ctx = Context::new();
        qcode!(
            ctx,
            "
            varnode i64 ptr;
            <block>
                call [ptr];
            "
        );
        let call_id = BasicBlock::from_id(&ctx, block).instruction_ids()[0];
        let ptr = match ctx.get_insn(call_id).mnemonic() {
            Mnemonic::CallInd(call) => call.ptr.qualify(call_id.func),
            other => panic!("expected CallInd, got {other:?}"),
        };
        // `ptr` is a shared varnode, so query its uses across functions.
        assert_eq!(ctx.users_across_functions(ptr), vec![call_id]);

        let target = FunctionBody::make(&mut ctx, "target".into()).unwrap().id;
        ctx.replace_instruction_mnemonic(
            call_id,
            Mnemonic::Call(Call {
                target: Callee::Real(target),
                args: vec![],
                clobbers: vec![],
                tag: Default::default(),
            }),
        );

        assert!(
            ctx.users_across_functions(ptr).is_empty(),
            "old indirect pointer should no longer list the rewritten call"
        );
        assert!(matches!(
            ctx.get_insn(call_id).mnemonic(),
            Mnemonic::Call(Call {
                target: actual,
                args,
                ..
            }) if *actual == Callee::Real(target) && args.is_empty()
        ));
    }

    #[test]
    fn users_across_functions_keeps_ssa_users_in_the_owning_function() {
        let mut ctx = Context::new();
        qcode!(
            ctx,
            "
            fn f:
                <f_entry>
                    %fx = i64 1 + i64 2;
                    %fuse = %fx + i64 3;
                    return at %fuse;
            fn g:
                <g_entry>
                    %gx = i64 4 + i64 5;
                    %guse = %gx + i64 6;
                    return at %guse;
            "
        );
        let f_ids = BasicBlock::from_id(&ctx, f_entry).instruction_ids();
        let g_ids = BasicBlock::from_id(&ctx, g_entry).instruction_ids();
        assert_eq!(
            f_ids[0].local, g_ids[0].local,
            "precondition: arena-local ids collide"
        );
        assert_eq!(
            ctx.users_across_functions(ValueId::Instruction(f_ids[0])),
            vec![f_ids[1]],
            "an SSA query must not pick up the same local key from another function"
        );
    }

    #[test]
    fn replace_instruction_mnemonic_moves_operand_users() {
        let mut ctx = Context::new();
        qcode!(
            ctx,
            "
            varnode i64 x;
            varnode i64 y;
            <block>
                %a = load(x:8, x);
                return at %a;
            "
        );
        let load_id = BasicBlock::from_id(&ctx, block).instruction_ids()[0];
        let old_ptr = ValueId::Varnode(x);
        let new_ptr = ValueId::Varnode(y);
        // Varnodes are shared values, so query their uses across functions.
        assert_eq!(ctx.users_across_functions(old_ptr), vec![load_id]);
        assert!(ctx.users_across_functions(new_ptr).is_empty());

        ctx.replace_instruction_mnemonic(
            load_id,
            Mnemonic::Load(Load {
                space: ctx.shared.default_space.into(),
                ptr: new_ptr.localize(load_id.func),
                size: 8,
            }),
        );

        assert!(ctx.users_across_functions(old_ptr).is_empty());
        assert_eq!(ctx.users_across_functions(new_ptr), vec![load_id]);
    }

    #[test]
    fn replace_instruction_mnemonic_tracks_repeated_operands() {
        let mut ctx = Context::new();
        qcode!(
            ctx,
            "
            varnode i64 x;
            varnode i64 y;
            <block>
                %a = load(x:8, x);
                return at %a;
            "
        );
        let load_id = BasicBlock::from_id(&ctx, block).instruction_ids()[0];
        let old_ptr = ValueId::Varnode(x);
        let new_arg = ValueId::Varnode(y);

        ctx.replace_instruction_mnemonic(
            load_id,
            Mnemonic::Binop(Binary {
                op: Binop::Int(IntBinop::Add),
                lhs: new_arg.localize(load_id.func),
                rhs: new_arg.localize(load_id.func),
            }),
        );

        assert!(ctx.users_across_functions(old_ptr).is_empty());
        assert_eq!(
            ctx.users_across_functions(new_arg),
            vec![load_id, load_id],
            "a mnemonic using the same operand twice should record both uses"
        );
    }

    #[test]
    fn remove_instruction_unparented_noop() {
        let mut ctx = Context::new();
        qcode!(
            ctx,
            "
            varnode i64 x;
            <block>
                %a = load(x:8, &x);
                return at %a;
            "
        );
        let load_id = BasicBlock::from_id(&ctx, block).instruction_ids()[0];

        // Manually detach from block without using remove_instruction,
        // simulating an instruction with no parent.
        ctx.instruction_mut(load_id).parent = None;

        // Should not panic even though parent is None.
        ctx.remove_instruction(load_id);

        assert!(ctx.get_named("a").is_none());
    }

    #[test]
    fn add_cfg_edge_returns_id_and_remove_unlinks_both_blocks() {
        let mut ctx = Context::new();
        // CFG edges are intra-function (strict IR locality): both blocks in one func.
        let f = ctx.anon_function();
        let a = BasicBlock::make(&mut ctx, f).id;
        let b = BasicBlock::make(&mut ctx, f).id;
        let c = BasicBlock::make(&mut ctx, f).id;

        let edge = ctx.add_cfg_edge(a, b);
        let surviving_edge = ctx.add_cfg_edge(b, c);
        assert_eq!(
            BasicBlock::from_id(&ctx, a)
                .successors()
                .collect::<Vec<_>>(),
            vec![(edge, b)]
        );
        assert_eq!(
            BasicBlock::from_id(&ctx, b)
                .predecessors()
                .collect::<Vec<_>>(),
            vec![(edge, a)]
        );

        ctx.remove_cfg_edge(a.func, edge);
        assert!(BasicBlock::from_id(&ctx, a).successors().next().is_none());
        assert!(BasicBlock::from_id(&ctx, b).predecessors().next().is_none());
        assert!(!ctx.bodies[a.func].edges.contains(edge));
        let surviving = ctx.edge(a.func, surviving_edge);
        assert_eq!(
            surviving.from, b.local,
            "swap removal must preserve the source"
        );
        assert_eq!(
            surviving.to, c.local,
            "swap removal must preserve the target"
        );
        assert_eq!(ctx.bodies[a.func].edges.len(), 1);

        let self_edge = ctx.add_cfg_edge(a, a);
        ctx.remove_cfg_edge(a.func, self_edge);
        assert!(!ctx.bodies[a.func].edges.contains(self_edge));
        assert!(ctx.block(a).edges.is_empty());

        let parallel_a = ctx.add_cfg_edge(a, b);
        let parallel_b = ctx.add_cfg_edge(a, b);
        ctx.remove_cfg_edge(a.func, parallel_a);
        assert!(!ctx.bodies[a.func].edges.contains(parallel_a));
        assert!(ctx.bodies[a.func].edges.contains(parallel_b));
        assert_eq!(
            BasicBlock::from_id(&ctx, a)
                .successors()
                .collect::<Vec<_>>(),
            vec![(parallel_b, b)],
        );
    }

    #[test]
    fn truth_map_tracks_four_states_and_conflicts() {
        let mut ctx = Context::new();
        let callee = FunctionBody::make(&mut ctx, "callee".into()).unwrap().id;
        let prop = Proposition::FunctionReturns(callee);

        // First assume wins; same polarity is idempotent; opposite fails.
        assert!(ctx.assume_true(prop));
        assert!(ctx.assume_true(prop));
        assert!(!ctx.assume_false(prop));
        assert_eq!(ctx.known(prop), None, "assumed is not known");

        // The truth map is part of the arena, so it snapshots with a clone.
        let snapshot = ctx.clone();

        // Proving the opposite overturns the assumption and records the
        // violation with both pass names.
        let scope = pass_scope::enter("verifier");
        assert!(ctx.set_known(prop, false), "overturning is novel");
        drop(scope);
        assert_eq!(ctx.known(prop), Some(false));
        let [v] = ctx.violations() else {
            panic!("expected one violation")
        };
        assert_eq!(v.prop, prop);
        assert!(v.assumed);
        assert_eq!(v.asserting_pass, "verifier");

        // Re-proving the same value is not novel.
        assert!(!ctx.set_known(prop, false));

        // The independent snapshot is unaffected.
        assert!(snapshot.violations().is_empty());
        assert_eq!(snapshot.known(prop), None);

        // An assume against a known fact fails; with it, succeeds.
        assert!(!ctx.assume_true(prop));
        assert!(ctx.assume_false(prop));
    }

    #[test]
    fn seeded_facts_are_not_novel() {
        let mut ctx = Context::new();
        let callee = FunctionBody::make(&mut ctx, "exit".into()).unwrap().id;
        let prop = Proposition::FunctionReturns(callee);

        ctx.seed_known(prop, false, PassName("seed"));
        assert_eq!(ctx.known(prop), Some(false));
        assert!(!ctx.assume_true(prop), "seeded fact blocks opposite assume");
        assert!(
            !ctx.set_known(prop, false),
            "re-proving a seed is not novel"
        );
        assert!(ctx.violations().is_empty());
    }

    #[test]
    fn discovered_code_records_and_survives_round_trip() {
        let mut ctx = Context::new();
        ctx.discover_code(0x1000, 0x10f0, 0x1100);
        ctx.discover_code(0x1000, 0x10f0, 0x1200);
        ctx.discover_code(0x1000, 0x10f0, 0x1100); // duplicate target is deduped

        let targets: Vec<u64> = ctx.discoveries().map(|d| d.target).collect();
        assert_eq!(targets, vec![0x1100, 0x1200]);

        let config = bincode::config::standard();
        let bytes = bincode::serde::encode_to_vec(&ctx, config).expect("encode");
        let (restored, _): (Context<'static>, usize) =
            bincode::serde::decode_from_slice(&bytes, config).expect("decode");
        assert_eq!(
            restored.discoveries().map(|d| d.target).collect::<Vec<_>>(),
            targets
        );
    }

    #[test]
    fn assume_executable_narrows_once_protections_known() {
        let mut ctx = Context::new();
        let mut image = crate::memory_image::MemoryImage::default();
        image.add_segment(0x1000, vec![0u8; 4], true, false); // code
        image.add_segment(0x2000, vec![0u8; 4], false, true); // data
        let binary: &dyn wazabin_binary::BinaryFormat = &image;

        // Default r/x while protections unknown: everything is permissive, even
        // unmapped (the lifter reads bytes from the format, not the image).
        assert!(ctx.assume_executable(binary, 0x1000));
        assert!(ctx.assume_executable(binary, 0x2000));
        assert!(ctx.assume_executable(binary, 0x9999));

        ctx.mark_protections_known();
        assert!(
            ctx.assume_executable(binary, 0x1000),
            "code region stays liftable"
        );
        assert!(
            !ctx.assume_executable(binary, 0x2000),
            "data region is skipped once protections are known"
        );
        assert!(
            !ctx.assume_executable(binary, 0x9999),
            "unmapped is skipped once known"
        );
        // The skip records the proven fact for the whole containing segment.
        assert_eq!(
            ctx.known(Proposition::ExecutableMemory {
                start: 0x2000,
                end: 0x2004,
            }),
            Some(false),
        );
    }

    #[test]
    fn assume_executable_honors_region_override() {
        let mut ctx = Context::new();
        let mut image = crate::memory_image::MemoryImage::default();
        image.add_segment(0x1000, vec![0u8; 4], true, false); // code
        image.add_segment(0x2000, vec![0u8; 4], false, true); // data
        let binary: &dyn wazabin_binary::BinaryFormat = &image;
        ctx.mark_protections_known();

        // Force the data region executable and the code region non-executable.
        ctx.seed_known(
            Proposition::ExecutableMemory {
                start: 0x2000,
                end: 0x2004,
            },
            true,
            PassName("override"),
        );
        ctx.seed_known(
            Proposition::ExecutableMemory {
                start: 0x1000,
                end: 0x1004,
            },
            false,
            PassName("override"),
        );

        assert!(
            ctx.assume_executable(binary, 0x2000),
            "override wins over the non-executable segment flag"
        );
        assert!(
            !ctx.assume_executable(binary, 0x1000),
            "override wins over the executable segment flag"
        );
    }

    #[test]
    fn context_survives_bincode_round_trip() {
        let mut ctx = Context::new();
        qcode!(
            ctx,
            "
            varnode i64 ptr;
            <block>
                %a = load(ptr:8, &ptr);
                %b = %a + i64 0x10;
                store(ptr:8, &ptr <- i64 0x1234);
                return at %b;
            "
        );

        // A SpaceAddress type exercises the custom TypeManager serialization.
        let some_space = ctx.get_or_make_named_space("scratch");
        let sa = ctx.shared.types.get_or_make_space_address(8, some_space);
        let sa_size = ctx.shared.types.size_of(sa);

        let blocks_before = ctx.block_ids().len();
        let insns_before = ctx.instruction_ids().len();
        let funcs_before = ctx.function_ids().len();

        let config = bincode::config::standard();
        let bytes = bincode::serde::encode_to_vec(&ctx, config).expect("encode");
        let (restored, _): (Context<'static>, usize) =
            bincode::serde::decode_from_slice(&bytes, config).expect("decode");

        assert_eq!(restored.block_ids().len(), blocks_before);
        assert_eq!(restored.instruction_ids().len(), insns_before);
        assert_eq!(restored.function_ids().len(), funcs_before);
        for function_id in restored.function_ids() {
            assert_eq!(restored.bodies[function_id].id(), function_id);
        }
        // The SpaceAddress type round-trips: same id, same size, same space.
        assert_eq!(restored.shared.types.size_of(sa), sa_size);
        assert_eq!(
            restored.shared.types.space_of(sa),
            Some(crate::space::MemorySpaceId::Shared(some_space))
        );
    }

    #[test]
    fn compact_edge_arena_preserves_ids_across_round_trip() {
        let mut ctx = Context::new();
        let function = ctx.anon_function();
        let a = BasicBlock::make(&mut ctx, function).id;
        let b = BasicBlock::make(&mut ctx, function).id;
        let c = BasicBlock::make(&mut ctx, function).id;
        let d = BasicBlock::make(&mut ctx, function).id;
        let first = ctx.add_cfg_edge(a, b);
        let removed = ctx.add_cfg_edge(b, c);
        let last = ctx.add_cfg_edge(c, d);
        ctx.remove_cfg_edge(function, removed);

        let physical_order: Vec<_> = ctx.bodies[function]
            .edges
            .iter()
            .map(|edge| edge.id)
            .collect();
        assert_eq!(physical_order, vec![first, last]);

        let config = bincode::config::standard();
        let bytes = bincode::serde::encode_to_vec(&ctx, config).expect("encode");
        let (mut restored, _): (Context<'static>, usize) =
            bincode::serde::decode_from_slice(&bytes, config).expect("decode");

        assert!(!restored.bodies[function].edges.contains(removed));
        assert_eq!(
            restored.bodies[function]
                .edges
                .iter()
                .map(|edge| edge.id)
                .collect::<Vec<_>>(),
            physical_order,
        );
        assert_eq!(restored.edge(function, first).to, b.local);
        assert_eq!(restored.edge(function, last).from, c.local);

        let fresh = restored.add_cfg_edge(a, d);
        assert!(fresh > last);
        assert_ne!(fresh, removed, "removed edge IDs must never be reused");
    }

    #[test]
    fn compact_instruction_arena_preserves_ids_across_round_trip() {
        let mut ctx = Context::new();
        qcode!(
            ctx,
            "
            <block>
                %first = i64 1 + i64 2;
                %removed = i64 3 + i64 4;
                return at %first;
            "
        );
        let ids = BasicBlock::from_id(&ctx, block).instruction_ids();
        let first = ids[0];
        let removed = ids[1];
        let last = ids[2];
        ctx.remove_instruction(removed);

        let physical_order: Vec<_> = ctx.bodies[first.func]
            .insns
            .iter()
            .map(|insn| insn.id)
            .collect();
        assert_eq!(physical_order, vec![first.local, last.local]);

        let config = bincode::config::standard();
        let bytes = bincode::serde::encode_to_vec(&ctx, config).expect("encode");
        let (mut restored, _): (Context<'static>, usize) =
            bincode::serde::decode_from_slice(&bytes, config).expect("decode");

        assert!(!restored.contains_instruction(removed));
        assert_eq!(
            restored.bodies[first.func]
                .insns
                .iter()
                .map(|insn| insn.id)
                .collect::<Vec<_>>(),
            physical_order,
        );
        assert!(restored.contains_instruction(first));
        assert!(restored.contains_instruction(last));

        let template = restored.instruction(last).clone();
        let fresh = restored.push_insn(first.func, template);
        assert!(fresh.local > last.local);
        assert_ne!(
            fresh, removed,
            "removed instruction IDs must never be reused"
        );
    }

    #[test]
    fn compact_param_arena_preserves_ids_across_round_trip() {
        let mut ctx = Context::new();
        let function = ctx.anon_function();
        let block = BasicBlock::make(&mut ctx, function).id;
        let first = BasicBlock::from_id_mut(&mut ctx, block).push_param(8).id;
        let removed = BasicBlock::from_id_mut(&mut ctx, block).push_param(8).id;
        let last = BasicBlock::from_id_mut(&mut ctx, block).push_param(8).id;

        ctx.block_mut(block).params.remove(1);
        ctx.block_param_mut(last).index = 1;
        ctx.remove_block_param(removed);

        let physical_order: Vec<_> = ctx.bodies[function]
            .params
            .iter()
            .map(|param| param.id)
            .collect();
        assert_eq!(physical_order, vec![first.local, last.local]);
        assert_eq!(ctx.block_param(first).index, 0);
        assert_eq!(ctx.block_param(last).index, 1);

        let config = bincode::config::standard();
        let bytes = bincode::serde::encode_to_vec(&ctx, config).expect("encode");
        let (mut restored, _): (Context<'static>, usize) =
            bincode::serde::decode_from_slice(&bytes, config).expect("decode");

        assert!(!restored.contains_block_param(removed));
        assert_eq!(
            restored.bodies[function]
                .params
                .iter()
                .map(|param| param.id)
                .collect::<Vec<_>>(),
            physical_order,
        );
        assert!(restored.contains_block_param(first));
        assert!(restored.contains_block_param(last));

        let fresh = BasicBlock::from_id_mut(&mut restored, block)
            .push_param(8)
            .id;
        assert!(fresh.local > last.local);
        assert_ne!(fresh, removed, "removed parameter IDs must never be reused");
    }

    #[test]
    fn compact_block_arena_preserves_ids_across_round_trip() {
        let mut ctx = Context::new();
        let function = ctx.anon_function();
        let first = BasicBlock::make(&mut ctx, function).id;
        let removed = BasicBlock::make(&mut ctx, function).id;
        let last = BasicBlock::make(&mut ctx, function).id;
        FunctionBody::from_id_mut(&mut ctx, function)
            .set_root(first)
            .expect("set root");

        ctx.delete_block(removed);

        let physical_order: Vec<_> = ctx.bodies[function]
            .blocks
            .iter()
            .map(|block| block.id)
            .collect();
        assert_eq!(physical_order, vec![first.local, last.local]);
        assert_eq!(ctx.block_ids(), vec![first, last]);

        let config = bincode::config::standard();
        let bytes = bincode::serde::encode_to_vec(&ctx, config).expect("encode");
        let (mut restored, _): (Context<'static>, usize) =
            bincode::serde::decode_from_slice(&bytes, config).expect("decode");

        assert!(!restored.contains_block(removed));
        assert_eq!(
            restored.bodies[function]
                .blocks
                .iter()
                .map(|block| block.id)
                .collect::<Vec<_>>(),
            physical_order,
        );
        assert!(restored.contains_block(first));
        assert!(restored.contains_block(last));
        assert_eq!(
            FunctionBody::from_id(&restored, function)
                .root()
                .map(|block| block.id),
            Some(first),
        );

        let fresh = BasicBlock::make(&mut restored, function).id;
        assert!(fresh.local > last.local);
        assert_ne!(fresh, removed, "removed block IDs must never be reused");
    }

    #[test]
    fn deleting_root_clears_function_root() {
        let mut ctx = Context::new();
        let function = ctx.anon_function();
        let root = BasicBlock::make(&mut ctx, function).id;
        FunctionBody::from_id_mut(&mut ctx, function)
            .set_root(root)
            .expect("set root");

        ctx.delete_block(root);

        assert!(!ctx.contains_block(root));
        assert!(FunctionBody::from_id(&ctx, function).root().is_none());
        assert!(ctx.block_ids().is_empty());
    }

    #[test]
    fn get_unique_name_resumes_probe_and_reuses_freed_suffixes() {
        use crate::value::VarnodeId;

        let mut ctx = Context::new();
        let id = ValueId::Varnode(VarnodeId::from(0usize));

        // Mirror real callers: take the deduplicated name, then bind it.
        fn take(ctx: &mut Context<'static>, id: ValueId, base: &str) -> String {
            let name = ctx
                .get_unique_name(Cow::Owned(base.to_string()))
                .to_string();
            ctx.update_name(Cow::Owned(name.clone()), id, None).unwrap();
            name
        }

        // Suffixes are handed out in ascending order (bare name first).
        assert_eq!(take(&mut ctx, id, "tmp"), "tmp");
        assert_eq!(take(&mut ctx, id, "tmp"), "tmp_1");
        assert_eq!(take(&mut ctx, id, "tmp"), "tmp_2");
        assert_eq!(take(&mut ctx, id, "tmp"), "tmp_3");

        // A distinct base is unaffected by tmp's hint.
        assert_eq!(take(&mut ctx, id, "x"), "x");
        assert_eq!(take(&mut ctx, id, "x"), "x_1");

        // Freeing tmp_1 must make the next tmp reuse it, exactly as a naive
        // first-free scan would — the resume hint must not skip the hole.
        ctx.update_name(Cow::Borrowed("relocated"), id, Some("tmp_1"))
            .unwrap();
        assert_eq!(take(&mut ctx, id, "tmp"), "tmp_1");
        // ...then continue past the still-taken suffixes.
        assert_eq!(take(&mut ctx, id, "tmp"), "tmp_4");
    }

    // --- split_function_at (strict-local construction verb, ruling 2) ---

    mod split_function_at {
        use super::*;

        use crate::value::insn::{Callee, Mnemonic, TailCall};
        use crate::value::{BasicBlock, FunctionBody, Instruction, Value};
        use std::borrow::Cow;

        fn block_at(ctx: &mut Context<'static>, func: FunctionId, addr: u64) -> BlockId {
            BasicBlock::make(ctx, func).with_address(addr).id
        }

        fn branch_at(ctx: &mut Context<'static>, block: BlockId, target: BlockId, addr: u64) {
            let id = (ctx).builder(block).push_branch(target).id;
            Instruction::from_id_mut(ctx, id).set_address(addr);
        }

        fn cbranch_at(
            ctx: &mut Context<'static>,
            block: BlockId,
            success: BlockId,
            failure: BlockId,
            addr: u64,
        ) {
            let cond = ctx.get_const(1, 1).id();
            let id = (ctx).builder(block).push_cbranch(cond, success, failure).id;
            Instruction::from_id_mut(ctx, id).set_address(addr);
        }

        fn return_at(ctx: &mut Context<'static>, block: BlockId, addr: u64) {
            let zero = ctx.get_const(0, 8).id();
            let id = (ctx).builder(block).push_return(zero).id;
            Instruction::from_id_mut(ctx, id).set_address(addr);
        }

        fn block_at_addr(ctx: &Context, func: FunctionId, addr: u64) -> BlockId {
            FunctionBody::from_id(ctx, func)
                .block_ids()
                .into_iter()
                .find(|b| ctx.block(*b).address == Some(addr))
                .unwrap_or_else(|| panic!("{func:?} has no block at {addr:#x}"))
        }

        fn addrs(ctx: &Context, func: FunctionId) -> Vec<u64> {
            let mut got: Vec<u64> = FunctionBody::from_id(ctx, func)
                .block_ids()
                .into_iter()
                .filter_map(|b| ctx.block(b).address)
                .collect();
            got.sort_unstable();
            got
        }

        /// F@0x1000 (`jmp 0x2000`) absorbed the body later found to be its own
        /// function at 0x2000 (`0x2000: jmp 0x2005 ; 0x2005: ret`). Splitting at the
        /// 0x2000 block reuses the stub `G`, moves 0x2000+0x2005 into `G` self-stored,
        /// leaves only the thunk in `F`, and turns the thunk's branch into a `TailCall`.
        #[test]
        fn splits_absorbed_body_reusing_the_stub() {
            let mut ctx = Context::new();
            let f = FunctionBody::make_at_addr(&mut ctx, 0x1000, Some(Cow::Borrowed("thunk"))).id;
            let b0 = block_at(&mut ctx, f, 0x1000);
            let b1 = block_at(&mut ctx, f, 0x2000);
            let b2 = block_at(&mut ctx, f, 0x2005);
            branch_at(&mut ctx, b0, b1, 0x1000);
            branch_at(&mut ctx, b1, b2, 0x2000);
            return_at(&mut ctx, b2, 0x2005);
            {
                let mut func = FunctionBody::from_id_mut(&mut ctx, f);
                func.set_root(b0).unwrap();
            }
            // A later `call 0x2000` minted the stub.
            let g = FunctionBody::make_at_addr(&mut ctx, 0x2000, Some(Cow::Borrowed("real"))).id;

            let split_g = ctx.split_function_at(b1);
            assert_eq!(
                split_g, g,
                "the split must reuse the existing stub at 0x2000"
            );

            assert_eq!(addrs(&ctx, f), vec![0x1000]);
            assert_eq!(addrs(&ctx, g), vec![0x2000, 0x2005]);
            let g_entry = block_at_addr(&ctx, g, 0x2000);
            assert_eq!(ctx.bodies[g].root_id(), Some(g_entry.local));

            // Every G block is self-stored.
            for b in FunctionBody::from_id(&ctx, g).block_ids() {
                assert_eq!(b.func, g);
            }

            // The thunk's branch into the tail became a TailCall(G); its edge is gone.
            let f_entry = block_at_addr(&ctx, f, 0x1000);
            assert_eq!(BasicBlock::from_id(&ctx, f_entry).successors().count(), 0);
            let term = BasicBlock::from_id(&ctx, f_entry)
                .instructions()
                .last()
                .map(|i| i.mnemonic().clone());
            assert!(
                matches!(term, Some(Mnemonic::TailCall(TailCall { target, .. })) if target == Callee::Real(g)),
                "thunk branch must become TailCall(G), got {term:?}",
            );
        }

        #[test]
        fn split_rehomes_temporary_values_spaces_and_pointer_types() {
            let mut ctx = Context::new();
            let f = FunctionBody::make_at_addr(&mut ctx, 0x1000, Some(Cow::Borrowed("f"))).id;
            let entry = block_at(&mut ctx, f, 0x1000);
            let tail = block_at(&mut ctx, f, 0x2000);
            branch_at(&mut ctx, entry, tail, 0x1000);
            FunctionBody::from_id_mut(&mut ctx, f)
                .set_root(entry)
                .unwrap();

            let temp = ctx
                .builder(tail)
                .make_named_temp(Cow::Borrowed("scratch"), 8);
            ctx.builder(entry)
                .make_named_temp(Cow::Borrowed("unused"), 4);
            let temp_space = ctx.bodies[f].temps[temp.local].space;
            let load = {
                let mut builder = ctx.builder(tail);
                let ValueId::Instruction(load) = builder
                    .push_load::<false>(
                        ValueId::Temp(temp),
                        8,
                        LocalMemorySpaceId::Temp(temp_space),
                    )
                    .id()
                else {
                    unreachable!()
                };
                builder.push_return(ValueId::Instruction(load));
                load
            };
            let pointer_type = ctx
                .shared
                .types
                .get_or_make_space_address(8, MemorySpaceId::Temp(TempSpaceId::new(f, temp_space)));
            ctx.instruction_mut(load).type_id = pointer_type;

            let g =
                FunctionBody::make_at_addr(&mut ctx, 0x2000, Some(Cow::Borrowed("discovered"))).id;
            assert_eq!(ctx.split_function_at(tail), g);

            let diagnostics = crate::verify_body_arena_integrity(&ctx);
            assert!(diagnostics.is_empty(), "{diagnostics:#?}");
            assert_eq!(ctx.bodies[g].temp_spaces.len(), 1);
            assert_eq!(ctx.bodies[g].temps.len(), 1);
            assert_eq!(ctx.bodies[f].temps.len(), 2, "source arenas remain intact");

            let moved_load = FunctionBody::from_id(&ctx, g)
                .blocks()
                .flat_map(|block| block.instructions())
                .find(|insn| matches!(insn.mnemonic(), Mnemonic::Load(_)))
                .expect("load moved with the split");
            let Mnemonic::Load(moved) = moved_load.mnemonic() else {
                unreachable!()
            };
            let LocalMemorySpaceId::Temp(moved_space) = moved.space else {
                panic!("load lost temporary-space provenance")
            };
            assert!(matches!(moved.ptr, crate::value::LocalValueId::Temp(_)));
            assert!(usize::from(moved_space) < ctx.bodies[g].temp_spaces.len());
            assert_eq!(
                ctx.shared.types.space_of(moved_load.type_id()),
                Some(MemorySpaceId::Temp(TempSpaceId::new(g, moved_space)))
            );

            // This is the path that previously panicked in `function_fingerprint`.
            let rendered = FunctionBody::from_id(&ctx, g).to_string();
            assert!(rendered.contains("scratch"));
        }

        #[test]
        fn split_stops_at_a_foreign_rootless_stub_address() {
            let mut ctx = Context::new();
            let f = FunctionBody::make_at_addr(&mut ctx, 0x1000, Some(Cow::Borrowed("f"))).id;
            let entry = block_at(&mut ctx, f, 0x1000);
            let split = block_at(&mut ctx, f, 0x2000);
            let foreign_entry = block_at(&mut ctx, f, 0x3000);
            let foreign_body = block_at(&mut ctx, f, 0x3005);
            branch_at(&mut ctx, entry, split, 0x1000);
            branch_at(&mut ctx, split, foreign_entry, 0x2000);
            branch_at(&mut ctx, foreign_entry, foreign_body, 0x3000);
            return_at(&mut ctx, foreign_body, 0x3005);
            FunctionBody::from_id_mut(&mut ctx, f)
                .set_root(entry)
                .unwrap();

            let g = FunctionBody::make_at_addr(&mut ctx, 0x2000, Some(Cow::Borrowed("g"))).id;
            let h = FunctionBody::make_at_addr(&mut ctx, 0x3000, Some(Cow::Borrowed("h"))).id;
            assert!(FunctionBody::from_id(&ctx, g).root().is_none());
            assert!(FunctionBody::from_id(&ctx, h).root().is_none());

            assert_eq!(ctx.split_function_at(split), g);
            assert_eq!(addrs(&ctx, g), vec![0x2000]);
            assert_eq!(addrs(&ctx, f), vec![0x1000, 0x3000, 0x3005]);
            assert!(FunctionBody::from_id(&ctx, h).root().is_none());

            let g_entry = block_at_addr(&ctx, g, 0x2000);
            let term = BasicBlock::from_id(&ctx, g_entry)
                .instructions()
                .last()
                .map(|i| i.mnemonic().clone());
            assert!(
                matches!(term, Some(Mnemonic::TailCall(TailCall { target, .. })) if target == Callee::Real(h)),
                "split tail must stop and tail-call rootless stub H, got {term:?}",
            );
        }

        #[test]
        fn split_rehomes_block_param_origin_into_destination_arena() {
            let mut ctx = Context::new();
            let f = FunctionBody::make_at_addr(&mut ctx, 0x1000, Some(Cow::Borrowed("f"))).id;
            let entry = block_at(&mut ctx, f, 0x1000);
            let tail = block_at(&mut ctx, f, 0x2000);
            let param = BasicBlock::from_id_mut(&mut ctx, tail).push_param(8).id;
            crate::value::BlockParam::from_id_mut(&mut ctx, param)
                .set_origin(ValueId::BlockParam(param));

            let arg = ctx.get_const(7, 8).id();
            let branch = ctx.builder(entry).push_branch_with_args(tail, vec![arg]).id;
            Instruction::from_id_mut(&mut ctx, branch).set_address(0x1000);
            let ret = ctx.builder(tail).push_return(ValueId::BlockParam(param)).id;
            Instruction::from_id_mut(&mut ctx, ret).set_address(0x2000);
            FunctionBody::from_id_mut(&mut ctx, f)
                .set_root(entry)
                .unwrap();

            let g = ctx.split_function_at(tail);
            let new_tail = block_at_addr(&ctx, g, 0x2000);
            let new_param = BasicBlock::from_id(&ctx, new_tail).params().next().unwrap();
            assert_eq!(new_param.origin(), Some(ValueId::BlockParam(new_param.id)));
        }

        /// A relocated block carrying a `&<block>` literal that names another
        /// relocated block must have that literal re-pointed at the clone.
        ///
        /// `SymbolicRef::Block` holds an *absolute* `BlockId` — the one construct
        /// that can name a block in another function — so unlike operands and
        /// branch targets it is not fixed up by re-localization. Left alone it
        /// would dangle into the source arena slot that phase 5 deletes.
        #[test]
        fn split_rehomes_symbolic_block_literals() {
            use crate::value::literal::SymbolicRef;

            let mut ctx = Context::new();
            let f = FunctionBody::make_at_addr(&mut ctx, 0x1000, Some(Cow::Borrowed("f"))).id;
            let entry = block_at(&mut ctx, f, 0x1000);
            let tail = block_at(&mut ctx, f, 0x2000);
            let landing = block_at(&mut ctx, f, 0x2008);

            // A code-pointer constant in `tail` that symbolically names `landing`.
            // Both blocks move together when `tail` is split off into `g`.
            let lit = ctx.get_const(0x2008, 8).id();
            let ValueId::Literal(lit_id) = lit else {
                panic!("expected a literal");
            };
            ctx.shared.values.literals[lit_id].symbolic = Some(SymbolicRef::Block(landing));

            branch_at(&mut ctx, entry, tail, 0x1000);
            // `goto [&<landing>]` — the literal reaches the IR as an operand.
            let ind = ctx.builder(tail).push_branchind(lit).id;
            Instruction::from_id_mut(&mut ctx, ind).set_address(0x2000);
            ctx.add_cfg_edge(tail, landing);
            return_at(&mut ctx, landing, 0x2008);
            FunctionBody::from_id_mut(&mut ctx, f)
                .set_root(entry)
                .unwrap();

            let g = ctx.split_function_at(tail);

            let new_landing = block_at_addr(&ctx, g, 0x2008);
            let new_tail = block_at_addr(&ctx, g, 0x2000);
            let Mnemonic::BranchInd(b) = BasicBlock::from_id(&ctx, new_tail)
                .instructions()
                .last()
                .unwrap()
                .mnemonic()
                .clone()
            else {
                panic!("tail must still end in an indirect branch");
            };
            let crate::value::LocalValueId::Literal(new_lit) = b.ptr else {
                panic!("indirect branch operand must still be a literal");
            };
            assert_eq!(
                ctx.shared.values.literals[new_lit].symbolic,
                Some(SymbolicRef::Block(new_landing)),
                "the relocated literal must name the clone, not the deleted original",
            );
            assert_eq!(
                ctx.shared.values.literals[new_lit].value, 0x2008,
                "re-pointing the symbol must not disturb the numeric value",
            );
        }

        /// A conditional arm into the split block is routed through a fresh
        /// intra-function trampoline ending in a `TailCall`; the fall-through arm is
        /// untouched and no foreign block reference survives.
        #[test]
        fn conditional_arm_into_split_block_uses_a_trampoline() {
            let mut ctx = Context::new();
            let f = FunctionBody::make_at_addr(&mut ctx, 0x1000, Some(Cow::Borrowed("f"))).id;
            let entry = block_at(&mut ctx, f, 0x1000);
            let cont = block_at(&mut ctx, f, 0x1008);
            let tail = block_at(&mut ctx, f, 0x2000);
            cbranch_at(&mut ctx, entry, tail, cont, 0x1000);
            return_at(&mut ctx, cont, 0x1008);
            return_at(&mut ctx, tail, 0x2000);
            FunctionBody::from_id_mut(&mut ctx, f)
                .set_root(entry)
                .unwrap();

            let g = ctx.split_function_at(tail);

            let entry = block_at_addr(&ctx, f, 0x1000);
            let cont = block_at_addr(&ctx, f, 0x1008);
            assert_eq!(addrs(&ctx, g), vec![0x2000]);

            let Mnemonic::CBranch(cb) = BasicBlock::from_id(&ctx, entry)
                .instructions()
                .last()
                .unwrap()
                .mnemonic()
                .clone()
            else {
                panic!("entry must still end in a cbranch");
            };
            assert_eq!(cb.failure_block, cont.local, "fall-through arm untouched");
            let tramp = BlockId::new(entry.func, cb.success_block);
            assert_eq!(
                BasicBlock::from_id(&ctx, tramp).parent().map(|f| f.id),
                Some(f),
                "trampoline lives in F",
            );
            let term = BasicBlock::from_id(&ctx, tramp)
                .instructions()
                .last()
                .map(|i| i.mnemonic().clone());
            assert!(
                matches!(term, Some(Mnemonic::TailCall(TailCall { target, .. })) if target == Callee::Real(g)),
                "trampoline must tail-call G, got {term:?}",
            );
            // Every successor of entry is intra-F.
            for (_, s) in BasicBlock::from_id(&ctx, entry).successors() {
                assert_eq!(BasicBlock::from_id(&ctx, s).parent().map(|f| f.id), Some(f));
            }
        }

        /// With no pre-existing stub at the landing address, the split mints a
        /// conventional `fn_<addr>` and moves the tail into it self-stored.
        #[test]
        fn mints_a_conventional_function_when_no_stub_exists() {
            let mut ctx = Context::new();
            wazabin_qcode_macro::qcode!(
                ctx,
                "
                fn f:
                <entry>
                    goto <0x1008>;
                <0x1008>
                    return 0x0;
                "
            );

            let mid = block_at_addr(&ctx, f, 0x1008);
            let g = ctx.split_function_at(mid);
            assert_eq!(FunctionBody::from_id(&ctx, g).name(), "fn_1008");
            // f keeps only its (unaddressed) entry; the addressed mid block moved.
            assert_eq!(FunctionBody::from_id(&ctx, f).block_ids().len(), 1);
            assert_eq!(addrs(&ctx, g), vec![0x1008]);
            let addresses = crate::address_index::AddressIndex::analyze(&ctx);
            assert_eq!(addresses.function_at(0x1008), Some(g));
            for b in FunctionBody::from_id(&ctx, g).block_ids() {
                assert_eq!(b.func, g);
            }
        }

        /// Assert every live block's static terminator target is a live block of
        /// its own arena and has a matching CFG edge — the split invariant that,
        /// when violated, later dereferences a dead `LocalBlockId`.
        fn assert_no_dangling_terminators(ctx: &Context) {
            for b in ctx.block_ids() {
                let Some(mnemonic) = BasicBlock::from_id(ctx, b)
                    .instructions()
                    .last()
                    .map(|t| t.mnemonic().clone())
                else {
                    continue;
                };
                let targets = match &mnemonic {
                    Mnemonic::Branch(crate::value::insn::Branch { target, .. }) => vec![*target],
                    Mnemonic::CBranch(crate::value::insn::CBranch {
                        success_block,
                        failure_block,
                        ..
                    }) => vec![*success_block, *failure_block],
                    _ => vec![],
                };
                let succs: std::collections::HashSet<BlockId> = BasicBlock::from_id(ctx, b)
                    .successors()
                    .map(|(_, s)| s)
                    .collect();
                for t in targets {
                    let tid = BlockId::new(b.func, t);
                    assert!(
                        ctx.contains_block(tid),
                        "block {b:?} terminator names dead block {tid:?}"
                    );
                    assert!(
                        succs.contains(&tid),
                        "block {b:?} terminator target {tid:?} has no CFG edge (operand/edge desync)"
                    );
                }
            }
        }

        /// A *retained* predecessor branching into the middle of the split tail
        /// forces that landing to be promoted to its own function (recursive
        /// split), so every predecessor — retained and in-tail — tail-calls it
        /// rather than naming a block that is about to relocate.
        #[test]
        fn retained_predecessor_into_mid_tail_promotes_the_landing() {
            let mut ctx = Context::new();
            // entry -> {tail@2000, retained@1008}; both retained@1008 and the tail
            // entry@2000 branch into the mid-tail landing@2008.
            wazabin_qcode_macro::qcode!(
                ctx,
                "
                fn f:
                <entry @c:i8>
                    if @c goto <0x2000> else goto <0x1008>;
                <0x1008>
                    goto <0x2008>;
                <0x2000>
                    goto <0x2008>;
                <0x2008>
                    return 0x0;
                "
            );

            let tail = block_at_addr(&ctx, f, 0x2000);
            let g = ctx.split_function_at(tail);

            // The landing became its own function; every branch into it is a
            // TailCall, and nothing dangles.
            let addresses = crate::address_index::AddressIndex::analyze(&ctx);
            let landing_fn = addresses
                .function_at(0x2008)
                .expect("mid-tail landing must be promoted to a function");
            assert_ne!(landing_fn, g);
            assert_eq!(addrs(&ctx, g), vec![0x2000]);
            assert_no_dangling_terminators(&ctx);

            for (holder, addr) in [(f, 0x1008u64), (g, 0x2000u64)] {
                let block = block_at_addr(&ctx, holder, addr);
                let term = BasicBlock::from_id(&ctx, block)
                    .instructions()
                    .last()
                    .map(|i| i.mnemonic().clone());
                assert!(
                    matches!(term, Some(Mnemonic::TailCall(TailCall { target, .. })) if target == Callee::Real(landing_fn)),
                    "branch at {addr:#x} into the landing must tail-call it, got {term:?}",
                );
            }
        }

        /// A tail block whose conditional arm targets an entry registered in its
        /// *own* storing arena (a back-edge to the origin function's registered
        /// entry). Regression: the rewrite loop recomputed `foreign_entry` with the
        /// storing arena as `owner` instead of the scan's effective owner `g`; when
        /// the arm's callee equals that storing arena the recheck returned `None`
        /// and the arm rewrite was skipped, stranding the operand after the move
        /// (StableArena panic on objdump -Os).
        #[test]
        fn tail_conditional_to_own_registered_entry_uses_a_trampoline() {
            let mut ctx = Context::new();
            let f = FunctionBody::make_at_addr(&mut ctx, 0x1000, Some(Cow::Borrowed("f"))).id;
            let entry = block_at(&mut ctx, f, 0x1000);
            let tail = block_at(&mut ctx, f, 0x2000);
            let cont = block_at(&mut ctx, f, 0x2008);
            branch_at(&mut ctx, entry, tail, 0x1000);
            // tail conditionally branches back to f's own registered entry (0x1000).
            cbranch_at(&mut ctx, tail, entry, cont, 0x2000);
            return_at(&mut ctx, cont, 0x2008);
            FunctionBody::from_id_mut(&mut ctx, f)
                .set_root(entry)
                .unwrap();

            let g = ctx.split_function_at(tail);

            assert_no_dangling_terminators(&ctx);
            let diagnostics = crate::verify_body_arena_integrity(&ctx);
            assert!(diagnostics.is_empty(), "{diagnostics:#?}");

            // The moved tail's back-edge arm routes through a trampoline that
            // tail-calls f (its own function), relocated into g.
            let moved_tail = block_at_addr(&ctx, g, 0x2000);
            let Mnemonic::CBranch(cb) = BasicBlock::from_id(&ctx, moved_tail)
                .instructions()
                .last()
                .unwrap()
                .mnemonic()
                .clone()
            else {
                panic!("moved tail must still end in a cbranch");
            };
            let tramp = BlockId::new(g, cb.success_block);
            assert_eq!(tramp.func, g, "trampoline must have relocated into g");
            let term = BasicBlock::from_id(&ctx, tramp)
                .instructions()
                .last()
                .map(|i| i.mnemonic().clone());
            assert!(
                matches!(term, Some(Mnemonic::TailCall(TailCall { target, .. })) if target == Callee::Real(f)),
                "back-edge trampoline must tail-call f, got {term:?}",
            );
        }

        /// A *tail* block whose conditional arm targets a foreign entry gets a
        /// trampoline that must relocate into `g` alongside it. Regression test:
        /// the trampoline was previously minted in the origin arena and stranded,
        /// leaving the moved predecessor's arm naming a dead local.
        #[test]
        fn tail_conditional_to_foreign_entry_relocates_its_trampoline() {
            let mut ctx = Context::new();
            let f = FunctionBody::make_at_addr(&mut ctx, 0x1000, Some(Cow::Borrowed("f"))).id;
            let entry = block_at(&mut ctx, f, 0x1000);
            let tail = block_at(&mut ctx, f, 0x2000);
            let cont = block_at(&mut ctx, f, 0x2008);
            let foreign = block_at(&mut ctx, f, 0x3000);
            branch_at(&mut ctx, entry, tail, 0x1000);
            // tail (which will move into g) conditionally jumps to a foreign entry.
            cbranch_at(&mut ctx, tail, foreign, cont, 0x2000);
            return_at(&mut ctx, cont, 0x2008);
            return_at(&mut ctx, foreign, 0x3000);
            FunctionBody::from_id_mut(&mut ctx, f)
                .set_root(entry)
                .unwrap();
            let h = FunctionBody::make_at_addr(&mut ctx, 0x3000, Some(Cow::Borrowed("h"))).id;

            let g = ctx.split_function_at(tail);

            assert_no_dangling_terminators(&ctx);
            let diagnostics = crate::verify_body_arena_integrity(&ctx);
            assert!(diagnostics.is_empty(), "{diagnostics:#?}");

            // The moved tail's success arm points to a trampoline that now lives in
            // g and tail-calls the foreign function H.
            let moved_tail = block_at_addr(&ctx, g, 0x2000);
            let Mnemonic::CBranch(cb) = BasicBlock::from_id(&ctx, moved_tail)
                .instructions()
                .last()
                .unwrap()
                .mnemonic()
                .clone()
            else {
                panic!("moved tail must still end in a cbranch");
            };
            let tramp = BlockId::new(g, cb.success_block);
            assert_eq!(tramp.func, g, "trampoline must have relocated into g");
            let term = BasicBlock::from_id(&ctx, tramp)
                .instructions()
                .last()
                .map(|i| i.mnemonic().clone());
            assert!(
                matches!(term, Some(Mnemonic::TailCall(TailCall { target, .. })) if target == Callee::Real(h)),
                "relocated trampoline must tail-call H, got {term:?}",
            );
        }

        /// The *failure* arm of a retained conditional into the split entry is
        /// routed through a trampoline (mirror of the success-arm case), leaving
        /// the success arm untouched.
        #[test]
        fn conditional_failure_arm_into_split_block_uses_a_trampoline() {
            let mut ctx = Context::new();
            // split target (tail@2000) reached via the FAILURE arm; the fall-through
            // success arm (cont@1008) is left untouched.
            wazabin_qcode_macro::qcode!(
                ctx,
                "
                fn f:
                <entry @c:i8>
                    if @c goto <0x1008> else goto <0x2000>;
                <0x1008>
                    return 0x0;
                <0x2000>
                    return 0x0;
                "
            );

            let tail = block_at_addr(&ctx, f, 0x2000);
            let g = ctx.split_function_at(tail);

            assert_no_dangling_terminators(&ctx);
            let entry = BlockId::new(f, ctx.bodies[f].root_id().unwrap());
            let cont = block_at_addr(&ctx, f, 0x1008);
            let Mnemonic::CBranch(cb) = BasicBlock::from_id(&ctx, entry)
                .instructions()
                .last()
                .unwrap()
                .mnemonic()
                .clone()
            else {
                panic!("entry must still end in a cbranch");
            };
            assert_eq!(
                cb.success_block, cont.local,
                "success (fall-through) untouched"
            );
            let tramp = BlockId::new(entry.func, cb.failure_block);
            let term = BasicBlock::from_id(&ctx, tramp)
                .instructions()
                .last()
                .map(|i| i.mnemonic().clone());
            assert!(
                matches!(term, Some(Mnemonic::TailCall(TailCall { target, .. })) if target == Callee::Real(g)),
                "failure arm must route through a trampoline tail-calling G, got {term:?}",
            );
        }

        /// A conditional terminator *inside* the moved tail, targeting two other
        /// moved blocks, has both arms re-pointed at the clones.
        #[test]
        fn moved_tail_internal_conditional_remaps_both_arms() {
            let mut ctx = Context::new();
            // tail@2000 conditionally branches to two other moved blocks
            // (arm_a@2008, arm_b@2010); all three relocate into g together.
            wazabin_qcode_macro::qcode!(
                ctx,
                "
                fn f:
                <entry>
                    goto <0x2000>;
                <0x2000>
                    %c = 0x0 == 0x0;
                    if %c goto <0x2008> else goto <0x2010>;
                <0x2008>
                    return 0x0;
                <0x2010>
                    return 0x0;
                "
            );

            let tail = block_at_addr(&ctx, f, 0x2000);
            let g = ctx.split_function_at(tail);

            assert_eq!(addrs(&ctx, g), vec![0x2000, 0x2008, 0x2010]);
            assert_no_dangling_terminators(&ctx);
            let moved_tail = block_at_addr(&ctx, g, 0x2000);
            let Mnemonic::CBranch(cb) = BasicBlock::from_id(&ctx, moved_tail)
                .instructions()
                .last()
                .unwrap()
                .mnemonic()
                .clone()
            else {
                panic!("moved tail must still end in a cbranch");
            };
            let a = block_at_addr(&ctx, g, 0x2008);
            let b = block_at_addr(&ctx, g, 0x2010);
            assert_eq!(cb.success_block, a.local, "success arm re-pointed to clone");
            assert_eq!(cb.failure_block, b.local, "failure arm re-pointed to clone");
        }

        /// An unconditional `Branch` *inside* the moved tail, between two moved
        /// blocks, has its target re-pointed at the clone.
        #[test]
        fn moved_tail_internal_branch_remaps_target() {
            let mut ctx = Context::new();
            wazabin_qcode_macro::qcode!(
                ctx,
                "
                fn f:
                <entry>
                    goto <0x2000>;
                <0x2000>
                    goto <0x2008>;
                <0x2008>
                    return 0x0;
                "
            );

            let tail = block_at_addr(&ctx, f, 0x2000);
            let g = ctx.split_function_at(tail);

            assert_eq!(addrs(&ctx, g), vec![0x2000, 0x2008]);
            assert_no_dangling_terminators(&ctx);
            let moved_tail = block_at_addr(&ctx, g, 0x2000);
            let Mnemonic::Branch(br) = BasicBlock::from_id(&ctx, moved_tail)
                .instructions()
                .last()
                .unwrap()
                .mnemonic()
                .clone()
            else {
                panic!("moved tail must still end in a branch");
            };
            let end = block_at_addr(&ctx, g, 0x2008);
            assert_eq!(br.target, end.local, "internal branch re-pointed to clone");
        }

        /// A relocated block carrying a `Store` into a temporary space keeps its
        /// space provenance rebased into the destination arena.
        #[test]
        fn split_rehomes_store_temporary_space() {
            let mut ctx = Context::new();
            let f = FunctionBody::make_at_addr(&mut ctx, 0x1000, Some(Cow::Borrowed("f"))).id;
            let entry = block_at(&mut ctx, f, 0x1000);
            let tail = block_at(&mut ctx, f, 0x2000);
            branch_at(&mut ctx, entry, tail, 0x1000);

            let slot = ctx.builder(tail).make_named_temp(Cow::Borrowed("slot"), 8);
            let space = ctx.bodies[f].temps[slot.local].space;
            let value = ctx.get_const(0x2a, 8).id();
            {
                let mut builder = ctx.builder(tail);
                builder.push_store(value, ValueId::Temp(slot), LocalMemorySpaceId::Temp(space));
                builder.push_return(value);
            }
            FunctionBody::from_id_mut(&mut ctx, f)
                .set_root(entry)
                .unwrap();

            let g = ctx.split_function_at(tail);
            let diagnostics = crate::verify_body_arena_integrity(&ctx);
            assert!(diagnostics.is_empty(), "{diagnostics:#?}");

            let moved_store = FunctionBody::from_id(&ctx, g)
                .blocks()
                .flat_map(|block| block.instructions())
                .find(|insn| matches!(insn.mnemonic(), Mnemonic::Store(_)))
                .expect("store moved with the split");
            let Mnemonic::Store(moved) = moved_store.mnemonic() else {
                unreachable!()
            };
            let LocalMemorySpaceId::Temp(moved_space) = moved.space else {
                panic!("store lost temporary-space provenance")
            };
            assert!(usize::from(moved_space) < ctx.bodies[g].temp_spaces.len());
        }
    }
}