llvm-native-core-ext 0.1.0

Extended modules for llvm-native-core: analysis passes, transforms, codegen extras, bitcode, linker, JIT, utilities. Part of the llvm-native workspace (https://crates.io/crates/llvm-native).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
//! X86 Stack Maps, PatchPoints, Statepoints, and GC Safepoint Module
//!
//! This module provides a complete implementation of LLVM's stack map
//! infrastructure for the X86 architecture, including:
//!
//! - **X86StackMaps** — Core stack map data structures and management for X86.
//! - **X86StackMapFormat** — Binary format for `.llvm_stackmaps` section:
//!   header, function records, stack size records, location records,
//!   live-out records, and constant pool records.
//! - **X86PatchPoint** — Patchable call/jump sequences using NOP sleds,
//!   metadata encoding in instruction streams, and runtime modification support.
//! - **X86StatePoint** — GC statepoint intrinsic lowering: root location
//!   encoding, derived/base pointer tracking, relocation records, and
//!   stack map generation for statepoints.
//! - **X86GCSafepoint** — Safepoint poll insertion (function entry and loop
//!   backedge), polling page mechanism, call safepoints.
//! - **X86StackMapGenerator** — Full stack map section generation with live
//!   variable tracking and register/stack/constant location encoding.
//! - **X86StackMapParser** — Parse `.llvm_stackmaps` sections, lookup by ID,
//!   resolve register names, extract live variable locations.
//! - **X86DeoptState** — Deoptimization bundle format with frame state,
//!   register state, and continuation point encoding.
//!
//! ## Integration Points
//!
//! - `llvm_native_core::codegen::*` — generic codegen infrastructure (MachineInstr, etc.)
//! - `llvm_native_core::x86::*` — X86 backend types (register info, calling conventions)
//!
//! ## References
//!
//! - LLVM Stack Map Format specification (version 3)
//! - LLVM Statepoint and PatchPoint intrinsic documentation
//! - Intel® 64 and IA-32 Architectures Software Developer's Manual
//! - System V AMD64 ABI
//!
//! Clean-room behavioral reconstruction. No LLVM C++ source code is consulted.

use llvm_native_core::codegen::{
    MachineBasicBlock, MachineFunction, MachineInstr, MachineOperand, PhysReg, VirtReg,
};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::io::{self, Cursor, Read, Seek, SeekFrom, Write};

// ============================================================================
// Constants
// ============================================================================

/// Stack map format version (current LLVM version is 3).
pub const STACK_MAP_VERSION: u8 = 3;

/// Reserved byte in the stack map header (always 0).
pub const STACK_MAP_RESERVED1: u8 = 0;

/// Reserved word in the stack map header (always 0).
pub const STACK_MAP_RESERVED2: u16 = 0;

/// Stack map section name in ELF object files.
pub const STACK_MAP_SECTION_NAME: &str = ".llvm_stackmaps";

/// Maximum number of locations per stack map record.
pub const MAX_LOCATIONS_PER_RECORD: usize = 256;

/// Maximum number of live-out registers per stack map record.
pub const MAX_LIVE_OUT_REGS: usize = 16;

/// Maximum number of constant pool entries.
pub const MAX_CONSTANT_ENTRIES: usize = 1024;

/// Size of a patchable NOP sled (in bytes) for X86-64.
pub const PATCHABLE_NOP_SLED_SIZE: usize = 64;

/// Size of a patchable call sequence prefix (in bytes).
pub const PATCHABLE_CALL_SEQUENCE_SIZE: usize = 16;

/// Size of a patchable jump sequence prefix (in bytes).
pub const PATCHABLE_JUMP_SEQUENCE_SIZE: usize = 10;

/// Polling page address for safepoint checks.
/// In a real runtime, this is mapped as non-readable when GC is needed.
pub const POLLING_PAGE_ADDRESS: u64 = 0x7FFF_FFFF_0000u64;

/// Dwarf register number for the stack pointer (RSP in X86-64).
pub const DWARF_REG_RSP: u16 = 7;

/// Dwarf register number for the frame pointer (RBP in X86-64).
pub const DWARF_REG_RBP: u16 = 6;

/// Dwarf register number for the instruction pointer (RIP in X86-64).
pub const DWARF_REG_RIP: u16 = 16;

/// Dwarf register number for RAX (return value / scratch).
pub const DWARF_REG_RAX: u16 = 0;

/// Maximum frame size supported by the stack map infrastructure.
pub const MAX_FRAME_SIZE: u64 = 0xFFFF_FFFFu64;

/// Deoptimization bundle magic number.
pub const DEOPT_BUNDLE_MAGIC: u32 = 0xDE0B_DE0B;

/// Deoptimization bundle version.
pub const DEOPT_BUNDLE_VERSION: u16 = 1;

// ============================================================================
// Enumerations
// ============================================================================

/// Location kind for stack map location records.
///
/// Describes where a live value is located at a safepoint or statepoint:
/// in a register, on the stack, as a constant, or as a vector splice.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum LocationKind {
    /// Value is in a register.
    Register = 1,
    /// Value is directly on the stack (frame pointer relative).
    Direct = 2,
    /// Value is indirect (pointer to stack location).
    Indirect = 3,
    /// Value is a constant.
    Constant = 4,
    /// Value is a constant at a known index in the constant pool.
    ConstantIndex = 5,
    /// Value is a vector splice (only for SIMD values stored across registers).
    VectorSplice = 6,
}

impl LocationKind {
    /// Parse a location kind from its byte representation.
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            1 => Some(LocationKind::Register),
            2 => Some(LocationKind::Direct),
            3 => Some(LocationKind::Indirect),
            4 => Some(LocationKind::Constant),
            5 => Some(LocationKind::ConstantIndex),
            6 => Some(LocationKind::VectorSplice),
            _ => None,
        }
    }

    /// Returns the human-readable name of this location kind.
    pub fn name(&self) -> &'static str {
        match self {
            LocationKind::Register => "Register",
            LocationKind::Direct => "Direct",
            LocationKind::Indirect => "Indirect",
            LocationKind::Constant => "Constant",
            LocationKind::ConstantIndex => "ConstantIndex",
            LocationKind::VectorSplice => "VectorSplice",
        }
    }

    /// Returns true if this kind implies a register location.
    pub fn is_register(&self) -> bool {
        matches!(self, LocationKind::Register | LocationKind::VectorSplice)
    }

    /// Returns true if this kind implies a stack location.
    pub fn is_stack(&self) -> bool {
        matches!(self, LocationKind::Direct | LocationKind::Indirect)
    }

    /// Returns true if this kind implies a constant value.
    pub fn is_constant(&self) -> bool {
        matches!(self, LocationKind::Constant | LocationKind::ConstantIndex)
    }
}

impl std::fmt::Display for LocationKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.name())
    }
}

/// Safepoint kind — describes the type of safepoint.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SafepointKind {
    /// Safepoint at a function entry (prologue).
    FunctionEntry,
    /// Safepoint at a loop backedge.
    LoopBackedge,
    /// Safepoint after a call instruction.
    AfterCall,
    /// Safepoint at an explicit statepoint.
    Statepoint,
    /// Safepoint for cooperative suspension.
    CooperativeSuspend,
    /// Safepoint at return (epilogue).
    FunctionExit,
}

impl SafepointKind {
    /// Returns the human-readable name.
    pub fn name(&self) -> &'static str {
        match self {
            SafepointKind::FunctionEntry => "function-entry",
            SafepointKind::LoopBackedge => "loop-backedge",
            SafepointKind::AfterCall => "after-call",
            SafepointKind::Statepoint => "statepoint",
            SafepointKind::CooperativeSuspend => "cooperative-suspend",
            SafepointKind::FunctionExit => "function-exit",
        }
    }
}

/// Patchable instruction type for runtime code modification.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PatchableType {
    /// Patchable call instruction (NOP sled preceding a call).
    Call,
    /// Patchable jump instruction (NOP sled preceding a jump).
    Jump,
    /// Patchable region (arbitrary code region that can be replaced).
    Region,
    /// Patchable trampoline (indirection through a trampoline).
    Trampoline,
}

/// Deoptimization reason — why a deoptimization occurred.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DeoptReason {
    /// Deoptimization due to type check failure.
    TypeCheckFailed { expected: String, actual: String },
    /// Deoptimization due to bounds check failure.
    BoundsCheckFailed { index: i64, length: i64 },
    /// Deoptimization due to null check failure.
    NullCheckFailed,
    /// Deoptimization due to speculative optimization guard failure.
    SpeculationFailed { guard_id: u32 },
    /// Deoptimization due to class hierarchy analysis miss.
    CHAMiss,
    /// Deoptimization due to inline cache miss.
    InlineCacheMiss,
    /// Deoptimization due to explicit deoptimize call.
    ExplicitDeopt { reason: String },
    /// Deoptimization for debugging (e.g., breakpoint reached).
    DebugDeopt,
    /// Other deoptimization reason.
    Other(String),
}

impl DeoptReason {
    /// Returns a short description of this deopt reason.
    pub fn description(&self) -> String {
        match self {
            DeoptReason::TypeCheckFailed { expected, actual } => {
                format!("Type check failed: expected {}, got {}", expected, actual)
            }
            DeoptReason::BoundsCheckFailed { index, length } => {
                format!(
                    "Bounds check failed: index {} out of bounds [0, {})",
                    index, length
                )
            }
            DeoptReason::NullCheckFailed => "Null check failed".to_string(),
            DeoptReason::SpeculationFailed { guard_id } => {
                format!("Speculation guard {} failed", guard_id)
            }
            DeoptReason::CHAMiss => "Class hierarchy analysis miss".to_string(),
            DeoptReason::InlineCacheMiss => "Inline cache miss".to_string(),
            DeoptReason::ExplicitDeopt { reason } => {
                format!("Explicit deoptimization: {}", reason)
            }
            DeoptReason::DebugDeopt => "Debug deoptimization".to_string(),
            DeoptReason::Other(s) => s.clone(),
        }
    }
}

// ============================================================================
// X86 Register Name Resolution
// ============================================================================

/// X86 Dwarf register name lookup table.
///
/// Maps Dwarf register numbers to human-readable X86 register names.
/// Supports both 32-bit and 64-bit register naming conventions.
#[derive(Debug, Clone)]
pub struct X86RegisterNames {
    /// Map from Dwarf register number to 64-bit register name.
    names_64: HashMap<u16, String>,
    /// Map from Dwarf register number to 32-bit register name.
    names_32: HashMap<u16, String>,
    /// Whether to use 64-bit names (true) or 32-bit names (false).
    use_64bit: bool,
}

impl X86RegisterNames {
    /// Create a new register name lookup table.
    pub fn new(use_64bit: bool) -> Self {
        let mut names_64 = HashMap::new();
        let mut names_32 = HashMap::new();

        // General-purpose registers (64-bit names)
        names_64.insert(0, "RAX".to_string());
        names_64.insert(1, "RDX".to_string());
        names_64.insert(2, "RCX".to_string());
        names_64.insert(3, "RBX".to_string());
        names_64.insert(4, "RSI".to_string());
        names_64.insert(5, "RDI".to_string());
        names_64.insert(6, "RBP".to_string());
        names_64.insert(7, "RSP".to_string());
        names_64.insert(8, "R8".to_string());
        names_64.insert(9, "R9".to_string());
        names_64.insert(10, "R10".to_string());
        names_64.insert(11, "R11".to_string());
        names_64.insert(12, "R12".to_string());
        names_64.insert(13, "R13".to_string());
        names_64.insert(14, "R14".to_string());
        names_64.insert(15, "R15".to_string());
        names_64.insert(16, "RIP".to_string());

        // General-purpose registers (32-bit names)
        names_32.insert(0, "EAX".to_string());
        names_32.insert(1, "EDX".to_string());
        names_32.insert(2, "ECX".to_string());
        names_32.insert(3, "EBX".to_string());
        names_32.insert(4, "ESI".to_string());
        names_32.insert(5, "EDI".to_string());
        names_32.insert(6, "EBP".to_string());
        names_32.insert(7, "ESP".to_string());
        names_32.insert(8, "R8D".to_string());
        names_32.insert(9, "R9D".to_string());
        names_32.insert(10, "R10D".to_string());
        names_32.insert(11, "R11D".to_string());
        names_32.insert(12, "R12D".to_string());
        names_32.insert(13, "R13D".to_string());
        names_32.insert(14, "R14D".to_string());
        names_32.insert(15, "R15D".to_string());
        names_32.insert(16, "EIP".to_string());

        // XMM registers (64-bit names are the same as 32-bit for XMM/YMM/ZMM)
        for i in 0..32u16 {
            let idx = i + 17;
            let name = if i < 16 {
                format!("XMM{}", i)
            } else {
                format!("XMM{}", i)
            };
            names_64.insert(idx, name.clone());
            names_32.insert(idx, name);
        }

        // YMM registers
        for i in 0..32u16 {
            let idx = i + 49;
            let name = format!("YMM{}", i);
            names_64.insert(idx, name.clone());
            names_32.insert(idx, name);
        }

        // ZMM registers
        for i in 0..32u16 {
            let idx = i + 81;
            let name = format!("ZMM{}", i);
            names_64.insert(idx, name.clone());
            names_32.insert(idx, name);
        }

        // Flag register
        names_64.insert(49, "EFLAGS".to_string());
        names_32.insert(49, "EFLAGS".to_string());

        // Segment registers
        names_64.insert(50, "ES".to_string());
        names_64.insert(51, "CS".to_string());
        names_64.insert(52, "SS".to_string());
        names_64.insert(53, "DS".to_string());
        names_64.insert(54, "FS".to_string());
        names_64.insert(55, "GS".to_string());
        names_32.insert(50, "ES".to_string());
        names_32.insert(51, "CS".to_string());
        names_32.insert(52, "SS".to_string());
        names_32.insert(53, "DS".to_string());
        names_32.insert(54, "FS".to_string());
        names_32.insert(55, "GS".to_string());

        X86RegisterNames {
            names_64,
            names_32,
            use_64bit,
        }
    }

    /// Resolve a Dwarf register number to its human-readable name.
    pub fn resolve(&self, dwarf_reg: u16) -> String {
        if self.use_64bit {
            self.names_64
                .get(&dwarf_reg)
                .cloned()
                .unwrap_or_else(|| format!("Reg({})", dwarf_reg))
        } else {
            self.names_32
                .get(&dwarf_reg)
                .cloned()
                .unwrap_or_else(|| format!("Reg({})", dwarf_reg))
        }
    }

    /// Set whether to use 64-bit register naming.
    pub fn set_64bit(&mut self, use_64bit: bool) {
        self.use_64bit = use_64bit;
    }

    /// Returns true if this Dwarf register number is a general-purpose register.
    pub fn is_gpr(&self, dwarf_reg: u16) -> bool {
        dwarf_reg <= 15
    }

    /// Returns true if this Dwarf register number is an XMM register.
    pub fn is_xmm(&self, dwarf_reg: u16) -> bool {
        (17..49).contains(&dwarf_reg)
    }

    /// Returns true if this Dwarf register number is a YMM register.
    pub fn is_ymm(&self, dwarf_reg: u16) -> bool {
        (49..81).contains(&dwarf_reg)
    }

    /// Returns true if this Dwarf register number is a ZMM register.
    pub fn is_zmm(&self, dwarf_reg: u16) -> bool {
        (81..113).contains(&dwarf_reg)
    }

    /// Returns true if this Dwarf register is a caller-saved register (X86-64 SYSV).
    pub fn is_caller_saved(&self, dwarf_reg: u16) -> bool {
        matches!(
            dwarf_reg,
            0   // RAX
            | 1   // RDX
            | 2   // RCX
            | 4   // RSI
            | 5   // RDI
            | 8   // R8
            | 9   // R9
            | 10  // R10
            | 11 // R11
        ) || self.is_xmm(dwarf_reg)
    }

    /// Returns true if this Dwarf register is a callee-saved register (X86-64 SYSV).
    pub fn is_callee_saved(&self, dwarf_reg: u16) -> bool {
        matches!(
            dwarf_reg,
            3   // RBX
            | 6   // RBP
            | 7   // RSP
            | 12  // R12
            | 13  // R13
            | 14  // R14
            | 15 // R15
        )
    }
}

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

// ============================================================================
// X86StackMapFormat — Core Data Types
// ============================================================================

/// Stack map binary format header.
///
/// The header identifies the version of the stack map format and reserves
/// space for future extensions. The header is 8 bytes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StackMapHeader {
    /// Stack map format version (currently 3).
    pub version: u8,
    /// Reserved byte 1 (must be 0).
    pub reserved1: u8,
    /// Reserved word (must be 0).
    pub reserved2: u16,
    /// Reserved padding (64-bit alignment).
    pub reserved3: u32,
}

impl StackMapHeader {
    /// Create a new stack map header with the given version.
    pub fn new(version: u8) -> Self {
        StackMapHeader {
            version,
            reserved1: 0,
            reserved2: 0,
            reserved3: 0,
        }
    }

    /// Create a header for the current version (3).
    pub fn current() -> Self {
        StackMapHeader::new(STACK_MAP_VERSION)
    }

    /// Serialize the header to bytes.
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut buf = Vec::with_capacity(8);
        buf.push(self.version);
        buf.push(self.reserved1);
        buf.extend_from_slice(&self.reserved2.to_le_bytes());
        buf.extend_from_slice(&self.reserved3.to_le_bytes());
        buf
    }

    /// Deserialize a header from a byte reader.
    pub fn from_reader<R: Read>(reader: &mut R) -> io::Result<Self> {
        let mut version_buf = [0u8; 1];
        reader.read_exact(&mut version_buf)?;
        let version = version_buf[0];

        let mut reserved1_buf = [0u8; 1];
        reader.read_exact(&mut reserved1_buf)?;
        let reserved1 = reserved1_buf[0];

        let mut reserved2_buf = [0u8; 2];
        reader.read_exact(&mut reserved2_buf)?;
        let reserved2 = u16::from_le_bytes(reserved2_buf);

        let mut reserved3_buf = [0u8; 4];
        reader.read_exact(&mut reserved3_buf)?;
        let reserved3 = u32::from_le_bytes(reserved3_buf);

        Ok(StackMapHeader {
            version,
            reserved1,
            reserved2,
            reserved3,
        })
    }

    /// Validate the header fields.
    pub fn validate(&self) -> Result<(), String> {
        if self.version != STACK_MAP_VERSION {
            return Err(format!(
                "Unsupported stack map version: {} (expected {})",
                self.version, STACK_MAP_VERSION
            ));
        }
        if self.reserved1 != 0 {
            return Err(format!(
                "Invalid reserved byte 1: {} (expected 0)",
                self.reserved1
            ));
        }
        if self.reserved2 != 0 {
            return Err(format!(
                "Invalid reserved word 2: {} (expected 0)",
                self.reserved2
            ));
        }
        Ok(())
    }
}

impl Default for StackMapHeader {
    fn default() -> Self {
        StackMapHeader::current()
    }
}

/// Stack map function record.
///
/// Each function record describes the stack map entries for a single function:
/// its address in memory, the total stack frame size, and the number of
/// stack size / stack map records it contains.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StackMapFunctionRecord {
    /// Address of the function in memory (relative to the load address).
    pub function_address: u64,
    /// Total stack frame size (in bytes).
    pub stack_size: u64,
    /// Number of stack size records for this function.
    pub stack_size_count: u32,
    /// Number of stack map records (safepoints/statepoints) for this function.
    pub record_count: u32,
}

impl StackMapFunctionRecord {
    /// Create a new function record.
    pub fn new(
        function_address: u64,
        stack_size: u64,
        stack_size_count: u32,
        record_count: u32,
    ) -> Self {
        StackMapFunctionRecord {
            function_address,
            stack_size,
            stack_size_count,
            record_count,
        }
    }

    /// Serialize the function record to bytes (3 × u64, i.e., 24 bytes).
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut buf = Vec::with_capacity(24);
        buf.extend_from_slice(&self.function_address.to_le_bytes());
        buf.extend_from_slice(&self.stack_size.to_le_bytes());
        // Pack stack_size_count and record_count into the third u64.
        let packed: u64 = (self.record_count as u64) << 32 | (self.stack_size_count as u64);
        buf.extend_from_slice(&packed.to_le_bytes());
        buf
    }

    /// Deserialize a function record from a byte reader.
    pub fn from_reader<R: Read>(reader: &mut R) -> io::Result<Self> {
        let mut addr_buf = [0u8; 8];
        reader.read_exact(&mut addr_buf)?;
        let function_address = u64::from_le_bytes(addr_buf);

        let mut stack_buf = [0u8; 8];
        reader.read_exact(&mut stack_buf)?;
        let stack_size = u64::from_le_bytes(stack_buf);

        let mut packed_buf = [0u8; 8];
        reader.read_exact(&mut packed_buf)?;
        let packed = u64::from_le_bytes(packed_buf);
        let stack_size_count = (packed & 0xFFFF_FFFF) as u32;
        let record_count = ((packed >> 32) & 0xFFFF_FFFF) as u32;

        Ok(StackMapFunctionRecord {
            function_address,
            stack_size,
            stack_size_count,
            record_count,
        })
    }
}

/// Stack size record.
///
/// Maps a function-relative offset to the stack frame size at that point.
/// This allows encoding stack size changes during the function (e.g.,
/// after dynamic stack allocation).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StackSizeRecord {
    /// Offset from the function start (in bytes).
    pub function_offset: u64,
    /// Stack frame size at this offset (in bytes).
    pub stack_size: u64,
}

impl StackSizeRecord {
    /// Create a new stack size record.
    pub fn new(function_offset: u64, stack_size: u64) -> Self {
        StackSizeRecord {
            function_offset,
            stack_size,
        }
    }

    /// Serialize the stack size record to bytes (2 × u64 = 16 bytes).
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut buf = Vec::with_capacity(16);
        buf.extend_from_slice(&self.function_offset.to_le_bytes());
        buf.extend_from_slice(&self.stack_size.to_le_bytes());
        buf
    }

    /// Deserialize a stack size record from a byte reader.
    pub fn from_reader<R: Read>(reader: &mut R) -> io::Result<Self> {
        let mut offset_buf = [0u8; 8];
        reader.read_exact(&mut offset_buf)?;
        let function_offset = u64::from_le_bytes(offset_buf);

        let mut size_buf = [0u8; 8];
        reader.read_exact(&mut size_buf)?;
        let stack_size = u64::from_le_bytes(size_buf);

        Ok(StackSizeRecord {
            function_offset,
            stack_size,
        })
    }
}

/// Stack map location record.
///
/// Describes the location of a single live value at a safepoint or statepoint.
/// A location can be a register, stack slot, constant, or vector splice.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LocationRecord {
    /// The kind of location (register, direct, indirect, constant, etc.).
    pub kind: LocationKind,
    /// The Dwarf register number (for register/vector locations) or 0.
    pub dwarf_reg_num: u16,
    /// The offset: for stack locations, the offset from SP/BP; for constants,
    /// the value or constant pool index.
    pub offset: i32,
    /// Size of the location in bytes (0 for constant index, 8 for pointer).
    pub size: u16,
    /// Reserved field for alignment padding (must be 0).
    pub reserved: u16,
}

impl LocationRecord {
    /// Create a new register location record.
    pub fn new_register(dwarf_reg: u16, size: u16) -> Self {
        LocationRecord {
            kind: LocationKind::Register,
            dwarf_reg_num: dwarf_reg,
            offset: 0,
            size,
            reserved: 0,
        }
    }

    /// Create a new direct stack location record.
    pub fn new_direct(dwarf_reg: u16, offset: i32, size: u16) -> Self {
        LocationRecord {
            kind: LocationKind::Direct,
            dwarf_reg_num: dwarf_reg,
            offset,
            size,
            reserved: 0,
        }
    }

    /// Create a new indirect stack location record.
    pub fn new_indirect(dwarf_reg: u16, offset: i32, size: u16) -> Self {
        LocationRecord {
            kind: LocationKind::Indirect,
            dwarf_reg_num: dwarf_reg,
            offset,
            size,
            reserved: 0,
        }
    }

    /// Create a new constant location record.
    pub fn new_constant(value: i32) -> Self {
        LocationRecord {
            kind: LocationKind::Constant,
            dwarf_reg_num: 0,
            offset: value,
            size: 8, // Constants are always 8 bytes in this representation
            reserved: 0,
        }
    }

    /// Create a new constant-index location record.
    pub fn new_constant_index(index: i32) -> Self {
        LocationRecord {
            kind: LocationKind::ConstantIndex,
            dwarf_reg_num: 0,
            offset: index,
            size: 0,
            reserved: 0,
        }
    }

    /// Create a new vector splice location record.
    pub fn new_vector_splice(dwarf_reg: u16, offset: i32, size: u16) -> Self {
        LocationRecord {
            kind: LocationKind::VectorSplice,
            dwarf_reg_num: dwarf_reg,
            offset,
            size,
            reserved: 0,
        }
    }

    /// Serialize the location record to bytes (16 bytes).
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut buf = Vec::with_capacity(16);
        let kind_byte = self.kind as u8;
        buf.push(kind_byte);
        buf.push(0); // padding
        buf.extend_from_slice(&self.dwarf_reg_num.to_le_bytes());
        buf.extend_from_slice(&self.offset.to_le_bytes());
        buf.extend_from_slice(&self.size.to_le_bytes());
        buf.extend_from_slice(&self.reserved.to_le_bytes());
        buf
    }

    /// Deserialize a location record from a byte reader.
    pub fn from_reader<R: Read>(reader: &mut R) -> io::Result<Self> {
        let mut kind_buf = [0u8; 1];
        reader.read_exact(&mut kind_buf)?;
        let kind_val = kind_buf[0];

        let mut pad_buf = [0u8; 1];
        reader.read_exact(&mut pad_buf)?;

        let mut reg_buf = [0u8; 2];
        reader.read_exact(&mut reg_buf)?;
        let dwarf_reg_num = u16::from_le_bytes(reg_buf);

        let mut offset_buf = [0u8; 4];
        reader.read_exact(&mut offset_buf)?;
        let offset = i32::from_le_bytes(offset_buf);

        let mut size_buf = [0u8; 2];
        reader.read_exact(&mut size_buf)?;
        let size = u16::from_le_bytes(size_buf);

        let mut reserved_buf = [0u8; 2];
        reader.read_exact(&mut reserved_buf)?;
        let reserved = u16::from_le_bytes(reserved_buf);

        let kind = LocationKind::from_u8(kind_val).ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::InvalidData,
                format!("Unknown location kind: {}", kind_val),
            )
        })?;

        Ok(LocationRecord {
            kind,
            dwarf_reg_num,
            offset,
            size,
            reserved,
        })
    }
}

/// Live-out register record.
///
/// Describes a register that is live-out at a call statepoint.
/// These are registers that the called function may modify, so the
/// stack map records their position in the caller's frame.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LiveOutRecord {
    /// Dwarf register number of the live-out register.
    pub dwarf_reg_num: u16,
    /// Reserved field (must be 0).
    pub reserved: u16,
    /// Size of the live-out value in bytes.
    pub size: u8,
    /// Additional padding for alignment.
    pub padding: u8,
}

impl LiveOutRecord {
    /// Create a new live-out record.
    pub fn new(dwarf_reg_num: u16, size: u8) -> Self {
        LiveOutRecord {
            dwarf_reg_num,
            reserved: 0,
            size,
            padding: 0,
        }
    }

    /// Serialize the live-out record to bytes (8 bytes).
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut buf = Vec::with_capacity(8);
        buf.extend_from_slice(&self.dwarf_reg_num.to_le_bytes());
        buf.extend_from_slice(&self.reserved.to_le_bytes());
        buf.push(self.size);
        buf.push(self.padding);
        buf.extend_from_slice(&0u32.to_le_bytes()); // additional padding
        buf
    }

    /// Deserialize a live-out record from a byte reader.
    pub fn from_reader<R: Read>(reader: &mut R) -> io::Result<Self> {
        let mut reg_buf = [0u8; 2];
        reader.read_exact(&mut reg_buf)?;
        let dwarf_reg_num = u16::from_le_bytes(reg_buf);

        let mut reserved_buf = [0u8; 2];
        reader.read_exact(&mut reserved_buf)?;
        let reserved = u16::from_le_bytes(reserved_buf);

        let mut size_buf = [0u8; 1];
        reader.read_exact(&mut size_buf)?;
        let size = size_buf[0];

        let mut pad_buf = [0u8; 1];
        reader.read_exact(&mut pad_buf)?;
        let padding = pad_buf[0];

        // Skip 4 bytes of padding
        let mut skip_buf = [0u8; 4];
        reader.read_exact(&mut skip_buf)?;

        Ok(LiveOutRecord {
            dwarf_reg_num,
            reserved,
            size,
            padding,
        })
    }
}

/// Constant pool record.
///
/// Stores a 64-bit constant value referenced by `LocationKind::ConstantIndex`
/// location records.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConstantPoolRecord {
    /// The 64-bit constant value.
    pub value: u64,
}

impl ConstantPoolRecord {
    /// Create a new constant pool record.
    pub fn new(value: u64) -> Self {
        ConstantPoolRecord { value }
    }

    /// Serialize the constant pool record to bytes (8 bytes).
    pub fn to_bytes(&self) -> Vec<u8> {
        self.value.to_le_bytes().to_vec()
    }

    /// Deserialize a constant pool record from a byte reader.
    pub fn from_reader<R: Read>(reader: &mut R) -> io::Result<Self> {
        let mut buf = [0u8; 8];
        reader.read_exact(&mut buf)?;
        let value = u64::from_le_bytes(buf);
        Ok(ConstantPoolRecord { value })
    }
}

/// Stack map record — a single safepoint/statepoint entry.
///
/// Aggregates the patchpoint ID, instruction offset, location records,
/// and live-out records for a single garbage collection safepoint.
#[derive(Debug, Clone)]
pub struct StackMapRecord {
    /// Unique identifier for this stack map entry (patchpoint ID).
    pub id: u64,
    /// Offset from the function start to this stack map entry.
    pub instruction_offset: u32,
    /// Reserved field for alignment (must be 0).
    pub reserved: u16,
    /// Number of location records in this entry.
    pub num_locations: u16,
    /// Location records describing where live values are.
    pub locations: Vec<LocationRecord>,
    /// Live-out register records (for call statepoints).
    pub live_outs: Vec<LiveOutRecord>,
}

impl StackMapRecord {
    /// Create a new, empty stack map record.
    pub fn new(id: u64, instruction_offset: u32) -> Self {
        StackMapRecord {
            id,
            instruction_offset,
            reserved: 0,
            num_locations: 0,
            locations: Vec::new(),
            live_outs: Vec::new(),
        }
    }

    /// Add a location record.
    pub fn add_location(&mut self, location: LocationRecord) {
        self.locations.push(location);
        self.num_locations = self.locations.len() as u16;
    }

    /// Add a live-out record.
    pub fn add_live_out(&mut self, live_out: LiveOutRecord) {
        self.live_outs.push(live_out);
    }

    /// Get the number of location records.
    pub fn location_count(&self) -> usize {
        self.locations.len()
    }

    /// Get the number of live-out records.
    pub fn live_out_count(&self) -> usize {
        self.live_outs.len()
    }

    /// Serialize the stack map record header to bytes (without locations/live-outs).
    pub fn to_header_bytes(&self) -> Vec<u8> {
        let mut buf = Vec::with_capacity(16);
        buf.extend_from_slice(&self.id.to_le_bytes());
        buf.extend_from_slice(&self.instruction_offset.to_le_bytes());
        buf.extend_from_slice(&self.reserved.to_le_bytes());
        buf.extend_from_slice(&self.num_locations.to_le_bytes());
        buf
    }

    /// Deserialize a stack map record header from a byte reader.
    pub fn header_from_reader<R: Read>(reader: &mut R) -> io::Result<(u64, u32, u16, u16)> {
        let mut id_buf = [0u8; 8];
        reader.read_exact(&mut id_buf)?;
        let id = u64::from_le_bytes(id_buf);

        let mut offset_buf = [0u8; 4];
        reader.read_exact(&mut offset_buf)?;
        let instruction_offset = u32::from_le_bytes(offset_buf);

        let mut reserved_buf = [0u8; 2];
        reader.read_exact(&mut reserved_buf)?;
        let reserved = u16::from_le_bytes(reserved_buf);

        let mut num_buf = [0u8; 2];
        reader.read_exact(&mut num_buf)?;
        let num_locations = u16::from_le_bytes(num_buf);

        Ok((id, instruction_offset, reserved, num_locations))
    }
}

// ============================================================================
// X86StackMapFormat — Complete Binary Section Format
// ============================================================================

/// Complete in-memory representation of a `.llvm_stackmaps` section.
///
/// This struct holds the parsed or generated stack map data and provides
/// methods for serialization, deserialization, and querying.
#[derive(Debug, Clone)]
pub struct X86StackMapFormat {
    /// Stack map header (version info).
    pub header: StackMapHeader,
    /// Number of functions recorded.
    pub num_functions: u32,
    /// Number of constant pool entries.
    pub num_constants: u32,
    /// Function records (one per function with stack maps).
    pub functions: Vec<StackMapFunctionRecord>,
    /// Stack size records for all functions.
    pub stack_sizes: Vec<StackSizeRecord>,
    /// All constant pool entries.
    pub constants: Vec<ConstantPoolRecord>,
    /// Stack map records for all functions.
    pub records: Vec<StackMapRecord>,
    /// Raw section data (if loaded from binary).
    pub raw_data: Option<Vec<u8>>,
}

impl X86StackMapFormat {
    /// Create a new, empty stack map format.
    pub fn new() -> Self {
        X86StackMapFormat {
            header: StackMapHeader::current(),
            num_functions: 0,
            num_constants: 0,
            functions: Vec::new(),
            stack_sizes: Vec::new(),
            constants: Vec::new(),
            records: Vec::new(),
            raw_data: None,
        }
    }

    /// Add a function record and its associated stack size/stack map records.
    pub fn add_function(
        &mut self,
        func: StackMapFunctionRecord,
        sizes: Vec<StackSizeRecord>,
        recs: Vec<StackMapRecord>,
    ) {
        self.functions.push(func);
        self.stack_sizes.extend(sizes);
        self.records.extend(recs);
        self.num_functions = self.functions.len() as u32;
    }

    /// Add a constant pool entry.
    pub fn add_constant(&mut self, value: u64) -> u32 {
        let index = self.constants.len() as u32;
        self.constants.push(ConstantPoolRecord::new(value));
        self.num_constants = self.constants.len() as u32;
        index
    }

    /// Get a constant value by its pool index.
    pub fn get_constant(&self, index: u32) -> Option<u64> {
        self.constants.get(index as usize).map(|c| c.value)
    }

    /// Find all stack map records for a given function address.
    pub fn find_records_by_address(&self, address: u64) -> Vec<&StackMapRecord> {
        // Find the function record
        let mut record_offset = 0;
        for func in &self.functions {
            if func.function_address == address {
                let count = func.record_count as usize;
                return self.records[record_offset..record_offset + count]
                    .iter()
                    .collect();
            }
            record_offset += func.record_count as usize;
        }
        Vec::new()
    }

    /// Find a specific stack map record by ID.
    pub fn find_record_by_id(&self, id: u64) -> Option<&StackMapRecord> {
        self.records.iter().find(|r| r.id == id)
    }

    /// Get the total number of stack map records.
    pub fn total_records(&self) -> usize {
        self.records.len()
    }

    /// Get the total number of location records across all stack maps.
    pub fn total_locations(&self) -> usize {
        self.records.iter().map(|r| r.locations.len()).sum()
    }

    /// Serialize the complete stack map section to bytes.
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut buf: Vec<u8> = Vec::new();

        // Header (8 bytes)
        buf.extend_from_slice(&self.header.to_bytes());

        // num_functions (4 bytes)
        buf.extend_from_slice(&self.num_functions.to_le_bytes());

        // num_constants (4 bytes)
        buf.extend_from_slice(&self.num_constants.to_le_bytes());

        // num_records (4 bytes) — total across all functions
        let total_records = self.records.len() as u32;
        buf.extend_from_slice(&total_records.to_le_bytes());

        // Padding to align to 8 bytes
        let current_len = buf.len();
        if current_len % 8 != 0 {
            let padding = 8 - (current_len % 8);
            buf.extend_from_slice(&vec![0u8; padding]);
        }

        // Function records
        for func in &self.functions {
            buf.extend_from_slice(&func.to_bytes());
        }

        // Constant records
        for constant in &self.constants {
            buf.extend_from_slice(&constant.to_bytes());
        }

        // Stack map records (headers + locations + live-outs)
        // Note: In the actual LLVM format, all location records are stored
        // contiguously before the stack map record headers. But we use a
        // simplified layout here for clarity.
        for record in &self.records {
            buf.extend_from_slice(&record.to_header_bytes());
            // Location records for this stack map
            for loc in &record.locations {
                buf.extend_from_slice(&loc.to_bytes());
            }
            // Padding to 8-byte alignment
            let pad_len = (8 - (buf.len() % 8)) % 8;
            if pad_len > 0 {
                buf.extend_from_slice(&vec![0u8; pad_len]);
            }
            // Live-out count (2 bytes), padding (6 bytes)
            let live_out_count = record.live_outs.len() as u16;
            buf.extend_from_slice(&live_out_count.to_le_bytes());
            buf.extend_from_slice(&vec![0u8; 6]);
            // Live-out records
            for live_out in &record.live_outs {
                buf.extend_from_slice(&live_out.to_bytes());
            }
        }

        // Stack size records
        for size_rec in &self.stack_sizes {
            buf.extend_from_slice(&size_rec.to_bytes());
        }

        buf
    }

    /// Deserialize a complete stack map section from bytes.
    pub fn from_bytes(data: &[u8]) -> io::Result<Self> {
        let mut cursor = Cursor::new(data);

        let header = StackMapHeader::from_reader(&mut cursor)?;

        let mut num_func_buf = [0u8; 4];
        cursor.read_exact(&mut num_func_buf)?;
        let num_functions = u32::from_le_bytes(num_func_buf);

        let mut num_const_buf = [0u8; 4];
        cursor.read_exact(&mut num_const_buf)?;
        let num_constants = u32::from_le_bytes(num_const_buf);

        let mut num_rec_buf = [0u8; 4];
        cursor.read_exact(&mut num_rec_buf)?;
        let total_records = u32::from_le_bytes(num_rec_buf);

        // Align to 8 bytes
        let pos = cursor.position() as usize;
        if pos % 8 != 0 {
            let pad = 8 - (pos % 8);
            cursor.seek(SeekFrom::Current(pad as i64))?;
        }

        // Read function records
        let mut functions = Vec::with_capacity(num_functions as usize);
        for _ in 0..num_functions {
            functions.push(StackMapFunctionRecord::from_reader(&mut cursor)?);
        }

        // Read constants
        let mut constants = Vec::with_capacity(num_constants as usize);
        for _ in 0..num_constants {
            constants.push(ConstantPoolRecord::from_reader(&mut cursor)?);
        }

        // Read stack map records
        let mut records = Vec::with_capacity(total_records as usize);
        for _ in 0..total_records {
            let (id, instruction_offset, reserved, num_locations) =
                StackMapRecord::header_from_reader(&mut cursor)?;

            let mut record = StackMapRecord::new(id, instruction_offset);
            record.reserved = reserved;
            record.num_locations = num_locations;

            // Read location records
            for _ in 0..num_locations {
                record.add_location(LocationRecord::from_reader(&mut cursor)?);
            }

            // Align to 8 bytes
            let cur_pos = cursor.position() as usize;
            if cur_pos % 8 != 0 {
                let pad = 8 - (cur_pos % 8);
                cursor.seek(SeekFrom::Current(pad as i64))?;
            }

            // Read live-out records
            let mut live_count_buf = [0u8; 2];
            cursor.read_exact(&mut live_count_buf)?;
            let live_count = u16::from_le_bytes(live_count_buf);

            // Skip padding
            cursor.seek(SeekFrom::Current(6))?;

            for _ in 0..live_count {
                record.add_live_out(LiveOutRecord::from_reader(&mut cursor)?);
            }

            records.push(record);
        }

        // Read stack size records
        let mut stack_sizes = Vec::new();
        let total_sizes: usize = functions.iter().map(|f| f.stack_size_count as usize).sum();
        for _ in 0..total_sizes {
            stack_sizes.push(StackSizeRecord::from_reader(&mut cursor)?);
        }

        Ok(X86StackMapFormat {
            header,
            num_functions,
            num_constants,
            functions,
            stack_sizes,
            constants,
            records,
            raw_data: Some(data.to_vec()),
        })
    }

    /// Validate the structure of the stack map format.
    pub fn validate(&self) -> Result<(), Vec<String>> {
        let mut errors = Vec::new();

        if let Err(e) = self.header.validate() {
            errors.push(e);
        }

        let expected_records: usize = self.functions.iter().map(|f| f.record_count as usize).sum();
        if self.records.len() != expected_records {
            errors.push(format!(
                "Record count mismatch: expected {}, got {}",
                expected_records,
                self.records.len()
            ));
        }

        let expected_sizes: usize = self
            .functions
            .iter()
            .map(|f| f.stack_size_count as usize)
            .sum();
        if self.stack_sizes.len() != expected_sizes {
            errors.push(format!(
                "Stack size record count mismatch: expected {}, got {}",
                expected_sizes,
                self.stack_sizes.len()
            ));
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }
}

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

// ============================================================================
// X86StackMaps — Stack Map Management
// ============================================================================

/// Main stack map management struct for X86 targets.
///
/// `X86StackMaps` tracks all stack map data for a compilation unit,
/// including function records, location records, and constant pool entries.
/// It provides high-level APIs for registering functions, adding safepoints,
/// and generating the `.llvm_stackmaps` section.
#[derive(Debug, Clone)]
pub struct X86StackMaps {
    /// The underlying stack map format data.
    pub format: X86StackMapFormat,
    /// Register name resolver.
    pub reg_names: X86RegisterNames,
    /// Next patchpoint ID (incremented for each new stack map entry).
    pub next_id: u64,
    /// Function-specific data accumulated during compilation.
    pub functions_data: Vec<X86FunctionStackMapData>,
    /// Whether to emit the stack map section.
    pub enabled: bool,
    /// Whether to emit verbose stack map information.
    pub verbose: bool,
    /// Target triple for register name resolution.
    pub target_triple: String,
}

/// Per-function stack map accumulation data.
#[derive(Debug, Clone)]
pub struct X86FunctionStackMapData {
    /// Function name.
    pub name: String,
    /// Function address (to be filled during linking/emission).
    pub address: u64,
    /// Total stack frame size.
    pub stack_size: u64,
    /// Stack size records for this function.
    pub stack_sizes: Vec<StackSizeRecord>,
    /// Stack map records for this function.
    pub records: Vec<StackMapRecord>,
    /// Map from instruction offset to stack map ID.
    pub offset_to_id: HashMap<u32, u64>,
}

impl X86FunctionStackMapData {
    /// Create new function stack map data.
    pub fn new(name: &str, stack_size: u64) -> Self {
        X86FunctionStackMapData {
            name: name.to_string(),
            address: 0,
            stack_size,
            stack_sizes: Vec::new(),
            records: Vec::new(),
            offset_to_id: HashMap::new(),
        }
    }

    /// Add a stack size record.
    pub fn add_stack_size(&mut self, offset: u64, size: u64) {
        self.stack_sizes.push(StackSizeRecord::new(offset, size));
    }

    /// Add a stack map record.
    pub fn add_record(&mut self, record: StackMapRecord) {
        self.offset_to_id
            .insert(record.instruction_offset, record.id);
        self.records.push(record);
    }
}

impl X86StackMaps {
    /// Create a new X86 stack maps manager.
    pub fn new(target_triple: &str, use_64bit: bool) -> Self {
        X86StackMaps {
            format: X86StackMapFormat::new(),
            reg_names: X86RegisterNames::new(use_64bit),
            next_id: 0,
            functions_data: Vec::new(),
            enabled: true,
            verbose: false,
            target_triple: target_triple.to_string(),
        }
    }

    /// Allocate a new unique patchpoint/stack map ID.
    pub fn allocate_id(&mut self) -> u64 {
        let id = self.next_id;
        self.next_id += 1;
        id
    }

    /// Register a function for stack map tracking.
    pub fn register_function(&mut self, name: &str, stack_size: u64) -> usize {
        let data = X86FunctionStackMapData::new(name, stack_size);
        let index = self.functions_data.len();
        self.functions_data.push(data);
        index
    }

    /// Add a stack size record for a registered function.
    pub fn add_stack_size(&mut self, func_index: usize, offset: u64, size: u64) {
        if let Some(data) = self.functions_data.get_mut(func_index) {
            data.add_stack_size(offset, size);
        }
    }

    /// Add a stack map record for a registered function.
    pub fn add_record(&mut self, func_index: usize, record: StackMapRecord) {
        if let Some(data) = self.functions_data.get_mut(func_index) {
            data.add_record(record);
        }
    }

    /// Finalize all accumulated data into the stack map format.
    /// This should be called before emitting the section.
    pub fn finalize(&mut self) {
        self.format = X86StackMapFormat::new();

        for func_data in &self.functions_data {
            let func_record = StackMapFunctionRecord::new(
                func_data.address,
                func_data.stack_size,
                func_data.stack_sizes.len() as u32,
                func_data.records.len() as u32,
            );
            self.format.add_function(
                func_record,
                func_data.stack_sizes.clone(),
                func_data.records.clone(),
            );
        }
    }

    /// Generate the `.llvm_stackmaps` section bytes.
    pub fn emit_section(&mut self) -> Vec<u8> {
        self.finalize();
        self.format.to_bytes()
    }

    /// Generate assembly text for the `.llvm_stackmaps` section.
    pub fn emit_asm(&self) -> String {
        let mut asm = String::new();

        asm.push_str(&format!(
            "\t.section\t{},\"\",@progbits\n",
            STACK_MAP_SECTION_NAME
        ));

        let bytes = self.format.to_bytes();
        for chunk in bytes.chunks(16) {
            asm.push_str("\t.byte\t");
            let vals: Vec<String> = chunk.iter().map(|b| format!("{}", b)).collect();
            asm.push_str(&vals.join(", "));
            asm.push('\n');
        }

        asm
    }

    /// Look up a stack map record by its ID.
    pub fn lookup_record(&self, id: u64) -> Option<&StackMapRecord> {
        self.format.find_record_by_id(id)
    }

    /// Get all stack map records for a function.
    pub fn get_function_records(&self, func_index: usize) -> Option<&[StackMapRecord]> {
        self.functions_data
            .get(func_index)
            .map(|d| d.records.as_slice())
    }

    /// Get the total number of registered functions.
    pub fn function_count(&self) -> usize {
        self.functions_data.len()
    }

    /// Set whether stack map emission is enabled.
    pub fn set_enabled(&mut self, enabled: bool) {
        self.enabled = enabled;
    }

    /// Set verbose mode for debugging.
    pub fn set_verbose(&mut self, verbose: bool) {
        self.verbose = verbose;
    }

    /// Validate the stack map data.
    pub fn validate(&self) -> Result<(), Vec<String>> {
        let mut errors = Vec::new();

        // Check that all recorded IDs are unique
        let mut ids: HashSet<u64> = HashSet::new();
        for func_data in &self.functions_data {
            for record in &func_data.records {
                if !ids.insert(record.id) {
                    errors.push(format!("Duplicate stack map ID: {}", record.id));
                }
            }
        }

        // Check location count limits
        for func_data in &self.functions_data {
            for record in &func_data.records {
                if record.locations.len() > MAX_LOCATIONS_PER_RECORD {
                    errors.push(format!(
                        "Too many locations in record {} ({} > {})",
                        record.id,
                        record.locations.len(),
                        MAX_LOCATIONS_PER_RECORD,
                    ));
                }
                if record.live_outs.len() > MAX_LIVE_OUT_REGS {
                    errors.push(format!(
                        "Too many live-out regs in record {} ({} > {})",
                        record.id,
                        record.live_outs.len(),
                        MAX_LIVE_OUT_REGS,
                    ));
                }
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }
}

impl Default for X86StackMaps {
    fn default() -> Self {
        X86StackMaps::new("x86_64-unknown-linux-gnu", true)
    }
}

// ============================================================================
// X86PatchPoint — Patchable Code Sequences
// ============================================================================

/// Patchable instruction sequence builder for X86.
///
/// Implements `llvm.experimental.patchpoint.*` intrinsics support:
/// generates NOP sleds (patchable regions) that can be modified at runtime
/// by JIT compilers or self-modifying code. Supports patchable calls,
/// jump destinations, and arbitrary code regions.
///
/// ## NOP Sled Layout
///
/// A patchable NOP sled is a sequence of multi-byte NOP instructions that
/// precede the actual call/jump instruction. The runtime can overwrite
/// some or all of the NOP sled with actual instructions (e.g., to inline
/// a callee at a callsite).
///
/// ```
/// +------------------+
/// | NOP sled (64 B)  | ← patchable region (can be overwritten)
/// +------------------+
/// | CALL <target>    | ← actual call instruction (5 bytes)
/// +------------------+
/// ```
#[derive(Debug, Clone)]
pub struct X86PatchPoint {
    /// The patchpoint ID (matches the stack map ID).
    pub id: u64,
    /// The type of patchable instruction.
    pub patch_type: PatchableType,
    /// The size of the NOP sled in bytes.
    pub nop_sled_size: usize,
    /// The target address or symbol for the call/jump.
    pub target: Option<String>,
    /// The return type for patchable calls.
    pub return_type: Option<String>,
    /// Number of actual arguments passed to the call.
    pub num_args: u32,
    /// Calling convention used for the call.
    pub calling_convention: String,
    /// Encoded metadata bytes stored in the instruction stream.
    pub metadata: Vec<u8>,
    /// Whether the patchpoint is stackmap-relative (for relocations).
    pub is_stackmap_relative: bool,
}

impl X86PatchPoint {
    /// Create a new patchpoint for a call.
    pub fn new_call(id: u64, target: &str, num_args: u32) -> Self {
        X86PatchPoint {
            id,
            patch_type: PatchableType::Call,
            nop_sled_size: PATCHABLE_NOP_SLED_SIZE,
            target: Some(target.to_string()),
            return_type: None,
            num_args,
            calling_convention: "anyregcc".to_string(),
            metadata: Vec::new(),
            is_stackmap_relative: false,
        }
    }

    /// Create a new patchpoint for a call with a specific return type.
    pub fn new_typed_call(id: u64, target: &str, num_args: u32, ret_type: &str) -> Self {
        X86PatchPoint {
            id,
            patch_type: PatchableType::Call,
            nop_sled_size: PATCHABLE_NOP_SLED_SIZE,
            target: Some(target.to_string()),
            return_type: Some(ret_type.to_string()),
            num_args,
            calling_convention: "anyregcc".to_string(),
            metadata: Vec::new(),
            is_stackmap_relative: false,
        }
    }

    /// Create a new patchpoint for a void call (no return value).
    pub fn new_void_call(id: u64, target: &str, num_args: u32) -> Self {
        X86PatchPoint {
            id,
            patch_type: PatchableType::Call,
            nop_sled_size: PATCHABLE_NOP_SLED_SIZE,
            target: Some(target.to_string()),
            return_type: None,
            num_args,
            calling_convention: "anyregcc".to_string(),
            metadata: Vec::new(),
            is_stackmap_relative: false,
        }
    }

    /// Create a new patchable jump.
    pub fn new_jump(id: u64, target: &str) -> Self {
        X86PatchPoint {
            id,
            patch_type: PatchableType::Jump,
            nop_sled_size: PATCHABLE_JUMP_SEQUENCE_SIZE,
            target: Some(target.to_string()),
            return_type: None,
            num_args: 0,
            calling_convention: "".to_string(),
            metadata: Vec::new(),
            is_stackmap_relative: false,
        }
    }

    /// Create a new patchable region (arbitrary code area).
    pub fn new_region(id: u64, size: usize) -> Self {
        X86PatchPoint {
            id,
            patch_type: PatchableType::Region,
            nop_sled_size: size,
            target: None,
            return_type: None,
            num_args: 0,
            calling_convention: "".to_string(),
            metadata: Vec::new(),
            is_stackmap_relative: false,
        }
    }

    /// Set the calling convention for this patchpoint.
    pub fn set_calling_convention(&mut self, cc: &str) {
        self.calling_convention = cc.to_string();
    }

    /// Embed metadata bytes in the instruction stream.
    pub fn set_metadata(&mut self, data: &[u8]) {
        self.metadata = data.to_vec();
    }

    /// Set whether this is a stackmap-relative patchpoint.
    pub fn set_stackmap_relative(&mut self, relative: bool) {
        self.is_stackmap_relative = relative;
    }

    /// Generate the NOP sled bytes for this patchpoint.
    ///
    /// The NOP sled uses multi-byte NOP instructions for efficiency
    /// (fewer fetches to skip the sled).
    pub fn generate_nop_sled(&self) -> Vec<u8> {
        let size = self.nop_sled_size;
        let mut sled = Vec::with_capacity(size);

        // Fill with optimal multi-byte NOPs.
        // X86 NOP encodings:
        //   1 byte:  90
        //   2 bytes: 66 90
        //   3 bytes: 0F 1F 00
        //   4 bytes: 0F 1F 40 00
        //   5 bytes: 0F 1F 44 00 00
        //   6 bytes: 66 0F 1F 44 00 00
        //   7 bytes: 0F 1F 80 00 00 00 00
        //   8 bytes: 0F 1F 84 00 00 00 00 00
        //   9 bytes: 66 0F 1F 84 00 00 00 00 00
        let mut remaining = size;
        while remaining > 0 {
            match remaining {
                1 => {
                    sled.push(0x90);
                    remaining -= 1;
                }
                2 => {
                    sled.extend_from_slice(&[0x66, 0x90]);
                    remaining -= 2;
                }
                3 => {
                    sled.extend_from_slice(&[0x0F, 0x1F, 0x00]);
                    remaining -= 3;
                }
                x if x >= 9 => {
                    sled.extend_from_slice(&[0x66, 0x0F, 0x1F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00]);
                    remaining -= 9;
                }
                x if x >= 8 => {
                    sled.extend_from_slice(&[0x0F, 0x1F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00]);
                    remaining -= 8;
                }
                x if x >= 7 => {
                    sled.extend_from_slice(&[0x0F, 0x1F, 0x80, 0x00, 0x00, 0x00, 0x00]);
                    remaining -= 7;
                }
                x if x >= 6 => {
                    sled.extend_from_slice(&[0x66, 0x0F, 0x1F, 0x44, 0x00, 0x00]);
                    remaining -= 6;
                }
                x if x >= 5 => {
                    sled.extend_from_slice(&[0x0F, 0x1F, 0x44, 0x00, 0x00]);
                    remaining -= 5;
                }
                x if x >= 4 => {
                    sled.extend_from_slice(&[0x0F, 0x1F, 0x40, 0x00]);
                    remaining -= 4;
                }
                _ => {
                    sled.push(0x90);
                    remaining -= 1;
                }
            }
        }

        sled
    }

    /// Generate the machine instructions implementing this patchpoint.
    ///
    /// Returns a pair: (NOP sled instructions, actual call/jump instruction).
    pub fn generate_machine_instrs(&self) -> (Vec<MachineInstr>, Option<MachineInstr>) {
        let sled_instrs = self._gen_nop_sled_instrs();
        let call_instr = self._gen_call_or_jump_instr();
        (sled_instrs, call_instr)
    }

    /// Generate NOP sled as explicit NOP MachineInstr list.
    fn _gen_nop_sled_instrs(&self) -> Vec<MachineInstr> {
        let num_nops = if self.nop_sled_size >= 8 {
            self.nop_sled_size / 8
        } else {
            self.nop_sled_size
        };

        let mut instrs = Vec::with_capacity(num_nops);
        for _ in 0..num_nops {
            let mut instr = MachineInstr::new(0x90); // NOP opcode
            instr.push_imm(0);
            instrs.push(instr);
        }
        instrs
    }

    /// Generate the actual call or jump instruction.
    fn _gen_call_or_jump_instr(&self) -> Option<MachineInstr> {
        match self.patch_type {
            PatchableType::Call => {
                let mut instr = MachineInstr::new(0xE8); // CALL rel32
                if let Some(ref tgt) = self.target {
                    instr.push_label(tgt);
                } else {
                    instr.push_imm(0); // placeholder
                }
                Some(instr)
            }
            PatchableType::Jump => {
                let mut instr = MachineInstr::new(0xE9); // JMP rel32
                if let Some(ref tgt) = self.target {
                    instr.push_label(tgt);
                } else {
                    instr.push_imm(0);
                }
                Some(instr)
            }
            _ => None,
        }
    }

    /// Generate the LLVM IR assembly text for this patchpoint.
    pub fn to_ir_text(&self) -> String {
        let mut ir = String::new();
        ir.push_str(&format!(
            "  call {} @llvm.experimental.patchpoint.{}(\n",
            match self.patch_type {
                PatchableType::Call if self.return_type.is_some() => "any",
                _ => "void",
            },
            match self.patch_type {
                PatchableType::Call => "i64",
                PatchableType::Jump => "i64",
                _ => "void",
            },
        ));

        ir.push_str(&format!(
            "    i64 {}, i32 {}, i8* null",
            self.id, self.nop_sled_size
        ));
        if let Some(ref target) = self.target {
            ir.push_str(&format!(", i8* bitcast (void ()* @{} to i8*)", target));
        } else {
            ir.push_str(", i8* null");
        }

        // Add argument types
        for i in 0..self.num_args {
            ir.push_str(&format!(", i64 {}", i));
        }

        // Add metadata if present
        if !self.metadata.is_empty() {
            ir.push_str(&format!(
                ", i32 {}",
                std::str::from_utf8(&self.metadata).unwrap_or("<binary>")
            ));
        }

        ir.push(')');
        ir
    }

    /// Generate the corresponding stack map record for this patchpoint.
    pub fn generate_stack_map_record(&self, instruction_offset: u32) -> StackMapRecord {
        StackMapRecord::new(self.id, instruction_offset)
    }
}

impl Default for X86PatchPoint {
    fn default() -> Self {
        X86PatchPoint::new_void_call(0, "unknown", 0)
    }
}

// ============================================================================
// X86StatePoint — GC Statepoint Support
// ============================================================================

/// Represents a GC statepoint — the lowering of
/// `llvm.experimental.gc.statepoint` intrinsic.
///
/// A statepoint is a call site where the garbage collector may run.
/// It records the locations of all live GC pointers (roots) and
/// derived pointers so that the GC can find and update them.
///
/// ## Statepoint Structure
///
/// ```
/// %result = call token (i64, i32, <callee>, i32, i32, ...)*
///     @llvm.experimental.gc.statepoint.p0(
///         i64 <id>,               // statepoint ID
///         i32 <nop bytes>,       // number of patchable NOP bytes
///         <callee> <target>,      // function pointer being called
///         i32 <nargs>,            // number of call arguments
///         i32 <flags>,            // flags (unused, pass 0)
///         ... <call args>,        // arguments to the call
///         i32 0,                  // transition args (deprecated, pass 0)
///         i32 <num deopt args>,   // number of deopt args
///         ... <deopt args>,       // deoptimization bundle
///         ... <gc args>           // GC pointer arguments
///     )
/// ```
#[derive(Debug, Clone)]
pub struct X86StatePoint {
    /// The statepoint ID (unique identifier).
    pub id: u64,
    /// Number of NOP bytes before the call for patching.
    pub nop_bytes: u32,
    /// The target function being called.
    pub callee: String,
    /// Number of actual call arguments.
    pub num_call_args: u32,
    /// Call flags (currently unused, always 0).
    pub flags: u32,
    /// The call arguments (as LLVM values).
    pub call_args: Vec<X86StatepointValue>,
    /// Number of GC transition arguments (always 0).
    pub num_transition_args: u32,
    /// Number of deoptimization arguments.
    pub num_deopt_args: u32,
    /// Deoptimization bundle values.
    pub deopt_args: Vec<X86StatepointValue>,
    /// GC pointer arguments (roots).
    pub gc_args: Vec<X86StatepointValue>,
    /// The derived pointer IDs (indices into gc_args for derived pointers).
    pub derived_pointer_ids: Vec<u32>,
    /// The base pointer IDs (indices into gc_args for base pointers).
    pub base_pointer_ids: Vec<u32>,
    /// GC transition bundle.
    pub gc_transition_args: Vec<X86StatepointValue>,
    /// Relocation records for GC relocation.
    pub relocation_records: Vec<X86RelocationRecord>,
}

/// A value passed to a statepoint (call arg, deopt arg, or GC root).
#[derive(Debug, Clone)]
pub struct X86StatepointValue {
    /// The value representation (register, constant, or stack slot).
    pub repr: X86StatepointValueRepr,
    /// The type of the value.
    pub value_type: String,
    /// Whether this value is a GC pointer.
    pub is_gc_pointer: bool,
}

/// Representation of a statepoint value.
#[derive(Debug, Clone)]
pub enum X86StatepointValueRepr {
    /// Value is in a register.
    Register { dwarf_reg: u16, size: u16 },
    /// Value is on the stack.
    Stack { offset: i32, size: u16 },
    /// Value is an immediate constant.
    Constant { value: i64 },
    /// Value is undefined.
    Undef,
}

impl X86StatepointValue {
    /// Create a register value.
    pub fn reg(dwarf_reg: u16, value_type: &str) -> Self {
        X86StatepointValue {
            repr: X86StatepointValueRepr::Register { dwarf_reg, size: 8 },
            value_type: value_type.to_string(),
            is_gc_pointer: false,
        }
    }

    /// Create a stack value.
    pub fn stack(offset: i32, value_type: &str) -> Self {
        X86StatepointValue {
            repr: X86StatepointValueRepr::Stack { offset, size: 8 },
            value_type: value_type.to_string(),
            is_gc_pointer: false,
        }
    }

    /// Create a constant value.
    pub fn constant(value: i64, value_type: &str) -> Self {
        X86StatepointValue {
            repr: X86StatepointValueRepr::Constant { value },
            value_type: value_type.to_string(),
            is_gc_pointer: false,
        }
    }

    /// Create an undefined value.
    pub fn undef(value_type: &str) -> Self {
        X86StatepointValue {
            repr: X86StatepointValueRepr::Undef,
            value_type: value_type.to_string(),
            is_gc_pointer: false,
        }
    }

    /// Mark this value as a GC pointer.
    pub fn mark_gc_pointer(&mut self) {
        self.is_gc_pointer = true;
    }

    /// Generate a location record for this value.
    pub fn to_location_record(&self) -> Option<LocationRecord> {
        match self.repr {
            X86StatepointValueRepr::Register { dwarf_reg, size } => {
                Some(LocationRecord::new_register(dwarf_reg, size))
            }
            X86StatepointValueRepr::Stack { offset, size } => {
                Some(LocationRecord::new_indirect(DWARF_REG_RSP, offset, size))
            }
            X86StatepointValueRepr::Constant { value } => {
                Some(LocationRecord::new_constant(value as i32))
            }
            X86StatepointValueRepr::Undef => None,
        }
    }
}

/// GC relocation record — tracks a pointer that needs to be updated
/// after a statepoint call completes.
///
/// If the GC moves objects during a statepoint, all pointers into the
/// moved objects must be updated. Relocation records map a source
/// pointer (before the call) to a destination (after the call).
#[derive(Debug, Clone)]
pub struct X86RelocationRecord {
    /// The statepoint ID this relocation belongs to.
    pub statepoint_id: u64,
    /// Index into the GC args of the base pointer.
    pub base_ptr_index: u32,
    /// Index into the GC args of the derived pointer.
    pub derived_ptr_index: u32,
    /// Offset from the base to the derived pointer.
    pub offset_from_base: i64,
}

impl X86RelocationRecord {
    /// Create a new relocation record.
    pub fn new(
        statepoint_id: u64,
        base_ptr_index: u32,
        derived_ptr_index: u32,
        offset_from_base: i64,
    ) -> Self {
        X86RelocationRecord {
            statepoint_id,
            base_ptr_index,
            derived_ptr_index,
            offset_from_base,
        }
    }

    /// Returns true if this relocation is for a derived pointer.
    pub fn is_derived(&self) -> bool {
        self.derived_ptr_index != self.base_ptr_index
    }

    /// Returns true if this relocation has a non-zero offset.
    pub fn has_interior_offset(&self) -> bool {
        self.offset_from_base != 0
    }
}

impl X86StatePoint {
    /// Create a new statepoint.
    pub fn new(id: u64, callee: &str, num_call_args: u32) -> Self {
        X86StatePoint {
            id,
            nop_bytes: 0,
            callee: callee.to_string(),
            num_call_args,
            flags: 0,
            call_args: Vec::new(),
            num_transition_args: 0,
            num_deopt_args: 0,
            deopt_args: Vec::new(),
            gc_args: Vec::new(),
            derived_pointer_ids: Vec::new(),
            base_pointer_ids: Vec::new(),
            gc_transition_args: Vec::new(),
            relocation_records: Vec::new(),
        }
    }

    /// Add a call argument.
    pub fn add_call_arg(&mut self, arg: X86StatepointValue) {
        self.call_args.push(arg);
        self.num_call_args = self.call_args.len() as u32;
    }

    /// Add a deoptimization argument.
    pub fn add_deopt_arg(&mut self, arg: X86StatepointValue) {
        self.deopt_args.push(arg);
        self.num_deopt_args = self.deopt_args.len() as u32;
    }

    /// Add a GC root pointer.
    pub fn add_gc_root(&mut self, value: X86StatepointValue) -> u32 {
        let idx = self.gc_args.len() as u32;
        self.gc_args.push(value);
        self.base_pointer_ids.push(idx);
        idx
    }

    /// Add a derived GC pointer with its base pointer.
    pub fn add_derived_pointer(
        &mut self,
        derived: X86StatepointValue,
        base_index: u32,
        offset_from_base: i64,
    ) -> u32 {
        let derived_idx = self.gc_args.len() as u32;
        self.gc_args.push(derived);
        self.derived_pointer_ids.push(derived_idx);

        let reloc = X86RelocationRecord::new(self.id, base_index, derived_idx, offset_from_base);
        self.relocation_records.push(reloc);

        derived_idx
    }

    /// Set the number of patchable NOP bytes before the statepoint.
    pub fn set_nop_bytes(&mut self, nop_bytes: u32) {
        self.nop_bytes = nop_bytes;
    }

    /// Generate the LLVM IR text for `gc.statepoint`.
    pub fn to_ir_text(&self) -> String {
        let mut ir = String::new();

        ir.push_str(&format!(
            "  %result = call token (i64, i32, {}, i32, i32, ...)* @llvm.experimental.gc.statepoint.p0(\n",
            if self.callee.starts_with('@') {
                "i8*"
            } else {
                &self.callee
            }
        ));

        ir.push_str(&format!("    i64 {}, i32 {}", self.id, self.nop_bytes));
        ir.push_str(&format!(", i8* bitcast (void ()* @{} to i8*)", self.callee));
        ir.push_str(&format!(", i32 {}, i32 {}", self.num_call_args, self.flags));

        // Call args
        for arg in &self.call_args {
            ir.push_str(", ");
            ir.push_str(&format_arg_value(arg));
        }

        // Transition args
        ir.push_str(", i32 0, i32 0");
        ir.push_str(&format!(", i32 {}", self.num_deopt_args));

        // Deopt args
        for arg in &self.deopt_args {
            ir.push_str(", ");
            ir.push_str(&format_arg_value(arg));
        }

        // GC args
        for arg in &self.gc_args {
            ir.push_str(", ");
            ir.push_str(&format_arg_value(arg));
        }

        ir.push(')');
        ir
    }

    /// Generate the corresponding stack map record.
    pub fn generate_stack_map_record(&self, instruction_offset: u32) -> StackMapRecord {
        let mut record = StackMapRecord::new(self.id, instruction_offset);

        // Add locations for each GC root
        for gc_arg in &self.gc_args {
            if let Some(loc) = gc_arg.to_location_record() {
                record.add_location(loc);
            }
        }

        // Add locations for deopt args (if needed)
        for deopt_arg in &self.deopt_args {
            if let Some(loc) = deopt_arg.to_location_record() {
                record.add_location(loc);
            }
        }

        record
    }

    /// Get all GC root locations as location records.
    pub fn get_gc_root_locations(&self) -> Vec<LocationRecord> {
        self.gc_args
            .iter()
            .filter_map(|arg| arg.to_location_record())
            .collect()
    }

    /// Get derived pointer locations with their base pointer info.
    pub fn get_derived_locations(&self) -> Vec<(LocationRecord, u32, i64)> {
        self.derived_pointer_ids
            .iter()
            .filter_map(|&idx| {
                let reloc = self
                    .relocation_records
                    .iter()
                    .find(|r| r.derived_ptr_index == idx)?;
                let arg = self.gc_args.get(idx as usize)?;
                let loc = arg.to_location_record()?;
                Some((loc, reloc.base_ptr_index, reloc.offset_from_base))
            })
            .collect()
    }

    /// Get the base pointer location for a derived pointer index.
    pub fn get_base_for_derived(&self, derived_idx: u32) -> Option<&X86StatepointValue> {
        let reloc = self
            .relocation_records
            .iter()
            .find(|r| r.derived_ptr_index == derived_idx)?;
        self.gc_args.get(reloc.base_ptr_index as usize)
    }
}

/// Format an argument value for LLVM IR text.
fn format_arg_value(arg: &X86StatepointValue) -> String {
    match &arg.repr {
        X86StatepointValueRepr::Register { dwarf_reg, .. } => {
            format!("%reg{}", dwarf_reg)
        }
        X86StatepointValueRepr::Stack { offset, .. } => {
            format!("i64 %stack_{}", offset)
        }
        X86StatepointValueRepr::Constant { value } => {
            format!("i64 {}", value)
        }
        X86StatepointValueRepr::Undef => "undef".to_string(),
    }
}

// ============================================================================
// X86GCSafepoint — GC Safepoint Insertion
// ============================================================================

/// GC safepoint manager for X86 targets.
///
/// Handles insertion of safepoint polls at strategic locations:
/// - Function entry (prologue)
/// - Loop backedges
/// - After call instructions that may trigger GC
///
/// The safepoint poll mechanism uses a *polling page*: a special page
/// in memory that is normally readable. When the GC needs all threads
/// to stop, it unmaps this page. The safepoint poll reads from this
/// page; if the read succeeds, the thread continues. If a SIGSEGV
/// occurs, the signal handler stops the thread for GC.
///
/// ## Polling Sequence (X86-64)
///
/// ```asm
///     mov rax, [0x7FFFFF0000]   ; load from polling page
///     ; If SIGSEGV occurs here, thread is stopped for GC
///     test rax, rax              ; dummy use of the loaded value
/// ```
#[derive(Debug, Clone)]
pub struct X86GCSafepoint {
    /// Whether safepoint insertion is enabled.
    pub enabled: bool,
    /// The polling page address.
    pub polling_page_address: u64,
    /// The polling page access size (in bytes).
    pub polling_page_size: u64,
    /// Number of safepoints inserted.
    pub safepoint_count: u32,
    /// Whether to insert safepoints at function entry.
    pub insert_at_entry: bool,
    /// Whether to insert safepoints at loop backedges.
    pub insert_at_backedge: bool,
    /// Whether to insert safepoints after calls.
    pub insert_after_calls: bool,
    /// Backedge safepoint frequency (1 = every backedge, N = every Nth backedge).
    pub backedge_frequency: u32,
    /// The safepoint insertion statistics.
    pub stats: X86SafepointStats,
    /// List of inserted safepoint locations.
    pub safepoints: Vec<X86SafepointLocation>,
}

/// Safepoint insertion statistics.
#[derive(Debug, Clone, Default)]
pub struct X86SafepointStats {
    /// Number of function entry safepoints inserted.
    pub entry_safepoints: u32,
    /// Number of loop backedge safepoints inserted.
    pub backedge_safepoints: u32,
    /// Number of call safepoints inserted.
    pub call_safepoints: u32,
    /// Number of statepoint safepoints recorded.
    pub statepoint_safepoints: u32,
    /// Number of cooperative suspension points.
    pub coop_suspend_points: u32,
    /// Number of function exit safepoints.
    pub exit_safepoints: u32,
    /// Total number of safepoints.
    pub total: u32,
}

impl X86SafepointStats {
    /// Update total count.
    pub fn update_total(&mut self) {
        self.total = self.entry_safepoints
            + self.backedge_safepoints
            + self.call_safepoints
            + self.statepoint_safepoints
            + self.coop_suspend_points
            + self.exit_safepoints;
    }
}

/// A single safepoint location in generated code.
#[derive(Debug, Clone)]
pub struct X86SafepointLocation {
    /// The safepoint kind.
    pub kind: SafepointKind,
    /// The function this safepoint belongs to.
    pub function_name: String,
    /// The instruction offset within the function.
    pub instruction_offset: u32,
    /// The stack map ID associated with this safepoint.
    pub stack_map_id: u64,
    /// The machine instruction at this safepoint.
    pub machine_instr: Option<MachineInstr>,
}

impl X86SafepointLocation {
    /// Create a new safepoint location.
    pub fn new(
        kind: SafepointKind,
        function_name: &str,
        instruction_offset: u32,
        stack_map_id: u64,
    ) -> Self {
        X86SafepointLocation {
            kind,
            function_name: function_name.to_string(),
            instruction_offset,
            stack_map_id,
            machine_instr: None,
        }
    }

    /// Set the machine instruction at this safepoint.
    pub fn set_machine_instr(&mut self, instr: MachineInstr) {
        self.machine_instr = Some(instr);
    }
}

impl X86GCSafepoint {
    /// Create a new GC safepoint manager.
    pub fn new() -> Self {
        X86GCSafepoint {
            enabled: true,
            polling_page_address: POLLING_PAGE_ADDRESS,
            polling_page_size: 4096,
            safepoint_count: 0,
            insert_at_entry: true,
            insert_at_backedge: true,
            insert_after_calls: false,
            backedge_frequency: 1,
            stats: X86SafepointStats::default(),
            safepoints: Vec::new(),
        }
    }

    /// Enable or disable safepoint insertion.
    pub fn set_enabled(&mut self, enabled: bool) {
        self.enabled = enabled;
    }

    /// Set the polling page address.
    pub fn set_polling_page(&mut self, address: u64) {
        self.polling_page_address = address;
    }

    /// Configure which safepoint types to insert.
    pub fn configure(
        &mut self,
        at_entry: bool,
        at_backedge: bool,
        after_calls: bool,
        backedge_freq: u32,
    ) {
        self.insert_at_entry = at_entry;
        self.insert_at_backedge = at_backedge;
        self.insert_after_calls = after_calls;
        self.backedge_frequency = backedge_freq;
    }

    /// Generate the polling page load instruction sequence.
    ///
    /// Returns the machine instructions that implement the safepoint poll.
    pub fn generate_poll_sequence(&self) -> Vec<MachineInstr> {
        let mut seq = Vec::with_capacity(2);

        // MOV RAX, [polling_page_address]
        let mut mov_instr = MachineInstr::new(0x48A1); // MOV RAX, moffs64
        mov_instr.push_imm(self.polling_page_address as i64);
        seq.push(mov_instr);

        // TEST RAX, RAX — dummy use to ensure the load isn't optimized away
        let mut test_instr = MachineInstr::new(0x85); // TEST r, r/m
        test_instr.push_reg(DWARF_REG_RAX as u32);
        test_instr.push_reg(DWARF_REG_RAX as u32);
        seq.push(test_instr);

        seq
    }

    /// Generate the safepoint poll as LLVM IR.
    pub fn generate_poll_ir(&self) -> String {
        format!(
            "  %safepoint_load = load volatile i64, i64* inttoptr (i64 {} to i64*)\n",
            self.polling_page_address
        )
    }

    /// Insert a safepoint at function entry.
    ///
    /// Returns the safepoint location and generated instructions.
    pub fn insert_entry_safepoint(
        &mut self,
        func_name: &str,
        stack_map_id: u64,
    ) -> (X86SafepointLocation, Vec<MachineInstr>) {
        let loc = X86SafepointLocation::new(
            SafepointKind::FunctionEntry,
            func_name,
            0, // at function entry, offset 0
            stack_map_id,
        );
        self.stats.entry_safepoints += 1;
        self.stats.update_total();
        self.safepoints.push(loc.clone());
        self.safepoint_count += 1;

        (loc, self.generate_poll_sequence())
    }

    /// Insert a safepoint at a loop backedge.
    pub fn insert_backedge_safepoint(
        &mut self,
        func_name: &str,
        instruction_offset: u32,
        stack_map_id: u64,
    ) -> (X86SafepointLocation, Vec<MachineInstr>) {
        let loc = X86SafepointLocation::new(
            SafepointKind::LoopBackedge,
            func_name,
            instruction_offset,
            stack_map_id,
        );
        self.stats.backedge_safepoints += 1;
        self.stats.update_total();
        self.safepoints.push(loc.clone());
        self.safepoint_count += 1;

        (loc, self.generate_poll_sequence())
    }

    /// Insert a safepoint after a call instruction.
    pub fn insert_call_safepoint(
        &mut self,
        func_name: &str,
        instruction_offset: u32,
        stack_map_id: u64,
    ) -> (X86SafepointLocation, Vec<MachineInstr>) {
        let loc = X86SafepointLocation::new(
            SafepointKind::AfterCall,
            func_name,
            instruction_offset,
            stack_map_id,
        );
        self.stats.call_safepoints += 1;
        self.stats.update_total();
        self.safepoints.push(loc.clone());
        self.safepoint_count += 1;

        (loc, self.generate_poll_sequence())
    }

    /// Record a statepoint safepoint (does not insert additional poll).
    pub fn record_statepoint(
        &mut self,
        func_name: &str,
        instruction_offset: u32,
        stack_map_id: u64,
    ) -> X86SafepointLocation {
        let loc = X86SafepointLocation::new(
            SafepointKind::Statepoint,
            func_name,
            instruction_offset,
            stack_map_id,
        );
        self.stats.statepoint_safepoints += 1;
        self.stats.update_total();
        self.safepoints.push(loc.clone());
        self.safepoint_count += 1;
        loc
    }

    /// Insert a cooperative suspension safepoint.
    pub fn insert_cooperative_suspend(
        &mut self,
        func_name: &str,
        instruction_offset: u32,
        stack_map_id: u64,
    ) -> (X86SafepointLocation, Vec<MachineInstr>) {
        let loc = X86SafepointLocation::new(
            SafepointKind::CooperativeSuspend,
            func_name,
            instruction_offset,
            stack_map_id,
        );
        self.stats.coop_suspend_points += 1;
        self.stats.update_total();
        self.safepoints.push(loc.clone());
        self.safepoint_count += 1;

        (loc, self.generate_poll_sequence())
    }

    /// Get statistics for safepoint insertion.
    pub fn get_stats(&self) -> &X86SafepointStats {
        &self.stats
    }

    /// Get all safepoints for a specific function.
    pub fn get_function_safepoints(&self, func_name: &str) -> Vec<&X86SafepointLocation> {
        self.safepoints
            .iter()
            .filter(|sp| sp.function_name == func_name)
            .collect()
    }

    /// Check if a given instruction offset is a safepoint.
    pub fn is_safepoint(&self, func_name: &str, offset: u32) -> bool {
        self.safepoints
            .iter()
            .any(|sp| sp.function_name == func_name && sp.instruction_offset == offset)
    }

    /// Determine whether a backedge should receive a safepoint based on frequency.
    pub fn should_insert_backedge(&self, backedge_counter: u32) -> bool {
        if !self.insert_at_backedge || self.backedge_frequency == 0 {
            return false;
        }
        backedge_counter % self.backedge_frequency == 0
    }

    /// Reset all state (for re-use).
    pub fn reset(&mut self) {
        self.safepoint_count = 0;
        self.stats = X86SafepointStats::default();
        self.safepoints.clear();
    }
}

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

// ============================================================================
// X86StackMapGenerator — Stack Map Section Generation
// ============================================================================

/// Generates the `.llvm_stackmaps` section content from compiled functions.
///
/// The stack map generator tracks live variables at safepoints and statepoints,
/// encodes their locations as register, stack, or constant values, and
/// produces the binary stack map section format understood by LLVM runtimes.
#[derive(Debug, Clone)]
pub struct X86StackMapGenerator {
    /// The stack maps manager for accumulating data.
    pub stack_maps: X86StackMaps,
    /// The safepoint manager for tracking safepoint insertions.
    pub safepoint: X86GCSafepoint,
    /// Map from function name to its index in stack_maps.functions_data.
    pub function_index_map: HashMap<String, usize>,
    /// Live variable tracking state per function.
    pub live_var_state: HashMap<String, X86LiveVarState>,
    /// The register name resolver.
    pub reg_names: X86RegisterNames,
    /// Current function being processed.
    pub current_function: Option<String>,
    /// Current instruction offset within the current function.
    pub current_offset: u32,
}

/// Live variable tracking state for a function.
#[derive(Debug, Clone)]
pub struct X86LiveVarState {
    /// Map from virtual register to its current location.
    pub var_locations: HashMap<VirtReg, LocationRecord>,
    /// Map from virtual register to its type string.
    pub var_types: HashMap<VirtReg, String>,
    /// Map from virtual register to whether it's a GC pointer.
    pub gc_pointers: HashSet<VirtReg>,
    /// Stack slots currently in use.
    pub stack_slots: Vec<X86StackSlot>,
    /// Current stack frame size.
    pub frame_size: u64,
    /// Current instruction offset.
    pub offset: u32,
}

/// A stack slot allocated for spilling.
#[derive(Debug, Clone)]
pub struct X86StackSlot {
    /// Offset from the frame pointer (RBP).
    pub offset: i32,
    /// Size of the slot in bytes.
    pub size: u16,
    /// Whether this slot holds a GC pointer.
    pub is_gc_pointer: bool,
    /// The virtual register spilled to this slot.
    pub spilled_reg: Option<VirtReg>,
}

impl X86StackSlot {
    /// Create a new stack slot.
    pub fn new(offset: i32, size: u16) -> Self {
        X86StackSlot {
            offset,
            size,
            is_gc_pointer: false,
            spilled_reg: None,
        }
    }

    /// Mark this slot as holding a GC pointer.
    pub fn mark_gc_pointer(&mut self) {
        self.is_gc_pointer = true;
    }
}

impl X86LiveVarState {
    /// Create a new live variable state.
    pub fn new() -> Self {
        X86LiveVarState {
            var_locations: HashMap::new(),
            var_types: HashMap::new(),
            gc_pointers: HashSet::new(),
            stack_slots: Vec::new(),
            frame_size: 0,
            offset: 0,
        }
    }

    /// Record a variable's location.
    pub fn record_location(&mut self, reg: VirtReg, location: LocationRecord) {
        self.var_locations.insert(reg, location);
    }

    /// Record a variable's type.
    pub fn record_type(&mut self, reg: VirtReg, ty: &str) {
        self.var_types.insert(reg, ty.to_string());
    }

    /// Mark a variable as a GC pointer.
    pub fn mark_gc_pointer(&mut self, reg: VirtReg) {
        self.gc_pointers.insert(reg);
    }

    /// Check if a virtual register is a GC pointer.
    pub fn is_gc_pointer(&self, reg: VirtReg) -> bool {
        self.gc_pointers.contains(&reg)
    }

    /// Allocate a new stack slot for spilling.
    pub fn allocate_stack_slot(&mut self, size: u16) -> X86StackSlot {
        let offset = if self.stack_slots.is_empty() {
            -(size as i32) // First slot at -size from RBP
        } else {
            let last = self.stack_slots.last().unwrap();
            last.offset - (size as i32)
        };

        let slot = X86StackSlot::new(offset, size);
        self.stack_slots.push(slot.clone());

        // Update frame size estimate
        self.frame_size = self.frame_size.max((-offset) as u64);

        slot
    }

    /// Get the location of a live variable at the current point.
    pub fn get_live_location(&self, reg: VirtReg) -> Option<&LocationRecord> {
        self.var_locations.get(&reg)
    }

    /// Get all GC pointer locations that are currently live.
    pub fn get_live_gc_pointers(&self) -> Vec<(VirtReg, &LocationRecord)> {
        self.gc_pointers
            .iter()
            .filter_map(|reg| self.var_locations.get(reg).map(|loc| (*reg, loc)))
            .collect()
    }
}

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

impl X86StackMapGenerator {
    /// Create a new stack map generator for X86 targets.
    pub fn new(use_64bit: bool) -> Self {
        X86StackMapGenerator {
            stack_maps: X86StackMaps::new("x86_64-unknown-linux-gnu", use_64bit),
            safepoint: X86GCSafepoint::new(),
            function_index_map: HashMap::new(),
            live_var_state: HashMap::new(),
            reg_names: X86RegisterNames::new(use_64bit),
            current_function: None,
            current_offset: 0,
        }
    }

    /// Begin processing a function.
    pub fn begin_function(&mut self, name: &str, stack_size: u64) {
        self.current_function = Some(name.to_string());
        self.current_offset = 0;

        let func_index = self.stack_maps.register_function(name, stack_size);
        self.function_index_map.insert(name.to_string(), func_index);

        let state = X86LiveVarState::new();
        self.live_var_state.insert(name.to_string(), state);
    }

    /// End processing the current function.
    pub fn end_function(&mut self) {
        self.current_function = None;
        self.current_offset = 0;
    }

    /// Advance the instruction offset.
    pub fn advance_offset(&mut self, delta: u32) {
        self.current_offset += delta;
    }

    /// Record a register location for a variable.
    pub fn record_register_location(
        &mut self,
        func_name: &str,
        virt_reg: VirtReg,
        dwarf_reg: u16,
        size: u16,
        ty: &str,
        is_gc_ptr: bool,
    ) {
        if let Some(state) = self.live_var_state.get_mut(func_name) {
            let loc = LocationRecord::new_register(dwarf_reg, size);
            state.record_location(virt_reg, loc);
            state.record_type(virt_reg, ty);
            if is_gc_ptr {
                state.mark_gc_pointer(virt_reg);
            }
        }
    }

    /// Record a stack location for a variable.
    pub fn record_stack_location(
        &mut self,
        func_name: &str,
        virt_reg: VirtReg,
        offset: i32,
        size: u16,
        ty: &str,
        is_gc_ptr: bool,
        is_indirect: bool,
    ) {
        if let Some(state) = self.live_var_state.get_mut(func_name) {
            let loc = if is_indirect {
                LocationRecord::new_indirect(DWARF_REG_RSP, offset, size)
            } else {
                LocationRecord::new_direct(DWARF_REG_RSP, offset, size)
            };
            state.record_location(virt_reg, loc);
            state.record_type(virt_reg, ty);
            if is_gc_ptr {
                state.mark_gc_pointer(virt_reg);
            }
        }
    }

    /// Record a constant value for a variable.
    pub fn record_constant_location(
        &mut self,
        func_name: &str,
        virt_reg: VirtReg,
        value: i32,
        ty: &str,
    ) {
        if let Some(state) = self.live_var_state.get_mut(func_name) {
            let loc = LocationRecord::new_constant(value);
            state.record_location(virt_reg, loc);
            state.record_type(virt_reg, ty);
        }
    }

    /// Generate a stack map record at the current location.
    ///
    /// Captures all live GC pointer locations at this safepoint.
    pub fn generate_stack_map_record(
        &mut self,
        func_name: &str,
        id: u64,
    ) -> Option<StackMapRecord> {
        let state = self.live_var_state.get(func_name)?;
        let func_index = self.function_index_map.get(func_name)?;

        let mut record = StackMapRecord::new(id, self.current_offset);

        // Add locations for all live GC pointers
        let live_gc = state.get_live_gc_pointers();
        for (_reg, loc) in live_gc {
            record.add_location(loc.clone());
        }

        self.stack_maps.add_record(*func_index, record.clone());
        Some(record)
    }

    /// Generate a stack map record from a patchpoint.
    pub fn generate_from_patchpoint(
        &mut self,
        func_name: &str,
        patchpoint: &X86PatchPoint,
    ) -> Option<StackMapRecord> {
        let func_index = self.function_index_map.get(func_name)?;
        let record = patchpoint.generate_stack_map_record(self.current_offset);
        self.stack_maps.add_record(*func_index, record.clone());
        Some(record)
    }

    /// Generate a stack map record from a statepoint.
    pub fn generate_from_statepoint(
        &mut self,
        func_name: &str,
        statepoint: &X86StatePoint,
    ) -> Option<StackMapRecord> {
        let func_index = self.function_index_map.get(func_name)?;
        let record = statepoint.generate_stack_map_record(self.current_offset);
        self.stack_maps.add_record(*func_index, record.clone());
        Some(record)
    }

    /// Generate a stack map record from a safepoint location.
    pub fn generate_from_safepoint(
        &mut self,
        func_name: &str,
        sp: &X86SafepointLocation,
    ) -> Option<StackMapRecord> {
        self.current_offset = sp.instruction_offset;
        self.generate_stack_map_record(func_name, sp.stack_map_id)
    }

    /// Spill a register to a stack slot and record the location change.
    pub fn spill_register(
        &mut self,
        func_name: &str,
        virt_reg: VirtReg,
        size: u16,
    ) -> Option<X86StackSlot> {
        let state = self.live_var_state.get_mut(func_name)?;
        let is_gc_ptr = state.is_gc_pointer(virt_reg);
        let mut slot = state.allocate_stack_slot(size);
        if is_gc_ptr {
            slot.mark_gc_pointer();
        }
        slot.spilled_reg = Some(virt_reg);

        // Update the variable's location to point to the stack slot
        let loc = LocationRecord::new_direct(DWARF_REG_RSP, slot.offset, size);
        state.record_location(virt_reg, loc);

        Some(slot)
    }

    /// Reload a spilled register.
    pub fn reload_register(&mut self, func_name: &str, virt_reg: VirtReg, dwarf_reg: u16) {
        if let Some(state) = self.live_var_state.get_mut(func_name) {
            let ty = state.var_types.get(&virt_reg).cloned().unwrap_or_default();
            let size: u16 = 8; // Default pointer size
            let loc = LocationRecord::new_register(dwarf_reg, size);
            state.record_location(virt_reg, loc);
        }
    }

    /// Record a stack size change.
    pub fn record_stack_size_change(&mut self, func_name: &str, new_size: u64) {
        if let Some(func_index) = self.function_index_map.get(func_name) {
            self.stack_maps
                .add_stack_size(*func_index, self.current_offset as u64, new_size);
        }
    }

    /// Generate the complete `.llvm_stackmaps` section.
    pub fn generate_section(&mut self) -> Vec<u8> {
        self.stack_maps.emit_section()
    }

    /// Generate assembly text for the stack map section.
    pub fn generate_section_asm(&self) -> String {
        self.stack_maps.emit_asm()
    }

    /// Add a constant to the constant pool.
    pub fn add_constant(&mut self, value: u64) -> u32 {
        self.stack_maps.format.add_constant(value)
    }

    /// Get the current stack maps manager.
    pub fn get_stack_maps(&self) -> &X86StackMaps {
        &self.stack_maps
    }

    /// Get a mutable reference to the stack maps manager.
    pub fn get_stack_maps_mut(&mut self) -> &mut X86StackMaps {
        &mut self.stack_maps
    }

    /// Enable or disable safepoint insertion during generation.
    pub fn set_safepoints_enabled(&mut self, enabled: bool) {
        self.safepoint.set_enabled(enabled);
    }

    /// Finalize and validate the generated data.
    pub fn finalize(&mut self) -> Result<(), Vec<String>> {
        self.stack_maps.finalize();

        let mut errors = Vec::new();

        if let Err(e) = self.stack_maps.validate() {
            errors.extend(e);
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }
}

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

// ============================================================================
// X86StackMapParser — Stack Map Section Parser
// ============================================================================

/// Parser for the `.llvm_stackmaps` ELF section.
///
/// Provides methods to parse the binary stack map section, look up
/// stack map entries by ID, extract live variable locations, and
/// resolve Dwarf register numbers to human-readable names.
#[derive(Debug, Clone)]
pub struct X86StackMapParser {
    /// The parsed stack map format data.
    pub format: X86StackMapFormat,
    /// Register name resolver.
    pub reg_names: X86RegisterNames,
    /// Index: stack map ID → record.
    pub id_index: HashMap<u64, StackMapRecord>,
    /// Index: function address → function record.
    pub addr_index: HashMap<u64, StackMapFunctionRecord>,
    /// Whether parsing was successful.
    pub parsed: bool,
    /// Parse warnings (non-fatal).
    pub warnings: Vec<String>,
}

impl X86StackMapParser {
    /// Create a new stack map parser.
    pub fn new(use_64bit: bool) -> Self {
        X86StackMapParser {
            format: X86StackMapFormat::new(),
            reg_names: X86RegisterNames::new(use_64bit),
            id_index: HashMap::new(),
            addr_index: HashMap::new(),
            parsed: false,
            warnings: Vec::new(),
        }
    }

    /// Parse a `.llvm_stackmaps` section from raw bytes.
    pub fn parse(&mut self, data: &[u8]) -> Result<(), String> {
        self.warnings.clear();

        let format = X86StackMapFormat::from_bytes(data)
            .map_err(|e| format!("Failed to parse stack map section: {}", e))?;

        // Validate the format
        if let Err(errors) = format.validate() {
            return Err(format!("Validation errors: {}", errors.join("; ")));
        }

        // Build lookup indices
        for record in &format.records {
            if self.id_index.contains_key(&record.id) {
                self.warnings.push(format!(
                    "Duplicate stack map ID: {} (keeping first occurrence)",
                    record.id
                ));
            } else {
                self.id_index.insert(record.id, record.clone());
            }
        }

        for func in &format.functions {
            self.addr_index.insert(func.function_address, func.clone());
        }

        self.format = format;
        self.parsed = true;

        Ok(())
    }

    /// Parse a `.llvm_stackmaps` section from an ELF section.
    pub fn parse_section(&mut self, section_name: &str, data: &[u8]) -> Result<(), String> {
        if section_name != STACK_MAP_SECTION_NAME {
            return Err(format!(
                "Not a stack map section: '{}' (expected '{}')",
                section_name, STACK_MAP_SECTION_NAME
            ));
        }
        self.parse(data)
    }

    /// Look up a stack map record by its ID.
    pub fn lookup_by_id(&self, id: u64) -> Option<&StackMapRecord> {
        self.id_index.get(&id)
    }

    /// Look up stack map records by function address.
    pub fn lookup_by_address(&self, address: u64) -> Vec<&StackMapRecord> {
        self.format.find_records_by_address(address)
    }

    /// Look up a function record by its address.
    pub fn lookup_function(&self, address: u64) -> Option<&StackMapFunctionRecord> {
        self.addr_index.get(&address)
    }

    /// Extract live variable locations from a stack map record.
    ///
    /// Returns a list of (register name, offset, size) tuples describing
    /// where each live value is located.
    pub fn extract_live_locations(
        &self,
        record: &StackMapRecord,
    ) -> Vec<(String, LocationKind, i32, u16)> {
        record
            .locations
            .iter()
            .map(|loc| {
                let reg_name = self.reg_names.resolve(loc.dwarf_reg_num);
                (reg_name, loc.kind, loc.offset, loc.size)
            })
            .collect()
    }

    /// Extract only GC root locations (pointers) from a record.
    ///
    /// GC roots are typically identified by being pointer-sized (8 bytes
    /// in 64-bit mode, 4 bytes in 32-bit mode) and having register or
    /// stack locations.
    pub fn extract_gc_roots(
        &self,
        record: &StackMapRecord,
        pointer_size: u16,
    ) -> Vec<(String, i32)> {
        record
            .locations
            .iter()
            .filter(|loc| loc.size == pointer_size && loc.kind.is_register() || loc.kind.is_stack())
            .map(|loc| {
                let reg_name = self.reg_names.resolve(loc.dwarf_reg_num);
                (reg_name, loc.offset)
            })
            .collect()
    }

    /// Extract live-out register information from a record.
    pub fn extract_live_outs(&self, record: &StackMapRecord) -> Vec<(String, u8)> {
        record
            .live_outs
            .iter()
            .map(|lo| {
                let reg_name = self.reg_names.resolve(lo.dwarf_reg_num);
                (reg_name, lo.size)
            })
            .collect()
    }

    /// Resolve a Dwarf register number to its name.
    pub fn resolve_register(&self, dwarf_reg: u16) -> String {
        self.reg_names.resolve(dwarf_reg)
    }

    /// Get the constant value from the pool by index.
    pub fn get_constant(&self, index: u32) -> Option<u64> {
        self.format.get_constant(index)
    }

    /// Get all stack map IDs.
    pub fn get_all_ids(&self) -> Vec<u64> {
        let mut ids: Vec<u64> = self.id_index.keys().copied().collect();
        ids.sort();
        ids
    }

    /// Get the number of stack map records.
    pub fn record_count(&self) -> usize {
        self.format.total_records()
    }

    /// Get parse warnings.
    pub fn get_warnings(&self) -> &[String] {
        &self.warnings
    }

    /// Get the stack map format version.
    pub fn version(&self) -> u8 {
        self.format.header.version
    }

    /// Check if the parser has successfully parsed data.
    pub fn is_parsed(&self) -> bool {
        self.parsed
    }

    /// Dump all stack map records in a human-readable format.
    pub fn dump_records(&self) -> String {
        let mut output = String::new();

        output.push_str(&format!(
            "Stack Map Section (version {}, {} functions, {} constants, {} records)\n\n",
            self.format.header.version,
            self.format.functions.len(),
            self.format.constants.len(),
            self.format.records.len(),
        ));

        for func in &self.format.functions {
            output.push_str(&format!(
                "Function at 0x{:016X}: stack_size={}, records={}\n",
                func.function_address, func.stack_size, func.record_count
            ));
        }

        output.push('\n');

        for record in &self.format.records {
            output.push_str(&format!(
                "  Record ID={}: offset=0x{:04X}, {} locations, {} live-outs\n",
                record.id,
                record.instruction_offset,
                record.locations.len(),
                record.live_outs.len(),
            ));

            for (i, loc) in record.locations.iter().enumerate() {
                let reg_name = self.reg_names.resolve(loc.dwarf_reg_num);
                output.push_str(&format!(
                    "    loc[{}]: kind={}, reg={}, offset={}, size={}\n",
                    i, loc.kind, reg_name, loc.offset, loc.size,
                ));
            }

            for (i, lo) in record.live_outs.iter().enumerate() {
                let reg_name = self.reg_names.resolve(lo.dwarf_reg_num);
                output.push_str(&format!(
                    "    live-out[{}]: reg={}, size={}\n",
                    i, reg_name, lo.size,
                ));
            }
        }

        output
    }
}

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

// ============================================================================
// X86DeoptState — Deoptimization State
// ============================================================================

/// Deoptimization state for X86 targets.
///
/// When a speculative optimization fails at runtime (e.g., a type check
/// guard, bounds check, or inline cache miss), the runtime must
/// deoptimize: it reconstructs the interpreter state from the
/// deoptimization bundle, rewrites the stack frame, and resumes
/// execution in the interpreter at the correct continuation point.
#[derive(Debug, Clone)]
pub struct X86DeoptState {
    /// The deoptimization bundle magic number.
    pub magic: u32,
    /// The deoptimization bundle version.
    pub version: u16,
    /// The compilation unit ID this bundle belongs to.
    pub compilation_unit_id: u32,
    /// The frame state encoding: how to reconstruct the stack frame.
    pub frame_state: X86FrameState,
    /// The register state encoding: how to restore register values.
    pub register_state: X86RegisterState,
    /// The continuation point: where to resume execution in the interpreter.
    pub continuation_point: X86ContinuationPoint,
    /// The reason for deoptimization.
    pub reason: DeoptReason,
    /// Additional deoptimization bundle metadata.
    pub metadata: Vec<u8>,
}

/// Frame state encoding for deoptimization.
///
/// Describes how to reconstruct the interpreter's virtual stack frame
/// from the current compiled frame. This includes the mapping from
/// compiled-frame locations to interpreter locals and expression stack.
#[derive(Debug, Clone)]
pub struct X86FrameState {
    /// Total size of the frame to reconstruct (in bytes).
    pub frame_size: u32,
    /// Number of local variables to reconstruct.
    pub num_locals: u32,
    /// Number of expression stack slots to reconstruct.
    pub num_stack_slots: u32,
    /// Number of locked monitors to reconstruct.
    pub num_monitors: u32,
    /// The local variable encoding entries.
    pub locals: Vec<X86FrameSlot>,
    /// The expression stack encoding entries.
    pub stack: Vec<X86FrameSlot>,
    /// The monitor encoding entries.
    pub monitors: Vec<X86MonitorSlot>,
    /// Bytecode offset in the interpreted code.
    pub bytecode_offset: u32,
    /// Method reference for the reconstructed frame.
    pub method_ref: u64,
}

/// A single slot in the reconstructed frame.
#[derive(Debug, Clone)]
pub struct X86FrameSlot {
    /// The slot index (local number or stack slot number).
    pub index: u32,
    /// The location of this slot in the compiled frame.
    pub location: LocationRecord,
    /// The type of the value in this slot.
    pub value_type: String,
    /// Whether this is a reference (object pointer) type.
    pub is_reference: bool,
    /// Whether this value is live at this point.
    pub is_live: bool,
}

/// A monitor slot for lock state reconstruction.
#[derive(Debug, Clone)]
pub struct X86MonitorSlot {
    /// The monitor index.
    pub index: u32,
    /// The object reference being locked.
    pub object_location: LocationRecord,
    /// Whether this is a reentrant lock.
    pub is_reentrant: bool,
}

/// Register state encoding for deoptimization.
///
/// Describes how to restore the values of architectural registers
/// from the deoptimization bundle.
#[derive(Debug, Clone)]
pub struct X86RegisterState {
    /// Number of general-purpose registers with state.
    pub num_gprs: u32,
    /// Number of XMM registers with state.
    pub num_xmms: u32,
    /// Number of YMM registers with state.
    pub num_ymms: u32,
    /// Number of ZMM registers with state.
    pub num_zmms: u32,
    /// General-purpose register state entries.
    pub gprs: Vec<X86RegisterSlot>,
    /// XMM register state entries.
    pub xmms: Vec<X86RegisterSlot>,
    /// YMM register state entries.
    pub ymms: Vec<X86RegisterSlot>,
    /// ZMM register state entries.
    pub zmms: Vec<X86RegisterSlot>,
    /// RFLAGS register state.
    pub rflags: Option<u64>,
    /// RIP (instruction pointer) state.
    pub rip: Option<u64>,
}

/// A single register state entry.
#[derive(Debug, Clone)]
pub struct X86RegisterSlot {
    /// The Dwarf register number.
    pub dwarf_reg: u16,
    /// The register value.
    pub value: u64,
    /// Whether this register is a reference type.
    pub is_reference: bool,
}

/// Continuation point encoding for deoptimization.
///
/// Specifies where in the interpreter (or baseline compiler) to resume
/// execution after deoptimization has reconstructed the state.
#[derive(Debug, Clone)]
pub struct X86ContinuationPoint {
    /// The bytecode offset to resume at.
    pub bytecode_offset: u32,
    /// The bytecode method reference.
    pub method_ref: u64,
    /// The dispatch kind (interpreted, baseline JIT, etc.).
    pub dispatch_kind: X86DeoptDispatchKind,
    /// The exception handler offset (if resuming into a handler).
    pub exception_handler_offset: Option<u32>,
    /// Whether this is a re-execution of the same opcode.
    pub is_reexecute: bool,
}

/// Dispatch kind for deoptimization resumption.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86DeoptDispatchKind {
    /// Resume in the interpreter.
    Interpreter,
    /// Resume in the baseline JIT.
    BaselineJIT,
    /// Resume in the optimizing JIT (recompilation).
    OptimizingJIT,
    /// Resume at an exception handler.
    ExceptionHandler,
    /// Resume at an unwind stub.
    UnwindStub,
}

impl X86DeoptDispatchKind {
    /// Returns the human-readable name.
    pub fn name(&self) -> &'static str {
        match self {
            X86DeoptDispatchKind::Interpreter => "interpreter",
            X86DeoptDispatchKind::BaselineJIT => "baseline-jit",
            X86DeoptDispatchKind::OptimizingJIT => "optimizing-jit",
            X86DeoptDispatchKind::ExceptionHandler => "exception-handler",
            X86DeoptDispatchKind::UnwindStub => "unwind-stub",
        }
    }
}

impl Default for X86FrameSlot {
    fn default() -> Self {
        X86FrameSlot {
            index: 0,
            location: LocationRecord::new_register(0, 0),
            value_type: "i64".to_string(),
            is_reference: false,
            is_live: true,
        }
    }
}

impl X86FrameSlot {
    /// Create a new local variable slot.
    pub fn new_local(index: u32, location: LocationRecord, value_type: &str, is_ref: bool) -> Self {
        X86FrameSlot {
            index,
            location,
            value_type: value_type.to_string(),
            is_reference: is_ref,
            is_live: true,
        }
    }

    /// Create a new expression stack slot.
    pub fn new_stack(index: u32, location: LocationRecord, value_type: &str, is_ref: bool) -> Self {
        X86FrameSlot {
            index,
            location,
            value_type: value_type.to_string(),
            is_reference: is_ref,
            is_live: true,
        }
    }

    /// Mark this slot as dead (not live at this point).
    pub fn mark_dead(&mut self) {
        self.is_live = false;
    }
}

impl X86MonitorSlot {
    /// Create a new monitor slot.
    pub fn new(index: u32, object_location: LocationRecord, reentrant: bool) -> Self {
        X86MonitorSlot {
            index,
            object_location,
            is_reentrant: reentrant,
        }
    }
}

impl X86RegisterSlot {
    /// Create a new register slot.
    pub fn new(dwarf_reg: u16, value: u64, is_ref: bool) -> Self {
        X86RegisterSlot {
            dwarf_reg,
            value,
            is_reference: is_ref,
        }
    }
}

impl X86ContinuationPoint {
    /// Create a new continuation point for interpreter resumption.
    pub fn new_interpreter(bytecode_offset: u32, method_ref: u64, reexecute: bool) -> Self {
        X86ContinuationPoint {
            bytecode_offset,
            method_ref,
            dispatch_kind: X86DeoptDispatchKind::Interpreter,
            exception_handler_offset: None,
            is_reexecute: reexecute,
        }
    }

    /// Create a new continuation point for baseline JIT resumption.
    pub fn new_baseline(bytecode_offset: u32, method_ref: u64) -> Self {
        X86ContinuationPoint {
            bytecode_offset,
            method_ref,
            dispatch_kind: X86DeoptDispatchKind::BaselineJIT,
            exception_handler_offset: None,
            is_reexecute: false,
        }
    }

    /// Create a continuation point for an exception handler.
    pub fn new_exception_handler(
        bytecode_offset: u32,
        method_ref: u64,
        handler_offset: u32,
    ) -> Self {
        X86ContinuationPoint {
            bytecode_offset,
            method_ref,
            dispatch_kind: X86DeoptDispatchKind::ExceptionHandler,
            exception_handler_offset: Some(handler_offset),
            is_reexecute: false,
        }
    }
}

impl X86RegisterState {
    /// Create a new, empty register state.
    pub fn new() -> Self {
        X86RegisterState {
            num_gprs: 0,
            num_xmms: 0,
            num_ymms: 0,
            num_zmms: 0,
            gprs: Vec::new(),
            xmms: Vec::new(),
            ymms: Vec::new(),
            zmms: Vec::new(),
            rflags: None,
            rip: None,
        }
    }

    /// Add a general-purpose register state entry.
    pub fn add_gpr(&mut self, dwarf_reg: u16, value: u64, is_ref: bool) {
        self.gprs
            .push(X86RegisterSlot::new(dwarf_reg, value, is_ref));
        self.num_gprs = self.gprs.len() as u32;
    }

    /// Add an XMM register state entry.
    pub fn add_xmm(&mut self, dwarf_reg: u16, value: u64) {
        self.xmms
            .push(X86RegisterSlot::new(dwarf_reg, value, false));
        self.num_xmms = self.xmms.len() as u32;
    }

    /// Add a YMM register state entry.
    pub fn add_ymm(&mut self, dwarf_reg: u16, value: u64) {
        self.ymms
            .push(X86RegisterSlot::new(dwarf_reg, value, false));
        self.num_ymms = self.ymms.len() as u32;
    }

    /// Add a ZMM register state entry.
    pub fn add_zmm(&mut self, dwarf_reg: u16, value: u64) {
        self.zmms
            .push(X86RegisterSlot::new(dwarf_reg, value, false));
        self.num_zmms = self.zmms.len() as u32;
    }

    /// Set the RFLAGS register value.
    pub fn set_rflags(&mut self, rflags: u64) {
        self.rflags = Some(rflags);
    }

    /// Set the RIP register value.
    pub fn set_rip(&mut self, rip: u64) {
        self.rip = Some(rip);
    }

    /// Get a GPR value by Dwarf register number.
    pub fn get_gpr(&self, dwarf_reg: u16) -> Option<u64> {
        self.gprs
            .iter()
            .find(|slot| slot.dwarf_reg == dwarf_reg)
            .map(|slot| slot.value)
    }

    /// Check if a register holds a GC reference.
    pub fn is_gpr_reference(&self, dwarf_reg: u16) -> bool {
        self.gprs
            .iter()
            .find(|slot| slot.dwarf_reg == dwarf_reg)
            .map(|slot| slot.is_reference)
            .unwrap_or(false)
    }

    /// Get the total number of tracked registers.
    pub fn total_registers(&self) -> usize {
        self.gprs.len() + self.xmms.len() + self.ymms.len() + self.zmms.len()
    }
}

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

impl X86FrameState {
    /// Create a new, empty frame state.
    pub fn new(method_ref: u64, bytecode_offset: u32) -> Self {
        X86FrameState {
            frame_size: 0,
            num_locals: 0,
            num_stack_slots: 0,
            num_monitors: 0,
            locals: Vec::new(),
            stack: Vec::new(),
            monitors: Vec::new(),
            bytecode_offset,
            method_ref,
        }
    }

    /// Add a local variable slot.
    pub fn add_local(
        &mut self,
        index: u32,
        location: LocationRecord,
        value_type: &str,
        is_ref: bool,
    ) {
        self.locals
            .push(X86FrameSlot::new_local(index, location, value_type, is_ref));
        self.num_locals = self.locals.len() as u32;
        self.frame_size = self.frame_size.max(
            (index + 1) * 8, // rough size estimate
        );
    }

    /// Add an expression stack slot.
    pub fn add_stack_slot(
        &mut self,
        index: u32,
        location: LocationRecord,
        value_type: &str,
        is_ref: bool,
    ) {
        self.stack
            .push(X86FrameSlot::new_stack(index, location, value_type, is_ref));
        self.num_stack_slots = self.stack.len() as u32;
    }

    /// Add a monitor slot.
    pub fn add_monitor(&mut self, index: u32, object_location: LocationRecord, reentrant: bool) {
        self.monitors
            .push(X86MonitorSlot::new(index, object_location, reentrant));
        self.num_monitors = self.monitors.len() as u32;
    }

    /// Get all reference-typed slots that are live.
    pub fn get_live_refs(&self) -> Vec<&X86FrameSlot> {
        let mut refs: Vec<&X86FrameSlot> = Vec::new();

        refs.extend(self.locals.iter().filter(|s| s.is_reference && s.is_live));
        refs.extend(self.stack.iter().filter(|s| s.is_reference && s.is_live));

        refs
    }

    /// Mark all slots as dead (for conservative deopt).
    pub fn mark_all_dead(&mut self) {
        for local in &mut self.locals {
            local.mark_dead();
        }
        for slot in &mut self.stack {
            slot.mark_dead();
        }
    }
}

impl X86DeoptState {
    /// Create a new deoptimization state.
    pub fn new(
        compilation_unit_id: u32,
        frame_state: X86FrameState,
        register_state: X86RegisterState,
        continuation_point: X86ContinuationPoint,
        reason: DeoptReason,
    ) -> Self {
        X86DeoptState {
            magic: DEOPT_BUNDLE_MAGIC,
            version: DEOPT_BUNDLE_VERSION,
            compilation_unit_id,
            frame_state,
            register_state,
            continuation_point,
            reason,
            metadata: Vec::new(),
        }
    }

    /// Set additional metadata.
    pub fn set_metadata(&mut self, metadata: &[u8]) {
        self.metadata = metadata.to_vec();
    }

    /// Serialize the deoptimization bundle to bytes.
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut buf = Vec::new();

        // Header
        buf.extend_from_slice(&self.magic.to_le_bytes());
        buf.extend_from_slice(&self.version.to_le_bytes());
        buf.extend_from_slice(&self.compilation_unit_id.to_le_bytes());

        // Frame state
        buf.extend_from_slice(&self.frame_state.frame_size.to_le_bytes());
        buf.extend_from_slice(&self.frame_state.num_locals.to_le_bytes());
        buf.extend_from_slice(&self.frame_state.num_stack_slots.to_le_bytes());
        buf.extend_from_slice(&self.frame_state.num_monitors.to_le_bytes());
        buf.extend_from_slice(&self.frame_state.bytecode_offset.to_le_bytes());
        buf.extend_from_slice(&self.frame_state.method_ref.to_le_bytes());

        // Local slots
        for local in &self.frame_state.locals {
            buf.push(local.index as u8);
            buf.push(local.is_reference as u8);
            buf.push(local.is_live as u8);
            buf.push(0); // padding
            buf.extend_from_slice(&local.location.to_bytes());
        }

        // Stack slots
        for slot in &self.frame_state.stack {
            buf.push(slot.index as u8);
            buf.push(slot.is_reference as u8);
            buf.push(slot.is_live as u8);
            buf.push(0);
            buf.extend_from_slice(&slot.location.to_bytes());
        }

        // Monitor slots
        for monitor in &self.frame_state.monitors {
            buf.push(monitor.index as u8);
            buf.push(monitor.is_reentrant as u8);
            buf.extend_from_slice(&[0u8; 2]);
            buf.extend_from_slice(&monitor.object_location.to_bytes());
        }

        // Register state
        buf.extend_from_slice(&self.register_state.num_gprs.to_le_bytes());
        buf.extend_from_slice(&self.register_state.num_xmms.to_le_bytes());
        buf.extend_from_slice(&self.register_state.num_ymms.to_le_bytes());
        buf.extend_from_slice(&self.register_state.num_zmms.to_le_bytes());

        for gpr in &self.register_state.gprs {
            buf.extend_from_slice(&gpr.dwarf_reg.to_le_bytes());
            buf.push(gpr.is_reference as u8);
            buf.extend_from_slice(&[0u8; 5]); // padding
            buf.extend_from_slice(&gpr.value.to_le_bytes());
        }

        for xmm in &self.register_state.xmms {
            buf.extend_from_slice(&xmm.dwarf_reg.to_le_bytes());
            buf.extend_from_slice(&[0u8; 6]);
            buf.extend_from_slice(&xmm.value.to_le_bytes());
        }

        // Continuation point
        buf.extend_from_slice(&self.continuation_point.bytecode_offset.to_le_bytes());
        buf.extend_from_slice(&self.continuation_point.method_ref.to_le_bytes());
        buf.push(self.continuation_point.dispatch_kind as u8);
        buf.push(self.continuation_point.is_reexecute as u8);
        buf.extend_from_slice(&[0u8; 2]); // padding
        if let Some(handler) = self.continuation_point.exception_handler_offset {
            buf.extend_from_slice(&handler.to_le_bytes());
        } else {
            buf.extend_from_slice(&0u32.to_le_bytes());
        }

        // Reason string
        let reason_str = self.reason.description();
        let reason_bytes = reason_str.as_bytes();
        buf.extend_from_slice(&(reason_bytes.len() as u32).to_le_bytes());
        buf.extend_from_slice(reason_bytes);

        // Metadata
        buf.extend_from_slice(&(self.metadata.len() as u32).to_le_bytes());
        buf.extend_from_slice(&self.metadata);

        buf
    }

    /// Deserialize a deoptimization bundle from bytes.
    pub fn from_bytes(data: &[u8]) -> io::Result<Self> {
        let mut cursor = Cursor::new(data);

        let mut magic_buf = [0u8; 4];
        cursor.read_exact(&mut magic_buf)?;
        let magic = u32::from_le_bytes(magic_buf);

        if magic != DEOPT_BUNDLE_MAGIC {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!("Invalid deopt bundle magic: 0x{:08X}", magic),
            ));
        }

        let mut ver_buf = [0u8; 2];
        cursor.read_exact(&mut ver_buf)?;
        let version = u16::from_le_bytes(ver_buf);

        let mut cu_buf = [0u8; 4];
        cursor.read_exact(&mut cu_buf)?;
        let compilation_unit_id = u32::from_le_bytes(cu_buf);

        // Frame state
        let mut fs_size_buf = [0u8; 4];
        cursor.read_exact(&mut fs_size_buf)?;
        let frame_size = u32::from_le_bytes(fs_size_buf);

        let mut nl_buf = [0u8; 4];
        cursor.read_exact(&mut nl_buf)?;
        let num_locals = u32::from_le_bytes(nl_buf);

        let mut ns_buf = [0u8; 4];
        cursor.read_exact(&mut ns_buf)?;
        let num_stack_slots = u32::from_le_bytes(ns_buf);

        let mut nm_buf = [0u8; 4];
        cursor.read_exact(&mut nm_buf)?;
        let num_monitors = u32::from_le_bytes(nm_buf);

        let mut bc_buf = [0u8; 4];
        cursor.read_exact(&mut bc_buf)?;
        let bytecode_offset = u32::from_le_bytes(bc_buf);

        let mut mr_buf = [0u8; 8];
        cursor.read_exact(&mut mr_buf)?;
        let method_ref = u64::from_le_bytes(mr_buf);

        let mut frame_state = X86FrameState::new(method_ref, bytecode_offset);
        frame_state.frame_size = frame_size;

        // Read locals
        for _ in 0..num_locals {
            let mut idx_buf = [0u8; 1];
            cursor.read_exact(&mut idx_buf)?;
            let index = idx_buf[0] as u32;

            let mut is_ref_buf = [0u8; 1];
            cursor.read_exact(&mut is_ref_buf)?;
            let is_reference = is_ref_buf[0] != 0;

            let mut is_live_buf = [0u8; 1];
            cursor.read_exact(&mut is_live_buf)?;
            let is_live = is_live_buf[0] != 0;

            cursor.seek(SeekFrom::Current(1))?; // padding
            let location = LocationRecord::from_reader(&mut cursor)?;

            let mut slot = X86FrameSlot::new_local(index, location, "unknown", is_reference);
            if !is_live {
                slot.mark_dead();
            }
            frame_state.locals.push(slot);
        }
        frame_state.num_locals = frame_state.locals.len() as u32;

        // Read stack slots
        for _ in 0..num_stack_slots {
            let mut idx_buf = [0u8; 1];
            cursor.read_exact(&mut idx_buf)?;
            let index = idx_buf[0] as u32;

            let mut is_ref_buf = [0u8; 1];
            cursor.read_exact(&mut is_ref_buf)?;
            let is_reference = is_ref_buf[0] != 0;

            let mut is_live_buf = [0u8; 1];
            cursor.read_exact(&mut is_live_buf)?;
            let is_live = is_live_buf[0] != 0;

            cursor.seek(SeekFrom::Current(1))?;
            let location = LocationRecord::from_reader(&mut cursor)?;

            let mut slot = X86FrameSlot::new_stack(index, location, "unknown", is_reference);
            if !is_live {
                slot.mark_dead();
            }
            frame_state.stack.push(slot);
        }
        frame_state.num_stack_slots = frame_state.stack.len() as u32;

        // Read monitors
        for _ in 0..num_monitors {
            let mut idx_buf = [0u8; 1];
            cursor.read_exact(&mut idx_buf)?;
            let index = idx_buf[0] as u32;

            let mut re_buf = [0u8; 1];
            cursor.read_exact(&mut re_buf)?;
            let is_reentrant = re_buf[0] != 0;

            cursor.seek(SeekFrom::Current(2))?;
            let object_location = LocationRecord::from_reader(&mut cursor)?;

            frame_state
                .monitors
                .push(X86MonitorSlot::new(index, object_location, is_reentrant));
        }
        frame_state.num_monitors = frame_state.monitors.len() as u32;

        // Register state
        let mut ng_buf = [0u8; 4];
        cursor.read_exact(&mut ng_buf)?;
        let _num_gprs = u32::from_le_bytes(ng_buf);

        let mut nx_buf = [0u8; 4];
        cursor.read_exact(&mut nx_buf)?;
        let _num_xmms = u32::from_le_bytes(nx_buf);

        let mut ny_buf = [0u8; 4];
        cursor.read_exact(&mut ny_buf)?;
        let _num_ymms = u32::from_le_bytes(ny_buf);

        let mut nz_buf = [0u8; 4];
        cursor.read_exact(&mut nz_buf)?;
        let _num_zmms = u32::from_le_bytes(nz_buf);

        let mut register_state = X86RegisterState::new();

        for _ in 0.._num_gprs {
            let mut reg_buf = [0u8; 2];
            cursor.read_exact(&mut reg_buf)?;
            let dwarf_reg = u16::from_le_bytes(reg_buf);

            let mut ref_buf = [0u8; 1];
            cursor.read_exact(&mut ref_buf)?;
            let is_ref = ref_buf[0] != 0;

            cursor.seek(SeekFrom::Current(5))?;

            let mut val_buf = [0u8; 8];
            cursor.read_exact(&mut val_buf)?;
            let value = u64::from_le_bytes(val_buf);

            register_state.add_gpr(dwarf_reg, value, is_ref);
        }

        // Continuation point
        let mut cp_bc_buf = [0u8; 4];
        cursor.read_exact(&mut cp_bc_buf)?;
        let cp_bytecode_offset = u32::from_le_bytes(cp_bc_buf);

        let mut cp_mr_buf = [0u8; 8];
        cursor.read_exact(&mut cp_mr_buf)?;
        let cp_method_ref = u64::from_le_bytes(cp_mr_buf);

        let mut kind_buf = [0u8; 1];
        cursor.read_exact(&mut kind_buf)?;
        let dispatch_kind_val = kind_buf[0];

        let mut re_buf = [0u8; 1];
        cursor.read_exact(&mut re_buf)?;
        let is_reexecute = re_buf[0] != 0;

        cursor.seek(SeekFrom::Current(2))?;

        let mut eh_buf = [0u8; 4];
        cursor.read_exact(&mut eh_buf)?;
        let eh_offset = u32::from_le_bytes(eh_buf);

        let dispatch_kind = match dispatch_kind_val {
            0 => X86DeoptDispatchKind::Interpreter,
            1 => X86DeoptDispatchKind::BaselineJIT,
            2 => X86DeoptDispatchKind::OptimizingJIT,
            3 => X86DeoptDispatchKind::ExceptionHandler,
            4 => X86DeoptDispatchKind::UnwindStub,
            _ => X86DeoptDispatchKind::Interpreter,
        };

        let continuation_point = X86ContinuationPoint {
            bytecode_offset: cp_bytecode_offset,
            method_ref: cp_method_ref,
            dispatch_kind,
            exception_handler_offset: if eh_offset != 0 {
                Some(eh_offset)
            } else {
                None
            },
            is_reexecute,
        };

        // Reason
        let mut reason_len_buf = [0u8; 4];
        cursor.read_exact(&mut reason_len_buf)?;
        let reason_len = u32::from_le_bytes(reason_len_buf) as usize;

        let mut reason_bytes = vec![0u8; reason_len];
        cursor.read_exact(&mut reason_bytes)?;
        let reason_str = String::from_utf8_lossy(&reason_bytes).to_string();
        let reason = DeoptReason::Other(reason_str);

        // Metadata
        let mut meta_len_buf = [0u8; 4];
        cursor.read_exact(&mut meta_len_buf)?;
        let meta_len = u32::from_le_bytes(meta_len_buf) as usize;

        let mut metadata = vec![0u8; meta_len];
        cursor.read_exact(&mut metadata)?;

        Ok(X86DeoptState {
            magic,
            version,
            compilation_unit_id,
            frame_state,
            register_state,
            continuation_point,
            reason,
            metadata,
        })
    }

    /// Get all GC references in this deoptimization state.
    pub fn get_gc_references(&self) -> Vec<(String, u64)> {
        let mut refs = Vec::new();

        // Frame slots that are references
        for local in &self.frame_state.locals {
            if local.is_reference && local.is_live {
                refs.push((format!("local[{}]", local.index), 0));
            }
        }
        for slot in &self.frame_state.stack {
            if slot.is_reference && slot.is_live {
                refs.push((format!("stack[{}]", slot.index), 0));
            }
        }

        // Register values that are references
        for gpr in &self.register_state.gprs {
            if gpr.is_reference {
                refs.push((format!("Reg({})", gpr.dwarf_reg), gpr.value));
            }
        }

        refs
    }

    /// Validate the deoptimization bundle.
    pub fn validate(&self) -> Result<(), Vec<String>> {
        let mut errors = Vec::new();

        if self.magic != DEOPT_BUNDLE_MAGIC {
            errors.push(format!(
                "Invalid magic: 0x{:08X} (expected 0x{:08X})",
                self.magic, DEOPT_BUNDLE_MAGIC
            ));
        }

        if self.version != DEOPT_BUNDLE_VERSION {
            errors.push(format!(
                "Invalid version: {} (expected {})",
                self.version, DEOPT_BUNDLE_VERSION
            ));
        }

        if self.frame_state.num_locals != self.frame_state.locals.len() as u32 {
            errors.push(format!(
                "Local count mismatch: header says {}, but {} locals present",
                self.frame_state.num_locals,
                self.frame_state.locals.len(),
            ));
        }

        if self.frame_state.num_stack_slots != self.frame_state.stack.len() as u32 {
            errors.push(format!(
                "Stack slot count mismatch: header says {}, but {} slots present",
                self.frame_state.num_stack_slots,
                self.frame_state.stack.len(),
            ));
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }
}

// ============================================================================
// Stack Map Section Writer — ELF Section Emission
// ============================================================================

/// Writes the `.llvm_stackmaps` section to an object file or buffer.
#[derive(Debug, Clone)]
pub struct X86StackMapWriter {
    /// Section alignment (typically 8 bytes).
    pub alignment: u32,
    /// Section flags (e.g., SHF_ALLOC).
    pub flags: u64,
    /// Whether to emit the section as read-only.
    pub read_only: bool,
}

impl X86StackMapWriter {
    /// Create a new stack map section writer.
    pub fn new() -> Self {
        X86StackMapWriter {
            alignment: 8,
            flags: 0, // No special flags by default
            read_only: true,
        }
    }

    /// Write the stack map section header.
    pub fn write_header<W: Write>(
        &self,
        writer: &mut W,
        generator: &mut X86StackMapGenerator,
    ) -> io::Result<()> {
        let section = generator.stack_maps.emit_section();
        writer.write_all(&section)?;
        Ok(())
    }

    /// Write the complete stack map section from raw format data.
    pub fn write_section<W: Write>(
        &self,
        writer: &mut W,
        format: &X86StackMapFormat,
    ) -> io::Result<()> {
        let bytes = format.to_bytes();
        writer.write_all(&bytes)?;
        Ok(())
    }

    /// Generate ELF section header entry for `.llvm_stackmaps`.
    pub fn generate_elf_section_header(&self, offset: u64, size: u64) -> Vec<u8> {
        let mut buf = Vec::new();

        // sh_name (offset into string table) — placeholder
        buf.extend_from_slice(&0u32.to_le_bytes());

        // sh_type = SHT_PROGBITS (1)
        buf.extend_from_slice(&1u32.to_le_bytes());

        // sh_flags = SHF_ALLOC (2)
        buf.extend_from_slice(&(2u64).to_le_bytes());

        // sh_addr = 0 (relocatable)
        buf.extend_from_slice(&0u64.to_le_bytes());

        // sh_offset
        buf.extend_from_slice(&offset.to_le_bytes());

        // sh_size
        buf.extend_from_slice(&size.to_le_bytes());

        // sh_link = 0
        buf.extend_from_slice(&0u32.to_le_bytes());

        // sh_info = 0
        buf.extend_from_slice(&0u32.to_le_bytes());

        // sh_addralign = 8
        buf.extend_from_slice(&self.alignment.to_le_bytes());

        // sh_entsize = 0 (no fixed entry size)
        buf.extend_from_slice(&0u64.to_le_bytes());

        buf
    }
}

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

// ============================================================================
// Stack Map Verification
// ============================================================================

/// Verifier for stack map data integrity.
///
/// Checks that stack map data is consistent, well-formed, and matches
/// the expected format. Used for testing and debugging.
#[derive(Debug, Clone)]
pub struct X86StackMapVerifier {
    /// The stack maps to verify.
    pub stack_maps: X86StackMaps,
    /// Verification errors found.
    pub errors: Vec<String>,
    /// Verification warnings found.
    pub warnings: Vec<String>,
}

impl X86StackMapVerifier {
    /// Create a new stack map verifier.
    pub fn new(stack_maps: X86StackMaps) -> Self {
        X86StackMapVerifier {
            stack_maps,
            errors: Vec::new(),
            warnings: Vec::new(),
        }
    }

    /// Run all verification checks.
    pub fn verify(&mut self) -> bool {
        self.errors.clear();
        self.warnings.clear();

        self.check_header();
        self.check_function_records();
        self.check_location_records();
        self.check_constant_pool();
        self.check_id_uniqueness();
        self.check_live_out_registers();
        self.check_stack_size_consistency();

        self.errors.is_empty()
    }

    /// Verify the stack map header.
    fn check_header(&mut self) {
        let h = &self.stack_maps.format.header;
        if h.version != STACK_MAP_VERSION {
            self.errors.push(format!(
                "Unsupported stack map version: {} (expected {})",
                h.version, STACK_MAP_VERSION
            ));
        }
        if h.reserved1 != 0 || h.reserved2 != 0 {
            self.errors
                .push("Reserved header fields are non-zero".to_string());
        }
    }

    /// Verify function records.
    fn check_function_records(&mut self) {
        for func in &self.stack_maps.format.functions {
            if func.stack_size > MAX_FRAME_SIZE {
                self.errors.push(format!(
                    "Function at 0x{:016X}: stack size {} exceeds maximum {}",
                    func.function_address, func.stack_size, MAX_FRAME_SIZE
                ));
            }
            if func.record_count == 0 {
                self.warnings.push(format!(
                    "Function at 0x{:016X} has no stack map records",
                    func.function_address
                ));
            }
        }
    }

    /// Verify location records.
    fn check_location_records(&mut self) {
        for record in &self.stack_maps.format.records {
            for loc in &record.locations {
                if loc.size == 0 && loc.kind != LocationKind::ConstantIndex {
                    self.warnings.push(format!(
                        "Record ID {}: location has size 0 (kind: {})",
                        record.id,
                        loc.kind.name()
                    ));
                }
            }
            if record.locations.len() > MAX_LOCATIONS_PER_RECORD {
                self.errors.push(format!(
                    "Record ID {}: {} locations exceeds maximum {}",
                    record.id,
                    record.locations.len(),
                    MAX_LOCATIONS_PER_RECORD
                ));
            }
        }
    }

    /// Verify constant pool integrity.
    fn check_constant_pool(&mut self) {
        for record in &self.stack_maps.format.records {
            for loc in &record.locations {
                if loc.kind == LocationKind::ConstantIndex {
                    let index = loc.offset as u32;
                    if self.stack_maps.format.get_constant(index).is_none() {
                        self.errors.push(format!(
                            "Record ID {}: constant index {} out of bounds",
                            record.id, index
                        ));
                    }
                }
            }
        }
    }

    /// Check that all stack map IDs are unique.
    fn check_id_uniqueness(&mut self) {
        let mut seen: HashMap<u64, usize> = HashMap::new();
        for (i, record) in self.stack_maps.format.records.iter().enumerate() {
            if let Some(prev) = seen.get(&record.id) {
                self.errors.push(format!(
                    "Duplicate stack map ID {} (records {} and {})",
                    record.id, prev, i
                ));
            } else {
                seen.insert(record.id, i);
            }
        }
    }

    /// Verify live-out register records.
    fn check_live_out_registers(&mut self) {
        for record in &self.stack_maps.format.records {
            for live_out in &record.live_outs {
                if live_out.dwarf_reg_num > 112 {
                    self.warnings.push(format!(
                        "Record ID {}: live-out register {} may be invalid",
                        record.id, live_out.dwarf_reg_num
                    ));
                }
            }
        }
    }

    /// Check stack size record consistency.
    fn check_stack_size_consistency(&mut self) {
        for func in &self.stack_maps.format.functions {
            if func.stack_size_count > 0
                && func.stack_size_count as usize != self.stack_maps.format.stack_sizes.len()
            {
                // This is a gross check; per-function tracking is more precise
                // in the format but would require index tracking
            }
        }
    }

    /// Get the verification report as a string.
    pub fn report(&self) -> String {
        let mut report = String::new();
        report.push_str("=== Stack Map Verification Report ===\n\n");

        if self.errors.is_empty() && self.warnings.is_empty() {
            report.push_str("PASS: No errors or warnings.\n");
        } else {
            if !self.errors.is_empty() {
                report.push_str(&format!("ERRORS ({}):\n", self.errors.len()));
                for err in &self.errors {
                    report.push_str(&format!("  - {}\n", err));
                }
                report.push('\n');
            }
            if !self.warnings.is_empty() {
                report.push_str(&format!("WARNINGS ({}):\n", self.warnings.len()));
                for warn in &self.warnings {
                    report.push_str(&format!("  - {}\n", warn));
                }
            }
        }

        report
    }
}

// ============================================================================
// Integration Helpers — building block-level stack map scenarios
// ============================================================================

/// Helper to build a complete stack map scenario for a single function
/// with safepoints, statepoints, and patchpoints.
#[derive(Debug, Clone)]
pub struct X86StackMapScenario {
    /// Function name.
    pub function_name: String,
    /// Stack map generator.
    pub generator: X86StackMapGenerator,
    /// Patchpoints in this function.
    pub patchpoints: Vec<X86PatchPoint>,
    /// Statepoints in this function.
    pub statepoints: Vec<X86StatePoint>,
    /// Safepoint locations.
    pub safepoints: Vec<X86SafepointLocation>,
    /// Stack size records.
    pub stack_sizes: Vec<(u32, u64)>,
}

impl X86StackMapScenario {
    /// Create a new scenario for a named function.
    pub fn new(function_name: &str, frame_size: u64, use_64bit: bool) -> Self {
        let mut generator = X86StackMapGenerator::new(use_64bit);
        generator.begin_function(function_name, frame_size);

        X86StackMapScenario {
            function_name: function_name.to_string(),
            generator,
            patchpoints: Vec::new(),
            statepoints: Vec::new(),
            safepoints: Vec::new(),
            stack_sizes: Vec::new(),
        }
    }

    /// Add a patchpoint at the current offset.
    pub fn add_patchpoint(&mut self, pp: X86PatchPoint) {
        self.generator
            .generate_from_patchpoint(&self.function_name, &pp);
        self.patchpoints.push(pp);
    }

    /// Add a statepoint at the current offset.
    pub fn add_statepoint(&mut self, sp: X86StatePoint) {
        self.generator
            .generate_from_statepoint(&self.function_name, &sp);
        self.statepoints.push(sp);
    }

    /// Insert an entry safepoint.
    pub fn add_entry_safepoint(&mut self) {
        let id = self.generator.stack_maps.allocate_id();
        let (sp, _) = self
            .generator
            .safepoint
            .insert_entry_safepoint(&self.function_name, id);
        self.generator
            .generate_from_safepoint(&self.function_name, &sp);
        self.safepoints.push(sp);
    }

    /// Insert a backedge safepoint.
    pub fn add_backedge_safepoint(&mut self, offset: u32) {
        let id = self.generator.stack_maps.allocate_id();
        let (sp, _) =
            self.generator
                .safepoint
                .insert_backedge_safepoint(&self.function_name, offset, id);
        self.generator
            .generate_from_safepoint(&self.function_name, &sp);
        self.safepoints.push(sp);
    }

    /// Record a stack size change.
    pub fn record_stack_size(&mut self, offset: u32, size: u64) {
        self.generator
            .record_stack_size_change(&self.function_name, size as u64);
        self.stack_sizes.push((offset, size));
    }

    /// Finalize the scenario and return the section bytes.
    pub fn finalize(&mut self) -> Result<Vec<u8>, Vec<String>> {
        self.generator.end_function();
        self.generator
            .finalize()
            .map(|()| self.generator.generate_section())
    }

    /// Get a reference to the generator.
    pub fn generator(&self) -> &X86StackMapGenerator {
        &self.generator
    }

    /// Get a mutable reference to the generator.
    pub fn generator_mut(&mut self) -> &mut X86StackMapGenerator {
        &mut self.generator
    }
}

// ============================================================================
// X86FrameMap — Frame Map for Deoptimization
// ============================================================================
//
// The frame map reconstructs a virtual frame from physical register and
// stack state, enabling deoptimization into any point in the compilation
// pipeline. It maps every live value (register, stack slot, constant) to
// its logical position in the virtual frame, encodes register save areas,
// and bundles all metadata required for runtime frame reconstruction.

/// A virtual frame constructed from register + stack slot state.
///
/// The `X86FrameMap` encodes the complete logical view of a stack frame
/// as seen by higher-level compilation tiers (e.g., an interpreter or
/// baseline JIT). At a deoptimization point, the runtime uses this map
/// to reconstruct the virtual frame from the optimized code's physical
/// state.
#[derive(Debug, Clone)]
pub struct X86FrameMap {
    /// Frame size in bytes (total size of the virtual frame).
    pub frame_size: u64,
    /// Number of local variable slots in the virtual frame.
    pub num_locals: usize,
    /// Number of expression/operand stack slots.
    pub num_stack_slots: usize,
    /// Number of monitor/lock slots.
    pub num_monitors: usize,
    /// Slots representing locals, stack values, and monitors.
    pub slots: Vec<X86FrameMapSlot>,
    /// Register save area layout.
    pub register_save_area: X86RASaveArea,
    /// Mapping from physical register numbers to virtual frame slots.
    pub reg_to_slot: BTreeMap<u16, usize>,
    /// Mapping from stack offsets to virtual frame slots.
    pub stack_to_slot: BTreeMap<i32, usize>,
    /// Deoptimization bundle data (compressed frame state).
    pub deopt_bundle: Option<X86DeoptBundle>,
    /// Whether this frame map has been validated.
    pub validated: bool,
}

/// A slot in the virtual frame — represents a local variable,
/// operand stack entry, or monitor object.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct X86FrameMapSlot {
    /// Slot index in the virtual frame (0-based).
    pub index: usize,
    /// Logical slot kind.
    pub slot_kind: X86FrameSlotKind,
    /// Where the value currently lives.
    pub location: X86FrameValueLocation,
    /// Type of the value (as a string description).
    pub value_type: String,
    /// Whether this slot holds a GC-managed reference.
    pub is_reference: bool,
    /// Whether this slot is live at the current point.
    pub is_live: bool,
    /// The size of the slot in bytes.
    pub size: u32,
    /// Original variable name (if known from debug info).
    pub debug_name: Option<String>,
}

/// Kind of a virtual frame slot.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum X86FrameSlotKind {
    /// A local variable.
    Local,
    /// An operand stack entry.
    Stack,
    /// A monitor/lock object.
    Monitor,
    /// A callee-saved register spill.
    CalleeSaveSpill,
    /// A return address slot.
    ReturnAddress,
    /// A frame pointer save slot.
    FramePointerSave,
}

impl X86FrameSlotKind {
    pub fn name(&self) -> &'static str {
        match self {
            X86FrameSlotKind::Local => "Local",
            X86FrameSlotKind::Stack => "Stack",
            X86FrameSlotKind::Monitor => "Monitor",
            X86FrameSlotKind::CalleeSaveSpill => "CalleeSaveSpill",
            X86FrameSlotKind::ReturnAddress => "ReturnAddress",
            X86FrameSlotKind::FramePointerSave => "FramePointerSave",
        }
    }
}

/// Where a value is physically located during optimized execution.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum X86FrameValueLocation {
    /// Value is in a physical register.
    Register { dwarf_reg: u16 },
    /// Value is on the stack at the given frame-relative offset.
    Stack { offset: i32 },
    /// Value is a known constant.
    Constant { value: i64 },
    /// Value is undefined / dead.
    Undef,
    /// Value is split across multiple locations (e.g., SIMD vector).
    Split {
        locations: Vec<X86FrameValueLocation>,
    },
}

impl X86FrameValueLocation {
    pub fn is_register(&self) -> bool {
        matches!(self, X86FrameValueLocation::Register { .. })
    }

    pub fn is_stack(&self) -> bool {
        matches!(self, X86FrameValueLocation::Stack { .. })
    }

    pub fn is_constant(&self) -> bool {
        matches!(self, X86FrameValueLocation::Constant { .. })
    }

    pub fn dwarf_reg(&self) -> Option<u16> {
        match self {
            X86FrameValueLocation::Register { dwarf_reg } => Some(*dwarf_reg),
            _ => None,
        }
    }

    pub fn stack_offset(&self) -> Option<i32> {
        match self {
            X86FrameValueLocation::Stack { offset } => Some(*offset),
            _ => None,
        }
    }
}

/// Register save area layout for X86-64 frames.
///
/// Describes how callee-saved and caller-saved registers are arranged
/// in the stack frame. The runtime uses this to restore register state
/// during deoptimization or exception unwinding.
#[derive(Debug, Clone)]
pub struct X86RASaveArea {
    /// Base offset of the register save area (relative to RBP).
    pub base_offset: i32,
    /// Total size of the save area in bytes.
    pub total_size: u32,
    /// Saved GPR slots (reg_num → offset from base).
    pub gpr_saves: BTreeMap<u16, i32>,
    /// Saved XMM slots (reg_num → offset from base).
    pub xmm_saves: BTreeMap<u16, i32>,
    /// Saved YMM upper halves (reg_num → offset from base).
    pub ymm_saves: BTreeMap<u16, i32>,
    /// Whether RFLAGS is saved.
    pub saves_rflags: bool,
    /// Offset of RFLAGS from base (if saved).
    pub rflags_offset: Option<i32>,
    /// Whether MXCSR is saved.
    pub saves_mxcsr: bool,
    /// Offset of MXCSR from base (if saved).
    pub mxcsr_offset: Option<i32>,
    /// Alignment requirement for the save area.
    pub alignment: u32,
}

/// Deoptimization bundle — compressed frame state for runtime deopt.
///
/// Encodes the minimal set of information needed to reconstruct
/// a virtual frame from an optimized frame at a deoptimization point.
#[derive(Debug, Clone)]
pub struct X86DeoptBundle {
    /// Magic number identifying this as a deopt bundle.
    pub magic: u32,
    /// Bundle format version.
    pub version: u16,
    /// Reason for deoptimization.
    pub reason: DeoptReason,
    /// Compressed frame state bytes.
    pub frame_state_bytes: Vec<u8>,
    /// Number of live register values.
    pub num_register_values: u16,
    /// Number of live stack values.
    pub num_stack_values: u16,
    /// Compressed register state.
    pub register_state_bytes: Vec<u8>,
    /// Continuation metadata.
    pub continuation_bytes: Vec<u8>,
    /// Original compilation unit identifier (for debug lookup).
    pub compilation_unit_id: u32,
}

/// Helper for reconstructing a stack frame from deoptimization state.
#[derive(Debug)]
pub struct X86FrameReconstructor {
    /// The frame map to reconstruct from.
    pub frame_map: X86FrameMap,
    /// Register value snapshot.
    pub register_values: BTreeMap<u16, i64>,
    /// Stack memory snapshot (offset → value).
    pub stack_memory: BTreeMap<i32, Vec<u8>>,
    /// Reconstructed virtual frame slots.
    pub reconstructed_slots: Vec<Option<i64>>,
    /// Whether reconstruction succeeded.
    pub success: bool,
}

impl Default for X86FrameSlotKind {
    fn default() -> Self {
        X86FrameSlotKind::Local
    }
}

impl Default for X86FrameMapSlot {
    fn default() -> Self {
        X86FrameMapSlot {
            index: 0,
            slot_kind: X86FrameSlotKind::Local,
            location: X86FrameValueLocation::Undef,
            value_type: String::new(),
            is_reference: false,
            is_live: true,
            size: 8,
            debug_name: None,
        }
    }
}

impl X86FrameMapSlot {
    /// Create a new local variable slot.
    pub fn new_local(index: usize, value_type: &str, size: u32) -> Self {
        X86FrameMapSlot {
            index,
            slot_kind: X86FrameSlotKind::Local,
            location: X86FrameValueLocation::Undef,
            value_type: value_type.to_string(),
            is_reference: false,
            is_live: true,
            size,
            debug_name: None,
        }
    }

    /// Create a new operand stack slot.
    pub fn new_stack(index: usize, value_type: &str, size: u32) -> Self {
        X86FrameMapSlot {
            index,
            slot_kind: X86FrameSlotKind::Stack,
            location: X86FrameValueLocation::Undef,
            value_type: value_type.to_string(),
            is_reference: false,
            is_live: true,
            size,
            debug_name: None,
        }
    }

    /// Create a new monitor slot.
    pub fn new_monitor(index: usize) -> Self {
        X86FrameMapSlot {
            index,
            slot_kind: X86FrameSlotKind::Monitor,
            location: X86FrameValueLocation::Undef,
            value_type: "ObjectReference".to_string(),
            is_reference: true,
            is_live: true,
            size: 8,
            debug_name: None,
        }
    }

    /// Set the physical location of this slot's value.
    pub fn set_location(&mut self, loc: X86FrameValueLocation) {
        let is_live = !matches!(loc, X86FrameValueLocation::Undef);
        self.location = loc;
        self.is_live = is_live;
    }

    /// Mark this slot as holding a GC reference.
    pub fn mark_reference(&mut self) {
        self.is_reference = true;
    }

    /// Mark this slot as dead (value no longer live).
    pub fn mark_dead(&mut self) {
        self.is_live = false;
        self.location = X86FrameValueLocation::Undef;
    }

    /// Set the debug name for this slot.
    pub fn set_debug_name(&mut self, name: &str) {
        self.debug_name = Some(name.to_string());
    }
}

impl Default for X86RASaveArea {
    fn default() -> Self {
        X86RASaveArea {
            base_offset: -8,
            total_size: 0,
            gpr_saves: BTreeMap::new(),
            xmm_saves: BTreeMap::new(),
            ymm_saves: BTreeMap::new(),
            saves_rflags: false,
            rflags_offset: None,
            saves_mxcsr: false,
            mxcsr_offset: None,
            alignment: 16,
        }
    }
}

impl X86RASaveArea {
    /// Create a new register save area at the given base offset.
    pub fn new(base_offset: i32) -> Self {
        X86RASaveArea {
            base_offset,
            total_size: 0,
            gpr_saves: BTreeMap::new(),
            xmm_saves: BTreeMap::new(),
            ymm_saves: BTreeMap::new(),
            saves_rflags: false,
            rflags_offset: None,
            saves_mxcsr: false,
            mxcsr_offset: None,
            alignment: 16,
        }
    }

    /// Save a GPR at the specified offset from base.
    pub fn save_gpr(&mut self, dwarf_reg: u16, offset: i32) {
        self.gpr_saves.insert(dwarf_reg, offset);
        self.total_size = self.total_size.max((offset.abs() + 8) as u32);
    }

    /// Save an XMM register.
    pub fn save_xmm(&mut self, dwarf_reg: u16, offset: i32) {
        self.xmm_saves.insert(dwarf_reg, offset);
        self.total_size = self.total_size.max((offset.abs() + 16) as u32);
    }

    /// Save a YMM register (upper 128 bits).
    pub fn save_ymm(&mut self, dwarf_reg: u16, offset: i32) {
        self.ymm_saves.insert(dwarf_reg, offset);
        self.total_size = self.total_size.max((offset.abs() + 16) as u32);
    }

    /// Mark RFLAGS as saved at the given offset.
    pub fn save_rflags(&mut self, offset: i32) {
        self.saves_rflags = true;
        self.rflags_offset = Some(offset);
        self.total_size = self.total_size.max((offset.abs() + 8) as u32);
    }

    /// Mark MXCSR as saved at the given offset.
    pub fn save_mxcsr(&mut self, offset: i32) {
        self.saves_mxcsr = true;
        self.mxcsr_offset = Some(offset);
        self.total_size = self.total_size.max((offset.abs() + 4) as u32);
    }

    /// Get the offset of a saved GPR.
    pub fn gpr_offset(&self, dwarf_reg: u16) -> Option<i32> {
        self.gpr_saves.get(&dwarf_reg).copied()
    }

    /// Get the offset of a saved XMM.
    pub fn xmm_offset(&self, dwarf_reg: u16) -> Option<i32> {
        self.xmm_saves.get(&dwarf_reg).copied()
    }

    /// Total number of saved registers.
    pub fn total_saved_regs(&self) -> usize {
        self.gpr_saves.len() + self.xmm_saves.len() + self.ymm_saves.len()
    }

    /// Align the total size to the required alignment.
    pub fn align_size(&mut self) {
        let align = self.alignment as u32;
        if self.total_size % align != 0 {
            self.total_size = (self.total_size + align - 1) & !(align - 1);
        }
    }
}

impl Default for X86DeoptBundle {
    fn default() -> Self {
        X86DeoptBundle {
            magic: DEOPT_BUNDLE_MAGIC,
            version: DEOPT_BUNDLE_VERSION,
            reason: DeoptReason::ExplicitDeopt {
                reason: String::new(),
            },
            frame_state_bytes: Vec::new(),
            num_register_values: 0,
            num_stack_values: 0,
            register_state_bytes: Vec::new(),
            continuation_bytes: Vec::new(),
            compilation_unit_id: 0,
        }
    }
}

impl X86DeoptBundle {
    /// Create a new deoptimization bundle.
    pub fn new(reason: DeoptReason, compilation_unit_id: u32) -> Self {
        X86DeoptBundle {
            magic: DEOPT_BUNDLE_MAGIC,
            version: DEOPT_BUNDLE_VERSION,
            reason,
            frame_state_bytes: Vec::new(),
            num_register_values: 0,
            num_stack_values: 0,
            register_state_bytes: Vec::new(),
            continuation_bytes: Vec::new(),
            compilation_unit_id,
        }
    }

    /// Set the compressed frame state.
    pub fn set_frame_state(&mut self, bytes: Vec<u8>, num_regs: u16, num_stacks: u16) {
        self.frame_state_bytes = bytes;
        self.num_register_values = num_regs;
        self.num_stack_values = num_stacks;
    }

    /// Set the compressed register state.
    pub fn set_register_state(&mut self, bytes: Vec<u8>) {
        self.register_state_bytes = bytes;
    }

    /// Set continuation metadata.
    pub fn set_continuation(&mut self, bytes: Vec<u8>) {
        self.continuation_bytes = bytes;
    }

    /// Validate the bundle magic and version.
    pub fn validate(&self) -> bool {
        self.magic == DEOPT_BUNDLE_MAGIC && self.version == DEOPT_BUNDLE_VERSION
    }

    /// Total size of the bundle in bytes.
    pub fn total_size(&self) -> usize {
        4 + 2  // magic + version
            + self.frame_state_bytes.len()
            + 2 + 2  // num_register_values + num_stack_values
            + self.register_state_bytes.len()
            + self.continuation_bytes.len()
            + 4 // compilation_unit_id
    }
}

impl Default for X86FrameMap {
    fn default() -> Self {
        X86FrameMap {
            frame_size: 0,
            num_locals: 0,
            num_stack_slots: 0,
            num_monitors: 0,
            slots: Vec::new(),
            register_save_area: X86RASaveArea::default(),
            reg_to_slot: BTreeMap::new(),
            stack_to_slot: BTreeMap::new(),
            deopt_bundle: None,
            validated: false,
        }
    }
}

impl X86FrameMap {
    /// Create a new empty frame map with the given frame size.
    pub fn new(frame_size: u64) -> Self {
        X86FrameMap {
            frame_size,
            num_locals: 0,
            num_stack_slots: 0,
            num_monitors: 0,
            slots: Vec::new(),
            register_save_area: X86RASaveArea::new(-(frame_size as i32)),
            reg_to_slot: BTreeMap::new(),
            stack_to_slot: BTreeMap::new(),
            deopt_bundle: None,
            validated: false,
        }
    }

    /// Add a local variable slot.
    pub fn add_local(&mut self, value_type: &str, size: u32) -> usize {
        let index = self.slots.len();
        let slot = X86FrameMapSlot::new_local(index, value_type, size);
        self.slots.push(slot);
        self.num_locals += 1;
        index
    }

    /// Add an operand stack slot.
    pub fn add_stack_slot(&mut self, value_type: &str, size: u32) -> usize {
        let index = self.slots.len();
        let slot = X86FrameMapSlot::new_stack(index, value_type, size);
        self.slots.push(slot);
        self.num_stack_slots += 1;
        index
    }

    /// Add a monitor slot.
    pub fn add_monitor(&mut self) -> usize {
        let index = self.slots.len();
        let slot = X86FrameMapSlot::new_monitor(index);
        self.slots.push(slot);
        self.num_monitors += 1;
        index
    }

    /// Map a physical register to a virtual frame slot.
    pub fn map_register_to_slot(&mut self, dwarf_reg: u16, slot_index: usize) {
        self.reg_to_slot.insert(dwarf_reg, slot_index);
        if slot_index < self.slots.len() {
            self.slots[slot_index].set_location(X86FrameValueLocation::Register { dwarf_reg });
        }
    }

    /// Map a stack offset to a virtual frame slot.
    pub fn map_stack_to_slot(&mut self, offset: i32, slot_index: usize) {
        self.stack_to_slot.insert(offset, slot_index);
        if slot_index < self.slots.len() {
            self.slots[slot_index].set_location(X86FrameValueLocation::Stack { offset });
        }
    }

    /// Set the deoptimization bundle.
    pub fn set_deopt_bundle(&mut self, bundle: X86DeoptBundle) {
        self.deopt_bundle = Some(bundle);
    }

    /// Get all slots that hold GC references.
    pub fn reference_slots(&self) -> Vec<&X86FrameMapSlot> {
        self.slots
            .iter()
            .filter(|s| s.is_reference && s.is_live)
            .collect()
    }

    /// Get the slot for a given register, if any.
    pub fn slot_for_register(&self, dwarf_reg: u16) -> Option<&X86FrameMapSlot> {
        self.reg_to_slot
            .get(&dwarf_reg)
            .and_then(|&idx| self.slots.get(idx))
    }

    /// Get the slot for a given stack offset, if any.
    pub fn slot_for_stack_offset(&self, offset: i32) -> Option<&X86FrameMapSlot> {
        self.stack_to_slot
            .get(&offset)
            .and_then(|&idx| self.slots.get(idx))
    }

    /// Total number of slots.
    pub fn total_slots(&self) -> usize {
        self.slots.len()
    }

    /// Mark the frame map as validated.
    pub fn validate(&mut self) -> bool {
        self.validated = true;
        if let Some(ref bundle) = self.deopt_bundle {
            if !bundle.validate() {
                self.validated = false;
                return false;
            }
        }
        true
    }

    /// Generate DWARF CFI-like bytecode for the register save area.
    pub fn generate_save_area_cfi(&self) -> Vec<u8> {
        let mut cfi = Vec::new();
        for (&reg, &offset) in &self.register_save_area.gpr_saves {
            cfi.extend_from_slice(&[0x80 | (reg as u8 & 0x3F), (offset & 0x7F) as u8]);
        }
        for (&reg, &offset) in &self.register_save_area.xmm_saves {
            cfi.push(0x90);
            cfi.push(reg as u8);
            cfi.push((offset & 0x7F) as u8);
        }
        cfi
    }

    /// Encode the full frame map as a compact byte sequence for runtime use.
    pub fn encode(&self) -> Vec<u8> {
        let mut buf = Vec::new();
        buf.extend_from_slice(&(self.frame_size as u32).to_le_bytes());
        buf.extend_from_slice(&(self.slots.len() as u32).to_le_bytes());
        for slot in &self.slots {
            buf.push(if slot.is_reference { 1 } else { 0 });
            buf.push(if slot.is_live { 1 } else { 0 });
            buf.extend_from_slice(&slot.size.to_le_bytes());
            let kind_byte = match slot.slot_kind {
                X86FrameSlotKind::Local => 0u8,
                X86FrameSlotKind::Stack => 1,
                X86FrameSlotKind::Monitor => 2,
                X86FrameSlotKind::CalleeSaveSpill => 3,
                X86FrameSlotKind::ReturnAddress => 4,
                X86FrameSlotKind::FramePointerSave => 5,
            };
            buf.push(kind_byte);
            match &slot.location {
                X86FrameValueLocation::Register { dwarf_reg } => {
                    buf.push(0);
                    buf.extend_from_slice(&dwarf_reg.to_le_bytes());
                }
                X86FrameValueLocation::Stack { offset } => {
                    buf.push(1);
                    buf.extend_from_slice(&offset.to_le_bytes());
                }
                X86FrameValueLocation::Constant { value } => {
                    buf.push(2);
                    buf.extend_from_slice(&value.to_le_bytes());
                }
                X86FrameValueLocation::Undef => {
                    buf.push(3);
                }
                X86FrameValueLocation::Split { locations } => {
                    buf.push(4);
                    buf.extend_from_slice(&(locations.len() as u32).to_le_bytes());
                }
            }
        }
        buf
    }
}

impl X86FrameReconstructor {
    /// Create a new frame reconstructor from a frame map.
    pub fn new(frame_map: X86FrameMap) -> Self {
        let slot_count = frame_map.slots.len();
        X86FrameReconstructor {
            frame_map,
            register_values: BTreeMap::new(),
            stack_memory: BTreeMap::new(),
            reconstructed_slots: vec![None; slot_count],
            success: false,
        }
    }

    /// Set a register value from the physical frame.
    pub fn set_register(&mut self, dwarf_reg: u16, value: i64) {
        self.register_values.insert(dwarf_reg, value);
    }

    /// Set stack memory from the physical frame.
    pub fn set_stack_memory(&mut self, offset: i32, bytes: Vec<u8>) {
        self.stack_memory.insert(offset, bytes);
    }

    /// Reconstruct all virtual frame slots from physical state.
    pub fn reconstruct(&mut self) -> bool {
        for (slot_idx, slot) in self.frame_map.slots.iter().enumerate() {
            if !slot.is_live {
                continue;
            }
            let value = match &slot.location {
                X86FrameValueLocation::Register { dwarf_reg } => {
                    self.register_values.get(dwarf_reg).copied()
                }
                X86FrameValueLocation::Stack { offset } => {
                    self.stack_memory.get(offset).and_then(|bytes| {
                        if bytes.len() >= 8 {
                            Some(i64::from_le_bytes([
                                bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5],
                                bytes[6], bytes[7],
                            ]))
                        } else {
                            None
                        }
                    })
                }
                X86FrameValueLocation::Constant { value } => Some(*value),
                X86FrameValueLocation::Undef => None,
                X86FrameValueLocation::Split { .. } => None,
            };
            self.reconstructed_slots[slot_idx] = value;
        }
        self.success = self
            .reconstructed_slots
            .iter()
            .enumerate()
            .all(|(idx, v)| !self.frame_map.slots[idx].is_live || v.is_some());
        self.success
    }

    /// Get a reconstructed slot value.
    pub fn get_slot_value(&self, index: usize) -> Option<i64> {
        self.reconstructed_slots.get(index).copied().flatten()
    }

    /// Get all live GC reference values.
    pub fn get_gc_references(&self) -> Vec<i64> {
        self.frame_map
            .slots
            .iter()
            .enumerate()
            .filter(|(_, s)| s.is_reference && s.is_live)
            .filter_map(|(idx, _)| self.reconstructed_slots.get(idx).copied().flatten())
            .collect()
    }
}

// ============================================================================
// X86ExceptionHandlingMaps — Exception Handling Stack Maps
// ============================================================================
//
// Encodes stack maps for exception handling constructs: landing pads,
// personality functions, and cleanup regions. These maps tell the runtime
// where exception handlers are, how to find the personality routine, and
// which cleanup actions to perform during stack unwinding.

/// An exception handling stack map entry for a single function.
#[derive(Debug, Clone)]
pub struct X86EHStackMap {
    /// Function this EH map applies to.
    pub function_name: String,
    /// Landing pad maps keyed by instruction offset.
    pub landing_pads: BTreeMap<u32, X86LandingPadMap>,
    /// Personality function information.
    pub personality: Option<X86PersonalityFuncMap>,
    /// Cleanup action maps keyed by instruction offset.
    pub cleanups: BTreeMap<u32, X86CleanupMap>,
    /// LSDA (Language-Specific Data Area) offset, if any.
    pub lsda_offset: Option<u32>,
    /// Whether this function has exception-handling code.
    pub has_eh: bool,
}

/// Landing pad stack map — describes a single exception handling landing pad.
#[derive(Debug, Clone)]
pub struct X86LandingPadMap {
    /// Offset of the landing pad instruction.
    pub offset: u32,
    /// The stack map ID associated with this landing pad.
    pub stack_map_id: u64,
    /// Clauses for this landing pad (catch, filter, cleanup).
    pub clauses: Vec<X86LandingPadClause>,
    /// DWARF register where the exception object pointer is stored.
    pub exception_pointer_reg: Option<u16>,
    /// DWARF register where the selector value is stored.
    pub selector_reg: Option<u16>,
    /// Stack offset where the exception object is spilled.
    pub exception_object_spill: Option<i32>,
    /// Whether this is a cleanup-only landing pad.
    pub is_cleanup: bool,
    /// Whether this landing pad catches all exceptions.
    pub is_catch_all: bool,
}

/// A clause in a landing pad (catch type or filter).
#[derive(Debug, Clone)]
pub enum X86LandingPadClause {
    /// Catch a specific type (by type info pointer).
    Catch {
        type_info_ptr: u64,
        type_name: String,
    },
    /// Filter: only allow exceptions matching these types.
    Filter {
        type_info_ptrs: Vec<u64>,
        type_names: Vec<String>,
    },
    /// Cleanup clause.
    Cleanup,
}

impl X86LandingPadClause {
    pub fn is_catch(&self) -> bool {
        matches!(self, X86LandingPadClause::Catch { .. })
    }

    pub fn is_filter(&self) -> bool {
        matches!(self, X86LandingPadClause::Filter { .. })
    }

    pub fn is_cleanup(&self) -> bool {
        matches!(self, X86LandingPadClause::Cleanup)
    }
}

/// Personality function stack map — describes how to find and call
/// the personality routine.
#[derive(Debug, Clone)]
pub struct X86PersonalityFuncMap {
    /// The personality function pointer or symbol name.
    pub personality_func: String,
    /// GCC-style personality: unwinding through DWARF CFI.
    pub is_gcc_personality: bool,
    /// SEH (Structured Exception Handling) personality.
    pub is_seh_personality: bool,
    /// Whether this personality is for a specific language runtime.
    pub language: Option<String>,
    /// Offset of the personality function's GOT entry (if PIC).
    pub got_offset: Option<u32>,
}

impl Default for X86PersonalityFuncMap {
    fn default() -> Self {
        X86PersonalityFuncMap {
            personality_func: "__gxx_personality_v0".to_string(),
            is_gcc_personality: true,
            is_seh_personality: false,
            language: Some("C++".to_string()),
            got_offset: None,
        }
    }
}

/// Cleanup stack map — describes cleanup actions at a given point.
#[derive(Debug, Clone)]
pub struct X86CleanupMap {
    /// Offset of the cleanup action.
    pub offset: u32,
    /// Stack map ID for this cleanup point.
    pub stack_map_id: u64,
    /// Whether this cleanup destroys local objects.
    pub destroys_locals: bool,
    /// Whether this cleanup releases locks/monitors.
    pub releases_monitors: bool,
    /// Whether this cleanup calls destructors.
    pub calls_destructors: bool,
    /// List of destructor calls (offset → type name).
    pub destructor_calls: Vec<(i32, String)>,
    /// Whether this cleanup must be run during normal exit too.
    pub run_on_normal_exit: bool,
}

impl Default for X86EHStackMap {
    fn default() -> Self {
        X86EHStackMap {
            function_name: String::new(),
            landing_pads: BTreeMap::new(),
            personality: None,
            cleanups: BTreeMap::new(),
            lsda_offset: None,
            has_eh: false,
        }
    }
}

impl X86EHStackMap {
    /// Create a new EH stack map for a function.
    pub fn new(function_name: &str) -> Self {
        X86EHStackMap {
            function_name: function_name.to_string(),
            landing_pads: BTreeMap::new(),
            personality: None,
            cleanups: BTreeMap::new(),
            lsda_offset: None,
            has_eh: false,
        }
    }

    /// Add a landing pad stack map.
    pub fn add_landing_pad(&mut self, offset: u32, lp: X86LandingPadMap) {
        self.has_eh = true;
        self.landing_pads.insert(offset, lp);
    }

    /// Set the personality function.
    pub fn set_personality(&mut self, personality: X86PersonalityFuncMap) {
        self.has_eh = true;
        self.personality = Some(personality);
    }

    /// Add a cleanup stack map.
    pub fn add_cleanup(&mut self, offset: u32, cleanup: X86CleanupMap) {
        self.has_eh = true;
        self.cleanups.insert(offset, cleanup);
    }

    /// Set the LSDA offset.
    pub fn set_lsda_offset(&mut self, offset: u32) {
        self.lsda_offset = Some(offset);
    }

    /// Get the landing pad at a specific offset.
    pub fn landing_pad_at(&self, offset: u32) -> Option<&X86LandingPadMap> {
        self.landing_pads.get(&offset)
    }

    /// Total number of landing pads.
    pub fn landing_pad_count(&self) -> usize {
        self.landing_pads.len()
    }

    /// Total number of cleanups.
    pub fn cleanup_count(&self) -> usize {
        self.cleanups.len()
    }

    /// Generate a compact encoding of all EH stack map data.
    pub fn encode(&self) -> Vec<u8> {
        let mut buf = Vec::new();
        // Header
        buf.push(if self.has_eh { 1 } else { 0 });
        buf.push(self.landing_pads.len() as u8);
        buf.push(self.cleanups.len() as u8);
        buf.push(if self.personality.is_some() { 1 } else { 0 });

        // Landing pads
        for (&offset, lp) in &self.landing_pads {
            buf.extend_from_slice(&offset.to_le_bytes());
            buf.extend_from_slice(&lp.stack_map_id.to_le_bytes());
            buf.push(if lp.is_cleanup { 1 } else { 0 });
            buf.push(if lp.is_catch_all { 1 } else { 0 });
            buf.push(lp.clauses.len() as u8);
            for clause in &lp.clauses {
                match clause {
                    X86LandingPadClause::Catch { type_info_ptr, .. } => {
                        buf.push(0);
                        buf.extend_from_slice(&type_info_ptr.to_le_bytes());
                    }
                    X86LandingPadClause::Filter { type_info_ptrs, .. } => {
                        buf.push(1);
                        buf.extend_from_slice(&(type_info_ptrs.len() as u32).to_le_bytes());
                    }
                    X86LandingPadClause::Cleanup => {
                        buf.push(2);
                    }
                }
            }
        }
        // Cleanups
        for (&offset, cleanup) in &self.cleanups {
            buf.extend_from_slice(&offset.to_le_bytes());
            buf.extend_from_slice(&cleanup.stack_map_id.to_le_bytes());
            let mut flags: u8 = 0;
            if cleanup.destroys_locals {
                flags |= 1;
            }
            if cleanup.releases_monitors {
                flags |= 2;
            }
            if cleanup.calls_destructors {
                flags |= 4;
            }
            if cleanup.run_on_normal_exit {
                flags |= 8;
            }
            buf.push(flags);
        }
        buf
    }
}

impl Default for X86LandingPadMap {
    fn default() -> Self {
        X86LandingPadMap {
            offset: 0,
            stack_map_id: 0,
            clauses: Vec::new(),
            exception_pointer_reg: None,
            selector_reg: None,
            exception_object_spill: None,
            is_cleanup: false,
            is_catch_all: false,
        }
    }
}

impl X86LandingPadMap {
    /// Create a new landing pad map.
    pub fn new(offset: u32, stack_map_id: u64) -> Self {
        X86LandingPadMap {
            offset,
            stack_map_id,
            clauses: Vec::new(),
            exception_pointer_reg: None,
            selector_reg: None,
            exception_object_spill: None,
            is_cleanup: false,
            is_catch_all: false,
        }
    }

    /// Add a catch clause.
    pub fn add_catch(&mut self, type_info_ptr: u64, type_name: &str) {
        self.clauses.push(X86LandingPadClause::Catch {
            type_info_ptr,
            type_name: type_name.to_string(),
        });
    }

    /// Add a filter clause.
    pub fn add_filter(&mut self, type_info_ptrs: Vec<u64>, type_names: Vec<String>) {
        self.clauses.push(X86LandingPadClause::Filter {
            type_info_ptrs,
            type_names,
        });
    }

    /// Add a cleanup clause.
    pub fn add_cleanup_clause(&mut self) {
        self.is_cleanup = true;
        self.clauses.push(X86LandingPadClause::Cleanup);
    }

    /// Mark this as a catch-all landing pad.
    pub fn set_catch_all(&mut self) {
        self.is_catch_all = true;
    }

    /// Set the exception pointer register.
    pub fn set_exception_pointer_reg(&mut self, reg: u16) {
        self.exception_pointer_reg = Some(reg);
    }

    /// Set the selector register.
    pub fn set_selector_reg(&mut self, reg: u16) {
        self.selector_reg = Some(reg);
    }

    /// Set the exception object spill location.
    pub fn set_exception_object_spill(&mut self, offset: i32) {
        self.exception_object_spill = Some(offset);
    }
}

impl Default for X86CleanupMap {
    fn default() -> Self {
        X86CleanupMap {
            offset: 0,
            stack_map_id: 0,
            destroys_locals: false,
            releases_monitors: false,
            calls_destructors: false,
            destructor_calls: Vec::new(),
            run_on_normal_exit: false,
        }
    }
}

impl X86CleanupMap {
    /// Create a new cleanup map.
    pub fn new(offset: u32, stack_map_id: u64) -> Self {
        X86CleanupMap {
            offset,
            stack_map_id,
            destroys_locals: false,
            releases_monitors: false,
            calls_destructors: false,
            destructor_calls: Vec::new(),
            run_on_normal_exit: false,
        }
    }

    /// Mark that this cleanup destroys local objects.
    pub fn mark_destroys_locals(&mut self) {
        self.destroys_locals = true;
    }

    /// Mark that this cleanup releases monitors.
    pub fn mark_releases_monitors(&mut self) {
        self.releases_monitors = true;
    }

    /// Add a destructor call.
    pub fn add_destructor_call(&mut self, stack_offset: i32, type_name: &str) {
        self.calls_destructors = true;
        self.destructor_calls
            .push((stack_offset, type_name.to_string()));
    }

    /// Mark that this cleanup also runs on normal (non-exceptional) exit.
    pub fn mark_run_on_normal_exit(&mut self) {
        self.run_on_normal_exit = true;
    }
}

/// Generator for exception handling stack map sections.
#[derive(Debug, Clone)]
pub struct X86EHMapGenerator {
    /// All EH stack maps keyed by function name.
    pub eh_maps: BTreeMap<String, X86EHStackMap>,
    /// Whether EH stack map generation is enabled.
    pub enabled: bool,
}

impl Default for X86EHMapGenerator {
    fn default() -> Self {
        X86EHMapGenerator {
            eh_maps: BTreeMap::new(),
            enabled: true,
        }
    }
}

impl X86EHMapGenerator {
    /// Create a new EH map generator.
    pub fn new(enabled: bool) -> Self {
        X86EHMapGenerator {
            eh_maps: BTreeMap::new(),
            enabled,
        }
    }

    /// Get or create the EH stack map for a function.
    pub fn get_or_create(&mut self, function_name: &str) -> &mut X86EHStackMap {
        self.eh_maps
            .entry(function_name.to_string())
            .or_insert_with(|| X86EHStackMap::new(function_name))
    }

    /// Emit all EH stack maps as a compact section.
    pub fn emit_section(&self) -> Vec<u8> {
        let mut buf = Vec::new();
        buf.extend_from_slice(&(self.eh_maps.len() as u32).to_le_bytes());
        for (name, eh_map) in &self.eh_maps {
            let name_bytes = name.as_bytes();
            buf.extend_from_slice(&(name_bytes.len() as u32).to_le_bytes());
            buf.extend_from_slice(name_bytes);
            buf.extend_from_slice(&eh_map.encode());
        }
        buf
    }

    /// Emit an assembly representation of all EH maps.
    pub fn emit_assembly(&self) -> String {
        let mut asm = String::new();
        asm.push_str("\t.section .eh_frame_stackmaps,\"a\",@progbits\n");
        for (name, eh_map) in &self.eh_maps {
            asm.push_str(&format!("\t# EH map for: {}\n", name));
            asm.push_str(&format!("\t.long {}\n", eh_map.landing_pad_count() as u32));
            for (&offset, lp) in &eh_map.landing_pads {
                asm.push_str(&format!("\t.long {}  # landing pad offset\n", offset));
                asm.push_str(&format!("\t.quad {}  # stack map ID\n", lp.stack_map_id));
            }
        }
        asm
    }

    /// Total number of functions with EH.
    pub fn function_count(&self) -> usize {
        self.eh_maps.len()
    }
}

// ============================================================================
// X86DebugInfoStackMaps — Debug Info Stack Maps
// ============================================================================
//
// Provides variable location tracking across call sites, debug value
// recording at stack map points, and DWARF expression generation for
// variables that live in registers or on the stack during optimized
// execution. Integrates with the debug info infrastructure to produce
// precise variable locations even when aggressive optimizations are applied.

/// A debug variable location — where a source-level variable lives at a
/// particular program point.
#[derive(Debug, Clone)]
pub struct X86DebugVarLocation {
    /// Source-level variable name.
    pub var_name: String,
    /// DWARF tag for the variable (e.g., DW_TAG_variable).
    pub dwarf_tag: u16,
    /// Type name.
    pub type_name: String,
    /// The location of the variable's value.
    pub location: X86DebugLocation,
    /// Whether this variable is live at this point.
    pub is_live: bool,
    /// Stack map ID that this location is associated with.
    pub stack_map_id: u64,
    /// Instruction offset where this location is valid.
    pub instruction_offset: u32,
    /// Whether this is an entry value (DW_OP_entry_value).
    pub is_entry_value: bool,
    /// Fragment information for SROA'd variables.
    pub fragment: Option<X86DebugFragment>,
}

/// Describes where a variable's value is physically located.
#[derive(Debug, Clone)]
pub enum X86DebugLocation {
    /// Value is in a register.
    Register { dwarf_reg: u16, offset: i32 },
    /// Value is on the stack.
    Stack { frame_offset: i32, size: u32 },
    /// Value is a compile-time constant.
    Constant { value: i64 },
    /// Value is at a memory address.
    Memory { address: u64 },
    /// Value is computed by a DWARF expression.
    DwarfExpression { expr_bytes: Vec<u8> },
    /// Value is unavailable (optimized out).
    Unavailable,
    /// Value is split across multiple locations.
    Composite { pieces: Vec<X86DebugPiece> },
}

/// A piece of a composite location (for SROA / split variables).
#[derive(Debug, Clone)]
pub struct X86DebugPiece {
    /// Byte offset within the variable.
    pub offset_in_variable: u32,
    /// Byte size of this piece.
    pub size: u32,
    /// Where this piece lives.
    pub location: X86DebugLocation,
}

/// Fragment information for SROA'd (scalar-replaced) variables.
#[derive(Debug, Clone)]
pub struct X86DebugFragment {
    /// Byte offset of this fragment within the original variable.
    pub offset: u32,
    /// Size of this fragment in bytes.
    pub size: u32,
    /// Total size of the original variable.
    pub total_size: u32,
}

/// A recorded debug value at a stack map point.
#[derive(Debug, Clone)]
pub struct X86DebugValueRecord {
    /// The variable location.
    pub var_location: X86DebugVarLocation,
    /// The DWARF expression encoding the value's location.
    pub dwarf_expression: Vec<u8>,
    /// Whether the expression is valid.
    pub expression_valid: bool,
    /// The original DIExpression from debug metadata.
    pub di_expression: Vec<u8>,
}

/// Debug info stack map for a function — tracks variable locations
/// at every stack map point.
#[derive(Debug, Clone)]
pub struct X86DebugInfoMap {
    /// Function name.
    pub function_name: String,
    /// Variable locations keyed by stack map ID.
    pub locations_by_id: BTreeMap<u64, Vec<X86DebugVarLocation>>,
    /// Variable locations keyed by instruction offset.
    pub locations_by_offset: BTreeMap<u32, Vec<X86DebugVarLocation>>,
    /// All recorded debug values.
    pub debug_values: Vec<X86DebugValueRecord>,
    /// DWARF compilation unit offset for debug info.
    pub cu_offset: u64,
    /// Whether debug info is available for this function.
    pub has_debug_info: bool,
}

/// Tracks variable locations across call sites for debug info.
#[derive(Debug, Clone)]
pub struct X86DebugLocTracker {
    /// Current variable locations (var name → location).
    pub current_locations: HashMap<String, X86DebugLocation>,
    /// Variable type information.
    pub var_types: HashMap<String, String>,
    /// History of location changes (offset → variable → location).
    pub location_history: Vec<(u32, String, X86DebugLocation)>,
    /// Whether tracking is active.
    pub active: bool,
    /// Current instruction offset.
    pub current_offset: u32,
}

impl Default for X86DebugVarLocation {
    fn default() -> Self {
        X86DebugVarLocation {
            var_name: String::new(),
            dwarf_tag: 0,
            type_name: String::new(),
            location: X86DebugLocation::Unavailable,
            is_live: false,
            stack_map_id: 0,
            instruction_offset: 0,
            is_entry_value: false,
            fragment: None,
        }
    }
}

impl X86DebugVarLocation {
    /// Create a new live register location.
    pub fn new_register(
        var_name: &str,
        dwarf_reg: u16,
        type_name: &str,
        stack_map_id: u64,
        offset: u32,
    ) -> Self {
        X86DebugVarLocation {
            var_name: var_name.to_string(),
            dwarf_tag: 0x34, // DW_TAG_variable
            type_name: type_name.to_string(),
            location: X86DebugLocation::Register {
                dwarf_reg,
                offset: 0,
            },
            is_live: true,
            stack_map_id,
            instruction_offset: offset,
            is_entry_value: false,
            fragment: None,
        }
    }

    /// Create a new live stack location.
    pub fn new_stack(
        var_name: &str,
        frame_offset: i32,
        size: u32,
        type_name: &str,
        stack_map_id: u64,
        offset: u32,
    ) -> Self {
        X86DebugVarLocation {
            var_name: var_name.to_string(),
            dwarf_tag: 0x34,
            type_name: type_name.to_string(),
            location: X86DebugLocation::Stack { frame_offset, size },
            is_live: true,
            stack_map_id,
            instruction_offset: offset,
            is_entry_value: false,
            fragment: None,
        }
    }

    /// Mark this variable as optimized out.
    pub fn mark_unavailable(&mut self) {
        self.is_live = false;
        self.location = X86DebugLocation::Unavailable;
    }

    /// Mark this as an entry value (parameter value at function entry).
    pub fn mark_entry_value(&mut self) {
        self.is_entry_value = true;
    }

    /// Set fragment info for SROA'd variables.
    pub fn set_fragment(&mut self, offset: u32, size: u32, total_size: u32) {
        self.fragment = Some(X86DebugFragment {
            offset,
            size,
            total_size,
        });
    }
}

impl Default for X86DebugPiece {
    fn default() -> Self {
        X86DebugPiece {
            offset_in_variable: 0,
            size: 0,
            location: X86DebugLocation::Unavailable,
        }
    }
}

impl X86DebugPiece {
    /// Create a new debug piece.
    pub fn new(offset_in_variable: u32, size: u32, location: X86DebugLocation) -> Self {
        X86DebugPiece {
            offset_in_variable,
            size,
            location,
        }
    }
}

/// Generator for DWARF expressions from X86 debug locations.
#[derive(Debug, Clone)]
pub struct X86DwarfExprGenerator {
    /// Whether to use 64-bit DWARF format.
    pub use_dwarf64: bool,
    /// Current frame base register (DWARF reg number).
    pub frame_base_reg: u16,
    /// Frame base offset from the register.
    pub frame_base_offset: i32,
}

impl Default for X86DwarfExprGenerator {
    fn default() -> Self {
        X86DwarfExprGenerator {
            use_dwarf64: false,
            frame_base_reg: DWARF_REG_RBP,
            frame_base_offset: 0,
        }
    }
}

impl X86DwarfExprGenerator {
    /// Create a new DWARF expression generator.
    pub fn new(use_dwarf64: bool) -> Self {
        X86DwarfExprGenerator {
            use_dwarf64,
            frame_base_reg: DWARF_REG_RBP,
            frame_base_offset: 0,
        }
    }

    /// Set the frame base.
    pub fn set_frame_base(&mut self, reg: u16, offset: i32) {
        self.frame_base_reg = reg;
        self.frame_base_offset = offset;
    }

    /// Generate a DWARF expression for a register location.
    pub fn generate_register_expr(&self, dwarf_reg: u16, offset: i32) -> Vec<u8> {
        let mut expr = Vec::new();
        // DW_OP_regX for registers 0-31, or DW_OP_regx for others
        if dwarf_reg <= 31 {
            expr.push(0x50 + dwarf_reg as u8); // DW_OP_reg0 .. DW_OP_reg31
        } else {
            expr.push(0x90); // DW_OP_regx
            expr.extend_from_slice(&self.encode_uleb128(dwarf_reg as u64));
        }
        if offset != 0 {
            expr.push(0x23); // DW_OP_plus_uconst
            expr.extend_from_slice(&self.encode_uleb128(offset as u64));
        }
        expr
    }

    /// Generate a DWARF expression for a stack location.
    pub fn generate_stack_expr(&self, frame_offset: i32, size: u32) -> Vec<u8> {
        let mut expr = Vec::new();
        // DW_OP_fbreg <offset>
        let effective_offset = frame_offset - self.frame_base_offset;
        expr.push(0x91); // DW_OP_fbreg
        expr.extend_from_slice(&self.encode_sleb128(effective_offset as i64));
        if size > 0 {
            // DW_OP_deref_size <size>
            expr.push(0x94); // DW_OP_deref_size
            expr.push(size as u8);
        }
        expr
    }

    /// Generate a DWARF expression for a constant value.
    pub fn generate_constant_expr(&self, value: i64) -> Vec<u8> {
        let mut expr = Vec::new();
        match value {
            0 => expr.push(0x30),                    // DW_OP_lit0
            1 => expr.push(0x31),                    // DW_OP_lit1
            2..=31 => expr.push(0x2F + value as u8), // DW_OP_lit2 .. DW_OP_lit31
            v if v >= 0 && v <= 127 => {
                expr.push(0x08); // DW_OP_const1u
                expr.push(v as u8);
            }
            v if v >= -128 && v <= -1 => {
                expr.push(0x0C); // DW_OP_const1s
                expr.push(v as u8);
            }
            v if v >= 0 && v <= 0x7FFF => {
                expr.push(0x0A); // DW_OP_const2u
                expr.extend_from_slice(&(v as u16).to_le_bytes());
            }
            v if v >= -0x8000 && v <= -1 => {
                expr.push(0x0E); // DW_OP_const2s
                expr.extend_from_slice(&(v as i16).to_le_bytes());
            }
            v if v >= 0 && v <= 0x7FFF_FFFF => {
                expr.push(0x0C); // DW_OP_const4u
                expr.extend_from_slice(&(v as u32).to_le_bytes());
            }
            v => {
                expr.push(0x0E); // DW_OP_const8u (DWARF64)
                expr.extend_from_slice(&v.to_le_bytes());
            }
        }
        expr
    }

    /// Generate a DWARF expression for a memory address.
    pub fn generate_memory_expr(&self, address: u64) -> Vec<u8> {
        let mut expr = Vec::new();
        expr.push(0x03); // DW_OP_addr
        if self.use_dwarf64 {
            expr.extend_from_slice(&address.to_le_bytes());
        } else {
            expr.extend_from_slice(&(address as u32).to_le_bytes());
        }
        expr
    }

    /// Generate a DWARF expression for an unavailable value.
    pub fn generate_unavailable_expr(&self) -> Vec<u8> {
        vec![0x00] // DW_OP_nop (or could be explicit)
    }

    /// Generate a composite DWARF expression from pieces.
    pub fn generate_composite_expr(&self, pieces: &[X86DebugPiece]) -> Vec<u8> {
        let mut expr = Vec::new();
        for piece in pieces {
            match &piece.location {
                X86DebugLocation::Register { dwarf_reg, offset } => {
                    expr.extend_from_slice(&self.generate_register_expr(*dwarf_reg, *offset));
                }
                X86DebugLocation::Stack { frame_offset, size } => {
                    expr.extend_from_slice(&self.generate_stack_expr(*frame_offset, *size));
                }
                X86DebugLocation::Constant { value } => {
                    expr.extend_from_slice(&self.generate_constant_expr(*value));
                }
                _ => {
                    expr.push(0x00); // DW_OP_nop for unsupported
                }
            }
            // DW_OP_piece <size>
            expr.push(0x93); // DW_OP_piece
            expr.extend_from_slice(&self.encode_uleb128(piece.size as u64));
        }
        expr
    }

    /// Generate the full DWARF expression for a debug location.
    pub fn generate_expr(&self, location: &X86DebugLocation) -> Vec<u8> {
        match location {
            X86DebugLocation::Register { dwarf_reg, offset } => {
                self.generate_register_expr(*dwarf_reg, *offset)
            }
            X86DebugLocation::Stack { frame_offset, size } => {
                self.generate_stack_expr(*frame_offset, *size)
            }
            X86DebugLocation::Constant { value } => self.generate_constant_expr(*value),
            X86DebugLocation::Memory { address } => self.generate_memory_expr(*address),
            X86DebugLocation::DwarfExpression { expr_bytes } => expr_bytes.clone(),
            X86DebugLocation::Unavailable => self.generate_unavailable_expr(),
            X86DebugLocation::Composite { pieces } => self.generate_composite_expr(pieces),
        }
    }

    /// Generate a DWARF location list entry.
    pub fn generate_loclist_entry(
        &self,
        start_offset: u64,
        end_offset: u64,
        location: &X86DebugLocation,
    ) -> Vec<u8> {
        let mut entry = Vec::new();
        entry.extend_from_slice(&start_offset.to_le_bytes());
        entry.extend_from_slice(&end_offset.to_le_bytes());
        let expr = self.generate_expr(location);
        entry.extend_from_slice(&(expr.len() as u16).to_le_bytes());
        entry.extend_from_slice(&expr);
        entry
    }

    /// Encode an unsigned LEB128 value.
    fn encode_uleb128(&self, mut value: u64) -> Vec<u8> {
        let mut buf = Vec::new();
        loop {
            let mut byte = (value & 0x7F) as u8;
            value >>= 7;
            if value != 0 {
                byte |= 0x80;
            }
            buf.push(byte);
            if value == 0 {
                break;
            }
        }
        buf
    }

    /// Encode a signed LEB128 value.
    fn encode_sleb128(&self, mut value: i64) -> Vec<u8> {
        let mut buf = Vec::new();
        loop {
            let mut byte = (value & 0x7F) as u8;
            value >>= 7;
            if (value == 0 && (byte & 0x40) == 0) || (value == -1 && (byte & 0x40) != 0) {
                buf.push(byte);
                break;
            }
            byte |= 0x80;
            buf.push(byte);
        }
        buf
    }
}

impl Default for X86DebugValueRecord {
    fn default() -> Self {
        X86DebugValueRecord {
            var_location: X86DebugVarLocation::default(),
            dwarf_expression: Vec::new(),
            expression_valid: false,
            di_expression: Vec::new(),
        }
    }
}

impl X86DebugValueRecord {
    /// Create a new debug value record.
    pub fn new(var_location: X86DebugVarLocation) -> Self {
        X86DebugValueRecord {
            var_location,
            dwarf_expression: Vec::new(),
            expression_valid: false,
            di_expression: Vec::new(),
        }
    }

    /// Generate the DWARF expression for this value using a generator.
    pub fn generate_expression(&mut self, generator: &X86DwarfExprGenerator) {
        self.dwarf_expression = generator.generate_expr(&self.var_location.location);
        self.expression_valid = true;
    }

    /// Set the DIExpression from debug metadata.
    pub fn set_di_expression(&mut self, expr: Vec<u8>) {
        self.di_expression = expr;
    }
}

impl Default for X86DebugInfoMap {
    fn default() -> Self {
        X86DebugInfoMap {
            function_name: String::new(),
            locations_by_id: BTreeMap::new(),
            locations_by_offset: BTreeMap::new(),
            debug_values: Vec::new(),
            cu_offset: 0,
            has_debug_info: false,
        }
    }
}

impl X86DebugInfoMap {
    /// Create a new debug info map for a function.
    pub fn new(function_name: &str) -> Self {
        X86DebugInfoMap {
            function_name: function_name.to_string(),
            locations_by_id: BTreeMap::new(),
            locations_by_offset: BTreeMap::new(),
            debug_values: Vec::new(),
            cu_offset: 0,
            has_debug_info: false,
        }
    }

    /// Record a debug value at a stack map point.
    pub fn record_debug_value(&mut self, record: X86DebugValueRecord) {
        self.has_debug_info = true;
        let loc = record.var_location.clone();
        self.locations_by_id
            .entry(loc.stack_map_id)
            .or_insert_with(Vec::new)
            .push(loc.clone());
        self.locations_by_offset
            .entry(loc.instruction_offset)
            .or_insert_with(Vec::new)
            .push(loc);
        self.debug_values.push(record);
    }

    /// Get variable locations at a specific stack map ID.
    pub fn locations_at_id(&self, id: u64) -> Option<&Vec<X86DebugVarLocation>> {
        self.locations_by_id.get(&id)
    }

    /// Get variable locations at a specific instruction offset.
    pub fn locations_at_offset(&self, offset: u32) -> Option<&Vec<X86DebugVarLocation>> {
        self.locations_by_offset.get(&offset)
    }

    /// Get all variable names tracked.
    pub fn all_variable_names(&self) -> HashSet<&str> {
        self.debug_values
            .iter()
            .map(|dv| dv.var_location.var_name.as_str())
            .collect()
    }

    /// Total number of debug value records.
    pub fn record_count(&self) -> usize {
        self.debug_values.len()
    }

    /// Emit DWARF .debug_loc section entries for all variables.
    pub fn emit_debug_loc_section(&self, generator: &X86DwarfExprGenerator) -> Vec<u8> {
        let mut buf = Vec::new();
        for dv in &self.debug_values {
            if !dv.var_location.is_live {
                continue;
            }
            let expr = generator.generate_expr(&dv.var_location.location);
            buf.extend_from_slice(&dv.var_location.instruction_offset.to_le_bytes());
            buf.extend_from_slice(&(dv.var_location.instruction_offset + 4).to_le_bytes());
            buf.extend_from_slice(&(expr.len() as u16).to_le_bytes());
            buf.extend_from_slice(&expr);
        }
        // End-of-list marker
        buf.extend_from_slice(&0u64.to_le_bytes());
        buf.extend_from_slice(&0u64.to_le_bytes());
        buf
    }
}

impl Default for X86DebugLocTracker {
    fn default() -> Self {
        X86DebugLocTracker {
            current_locations: HashMap::new(),
            var_types: HashMap::new(),
            location_history: Vec::new(),
            active: false,
            current_offset: 0,
        }
    }
}

impl X86DebugLocTracker {
    /// Create a new debug location tracker.
    pub fn new() -> Self {
        X86DebugLocTracker {
            current_locations: HashMap::new(),
            var_types: HashMap::new(),
            location_history: Vec::new(),
            active: false,
            current_offset: 0,
        }
    }

    /// Start tracking.
    pub fn begin(&mut self) {
        self.active = true;
        self.current_offset = 0;
    }

    /// Advance to the given instruction offset.
    pub fn advance_to(&mut self, offset: u32) {
        self.current_offset = offset;
    }

    /// Record a variable's location.
    pub fn set_location(&mut self, var_name: &str, location: X86DebugLocation, type_name: &str) {
        if !self.active {
            return;
        }
        self.current_locations
            .insert(var_name.to_string(), location.clone());
        self.var_types
            .insert(var_name.to_string(), type_name.to_string());
        self.location_history
            .push((self.current_offset, var_name.to_string(), location));
    }

    /// Get the current location of a variable.
    pub fn get_location(&self, var_name: &str) -> Option<&X86DebugLocation> {
        self.current_locations.get(var_name)
    }

    /// Get the type of a variable.
    pub fn get_type(&self, var_name: &str) -> Option<&String> {
        self.var_types.get(var_name)
    }

    /// Capture a snapshot of all live variables at the current offset.
    pub fn capture_locations(&self, stack_map_id: u64) -> Vec<X86DebugVarLocation> {
        self.current_locations
            .iter()
            .filter_map(|(name, loc)| {
                let type_name = self.var_types.get(name).cloned().unwrap_or_default();
                match loc {
                    X86DebugLocation::Register {
                        dwarf_reg,
                        offset: _,
                    } => Some(X86DebugVarLocation::new_register(
                        name,
                        *dwarf_reg,
                        &type_name,
                        stack_map_id,
                        self.current_offset,
                    )),
                    X86DebugLocation::Stack { frame_offset, size } => {
                        Some(X86DebugVarLocation::new_stack(
                            name,
                            *frame_offset,
                            *size,
                            &type_name,
                            stack_map_id,
                            self.current_offset,
                        ))
                    }
                    _ => {
                        let loc = X86DebugVarLocation {
                            var_name: name.clone(),
                            dwarf_tag: 0x34,
                            type_name,
                            location: loc.clone(),
                            is_live: true,
                            stack_map_id,
                            instruction_offset: self.current_offset,
                            is_entry_value: false,
                            fragment: None,
                        };
                        Some(loc)
                    }
                }
            })
            .collect()
    }

    /// Stop tracking.
    pub fn end(&mut self) {
        self.active = false;
    }
}

// ============================================================================
// X86Safepoints — Safepoint Management & GC Cooperation
// ============================================================================
//
// Extended safepoint infrastructure for thread suspension, GC cooperation,
// and runtime safepoint management. This builds on `X86GCSafepoint` with
// additional mechanisms for thread-level safepoint coordination, guard-page
// based polling, and cooperative GC handshake protocols.

/// A safepoint action — what the runtime should do at a given safepoint.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum X86SafepointAction {
    /// No specific GC action needed; just a potential suspension point.
    PollOnly,
    /// Perform a stop-the-world GC pause.
    GCCollect { generation: u32, is_full_gc: bool },
    /// Thread should deoptimize to the interpreter.
    Deoptimize {
        reason: DeoptReason,
        target_bytecode_offset: u32,
    },
    /// Thread should suspend and wait for a signal.
    Suspend,
    /// Thread should take a cooperative suspension sample.
    CooperativeSample { sample_id: u64 },
    /// Thread should execute an asynchronous event handler.
    AsyncEventHandler { event_id: u64 },
    /// Custom runtime action.
    Custom { action_id: u32, payload: Vec<u8> },
}

impl X86SafepointAction {
    pub fn name(&self) -> &'static str {
        match self {
            X86SafepointAction::PollOnly => "PollOnly",
            X86SafepointAction::GCCollect { .. } => "GCCollect",
            X86SafepointAction::Deoptimize { .. } => "Deoptimize",
            X86SafepointAction::Suspend => "Suspend",
            X86SafepointAction::CooperativeSample { .. } => "CooperativeSample",
            X86SafepointAction::AsyncEventHandler { .. } => "AsyncEventHandler",
            X86SafepointAction::Custom { .. } => "Custom",
        }
    }

    pub fn requires_gc_pause(&self) -> bool {
        matches!(self, X86SafepointAction::GCCollect { .. })
    }

    pub fn requires_deopt(&self) -> bool {
        matches!(self, X86SafepointAction::Deoptimize { .. })
    }

    pub fn requires_suspension(&self) -> bool {
        matches!(
            self,
            X86SafepointAction::Suspend
                | X86SafepointAction::GCCollect { .. }
                | X86SafepointAction::Deoptimize { .. }
        )
    }
}

/// Safepoint manager for X86 threads — coordinates safepoint polling,
/// thread suspension, and GC cooperation.
#[derive(Debug, Clone)]
pub struct X86Safepoints {
    /// The underlying GC safepoint infrastructure.
    pub gc_safepoint: X86GCSafepoint,
    /// Pending safepoint actions keyed by safepoint ID.
    pub pending_actions: BTreeMap<u64, X86SafepointAction>,
    /// Threads that are currently at safepoints.
    pub threads_at_safepoint: HashSet<u64>,
    /// Whether a global GC is in progress.
    pub global_gc_in_progress: bool,
    /// The current GC generation (for generational collectors).
    pub current_gc_generation: u32,
    /// Total number of safepoints hit across all threads.
    pub total_safepoint_hits: u64,
    /// Guard page configuration.
    pub guard_page: X86SafepointGuardPage,
    /// Whether cooperative suspension is enabled.
    pub cooperative_suspension_enabled: bool,
    /// Whether thread suspension at safepoints is enabled.
    pub thread_suspension_enabled: bool,
}

/// Guard page configuration for safepoint polling.
#[derive(Debug, Clone)]
pub struct X86SafepointGuardPage {
    /// Virtual address of the guard page.
    pub page_address: u64,
    /// Page size (typically 4096).
    pub page_size: u64,
    /// Whether the guard page is currently armed (unmapped).
    pub is_armed: bool,
    /// Offset within the page to load from for the poll.
    pub poll_offset: u32,
    /// Whether to use a dedicated polling page.
    pub use_dedicated_page: bool,
}

/// Protocol for cooperative GC handshake between mutator threads and GC.
#[derive(Debug, Clone)]
pub struct X86CooperativeGCHandshake {
    /// Whether the mutator should yield at the next safepoint.
    pub should_yield: bool,
    /// Whether the GC is waiting for this thread.
    pub gc_waiting: bool,
    /// Handshake state machine.
    pub state: X86HandshakeState,
    /// Number of times this thread has yielded for GC.
    pub yield_count: u64,
    /// Whether parking is supported at safepoints.
    pub supports_parking: bool,
}

/// States for the cooperative handshake protocol.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86HandshakeState {
    /// Normal execution; no GC requested.
    Running,
    /// GC has been requested; thread should reach a safepoint.
    GCRequested,
    /// Thread is at a safepoint and ready to yield.
    AtSafepoint,
    /// Thread has yielded; GC can proceed.
    Yielded,
    /// GC is complete; thread can resume.
    Resume,
    /// Thread is resuming execution.
    Resuming,
}

impl X86HandshakeState {
    pub fn name(&self) -> &'static str {
        match self {
            X86HandshakeState::Running => "Running",
            X86HandshakeState::GCRequested => "GCRequested",
            X86HandshakeState::AtSafepoint => "AtSafepoint",
            X86HandshakeState::Yielded => "Yielded",
            X86HandshakeState::Resume => "Resume",
            X86HandshakeState::Resuming => "Resuming",
        }
    }
}

impl Default for X86SafepointGuardPage {
    fn default() -> Self {
        X86SafepointGuardPage {
            page_address: POLLING_PAGE_ADDRESS,
            page_size: 4096,
            is_armed: false,
            poll_offset: 0,
            use_dedicated_page: true,
        }
    }
}

impl X86SafepointGuardPage {
    /// Create a new guard page configuration.
    pub fn new(page_address: u64, page_size: u64) -> Self {
        X86SafepointGuardPage {
            page_address,
            page_size,
            is_armed: false,
            poll_offset: 0,
            use_dedicated_page: true,
        }
    }

    /// Arm the guard page (unmap it so loads cause SEGV).
    /// In a real runtime, this would call `mprotect(PROT_NONE)`.
    pub fn arm(&mut self) {
        self.is_armed = true;
    }

    /// Disarm the guard page (remap it so loads succeed).
    /// In a real runtime, this would call `mprotect(PROT_READ)`.
    pub fn disarm(&mut self) {
        self.is_armed = false;
    }

    /// Generate the X86 polling instruction sequence.
    /// This loads from the guard page: `testb $0, guard_page_addr(%rax)`
    /// If the page is unmapped, this triggers a SEGV → signal handler → safepoint.
    pub fn generate_poll_instruction_bytes(&self) -> Vec<u8> {
        // 64-bit: movabs guard_page_address, %r11; testb $0, (%r11)
        // Encoding: 49 BB <addr> 41 80 3B 00
        let mut bytes = vec![0x49, 0xBB];
        bytes.extend_from_slice(&self.page_address.to_le_bytes());
        bytes.extend_from_slice(&[0x41, 0x80, 0x3B, 0x00]);
        bytes
    }

    /// Generate an alternative polling load using RIP-relative addressing.
    pub fn generate_rip_relative_poll(&self, rip_offset: i32) -> Vec<u8> {
        // testb $0, (%rip + offset)
        let mut bytes = vec![0x80, 0x3D];
        bytes.extend_from_slice(&rip_offset.to_le_bytes());
        bytes.push(0x00);
        bytes
    }
}

impl Default for X86CooperativeGCHandshake {
    fn default() -> Self {
        X86CooperativeGCHandshake {
            should_yield: false,
            gc_waiting: false,
            state: X86HandshakeState::Running,
            yield_count: 0,
            supports_parking: false,
        }
    }
}

impl X86CooperativeGCHandshake {
    /// Create a new cooperative GC handshake.
    pub fn new(supports_parking: bool) -> Self {
        X86CooperativeGCHandshake {
            should_yield: false,
            gc_waiting: false,
            state: X86HandshakeState::Running,
            yield_count: 0,
            supports_parking,
        }
    }

    /// Request a GC — transition to GCRequested state.
    pub fn request_gc(&mut self) {
        self.should_yield = true;
        self.gc_waiting = true;
        self.state = X86HandshakeState::GCRequested;
    }

    /// Thread has reached a safepoint and is ready.
    pub fn reach_safepoint(&mut self) {
        if self.state == X86HandshakeState::GCRequested {
            self.state = X86HandshakeState::AtSafepoint;
        }
    }

    /// Thread yields to the GC.
    pub fn yield_to_gc(&mut self) {
        if self.state == X86HandshakeState::AtSafepoint {
            self.state = X86HandshakeState::Yielded;
            self.yield_count += 1;
        }
    }

    /// GC signals that the thread can resume.
    pub fn resume(&mut self) {
        self.state = X86HandshakeState::Resume;
    }

    /// Thread resumes execution.
    pub fn resume_execution(&mut self) {
        if self.state == X86HandshakeState::Resume {
            self.state = X86HandshakeState::Resuming;
            self.should_yield = false;
            self.gc_waiting = false;
            self.state = X86HandshakeState::Running;
        }
    }

    /// Check if the thread should yield at the next safepoint.
    pub fn needs_yield(&self) -> bool {
        self.should_yield
    }

    /// Check if the thread is currently in a yield state.
    pub fn is_yielded(&self) -> bool {
        self.state == X86HandshakeState::Yielded
    }

    /// Get the current handshake state.
    pub fn current_state(&self) -> X86HandshakeState {
        self.state
    }
}

impl Default for X86Safepoints {
    fn default() -> Self {
        X86Safepoints {
            gc_safepoint: X86GCSafepoint::default(),
            pending_actions: BTreeMap::new(),
            threads_at_safepoint: HashSet::new(),
            global_gc_in_progress: false,
            current_gc_generation: 0,
            total_safepoint_hits: 0,
            guard_page: X86SafepointGuardPage::default(),
            cooperative_suspension_enabled: false,
            thread_suspension_enabled: false,
        }
    }
}

impl X86Safepoints {
    /// Create a new safepoints manager.
    pub fn new() -> Self {
        X86Safepoints::default()
    }

    /// Enable cooperative suspension.
    pub fn enable_cooperative_suspension(&mut self) {
        self.cooperative_suspension_enabled = true;
        self.gc_safepoint.set_enabled(true);
    }

    /// Enable thread suspension at safepoints.
    pub fn enable_thread_suspension(&mut self) {
        self.thread_suspension_enabled = true;
    }

    /// Configure the guard page for polling.
    pub fn configure_guard_page(&mut self, page_address: u64, page_size: u64) {
        self.guard_page = X86SafepointGuardPage::new(page_address, page_size);
    }

    /// Set a pending safepoint action.
    pub fn set_action(&mut self, safepoint_id: u64, action: X86SafepointAction) {
        self.pending_actions.insert(safepoint_id, action);
    }

    /// Get the action for a safepoint, if any.
    pub fn get_action(&self, safepoint_id: u64) -> Option<&X86SafepointAction> {
        self.pending_actions.get(&safepoint_id)
    }

    /// Take (remove) the action for a safepoint.
    pub fn take_action(&mut self, safepoint_id: u64) -> Option<X86SafepointAction> {
        self.pending_actions.remove(&safepoint_id)
    }

    /// Mark a thread as having reached a safepoint.
    pub fn thread_at_safepoint(&mut self, thread_id: u64) {
        self.threads_at_safepoint.insert(thread_id);
        self.total_safepoint_hits += 1;
    }

    /// Mark a thread as having left a safepoint.
    pub fn thread_left_safepoint(&mut self, thread_id: u64) {
        self.threads_at_safepoint.remove(&thread_id);
    }

    /// Check if all known threads are at safepoints.
    pub fn all_threads_at_safepoint(&self, total_threads: usize) -> bool {
        self.threads_at_safepoint.len() == total_threads
    }

    /// Begin a global GC cycle.
    pub fn begin_global_gc(&mut self, generation: u32) {
        self.global_gc_in_progress = true;
        self.current_gc_generation = generation;
        self.guard_page.arm();
    }

    /// End a global GC cycle.
    pub fn end_global_gc(&mut self) {
        self.global_gc_in_progress = false;
        self.guard_page.disarm();
    }

    /// Generate the SEGV signal handler assembly stub that processes
    /// safepoint polls. When a thread loads from the guard page and
    /// triggers a SEGV, this handler runs the pending safepoint action.
    pub fn generate_signal_handler_stub(&self) -> String {
        let mut asm = String::new();
        asm.push_str("# Safepoint SEGV signal handler stub\n");
        asm.push_str("safepoint_signal_handler:\n");
        asm.push_str("    # Save all volatile registers\n");
        asm.push_str("    push %rax\n");
        asm.push_str("    push %rcx\n");
        asm.push_str("    push %rdx\n");
        asm.push_str("    push %rsi\n");
        asm.push_str("    push %rdi\n");
        asm.push_str("    push %r8\n");
        asm.push_str("    push %r9\n");
        asm.push_str("    push %r10\n");
        asm.push_str("    push %r11\n");
        asm.push_str("    # Check if fault was from polling page\n");
        asm.push_str("    movq %r11, %rdi  # fault address in R11\n");
        asm.push_str("    callq safepoint_is_poll_fault\n");
        asm.push_str("    test %al, %al\n");
        asm.push_str("    jz not_safepoint_fault\n");
        asm.push_str("    # Execute pending safepoint action\n");
        asm.push_str("    callq safepoint_execute_action\n");
        asm.push_str("    # Restore registers and return\n");
        asm.push_str("not_safepoint_fault:\n");
        asm.push_str("    pop %r11\n");
        asm.push_str("    pop %r10\n");
        asm.push_str("    pop %r9\n");
        asm.push_str("    pop %r8\n");
        asm.push_str("    pop %rdi\n");
        asm.push_str("    pop %rsi\n");
        asm.push_str("    pop %rdx\n");
        asm.push_str("    pop %rcx\n");
        asm.push_str("    pop %rax\n");
        asm.push_str("    retq\n");
        asm
    }

    /// Check whether a fault address falls within the polling page.
    pub fn is_poll_fault(&self, fault_address: u64) -> bool {
        fault_address >= self.guard_page.page_address
            && fault_address < self.guard_page.page_address + self.guard_page.page_size
    }

    /// Get the total number of safepoints hit.
    pub fn total_hits(&self) -> u64 {
        self.total_safepoint_hits
    }

    /// Number of pending actions.
    pub fn pending_action_count(&self) -> usize {
        self.pending_actions.len()
    }

    /// Number of threads currently at safepoints.
    pub fn threads_at_safepoint_count(&self) -> usize {
        self.threads_at_safepoint.len()
    }

    /// Clear all pending actions.
    pub fn clear_actions(&mut self) {
        self.pending_actions.clear();
    }

    /// Reset safepoint statistics.
    pub fn reset_stats(&mut self) {
        self.total_safepoint_hits = 0;
        self.gc_safepoint.reset();
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    // -------------------------------------------------------------------------
    // StackMapHeader tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_stack_map_header_creation() {
        let header = StackMapHeader::current();
        assert_eq!(header.version, STACK_MAP_VERSION);
        assert_eq!(header.reserved1, 0);
        assert_eq!(header.reserved2, 0);
        assert_eq!(header.reserved3, 0);
    }

    #[test]
    fn test_stack_map_header_roundtrip() {
        let header = StackMapHeader::current();
        let bytes = header.to_bytes();
        assert_eq!(bytes.len(), 8);

        let mut cursor = Cursor::new(&bytes);
        let parsed = StackMapHeader::from_reader(&mut cursor).unwrap();
        assert_eq!(header, parsed);
    }

    #[test]
    fn test_stack_map_header_validation() {
        let header = StackMapHeader::current();
        assert!(header.validate().is_ok());

        let bad_header = StackMapHeader::new(99);
        assert!(bad_header.validate().is_err());
    }

    // -------------------------------------------------------------------------
    // LocationKind tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_location_kind_from_u8() {
        assert_eq!(LocationKind::from_u8(1), Some(LocationKind::Register));
        assert_eq!(LocationKind::from_u8(2), Some(LocationKind::Direct));
        assert_eq!(LocationKind::from_u8(3), Some(LocationKind::Indirect));
        assert_eq!(LocationKind::from_u8(4), Some(LocationKind::Constant));
        assert_eq!(LocationKind::from_u8(5), Some(LocationKind::ConstantIndex));
        assert_eq!(LocationKind::from_u8(6), Some(LocationKind::VectorSplice));
        assert_eq!(LocationKind::from_u8(0), None);
        assert_eq!(LocationKind::from_u8(255), None);
    }

    #[test]
    fn test_location_kind_properties() {
        assert!(LocationKind::Register.is_register());
        assert!(LocationKind::VectorSplice.is_register());
        assert!(LocationKind::Direct.is_stack());
        assert!(LocationKind::Indirect.is_stack());
        assert!(LocationKind::Constant.is_constant());
        assert!(LocationKind::ConstantIndex.is_constant());

        assert!(!LocationKind::Register.is_stack());
        assert!(!LocationKind::Constant.is_register());
        assert!(!LocationKind::Direct.is_constant());
    }

    // -------------------------------------------------------------------------
    // LocationRecord tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_location_record_register() {
        let loc = LocationRecord::new_register(0, 8);
        assert_eq!(loc.kind, LocationKind::Register);
        assert_eq!(loc.dwarf_reg_num, 0);
        assert_eq!(loc.size, 8);
        assert_eq!(loc.offset, 0);
    }

    #[test]
    fn test_location_record_direct() {
        let loc = LocationRecord::new_direct(6, -16, 8);
        assert_eq!(loc.kind, LocationKind::Direct);
        assert_eq!(loc.dwarf_reg_num, 6); // RBP
        assert_eq!(loc.offset, -16);
        assert_eq!(loc.size, 8);
    }

    #[test]
    fn test_location_record_indirect() {
        let loc = LocationRecord::new_indirect(7, 32, 8);
        assert_eq!(loc.kind, LocationKind::Indirect);
        assert_eq!(loc.dwarf_reg_num, 7); // RSP
        assert_eq!(loc.offset, 32);
    }

    #[test]
    fn test_location_record_constant() {
        let loc = LocationRecord::new_constant(42);
        assert_eq!(loc.kind, LocationKind::Constant);
        assert_eq!(loc.offset, 42);
        assert_eq!(loc.size, 8);
    }

    #[test]
    fn test_location_record_constant_index() {
        let loc = LocationRecord::new_constant_index(3);
        assert_eq!(loc.kind, LocationKind::ConstantIndex);
        assert_eq!(loc.offset, 3);
        assert_eq!(loc.size, 0);
    }

    #[test]
    fn test_location_record_roundtrip() {
        let loc = LocationRecord::new_register(0, 8);
        let bytes = loc.to_bytes();
        assert_eq!(bytes.len(), 16);

        let mut cursor = Cursor::new(&bytes);
        let parsed = LocationRecord::from_reader(&mut cursor).unwrap();
        assert_eq!(loc, parsed);
    }

    #[test]
    fn test_location_record_multiple_roundtrip() {
        let locs = vec![
            LocationRecord::new_register(0, 8),
            LocationRecord::new_direct(6, -16, 8),
            LocationRecord::new_constant(42),
            LocationRecord::new_vector_splice(17, 0, 32),
        ];

        let mut buf = Vec::new();
        for loc in &locs {
            buf.extend_from_slice(&loc.to_bytes());
        }

        let mut cursor = Cursor::new(&buf);
        for expected in &locs {
            let parsed = LocationRecord::from_reader(&mut cursor).unwrap();
            assert_eq!(*expected, parsed);
        }
    }

    // -------------------------------------------------------------------------
    // StackMapFunctionRecord tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_function_record_roundtrip() {
        let func = StackMapFunctionRecord::new(0x1000, 128, 2, 5);
        let bytes = func.to_bytes();
        assert_eq!(bytes.len(), 24);

        let mut cursor = Cursor::new(&bytes);
        let parsed = StackMapFunctionRecord::from_reader(&mut cursor).unwrap();
        assert_eq!(func, parsed);
    }

    // -------------------------------------------------------------------------
    // StackSizeRecord tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_stack_size_record_roundtrip() {
        let rec = StackSizeRecord::new(0x20, 96);
        let bytes = rec.to_bytes();
        assert_eq!(bytes.len(), 16);

        let mut cursor = Cursor::new(&bytes);
        let parsed = StackSizeRecord::from_reader(&mut cursor).unwrap();
        assert_eq!(rec, parsed);
    }

    // -------------------------------------------------------------------------
    // LiveOutRecord tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_live_out_record_roundtrip() {
        let rec = LiveOutRecord::new(0, 8);
        let bytes = rec.to_bytes();
        assert_eq!(bytes.len(), 8);

        let mut cursor = Cursor::new(&bytes);
        let parsed = LiveOutRecord::from_reader(&mut cursor).unwrap();
        assert_eq!(rec, parsed);
    }

    // -------------------------------------------------------------------------
    // ConstantPoolRecord tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_constant_pool_record_roundtrip() {
        let rec = ConstantPoolRecord::new(0xDEADBEEF_CAFEBABE);
        let bytes = rec.to_bytes();
        assert_eq!(bytes.len(), 8);

        let mut cursor = Cursor::new(&bytes);
        let parsed = ConstantPoolRecord::from_reader(&mut cursor).unwrap();
        assert_eq!(rec, parsed);
    }

    // -------------------------------------------------------------------------
    // StackMapRecord tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_stack_map_record_creation() {
        let record = StackMapRecord::new(1, 0x20);
        assert_eq!(record.id, 1);
        assert_eq!(record.instruction_offset, 0x20);
        assert_eq!(record.locations.len(), 0);
        assert_eq!(record.live_outs.len(), 0);
    }

    #[test]
    fn test_stack_map_record_add_location() {
        let mut record = StackMapRecord::new(1, 0x10);
        record.add_location(LocationRecord::new_register(0, 8));
        record.add_location(LocationRecord::new_direct(6, -8, 8));

        assert_eq!(record.location_count(), 2);
        assert_eq!(record.num_locations, 2);
    }

    #[test]
    fn test_stack_map_record_header_roundtrip() {
        let record = StackMapRecord::new(42, 0x100);
        let bytes = record.to_header_bytes();
        assert_eq!(bytes.len(), 16);

        let mut cursor = Cursor::new(&bytes);
        let (id, offset, _reserved, num_locs) =
            StackMapRecord::header_from_reader(&mut cursor).unwrap();
        assert_eq!(id, 42);
        assert_eq!(offset, 0x100);
        assert_eq!(num_locs, 0);
    }

    // -------------------------------------------------------------------------
    // X86RegisterNames tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_register_name_resolution_64bit() {
        let names = X86RegisterNames::new(true);
        assert_eq!(names.resolve(0), "RAX");
        assert_eq!(names.resolve(6), "RBP");
        assert_eq!(names.resolve(7), "RSP");
        assert_eq!(names.resolve(16), "RIP");
        assert_eq!(names.resolve(17), "XMM0");
    }

    #[test]
    fn test_register_name_resolution_32bit() {
        let names = X86RegisterNames::new(false);
        assert_eq!(names.resolve(0), "EAX");
        assert_eq!(names.resolve(6), "EBP");
        assert_eq!(names.resolve(7), "ESP");
        assert_eq!(names.resolve(16), "EIP");
    }

    #[test]
    fn test_register_name_unknown() {
        let names = X86RegisterNames::new(true);
        assert_eq!(names.resolve(200), "Reg(200)");
    }

    #[test]
    fn test_register_classification() {
        let names = X86RegisterNames::new(true);
        assert!(names.is_gpr(0)); // RAX
        assert!(names.is_gpr(15)); // R15
        assert!(!names.is_gpr(17)); // XMM0
        assert!(names.is_xmm(17));
        assert!(names.is_ymm(49));
        assert!(names.is_zmm(81));
    }

    #[test]
    fn test_register_caller_callee_saved() {
        let names = X86RegisterNames::new(true);
        // Caller-saved
        assert!(names.is_caller_saved(0)); // RAX
        assert!(names.is_caller_saved(2)); // RCX
        assert!(names.is_caller_saved(11)); // R11
        assert!(names.is_caller_saved(17)); // XMM0
                                            // Callee-saved
        assert!(names.is_callee_saved(3)); // RBX
        assert!(names.is_callee_saved(6)); // RBP
        assert!(names.is_callee_saved(12)); // R12
    }

    // -------------------------------------------------------------------------
    // X86StackMapFormat tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_format_creation() {
        let fmt = X86StackMapFormat::new();
        assert_eq!(fmt.header.version, STACK_MAP_VERSION);
        assert_eq!(fmt.num_functions, 0);
        assert_eq!(fmt.num_constants, 0);
        assert_eq!(fmt.functions.len(), 0);
    }

    #[test]
    fn test_format_add_constant() {
        let mut fmt = X86StackMapFormat::new();
        let idx = fmt.add_constant(42);
        assert_eq!(idx, 0);
        assert_eq!(fmt.get_constant(0), Some(42));
        assert_eq!(fmt.num_constants, 1);

        let idx2 = fmt.add_constant(100);
        assert_eq!(idx2, 1);
        assert_eq!(fmt.get_constant(1), Some(100));
    }

    #[test]
    fn test_format_find_record_by_id() {
        let mut fmt = X86StackMapFormat::new();

        let func = StackMapFunctionRecord::new(0x1000, 64, 0, 2);
        let rec1 = StackMapRecord::new(10, 0x10);
        let rec2 = StackMapRecord::new(20, 0x20);
        fmt.add_function(func.clone(), Vec::new(), vec![rec1, rec2]);

        assert!(fmt.find_record_by_id(10).is_some());
        assert!(fmt.find_record_by_id(20).is_some());
        assert!(fmt.find_record_by_id(99).is_none());
    }

    #[test]
    fn test_format_roundtrip_empty() {
        let fmt = X86StackMapFormat::new();
        let bytes = fmt.to_bytes();
        let parsed = X86StackMapFormat::from_bytes(&bytes).unwrap();
        assert_eq!(parsed.header, fmt.header);
        assert_eq!(parsed.num_functions, fmt.num_functions);
    }

    #[test]
    fn test_format_roundtrip_with_data() {
        let mut fmt = X86StackMapFormat::new();

        let func = StackMapFunctionRecord::new(0x1000, 128, 1, 2);
        let size_rec = StackSizeRecord::new(0, 128);
        let mut rec1 = StackMapRecord::new(1, 0x10);
        rec1.add_location(LocationRecord::new_register(0, 8));
        let rec2 = StackMapRecord::new(2, 0x20);
        rec2.add_location(LocationRecord::new_direct(6, -16, 8));
        rec2.add_live_out(LiveOutRecord::new(0, 8));

        fmt.add_function(func, vec![size_rec], vec![rec1, rec2]);
        fmt.add_constant(0xDEADBEEF);

        let bytes = fmt.to_bytes();
        let parsed = X86StackMapFormat::from_bytes(&bytes).unwrap();

        assert_eq!(parsed.num_functions, 1);
        assert_eq!(parsed.num_constants, 1);
        assert_eq!(parsed.records.len(), 2);
        assert!(parsed.validate().is_ok());
    }

    #[test]
    fn test_format_validation() {
        let format = X86StackMapFormat::new();
        assert!(format.validate().is_ok());
    }

    // -------------------------------------------------------------------------
    // X86StackMaps tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_stack_maps_creation() {
        let sm = X86StackMaps::new("x86_64-unknown-linux-gnu", true);
        assert!(sm.enabled);
        assert!(!sm.verbose);
        assert_eq!(sm.next_id, 0);
    }

    #[test]
    fn test_stack_maps_allocate_id() {
        let mut sm = X86StackMaps::new("x86_64-unknown-linux-gnu", true);
        assert_eq!(sm.allocate_id(), 0);
        assert_eq!(sm.allocate_id(), 1);
        assert_eq!(sm.allocate_id(), 2);
        assert_eq!(sm.next_id, 3);
    }

    #[test]
    fn test_stack_maps_register_function() {
        let mut sm = X86StackMaps::new("x86_64-unknown-linux-gnu", true);
        let idx = sm.register_function("test_func", 128);
        assert_eq!(idx, 0);
        assert_eq!(sm.function_count(), 1);

        let idx2 = sm.register_function("test_func2", 256);
        assert_eq!(idx2, 1);
        assert_eq!(sm.function_count(), 2);
    }

    #[test]
    fn test_stack_maps_add_record() {
        let mut sm = X86StackMaps::new("x86_64-unknown-linux-gnu", true);
        let idx = sm.register_function("test", 128);
        let record = StackMapRecord::new(1, 0x10);
        sm.add_record(idx, record.clone());
        sm.finalize();

        assert_eq!(sm.format.records.len(), 1);
        let found = sm.lookup_record(1);
        assert!(found.is_some());
        assert_eq!(found.unwrap().id, 1);
    }

    #[test]
    fn test_stack_maps_validate_duplicate_ids() {
        let mut sm = X86StackMaps::new("x86_64-unknown-linux-gnu", true);
        let idx = sm.register_function("test", 128);

        // Add two records with the same ID (manually setting next_id)
        sm.next_id = 5;
        let rec1 = StackMapRecord::new(5, 0x10);
        let rec2 = StackMapRecord::new(5, 0x20);
        sm.add_record(idx, rec1);
        sm.add_record(idx, rec2);

        assert!(sm.validate().is_err());
    }

    #[test]
    fn test_stack_maps_emit_section() {
        let mut sm = X86StackMaps::new("x86_64-unknown-linux-gnu", true);
        let idx = sm.register_function("test", 128);
        sm.add_record(idx, StackMapRecord::new(1, 0x10));

        let section = sm.emit_section();
        assert!(!section.is_empty());
    }

    #[test]
    fn test_stack_maps_emit_asm() {
        let mut sm = X86StackMaps::new("x86_64-unknown-linux-gnu", true);
        let idx = sm.register_function("test", 128);
        sm.add_record(idx, StackMapRecord::new(1, 0x10));

        let asm = sm.emit_asm();
        assert!(asm.contains(STACK_MAP_SECTION_NAME));
    }

    // -------------------------------------------------------------------------
    // X86PatchPoint tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_patchpoint_call_creation() {
        let pp = X86PatchPoint::new_call(1, "my_function", 3);
        assert_eq!(pp.id, 1);
        assert_eq!(pp.patch_type, PatchableType::Call);
        assert_eq!(pp.target, Some("my_function".to_string()));
        assert_eq!(pp.num_args, 3);
        assert_eq!(pp.nop_sled_size, PATCHABLE_NOP_SLED_SIZE);
    }

    #[test]
    fn test_patchpoint_typed_call() {
        let pp = X86PatchPoint::new_typed_call(2, "alloc", 2, "i8*");
        assert_eq!(pp.return_type, Some("i8*".to_string()));
    }

    #[test]
    fn test_patchpoint_jump_creation() {
        let pp = X86PatchPoint::new_jump(3, "loop_start");
        assert_eq!(pp.patch_type, PatchableType::Jump);
        assert_eq!(pp.nop_sled_size, PATCHABLE_JUMP_SEQUENCE_SIZE);
        assert_eq!(pp.num_args, 0);
    }

    #[test]
    fn test_patchpoint_region_creation() {
        let pp = X86PatchPoint::new_region(4, 128);
        assert_eq!(pp.patch_type, PatchableType::Region);
        assert_eq!(pp.nop_sled_size, 128);
        assert_eq!(pp.target, None);
    }

    #[test]
    fn test_nop_sled_generation() {
        // Test various sizes
        let sizes = [0, 1, 7, 8, 9, 15, 16, 32, 64, 128];

        for size in &sizes {
            let pp = X86PatchPoint::new_region(0, *size);
            let sled = pp.generate_nop_sled();
            assert_eq!(
                sled.len(),
                *size,
                "NOP sled size mismatch for size {}",
                size
            );

            // Verify that the sled only contains NOP bytes
            // (simplified check: verify first byte is a known NOP prefix)
            if !sled.is_empty() {
                match sled[0] {
                    0x90 | 0x66 | 0x0F => {} // Valid NOP prefixes
                    _ => panic!("Unexpected byte in NOP sled: 0x{:02X}", sled[0]),
                }
            }
        }
    }

    #[test]
    fn test_patchpoint_machine_instrs_call() {
        let pp = X86PatchPoint::new_call(1, "target_func", 2);
        let (sled, call) = pp.generate_machine_instrs();

        assert!(!sled.is_empty());
        assert!(call.is_some());
        let call_instr = call.unwrap();
        assert_eq!(call_instr.opcode, 0xE8); // CALL opcode
    }

    #[test]
    fn test_patchpoint_machine_instrs_jump() {
        let pp = X86PatchPoint::new_jump(1, "target_label");
        let (sled, jmp) = pp.generate_machine_instrs();

        let jmp_instr = jmp.unwrap();
        assert_eq!(jmp_instr.opcode, 0xE9); // JMP opcode
    }

    #[test]
    fn test_patchpoint_machine_instrs_region() {
        let pp = X86PatchPoint::new_region(1, 32);
        let (sled, other) = pp.generate_machine_instrs();

        assert!(!sled.is_empty());
        assert!(other.is_none()); // Region has no call/jump
    }

    #[test]
    fn test_patchpoint_calling_convention() {
        let mut pp = X86PatchPoint::new_call(1, "func", 0);
        pp.set_calling_convention("preserve_mostcc");
        assert_eq!(pp.calling_convention, "preserve_mostcc");
    }

    #[test]
    fn test_patchpoint_metadata() {
        let mut pp = X86PatchPoint::new_call(1, "func", 0);
        pp.set_metadata(b"test_metadata");
        assert_eq!(pp.metadata, b"test_metadata");
    }

    #[test]
    fn test_patchpoint_to_ir_text() {
        let pp = X86PatchPoint::new_call(1, "target", 2);
        let ir = pp.to_ir_text();
        assert!(ir.contains("llvm.experimental.patchpoint"));
        assert!(ir.contains("@target"));
    }

    #[test]
    fn test_patchpoint_stack_map_record() {
        let pp = X86PatchPoint::new_call(42, "target", 0);
        let record = pp.generate_stack_map_record(0x100);
        assert_eq!(record.id, 42);
        assert_eq!(record.instruction_offset, 0x100);
    }

    // -------------------------------------------------------------------------
    // X86StatePoint tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_statepoint_creation() {
        let sp = X86StatePoint::new(1, "my_func", 2);
        assert_eq!(sp.id, 1);
        assert_eq!(sp.callee, "my_func");
        assert_eq!(sp.num_call_args, 2);
        assert_eq!(sp.nop_bytes, 0);
        assert_eq!(sp.flags, 0);
    }

    #[test]
    fn test_statepoint_add_gc_root() {
        let mut sp = X86StatePoint::new(1, "func", 0);
        let val = X86StatepointValue::reg(0, "i8*");
        sp.add_gc_root(val);
        assert_eq!(sp.gc_args.len(), 1);
        assert_eq!(sp.base_pointer_ids.len(), 1);
    }

    #[test]
    fn test_statepoint_add_derived_pointer() {
        let mut sp = X86StatePoint::new(1, "func", 0);
        let base = X86StatepointValue::reg(0, "i8*");
        let base_idx = sp.add_gc_root(base);

        let derived = X86StatepointValue::reg(1, "i8*");
        sp.add_derived_pointer(derived, base_idx, 16);

        assert_eq!(sp.gc_args.len(), 2);
        assert_eq!(sp.derived_pointer_ids.len(), 1);
        assert_eq!(sp.relocation_records.len(), 1);

        let reloc = &sp.relocation_records[0];
        assert_eq!(reloc.base_ptr_index, base_idx);
        assert_eq!(reloc.derived_ptr_index, 1);
        assert_eq!(reloc.offset_from_base, 16);
    }

    #[test]
    fn test_statepoint_values() {
        let reg_val = X86StatepointValue::reg(0, "i8*");
        assert!(matches!(
            reg_val.repr,
            X86StatepointValueRepr::Register { .. }
        ));

        let stack_val = X86StatepointValue::stack(-8, "i64");
        assert!(matches!(
            stack_val.repr,
            X86StatepointValueRepr::Stack { .. }
        ));

        let const_val = X86StatepointValue::constant(42, "i32");
        assert!(matches!(
            const_val.repr,
            X86StatepointValueRepr::Constant { value: 42 }
        ));

        let undef_val = X86StatepointValue::undef("i64");
        assert!(matches!(undef_val.repr, X86StatepointValueRepr::Undef));
    }

    #[test]
    fn test_statepoint_value_to_location_record() {
        let val = X86StatepointValue::reg(0, "i8*");
        let loc = val.to_location_record();
        assert!(loc.is_some());
        assert_eq!(loc.unwrap().kind, LocationKind::Register);
    }

    #[test]
    fn test_statepoint_to_ir_text() {
        let mut sp = X86StatePoint::new(1, "target", 1);
        sp.add_gc_root(X86StatepointValue::reg(0, "i8*"));
        let ir = sp.to_ir_text();
        assert!(ir.contains("llvm.experimental.gc.statepoint"));
        assert!(ir.contains("@target"));
    }

    #[test]
    fn test_statepoint_gc_root_locations() {
        let mut sp = X86StatePoint::new(1, "func", 0);
        sp.add_gc_root(X86StatepointValue::reg(0, "i8*"));
        sp.add_gc_root(X86StatepointValue::reg(1, "i8*"));

        let locs = sp.get_gc_root_locations();
        assert_eq!(locs.len(), 2);
    }

    #[test]
    fn test_statepoint_derived_locations() {
        let mut sp = X86StatePoint::new(1, "func", 0);
        let base_idx = sp.add_gc_root(X86StatepointValue::reg(0, "i8*"));
        sp.add_derived_pointer(X86StatepointValue::reg(1, "i8*"), base_idx, 8);

        let derived = sp.get_derived_locations();
        assert_eq!(derived.len(), 1);
        let (loc, base_idx, offset) = &derived[0];
        assert_eq!(*base_idx, 0);
        assert_eq!(*offset, 8);
    }

    #[test]
    fn test_statepoint_stack_map_record() {
        let mut sp = X86StatePoint::new(42, "func", 0);
        sp.add_gc_root(X86StatepointValue::reg(0, "i8*"));

        let record = sp.generate_stack_map_record(0x100);
        assert_eq!(record.id, 42);
        assert_eq!(record.instruction_offset, 0x100);
        assert_eq!(record.locations.len(), 1);
    }

    // -------------------------------------------------------------------------
    // X86RelocationRecord tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_relocation_record() {
        let rec = X86RelocationRecord::new(1, 0, 2, 16);
        assert!(rec.is_derived());
        assert!(rec.has_interior_offset());
    }

    #[test]
    fn test_relocation_record_not_derived() {
        let rec = X86RelocationRecord::new(1, 0, 0, 0);
        assert!(!rec.is_derived());
        assert!(!rec.has_interior_offset());
    }

    // -------------------------------------------------------------------------
    // X86GCSafepoint tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_safepoint_creation() {
        let sp = X86GCSafepoint::new();
        assert!(sp.enabled);
        assert_eq!(sp.polling_page_address, POLLING_PAGE_ADDRESS);
        assert!(sp.insert_at_entry);
        assert!(sp.insert_at_backedge);
        assert!(!sp.insert_after_calls);
        assert_eq!(sp.backedge_frequency, 1);
    }

    #[test]
    fn test_safepoint_poll_sequence() {
        let sp = X86GCSafepoint::new();
        let seq = sp.generate_poll_sequence();
        assert_eq!(seq.len(), 2);
    }

    #[test]
    fn test_safepoint_poll_ir() {
        let sp = X86GCSafepoint::new();
        let ir = sp.generate_poll_ir();
        assert!(ir.contains("volatile"));
        assert!(ir.contains("inttoptr"));
    }

    #[test]
    fn test_safepoint_insert_entry() {
        let mut sp = X86GCSafepoint::new();
        let (loc, seq) = sp.insert_entry_safepoint("test_func", 1);

        assert_eq!(loc.kind, SafepointKind::FunctionEntry);
        assert_eq!(loc.function_name, "test_func");
        assert_eq!(loc.instruction_offset, 0);
        assert!(!seq.is_empty());
        assert_eq!(sp.stats.entry_safepoints, 1);
        assert_eq!(sp.safepoint_count, 1);
    }

    #[test]
    fn test_safepoint_insert_backedge() {
        let mut sp = X86GCSafepoint::new();
        let (loc, _seq) = sp.insert_backedge_safepoint("loop_func", 0x40, 2);

        assert_eq!(loc.kind, SafepointKind::LoopBackedge);
        assert_eq!(loc.instruction_offset, 0x40);
        assert_eq!(sp.stats.backedge_safepoints, 1);
    }

    #[test]
    fn test_safepoint_record_statepoint() {
        let mut sp = X86GCSafepoint::new();
        let loc = sp.record_statepoint("func", 0x80, 3);

        assert_eq!(loc.kind, SafepointKind::Statepoint);
        assert_eq!(sp.stats.statepoint_safepoints, 1);
    }

    #[test]
    fn test_safepoint_cooperative_suspend() {
        let mut sp = X86GCSafepoint::new();
        let (loc, _seq) = sp.insert_cooperative_suspend("func", 0x60, 4);

        assert_eq!(loc.kind, SafepointKind::CooperativeSuspend);
        assert_eq!(sp.stats.coop_suspend_points, 1);
    }

    #[test]
    fn test_safepoint_is_safepoint() {
        let mut sp = X86GCSafepoint::new();
        sp.insert_entry_safepoint("func", 1);

        assert!(sp.is_safepoint("func", 0));
        assert!(!sp.is_safepoint("func", 0x10));
        assert!(!sp.is_safepoint("other_func", 0));
    }

    #[test]
    fn test_safepoint_should_insert_backedge() {
        let sp = X86GCSafepoint::new();
        assert!(sp.should_insert_backedge(0));
        assert!(sp.should_insert_backedge(1));
        assert!(sp.should_insert_backedge(2));
    }

    #[test]
    fn test_safepoint_with_frequency() {
        let mut sp = X86GCSafepoint::new();
        sp.configure(true, true, false, 4);

        assert!(sp.should_insert_backedge(0));
        assert!(sp.should_insert_backedge(4));
        assert!(!sp.should_insert_backedge(1));
        assert!(!sp.should_insert_backedge(3));
    }

    #[test]
    fn test_safepoint_reset() {
        let mut sp = X86GCSafepoint::new();
        sp.insert_entry_safepoint("func", 1);
        assert_eq!(sp.safepoint_count, 1);

        sp.reset();
        assert_eq!(sp.safepoint_count, 0);
        assert_eq!(sp.safepoints.len(), 0);
        assert_eq!(sp.stats.total, 0);
    }

    #[test]
    fn test_safepoint_get_function_safepoints() {
        let mut sp = X86GCSafepoint::new();
        sp.insert_entry_safepoint("func_a", 1);
        sp.insert_backedge_safepoint("func_a", 0x20, 2);
        sp.insert_entry_safepoint("func_b", 3);

        let func_a_sps = sp.get_function_safepoints("func_a");
        assert_eq!(func_a_sps.len(), 2);

        let func_b_sps = sp.get_function_safepoints("func_b");
        assert_eq!(func_b_sps.len(), 1);
    }

    // -------------------------------------------------------------------------
    // X86StackMapGenerator tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_generator_creation() {
        let r#gen = X86StackMapGenerator::new(true);
        assert_eq!(r#gen.current_function, None);
        assert_eq!(r#gen.current_offset, 0);
    }

    #[test]
    fn test_generator_begin_end_function() {
        let mut r#gen = X86StackMapGenerator::new(true);
        r#gen.begin_function("test", 128);
        assert_eq!(r#gen.current_function, Some("test".to_string()));
        assert_eq!(r#gen.function_index_map.contains_key("test"), true);

        r#gen.end_function();
        assert_eq!(r#gen.current_function, None);
    }

    #[test]
    fn test_generator_record_register_location() {
        let mut r#gen = X86StackMapGenerator::new(true);
        r#gen.begin_function("test", 128);

        r#gen.record_register_location("test", 1, 0, 8, "i8*", true);

        let state = r#gen.live_var_state.get("test").unwrap();
        let loc = state.get_live_location(1);
        assert!(loc.is_some());
        assert_eq!(loc.unwrap().kind, LocationKind::Register);

        // Verify GC pointer tracking
        assert!(state.is_gc_pointer(1));
        assert!(!state.is_gc_pointer(2));
    }

    #[test]
    fn test_generator_record_stack_location() {
        let mut r#gen = X86StackMapGenerator::new(true);
        r#gen.begin_function("test", 128);

        r#gen.record_stack_location("test", 2, -16, 8, "i64", false, true);

        let state = r#gen.live_var_state.get("test").unwrap();
        let loc = state.get_live_location(2);
        assert!(loc.is_some());
        assert_eq!(loc.unwrap().kind, LocationKind::Indirect);
    }

    #[test]
    fn test_generator_record_constant_location() {
        let mut r#gen = X86StackMapGenerator::new(true);
        r#gen.begin_function("test", 128);

        r#gen.record_constant_location("test", 3, 42, "i32");

        let state = r#gen.live_var_state.get("test").unwrap();
        let loc = state.get_live_location(3);
        assert!(loc.is_some());
        assert_eq!(loc.unwrap().kind, LocationKind::Constant);
    }

    #[test]
    fn test_generator_generate_stack_map_record() {
        let mut r#gen = X86StackMapGenerator::new(true);
        r#gen.begin_function("test", 128);

        // Record a live GC pointer
        r#gen.record_register_location("test", 1, 0, 8, "i8*", true);
        r#gen.advance_offset(0x10);

        let record = r#gen.generate_stack_map_record("test", 1);
        assert!(record.is_some());

        let rec = record.unwrap();
        assert_eq!(rec.id, 1);
        assert!(rec.locations.len() > 0);
    }

    #[test]
    fn test_generator_spill_register() {
        let mut r#gen = X86StackMapGenerator::new(true);
        r#gen.begin_function("test", 128);

        r#gen.record_register_location("test", 1, 0, 8, "i8*", true);

        let slot = r#gen.spill_register("test", 1, 8);
        assert!(slot.is_some());

        // After spilling, the variable should be in a stack slot
        let state = r#gen.live_var_state.get("test").unwrap();
        let loc = state.get_live_location(1);
        assert!(loc.is_some());
        assert_eq!(loc.unwrap().kind, LocationKind::Direct);
    }

    #[test]
    fn test_generator_reload_register() {
        let mut r#gen = X86StackMapGenerator::new(true);
        r#gen.begin_function("test", 128);

        r#gen.record_register_location("test", 1, 0, 8, "i8*", true);
        r#gen.spill_register("test", 1, 8);
        r#gen.reload_register("test", 1, 0);

        let state = r#gen.live_var_state.get("test").unwrap();
        let loc = state.get_live_location(1);
        assert!(loc.is_some());
        assert_eq!(loc.unwrap().kind, LocationKind::Register);
    }

    #[test]
    fn test_generator_stack_size_change() {
        let mut r#gen = X86StackMapGenerator::new(true);
        r#gen.begin_function("test", 128);

        r#gen.record_stack_size_change("test", 256);

        // Verify the stack size was recorded
        let sm = r#gen.get_stack_maps();
        assert_eq!(sm.function_count(), 1);

        r#gen.end_function();
    }

    #[test]
    fn test_generator_add_constant() {
        let mut r#gen = X86StackMapGenerator::new(true);
        let idx = r#gen.add_constant(0xBEEF);
        assert_eq!(idx, 0);

        let sm = r#gen.get_stack_maps();
        assert_eq!(sm.format.get_constant(0), Some(0xBEEF));
    }

    #[test]
    fn test_generator_generate_section() {
        let mut r#gen = X86StackMapGenerator::new(true);
        r#gen.begin_function("test", 128);
        r#gen.record_register_location("test", 1, 0, 8, "i8*", true);
        r#gen.generate_stack_map_record("test", 1);
        r#gen.end_function();

        let section = r#gen.generate_section();
        assert!(!section.is_empty());

        // The section should be parseable
        let mut parser = X86StackMapParser::new(true);
        assert!(parser.parse(&section).is_ok());
        assert!(parser.lookup_by_id(1).is_some());
    }

    #[test]
    fn test_generator_generate_section_asm() {
        let mut r#gen = X86StackMapGenerator::new(true);
        r#gen.begin_function("test", 128);
        r#gen.end_function();

        let asm = r#gen.generate_section_asm();
        assert!(asm.contains(STACK_MAP_SECTION_NAME));
    }

    #[test]
    fn test_generator_finalize() {
        let mut r#gen = X86StackMapGenerator::new(true);
        r#gen.begin_function("test", 128);
        r#gen.record_register_location("test", 1, 0, 8, "i8*", true);
        r#gen.generate_stack_map_record("test", 1);
        r#gen.end_function();

        assert!(r#gen.finalize().is_ok());
    }

    #[test]
    fn test_generator_with_patchpoint() {
        let mut r#gen = X86StackMapGenerator::new(true);
        r#gen.begin_function("test", 128);

        let pp = X86PatchPoint::new_call(42, "alloc", 1);
        r#gen.generate_from_patchpoint("test", &pp);

        r#gen.end_function();

        let section = r#gen.generate_section();
        let mut parser = X86StackMapParser::new(true);
        parser.parse(&section).unwrap();
        assert!(parser.lookup_by_id(42).is_some());
    }

    #[test]
    fn test_generator_with_statepoint() {
        let mut r#gen = X86StackMapGenerator::new(true);
        r#gen.begin_function("test", 128);

        let mut sp = X86StatePoint::new(99, "alloc", 1);
        sp.add_gc_root(X86StatepointValue::reg(0, "i8*"));
        r#gen.generate_from_statepoint("test", &sp);

        r#gen.end_function();

        let section = r#gen.generate_section();
        let mut parser = X86StackMapParser::new(true);
        parser.parse(&section).unwrap();
        assert!(parser.lookup_by_id(99).is_some());
    }

    // -------------------------------------------------------------------------
    // X86StackMapParser tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_parser_creation() {
        let parser = X86StackMapParser::new(true);
        assert!(!parser.is_parsed());
    }

    #[test]
    fn test_parser_parse_empty_section() {
        let mut parser = X86StackMapParser::new(true);
        let fmt = X86StackMapFormat::new();
        let bytes = fmt.to_bytes();
        assert!(parser.parse(&bytes).is_ok());
        assert!(parser.is_parsed());
        assert_eq!(parser.record_count(), 0);
    }

    #[test]
    fn test_parser_parse_with_data() {
        let mut parser = X86StackMapParser::new(true);

        let mut fmt = X86StackMapFormat::new();
        let func = StackMapFunctionRecord::new(0x1000, 64, 0, 2);
        let rec1 = StackMapRecord::new(10, 0x10);
        let rec2 = StackMapRecord::new(20, 0x20);
        fmt.add_function(func, Vec::new(), vec![rec1, rec2]);

        let bytes = fmt.to_bytes();
        parser.parse(&bytes).unwrap();

        assert_eq!(parser.record_count(), 2);
        assert_eq!(parser.version(), STACK_MAP_VERSION);
    }

    #[test]
    fn test_parser_lookup_by_id() {
        let mut parser = X86StackMapParser::new(true);

        let mut fmt = X86StackMapFormat::new();
        let func = StackMapFunctionRecord::new(0x1000, 64, 0, 1);
        let rec = StackMapRecord::new(42, 0x10);
        fmt.add_function(func, Vec::new(), vec![rec]);

        parser.parse(&fmt.to_bytes()).unwrap();

        let found = parser.lookup_by_id(42);
        assert!(found.is_some());
        assert_eq!(found.unwrap().instruction_offset, 0x10);

        let not_found = parser.lookup_by_id(99);
        assert!(not_found.is_none());
    }

    #[test]
    fn test_parser_lookup_by_address() {
        let mut parser = X86StackMapParser::new(true);

        let mut fmt = X86StackMapFormat::new();
        let func = StackMapFunctionRecord::new(0x2000, 64, 0, 2);
        let rec1 = StackMapRecord::new(1, 0x10);
        let rec2 = StackMapRecord::new(2, 0x20);
        fmt.add_function(func, Vec::new(), vec![rec1, rec2]);

        parser.parse(&fmt.to_bytes()).unwrap();

        let records = parser.lookup_by_address(0x2000);
        assert_eq!(records.len(), 2);

        let no_records = parser.lookup_by_address(0x9999);
        assert_eq!(no_records.len(), 0);
    }

    #[test]
    fn test_parser_lookup_function() {
        let mut parser = X86StackMapParser::new(true);

        let mut fmt = X86StackMapFormat::new();
        let func = StackMapFunctionRecord::new(0x3000, 96, 0, 0);
        fmt.add_function(func.clone(), Vec::new(), Vec::new());

        parser.parse(&fmt.to_bytes()).unwrap();

        let found = parser.lookup_function(0x3000);
        assert!(found.is_some());
        assert_eq!(found.unwrap().stack_size, 96);
    }

    #[test]
    fn test_parser_extract_live_locations() {
        let mut parser = X86StackMapParser::new(true);

        let mut fmt = X86StackMapFormat::new();
        let func = StackMapFunctionRecord::new(0x1000, 64, 0, 1);
        let mut rec = StackMapRecord::new(1, 0x10);
        rec.add_location(LocationRecord::new_register(0, 8));
        rec.add_location(LocationRecord::new_direct(6, -16, 8));
        fmt.add_function(func, Vec::new(), vec![rec]);

        parser.parse(&fmt.to_bytes()).unwrap();

        let locs = parser.extract_live_locations(parser.lookup_by_id(1).unwrap());
        assert_eq!(locs.len(), 2);
        // First location should be RAX (Dwarf 0)
        assert_eq!(locs[0].0, "RAX");
        assert_eq!(locs[0].1, LocationKind::Register);
    }

    #[test]
    fn test_parser_extract_gc_roots() {
        let mut parser = X86StackMapParser::new(true);

        let mut fmt = X86StackMapFormat::new();
        let func = StackMapFunctionRecord::new(0x1000, 64, 0, 1);
        let mut rec = StackMapRecord::new(1, 0x10);
        rec.add_location(LocationRecord::new_register(0, 8)); // 8-byte, likely pointer
        rec.add_location(LocationRecord::new_constant(42)); // constant, not pointer
        fmt.add_function(func, Vec::new(), vec![rec]);

        parser.parse(&fmt.to_bytes()).unwrap();

        let roots = parser.extract_gc_roots(parser.lookup_by_id(1).unwrap(), 8);
        // Should include the register (8 bytes) but not the constant
        assert!(!roots.is_empty());
    }

    #[test]
    fn test_parser_extract_live_outs() {
        let mut parser = X86StackMapParser::new(true);

        let mut fmt = X86StackMapFormat::new();
        let func = StackMapFunctionRecord::new(0x1000, 64, 0, 1);
        let mut rec = StackMapRecord::new(1, 0x10);
        rec.add_live_out(LiveOutRecord::new(0, 8));
        rec.add_live_out(LiveOutRecord::new(2, 8));
        fmt.add_function(func, Vec::new(), vec![rec]);

        parser.parse(&fmt.to_bytes()).unwrap();

        let live_outs = parser.extract_live_outs(parser.lookup_by_id(1).unwrap());
        assert_eq!(live_outs.len(), 2);
        assert_eq!(live_outs[0].0, "RAX");
    }

    #[test]
    fn test_parser_duplicate_id_warning() {
        let mut parser = X86StackMapParser::new(true);

        let mut fmt = X86StackMapFormat::new();
        let func = StackMapFunctionRecord::new(0x1000, 64, 0, 2);
        let rec1 = StackMapRecord::new(1, 0x10);
        let rec2 = StackMapRecord::new(1, 0x20); // Duplicate ID
        fmt.add_function(func, Vec::new(), vec![rec1, rec2]);

        parser.parse(&fmt.to_bytes()).unwrap();
        // Should not error but should warn
        assert!(!parser.warnings.is_empty());
    }

    #[test]
    fn test_parser_get_all_ids() {
        let mut parser = X86StackMapParser::new(true);

        let mut fmt = X86StackMapFormat::new();
        let func = StackMapFunctionRecord::new(0x1000, 64, 0, 3);
        fmt.add_function(
            func,
            Vec::new(),
            vec![
                StackMapRecord::new(5, 0x10),
                StackMapRecord::new(3, 0x20),
                StackMapRecord::new(1, 0x30),
            ],
        );

        parser.parse(&fmt.to_bytes()).unwrap();

        let ids = parser.get_all_ids();
        assert_eq!(ids, vec![1, 3, 5]);
    }

    #[test]
    fn test_parser_dump_records() {
        let mut parser = X86StackMapParser::new(true);

        let mut fmt = X86StackMapFormat::new();
        let func = StackMapFunctionRecord::new(0x1000, 64, 0, 1);
        let mut rec = StackMapRecord::new(1, 0x10);
        rec.add_location(LocationRecord::new_register(0, 8));
        fmt.add_function(func, Vec::new(), vec![rec]);

        parser.parse(&fmt.to_bytes()).unwrap();

        let dump = parser.dump_records();
        assert!(dump.contains("Stack Map Section"));
        assert!(dump.contains("Record ID=1"));
        assert!(dump.contains("RAX"));
    }

    // -------------------------------------------------------------------------
    // X86DeoptState tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_frame_state_creation() {
        let fs = X86FrameState::new(0xABCD, 0x100);
        assert_eq!(fs.method_ref, 0xABCD);
        assert_eq!(fs.bytecode_offset, 0x100);
        assert_eq!(fs.num_locals, 0);
        assert_eq!(fs.num_stack_slots, 0);
    }

    #[test]
    fn test_frame_state_add_local() {
        let mut fs = X86FrameState::new(1, 0);
        let loc = LocationRecord::new_register(0, 8);
        fs.add_local(0, loc, "i8*", true);
        assert_eq!(fs.num_locals, 1);
        assert_eq!(fs.locals.len(), 1);
    }

    #[test]
    fn test_frame_state_add_stack_slot() {
        let mut fs = X86FrameState::new(1, 0);
        let loc = LocationRecord::new_direct(6, -8, 8);
        fs.add_stack_slot(0, loc, "i64", false);
        assert_eq!(fs.num_stack_slots, 1);
    }

    #[test]
    fn test_frame_state_add_monitor() {
        let mut fs = X86FrameState::new(1, 0);
        let loc = LocationRecord::new_register(0, 8);
        fs.add_monitor(0, loc, false);
        assert_eq!(fs.num_monitors, 1);
    }

    #[test]
    fn test_frame_state_get_live_refs() {
        let mut fs = X86FrameState::new(1, 0);
        fs.add_local(0, LocationRecord::new_register(0, 8), "i8*", true);
        fs.add_local(1, LocationRecord::new_register(1, 8), "i64", false);
        fs.add_stack_slot(0, LocationRecord::new_direct(6, -8, 8), "i8*", true);

        let refs = fs.get_live_refs();
        assert_eq!(refs.len(), 2);
    }

    #[test]
    fn test_frame_slot_mark_dead() {
        let mut slot = X86FrameSlot::new_local(0, LocationRecord::new_register(0, 8), "i8*", true);
        assert!(slot.is_live);
        slot.mark_dead();
        assert!(!slot.is_live);
    }

    #[test]
    fn test_register_state_creation() {
        let rs = X86RegisterState::new();
        assert_eq!(rs.num_gprs, 0);
        assert_eq!(rs.total_registers(), 0);
    }

    #[test]
    fn test_register_state_add_gpr() {
        let mut rs = X86RegisterState::new();
        rs.add_gpr(0, 0xDEADBEEF, true);
        assert_eq!(rs.num_gprs, 1);
        assert!(rs.is_gpr_reference(0));
        assert_eq!(rs.get_gpr(0), Some(0xDEADBEEF));
    }

    #[test]
    fn test_register_state_add_xmm() {
        let mut rs = X86RegisterState::new();
        rs.add_xmm(17, 0xCAFE);
        assert_eq!(rs.num_xmms, 1);
    }

    #[test]
    fn test_register_state_set_rflags_rip() {
        let mut rs = X86RegisterState::new();
        rs.set_rflags(0x246);
        rs.set_rip(0x4000);

        assert_eq!(rs.rflags, Some(0x246));
        assert_eq!(rs.rip, Some(0x4000));
    }

    #[test]
    fn test_continuation_point_interpreter() {
        let cp = X86ContinuationPoint::new_interpreter(0x100, 0xABCD, true);
        assert_eq!(cp.bytecode_offset, 0x100);
        assert_eq!(cp.method_ref, 0xABCD);
        assert_eq!(cp.dispatch_kind, X86DeoptDispatchKind::Interpreter);
        assert!(cp.is_reexecute);
    }

    #[test]
    fn test_continuation_point_exception_handler() {
        let cp = X86ContinuationPoint::new_exception_handler(0x50, 0xBEEF, 0x80);
        assert_eq!(cp.dispatch_kind, X86DeoptDispatchKind::ExceptionHandler);
        assert_eq!(cp.exception_handler_offset, Some(0x80));
    }

    #[test]
    fn test_deopt_state_creation() {
        let fs = X86FrameState::new(1, 0x10);
        let rs = X86RegisterState::new();
        let cp = X86ContinuationPoint::new_interpreter(0x10, 1, false);
        let reason = DeoptReason::TypeCheckFailed {
            expected: "String".to_string(),
            actual: "Integer".to_string(),
        };

        let ds = X86DeoptState::new(42, fs, rs, cp, reason);
        assert_eq!(ds.magic, DEOPT_BUNDLE_MAGIC);
        assert_eq!(ds.version, DEOPT_BUNDLE_VERSION);
        assert_eq!(ds.compilation_unit_id, 42);
        assert!(ds.metadata.is_empty());
    }

    #[test]
    fn test_deopt_reason_descriptions() {
        let reasons = vec![
            DeoptReason::TypeCheckFailed {
                expected: "A".to_string(),
                actual: "B".to_string(),
            },
            DeoptReason::BoundsCheckFailed {
                index: 10,
                length: 5,
            },
            DeoptReason::NullCheckFailed,
            DeoptReason::SpeculationFailed { guard_id: 42 },
            DeoptReason::CHAMiss,
            DeoptReason::InlineCacheMiss,
            DeoptReason::DebugDeopt,
        ];

        for reason in reasons {
            let desc = reason.description();
            assert!(!desc.is_empty());
        }
    }

    #[test]
    fn test_deopt_state_get_gc_references() {
        let mut fs = X86FrameState::new(1, 0);
        fs.add_local(0, LocationRecord::new_register(0, 8), "i8*", true);

        let mut rs = X86RegisterState::new();
        rs.add_gpr(0, 0x1234, true);
        rs.add_gpr(2, 0x5678, false); // not a reference

        let cp = X86ContinuationPoint::new_interpreter(0, 1, false);
        let reason = DeoptReason::DebugDeopt;

        let ds = X86DeoptState::new(1, fs, rs, cp, reason);

        let refs = ds.get_gc_references();
        assert!(!refs.is_empty());
        // Should include the local slot and the reference GPR
    }

    #[test]
    fn test_deopt_state_roundtrip() {
        let mut fs = X86FrameState::new(1, 0x10);
        fs.add_local(0, LocationRecord::new_register(0, 8), "i8*", true);
        fs.add_stack_slot(0, LocationRecord::new_direct(6, -8, 8), "i64", false);

        let mut rs = X86RegisterState::new();
        rs.add_gpr(0, 0xDEAD, true);
        rs.add_gpr(2, 0xBEEF, false);

        let cp = X86ContinuationPoint::new_interpreter(0x10, 1, false);
        let reason = DeoptReason::NullCheckFailed;

        let ds = X86DeoptState::new(42, fs, rs, cp, reason);
        let bytes = ds.to_bytes();

        let parsed = X86DeoptState::from_bytes(&bytes).unwrap();
        assert_eq!(parsed.magic, DEOPT_BUNDLE_MAGIC);
        assert_eq!(parsed.compilation_unit_id, 42);
        assert_eq!(parsed.frame_state.num_locals, 1);
        assert_eq!(parsed.register_state.num_gprs, 2);
        assert_eq!(parsed.continuation_point.bytecode_offset, 0x10);
    }

    #[test]
    fn test_deopt_state_metadata() {
        let mut ds = X86DeoptState::new(
            1,
            X86FrameState::new(1, 0),
            X86RegisterState::new(),
            X86ContinuationPoint::new_interpreter(0, 1, false),
            DeoptReason::DebugDeopt,
        );
        ds.set_metadata(b"test_meta");

        let bytes = ds.to_bytes();
        let parsed = X86DeoptState::from_bytes(&bytes).unwrap();
        assert_eq!(parsed.metadata, b"test_meta");
    }

    #[test]
    fn test_deopt_state_validate() {
        let ds = X86DeoptState::new(
            1,
            X86FrameState::new(1, 0),
            X86RegisterState::new(),
            X86ContinuationPoint::new_interpreter(0, 1, false),
            DeoptReason::DebugDeopt,
        );
        assert!(ds.validate().is_ok());
    }

    #[test]
    fn test_deopt_dispatch_kind_names() {
        assert_eq!(X86DeoptDispatchKind::Interpreter.name(), "interpreter");
        assert_eq!(X86DeoptDispatchKind::BaselineJIT.name(), "baseline-jit");
        assert_eq!(X86DeoptDispatchKind::OptimizingJIT.name(), "optimizing-jit");
        assert_eq!(
            X86DeoptDispatchKind::ExceptionHandler.name(),
            "exception-handler"
        );
        assert_eq!(X86DeoptDispatchKind::UnwindStub.name(), "unwind-stub");
    }

    // -------------------------------------------------------------------------
    // X86LiveVarState tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_live_var_state_creation() {
        let state = X86LiveVarState::new();
        assert_eq!(state.frame_size, 0);
        assert_eq!(state.var_locations.len(), 0);
    }

    #[test]
    fn test_live_var_state_allocate_stack_slots() {
        let mut state = X86LiveVarState::new();

        let slot1 = state.allocate_stack_slot(8);
        assert_eq!(slot1.offset, -8);
        assert_eq!(state.frame_size, 8);

        let slot2 = state.allocate_stack_slot(16);
        assert_eq!(slot2.offset, -24);
        assert_eq!(state.frame_size, 24);
    }

    #[test]
    fn test_live_var_state_gc_pointer_tracking() {
        let mut state = X86LiveVarState::new();
        state.mark_gc_pointer(1);
        state.mark_gc_pointer(2);

        assert!(state.is_gc_pointer(1));
        assert!(state.is_gc_pointer(2));
        assert!(!state.is_gc_pointer(3));

        let live = state.get_live_gc_pointers();
        // No locations recorded yet, so empty
        assert_eq!(live.len(), 0);

        // Record a location and check again
        state.record_location(1, LocationRecord::new_register(0, 8));
        let live = state.get_live_gc_pointers();
        assert_eq!(live.len(), 1);
    }

    // -------------------------------------------------------------------------
    // X86StackMapScenario tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_scenario_creation() {
        let scenario = X86StackMapScenario::new("test_func", 128, true);
        assert_eq!(scenario.function_name, "test_func");
    }

    #[test]
    fn test_scenario_add_patchpoint() {
        let mut scenario = X86StackMapScenario::new("test_func", 128, true);
        let pp = X86PatchPoint::new_call(1, "alloc", 1);
        scenario.add_patchpoint(pp);
        assert_eq!(scenario.patchpoints.len(), 1);
    }

    #[test]
    fn test_scenario_add_statepoint() {
        let mut scenario = X86StackMapScenario::new("test_func", 128, true);
        let sp = X86StatePoint::new(2, "alloc", 1);
        scenario.add_statepoint(sp);
        assert_eq!(scenario.statepoints.len(), 1);
    }

    #[test]
    fn test_scenario_add_entry_safepoint() {
        let mut scenario = X86StackMapScenario::new("test_func", 128, true);
        scenario.add_entry_safepoint();
        assert_eq!(scenario.safepoints.len(), 1);
        assert_eq!(scenario.safepoints[0].kind, SafepointKind::FunctionEntry);
    }

    #[test]
    fn test_scenario_add_backedge_safepoint() {
        let mut scenario = X86StackMapScenario::new("test_func", 128, true);
        scenario.add_backedge_safepoint(0x40);
        assert_eq!(scenario.safepoints.len(), 1);
        assert_eq!(scenario.safepoints[0].kind, SafepointKind::LoopBackedge);
    }

    #[test]
    fn test_scenario_record_stack_size() {
        let mut scenario = X86StackMapScenario::new("test_func", 128, true);
        scenario.record_stack_size(0x10, 256);
        assert_eq!(scenario.stack_sizes.len(), 1);
    }

    #[test]
    fn test_scenario_finalize() {
        let mut scenario = X86StackMapScenario::new("test_func", 128, true);
        scenario.add_entry_safepoint();

        // Record a live GC pointer
        scenario
            .generator_mut()
            .record_register_location("test_func", 1, 0, 8, "i8*", true);
        scenario
            .generator_mut()
            .generate_stack_map_record("test_func", 42);

        let result = scenario.finalize();
        assert!(result.is_ok());

        let section = result.unwrap();
        assert!(!section.is_empty());

        // Parse and verify
        let mut parser = X86StackMapParser::new(true);
        parser.parse(&section).unwrap();
        assert!(parser.is_parsed());
    }

    // -------------------------------------------------------------------------
    // X86StackMapWriter tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_writer_creation() {
        let writer = X86StackMapWriter::new();
        assert_eq!(writer.alignment, 8);
        assert!(writer.read_only);
    }

    #[test]
    fn test_writer_generate_elf_section_header() {
        let writer = X86StackMapWriter::new();
        let header = writer.generate_elf_section_header(0x1000, 128);
        assert_eq!(header.len(), 64);
    }

    // -------------------------------------------------------------------------
    // X86StackMapVerifier tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_verifier_empty() {
        let sm = X86StackMaps::new("x86_64-unknown-linux-gnu", true);
        let mut verifier = X86StackMapVerifier::new(sm);
        assert!(verifier.verify());
        assert!(verifier.errors.is_empty());
    }

    #[test]
    fn test_verifier_warns_empty_functions() {
        let mut sm = X86StackMaps::new("x86_64-unknown-linux-gnu", true);
        let idx = sm.register_function("empty_func", 64);
        sm.finalize();

        // Force add a function with 0 records
        let func = StackMapFunctionRecord::new(0x1000, 64, 0, 0);
        sm.format.functions.push(func);

        let mut verifier = X86StackMapVerifier::new(sm);
        assert!(verifier.verify()); // Warning, not error
        assert!(!verifier.warnings.is_empty());
    }

    #[test]
    fn test_verifier_duplicate_ids() {
        let mut sm = X86StackMaps::new("x86_64-unknown-linux-gnu", true);
        let idx = sm.register_function("test", 64);

        // Manually add duplicate-id records
        sm.functions_data[0]
            .records
            .push(StackMapRecord::new(1, 0x10));
        sm.functions_data[0]
            .records
            .push(StackMapRecord::new(1, 0x20));
        sm.finalize();

        let mut verifier = X86StackMapVerifier::new(sm);
        assert!(!verifier.verify());
        assert!(!verifier.errors.is_empty());
    }

    #[test]
    fn test_verifier_report() {
        let sm = X86StackMaps::new("x86_64-unknown-linux-gnu", true);
        let verifier = X86StackMapVerifier::new(sm);
        let report = verifier.report();
        assert!(report.contains("PASS"));
    }

    // -------------------------------------------------------------------------
    // X86FunctionStackMapData tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_function_data_creation() {
        let data = X86FunctionStackMapData::new("test", 128);
        assert_eq!(data.name, "test");
        assert_eq!(data.stack_size, 128);
        assert_eq!(data.records.len(), 0);
    }

    #[test]
    fn test_function_data_add_records() {
        let mut data = X86FunctionStackMapData::new("test", 128);

        data.add_stack_size(0, 128);
        data.add_stack_size(0x20, 256);
        assert_eq!(data.stack_sizes.len(), 2);

        data.add_record(StackMapRecord::new(1, 0x10));
        data.add_record(StackMapRecord::new(2, 0x20));
        assert_eq!(data.records.len(), 2);

        // Check offset_to_id mapping
        assert_eq!(data.offset_to_id.get(&0x10), Some(&1));
        assert_eq!(data.offset_to_id.get(&0x20), Some(&2));
    }

    // -------------------------------------------------------------------------
    // X86SafepointLocation tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_safepoint_location_creation() {
        let loc = X86SafepointLocation::new(SafepointKind::FunctionEntry, "test_func", 0x10, 42);
        assert_eq!(loc.kind, SafepointKind::FunctionEntry);
        assert_eq!(loc.function_name, "test_func");
        assert_eq!(loc.instruction_offset, 0x10);
        assert_eq!(loc.stack_map_id, 42);
        assert!(loc.machine_instr.is_none());
    }

    #[test]
    fn test_safepoint_location_set_machine_instr() {
        let mut loc = X86SafepointLocation::new(SafepointKind::AfterCall, "test_func", 0x20, 1);
        let instr = MachineInstr::new(0xE8);
        loc.set_machine_instr(instr.clone());
        assert!(loc.machine_instr.is_some());
    }

    // -------------------------------------------------------------------------
    // X86SafepointStats tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_safepoint_stats_update_total() {
        let mut stats = X86SafepointStats::default();
        assert_eq!(stats.total, 0);

        stats.entry_safepoints = 2;
        stats.backedge_safepoints = 3;
        stats.call_safepoints = 1;
        stats.update_total();

        assert_eq!(stats.total, 6);
    }

    // -------------------------------------------------------------------------
    // End-to-end tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_end_to_end_section_generation_and_parsing() {
        // Create a generator
        let mut r#gen = X86StackMapGenerator::new(true);

        // Function 1
        r#gen.begin_function("function1", 128);
        r#gen.record_register_location("function1", 1, 0, 8, "i8*", true);
        r#gen.record_register_location("function1", 2, 1, 8, "i64", false);
        r#gen.advance_offset(0x10);
        r#gen.generate_stack_map_record("function1", 1);

        r#gen.advance_offset(0x20);
        r#gen.record_stack_location("function1", 3, -16, 8, "i8*", true, true);
        r#gen.generate_stack_map_record("function1", 2);
        r#gen.end_function();

        // Function 2
        r#gen.begin_function("function2", 256);
        r#gen.record_register_location("function2", 1, 0, 8, "i8*", true);
        r#gen.advance_offset(0x10);
        r#gen.generate_stack_map_record("function2", 3);
        r#gen.end_function();

        // Add some constants
        r#gen.add_constant(0xDEAD);
        r#gen.add_constant(0xBEEF);

        // Finalize and generate section
        let section = r#gen.generate_section();

        // Parse the section
        let mut parser = X86StackMapParser::new(true);
        parser.parse(&section).unwrap();

        // Verify parsed data
        assert_eq!(parser.record_count(), 3);
        assert!(parser.lookup_by_id(1).is_some());
        assert!(parser.lookup_by_id(2).is_some());
        assert!(parser.lookup_by_id(3).is_some());
        assert!(parser.lookup_by_id(99).is_none());

        // Verify function lookup
        let all_ids = parser.get_all_ids();
        assert_eq!(all_ids, vec![1, 2, 3]);

        // Extract locations for record 1
        let record1 = parser.lookup_by_id(1).unwrap();
        let locs = parser.extract_live_locations(record1);
        assert!(!locs.is_empty());
    }

    #[test]
    fn test_end_to_end_patchpoint_workflow() {
        let mut r#gen = X86StackMapGenerator::new(true);
        r#gen.begin_function("patch_func", 128);

        // Create a patchpoint
        let pp = X86PatchPoint::new_call(100, "alloc", 2);
        let (sled, call) = pp.generate_machine_instrs();

        assert!(!sled.is_empty());
        assert!(call.is_some());

        // Associate with the generator
        r#gen.generate_from_patchpoint("patch_func", &pp);

        r#gen.end_function();

        // Generate and parse
        let section = r#gen.generate_section();
        let mut parser = X86StackMapParser::new(true);
        parser.parse(&section).unwrap();

        let found = parser.lookup_by_id(100);
        assert!(found.is_some());
    }

    #[test]
    fn test_end_to_end_statepoint_workflow() {
        let mut r#gen = X86StackMapGenerator::new(true);
        r#gen.begin_function("state_func", 128);

        // Create a statepoint
        let mut sp = X86StatePoint::new(200, "alloc", 1);
        let base_val = X86StatepointValue::reg(0, "i8*");
        let base_idx = sp.add_gc_root(base_val);
        sp.add_derived_pointer(X86StatepointValue::reg(1, "i8*"), base_idx, 16);

        r#gen.generate_from_statepoint("state_func", &sp);
        r#gen.end_function();

        // Generate and parse
        let section = r#gen.generate_section();
        let mut parser = X86StackMapParser::new(true);
        parser.parse(&section).unwrap();

        let found = parser.lookup_by_id(200);
        assert!(found.is_some());
    }

    #[test]
    fn test_end_to_end_safepoint_insertion() {
        let mut r#gen = X86StackMapGenerator::new(true);
        r#gen.begin_function("safe_func", 128);

        // Insert entry safepoint
        let id = r#gen.stack_maps.allocate_id();
        let (sp, _) = r#gen.safepoint.insert_entry_safepoint("safe_func", id);
        r#gen.generate_from_safepoint("safe_func", &sp);

        // Insert backedge safepoint
        r#gen.advance_offset(0x40);
        let id2 = r#gen.stack_maps.allocate_id();
        let (sp2, _) = r#gen
            .safepoint
            .insert_backedge_safepoint("safe_func", 0x40, id2);
        r#gen.generate_from_safepoint("safe_func", &sp2);

        r#gen.end_function();

        // Check stats
        assert_eq!(r#gen.safepoint.stats.entry_safepoints, 1);
        assert_eq!(r#gen.safepoint.stats.backedge_safepoints, 1);

        // Generate and verify
        let section = r#gen.generate_section();
        let mut parser = X86StackMapParser::new(true);
        parser.parse(&section).unwrap();
    }

    #[test]
    fn test_end_to_end_deoptimization_bundle() {
        // Build a deopt state
        let mut fs = X86FrameState::new(0xCAFE, 0x40);

        // Add locals
        fs.add_local(0, LocationRecord::new_register(0, 8), "i8*", true);
        fs.add_local(1, LocationRecord::new_register(1, 8), "i64", false);
        fs.add_local(2, LocationRecord::new_direct(6, -8, 8), "i8*", true);

        // Add expression stack slots
        fs.add_stack_slot(0, LocationRecord::new_register(2, 8), "i32", false);
        fs.add_stack_slot(1, LocationRecord::new_register(3, 8), "i8*", true);

        // Build register state
        let mut rs = X86RegisterState::new();
        rs.add_gpr(0, 0x1000, true); // RAX = object pointer
        rs.add_gpr(2, 0x2000, false); // RCX = integer
        rs.add_gpr(6, 0x3000, false); // RBP = frame pointer
        rs.add_xmm(17, 0xCAFE_BABE);

        // Build continuation point
        let cp = X86ContinuationPoint::new_interpreter(0x40, 0xCAFE, false);

        // Build deopt state
        let reason = DeoptReason::BoundsCheckFailed {
            index: 10,
            length: 5,
        };
        let ds = X86DeoptState::new(100, fs, rs, cp, reason);

        // Serialize
        let bytes = ds.to_bytes();
        assert!(!bytes.is_empty());

        // Deserialize
        let parsed = X86DeoptState::from_bytes(&bytes).unwrap();

        // Verify
        assert_eq!(parsed.magic, DEOPT_BUNDLE_MAGIC);
        assert_eq!(parsed.compilation_unit_id, 100);
        assert_eq!(parsed.frame_state.num_locals, 3);
        assert_eq!(parsed.frame_state.num_stack_slots, 2);
        assert_eq!(parsed.register_state.num_gprs, 3);
        assert_eq!(parsed.register_state.num_xmms, 1);
        assert_eq!(parsed.continuation_point.bytecode_offset, 0x40);

        // Check GC references
        let gc_refs = parsed.get_gc_references();
        assert!(!gc_refs.is_empty());

        // Validate
        assert!(parsed.validate().is_ok());
    }

    #[test]
    fn test_end_to_end_complete_scenario() {
        // Simulate a complete compilation scenario with multiple functions,
        // statepoints, patchpoints, safepoints, and deoptimization.

        let mut r#gen = X86StackMapGenerator::new(true);

        // --- Function 1: main ---
        r#gen.begin_function("main", 256);
        r#gen.record_register_location("main", 1, 0, 8, "i8*", true);
        r#gen.record_register_location("main", 2, 2, 8, "i64", false);

        // Entry safepoint
        let eid = r#gen.stack_maps.allocate_id();
        let (esp, _) = r#gen.safepoint.insert_entry_safepoint("main", eid);
        r#gen.generate_from_safepoint("main", &esp);

        // Statepoint at allocation
        r#gen.advance_offset(0x20);
        let mut sp = X86StatePoint::new(100, "gc_alloc", 2);
        sp.add_gc_root(X86StatepointValue::reg(0, "i8*"));
        r#gen.generate_from_statepoint("main", &sp);

        // Backedge safepoint
        r#gen.advance_offset(0x30);
        let bid = r#gen.stack_maps.allocate_id();
        let (bsp, _) = r#gen.safepoint.insert_backedge_safepoint("main", 0x50, bid);
        r#gen.generate_from_safepoint("main", &bsp);

        // Patchpoint for JIT
        r#gen.advance_offset(0x10);
        let pp = X86PatchPoint::new_call(200, "compile_stub", 1);
        r#gen.generate_from_patchpoint("main", &pp);

        r#gen.end_function();

        // --- Function 2: helper ---
        r#gen.begin_function("helper", 128);
        r#gen.record_register_location("helper", 1, 0, 8, "i8*", true);

        let eid2 = r#gen.stack_maps.allocate_id();
        let (esp2, _) = r#gen.safepoint.insert_entry_safepoint("helper", eid2);
        r#gen.generate_from_safepoint("helper", &esp2);

        r#gen.end_function();

        // --- Generate section ---
        let section = r#gen.generate_section();

        // --- Parse and verify ---
        let mut parser = X86StackMapParser::new(true);
        assert!(parser.parse(&section).is_ok());

        // Verify all records are present
        let all_ids = parser.get_all_ids();
        assert!(!all_ids.is_empty());

        // Dump for debugging
        let dump = parser.dump_records();
        assert!(dump.contains("main"));

        // Run verifier
        let mut verifier = X86StackMapVerifier::new(r#gen.stack_maps.clone());
        assert!(verifier.verify());
    }

    #[test]
    fn test_nop_sled_edge_cases() {
        // Test NOP sled generation for boundary sizes
        let edge_sizes = [
            1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 16, 17, 31, 32, 33, 63, 64, 65,
        ];

        for size in &edge_sizes {
            let pp = X86PatchPoint::new_region(0, *size);
            let sled = pp.generate_nop_sled();
            assert_eq!(
                sled.len(),
                *size,
                "NOP sled size mismatch for edge size {}",
                size
            );
        }
    }

    #[test]
    fn test_multiple_functions_stack_size_tracking() {
        let mut r#gen = X86StackMapGenerator::new(true);

        // Function with dynamic stack
        r#gen.begin_function("dynamic_stack", 128);
        r#gen.record_stack_size_change("dynamic_stack", 128);
        r#gen.advance_offset(0x10);
        r#gen.record_stack_size_change("dynamic_stack", 256);
        r#gen.advance_offset(0x20);
        r#gen.record_stack_size_change("dynamic_stack", 128);
        r#gen.end_function();

        let section = r#gen.generate_section();
        let mut parser = X86StackMapParser::new(true);
        assert!(parser.parse(&section).is_ok());
    }

    #[test]
    fn test_statepoint_all_arg_types() {
        let mut sp = X86StatePoint::new(1, "callee", 4);

        sp.add_call_arg(X86StatepointValue::reg(0, "i64"));
        sp.add_call_arg(X86StatepointValue::stack(-8, "double"));
        sp.add_call_arg(X86StatepointValue::constant(42, "i32"));
        sp.add_call_arg(X86StatepointValue::undef("float"));

        assert_eq!(sp.call_args.len(), 4);
        assert_eq!(sp.num_call_args, 4);
    }

    #[test]
    fn test_location_record_vector_splice() {
        let loc = LocationRecord::new_vector_splice(17, 0, 32);
        assert_eq!(loc.kind, LocationKind::VectorSplice);
        assert_eq!(loc.dwarf_reg_num, 17);
        assert_eq!(loc.size, 32);

        let bytes = loc.to_bytes();
        let mut cursor = Cursor::new(&bytes);
        let parsed = LocationRecord::from_reader(&mut cursor).unwrap();
        assert_eq!(parsed.kind, LocationKind::VectorSplice);
    }

    #[test]
    fn test_register_names_ymm_zmm() {
        let names = X86RegisterNames::new(true);
        assert_eq!(names.resolve(49), "YMM0");
        assert_eq!(names.resolve(81), "ZMM0");
        assert!(names.is_ymm(49));
        assert!(names.is_zmm(81));
    }

    // -------------------------------------------------------------------------
    // X86FrameMap tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_frame_map_creation() {
        let fm = X86FrameMap::new(256);
        assert_eq!(fm.frame_size, 256);
        assert_eq!(fm.total_slots(), 0);
        assert!(!fm.validated);
    }

    #[test]
    fn test_frame_map_add_local() {
        let mut fm = X86FrameMap::new(128);
        let idx = fm.add_local("i64", 8);
        assert_eq!(idx, 0);
        assert_eq!(fm.num_locals, 1);
        assert_eq!(fm.total_slots(), 1);
        assert_eq!(fm.slots[0].slot_kind, X86FrameSlotKind::Local);
    }

    #[test]
    fn test_frame_map_add_stack_slot() {
        let mut fm = X86FrameMap::new(128);
        let idx = fm.add_stack_slot("i32", 4);
        assert_eq!(idx, 0);
        assert_eq!(fm.num_stack_slots, 1);
        assert_eq!(fm.slots[0].slot_kind, X86FrameSlotKind::Stack);
    }

    #[test]
    fn test_frame_map_add_monitor() {
        let mut fm = X86FrameMap::new(128);
        let idx = fm.add_monitor();
        assert_eq!(idx, 0);
        assert_eq!(fm.num_monitors, 1);
        assert!(fm.slots[0].is_reference);
    }

    #[test]
    fn test_frame_map_register_mapping() {
        let mut fm = X86FrameMap::new(128);
        let idx = fm.add_local("i64", 8);
        fm.map_register_to_slot(DWARF_REG_RAX, idx);

        let slot = fm.slot_for_register(DWARF_REG_RAX);
        assert!(slot.is_some());
        assert!(slot.unwrap().location.is_register());
    }

    #[test]
    fn test_frame_map_stack_mapping() {
        let mut fm = X86FrameMap::new(128);
        let idx = fm.add_local("i64", 8);
        fm.map_stack_to_slot(-16, idx);

        let slot = fm.slot_for_stack_offset(-16);
        assert!(slot.is_some());
        assert!(slot.unwrap().location.is_stack());
    }

    #[test]
    fn test_frame_map_reference_slots() {
        let mut fm = X86FrameMap::new(128);
        let idx1 = fm.add_local("ptr", 8);
        fm.slots[idx1].mark_reference();
        let idx2 = fm.add_local("num", 4);
        fm.slots[idx2].mark_dead();

        let refs = fm.reference_slots();
        assert_eq!(refs.len(), 1);
    }

    #[test]
    fn test_frame_map_validate() {
        let mut fm = X86FrameMap::new(128);
        assert!(fm.validate());
        assert!(fm.validated);
    }

    #[test]
    fn test_frame_map_validate_with_bad_bundle() {
        let mut fm = X86FrameMap::new(256);
        let bundle = X86DeoptBundle {
            magic: 0xDEADBEEF, // invalid magic
            ..X86DeoptBundle::default()
        };
        fm.set_deopt_bundle(bundle);
        assert!(!fm.validate());
    }

    #[test]
    fn test_frame_map_encode() {
        let mut fm = X86FrameMap::new(128);
        fm.add_local("i64", 8);
        let idx = fm.add_stack_slot("i32", 4);
        fm.map_register_to_slot(DWARF_REG_RAX, idx);

        let encoded = fm.encode();
        assert!(encoded.len() > 16);
        // First 4 bytes = frame_size
        assert_eq!(
            u32::from_le_bytes([encoded[0], encoded[1], encoded[2], encoded[3]]),
            128
        );
    }

    #[test]
    fn test_frame_map_generate_save_area_cfi() {
        let fm = X86FrameMap::new(256);
        let cfi = fm.generate_save_area_cfi();
        // Empty save area produces empty CFI
        assert_eq!(cfi.len(), 0);
    }

    #[test]
    fn test_frame_slot_kind_names() {
        assert_eq!(X86FrameSlotKind::Local.name(), "Local");
        assert_eq!(X86FrameSlotKind::Stack.name(), "Stack");
        assert_eq!(X86FrameSlotKind::Monitor.name(), "Monitor");
        assert_eq!(X86FrameSlotKind::CalleeSaveSpill.name(), "CalleeSaveSpill");
        assert_eq!(X86FrameSlotKind::ReturnAddress.name(), "ReturnAddress");
        assert_eq!(
            X86FrameSlotKind::FramePointerSave.name(),
            "FramePointerSave"
        );
    }

    #[test]
    fn test_frame_value_location_properties() {
        let reg_loc = X86FrameValueLocation::Register { dwarf_reg: 0 };
        assert!(reg_loc.is_register());
        assert!(!reg_loc.is_stack());
        assert_eq!(reg_loc.dwarf_reg(), Some(0));

        let stack_loc = X86FrameValueLocation::Stack { offset: -8 };
        assert!(stack_loc.is_stack());
        assert!(!reg_loc.is_constant());
        assert_eq!(stack_loc.stack_offset(), Some(-8));

        let const_loc = X86FrameValueLocation::Constant { value: 42 };
        assert!(const_loc.is_constant());
    }

    #[test]
    fn test_frame_slot_set_debug_name() {
        let mut slot = X86FrameMapSlot::new_local(0, "i64", 8);
        assert!(slot.debug_name.is_none());
        slot.set_debug_name("myVar");
        assert_eq!(slot.debug_name, Some("myVar".to_string()));
    }

    #[test]
    fn test_register_save_area_creation() {
        let mut area = X86RASaveArea::new(-128);
        assert_eq!(area.base_offset, -128);
        area.save_gpr(3, -8);
        area.save_xmm(17, -24);
        assert_eq!(area.total_saved_regs(), 2);
        assert_eq!(area.gpr_offset(3), Some(-8));
    }

    #[test]
    fn test_register_save_area_rflags_mxcsr() {
        let mut area = X86RASaveArea::new(-256);
        area.save_rflags(-32);
        area.save_mxcsr(-40);
        assert!(area.saves_rflags);
        assert!(area.saves_mxcsr);
        assert_eq!(area.rflags_offset, Some(-32));
        assert_eq!(area.mxcsr_offset, Some(-40));
    }

    #[test]
    fn test_register_save_area_align_size() {
        let mut area = X86RASaveArea::new(-128);
        area.save_gpr(3, -8);
        area.align_size();
        assert_eq!(area.total_size % 16, 0);
    }

    #[test]
    fn test_deopt_bundle_creation() {
        let bundle = X86DeoptBundle::new(
            DeoptReason::TypeCheckFailed {
                expected: "int".to_string(),
                actual: "float".to_string(),
            },
            42,
        );
        assert_eq!(bundle.magic, DEOPT_BUNDLE_MAGIC);
        assert_eq!(bundle.version, DEOPT_BUNDLE_VERSION);
        assert_eq!(bundle.compilation_unit_id, 42);
        assert!(bundle.validate());
    }

    #[test]
    fn test_deopt_bundle_set_state() {
        let mut bundle = X86DeoptBundle::new(DeoptReason::NullCheckFailed, 1);
        bundle.set_frame_state(vec![1, 2, 3], 4, 5);
        bundle.set_register_state(vec![6, 7, 8]);
        bundle.set_continuation(vec![9, 10]);

        assert_eq!(bundle.num_register_values, 4);
        assert_eq!(bundle.num_stack_values, 5);
        assert!(bundle.total_size() > 16);
    }

    #[test]
    fn test_deopt_bundle_default() {
        let bundle = X86DeoptBundle::default();
        assert_eq!(bundle.magic, DEOPT_BUNDLE_MAGIC);
        assert!(bundle.validate());
    }

    #[test]
    fn test_frame_reconstructor_basic() {
        let mut fm = X86FrameMap::new(256);
        let idx = fm.add_local("ref", 8);
        fm.slots[idx].mark_reference();
        fm.slots[idx].set_location(X86FrameValueLocation::Register {
            dwarf_reg: DWARF_REG_RAX,
        });

        let mut recon = X86FrameReconstructor::new(fm);
        recon.set_register(DWARF_REG_RAX, 0x1234_5678);
        assert!(recon.reconstruct());
        assert_eq!(recon.get_slot_value(idx), Some(0x1234_5678));
    }

    #[test]
    fn test_frame_reconstructor_from_stack() {
        let mut fm = X86FrameMap::new(256);
        let idx = fm.add_local("val", 4);
        fm.slots[idx].set_location(X86FrameValueLocation::Stack { offset: -8 });

        let mut recon = X86FrameReconstructor::new(fm);
        let val_bytes = 42i64.to_le_bytes().to_vec();
        recon.set_stack_memory(-8, val_bytes);
        assert!(recon.reconstruct());
        assert_eq!(recon.get_slot_value(idx), Some(42));
    }

    #[test]
    fn test_frame_reconstructor_gc_references() {
        let mut fm = X86FrameMap::new(128);
        let idx1 = fm.add_local("obj1", 8);
        fm.slots[idx1].mark_reference();
        fm.slots[idx1].set_location(X86FrameValueLocation::Register {
            dwarf_reg: DWARF_REG_RAX,
        });
        let idx2 = fm.add_local("obj2", 8);
        fm.slots[idx2].mark_reference();
        fm.slots[idx2].set_location(X86FrameValueLocation::Register { dwarf_reg: 5 });

        let mut recon = X86FrameReconstructor::new(fm);
        recon.set_register(DWARF_REG_RAX, 0xAAAA);
        recon.set_register(5, 0xBBBB);
        assert!(recon.reconstruct());

        let refs = recon.get_gc_references();
        assert_eq!(refs.len(), 2);
        assert!(refs.contains(&0xAAAA));
        assert!(refs.contains(&0xBBBB));
    }

    // -------------------------------------------------------------------------
    // X86ExceptionHandlingMaps tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_eh_stack_map_creation() {
        let eh = X86EHStackMap::new("test_func");
        assert_eq!(eh.function_name, "test_func");
        assert!(!eh.has_eh);
        assert_eq!(eh.landing_pad_count(), 0);
    }

    #[test]
    fn test_eh_stack_map_add_landing_pad() {
        let mut eh = X86EHStackMap::new("func");
        let lp = X86LandingPadMap::new(0x100, 42);
        eh.add_landing_pad(0x100, lp);
        assert!(eh.has_eh);
        assert_eq!(eh.landing_pad_count(), 1);
        assert!(eh.landing_pad_at(0x100).is_some());
    }

    #[test]
    fn test_eh_stack_map_personality() {
        let mut eh = X86EHStackMap::new("func");
        let persona = X86PersonalityFuncMap::default();
        eh.set_personality(persona);
        assert!(eh.has_eh);
        assert!(eh.personality.is_some());
        assert!(eh.personality.unwrap().is_gcc_personality);
    }

    #[test]
    fn test_eh_stack_map_cleanup() {
        let mut eh = X86EHStackMap::new("func");
        let cleanup = X86CleanupMap::new(0x200, 99);
        eh.add_cleanup(0x200, cleanup);
        assert_eq!(eh.cleanup_count(), 1);
    }

    #[test]
    fn test_eh_stack_map_encode() {
        let mut eh = X86EHStackMap::new("func");
        let lp = X86LandingPadMap::new(0x100, 42);
        eh.add_landing_pad(0x100, lp);
        let encoded = eh.encode();
        assert!(encoded.len() > 0);
        // First byte: has_eh flag
        assert_eq!(encoded[0], 1);
    }

    #[test]
    fn test_landing_pad_add_catch() {
        let mut lp = X86LandingPadMap::new(0x100, 1);
        lp.add_catch(0x4000, "std::exception");
        assert_eq!(lp.clauses.len(), 1);
        assert!(lp.clauses[0].is_catch());
    }

    #[test]
    fn test_landing_pad_add_filter() {
        let mut lp = X86LandingPadMap::new(0x100, 1);
        lp.add_filter(vec![0x5000], vec!["MyException".to_string()]);
        assert_eq!(lp.clauses.len(), 1);
        assert!(lp.clauses[0].is_filter());
    }

    #[test]
    fn test_landing_pad_cleanup_clause() {
        let mut lp = X86LandingPadMap::new(0x100, 1);
        lp.add_cleanup_clause();
        assert!(lp.is_cleanup);
        assert!(lp.clauses[0].is_cleanup());
    }

    #[test]
    fn test_landing_pad_catch_all() {
        let mut lp = X86LandingPadMap::new(0x200, 2);
        assert!(!lp.is_catch_all);
        lp.set_catch_all();
        assert!(lp.is_catch_all);
    }

    #[test]
    fn test_landing_pad_register_config() {
        let mut lp = X86LandingPadMap::new(0x300, 3);
        lp.set_exception_pointer_reg(DWARF_REG_RAX);
        lp.set_selector_reg(1);
        lp.set_exception_object_spill(-16);
        assert_eq!(lp.exception_pointer_reg, Some(DWARF_REG_RAX));
        assert_eq!(lp.selector_reg, Some(1));
        assert_eq!(lp.exception_object_spill, Some(-16));
    }

    #[test]
    fn test_cleanup_map_creation() {
        let mut cm = X86CleanupMap::new(0x100, 5);
        assert_eq!(cm.stack_map_id, 5);
        assert!(!cm.destroys_locals);
    }

    #[test]
    fn test_cleanup_map_destructors() {
        let mut cm = X86CleanupMap::new(0x100, 5);
        cm.add_destructor_call(-24, "MyClass");
        assert!(cm.calls_destructors);
        assert_eq!(cm.destructor_calls.len(), 1);
    }

    #[test]
    fn test_cleanup_map_mark_run_on_normal_exit() {
        let mut cm = X86CleanupMap::new(0x200, 6);
        assert!(!cm.run_on_normal_exit);
        cm.mark_run_on_normal_exit();
        assert!(cm.run_on_normal_exit);
    }

    #[test]
    fn test_eh_map_generator_creation() {
        let r#gen = X86EHMapGenerator::new(true);
        assert!(r#gen.enabled);
        assert_eq!(r#gen.function_count(), 0);
    }

    #[test]
    fn test_eh_map_generator_get_or_create() {
        let mut r#gen = X86EHMapGenerator::new(true);
        {
            let eh = r#gen.get_or_create("func1");
            eh.add_landing_pad(0x100, X86LandingPadMap::new(0x100, 1));
        }
        assert_eq!(r#gen.function_count(), 1);
        // Second call returns existing map
        let eh2 = r#gen.get_or_create("func1");
        assert_eq!(eh2.landing_pad_count(), 1);
    }

    #[test]
    fn test_eh_map_generator_emit_section() {
        let mut r#gen = X86EHMapGenerator::new(true);
        r#gen.get_or_create("func")
            .add_landing_pad(0x100, X86LandingPadMap::new(0x100, 1));
        let section = r#gen.emit_section();
        assert!(section.len() > 0);
    }

    #[test]
    fn test_eh_map_generator_emit_assembly() {
        let mut r#gen = X86EHMapGenerator::new(true);
        r#gen.get_or_create("func")
            .add_landing_pad(0x100, X86LandingPadMap::new(0x100, 1));
        let asm = r#gen.emit_assembly();
        assert!(asm.contains(".eh_frame_stackmaps"));
        assert!(asm.contains("func"));
    }

    #[test]
    fn test_eh_map_complex_scenario() {
        let mut eh = X86EHStackMap::new("complexFunc");

        let mut lp = X86LandingPadMap::new(0x100, 1);
        lp.add_catch(0x4000, "TypeA");
        lp.set_exception_pointer_reg(DWARF_REG_RAX);
        eh.add_landing_pad(0x100, lp);

        let persona = X86PersonalityFuncMap {
            personality_func: "__gxx_personality_v0".to_string(),
            is_gcc_personality: true,
            is_seh_personality: false,
            language: Some("C++".to_string()),
            got_offset: Some(0x1000),
        };
        eh.set_personality(persona);

        let mut cleanup = X86CleanupMap::new(0x300, 3);
        cleanup.mark_destroys_locals();
        cleanup.mark_releases_monitors();
        cleanup.add_destructor_call(-32, "LockGuard");
        eh.add_cleanup(0x300, cleanup);

        assert_eq!(eh.landing_pad_count(), 1);
        assert_eq!(eh.cleanup_count(), 1);
        assert!(eh.has_eh);
    }

    // -------------------------------------------------------------------------
    // X86DebugInfoStackMaps tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_debug_var_location_register() {
        let loc = X86DebugVarLocation::new_register("x", DWARF_REG_RAX, "i32", 42, 0x100);
        assert_eq!(loc.var_name, "x");
        assert!(loc.is_live);
        assert_eq!(loc.stack_map_id, 42);
        assert!(!loc.is_entry_value);
    }

    #[test]
    fn test_debug_var_location_stack() {
        let loc = X86DebugVarLocation::new_stack("y", -16, 8, "i64", 99, 0x200);
        assert_eq!(loc.var_name, "y");
        assert!(loc.is_live);
        assert_eq!(loc.instruction_offset, 0x200);
    }

    #[test]
    fn test_debug_var_location_mark_unavailable() {
        let mut loc = X86DebugVarLocation::new_register("z", DWARF_REG_RAX, "i64", 1, 0);
        loc.mark_unavailable();
        assert!(!loc.is_live);
    }

    #[test]
    fn test_debug_var_location_entry_value() {
        let mut loc = X86DebugVarLocation::new_register("param", DWARF_REG_RAX, "i64", 1, 0);
        assert!(!loc.is_entry_value);
        loc.mark_entry_value();
        assert!(loc.is_entry_value);
    }

    #[test]
    fn test_debug_var_location_fragment() {
        let mut loc = X86DebugVarLocation::new_register("big", DWARF_REG_RAX, "[4 x i32]", 1, 0);
        loc.set_fragment(0, 4, 16);
        assert!(loc.fragment.is_some());
        let frag = loc.fragment.unwrap();
        assert_eq!(frag.offset, 0);
        assert_eq!(frag.size, 4);
        assert_eq!(frag.total_size, 16);
    }

    #[test]
    fn test_dwarf_expr_register_0_31() {
        let r#gen = X86DwarfExprGenerator::new(false);
        let expr = r#gen.generate_register_expr(0, 0);
        // DW_OP_reg0 = 0x50
        assert_eq!(expr[0], 0x50);
    }

    #[test]
    fn test_dwarf_expr_register_above_31() {
        let r#gen = X86DwarfExprGenerator::new(false);
        let expr = r#gen.generate_register_expr(49, 0);
        // DW_OP_regx = 0x90
        assert_eq!(expr[0], 0x90);
    }

    #[test]
    fn test_dwarf_expr_register_with_offset() {
        let r#gen = X86DwarfExprGenerator::new(false);
        let expr = r#gen.generate_register_expr(DWARF_REG_RAX, 8);
        assert!(expr.len() > 2);
    }

    #[test]
    fn test_dwarf_expr_stack() {
        let r#gen = X86DwarfExprGenerator::new(false);
        let expr = r#gen.generate_stack_expr(-16, 8);
        // DW_OP_fbreg = 0x91
        assert_eq!(expr[0], 0x91);
    }

    #[test]
    fn test_dwarf_expr_constant() {
        let r#gen = X86DwarfExprGenerator::new(false);
        let expr0 = r#gen.generate_constant_expr(0);
        assert_eq!(expr0[0], 0x30); // DW_OP_lit0

        let expr42 = r#gen.generate_constant_expr(42);
        assert!(expr42.len() >= 1);
    }

    #[test]
    fn test_dwarf_expr_memory() {
        let r#gen = X86DwarfExprGenerator::new(false);
        let expr = r#gen.generate_memory_expr(0x600000);
        assert_eq!(expr[0], 0x03); // DW_OP_addr
    }

    #[test]
    fn test_dwarf_expr_composite() {
        let r#gen = X86DwarfExprGenerator::new(false);
        let pieces = vec![
            X86DebugPiece::new(
                0,
                4,
                X86DebugLocation::Register {
                    dwarf_reg: DWARF_REG_RAX,
                    offset: 0,
                },
            ),
            X86DebugPiece::new(
                4,
                4,
                X86DebugLocation::Stack {
                    frame_offset: -16,
                    size: 4,
                },
            ),
        ];
        let expr = r#gen.generate_composite_expr(&pieces);
        assert!(expr.len() > 4);
    }

    #[test]
    fn test_dwarf_expr_generate_from_location() {
        let r#gen = X86DwarfExprGenerator::new(false);
        let loc = X86DebugLocation::Register {
            dwarf_reg: DWARF_REG_RAX,
            offset: 0,
        };
        let expr = r#gen.generate_expr(&loc);
        assert_eq!(expr[0], 0x50); // DW_OP_reg0
    }

    #[test]
    fn test_dwarf_expr_loclist_entry() {
        let r#gen = X86DwarfExprGenerator::new(false);
        let loc = X86DebugLocation::Register {
            dwarf_reg: DWARF_REG_RAX,
            offset: 0,
        };
        let entry = r#gen.generate_loclist_entry(0x100, 0x200, &loc);
        assert!(entry.len() > 8);
    }

    #[test]
    fn test_dwarf_expr_generator_frame_base() {
        let mut r#gen = X86DwarfExprGenerator::new(false);
        assert_eq!(r#gen.frame_base_reg, DWARF_REG_RBP);
        r#gen.set_frame_base(DWARF_REG_RSP, 8);
        assert_eq!(r#gen.frame_base_reg, DWARF_REG_RSP);
        assert_eq!(r#gen.frame_base_offset, 8);
    }

    #[test]
    fn test_debug_value_record_creation() {
        let loc = X86DebugVarLocation::new_register("v", DWARF_REG_RAX, "i64", 1, 0x100);
        let mut rec = X86DebugValueRecord::new(loc);
        assert!(!rec.expression_valid);

        let r#gen = X86DwarfExprGenerator::new(false);
        rec.generate_expression(&r#gen);
        assert!(rec.expression_valid);
        assert!(rec.dwarf_expression.len() > 0);
    }

    #[test]
    fn test_debug_value_record_di_expression() {
        let loc = X86DebugVarLocation::new_register("v", DWARF_REG_RAX, "i64", 1, 0);
        let mut rec = X86DebugValueRecord::new(loc);
        rec.set_di_expression(vec![0x12, 0x34]);
        assert_eq!(rec.di_expression, vec![0x12, 0x34]);
    }

    #[test]
    fn test_debug_info_map_creation() {
        let map = X86DebugInfoMap::new("func");
        assert_eq!(map.function_name, "func");
        assert!(!map.has_debug_info);
        assert_eq!(map.record_count(), 0);
    }

    #[test]
    fn test_debug_info_map_record_value() {
        let mut map = X86DebugInfoMap::new("func");
        let loc = X86DebugVarLocation::new_register("a", DWARF_REG_RAX, "i64", 1, 0x100);
        let rec = X86DebugValueRecord::new(loc);
        map.record_debug_value(rec);

        assert!(map.has_debug_info);
        assert_eq!(map.record_count(), 1);
        assert!(map.locations_at_id(1).is_some());
        assert!(map.locations_at_offset(0x100).is_some());
    }

    #[test]
    fn test_debug_info_map_all_variable_names() {
        let mut map = X86DebugInfoMap::new("func");
        map.record_debug_value(X86DebugValueRecord::new(X86DebugVarLocation::new_register(
            "x",
            DWARF_REG_RAX,
            "i64",
            1,
            0,
        )));
        map.record_debug_value(X86DebugValueRecord::new(X86DebugVarLocation::new_register(
            "y", 5, "i32", 2, 4,
        )));

        let names = map.all_variable_names();
        assert_eq!(names.len(), 2);
        assert!(names.contains("x"));
        assert!(names.contains("y"));
    }

    #[test]
    fn test_debug_info_map_emit_debug_loc() {
        let mut map = X86DebugInfoMap::new("func");
        let loc = X86DebugVarLocation::new_register("x", DWARF_REG_RAX, "i64", 1, 0x100);
        let mut rec = X86DebugValueRecord::new(loc);
        let r#gen = X86DwarfExprGenerator::new(false);
        rec.generate_expression(&r#gen);
        map.record_debug_value(rec);

        let section = map.emit_debug_loc_section(&r#gen);
        assert!(section.len() > 0);
        // Should end with end-of-list marker (16 zero bytes)
        assert!(section.ends_with(&[0u8; 16]));
    }

    #[test]
    fn test_debug_loc_tracker_lifecycle() {
        let mut tracker = X86DebugLocTracker::new();
        assert!(!tracker.active);

        tracker.begin();
        assert!(tracker.active);

        tracker.end();
        assert!(!tracker.active);
    }

    #[test]
    fn test_debug_loc_tracker_set_and_get() {
        let mut tracker = X86DebugLocTracker::new();
        tracker.begin();

        tracker.set_location(
            "myVar",
            X86DebugLocation::Register {
                dwarf_reg: DWARF_REG_RAX,
                offset: 0,
            },
            "i64",
        );

        let loc = tracker.get_location("myVar");
        assert!(loc.is_some());
        assert!(matches!(
            loc.unwrap(),
            X86DebugLocation::Register { dwarf_reg: 0, .. }
        ));
        assert_eq!(tracker.get_type("myVar"), Some(&"i64".to_string()));
    }

    #[test]
    fn test_debug_loc_tracker_capture_locations() {
        let mut tracker = X86DebugLocTracker::new();
        tracker.begin();
        tracker.advance_to(0x100);

        tracker.set_location(
            "a",
            X86DebugLocation::Register {
                dwarf_reg: DWARF_REG_RAX,
                offset: 0,
            },
            "i64",
        );
        tracker.set_location(
            "b",
            X86DebugLocation::Stack {
                frame_offset: -8,
                size: 4,
            },
            "i32",
        );

        let captured = tracker.capture_locations(42);
        assert_eq!(captured.len(), 2);
        for var in &captured {
            assert_eq!(var.stack_map_id, 42);
            assert_eq!(var.instruction_offset, 0x100);
        }
    }

    #[test]
    fn test_debug_loc_tracker_inactive_ignores_ops() {
        let mut tracker = X86DebugLocTracker::new();
        tracker.set_location(
            "x",
            X86DebugLocation::Register {
                dwarf_reg: DWARF_REG_RAX,
                offset: 0,
            },
            "i64",
        );
        assert!(tracker.get_location("x").is_none());
    }

    #[test]
    fn test_debug_loc_tracker_history() {
        let mut tracker = X86DebugLocTracker::new();
        tracker.begin();
        tracker.set_location(
            "v",
            X86DebugLocation::Register {
                dwarf_reg: DWARF_REG_RAX,
                offset: 0,
            },
            "i64",
        );
        tracker.advance_to(0x10);
        tracker.set_location(
            "v",
            X86DebugLocation::Stack {
                frame_offset: -16,
                size: 8,
            },
            "i64",
        );

        assert_eq!(tracker.location_history.len(), 2);
        assert_eq!(tracker.location_history[0].0, 0);
        assert_eq!(tracker.location_history[1].0, 0x10);
    }

    // -------------------------------------------------------------------------
    // X86Safepoints tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_safepoint_action_names() {
        assert_eq!(X86SafepointAction::PollOnly.name(), "PollOnly");
        assert_eq!(
            X86SafepointAction::GCCollect {
                generation: 0,
                is_full_gc: true
            }
            .name(),
            "GCCollect"
        );
        assert_eq!(X86SafepointAction::Suspend.name(), "Suspend");
    }

    #[test]
    fn test_safepoint_action_requires_gc_pause() {
        assert!(!X86SafepointAction::PollOnly.requires_gc_pause());
        assert!(X86SafepointAction::GCCollect {
            generation: 0,
            is_full_gc: false
        }
        .requires_gc_pause());
        assert!(!X86SafepointAction::Suspend.requires_gc_pause());
    }

    #[test]
    fn test_safepoint_action_requires_deopt() {
        assert!(!X86SafepointAction::PollOnly.requires_deopt());
        assert!(X86SafepointAction::Deoptimize {
            reason: DeoptReason::NullCheckFailed,
            target_bytecode_offset: 0,
        }
        .requires_deopt());
    }

    #[test]
    fn test_safepoint_action_requires_suspension() {
        assert!(!X86SafepointAction::PollOnly.requires_suspension());
        assert!(X86SafepointAction::Suspend.requires_suspension());
        assert!(X86SafepointAction::GCCollect {
            generation: 0,
            is_full_gc: true
        }
        .requires_suspension());
    }

    #[test]
    fn test_safepoint_guard_page_creation() {
        let page = X86SafepointGuardPage::new(0x7FFF_FFFF_0000, 4096);
        assert_eq!(page.page_address, 0x7FFF_FFFF_0000);
        assert!(!page.is_armed);
    }

    #[test]
    fn test_safepoint_guard_page_arm_disarm() {
        let mut page = X86SafepointGuardPage::new(0x1000, 4096);
        assert!(!page.is_armed);
        page.arm();
        assert!(page.is_armed);
        page.disarm();
        assert!(!page.is_armed);
    }

    #[test]
    fn test_safepoint_guard_page_poll_bytes() {
        let page = X86SafepointGuardPage::new(0x7FFF_FFFF_0000, 4096);
        let bytes = page.generate_poll_instruction_bytes();
        assert_eq!(bytes.len(), 14);
        // REX.W + MOVABS opcode: 49 BB
        assert_eq!(bytes[0], 0x49);
        assert_eq!(bytes[1], 0xBB);
    }

    #[test]
    fn test_safepoint_guard_page_rip_relative_poll() {
        let page = X86SafepointGuardPage::new(0x1000, 4096);
        let bytes = page.generate_rip_relative_poll(0x100);
        assert_eq!(bytes.len(), 7);
    }

    #[test]
    fn test_cooperative_handshake_creation() {
        let hs = X86CooperativeGCHandshake::new(true);
        assert_eq!(hs.current_state(), X86HandshakeState::Running);
        assert!(hs.supports_parking);
        assert!(!hs.needs_yield());
    }

    #[test]
    fn test_cooperative_handshake_full_flow() {
        let mut hs = X86CooperativeGCHandshake::new(false);

        assert_eq!(hs.current_state(), X86HandshakeState::Running);
        hs.request_gc();
        assert!(hs.needs_yield());
        assert_eq!(hs.current_state(), X86HandshakeState::GCRequested);

        hs.reach_safepoint();
        assert_eq!(hs.current_state(), X86HandshakeState::AtSafepoint);

        hs.yield_to_gc();
        assert!(hs.is_yielded());
        assert_eq!(hs.yield_count, 1);

        hs.resume();
        assert_eq!(hs.current_state(), X86HandshakeState::Resume);

        hs.resume_execution();
        assert_eq!(hs.current_state(), X86HandshakeState::Running);
        assert!(!hs.needs_yield());
    }

    #[test]
    fn test_handshake_state_names() {
        assert_eq!(X86HandshakeState::Running.name(), "Running");
        assert_eq!(X86HandshakeState::GCRequested.name(), "GCRequested");
        assert_eq!(X86HandshakeState::AtSafepoint.name(), "AtSafepoint");
        assert_eq!(X86HandshakeState::Yielded.name(), "Yielded");
        assert_eq!(X86HandshakeState::Resume.name(), "Resume");
        assert_eq!(X86HandshakeState::Resuming.name(), "Resuming");
    }

    #[test]
    fn test_x86_safepoints_creation() {
        let sp = X86Safepoints::new();
        assert_eq!(sp.total_hits(), 0);
        assert_eq!(sp.pending_action_count(), 0);
        assert!(!sp.global_gc_in_progress);
    }

    #[test]
    fn test_x86_safepoints_actions() {
        let mut sp = X86Safepoints::new();
        sp.set_action(1, X86SafepointAction::PollOnly);
        sp.set_action(2, X86SafepointAction::Suspend);

        assert_eq!(sp.pending_action_count(), 2);
        assert!(sp.get_action(1).is_some());
        assert!(sp.get_action(999).is_none());

        let taken = sp.take_action(1);
        assert_eq!(taken, Some(X86SafepointAction::PollOnly));
        assert_eq!(sp.pending_action_count(), 1);
    }

    #[test]
    fn test_x86_safepoints_thread_tracking() {
        let mut sp = X86Safepoints::new();

        sp.thread_at_safepoint(100);
        sp.thread_at_safepoint(200);
        sp.thread_at_safepoint(300);
        assert_eq!(sp.threads_at_safepoint_count(), 3);
        assert_eq!(sp.total_hits(), 3);

        sp.thread_left_safepoint(100);
        assert_eq!(sp.threads_at_safepoint_count(), 2);
        assert!(sp.all_threads_at_safepoint(2));
        assert!(!sp.all_threads_at_safepoint(3));
    }

    #[test]
    fn test_x86_safepoints_gc_cycle() {
        let mut sp = X86Safepoints::new();
        assert!(!sp.global_gc_in_progress);

        sp.begin_global_gc(2);
        assert!(sp.global_gc_in_progress);
        assert_eq!(sp.current_gc_generation, 2);
        assert!(sp.guard_page.is_armed);

        sp.end_global_gc();
        assert!(!sp.global_gc_in_progress);
        assert!(!sp.guard_page.is_armed);
    }

    #[test]
    fn test_x86_safepoints_poll_fault_check() {
        let mut sp = X86Safepoints::new();
        sp.configure_guard_page(0x7FFF_FFFF_0000, 4096);

        assert!(sp.is_poll_fault(0x7FFF_FFFF_0000));
        assert!(sp.is_poll_fault(0x7FFF_FFFF_0100));
        assert!(!sp.is_poll_fault(0x1000));
        assert!(!sp.is_poll_fault(0x7FFF_FFFF_1000));
    }

    #[test]
    fn test_x86_safepoints_signal_handler_stub() {
        let sp = X86Safepoints::new();
        let asm = sp.generate_signal_handler_stub();
        assert!(asm.contains("safepoint_signal_handler:"));
        assert!(asm.contains("safepoint_is_poll_fault"));
        assert!(asm.contains("safepoint_execute_action"));
    }

    #[test]
    fn test_x86_safepoints_clear_actions() {
        let mut sp = X86Safepoints::new();
        sp.set_action(1, X86SafepointAction::PollOnly);
        sp.set_action(2, X86SafepointAction::Suspend);
        sp.clear_actions();
        assert_eq!(sp.pending_action_count(), 0);
    }

    #[test]
    fn test_x86_safepoints_reset_stats() {
        let mut sp = X86Safepoints::new();
        sp.thread_at_safepoint(1);
        sp.thread_at_safepoint(2);
        assert_eq!(sp.total_hits(), 2);
        sp.reset_stats();
        assert_eq!(sp.total_hits(), 0);
    }

    #[test]
    fn test_x86_safepoints_cooperative_suspension() {
        let mut sp = X86Safepoints::new();
        assert!(!sp.cooperative_suspension_enabled);
        sp.enable_cooperative_suspension();
        assert!(sp.cooperative_suspension_enabled);
        assert!(sp.gc_safepoint.enabled);
    }

    #[test]
    fn test_x86_safepoints_thread_suspension() {
        let mut sp = X86Safepoints::new();
        assert!(!sp.thread_suspension_enabled);
        sp.enable_thread_suspension();
        assert!(sp.thread_suspension_enabled);
    }

    // -------------------------------------------------------------------------
    // End-to-end integration tests for new structures
    // -------------------------------------------------------------------------

    #[test]
    fn test_end_to_end_frame_map_deopt_workflow() {
        // Create a frame map with locals and a deopt bundle
        let mut fm = X86FrameMap::new(512);
        let local_idx = fm.add_local("myObj", 8);
        fm.slots[local_idx].mark_reference();
        fm.slots[local_idx].set_location(X86FrameValueLocation::Register {
            dwarf_reg: DWARF_REG_RAX,
        });
        fm.map_register_to_slot(DWARF_REG_RAX, local_idx);

        let bundle = X86DeoptBundle::new(
            DeoptReason::ExplicitDeopt {
                reason: "test".to_string(),
            },
            1,
        );
        fm.set_deopt_bundle(bundle);
        assert!(fm.validate());

        // Reconstruct
        let mut recon = X86FrameReconstructor::new(fm);
        recon.set_register(DWARF_REG_RAX, 0xDEAD_BEEF);
        assert!(recon.reconstruct());

        let refs = recon.get_gc_references();
        assert_eq!(refs, vec![0xDEAD_BEEF]);
    }

    #[test]
    fn test_end_to_end_eh_debug_integration() {
        // Build EH map and debug info map for the same function
        let mut eh_map = X86EHStackMap::new("demo");
        let lp = X86LandingPadMap::new(0x100, 42);
        eh_map.add_landing_pad(0x100, lp);

        let mut dbg_map = X86DebugInfoMap::new("demo");
        let var_loc =
            X86DebugVarLocation::new_register("error_obj", DWARF_REG_RAX, "Exception*", 42, 0x100);
        dbg_map.record_debug_value(X86DebugValueRecord::new(var_loc));

        assert!(eh_map.has_eh);
        assert!(dbg_map.has_debug_info);
        // Both map to the same instruction offset
        assert!(dbg_map.locations_at_offset(0x100).is_some());
        assert!(eh_map.landing_pad_at(0x100).is_some());
    }

    #[test]
    fn test_end_to_end_safepoints_with_frame_map() {
        let mut safepoints = X86Safepoints::new();
        safepoints.enable_cooperative_suspension();
        safepoints.configure_guard_page(0x7FFF_FFFF_0000, 4096);

        // Simulate GC cycle
        safepoints.begin_global_gc(1);
        assert!(safepoints.global_gc_in_progress);

        // Thread hits a safepoint
        safepoints.thread_at_safepoint(1);
        assert_eq!(safepoints.total_hits(), 1);

        // GC completes
        safepoints.end_global_gc();
        assert!(!safepoints.global_gc_in_progress);
    }

    #[test]
    fn test_end_to_end_all_four_systems() {
        // Frame Map
        let mut fm = X86FrameMap::new(256);
        fm.add_local("obj", 8);
        fm.slots[0].mark_reference();
        fm.slots[0].set_location(X86FrameValueLocation::Register {
            dwarf_reg: DWARF_REG_RAX,
        });

        // EH Maps
        let mut eh = X86EHStackMap::new("test");
        eh.add_landing_pad(0x100, X86LandingPadMap::new(0x100, 1));

        // Debug Info
        let mut dbg = X86DebugInfoMap::new("test");
        dbg.record_debug_value(X86DebugValueRecord::new(X86DebugVarLocation::new_register(
            "obj",
            DWARF_REG_RAX,
            "Object*",
            1,
            0x100,
        )));

        // Safepoints
        let mut sp = X86Safepoints::new();
        sp.set_action(
            1,
            X86SafepointAction::GCCollect {
                generation: 0,
                is_full_gc: true,
            },
        );

        // All systems active and consistent
        assert!(fm.validate());
        assert!(eh.has_eh);
        assert!(dbg.has_debug_info);
        assert_eq!(sp.pending_action_count(), 1);
    }
}