llvm-native-core 0.1.6

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
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
//! X86 Sanitizer CodeGen — Instrumentation insertion for AddressSanitizer
//! (redzone, shadow check, stack poisoning), MemorySanitizer (shadow
//! propagation, origin tracking), ThreadSanitizer (happens-before,
//! lock/unlock), UBSan (overflow, shift, divzero checks), LeakSanitizer
//! (allocation tracking), SafeStack (dual stack), CFI (type checks), and
//! ShadowCallStack.
//!
//! Clean-room behavioral reconstruction from:
//! - AddressSanitizer (ASan): Google sanitizers wiki, Clang documentation
//! - MemorySanitizer (MSan): shadow propagation and origin tracking specs
//! - ThreadSanitizer (TSan): happens-before, vector clocks, race detection
//! - UndefinedBehaviorSanitizer (UBSan): overflow, shift, bounds, alignment
//! - LeakSanitizer (LSan): allocation tracking and leak detection
//! - SafeStack: dual-stack protection for code-pointer integrity
//! - ShadowCallStack: return-address shadow stack
//! - Intel® 64 and IA-32 Architectures Software Developer's Manual
//!
//! Zero LLVM source code consultation. All behavior reconstructed from
//! published specifications and black-box oracle interrogation.

#![allow(non_upper_case_globals, dead_code)]

use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
use std::fmt;

// ============================================================================
// X86 Sanitizer CodeGen Constants
// ============================================================================

/// ASan shadow scale (1 byte of shadow per 8 bytes of application memory).
pub const X86_SANCODEGEN_ASAN_SHADOW_SCALE: u32 = 3;

/// ASan shadow granularity in bytes.
pub const X86_SANCODEGEN_ASAN_SHADOW_GRANULARITY: u32 = 1 << X86_SANCODEGEN_ASAN_SHADOW_SCALE;

/// ASan default shadow offset for x86-64.
pub const X86_SANCODEGEN_ASAN_SHADOW_OFFSET_X64: u64 = 0x7fff8000;

/// ASan shadow offset for x86-64 with ASLR.
pub const X86_SANCODEGEN_ASAN_SHADOW_OFFSET_X64_ASLR: u64 = 0x7fff80000000;

/// ASan shadow offset for i386.
pub const X86_SANCODEGEN_ASAN_SHADOW_OFFSET_X32: u32 = 0x20000000;

/// Size of redzone inserted after each stack variable (in bytes).
pub const X86_SANCODEGEN_STACK_REDZONE_SIZE: u32 = 32;

/// Minimum redzone size.
pub const X86_SANCODEGEN_MIN_REDZONE_SIZE: u32 = 16;

/// Size of redzone around global variables.
pub const X86_SANCODEGEN_GLOBAL_REDZONE_SIZE: u32 = 32;

/// MSan shadow offset for x86-64.
pub const X86_SANCODEGEN_MSAN_SHADOW_OFFSET_X64: u64 = 0x200000000000;

/// MSan origin offset for x86-64.
pub const X86_SANCODEGEN_MSAN_ORIGIN_OFFSET_X64: u64 = 0x100000000000;

/// MSan shadow scale.
pub const X86_SANCODEGEN_MSAN_SHADOW_SCALE: u32 = 1;

/// TSan shadow granularity.
pub const X86_SANCODEGEN_TSAN_SHADOW_GRANULARITY: u32 = 1;

/// UBSan default shift exponent width.
pub const X86_SANCODEGEN_UBSAN_MAX_SHIFT_WIDTH: u32 = 128;

/// SafeStack alignment for unsafe stack.
pub const X86_SANCODEGEN_SAFESTACK_ALIGNMENT: u32 = 16;

/// ShadowCallStack return address count per frame (shadow).
pub const X86_SANCODEGEN_SCS_SHADOW_ENTRIES: u32 = 8;

// ============================================================================
// Sanitizer CodeGen Configuration
// ============================================================================

/// Configuration for all sanitizer codegen passes.
#[derive(Debug, Clone)]
pub struct X86SanCodeGenConfig {
    /// Enable AddressSanitizer instrumentation.
    pub asan: bool,
    /// Enable MemorySanitizer instrumentation.
    pub msan: bool,
    /// Enable ThreadSanitizer instrumentation.
    pub tsan: bool,
    /// Enable UndefinedBehaviorSanitizer instrumentation.
    pub ubsan: bool,
    /// Enable LeakSanitizer instrumentation.
    pub lsan: bool,
    /// Enable SafeStack dual-stack instrumentation.
    pub safe_stack: bool,
    /// Enable ShadowCallStack return-address protection.
    pub shadow_call_stack: bool,
    /// Enable CFI type checks.
    pub cfi: bool,
    /// Shadow offset for ASan (0 = use default).
    pub asan_shadow_offset: u64,
    /// Redzone size for ASan stack variables.
    pub asan_redzone_size: u32,
    /// Halt on error.
    pub halt_on_error: bool,
    /// Track origins in MSan.
    pub msan_track_origins: bool,
    /// Maximum stack trace depth.
    pub stack_trace_depth: u32,
    /// Detect stack use-after-return in ASan.
    pub detect_stack_uar: bool,
    /// Detect container overflow in ASan.
    pub detect_container_overflow: bool,
    /// Recover rather than abort on UBSan errors.
    pub ubsan_recover: bool,
    /// Minimal runtime mode (no error messages).
    pub minimal_runtime: bool,
    /// Target is 64-bit.
    pub is_64bit: bool,
}

impl Default for X86SanCodeGenConfig {
    fn default() -> Self {
        Self {
            asan: false,
            msan: false,
            tsan: false,
            ubsan: false,
            lsan: false,
            safe_stack: false,
            shadow_call_stack: false,
            cfi: false,
            asan_shadow_offset: 0,
            asan_redzone_size: X86_SANCODEGEN_STACK_REDZONE_SIZE,
            halt_on_error: true,
            msan_track_origins: false,
            stack_trace_depth: 16,
            detect_stack_uar: false,
            detect_container_overflow: false,
            ubsan_recover: true,
            minimal_runtime: false,
            is_64bit: true,
        }
    }
}

impl X86SanCodeGenConfig {
    /// Configure for full ASan instrumentation on x86-64.
    pub fn asan_x64() -> Self {
        Self {
            asan: true,
            asan_shadow_offset: X86_SANCODEGEN_ASAN_SHADOW_OFFSET_X64,
            is_64bit: true,
            ..Default::default()
        }
    }

    /// Configure for full MSan instrumentation with origin tracking.
    pub fn msan_with_origins() -> Self {
        Self {
            msan: true,
            msan_track_origins: true,
            is_64bit: true,
            ..Default::default()
        }
    }

    /// Configure for full TSan instrumentation.
    pub fn tsan() -> Self {
        Self {
            tsan: true,
            halt_on_error: false,
            is_64bit: true,
            ..Default::default()
        }
    }

    /// Configure for UBSan with recovery.
    pub fn ubsan() -> Self {
        Self {
            ubsan: true,
            ubsan_recover: true,
            halt_on_error: false,
            is_64bit: true,
            ..Default::default()
        }
    }

    /// Enable all available sanitizers (mutually compatible subset).
    pub fn full_sanitize() -> Self {
        Self {
            asan: true,
            ubsan: true,
            lsan: true,
            safe_stack: true,
            shadow_call_stack: true,
            cfi: true,
            is_64bit: true,
            ..Default::default()
        }
    }
}

// ============================================================================
// ASan Instrumentation: IR-level Instrumentation Plan
// ============================================================================

/// Describes a single instrumented memory access for ASan.
#[derive(Debug, Clone)]
pub struct X86ASanInstrumentedAccess {
    /// The instruction being instrumented (e.g. load, store).
    pub opcode: String,
    /// Whether this is a store (true) or load (false).
    pub is_store: bool,
    /// Size of the access in bytes.
    pub size: u8,
    /// Alignment of the access in bytes.
    pub alignment: u8,
    /// Whether the access is to stack memory.
    pub is_stack: bool,
    /// Whether the access is to heap memory.
    pub is_heap: bool,
    /// Whether the access is to a global.
    pub is_global: bool,
    /// Address of the access (symbolic).
    pub address: u64,
    /// Source location (line info).
    pub source_loc: Option<X86SanSourceLocation>,
}

impl X86ASanInstrumentedAccess {
    pub fn new(opcode: &str, is_store: bool, size: u8, alignment: u8, address: u64) -> Self {
        Self {
            opcode: opcode.to_string(),
            is_store,
            size,
            alignment,
            is_stack: false,
            is_heap: false,
            is_global: false,
            address,
            source_loc: None,
        }
    }

    /// Mark this access as a stack access.
    pub fn as_stack(mut self) -> Self {
        self.is_stack = true;
        self
    }

    /// Mark this access as a heap access.
    pub fn as_heap(mut self) -> Self {
        self.is_heap = true;
        self
    }

    /// Mark this access as a global access.
    pub fn as_global(mut self) -> Self {
        self.is_global = true;
        self
    }

    /// Attach a source location.
    pub fn with_source(mut self, file: &str, line: u32, col: u32) -> Self {
        self.source_loc = Some(X86SanSourceLocation::new(file, line, col));
        self
    }

    /// Check if the access is aligned to its size (simplified).
    pub fn is_aligned(&self) -> bool {
        self.alignment >= self.size || self.size <= self.alignment
    }

    /// Compute the shadow address for this access (64-bit).
    pub fn compute_shadow_address_64(&self, shadow_offset: u64) -> u64 {
        (self.address >> X86_SANCODEGEN_ASAN_SHADOW_SCALE) + shadow_offset
    }

    /// Compute the shadow address for this access (32-bit).
    pub fn compute_shadow_address_32(&self, shadow_offset: u32) -> u32 {
        ((self.address as u32) >> X86_SANCODEGEN_ASAN_SHADOW_SCALE) + shadow_offset
    }
}

// ============================================================================
// ASan Stack Variable Protection
// ============================================================================

/// Describes a stack variable protected by ASan.
#[derive(Debug, Clone)]
pub struct X86ASanStackVar {
    /// Name of the variable (debug info).
    pub name: String,
    /// Offset from frame base.
    pub frame_offset: i32,
    /// Size of the variable in bytes.
    pub size: u32,
    /// Alignment of the variable.
    pub alignment: u32,
    /// Size of left (lower-address) redzone.
    pub left_redzone: u32,
    /// Size of right (higher-address) redzone.
    pub right_redzone: u32,
    /// Whether use-after-scope detection is enabled.
    pub use_after_scope: bool,
    /// Whether use-after-return detection is enabled.
    pub use_after_return: bool,
    /// Shadow byte value for the left redzone.
    pub left_shadow_byte: u8,
    /// Shadow byte value for the right redzone.
    pub right_shadow_byte: u8,
    /// Shadow byte value for the middle (padding) redzone.
    pub mid_shadow_byte: u8,
    /// Life range start (instruction index).
    pub life_start: u32,
    /// Life range end (instruction index).
    pub life_end: u32,
}

impl X86ASanStackVar {
    pub fn new(name: &str, frame_offset: i32, size: u32, alignment: u32) -> Self {
        Self {
            name: name.to_string(),
            frame_offset,
            size,
            alignment,
            left_redzone: X86_SANCODEGEN_STACK_REDZONE_SIZE,
            right_redzone: X86_SANCODEGEN_STACK_REDZONE_SIZE,
            use_after_scope: false,
            use_after_return: false,
            left_shadow_byte: X86_ASAN_SHADOW_STACK_LEFT,
            right_shadow_byte: X86_ASAN_SHADOW_STACK_RIGHT,
            mid_shadow_byte: X86_ASAN_SHADOW_STACK_MID,
            life_start: 0,
            life_end: u32::MAX,
        }
    }

    /// Total size including both redzones.
    pub fn total_size(&self) -> u32 {
        self.left_redzone + self.size + self.right_redzone
    }

    /// Start offset (lower address) of the variable itself.
    pub fn var_start(&self) -> i32 {
        self.frame_offset + self.left_redzone as i32
    }

    /// End offset (higher address) of the variable itself.
    pub fn var_end(&self) -> i32 {
        self.var_start() + self.size as i32
    }

    /// Enable use-after-scope detection.
    pub fn with_use_after_scope(mut self) -> Self {
        self.use_after_scope = true;
        self
    }

    /// Enable use-after-return detection.
    pub fn with_use_after_return(mut self) -> Self {
        self.use_after_return = true;
        self
    }

    /// Set the life range.
    pub fn with_life_range(mut self, start: u32, end: u32) -> Self {
        self.life_start = start;
        self.life_end = end;
        self
    }

    /// Compute shadow byte value based on partial addressability.
    pub fn shadow_byte_for_partial(accessible_bytes: u8) -> u8 {
        match accessible_bytes {
            0 => X86_ASAN_SHADOW_ADDRESSABLE,
            1 => X86_ASAN_SHADOW_PARTIAL1,
            2 => X86_ASAN_SHADOW_PARTIAL2,
            3 => X86_ASAN_SHADOW_PARTIAL3,
            4 => X86_ASAN_SHADOW_PARTIAL4,
            5 => X86_ASAN_SHADOW_PARTIAL5,
            6 => X86_ASAN_SHADOW_PARTIAL6,
            7 => X86_ASAN_SHADOW_PARTIAL7,
            _ => X86_ASAN_SHADOW_ADDRESSABLE,
        }
    }
}

/// Shadow byte constants for ASan.
pub const X86_ASAN_SHADOW_ADDRESSABLE: u8 = 0x00;
pub const X86_ASAN_SHADOW_PARTIAL1: u8 = 0x01;
pub const X86_ASAN_SHADOW_PARTIAL2: u8 = 0x02;
pub const X86_ASAN_SHADOW_PARTIAL3: u8 = 0x03;
pub const X86_ASAN_SHADOW_PARTIAL4: u8 = 0x04;
pub const X86_ASAN_SHADOW_PARTIAL5: u8 = 0x05;
pub const X86_ASAN_SHADOW_PARTIAL6: u8 = 0x06;
pub const X86_ASAN_SHADOW_PARTIAL7: u8 = 0x07;
pub const X86_ASAN_SHADOW_HEAP_LEFT: u8 = 0xFA;
pub const X86_ASAN_SHADOW_HEAP_RIGHT: u8 = 0xFB;
pub const X86_ASAN_SHADOW_STACK_LEFT: u8 = 0xF1;
pub const X86_ASAN_SHADOW_STACK_MID: u8 = 0xF2;
pub const X86_ASAN_SHADOW_STACK_RIGHT: u8 = 0xF3;
pub const X86_ASAN_SHADOW_GLOBAL: u8 = 0xF9;
pub const X86_ASAN_SHADOW_FREED: u8 = 0xFD;
pub const X86_ASAN_SHADOW_UAR: u8 = 0xF8;
pub const X86_ASAN_SHADOW_SCOPE: u8 = 0xF5;
pub const X86_ASAN_SHADOW_INTRA_OBJECT: u8 = 0xF4;
pub const X86_ASAN_SHADOW_INVALID: u8 = 0xFF;

// ============================================================================
// ASan Instrumented Stack Frame
// ============================================================================

/// Represents an instrumented stack frame with ASan redzones.
#[derive(Debug, Clone)]
pub struct X86ASanStackFrame {
    /// All stack variables in this frame.
    pub variables: Vec<X86ASanStackVar>,
    /// Total size of the instrumented frame.
    pub total_frame_size: u32,
    /// Number of use-after-scope-tracked variables.
    pub uas_count: u32,
    /// Number of use-after-return-tracked variables.
    pub uar_count: u32,
    /// Whether this frame uses a fake stack.
    pub uses_fake_stack: bool,
    /// Magic number for frame descriptor.
    pub frame_descriptor_magic: u64,
    /// Offset of the frame descriptor.
    pub frame_descriptor_offset: i32,
}

impl X86ASanStackFrame {
    pub fn new() -> Self {
        Self {
            variables: Vec::new(),
            total_frame_size: 0,
            uas_count: 0,
            uar_count: 0,
            uses_fake_stack: false,
            frame_descriptor_magic: 0x41B58AB3,
            frame_descriptor_offset: 0,
        }
    }

    /// Add a stack variable to the frame.
    pub fn add_variable(&mut self, var: X86ASanStackVar) {
        if var.use_after_scope {
            self.uas_count += 1;
        }
        if var.use_after_return {
            self.uar_count += 1;
            self.uses_fake_stack = true;
        }
        self.variables.push(var);
        self.total_frame_size = self.variables.iter().map(|v| v.total_size()).sum();
    }

    /// Compute the shadow memory poisoning operations needed.
    pub fn compute_shadow_operations(&self) -> Vec<X86ASanShadowOp> {
        let mut ops = Vec::new();
        let mut offset: i32 = 0;
        for var in &self.variables {
            // Poison left redzone
            let left_start = offset;
            let left_end = offset + var.left_redzone as i32;
            if var.left_redzone > 0 {
                ops.push(X86ASanShadowOp::poison(
                    left_start,
                    left_end,
                    var.left_shadow_byte,
                ));
            }
            offset = left_end;
            // Variable is addressable
            let var_start = offset;
            let var_end = offset + var.size as i32;
            // Generate partial poisoning if alignment requires it
            let aligned_size = var.size;
            let shadow_bytes_needed = (aligned_size + X86_SANCODEGEN_ASAN_SHADOW_GRANULARITY - 1)
                / X86_SANCODEGEN_ASAN_SHADOW_GRANULARITY;
            for i in 0..shadow_bytes_needed {
                let addr_in_var = i * X86_SANCODEGEN_ASAN_SHADOW_GRANULARITY;
                let remaining =
                    if addr_in_var + X86_SANCODEGEN_ASAN_SHADOW_GRANULARITY > aligned_size {
                        aligned_size - addr_in_var
                    } else {
                        X86_SANCODEGEN_ASAN_SHADOW_GRANULARITY
                    };
                let shadow_val = X86ASanStackVar::shadow_byte_for_partial(remaining as u8);
                ops.push(X86ASanShadowOp::set_shadow(
                    var_start + i as i32 * X86_SANCODEGEN_ASAN_SHADOW_GRANULARITY as i32,
                    shadow_val,
                ));
            }
            offset = var_end;
            // Poison right redzone
            if var.right_redzone > 0 {
                ops.push(X86ASanShadowOp::poison(
                    offset,
                    offset + var.right_redzone as i32,
                    var.right_shadow_byte,
                ));
            }
            offset += var.right_redzone as i32;
        }
        ops
    }

    /// Generate unpoisoning operations for the entire frame.
    pub fn unpoison_all(&self) -> Vec<X86ASanShadowOp> {
        let mut ops = Vec::new();
        let size = self.total_frame_size;
        if size > 0 {
            ops.push(X86ASanShadowOp::unpoison(0, size as i32));
        }
        ops
    }

    /// Get a variable by name.
    pub fn get_variable(&self, name: &str) -> Option<&X86ASanStackVar> {
        self.variables.iter().find(|v| v.name == name)
    }

    /// Get the total number of variables.
    pub fn variable_count(&self) -> usize {
        self.variables.len()
    }
}

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

// ============================================================================
// ASan Shadow Operation
// ============================================================================

/// A shadow memory operation to be emitted as IR.
#[derive(Debug, Clone)]
pub struct X86ASanShadowOp {
    /// Type of shadow operation.
    pub op_kind: X86ASanShadowOpKind,
    /// Start offset from frame base.
    pub start_offset: i32,
    /// End offset from frame base (exclusive for ranges).
    pub end_offset: i32,
    /// Shadow byte value to set.
    pub shadow_value: u8,
}

/// Types of shadow memory operations.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum X86ASanShadowOpKind {
    /// Poison a range with a fixed shadow value.
    Poison,
    /// Unpoison a range (set to ADDRESSABLE).
    Unpoison,
    /// Set a single shadow byte.
    SetShadow,
    /// Check a single access.
    CheckAccess,
}

impl X86ASanShadowOp {
    pub fn poison(start: i32, end: i32, value: u8) -> Self {
        Self {
            op_kind: X86ASanShadowOpKind::Poison,
            start_offset: start,
            end_offset: end,
            shadow_value: value,
        }
    }

    pub fn unpoison(start: i32, end: i32) -> Self {
        Self {
            op_kind: X86ASanShadowOpKind::Unpoison,
            start_offset: start,
            end_offset: end,
            shadow_value: X86_ASAN_SHADOW_ADDRESSABLE,
        }
    }

    pub fn set_shadow(offset: i32, value: u8) -> Self {
        Self {
            op_kind: X86ASanShadowOpKind::SetShadow,
            start_offset: offset,
            end_offset: offset + 1,
            shadow_value: value,
        }
    }

    pub fn check_access(offset: i32, size: u8) -> Self {
        Self {
            op_kind: X86ASanShadowOpKind::CheckAccess,
            start_offset: offset,
            end_offset: offset + size as i32,
            shadow_value: 0,
        }
    }
}

// ============================================================================
// MSan Instrumentation: Shadow and Origin Tracking
// ============================================================================

/// Tracks shadow state for a value in MSan.
#[derive(Debug, Clone)]
pub struct X86MSanShadowValue {
    /// The shadow (whether each bit is initialized).
    pub shadow: u64,
    /// The origin ID tracking where the uninitialized value came from.
    pub origin_id: u32,
}

impl X86MSanShadowValue {
    /// Fully initialized value (all bits known).
    pub const INITIALIZED: Self = Self {
        shadow: 0,
        origin_id: 0,
    };

    /// Fully uninitialized value.
    pub const UNINITIALIZED: Self = Self {
        shadow: u64::MAX,
        origin_id: 0,
    };

    pub fn new(shadow: u64, origin_id: u32) -> Self {
        Self { shadow, origin_id }
    }

    pub fn is_initialized(&self) -> bool {
        self.shadow == 0
    }

    pub fn is_uninitialized(&self) -> bool {
        self.shadow != 0
    }

    /// Propagate shadow through a binary operation.
    pub fn propagate_binary(lhs: &Self, rhs: &Self) -> Self {
        Self {
            shadow: lhs.shadow | rhs.shadow,
            origin_id: if lhs.shadow != 0 {
                lhs.origin_id
            } else {
                rhs.origin_id
            },
        }
    }

    /// Propagate shadow through a unary operation.
    pub fn propagate_unary(val: &Self) -> Self {
        val.clone()
    }

    /// Truncate shadow to a smaller bit width.
    pub fn truncate(&self, width: u32) -> Self {
        let mask = if width >= 64 {
            u64::MAX
        } else {
            (1u64 << width) - 1
        };
        Self {
            shadow: self.shadow & mask,
            origin_id: self.origin_id,
        }
    }

    /// Extend shadow to a larger bit width (zero-extend).
    pub fn zext(&self, _from_width: u32) -> Self {
        self.clone()
    }

    /// Sign-extend shadow to a larger bit width.
    pub fn sext(&self, from_width: u32) -> Self {
        if from_width == 0 || from_width >= 64 {
            return self.clone();
        }
        let sign_bit = 1u64 << (from_width - 1);
        let ext_mask = !((1u64 << from_width) - 1);
        if self.shadow & sign_bit != 0 {
            Self {
                shadow: self.shadow | ext_mask,
                origin_id: self.origin_id,
            }
        } else {
            self.clone()
        }
    }

    /// Bitcast shadow (no change needed).
    pub fn bitcast(&self) -> Self {
        self.clone()
    }
}

// ============================================================================
// MSan Origin Registry
// ============================================================================

/// An origin tracking entry for MSan.
#[derive(Debug, Clone)]
pub struct X86MSanOrigin {
    /// Unique origin ID.
    pub id: u32,
    /// Description of the origin.
    pub description: String,
    /// Stack trace where the uninitialized value was created.
    pub stack_trace: Option<Vec<X86SanStackFrame>>,
    /// The kind of origin.
    pub kind: X86MSanOriginKind,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum X86MSanOriginKind {
    /// Value comes from a heap allocation.
    HeapAllocation,
    /// Value comes from a stack allocation.
    StackAllocation,
    /// Value comes from a global variable.
    GlobalVariable,
    /// Value is a function parameter.
    FunctionParameter,
    /// Value generated by an instruction.
    Instruction,
    /// Value from deallocated memory.
    Deallocated,
    /// Unknown origin.
    Unknown,
}

impl fmt::Display for X86MSanOriginKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::HeapAllocation => write!(f, "heap"),
            Self::StackAllocation => write!(f, "stack"),
            Self::GlobalVariable => write!(f, "global"),
            Self::FunctionParameter => write!(f, "parameter"),
            Self::Instruction => write!(f, "instruction"),
            Self::Deallocated => write!(f, "deallocated"),
            Self::Unknown => write!(f, "unknown"),
        }
    }
}

impl X86MSanOrigin {
    pub fn new(id: u32, description: &str, kind: X86MSanOriginKind) -> Self {
        Self {
            id,
            description: description.to_string(),
            stack_trace: None,
            kind,
        }
    }

    /// Attach a stack trace to this origin.
    pub fn with_stack_trace(mut self, frames: Vec<X86SanStackFrame>) -> Self {
        self.stack_trace = Some(frames);
        self
    }
}

// ============================================================================
// MSan Shadow Propagation Table
// ============================================================================

/// Handles shadow propagation for all LLVM IR operations.
#[derive(Debug, Clone)]
pub struct X86MSanShadowPropagator {
    /// Mapping from instruction name to shadow propagation rule.
    pub propagation_rules: HashMap<String, X86MSanPropagationRule>,
    /// Whether origin tracking is active.
    pub track_origins: bool,
}

#[derive(Debug, Clone)]
pub enum X86MSanPropagationRule {
    /// Binary op: shadow = shadow(lhs) | shadow(rhs).
    BinaryOr,
    /// Binary op: shadow = shadow(lhs) & shadow(rhs) (for and/or).
    BinaryAnd,
    /// Unary op: shadow = shadow(input).
    Unary,
    /// Select: shadow = select(cond, shadow(t), shadow(f)).
    Select,
    /// Comparison: produces a single bit shadow.
    Comparison,
    /// Phi: shadow = or-of-all-incoming(shadows).
    Phi,
    /// Custom rule name.
    Custom(String),
}

impl X86MSanShadowPropagator {
    pub fn new(track_origins: bool) -> Self {
        let mut rules = HashMap::new();
        // Arithmetic
        rules.insert("add".to_string(), X86MSanPropagationRule::BinaryOr);
        rules.insert("sub".to_string(), X86MSanPropagationRule::BinaryOr);
        rules.insert("mul".to_string(), X86MSanPropagationRule::BinaryOr);
        rules.insert("udiv".to_string(), X86MSanPropagationRule::BinaryOr);
        rules.insert("sdiv".to_string(), X86MSanPropagationRule::BinaryOr);
        rules.insert("urem".to_string(), X86MSanPropagationRule::BinaryOr);
        rules.insert("srem".to_string(), X86MSanPropagationRule::BinaryOr);
        // Bitwise
        rules.insert("and".to_string(), X86MSanPropagationRule::BinaryAnd);
        rules.insert("or".to_string(), X86MSanPropagationRule::BinaryOr);
        rules.insert("xor".to_string(), X86MSanPropagationRule::BinaryOr);
        // Shifts
        rules.insert("shl".to_string(), X86MSanPropagationRule::BinaryOr);
        rules.insert("lshr".to_string(), X86MSanPropagationRule::BinaryOr);
        rules.insert("ashr".to_string(), X86MSanPropagationRule::BinaryOr);
        // Select / Phi
        rules.insert("select".to_string(), X86MSanPropagationRule::Select);
        rules.insert("phi".to_string(), X86MSanPropagationRule::Phi);
        // Comparison
        rules.insert("icmp".to_string(), X86MSanPropagationRule::Comparison);
        rules.insert("fcmp".to_string(), X86MSanPropagationRule::Comparison);
        // Floating-point
        rules.insert("fadd".to_string(), X86MSanPropagationRule::BinaryOr);
        rules.insert("fsub".to_string(), X86MSanPropagationRule::BinaryOr);
        rules.insert("fmul".to_string(), X86MSanPropagationRule::BinaryOr);
        rules.insert("fdiv".to_string(), X86MSanPropagationRule::BinaryOr);

        Self {
            propagation_rules: rules,
            track_origins,
        }
    }

    /// Get the propagation rule for an instruction.
    pub fn get_rule(&self, inst_name: &str) -> Option<&X86MSanPropagationRule> {
        self.propagation_rules.get(inst_name)
    }

    /// Apply the propagation rule for two shadow values.
    pub fn propagate_binary(
        &self,
        rule: &X86MSanPropagationRule,
        lhs: &X86MSanShadowValue,
        rhs: &X86MSanShadowValue,
    ) -> X86MSanShadowValue {
        match rule {
            X86MSanPropagationRule::BinaryOr => X86MSanShadowValue::propagate_binary(lhs, rhs),
            X86MSanPropagationRule::BinaryAnd => {
                let shadow = lhs.shadow & rhs.shadow;
                X86MSanShadowValue::new(shadow, lhs.origin_id)
            }
            _ => X86MSanShadowValue::propagate_binary(lhs, rhs),
        }
    }

    /// Register a custom propagation rule.
    pub fn register_rule(&mut self, inst_name: &str, rule: X86MSanPropagationRule) {
        self.propagation_rules.insert(inst_name.to_string(), rule);
    }
}

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

// ============================================================================
// TSan Instrumentation: Happens-Before and Race Detection
// ============================================================================

/// Event types tracked by TSan instrumentation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86TSanEventType {
    /// Memory read.
    Read,
    /// Memory write.
    Write,
    /// Mutex lock acquire.
    MutexLock,
    /// Mutex unlock release.
    MutexUnlock,
    /// Mutex read lock acquire.
    MutexReadLock,
    /// Mutex read unlock release.
    MutexReadUnlock,
    /// Thread creation.
    ThreadCreate,
    /// Thread join.
    ThreadJoin,
    /// Atomic load (acquire semantics).
    AtomicLoadAcquire,
    /// Atomic store (release semantics).
    AtomicStoreRelease,
    /// Atomic RMW.
    AtomicRMW,
    /// Atomic fence.
    AtomicFence,
    /// Signal send.
    SignalSend,
    /// Signal wait.
    SignalWait,
}

impl fmt::Display for X86TSanEventType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Read => write!(f, "READ"),
            Self::Write => write!(f, "WRITE"),
            Self::MutexLock => write!(f, "MUTEX_LOCK"),
            Self::MutexUnlock => write!(f, "MUTEX_UNLOCK"),
            Self::MutexReadLock => write!(f, "MUTEX_RDLOCK"),
            Self::MutexReadUnlock => write!(f, "MUTEX_RDUNLOCK"),
            Self::ThreadCreate => write!(f, "THREAD_CREATE"),
            Self::ThreadJoin => write!(f, "THREAD_JOIN"),
            Self::AtomicLoadAcquire => write!(f, "ATOMIC_LOAD_ACQUIRE"),
            Self::AtomicStoreRelease => write!(f, "ATOMIC_STORE_RELEASE"),
            Self::AtomicRMW => write!(f, "ATOMIC_RMW"),
            Self::AtomicFence => write!(f, "ATOMIC_FENCE"),
            Self::SignalSend => write!(f, "SIGNAL_SEND"),
            Self::SignalWait => write!(f, "SIGNAL_WAIT"),
        }
    }
}

/// A TSan instrumented event.
#[derive(Debug, Clone)]
pub struct X86TSanEvent {
    /// Type of the event.
    pub event_type: X86TSanEventType,
    /// Thread ID that generated this event.
    pub thread_id: u32,
    /// Logical clock value at event time.
    pub clock: u64,
    /// Memory address involved (0 for synchronization).
    pub address: u64,
    /// Size of the access in bytes.
    pub size: u8,
    /// Source location.
    pub source_loc: Option<X86SanSourceLocation>,
    /// Associated mutex ID (for lock/unlock events).
    pub mutex_id: u32,
}

impl X86TSanEvent {
    pub fn new(event_type: X86TSanEventType, thread_id: u32, clock: u64) -> Self {
        Self {
            event_type,
            thread_id,
            clock,
            address: 0,
            size: 0,
            source_loc: None,
            mutex_id: 0,
        }
    }

    /// Set the memory address.
    pub fn at_address(mut self, addr: u64, size: u8) -> Self {
        self.address = addr;
        self.size = size;
        self
    }

    /// Attach source location info.
    pub fn with_source(mut self, file: &str, line: u32, col: u32) -> Self {
        self.source_loc = Some(X86SanSourceLocation::new(file, line, col));
        self
    }

    /// Set the mutex ID.
    pub fn with_mutex(mut self, mutex_id: u32) -> Self {
        self.mutex_id = mutex_id;
        self
    }
}

// ============================================================================
// TSan Vector Clock
// ============================================================================

/// A clock entry in a vector clock.
#[derive(Debug, Clone, Copy)]
pub struct X86TSanClockEntry {
    pub thread_id: u32,
    pub clock: u64,
}

/// A vector clock for happens-before tracking.
#[derive(Debug, Clone)]
pub struct X86TSanVectorClock {
    pub entries: Vec<X86TSanClockEntry>,
}

impl X86TSanVectorClock {
    pub fn new() -> Self {
        Self {
            entries: Vec::new(),
        }
    }

    /// Get the clock for a thread.
    pub fn get(&self, thread_id: u32) -> u64 {
        for entry in &self.entries {
            if entry.thread_id == thread_id {
                return entry.clock;
            }
        }
        0
    }

    /// Set or update the clock for a thread.
    pub fn set(&mut self, thread_id: u32, clock: u64) {
        for entry in &mut self.entries {
            if entry.thread_id == thread_id {
                entry.clock = entry.clock.max(clock);
                return;
            }
        }
        self.entries.push(X86TSanClockEntry { thread_id, clock });
    }

    /// Tick the clock for a thread (increment by 1).
    pub fn tick(&mut self, thread_id: u32) {
        for entry in &mut self.entries {
            if entry.thread_id == thread_id {
                entry.clock += 1;
                return;
            }
        }
        self.entries.push(X86TSanClockEntry {
            thread_id,
            clock: 1,
        });
    }

    /// Check if this clock happens-before another clock.
    pub fn happens_before(&self, other: &Self) -> bool {
        if self.entries.is_empty() {
            return true;
        }
        for entry in &self.entries {
            let other_clock = other.get(entry.thread_id);
            if entry.clock > other_clock {
                return false;
            }
        }
        true
    }

    /// Check if this clock is concurrent with another clock.
    pub fn concurrent_with(&self, other: &Self) -> bool {
        !self.happens_before(other) && !other.happens_before(self)
    }

    /// Merge another clock into this one (join operation).
    pub fn join(&mut self, other: &Self) {
        for entry in &other.entries {
            self.set(entry.thread_id, entry.clock);
        }
    }

    /// Maximum clock across all threads.
    pub fn max_clock(&self) -> u64 {
        self.entries.iter().map(|e| e.clock).max().unwrap_or(0)
    }

    /// Number of clock entries.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Whether the clock is empty.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

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

// ============================================================================
// TSan Shadow Cell
// ============================================================================

/// A TSan shadow cell for a memory location.
#[derive(Debug, Clone)]
pub struct X86TSanShadowCell {
    /// Thread that last accessed this location.
    pub last_thread: u32,
    /// Clock of the last access.
    pub last_clock: u64,
    /// Thread that last wrote this location.
    pub last_write_thread: u32,
    /// Clock of the last write.
    pub write_clock: u64,
    /// Number of concurrent read accesses.
    pub read_count: u32,
    /// Access history (for more precise detection).
    pub history: Vec<X86TSanShadowHistoryEntry>,
}

/// A history entry in a shadow cell.
#[derive(Debug, Clone)]
pub struct X86TSanShadowHistoryEntry {
    pub thread_id: u32,
    pub clock: u64,
    pub is_write: bool,
    pub size: u8,
}

impl X86TSanShadowCell {
    pub fn new() -> Self {
        Self {
            last_thread: 0,
            last_clock: 0,
            last_write_thread: 0,
            write_clock: 0,
            read_count: 0,
            history: Vec::new(),
        }
    }

    /// Record a memory access. Returns true if a race was detected.
    pub fn record_access(&mut self, thread_id: u32, clock: u64, is_write: bool, size: u8) -> bool {
        let mut race_detected = false;

        if is_write {
            // Write-write race: another thread wrote without happens-before
            if self.last_write_thread != 0
                && self.last_write_thread != thread_id
                && self.write_clock >= clock
            {
                race_detected = true;
            }
            // Read-write race: another thread read without happens-before
            if self.last_thread != 0 && self.last_thread != thread_id && self.last_clock >= clock {
                race_detected = true;
            }
            // Update write state
            self.last_write_thread = thread_id;
            self.write_clock = clock;
            self.read_count = 0;
        } else {
            // Write-read race: another thread wrote without happens-before
            if self.last_write_thread != 0
                && self.last_write_thread != thread_id
                && self.write_clock >= clock
            {
                race_detected = true;
            }
            self.read_count += 1;
        }

        self.last_thread = thread_id;
        self.last_clock = clock;

        // Record in history
        let history_limit = 8;
        if self.history.len() >= history_limit {
            self.history.remove(0);
        }
        self.history.push(X86TSanShadowHistoryEntry {
            thread_id,
            clock,
            is_write,
            size,
        });

        race_detected
    }

    /// Reset this shadow cell.
    pub fn reset(&mut self) {
        self.last_thread = 0;
        self.last_clock = 0;
        self.last_write_thread = 0;
        self.write_clock = 0;
        self.read_count = 0;
        self.history.clear();
    }
}

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

// ============================================================================
// TSan Mutex Tracking
// ============================================================================

/// TSan mutex state for instrumentation.
#[derive(Debug, Clone)]
pub struct X86TSanMutexState {
    /// Unique mutex ID.
    pub id: u32,
    /// Thread that currently holds the lock (0 if unlocked).
    pub owner_thread: u32,
    /// Recursive lock count.
    pub lock_count: u32,
    /// Whether this is a read (shared) lock.
    pub is_read_lock: bool,
    /// Release clock (for happens-before edges).
    pub release_clock: X86TSanVectorClock,
    /// Whether the mutex has been destroyed.
    pub is_destroyed: bool,
}

impl X86TSanMutexState {
    pub fn new(id: u32) -> Self {
        Self {
            id,
            owner_thread: 0,
            lock_count: 0,
            is_read_lock: false,
            release_clock: X86TSanVectorClock::new(),
            is_destroyed: false,
        }
    }

    /// Acquire the mutex (lock).
    pub fn acquire(&mut self, thread_id: u32) {
        self.owner_thread = thread_id;
        self.lock_count += 1;
    }

    /// Release the mutex (unlock).
    pub fn release(&mut self, thread_clock: &X86TSanVectorClock) -> X86TSanVectorClock {
        let mut rel_clock = self.release_clock.clone();
        rel_clock.join(thread_clock);
        self.release_clock = rel_clock.clone();
        self.owner_thread = 0;
        self.lock_count = 0;
        rel_clock
    }

    /// Check if the mutex is locked.
    pub fn is_locked(&self) -> bool {
        self.owner_thread != 0
    }

    /// Mark as destroyed.
    pub fn destroy(&mut self) {
        self.is_destroyed = true;
    }
}

// ============================================================================
// UBSan Instrumentation: Overflow, Shift, DivZero Checks
// ============================================================================

/// Error kinds for UBSan instrumentation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86UBSanErrorKind {
    /// Division by zero (integer).
    IntegerDivideByZero,
    /// Division by zero (floating-point).
    FloatDivideByZero,
    /// Shift exponent negative.
    ShiftExponentNegative,
    /// Shift exponent too large for type.
    ShiftExponentTooLarge,
    /// Signed integer overflow.
    SignedIntegerOverflow,
    /// Pointer overflow.
    PointerOverflow,
    /// Null pointer arithmetic.
    NullPointerArithmetic,
    /// VLA bound not positive.
    VLABoundNotPositive,
    /// Out-of-bounds access.
    OutOfBounds,
    /// Type mismatch (dynamic type check).
    TypeMismatch,
    /// Alignment assumption violated.
    AlignmentAssumption,
    /// Unreachable code executed.
    UnreachableCode,
    /// Missing return in non-void function.
    MissingReturn,
    /// Non-null attribute violation.
    NonNullViolation,
    /// Built-in __builtin_unreachable reached.
    BuiltinUnreachable,
    /// Invalid bool value (not 0 or 1).
    InvalidBool,
    /// Invalid enum value.
    InvalidEnum,
    /// Implicit conversion truncation.
    ImplicitConversionTruncation,
    /// Implicit conversion sign change.
    ImplicitConversionSignChange,
    /// Negative array size.
    NegativeArraySize,
    /// Function type mismatch via pointer cast.
    FunctionTypeMismatch,
    /// Invalid vptr (virtual table pointer).
    InvalidVptr,
}

impl fmt::Display for X86UBSanErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::IntegerDivideByZero => write!(f, "division-by-zero"),
            Self::FloatDivideByZero => write!(f, "float-divide-by-zero"),
            Self::ShiftExponentNegative => write!(f, "shift-exponent-negative"),
            Self::ShiftExponentTooLarge => write!(f, "shift-exponent-too-large"),
            Self::SignedIntegerOverflow => write!(f, "signed-integer-overflow"),
            Self::PointerOverflow => write!(f, "pointer-overflow"),
            Self::NullPointerArithmetic => write!(f, "null-pointer-arithmetic"),
            Self::VLABoundNotPositive => write!(f, "vla-bound-not-positive"),
            Self::OutOfBounds => write!(f, "out-of-bounds"),
            Self::TypeMismatch => write!(f, "type-mismatch"),
            Self::AlignmentAssumption => write!(f, "alignment-assumption"),
            Self::UnreachableCode => write!(f, "unreachable-code"),
            Self::MissingReturn => write!(f, "missing-return"),
            Self::NonNullViolation => write!(f, "nonnull-violation"),
            Self::BuiltinUnreachable => write!(f, "builtin-unreachable"),
            Self::InvalidBool => write!(f, "invalid-bool"),
            Self::InvalidEnum => write!(f, "invalid-enum"),
            Self::ImplicitConversionTruncation => write!(f, "implicit-conversion-truncation"),
            Self::ImplicitConversionSignChange => write!(f, "implicit-conversion-sign-change"),
            Self::NegativeArraySize => write!(f, "negative-array-size"),
            Self::FunctionTypeMismatch => write!(f, "function-type-mismatch"),
            Self::InvalidVptr => write!(f, "invalid-vptr"),
        }
    }
}

/// A UBSan check to be inserted at the IR level.
#[derive(Debug, Clone)]
pub struct X86UBSanCheck {
    /// The kind of check.
    pub kind: X86UBSanErrorKind,
    /// Source location.
    pub source_loc: X86SanSourceLocation,
    /// Type description for error messages.
    pub type_descr: Option<String>,
    /// Additional data for the check.
    pub extra_data: Vec<u64>,
}

impl X86UBSanCheck {
    pub fn new(kind: X86UBSanErrorKind, file: &str, line: u32, col: u32) -> Self {
        Self {
            kind,
            source_loc: X86SanSourceLocation::new(file, line, col),
            type_descr: None,
            extra_data: Vec::new(),
        }
    }

    /// Add type description.
    pub fn with_type(mut self, descr: &str) -> Self {
        self.type_descr = Some(descr.to_string());
        self
    }

    /// Add extra data.
    pub fn with_data(mut self, data: Vec<u64>) -> Self {
        self.extra_data = data;
        self
    }
}

// ============================================================================
// LSan Instrumentation: Allocation Tracking
// ============================================================================

/// An allocation record for LSan.
#[derive(Debug, Clone)]
pub struct X86LSanAllocRecord {
    /// Pointer to the allocation.
    pub ptr: u64,
    /// Size of the allocation.
    pub size: u64,
    /// Stack trace at allocation time.
    pub alloc_stack: Vec<X86SanStackFrame>,
    /// Whether this allocation is reachable.
    pub is_reachable: bool,
    /// Whether it was directly freed.
    pub is_freed: bool,
    /// Allocation ID.
    pub alloc_id: u64,
    /// Whether it is from malloc or new.
    pub is_cpp: bool,
}

impl X86LSanAllocRecord {
    pub fn new(ptr: u64, size: u64, alloc_id: u64) -> Self {
        Self {
            ptr,
            size,
            alloc_stack: Vec::new(),
            is_reachable: false,
            is_freed: false,
            alloc_id,
            is_cpp: false,
        }
    }

    /// Attach a stack trace.
    pub fn with_stack(mut self, stack: Vec<X86SanStackFrame>) -> Self {
        self.alloc_stack = stack;
        self
    }

    /// Mark as freed.
    pub fn mark_freed(&mut self) {
        self.is_freed = true;
    }

    /// Mark as reachable (during leak scan).
    pub fn mark_reachable(&mut self) {
        self.is_reachable = true;
    }
}

// ============================================================================
// SafeStack Instrumentation
// ============================================================================

/// SafeStack configuration for dual-stack layout.
#[derive(Debug, Clone)]
pub struct X86SafeStackConfig {
    /// Base address of the safe stack.
    pub safe_stack_base: u64,
    /// Limit (top) of the safe stack.
    pub safe_stack_limit: u64,
    /// Base address of the unsafe stack.
    pub unsafe_stack_base: u64,
    /// Limit (top) of the unsafe stack.
    pub unsafe_stack_limit: u64,
    /// Whether SafeStack is enabled.
    pub enabled: bool,
    /// Size of the safe stack region.
    pub safe_stack_size: u64,
    /// Size of the unsafe stack region.
    pub unsafe_stack_size: u64,
}

impl Default for X86SafeStackConfig {
    fn default() -> Self {
        Self {
            safe_stack_base: 0,
            safe_stack_limit: 0,
            unsafe_stack_base: 0,
            unsafe_stack_limit: 0,
            enabled: false,
            safe_stack_size: 1024 * 1024,       // 1 MB safe stack
            unsafe_stack_size: 8 * 1024 * 1024, // 8 MB unsafe stack
        }
    }
}

impl X86SafeStackConfig {
    pub fn new(safe_stack_size: u64, unsafe_stack_size: u64) -> Self {
        Self {
            safe_stack_base: 0,
            safe_stack_limit: safe_stack_size,
            unsafe_stack_base: safe_stack_size,
            unsafe_stack_limit: safe_stack_size + unsafe_stack_size,
            enabled: true,
            safe_stack_size,
            unsafe_stack_size,
        }
    }

    /// Check if a given frame object should go on the safe stack.
    pub fn is_safe_object(&self, _alloca_name: &str, is_array: bool) -> bool {
        // Arrays/alloca go on unsafe stack; scalars go on safe stack
        !is_array
    }

    /// Get the safe stack pointer for a frame offset.
    pub fn safe_stack_addr(&self, offset: i32) -> u64 {
        self.safe_stack_base + offset as u64
    }

    /// Get the unsafe stack pointer for a frame offset.
    pub fn unsafe_stack_addr(&self, offset: i32) -> u64 {
        self.unsafe_stack_base + offset as u64
    }
}

// ============================================================================
// Shadow Call Stack Instrumentation
// ============================================================================

/// Shadow Call Stack for return-address protection.
#[derive(Debug, Clone)]
pub struct X86ShadowCallStack {
    /// Shadow stack entries (most recent first).
    pub entries: Vec<X86SCSEntry>,
    /// Current stack depth.
    pub depth: u32,
    /// Whether the shadow stack is active.
    pub active: bool,
    /// Total pushes since initialization.
    pub total_pushes: u64,
    /// Total pops since initialization.
    pub total_pops: u64,
    /// Number of mismatches detected.
    pub mismatches: u64,
}

/// A shadow call stack entry.
#[derive(Debug, Clone)]
pub struct X86SCSEntry {
    /// The return address stored.
    pub return_address: u64,
    /// Frame depth at time of push.
    pub frame_depth: u32,
    /// Whether this entry is valid.
    pub valid: bool,
    /// Source function name (for diagnostics).
    pub function: Option<String>,
}

impl X86ShadowCallStack {
    pub fn new() -> Self {
        Self {
            entries: Vec::new(),
            depth: 0,
            active: false,
            total_pushes: 0,
            total_pops: 0,
            mismatches: 0,
        }
    }

    /// Push a return address onto the shadow stack.
    pub fn push(&mut self, return_address: u64, function: Option<&str>) {
        self.entries.push(X86SCSEntry {
            return_address,
            frame_depth: self.depth,
            valid: true,
            function: function.map(String::from),
        });
        self.depth += 1;
        self.total_pushes += 1;
    }

    /// Pop and verify a return address from the shadow stack.
    pub fn pop(&mut self, expected_address: u64) -> bool {
        self.total_pops += 1;
        if let Some(entry) = self.entries.pop() {
            self.depth = self.depth.saturating_sub(1);
            if entry.return_address != expected_address {
                self.mismatches += 1;
                return false;
            }
            return true;
        }
        // Stack underflow
        self.mismatches += 1;
        false
    }

    /// Peek at the top return address without popping.
    pub fn peek(&self) -> Option<u64> {
        self.entries.last().map(|e| e.return_address)
    }

    /// Check if the shadow stack is empty.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Get the current depth.
    pub fn depth(&self) -> u32 {
        self.depth
    }

    /// Reset the shadow stack.
    pub fn reset(&mut self) {
        self.entries.clear();
        self.depth = 0;
        self.active = false;
    }
}

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

// ============================================================================
// CFI Type Check Instrumentation (within Sanitizer CodeGen)
// ============================================================================

/// A CFI type check descriptor.
#[derive(Debug, Clone)]
pub struct X86CFITypeCheck {
    /// The type being checked.
    pub type_name: String,
    /// The type identifier hash.
    pub type_hash: u64,
    /// The address being checked.
    pub target_address: u64,
    /// Source location of the check.
    pub source_loc: Option<X86SanSourceLocation>,
    /// Whether this is a virtual call check.
    pub is_vcall: bool,
    /// Whether this is an indirect call check.
    pub is_icall: bool,
    /// Bitmask for valid types (forward-edge CFI).
    pub bitmask: Option<u64>,
}

impl X86CFITypeCheck {
    pub fn new(type_name: &str, type_hash: u64, target_address: u64) -> Self {
        Self {
            type_name: type_name.to_string(),
            type_hash,
            target_address,
            source_loc: None,
            is_vcall: false,
            is_icall: false,
            bitmask: None,
        }
    }

    /// Mark as virtual call check.
    pub fn as_vcall(mut self) -> Self {
        self.is_vcall = true;
        self
    }

    /// Mark as indirect call check.
    pub fn as_icall(mut self) -> Self {
        self.is_icall = true;
        self
    }

    /// Set a bitmask for the valid type set.
    pub fn with_bitmask(mut self, bitmask: u64) -> Self {
        self.bitmask = Some(bitmask);
        self
    }

    /// Check whether the type passes the bitmask test.
    pub fn passes_bitmask(&self, type_id: u64) -> bool {
        if let Some(mask) = self.bitmask {
            (type_id & mask) == (self.type_hash & mask)
        } else {
            type_id == self.type_hash
        }
    }
}

// ============================================================================
// Source Location (shared)
// ============================================================================

/// A source location used across sanitizers.
#[derive(Debug, Clone)]
pub struct X86SanSourceLocation {
    /// Source file name.
    pub file: String,
    /// Line number (1-based).
    pub line: u32,
    /// Column number (1-based).
    pub column: u32,
}

impl X86SanSourceLocation {
    pub fn new(file: &str, line: u32, column: u32) -> Self {
        Self {
            file: file.to_string(),
            line,
            column,
        }
    }

    pub fn format(&self) -> String {
        format!("{}:{}:{}", self.file, self.line, self.column)
    }
}

// ============================================================================
// Stack Frame (shared)
// ============================================================================

/// A captured stack frame.
#[derive(Debug, Clone)]
pub struct X86SanStackFrame {
    /// Function name.
    pub function: Option<String>,
    /// Source file.
    pub file: Option<String>,
    /// Line number.
    pub line: Option<u32>,
    /// Column number.
    pub column: Option<u32>,
    /// Module name.
    pub module: Option<String>,
    /// Module offset (PC relative to module base).
    pub module_offset: Option<u64>,
    /// Raw instruction pointer.
    pub ip: u64,
}

impl X86SanStackFrame {
    pub fn new(ip: u64) -> Self {
        Self {
            function: None,
            file: None,
            line: None,
            column: None,
            module: None,
            module_offset: None,
            ip,
        }
    }

    pub fn with_function(ip: u64, func: &str) -> Self {
        Self {
            function: Some(func.to_string()),
            ip,
            ..Self::new(ip)
        }
    }

    pub fn format(&self) -> String {
        if let Some(func) = &self.function {
            if let (Some(file), Some(line)) = (&self.file, self.line) {
                format!("    #{} 0x{:x} in {} {}:{}", 0, self.ip, func, file, line)
            } else {
                format!("    #{} 0x{:x} in {}", 0, self.ip, func)
            }
        } else {
            format!("    #{} 0x{:x}", 0, self.ip)
        }
    }
}

// ============================================================================
// X86SanCodeGen — Top-level Orchestrator
// ============================================================================

/// The top-level X86 sanitizer codegen orchestrator.
///
/// Manages all sanitizer instrumentation passes for X86 targets,
/// coordinating ASan, MSan, TSan, UBSan, LSan, SafeStack, CFI,
/// and ShadowCallStack instrumentation at the IR level.
#[derive(Debug, Clone)]
pub struct X86SanCodeGen {
    /// Overall configuration.
    pub config: X86SanCodeGenConfig,
    /// ASan: instrumented memory accesses.
    pub asan_accesses: Vec<X86ASanInstrumentedAccess>,
    /// ASan: current stack frame being instrumented.
    pub asan_stack_frame: Option<X86ASanStackFrame>,
    /// ASan: all instrumented stack frames.
    pub asan_frames: Vec<X86ASanStackFrame>,
    /// MSan: shadow values for tracked registers/values.
    pub msan_shadows: HashMap<String, X86MSanShadowValue>,
    /// MSan: origin registry.
    pub msan_origins: Vec<X86MSanOrigin>,
    /// MSan: shadow propagator.
    pub msan_propagator: X86MSanShadowPropagator,
    /// TSan: events recorded.
    pub tsan_events: Vec<X86TSanEvent>,
    /// TSan: shadow memory cells.
    pub tsan_shadow: HashMap<u64, X86TSanShadowCell>,
    /// TSan: mutex states.
    pub tsan_mutexes: Vec<X86TSanMutexState>,
    /// TSan: global logical clock.
    pub tsan_global_tick: u64,
    /// UBSan: checks to insert.
    pub ubsan_checks: Vec<X86UBSanCheck>,
    /// LSan: allocation records.
    pub lsan_allocations: Vec<X86LSanAllocRecord>,
    /// LSan: next allocation ID.
    pub lsan_next_alloc_id: u64,
    /// SafeStack: configuration.
    pub safe_stack: X86SafeStackConfig,
    /// ShadowCallStack: shadow state.
    pub shadow_call_stack: X86ShadowCallStack,
    /// CFI: type checks generated.
    pub cfi_checks: Vec<X86CFITypeCheck>,
    /// Statistics.
    pub stats: X86SanCodeGenStats,
}

/// Statistics for sanitizer codegen.
#[derive(Debug, Clone, Default)]
pub struct X86SanCodeGenStats {
    /// ASan instrumented accesses.
    pub asan_instrumented: u64,
    /// ASan stack variables protected.
    pub asan_stack_vars: u64,
    /// MSan values tracked.
    pub msan_tracked: u64,
    /// MSan origins recorded.
    pub msan_origins: u64,
    /// TSan events recorded.
    pub tsan_events: u64,
    /// TSan races detected.
    pub tsan_races: u64,
    /// UBSan checks inserted.
    pub ubsan_checks: u64,
    /// LSan allocations tracked.
    pub lsan_allocs: u64,
    /// CFI checks inserted.
    pub cfi_checks: u64,
    /// Shadow call stack pushes.
    pub scs_pushes: u64,
    /// Functions processed.
    pub functions_processed: u64,
}

impl X86SanCodeGen {
    /// Create a new sanitizer codegen instance with default config.
    pub fn new() -> Self {
        let config = X86SanCodeGenConfig::default();
        Self {
            msan_propagator: X86MSanShadowPropagator::new(config.msan_track_origins),
            config,
            asan_accesses: Vec::new(),
            asan_stack_frame: None,
            asan_frames: Vec::new(),
            msan_shadows: HashMap::new(),
            msan_origins: Vec::new(),
            tsan_events: Vec::new(),
            tsan_shadow: HashMap::new(),
            tsan_mutexes: Vec::new(),
            tsan_global_tick: 0,
            ubsan_checks: Vec::new(),
            lsan_allocations: Vec::new(),
            lsan_next_alloc_id: 1,
            safe_stack: X86SafeStackConfig::default(),
            shadow_call_stack: X86ShadowCallStack::new(),
            cfi_checks: Vec::new(),
            stats: X86SanCodeGenStats::default(),
        }
    }

    /// Create with explicit configuration.
    pub fn with_config(config: X86SanCodeGenConfig) -> Self {
        let msan_origins_enabled = config.msan_track_origins;
        Self {
            msan_propagator: X86MSanShadowPropagator::new(msan_origins_enabled),
            config,
            ..Self::new()
        }
    }

    // ---- ASan Methods ----

    /// Instrument a memory load for ASan.
    pub fn asan_instrument_load(&mut self, addr: u64, size: u8, alignment: u8) {
        if !self.config.asan {
            return;
        }
        let access = X86ASanInstrumentedAccess::new("load", false, size, alignment, addr);
        self.asan_accesses.push(access);
        self.stats.asan_instrumented += 1;
    }

    /// Instrument a memory store for ASan.
    pub fn asan_instrument_store(&mut self, addr: u64, size: u8, alignment: u8) {
        if !self.config.asan {
            return;
        }
        let access = X86ASanInstrumentedAccess::new("store", true, size, alignment, addr);
        self.asan_accesses.push(access);
        self.stats.asan_instrumented += 1;
    }

    /// Begin instrumenting a stack frame for ASan.
    pub fn asan_begin_stack_frame(&mut self) {
        if !self.config.asan {
            return;
        }
        self.asan_stack_frame = Some(X86ASanStackFrame::new());
    }

    /// Add a stack variable to the current ASan frame.
    pub fn asan_add_stack_variable(
        &mut self,
        name: &str,
        frame_offset: i32,
        size: u32,
        alignment: u32,
    ) {
        if !self.config.asan {
            return;
        }
        let var = X86ASanStackVar::new(name, frame_offset, size, alignment);
        if let Some(ref mut frame) = self.asan_stack_frame {
            frame.add_variable(var);
            self.stats.asan_stack_vars += 1;
        }
    }

    /// Finish instrumenting the current ASan stack frame.
    pub fn asan_finish_stack_frame(&mut self) -> Vec<X86ASanShadowOp> {
        if !self.config.asan {
            return Vec::new();
        }
        if let Some(frame) = self.asan_stack_frame.take() {
            let ops = frame.compute_shadow_operations();
            self.asan_frames.push(frame);
            ops
        } else {
            Vec::new()
        }
    }

    /// Compute the shadow address for an ASan access (64-bit).
    pub fn asan_compute_shadow_64(&self, app_addr: u64) -> u64 {
        let offset = if self.config.asan_shadow_offset != 0 {
            self.config.asan_shadow_offset
        } else {
            X86_SANCODEGEN_ASAN_SHADOW_OFFSET_X64
        };
        (app_addr >> X86_SANCODEGEN_ASAN_SHADOW_SCALE) + offset
    }

    /// Compute the shadow address for an ASan access (32-bit).
    pub fn asan_compute_shadow_32(&self, app_addr: u32) -> u32 {
        (app_addr >> X86_SANCODEGEN_ASAN_SHADOW_SCALE) + X86_SANCODEGEN_ASAN_SHADOW_OFFSET_X32
    }

    // ---- MSan Methods ----

    /// Set the shadow for a named value in MSan.
    pub fn msan_set_shadow(&mut self, name: &str, shadow: X86MSanShadowValue) {
        if !self.config.msan {
            return;
        }
        self.msan_shadows.insert(name.to_string(), shadow);
        self.stats.msan_tracked += 1;
    }

    /// Get the shadow for a named value in MSan.
    pub fn msan_get_shadow(&self, name: &str) -> X86MSanShadowValue {
        if !self.config.msan {
            return X86MSanShadowValue::INITIALIZED;
        }
        self.msan_shadows
            .get(name)
            .cloned()
            .unwrap_or(X86MSanShadowValue::INITIALIZED)
    }

    /// Check if a value read from memory is fully initialized.
    pub fn msan_check_read(
        &mut self,
        addr: u64,
        size: u64,
        value_name: &str,
    ) -> Result<(), X86MSanErrorReport> {
        if !self.config.msan {
            return Ok(());
        }
        let shadow = self.msan_get_shadow(value_name);
        if shadow.is_uninitialized() {
            let origin = self.msan_origins.iter().find(|o| o.id == shadow.origin_id);
            let report = X86MSanErrorReport {
                address: addr,
                size,
                shadow,
                origin_description: origin.map(|o| o.description.clone()),
                origin_kind: origin.map(|o| o.kind.clone()),
            };
            return Err(report);
        }
        Ok(())
    }

    /// Allocate a new MSan origin.
    pub fn msan_allocate_origin(&mut self, description: &str, kind: X86MSanOriginKind) -> u32 {
        if !self.config.msan || !self.config.msan_track_origins {
            return 0;
        }
        let id = self.msan_origins.len() as u32 + 1;
        self.msan_origins
            .push(X86MSanOrigin::new(id, description, kind));
        self.stats.msan_origins += 1;
        id
    }

    /// Propagate shadow through a binary operation.
    pub fn msan_propagate_binary(
        &self,
        inst_name: &str,
        lhs_name: &str,
        rhs_name: &str,
    ) -> X86MSanShadowValue {
        let lhs = self.msan_get_shadow(lhs_name);
        let rhs = self.msan_get_shadow(rhs_name);
        let rule = self
            .msan_propagator
            .get_rule(inst_name)
            .unwrap_or(&X86MSanPropagationRule::BinaryOr);
        self.msan_propagator.propagate_binary(rule, &lhs, &rhs)
    }

    // ---- TSan Methods ----

    /// Record a TSan memory access event.
    pub fn tsan_record_access(
        &mut self,
        thread_id: u32,
        addr: u64,
        size: u8,
        is_write: bool,
    ) -> bool {
        if !self.config.tsan {
            return false;
        }
        self.tsan_global_tick += 1;
        let clock = self.tsan_global_tick;
        let event = X86TSanEvent::new(
            if is_write {
                X86TSanEventType::Write
            } else {
                X86TSanEventType::Read
            },
            thread_id,
            clock,
        )
        .at_address(addr, size);
        self.tsan_events.push(event);
        self.stats.tsan_events += 1;

        let cell = self
            .tsan_shadow
            .entry(addr)
            .or_insert_with(X86TSanShadowCell::new);
        let race = cell.record_access(thread_id, clock, is_write, size);
        if race {
            self.stats.tsan_races += 1;
        }
        race
    }

    /// Create a new TSan mutex.
    pub fn tsan_mutex_create(&mut self) -> u32 {
        if !self.config.tsan {
            return 0;
        }
        let id = self.tsan_mutexes.len() as u32 + 1;
        self.tsan_mutexes.push(X86TSanMutexState::new(id));
        id
    }

    /// Record a mutex lock (acquire).
    pub fn tsan_mutex_lock(&mut self, mutex_id: u32, thread_id: u32) {
        if !self.config.tsan {
            return;
        }
        if let Some(mutex) = self.tsan_mutexes.get_mut(mutex_id as usize - 1) {
            mutex.acquire(thread_id);
        }
    }

    /// Record a mutex unlock (release).
    pub fn tsan_mutex_unlock(&mut self, mutex_id: u32, thread_id: u32) {
        if !self.config.tsan {
            return;
        }
        if let Some(mutex) = self.tsan_mutexes.get_mut(mutex_id as usize - 1) {
            let thread_clock = X86TSanVectorClock::new(); // simplified
            mutex.release(&thread_clock);
        }
    }

    /// Get the global tick value.
    pub fn tsan_tick(&mut self) -> u64 {
        self.tsan_global_tick += 1;
        self.tsan_global_tick
    }

    // ---- UBSan Methods ----

    /// Add an overflow check.
    pub fn ubsan_check_overflow(&mut self, file: &str, line: u32, col: u32, type_descr: &str) {
        if !self.config.ubsan {
            return;
        }
        self.ubsan_checks.push(
            X86UBSanCheck::new(X86UBSanErrorKind::SignedIntegerOverflow, file, line, col)
                .with_type(type_descr),
        );
        self.stats.ubsan_checks += 1;
    }

    /// Add a division-by-zero check.
    pub fn ubsan_check_div_zero(&mut self, file: &str, line: u32, col: u32, is_float: bool) {
        if !self.config.ubsan {
            return;
        }
        let kind = if is_float {
            X86UBSanErrorKind::FloatDivideByZero
        } else {
            X86UBSanErrorKind::IntegerDivideByZero
        };
        self.ubsan_checks
            .push(X86UBSanCheck::new(kind, file, line, col));
        self.stats.ubsan_checks += 1;
    }

    /// Add a shift bounds check.
    pub fn ubsan_check_shift(&mut self, file: &str, line: u32, col: u32, rhs_width: u32) {
        if !self.config.ubsan {
            return;
        }
        let kind = if rhs_width >= X86_SANCODEGEN_UBSAN_MAX_SHIFT_WIDTH {
            X86UBSanErrorKind::ShiftExponentTooLarge
        } else {
            X86UBSanErrorKind::ShiftExponentNegative
        };
        self.ubsan_checks
            .push(X86UBSanCheck::new(kind, file, line, col));
        self.stats.ubsan_checks += 1;
    }

    /// Add a null pointer check.
    pub fn ubsan_check_null(&mut self, file: &str, line: u32, col: u32) {
        if !self.config.ubsan {
            return;
        }
        self.ubsan_checks.push(X86UBSanCheck::new(
            X86UBSanErrorKind::NullPointerArithmetic,
            file,
            line,
            col,
        ));
        self.stats.ubsan_checks += 1;
    }

    /// Add a bounds check.
    pub fn ubsan_check_bounds(&mut self, file: &str, line: u32, col: u32, type_descr: &str) {
        if !self.config.ubsan {
            return;
        }
        self.ubsan_checks.push(
            X86UBSanCheck::new(X86UBSanErrorKind::OutOfBounds, file, line, col)
                .with_type(type_descr),
        );
        self.stats.ubsan_checks += 1;
    }

    /// Add an alignment assumption check.
    pub fn ubsan_check_alignment(&mut self, file: &str, line: u32, col: u32) {
        if !self.config.ubsan {
            return;
        }
        self.ubsan_checks.push(X86UBSanCheck::new(
            X86UBSanErrorKind::AlignmentAssumption,
            file,
            line,
            col,
        ));
        self.stats.ubsan_checks += 1;
    }

    /// Add a type mismatch check.
    pub fn ubsan_check_type_mismatch(&mut self, file: &str, line: u32, col: u32, type_descr: &str) {
        if !self.config.ubsan {
            return;
        }
        self.ubsan_checks.push(
            X86UBSanCheck::new(X86UBSanErrorKind::TypeMismatch, file, line, col)
                .with_type(type_descr),
        );
        self.stats.ubsan_checks += 1;
    }

    /// Add an unreachable code check.
    pub fn ubsan_check_unreachable(&mut self, file: &str, line: u32, col: u32) {
        if !self.config.ubsan {
            return;
        }
        self.ubsan_checks.push(X86UBSanCheck::new(
            X86UBSanErrorKind::UnreachableCode,
            file,
            line,
            col,
        ));
        self.stats.ubsan_checks += 1;
    }

    // ---- LSan Methods ----

    /// Register a heap allocation for leak detection.
    pub fn lsan_register_allocation(&mut self, ptr: u64, size: u64) -> u64 {
        if !self.config.lsan {
            return 0;
        }
        let id = self.lsan_next_alloc_id;
        self.lsan_next_alloc_id += 1;
        self.lsan_allocations
            .push(X86LSanAllocRecord::new(ptr, size, id));
        self.stats.lsan_allocs += 1;
        id
    }

    /// Unregister a freed allocation.
    pub fn lsan_unregister_allocation(&mut self, ptr: u64) {
        if !self.config.lsan {
            return;
        }
        for alloc in &mut self.lsan_allocations {
            if alloc.ptr == ptr && !alloc.is_freed {
                alloc.mark_freed();
                return;
            }
        }
    }

    /// Detect leaked allocations.
    pub fn lsan_detect_leaks(&mut self, root_regions: &[(u64, u64)]) -> Vec<X86LSanLeakReport> {
        if !self.config.lsan {
            return Vec::new();
        }
        let mut leaks = Vec::new();
        // Simplified reachability analysis
        for alloc in &self.lsan_allocations {
            if alloc.is_freed {
                continue;
            }
            let mut reachable = false;
            for &(root_start, root_end) in root_regions {
                if alloc.ptr >= root_start && alloc.ptr < root_end {
                    reachable = true;
                    break;
                }
            }
            if !reachable {
                leaks.push(X86LSanLeakReport {
                    ptr: alloc.ptr,
                    size: alloc.size,
                    is_directly_lost: true,
                    alloc_id: alloc.alloc_id,
                });
            }
        }
        leaks
    }

    // ---- SafeStack Methods ----

    /// Enable SafeStack with given sizes.
    pub fn safe_stack_enable(&mut self, safe_size: u64, unsafe_size: u64) {
        self.safe_stack = X86SafeStackConfig::new(safe_size, unsafe_size);
        self.config.safe_stack = true;
    }

    /// Check if an object should be placed on the safe stack.
    pub fn safe_stack_is_safe_object(&self, name: &str, is_array: bool) -> bool {
        self.safe_stack.is_safe_object(name, is_array)
    }

    // ---- Shadow Call Stack Methods ----

    /// Push a return address onto the shadow call stack.
    pub fn scs_push(&mut self, return_address: u64, function: Option<&str>) {
        self.shadow_call_stack.push(return_address, function);
        self.stats.scs_pushes += 1;
    }

    /// Pop and verify a return address from the shadow call stack.
    pub fn scs_pop(&mut self, expected_address: u64) -> bool {
        self.shadow_call_stack.pop(expected_address)
    }

    /// Enable shadow call stack.
    pub fn scs_enable(&mut self) {
        self.shadow_call_stack.active = true;
        self.config.shadow_call_stack = true;
    }

    // ---- CFI Methods ----

    /// Add a CFI type check for indirect calls.
    pub fn cfi_add_icall_check(&mut self, type_name: &str, type_hash: u64, target_address: u64) {
        if !self.config.cfi {
            return;
        }
        self.cfi_checks
            .push(X86CFITypeCheck::new(type_name, type_hash, target_address).as_icall());
        self.stats.cfi_checks += 1;
    }

    /// Add a CFI type check for virtual calls.
    pub fn cfi_add_vcall_check(&mut self, type_name: &str, type_hash: u64, target_address: u64) {
        if !self.config.cfi {
            return;
        }
        self.cfi_checks
            .push(X86CFITypeCheck::new(type_name, type_hash, target_address).as_vcall());
        self.stats.cfi_checks += 1;
    }

    // ---- Orchestration Methods ----

    /// Begin processing a function.
    pub fn begin_function(&mut self, _name: &str) {
        self.stats.functions_processed += 1;
    }

    /// End processing a function; finalize per-function state.
    pub fn end_function(&mut self) {
        // Clear per-function MSan shadows
        self.msan_shadows.clear();
        self.asan_stack_frame = None;
    }

    /// Get combined statistics.
    pub fn get_stats(&self) -> &X86SanCodeGenStats {
        &self.stats
    }

    /// Reset all state.
    pub fn reset(&mut self) {
        self.asan_accesses.clear();
        self.asan_stack_frame = None;
        self.asan_frames.clear();
        self.msan_shadows.clear();
        self.msan_origins.clear();
        self.tsan_events.clear();
        self.tsan_shadow.clear();
        self.tsan_mutexes.clear();
        self.tsan_global_tick = 0;
        self.ubsan_checks.clear();
        self.lsan_allocations.clear();
        self.lsan_next_alloc_id = 1;
        self.shadow_call_stack.reset();
        self.cfi_checks.clear();
        self.stats = X86SanCodeGenStats::default();
    }
}

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

// ============================================================================
// Error Report Types
// ============================================================================

/// An MSan error report.
#[derive(Debug, Clone)]
pub struct X86MSanErrorReport {
    pub address: u64,
    pub size: u64,
    pub shadow: X86MSanShadowValue,
    pub origin_description: Option<String>,
    pub origin_kind: Option<X86MSanOriginKind>,
}

impl fmt::Display for X86MSanErrorReport {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "MSan: use of uninitialized value at 0x{:x}, size={}",
            self.address, self.size
        )?;
        if let Some(ref desc) = self.origin_description {
            write!(f, ", origin: {}", desc)?;
        }
        Ok(())
    }
}

/// An LSan leak report.
#[derive(Debug, Clone)]
pub struct X86LSanLeakReport {
    pub ptr: u64,
    pub size: u64,
    pub is_directly_lost: bool,
    pub alloc_id: u64,
}

impl fmt::Display for X86LSanLeakReport {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "LSan: {} leak of {} bytes at 0x{:x} (alloc #{})",
            if self.is_directly_lost {
                "direct"
            } else {
                "indirect"
            },
            self.size,
            self.ptr,
            self.alloc_id,
        )
    }
}

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

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

    // --- Config Tests ---

    #[test]
    fn test_config_defaults() {
        let cfg = X86SanCodeGenConfig::default();
        assert!(!cfg.asan);
        assert!(!cfg.msan);
        assert!(!cfg.tsan);
        assert!(!cfg.ubsan);
        assert!(!cfg.lsan);
        assert!(!cfg.safe_stack);
        assert!(!cfg.shadow_call_stack);
        assert!(!cfg.cfi);
        assert!(cfg.is_64bit);
    }

    #[test]
    fn test_config_asan_x64() {
        let cfg = X86SanCodeGenConfig::asan_x64();
        assert!(cfg.asan);
        assert_eq!(
            cfg.asan_shadow_offset,
            X86_SANCODEGEN_ASAN_SHADOW_OFFSET_X64
        );
        assert!(cfg.is_64bit);
    }

    #[test]
    fn test_config_msan_with_origins() {
        let cfg = X86SanCodeGenConfig::msan_with_origins();
        assert!(cfg.msan);
        assert!(cfg.msan_track_origins);
    }

    #[test]
    fn test_config_tsan() {
        let cfg = X86SanCodeGenConfig::tsan();
        assert!(cfg.tsan);
        assert!(!cfg.halt_on_error);
    }

    #[test]
    fn test_config_ubsan() {
        let cfg = X86SanCodeGenConfig::ubsan();
        assert!(cfg.ubsan);
        assert!(cfg.ubsan_recover);
    }

    #[test]
    fn test_config_full_sanitize() {
        let cfg = X86SanCodeGenConfig::full_sanitize();
        assert!(cfg.asan);
        assert!(cfg.ubsan);
        assert!(cfg.lsan);
        assert!(cfg.safe_stack);
        assert!(cfg.shadow_call_stack);
        assert!(cfg.cfi);
    }

    // --- ASan Instrumented Access Tests ---

    #[test]
    fn test_asan_access_creation() {
        let access = X86ASanInstrumentedAccess::new("load", false, 8, 8, 0x1000);
        assert!(!access.is_store);
        assert_eq!(access.size, 8);
        assert_eq!(access.alignment, 8);
        assert_eq!(access.address, 0x1000);
    }

    #[test]
    fn test_asan_access_with_flags() {
        let access = X86ASanInstrumentedAccess::new("store", true, 4, 4, 0x2000)
            .as_stack()
            .with_source("test.c", 42, 10);
        assert!(access.is_store);
        assert!(access.is_stack);
        assert!(access.source_loc.is_some());
        assert_eq!(access.source_loc.as_ref().unwrap().line, 42);
    }

    #[test]
    fn test_asan_access_aligned() {
        let access = X86ASanInstrumentedAccess::new("load", false, 8, 8, 0x1000);
        assert!(access.is_aligned());
        let misaligned = X86ASanInstrumentedAccess::new("load", false, 8, 4, 0x1000);
        assert!(!misaligned.is_aligned());
    }

    #[test]
    fn test_asan_compute_shadow_64() {
        let access = X86ASanInstrumentedAccess::new("load", false, 8, 8, 0x1000);
        let shadow = access.compute_shadow_address_64(X86_SANCODEGEN_ASAN_SHADOW_OFFSET_X64);
        let expected = (0x1000 >> 3) + X86_SANCODEGEN_ASAN_SHADOW_OFFSET_X64;
        assert_eq!(shadow, expected);
    }

    #[test]
    fn test_asan_compute_shadow_32() {
        let access = X86ASanInstrumentedAccess::new("load", false, 4, 4, 0x1000);
        let shadow = access.compute_shadow_address_32(X86_SANCODEGEN_ASAN_SHADOW_OFFSET_X32);
        let expected = (0x1000u32 >> 3) + X86_SANCODEGEN_ASAN_SHADOW_OFFSET_X32;
        assert_eq!(shadow, expected);
    }

    // --- ASan Stack Var Tests ---

    #[test]
    fn test_stack_var_creation() {
        let var = X86ASanStackVar::new("my_var", 16, 8, 8);
        assert_eq!(var.name, "my_var");
        assert_eq!(
            var.total_size(),
            X86_SANCODEGEN_STACK_REDZONE_SIZE + 8 + X86_SANCODEGEN_STACK_REDZONE_SIZE
        );
    }

    #[test]
    fn test_stack_var_with_options() {
        let var = X86ASanStackVar::new("v", 0, 4, 4)
            .with_use_after_scope()
            .with_use_after_return()
            .with_life_range(10, 50);
        assert!(var.use_after_scope);
        assert!(var.use_after_return);
        assert_eq!(var.life_start, 10);
        assert_eq!(var.life_end, 50);
    }

    #[test]
    fn test_stack_var_shadow_byte_partial() {
        assert_eq!(
            X86ASanStackVar::shadow_byte_for_partial(0),
            X86_ASAN_SHADOW_ADDRESSABLE
        );
        assert_eq!(
            X86ASanStackVar::shadow_byte_for_partial(3),
            X86_ASAN_SHADOW_PARTIAL3
        );
        assert_eq!(
            X86ASanStackVar::shadow_byte_for_partial(7),
            X86_ASAN_SHADOW_PARTIAL7
        );
        assert_eq!(
            X86ASanStackVar::shadow_byte_for_partial(8),
            X86_ASAN_SHADOW_ADDRESSABLE
        );
    }

    // --- ASan Stack Frame Tests ---

    #[test]
    fn test_stack_frame_add_variable() {
        let mut frame = X86ASanStackFrame::new();
        frame.add_variable(X86ASanStackVar::new("a", 0, 4, 4));
        frame.add_variable(X86ASanStackVar::new("b", 40, 8, 8));
        assert_eq!(frame.variable_count(), 2);
    }

    #[test]
    fn test_stack_frame_compute_shadow_ops() {
        let mut frame = X86ASanStackFrame::new();
        frame.add_variable(X86ASanStackVar::new("x", 0, 4, 4));
        let ops = frame.compute_shadow_operations();
        assert!(!ops.is_empty());
        // Should have at least poison and set_shadow operations
        let has_poison = ops.iter().any(|o| o.op_kind == X86ASanShadowOpKind::Poison);
        assert!(has_poison);
    }

    #[test]
    fn test_stack_frame_unpoison_all() {
        let mut frame = X86ASanStackFrame::new();
        frame.add_variable(X86ASanStackVar::new("x", 0, 4, 4));
        let ops = frame.unpoison_all();
        assert!(!ops.is_empty());
        assert_eq!(ops[0].op_kind, X86ASanShadowOpKind::Unpoison);
    }

    // --- MSan Shadow Value Tests ---

    #[test]
    fn test_msan_shadow_initialized() {
        assert!(X86MSanShadowValue::INITIALIZED.is_initialized());
        assert!(!X86MSanShadowValue::INITIALIZED.is_uninitialized());
    }

    #[test]
    fn test_msan_shadow_uninitialized() {
        assert!(!X86MSanShadowValue::UNINITIALIZED.is_initialized());
        assert!(X86MSanShadowValue::UNINITIALIZED.is_uninitialized());
    }

    #[test]
    fn test_msan_propagate_binary() {
        let lhs = X86MSanShadowValue::new(0x0F, 1);
        let rhs = X86MSanShadowValue::new(0xF0, 2);
        let result = X86MSanShadowValue::propagate_binary(&lhs, &rhs);
        assert_eq!(result.shadow, 0xFF);
        assert_eq!(result.origin_id, 1); // lhs origin since lhs shadow != 0
    }

    #[test]
    fn test_msan_truncate() {
        let val = X86MSanShadowValue::new(0xABCD, 3);
        let truncated = val.truncate(8);
        assert_eq!(truncated.shadow, 0xCD);
    }

    #[test]
    fn test_msan_sext_with_sign() {
        let val = X86MSanShadowValue::new(0x80, 5);
        let extended = val.sext(8);
        assert_eq!(extended.shadow, 0x80 | 0xFFFFFF00);
    }

    #[test]
    fn test_msan_propagator_new() {
        let prop = X86MSanShadowPropagator::new(true);
        assert!(prop.track_origins);
        assert!(prop.get_rule("add").is_some());
        assert!(prop.get_rule("icmp").is_some());
        assert!(prop.get_rule("nonexistent").is_none());
    }

    #[test]
    fn test_msan_propagator_propagate() {
        let prop = X86MSanShadowPropagator::new(false);
        let lhs = X86MSanShadowValue::new(0x01, 1);
        let rhs = X86MSanShadowValue::new(0x02, 2);
        let rule = prop.get_rule("add").unwrap();
        let result = prop.propagate_binary(rule, &lhs, &rhs);
        assert_eq!(result.shadow, 0x03);
    }

    // --- TSan Vector Clock Tests ---

    #[test]
    fn test_tsan_vector_clock_new() {
        let vc = X86TSanVectorClock::new();
        assert!(vc.is_empty());
        assert_eq!(vc.len(), 0);
    }

    #[test]
    fn test_tsan_vector_clock_tick() {
        let mut vc = X86TSanVectorClock::new();
        vc.tick(1);
        assert_eq!(vc.get(1), 1);
        vc.tick(1);
        assert_eq!(vc.get(1), 2);
    }

    #[test]
    fn test_tsan_vector_clock_set() {
        let mut vc = X86TSanVectorClock::new();
        vc.set(1, 5);
        vc.set(2, 10);
        assert_eq!(vc.get(1), 5);
        assert_eq!(vc.get(2), 10);
    }

    #[test]
    fn test_tsan_vector_clock_happens_before() {
        let mut vc1 = X86TSanVectorClock::new();
        vc1.set(1, 5);
        let mut vc2 = X86TSanVectorClock::new();
        vc2.set(1, 10);
        assert!(vc1.happens_before(&vc2));
        assert!(!vc2.happens_before(&vc1));
    }

    #[test]
    fn test_tsan_vector_clock_concurrent() {
        let mut vc1 = X86TSanVectorClock::new();
        vc1.set(1, 5);
        let mut vc2 = X86TSanVectorClock::new();
        vc2.set(2, 5);
        assert!(vc1.concurrent_with(&vc2));
    }

    #[test]
    fn test_tsan_vector_clock_join() {
        let mut vc1 = X86TSanVectorClock::new();
        vc1.set(1, 5);
        let mut vc2 = X86TSanVectorClock::new();
        vc2.set(2, 10);
        vc1.join(&vc2);
        assert_eq!(vc1.get(1), 5);
        assert_eq!(vc1.get(2), 10);
    }

    // --- TSan Shadow Cell Tests ---

    #[test]
    fn test_tsan_shadow_cell_new() {
        let cell = X86TSanShadowCell::new();
        assert_eq!(cell.last_thread, 0);
        assert_eq!(cell.read_count, 0);
    }

    #[test]
    fn test_tsan_shadow_cell_no_race_same_thread() {
        let mut cell = X86TSanShadowCell::new();
        assert!(!cell.record_access(1, 1, true, 4));
        assert!(!cell.record_access(1, 2, false, 4));
    }

    #[test]
    fn test_tsan_shadow_cell_write_write_race() {
        let mut cell = X86TSanShadowCell::new();
        cell.record_access(2, 5, true, 4);
        // Thread 1 writes at clock 3 which is <= 5, but different thread
        // In this simplified model the detection depends on implementation
        let race = cell.record_access(1, 3, true, 4);
        // This may or may not be detected depending on the comparison
        // We test that cell state is updated
        assert_eq!(cell.last_write_thread, 1);
        assert_eq!(cell.write_clock, 3);
    }

    #[test]
    fn test_tsan_shadow_cell_history_limit() {
        let mut cell = X86TSanShadowCell::new();
        for i in 0..12 {
            cell.record_access(i, i as u64, i % 2 == 0, 4);
        }
        // History should be limited to 8 entries
        assert!(cell.history.len() <= 8);
    }

    #[test]
    fn test_tsan_shadow_cell_reset() {
        let mut cell = X86TSanShadowCell::new();
        cell.record_access(1, 1, true, 4);
        cell.reset();
        assert_eq!(cell.last_thread, 0);
        assert!(cell.history.is_empty());
    }

    // --- TSan Mutex Tests ---

    #[test]
    fn test_tsan_mutex_new() {
        let m = X86TSanMutexState::new(1);
        assert_eq!(m.id, 1);
        assert!(!m.is_locked());
    }

    #[test]
    fn test_tsan_mutex_acquire_release() {
        let mut m = X86TSanMutexState::new(1);
        m.acquire(5);
        assert!(m.is_locked());
        assert_eq!(m.owner_thread, 5);
        m.release(&X86TSanVectorClock::new());
        assert!(!m.is_locked());
    }

    #[test]
    fn test_tsan_mutex_destroy() {
        let mut m = X86TSanMutexState::new(1);
        assert!(!m.is_destroyed);
        m.destroy();
        assert!(m.is_destroyed);
    }

    // --- TSan Event Tests ---

    #[test]
    fn test_tsan_event_creation() {
        let evt = X86TSanEvent::new(X86TSanEventType::Write, 1, 100);
        assert_eq!(evt.thread_id, 1);
        assert_eq!(evt.clock, 100);
    }

    #[test]
    fn test_tsan_event_with_address() {
        let evt = X86TSanEvent::new(X86TSanEventType::Read, 2, 50).at_address(0xDEAD, 8);
        assert_eq!(evt.address, 0xDEAD);
        assert_eq!(evt.size, 8);
    }

    #[test]
    fn test_tsan_event_type_display() {
        assert_eq!(format!("{}", X86TSanEventType::Read), "READ");
        assert_eq!(format!("{}", X86TSanEventType::MutexLock), "MUTEX_LOCK");
        assert_eq!(format!("{}", X86TSanEventType::AtomicFence), "ATOMIC_FENCE");
    }

    // --- UBSan Error Kind Tests ---

    #[test]
    fn test_ubsan_error_kind_display() {
        assert_eq!(
            format!("{}", X86UBSanErrorKind::IntegerDivideByZero),
            "division-by-zero"
        );
        assert_eq!(
            format!("{}", X86UBSanErrorKind::SignedIntegerOverflow),
            "signed-integer-overflow"
        );
        assert_eq!(
            format!("{}", X86UBSanErrorKind::InvalidVptr),
            "invalid-vptr"
        );
    }

    #[test]
    fn test_ubsan_check_creation() {
        let check = X86UBSanCheck::new(X86UBSanErrorKind::OutOfBounds, "foo.c", 10, 5);
        assert_eq!(check.source_loc.file, "foo.c");
        assert_eq!(check.source_loc.line, 10);
    }

    #[test]
    fn test_ubsan_check_with_type() {
        let check = X86UBSanCheck::new(X86UBSanErrorKind::TypeMismatch, "t.c", 1, 1)
            .with_type("struct Foo*");
        assert_eq!(check.type_descr.unwrap(), "struct Foo*");
    }

    // --- LSan Tests ---

    #[test]
    fn test_lsan_alloc_record_new() {
        let record = X86LSanAllocRecord::new(0x1000, 64, 1);
        assert_eq!(record.ptr, 0x1000);
        assert_eq!(record.size, 64);
        assert!(!record.is_freed);
    }

    #[test]
    fn test_lsan_alloc_record_mark_freed() {
        let mut record = X86LSanAllocRecord::new(0x1000, 64, 1);
        record.mark_freed();
        assert!(record.is_freed);
    }

    // --- SafeStack Tests ---

    #[test]
    fn test_safestack_config_default() {
        let cfg = X86SafeStackConfig::default();
        assert!(!cfg.enabled);
        assert_eq!(cfg.safe_stack_size, 1024 * 1024);
        assert_eq!(cfg.unsafe_stack_size, 8 * 1024 * 1024);
    }

    #[test]
    fn test_safestack_new() {
        let cfg = X86SafeStackConfig::new(4096, 8192);
        assert!(cfg.enabled);
        assert_eq!(cfg.safe_stack_size, 4096);
        assert_eq!(cfg.safe_stack_addr(0), 0);
    }

    #[test]
    fn test_safestack_is_safe_object() {
        let cfg = X86SafeStackConfig::new(4096, 8192);
        assert!(cfg.is_safe_object("x", false)); // scalar goes to safe
        assert!(!cfg.is_safe_object("arr", true)); // array goes to unsafe
    }

    // --- ShadowCallStack Tests ---

    #[test]
    fn test_scs_new() {
        let scs = X86ShadowCallStack::new();
        assert!(!scs.active);
        assert_eq!(scs.depth(), 0);
        assert!(scs.is_empty());
    }

    #[test]
    fn test_scs_push_pop() {
        let mut scs = X86ShadowCallStack::new();
        scs.push(0x12345678, Some("foo"));
        assert_eq!(scs.depth(), 1);
        assert_eq!(scs.peek(), Some(0x12345678));
        assert!(scs.pop(0x12345678));
        assert_eq!(scs.depth(), 0);
    }

    #[test]
    fn test_scs_pop_mismatch() {
        let mut scs = X86ShadowCallStack::new();
        scs.push(0xAAAA, None);
        assert!(!scs.pop(0xBBBB));
        assert_eq!(scs.mismatches, 1);
    }

    #[test]
    fn test_scs_reset() {
        let mut scs = X86ShadowCallStack::new();
        scs.push(0x1, None);
        scs.push(0x2, None);
        scs.reset();
        assert_eq!(scs.depth(), 0);
        assert!(scs.is_empty());
    }

    // --- CFI Tests ---

    #[test]
    fn test_cfi_type_check_new() {
        let check = X86CFITypeCheck::new("MyClass", 0xABCD, 0x4000);
        assert_eq!(check.type_name, "MyClass");
        assert_eq!(check.type_hash, 0xABCD);
    }

    #[test]
    fn test_cfi_type_check_flags() {
        let check = X86CFITypeCheck::new("Base", 0x1, 0x5000)
            .as_vcall()
            .with_bitmask(0xFF);
        assert!(check.is_vcall);
        assert!(!check.is_icall);
        assert_eq!(check.bitmask, Some(0xFF));
    }

    #[test]
    fn test_cfi_passes_bitmask() {
        let check = X86CFITypeCheck::new("T", 0x1234, 0).with_bitmask(0xFF00);
        assert!(check.passes_bitmask(0x1234));
        assert!(!check.passes_bitmask(0x5678));
    }

    // --- Source Location Tests ---

    #[test]
    fn test_source_location() {
        let loc = X86SanSourceLocation::new("main.c", 42, 7);
        assert_eq!(loc.file, "main.c");
        assert_eq!(loc.format(), "main.c:42:7");
    }

    // --- Stack Frame Tests ---

    #[test]
    fn test_stack_frame_new() {
        let sf = X86SanStackFrame::new(0x401000);
        assert_eq!(sf.ip, 0x401000);
        assert!(sf.function.is_none());
    }

    #[test]
    fn test_stack_frame_with_function() {
        let sf = X86SanStackFrame::with_function(0x401000, "main");
        assert_eq!(sf.function.as_deref(), Some("main"));
    }

    #[test]
    fn test_stack_frame_format() {
        let mut sf = X86SanStackFrame::new(0x401000);
        let formatted = sf.format();
        assert!(formatted.contains("0x401000"));
        sf.function = Some("main".to_string());
        let formatted2 = sf.format();
        assert!(formatted2.contains("main"));
    }

    // --- X86SanCodeGen Orchestrator Tests ---

    #[test]
    fn test_sancodegen_new() {
        let scg = X86SanCodeGen::new();
        assert!(!scg.config.asan);
        assert_eq!(scg.asan_accesses.len(), 0);
        assert!(scg.asan_stack_frame.is_none());
    }

    #[test]
    fn test_sancodegen_with_config() {
        let cfg = X86SanCodeGenConfig::asan_x64();
        let scg = X86SanCodeGen::with_config(cfg);
        assert!(scg.config.asan);
    }

    #[test]
    fn test_asan_instrument_load() {
        let mut scg = X86SanCodeGen::with_config(X86SanCodeGenConfig::asan_x64());
        scg.asan_instrument_load(0x1000, 8, 8);
        assert_eq!(scg.asan_accesses.len(), 1);
        assert_eq!(scg.stats.asan_instrumented, 1);
    }

    #[test]
    fn test_asan_instrument_store() {
        let mut scg = X86SanCodeGen::with_config(X86SanCodeGenConfig::asan_x64());
        scg.asan_instrument_store(0x2000, 4, 4);
        assert_eq!(scg.asan_accesses.len(), 1);
    }

    #[test]
    fn test_asan_stack_frame_lifecycle() {
        let mut scg = X86SanCodeGen::with_config(X86SanCodeGenConfig::asan_x64());
        scg.asan_begin_stack_frame();
        assert!(scg.asan_stack_frame.is_some());

        scg.asan_add_stack_variable("buf", 0, 64, 16);
        scg.asan_add_stack_variable("len", 80, 4, 4);
        assert_eq!(scg.stats.asan_stack_vars, 2);

        let ops = scg.asan_finish_stack_frame();
        assert!(scg.asan_stack_frame.is_none());
        assert!(!ops.is_empty());
        assert_eq!(scg.asan_frames.len(), 1);
    }

    #[test]
    fn test_asan_disabled_does_nothing() {
        let mut scg = X86SanCodeGen::new();
        scg.asan_instrument_load(0x1000, 8, 8);
        assert!(scg.asan_accesses.is_empty());
        scg.asan_begin_stack_frame();
        assert!(scg.asan_stack_frame.is_none());
    }

    #[test]
    fn test_asan_compute_shadow_methods() {
        let scg = X86SanCodeGen::with_config(X86SanCodeGenConfig::asan_x64());
        let shadow = scg.asan_compute_shadow_64(0x8000);
        assert_eq!(
            shadow,
            (0x8000 >> 3) + X86_SANCODEGEN_ASAN_SHADOW_OFFSET_X64
        );
    }

    #[test]
    fn test_msan_set_get_shadow() {
        let mut scg = X86SanCodeGen::with_config(X86SanCodeGenConfig::msan_with_origins());
        let sv = X86MSanShadowValue::new(0xFF, 42);
        scg.msan_set_shadow("v1", sv);
        let retrieved = scg.msan_get_shadow("v1");
        assert_eq!(retrieved.shadow, 0xFF);
        assert_eq!(retrieved.origin_id, 42);
    }

    #[test]
    fn test_msan_check_read_clean() {
        let mut scg = X86SanCodeGen::with_config(X86SanCodeGenConfig::msan_with_origins());
        scg.msan_set_shadow("x", X86MSanShadowValue::INITIALIZED);
        let result = scg.msan_check_read(0x1000, 8, "x");
        assert!(result.is_ok());
    }

    #[test]
    fn test_msan_allocate_origin() {
        let mut scg = X86SanCodeGen::with_config(X86SanCodeGenConfig::msan_with_origins());
        let id = scg.msan_allocate_origin("heap alloc", X86MSanOriginKind::HeapAllocation);
        assert_eq!(id, 1);
        let id2 = scg.msan_allocate_origin("stack var", X86MSanOriginKind::StackAllocation);
        assert_eq!(id2, 2);
        assert_eq!(scg.msan_origins.len(), 2);
    }

    #[test]
    fn test_msan_origin_no_tracking() {
        let mut scg = X86SanCodeGen::new();
        let id = scg.msan_allocate_origin("test", X86MSanOriginKind::Unknown);
        assert_eq!(id, 0);
    }

    #[test]
    fn test_msan_propagate_binary_call() {
        let mut scg = X86SanCodeGen::with_config(X86SanCodeGenConfig::msan_with_origins());
        scg.msan_set_shadow("a", X86MSanShadowValue::new(0x0F, 1));
        scg.msan_set_shadow("b", X86MSanShadowValue::new(0xF0, 2));
        let result = scg.msan_propagate_binary("add", "a", "b");
        assert_eq!(result.shadow, 0xFF);
        assert_eq!(result.origin_id, 1);
    }

    #[test]
    fn test_tsan_record_access() {
        let mut scg = X86SanCodeGen::with_config(X86SanCodeGenConfig::tsan());
        let race = scg.tsan_record_access(1, 0x4000, 4, true);
        assert!(!race); // first access never races
        assert_eq!(scg.stats.tsan_events, 1);
    }

    #[test]
    fn test_tsan_mutex_lifecycle() {
        let mut scg = X86SanCodeGen::with_config(X86SanCodeGenConfig::tsan());
        let mtx = scg.tsan_mutex_create();
        assert_eq!(mtx, 1);
        scg.tsan_mutex_lock(mtx, 5);
        scg.tsan_mutex_unlock(mtx, 5);
    }

    #[test]
    fn test_ubsan_add_checks() {
        let mut scg = X86SanCodeGen::with_config(X86SanCodeGenConfig::ubsan());
        scg.ubsan_check_overflow("test.c", 10, 1, "int");
        scg.ubsan_check_div_zero("test.c", 11, 1, false);
        scg.ubsan_check_shift("test.c", 12, 1, 64);
        scg.ubsan_check_null("test.c", 13, 1);
        assert_eq!(scg.ubsan_checks.len(), 4);
        assert_eq!(scg.stats.ubsan_checks, 4);
    }

    #[test]
    fn test_ubsan_disabled_noop() {
        let mut scg = X86SanCodeGen::new();
        scg.ubsan_check_overflow("t.c", 1, 1, "int");
        assert!(scg.ubsan_checks.is_empty());
    }

    #[test]
    fn test_lsan_register_unregister() {
        let mut scg = X86SanCodeGen::with_config(X86SanCodeGenConfig::full_sanitize());
        let id = scg.lsan_register_allocation(0xA000, 128);
        assert!(id > 0);
        assert_eq!(scg.stats.lsan_allocs, 1);
        scg.lsan_unregister_allocation(0xA000);
    }

    #[test]
    fn test_lsan_detect_leaks() {
        let mut scg = X86SanCodeGen::with_config(X86SanCodeGenConfig::full_sanitize());
        scg.lsan_register_allocation(0xDEAD, 64);
        let roots = vec![(0x0, 0x1000)]; // allocation not in roots
        let leaks = scg.lsan_detect_leaks(&roots);
        assert_eq!(leaks.len(), 1);
    }

    #[test]
    fn test_lsan_detect_no_leaks_in_root() {
        let mut scg = X86SanCodeGen::with_config(X86SanCodeGenConfig::full_sanitize());
        scg.lsan_register_allocation(0x500, 64);
        let roots = vec![(0x0, 0x1000)]; // allocation is in this range
        let leaks = scg.lsan_detect_leaks(&roots);
        assert!(leaks.is_empty());
    }

    #[test]
    fn test_safe_stack_enable() {
        let mut scg = X86SanCodeGen::new();
        assert!(!scg.config.safe_stack);
        scg.safe_stack_enable(4096, 8192);
        assert!(scg.config.safe_stack);
        assert!(scg.safe_stack.enabled);
    }

    #[test]
    fn test_scs_lifecycle() {
        let mut scg = X86SanCodeGen::new();
        scg.scs_enable();
        assert!(scg.config.shadow_call_stack);
        assert!(scg.shadow_call_stack.active);

        scg.scs_push(0x401234, Some("func"));
        assert_eq!(scg.stats.scs_pushes, 1);
        assert!(scg.scs_pop(0x401234));
    }

    #[test]
    fn test_cfi_add_checks() {
        let mut scg = X86SanCodeGen::with_config(X86SanCodeGenConfig::full_sanitize());
        scg.cfi_add_icall_check("void(int)", 0xABCD, 0x5000);
        scg.cfi_add_vcall_check("Base", 0x1234, 0x6000);
        assert_eq!(scg.cfi_checks.len(), 2);
        assert_eq!(scg.stats.cfi_checks, 2);
        assert!(scg.cfi_checks[0].is_icall);
        assert!(scg.cfi_checks[1].is_vcall);
    }

    #[test]
    fn test_begin_end_function() {
        let mut scg = X86SanCodeGen::with_config(X86SanCodeGenConfig::msan_with_origins());
        scg.msan_set_shadow("tmp", X86MSanShadowValue::INITIALIZED);
        scg.begin_function("my_func");
        assert_eq!(scg.stats.functions_processed, 1);
        scg.end_function();
        // MSan shadows should be cleared
        assert!(scg.msan_shadows.is_empty());
    }

    #[test]
    fn test_get_stats() {
        let mut scg = X86SanCodeGen::with_config(X86SanCodeGenConfig::asan_x64());
        scg.asan_instrument_load(0x100, 8, 8);
        scg.asan_instrument_store(0x200, 4, 4);
        let stats = scg.get_stats();
        assert_eq!(stats.asan_instrumented, 2);
    }

    #[test]
    fn test_reset() {
        let mut scg = X86SanCodeGen::with_config(X86SanCodeGenConfig::full_sanitize());
        scg.asan_instrument_load(0x100, 8, 8);
        scg.ubsan_check_null("f.c", 1, 1);
        scg.lsan_register_allocation(0x500, 32);
        scg.scs_push(0xDEAD, None);
        scg.reset();
        assert!(scg.asan_accesses.is_empty());
        assert!(scg.ubsan_checks.is_empty());
        assert!(scg.lsan_allocations.is_empty());
        assert_eq!(scg.stats.asan_instrumented, 0);
        assert!(scg.shadow_call_stack.is_empty());
    }

    #[test]
    fn test_shadow_op_poison() {
        let op = X86ASanShadowOp::poison(0, 32, X86_ASAN_SHADOW_STACK_LEFT);
        assert_eq!(op.op_kind, X86ASanShadowOpKind::Poison);
        assert_eq!(op.shadow_value, X86_ASAN_SHADOW_STACK_LEFT);
    }

    #[test]
    fn test_shadow_op_unpoison() {
        let op = X86ASanShadowOp::unpoison(0, 32);
        assert_eq!(op.op_kind, X86ASanShadowOpKind::Unpoison);
        assert_eq!(op.shadow_value, X86_ASAN_SHADOW_ADDRESSABLE);
    }

    #[test]
    fn test_shadow_op_set_shadow() {
        let op = X86ASanShadowOp::set_shadow(16, X86_ASAN_SHADOW_PARTIAL4);
        assert_eq!(op.op_kind, X86ASanShadowOpKind::SetShadow);
        assert_eq!(op.shadow_value, X86_ASAN_SHADOW_PARTIAL4);
    }

    #[test]
    fn test_shadow_op_check_access() {
        let op = X86ASanShadowOp::check_access(0, 8);
        assert_eq!(op.op_kind, X86ASanShadowOpKind::CheckAccess);
    }

    // --- Error Report Display Tests ---

    #[test]
    fn test_msan_error_report_display() {
        let report = X86MSanErrorReport {
            address: 0x1234,
            size: 8,
            shadow: X86MSanShadowValue::UNINITIALIZED,
            origin_description: Some("heap allocation".to_string()),
            origin_kind: Some(X86MSanOriginKind::HeapAllocation),
        };
        let s = format!("{}", report);
        assert!(s.contains("0x1234"));
        assert!(s.contains("uninitialized"));
        assert!(s.contains("heap allocation"));
    }

    #[test]
    fn test_lsan_leak_report_display() {
        let report = X86LSanLeakReport {
            ptr: 0xDEAD,
            size: 128,
            is_directly_lost: true,
            alloc_id: 7,
        };
        let s = format!("{}", report);
        assert!(s.contains("0xdead"));
        assert!(s.contains("128 bytes"));
        assert!(s.contains("alloc #7"));
    }

    #[test]
    fn test_origin_kind_display() {
        assert_eq!(format!("{}", X86MSanOriginKind::HeapAllocation), "heap");
        assert_eq!(format!("{}", X86MSanOriginKind::StackAllocation), "stack");
        assert_eq!(
            format!("{}", X86MSanOriginKind::FunctionParameter),
            "parameter"
        );
    }

    // --- Integration / Workflow Tests ---

    #[test]
    fn test_full_asan_workflow() {
        let mut scg = X86SanCodeGen::with_config(X86SanCodeGenConfig::asan_x64());
        scg.begin_function("example");

        // Simulate instrumenting a function with stack vars + accesses
        scg.asan_begin_stack_frame();
        scg.asan_add_stack_variable("buffer", 0, 256, 16);
        scg.asan_add_stack_variable("index", 272, 4, 4);
        scg.asan_finish_stack_frame();

        scg.asan_instrument_load(0x4000, 8, 8);
        scg.asan_instrument_store(0x4008, 4, 4);

        scg.end_function();
        assert_eq!(scg.stats.functions_processed, 1);
        assert_eq!(scg.asan_frames.len(), 1);
        assert_eq!(scg.stats.asan_stack_vars, 2);
        assert_eq!(scg.stats.asan_instrumented, 2);
    }

    #[test]
    fn test_full_ubsan_workflow() {
        let mut scg = X86SanCodeGen::with_config(X86SanCodeGenConfig::ubsan());
        scg.begin_function("compute");

        scg.ubsan_check_overflow("compute.c", 5, 10, "int");
        scg.ubsan_check_div_zero("compute.c", 7, 12, false);
        scg.ubsan_check_bounds("compute.c", 9, 5, "int*");
        scg.ubsan_check_unreachable("compute.c", 15, 1);

        scg.end_function();
        assert_eq!(scg.stats.functions_processed, 1);
        assert_eq!(scg.stats.ubsan_checks, 4);
    }

    #[test]
    fn test_combined_sanitizer_workflow() {
        let mut scg = X86SanCodeGen::with_config(X86SanCodeGenConfig::full_sanitize());
        scg.begin_function("multi_san");

        // ASan
        scg.asan_instrument_load(0x1000, 8, 8);

        // UBSan
        scg.ubsan_check_null("multi.c", 3, 1);

        // LSan
        scg.lsan_register_allocation(0x5000, 64);

        // CFI
        scg.cfi_add_icall_check("fnptr", 0x42, 0x7000);

        // SCS
        scg.scs_enable();
        scg.scs_push(0x401000, Some("multi_san"));

        scg.end_function();
        assert_eq!(scg.stats.functions_processed, 1);
        assert!(scg.stats.asan_instrumented > 0);
        assert!(scg.stats.ubsan_checks > 0);
        assert!(scg.stats.lsan_allocs > 0);
        assert!(scg.stats.cfi_checks > 0);
        assert!(scg.stats.scs_pushes > 0);
    }

    #[test]
    fn test_tsan_detailed_workflow() {
        let mut scg = X86SanCodeGen::with_config(X86SanCodeGenConfig::tsan());

        // Thread 1 writes to address
        scg.tsan_record_access(1, 0x4000, 4, true);
        // Thread 2 reads from same address (potential race)
        scg.tsan_record_access(2, 0x4000, 4, false);

        assert_eq!(scg.stats.tsan_events, 2);

        // Create and use a mutex
        let mtx = scg.tsan_mutex_create();
        scg.tsan_mutex_lock(mtx, 3);
        scg.tsan_mutex_unlock(mtx, 3);

        assert_eq!(scg.tsan_mutexes.len(), 1);
    }

    #[test]
    fn test_msan_origin_kinds_display() {
        let kinds = vec![
            X86MSanOriginKind::HeapAllocation,
            X86MSanOriginKind::StackAllocation,
            X86MSanOriginKind::GlobalVariable,
            X86MSanOriginKind::FunctionParameter,
            X86MSanOriginKind::Instruction,
            X86MSanOriginKind::Deallocated,
            X86MSanOriginKind::Unknown,
        ];
        for k in kinds {
            let s = format!("{}", k);
            assert!(!s.is_empty());
        }
    }

    #[test]
    fn test_msan_propagator_register_custom() {
        let mut prop = X86MSanShadowPropagator::new(false);
        prop.register_rule(
            "my_op",
            X86MSanPropagationRule::Custom("my_rule".to_string()),
        );
        let rule = prop.get_rule("my_op").unwrap();
        match rule {
            X86MSanPropagationRule::Custom(name) => assert_eq!(name, "my_rule"),
            _ => panic!("expected custom rule"),
        }
    }

    #[test]
    fn test_shadow_constants() {
        assert_eq!(X86_SANCODEGEN_ASAN_SHADOW_SCALE, 3);
        assert_eq!(X86_SANCODEGEN_ASAN_SHADOW_GRANULARITY, 8);
        assert_eq!(X86_SANCODEGEN_STACK_REDZONE_SIZE, 32);
        assert_eq!(X86_ASAN_SHADOW_ADDRESSABLE, 0);
        assert_eq!(X86_ASAN_SHADOW_STACK_LEFT, 0xF1);
        assert_eq!(X86_ASAN_SHADOW_FREED, 0xFD);
    }

    #[test]
    fn test_msan_shadow_value_bitcast() {
        let val = X86MSanShadowValue::new(0xABCD1234, 10);
        let cast = val.bitcast();
        assert_eq!(cast.shadow, val.shadow);
        assert_eq!(cast.origin_id, val.origin_id);
    }

    #[test]
    fn test_vector_clock_max_clock() {
        let mut vc = X86TSanVectorClock::new();
        vc.set(1, 5);
        vc.set(2, 12);
        vc.set(3, 7);
        assert_eq!(vc.max_clock(), 12);
    }

    #[test]
    fn test_vector_clock_default() {
        let vc = X86TSanVectorClock::default();
        assert!(vc.is_empty());
    }

    #[test]
    fn test_tsan_global_tick() {
        let mut scg = X86SanCodeGen::with_config(X86SanCodeGenConfig::tsan());
        let t1 = scg.tsan_tick();
        let t2 = scg.tsan_tick();
        assert!(t2 > t1);
    }

    #[test]
    fn test_ubsan_all_error_kinds_display() {
        // Verify all error kinds have display strings
        let kinds = [
            X86UBSanErrorKind::IntegerDivideByZero,
            X86UBSanErrorKind::FloatDivideByZero,
            X86UBSanErrorKind::ShiftExponentNegative,
            X86UBSanErrorKind::ShiftExponentTooLarge,
            X86UBSanErrorKind::SignedIntegerOverflow,
            X86UBSanErrorKind::PointerOverflow,
            X86UBSanErrorKind::NullPointerArithmetic,
            X86UBSanErrorKind::VLABoundNotPositive,
            X86UBSanErrorKind::OutOfBounds,
            X86UBSanErrorKind::TypeMismatch,
            X86UBSanErrorKind::AlignmentAssumption,
            X86UBSanErrorKind::UnreachableCode,
            X86UBSanErrorKind::MissingReturn,
            X86UBSanErrorKind::NonNullViolation,
            X86UBSanErrorKind::BuiltinUnreachable,
            X86UBSanErrorKind::InvalidBool,
            X86UBSanErrorKind::InvalidEnum,
            X86UBSanErrorKind::ImplicitConversionTruncation,
            X86UBSanErrorKind::ImplicitConversionSignChange,
            X86UBSanErrorKind::NegativeArraySize,
            X86UBSanErrorKind::FunctionTypeMismatch,
            X86UBSanErrorKind::InvalidVptr,
        ];
        for kind in &kinds {
            let s = format!("{}", kind);
            assert!(!s.is_empty());
        }
    }

    #[test]
    fn test_msan_propagator_all_builtin_rules() {
        let prop = X86MSanShadowPropagator::default();
        // All these should be registered
        assert!(prop.get_rule("add").is_some());
        assert!(prop.get_rule("sub").is_some());
        assert!(prop.get_rule("mul").is_some());
        assert!(prop.get_rule("udiv").is_some());
        assert!(prop.get_rule("sdiv").is_some());
        assert!(prop.get_rule("urem").is_some());
        assert!(prop.get_rule("srem").is_some());
        assert!(prop.get_rule("and").is_some());
        assert!(prop.get_rule("or").is_some());
        assert!(prop.get_rule("xor").is_some());
        assert!(prop.get_rule("shl").is_some());
        assert!(prop.get_rule("lshr").is_some());
        assert!(prop.get_rule("ashr").is_some());
        assert!(prop.get_rule("select").is_some());
        assert!(prop.get_rule("phi").is_some());
        assert!(prop.get_rule("icmp").is_some());
        assert!(prop.get_rule("fadd").is_some());
    }

    #[test]
    fn test_msan_propagator_default_no_origins() {
        let prop = X86MSanShadowPropagator::default();
        assert!(!prop.track_origins);
    }
}