llvm-native-core 0.1.10

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
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
//! C++20 Modules — Complete X86 Target Implementation
//!
//! Full implementation of the C++20 Modules TS for X86 targets, covering
//! module interface/implementation units, partitions, fragments, header units,
//! BMI serialization, module maps, dependency management, ownership tracking,
//! linkage rules, import resolution, caching, and standard library modules.
//!
//! Clean-room behavioral reconstruction from:
//! - ISO/IEC 14882:2020 §10 (Modules)
//! - Published Clang modules documentation
//! - System V AMD64 ABI
//! - Intel® 64 and IA-32 Architectures Software Developer's Manual
//!
//! Sections:
//!   Section 1:  X86Modules                 — Orchestrator / facade
//!   Section 2:  X86ModuleCompiler          — Module compilation pipeline
//!   Section 3:  X86ModuleMap               — Module map handling (.modulemap)
//!   Section 4:  X86ModuleDependency        — Dependency graph and ordering
//!   Section 5:  X86BMITransfer             — BMI serialization/deserialization
//!   Section 6:  X86ModuleCache             — On-disk cache management
//!   Section 7:  X86ModuleOwnership         — Ownership and reachability
//!   Section 8:  X86ModuleLinkage           — Module linkage semantics
//!   Section 9:  X86ModuleImport            — Import declaration handling
//!   Section 10: X86ModuleStandardLibrary   — Standard library modules
//!   Section 11: Tests                      — Complete test suite

// ═══════════════════════════════════════════════════════════════════════════════
// Imports
// ═══════════════════════════════════════════════════════════════════════════════

use std::collections::{HashMap, HashSet};
use std::fs;
use std::io::{BufReader, BufWriter, Read, Write};
use std::path::{Path, PathBuf};

use crate::clang::cpp_modules::{
    BmiFile, GlobalModuleFragment, HeaderUnitSynthesizer, ModuleDecl, ModuleDependencyGraph,
    ModuleImport, ModuleKind, ModuleMap, ModuleMapFile, ModuleName, ModuleOwnership,
    ModuleValidator, PrivateModuleFragment,
};
use crate::clang::{CLangStandard, ClangOptions};
use crate::x86::{
    x86_calling_convention::X86CallingConvention, x86_frame_lowering::X86FrameLowering,
    x86_target_machine::X86TargetMachine, X86_STACK_ALIGNMENT_64,
};

// ═══════════════════════════════════════════════════════════════════════════════
// X86 Module Constants
// ═══════════════════════════════════════════════════════════════════════════════

/// X86 module cache directory prefix.
pub const X86_MODULE_CACHE_DIR: &str = ".x86_module_cache";

/// X86 BMI file extension.
pub const X86_BMI_EXTENSION: &str = ".pcm";

/// X86 module map file name.
pub const X86_MODULE_MAP_FILE: &str = "module.modulemap";

/// Maximum number of cached BMI versions to keep.
pub const X86_CACHE_MAX_VERSIONS: usize = 5;

/// Maximum module cache size in bytes (default: 1 GiB).
pub const X86_CACHE_MAX_SIZE_BYTES: u64 = 1_073_741_824;

/// X86 module hash algorithm identifier.
pub const X86_MODULE_HASH_ALGORITHM: &str = "sha256";

/// X86 BMI signature magic.
pub const X86_BMI_SIGNATURE_MAGIC: &[u8; 4] = b"X86M";

/// X86 current BMI format version for X86-extended BMIs.
pub const X86_BMI_EXTENDED_VERSION: u32 = 2;

// ═══════════════════════════════════════════════════════════════════════════════
// Section 1: X86Modules — Orchestrator / Facade
// ═══════════════════════════════════════════════════════════════════════════════

/// `X86Modules` is the top-level orchestrator for all C++20 module operations
/// on X86 targets. It owns the compiler, dependency tracker, BMI transfer,
/// cache, ownership, linkage, import resolution, and standard library support.
///
/// This struct serves as the primary entry point for module-aware compilation
/// and is designed to be embedded in a Clang driver or build system.
pub struct X86Modules {
    /// The module compiler.
    pub compiler: X86ModuleCompiler,
    /// The module map for name resolution.
    pub module_map: X86ModuleMap,
    /// The module dependency graph.
    pub dependency: X86ModuleDependency,
    /// BMI serialization and transfer.
    pub bmi_transfer: X86BMITransfer,
    /// On-disk module cache.
    pub cache: X86ModuleCache,
    /// Module ownership and reachability tracker.
    pub ownership: X86ModuleOwnership,
    /// Module linkage manager.
    pub linkage: X86ModuleLinkage,
    /// Import declaration handler.
    pub import_handler: X86ModuleImport,
    /// Standard library modules.
    pub std_modules: X86ModuleStandardLibrary,
    /// Target machine for X86 code generation.
    pub target_machine: X86TargetMachine,
    /// X86 calling convention info.
    pub calling_convention: X86CallingConvention,
    /// X86 frame lowering info.
    pub frame_lowering: X86FrameLowering,
    /// Compiler options.
    pub options: ClangOptions,
    /// Whether modules are enabled.
    pub modules_enabled: bool,
    /// Current list of pending compilation units.
    pending_units: Vec<X86CompilationUnit>,
    /// Statistics counter.
    stats: X86ModuleStats,
}

/// Statistics for module operations.
#[derive(Debug, Clone, Default)]
pub struct X86ModuleStats {
    /// Number of modules compiled.
    pub modules_compiled: usize,
    /// Number of BMIs imported.
    pub bmis_imported: usize,
    /// Number of BMIs exported.
    pub bmis_exported: usize,
    /// Number of cache hits.
    pub cache_hits: usize,
    /// Number of cache misses.
    pub cache_misses: usize,
    /// Total BMI bytes transferred.
    pub total_bmi_bytes: u64,
    /// Compilation time in milliseconds (approximate).
    pub compilation_time_ms: u64,
}

/// A unit of compilation for the module system.
#[derive(Debug, Clone)]
pub struct X86CompilationUnit {
    /// Source file path.
    pub source_path: PathBuf,
    /// Module declaration (if this is a module unit).
    pub module_decl: Option<ModuleDecl>,
    /// The module interface or implementation kind.
    pub unit_kind: X86CompilationUnitKind,
    /// Target triple for this unit.
    pub target_triple: String,
    /// Include paths for this unit.
    pub include_paths: Vec<PathBuf>,
    /// Preprocessor defines.
    pub defines: Vec<(String, Option<String>)>,
    /// Required module imports.
    pub required_imports: Vec<ModuleImport>,
}

/// Kinds of compilation units supported by the X86 module system.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86CompilationUnitKind {
    /// A module interface unit (produces a BMI).
    ModuleInterface,
    /// A module implementation unit.
    ModuleImplementation,
    /// A module partition interface.
    ModulePartitionInterface,
    /// A module partition implementation.
    ModulePartitionImplementation,
    /// A header unit.
    HeaderUnit,
    /// A non-modular translation unit.
    NonModular,
    /// A global module fragment compilation.
    GlobalFragment,
}

impl X86Modules {
    /// Create a new X86Modules instance with the given options and target.
    pub fn new(options: ClangOptions, target_machine: X86TargetMachine) -> Self {
        Self {
            compiler: X86ModuleCompiler::new(options.clone()),
            module_map: X86ModuleMap::new(),
            dependency: X86ModuleDependency::new(),
            bmi_transfer: X86BMITransfer::new(),
            cache: X86ModuleCache::new(&options),
            ownership: X86ModuleOwnership::new(),
            linkage: X86ModuleLinkage::new(&options),
            import_handler: X86ModuleImport::new(),
            std_modules: X86ModuleStandardLibrary::new(),
            target_machine,
            calling_convention: X86CallingConvention::X86_64_SysV,
            frame_lowering: X86FrameLowering::default(),
            options,
            modules_enabled: true,
            pending_units: Vec::new(),
            stats: X86ModuleStats::default(),
        }
    }

    /// Enable or disable modules support.
    pub fn set_modules_enabled(&mut self, enabled: bool) {
        self.modules_enabled = enabled;
    }

    /// Add a compilation unit to the pending queue.
    pub fn add_compilation_unit(&mut self, unit: X86CompilationUnit) {
        self.pending_units.push(unit);
    }

    /// Add multiple compilation units.
    pub fn add_compilation_units(&mut self, units: impl IntoIterator<Item = X86CompilationUnit>) {
        self.pending_units.extend(units);
    }

    /// Process all pending compilation units in dependency order.
    /// Returns a list of compiled BMI paths and any errors encountered.
    pub fn process_all_units(&mut self) -> Result<Vec<X86CompilationResult>, String> {
        if !self.modules_enabled {
            return Ok(Vec::new());
        }

        // Build the dependency graph from pending units
        self.dependency
            .build_from_units(&self.pending_units, &self.module_map);

        // Detect cycles
        if let Some(cycle) = self.dependency.detect_cycle() {
            return Err(format!(
                "circular module dependency detected: {}",
                cycle.join(" -> ")
            ));
        }

        // Topologically sort units for compilation order
        let order = self.dependency.topological_sort()?;
        let mut results = Vec::new();

        // Collect unit indices by module name (clone what we need to avoid borrow conflicts)
        let unit_by_name: HashMap<String, usize> = self
            .pending_units
            .iter()
            .enumerate()
            .filter_map(|(i, u)| u.module_decl.as_ref().map(|m| (m.name.to_string(), i)))
            .collect();

        for unit_name in &order {
            if let Some(idx) = unit_by_name.get(unit_name) {
                let unit = self.pending_units[*idx].clone();
                let result = self.compile_unit(&unit)?;
                results.push(result);
            }
        }

        self.pending_units.clear();
        Ok(results)
    }

    /// Compile a single compilation unit.
    fn compile_unit(&mut self, unit: &X86CompilationUnit) -> Result<X86CompilationResult, String> {
        // Try cache first
        if let Some(decl) = &unit.module_decl {
            let module_name = decl.name.to_string();
            if let Some(cached_bmi) = self.cache.lookup(&module_name) {
                self.stats.cache_hits += 1;
                return Ok(X86CompilationResult {
                    module_name: module_name.clone(),
                    bmi_path: Some(cached_bmi),
                    from_cache: true,
                    unit_kind: unit.unit_kind,
                });
            }
            self.stats.cache_misses += 1;
        }

        // Compile the module
        let bmi = self
            .compiler
            .compile_unit(unit, &self.module_map, &self.import_handler)?;

        // Store in cache
        if bmi.bmi_path.is_some() {
            self.cache.store(unit, &bmi)?;
        }

        // Update ownership and linkage
        if let Some(decl) = &unit.module_decl {
            self.ownership
                .register_module(decl.name.clone(), unit.unit_kind);
            self.linkage
                .register_module(&decl.name, unit.unit_kind, &self.options);
        }

        Ok(bmi)
    }

    /// Import a module by name. Resolves the module and adds the import to
    /// the dependency graph.
    pub fn import_module(&mut self, import: &ModuleImport) -> Result<(), String> {
        self.import_handler
            .resolve_import(import, &self.module_map, &self.cache)?;
        if let Some(dep) = self.module_map.resolve_name(&import.name.to_string()) {
            let current = self
                .pending_units
                .last()
                .and_then(|u| u.module_decl.as_ref())
                .map(|d| d.name.to_string())
                .unwrap_or_default();
            if !current.is_empty() {
                self.dependency.add_dependency(&current, &dep);
            }
        }
        Ok(())
    }

    /// Get module compilation statistics.
    pub fn stats(&self) -> &X86ModuleStats {
        &self.stats
    }

    /// Reset the module system state (for testing/benchmarking).
    pub fn reset(&mut self) {
        self.compiler = X86ModuleCompiler::new(self.options.clone());
        self.module_map = X86ModuleMap::new();
        self.dependency = X86ModuleDependency::new();
        self.bmi_transfer = X86BMITransfer::new();
        self.cache = X86ModuleCache::new(&self.options);
        self.ownership = X86ModuleOwnership::new();
        self.linkage = X86ModuleLinkage::new(&self.options);
        self.import_handler = X86ModuleImport::new();
        self.pending_units.clear();
        self.stats = X86ModuleStats::default();
    }

    /// Validate the entire module configuration.
    pub fn validate(&self) -> Vec<String> {
        let mut errors = Vec::new();
        errors.extend(self.dependency.validate());
        errors.extend(self.module_map.validate());
        errors.extend(self.ownership.validate());
        errors.extend(self.linkage.validate());
        errors
    }
}

/// Result of compiling a single module unit.
#[derive(Debug, Clone)]
pub struct X86CompilationResult {
    /// The module's name.
    pub module_name: String,
    /// Path to the generated BMI.
    pub bmi_path: Option<PathBuf>,
    /// Whether the result came from cache.
    pub from_cache: bool,
    /// The kind of unit that was compiled.
    pub unit_kind: X86CompilationUnitKind,
}

impl X86CompilationResult {
    /// Create a new compilation result.
    pub fn new(
        module_name: &str,
        bmi_path: Option<PathBuf>,
        from_cache: bool,
        unit_kind: X86CompilationUnitKind,
    ) -> Self {
        Self {
            module_name: module_name.to_string(),
            bmi_path,
            from_cache,
            unit_kind,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Section 2: X86ModuleCompiler — Module Compilation Pipeline
// ═══════════════════════════════════════════════════════════════════════════════

/// `X86ModuleCompiler` handles parsing and compilation of all C++20 module
/// unit kinds: interface units, implementation units, partitions (interface
/// and implementation), global module fragments, and private module fragments.
/// It also processes header unit imports.
pub struct X86ModuleCompiler {
    /// Whether to emit verbose diagnostics.
    pub verbose: bool,
    /// The output directory for compiled BMIs.
    pub output_dir: PathBuf,
    /// Standard language version.
    pub standard: CLangStandard,
    /// Pending parsed module declarations.
    parsed_decls: Vec<ModuleDecl>,
    /// Current global module fragment state.
    current_global_fragment: Option<GlobalModuleFragment>,
    /// Current private module fragment state.
    current_private_fragment: Option<PrivateModuleFragment>,
    /// Header unit synthesizer for `import <header>;` processing.
    header_synthesizer: HeaderUnitSynthesizer,
    /// Partition registry: maps (module_name, partition_name) to compilation units.
    partition_registry: HashMap<(String, String), X86CompilationUnit>,
    /// The active module being compiled.
    active_module: Option<ModuleDecl>,
    /// Accumulated compilation errors.
    errors: Vec<String>,
    /// Module validator for C++20 compliance checking.
    validator: ModuleValidator,
}

impl X86ModuleCompiler {
    /// Create a new X86ModuleCompiler with default settings.
    pub fn new(options: ClangOptions) -> Self {
        Self {
            verbose: options.verbose,
            output_dir: PathBuf::from(X86_MODULE_CACHE_DIR),
            standard: options.standard,
            parsed_decls: Vec::new(),
            current_global_fragment: None,
            current_private_fragment: None,
            header_synthesizer: HeaderUnitSynthesizer::new(options.includes.clone()),
            partition_registry: HashMap::new(),
            active_module: None,
            errors: Vec::new(),
            validator: ModuleValidator::new(),
        }
    }

    /// Set the output directory for compiled BMIs.
    pub fn set_output_dir(&mut self, dir: &Path) {
        self.output_dir = dir.to_path_buf();
    }

    /// Parse a module declaration from source text.
    /// Handles:
    /// - `export module name;` — module interface
    /// - `module name;` — module implementation
    /// - `export module name:part;` — module interface partition
    /// - `module name:part;` — module implementation partition
    /// - `module;` — global module fragment
    /// - `module :private;` — private module fragment
    pub fn parse_module_decl(&mut self, source: &str) -> Option<ModuleDecl> {
        let decl = crate::clang::cpp_modules::parse_module_decl(source)?;

        // Validate the declaration
        if !self.validator.validate_module_decl(&decl) {
            self.errors.extend(self.validator.errors().iter().cloned());
            return None;
        }

        self.active_module = Some(decl.clone());
        self.parsed_decls.push(decl.clone());
        Some(decl)
    }

    /// Parse an import declaration from source text.
    /// Handles:
    /// - `import name;` — module import
    /// - `export import name;` — re-export
    /// - `import <header>;` — header unit import
    /// - `import name:part;` — partition import
    pub fn parse_import_decl(&mut self, source: &str) -> Option<ModuleImport> {
        let import = crate::clang::cpp_modules::parse_import_decl(source)?;
        Some(import)
    }

    /// Register a module partition interface or implementation.
    /// Partitions are named sub-components of a module that can be imported
    /// independently but belong to the same logical module.
    pub fn register_partition(
        &mut self,
        module_name: &str,
        partition_name: &str,
        unit: X86CompilationUnit,
    ) {
        self.partition_registry
            .insert((module_name.to_string(), partition_name.to_string()), unit);
    }

    /// Get a registered partition.
    pub fn get_partition(
        &self,
        module_name: &str,
        partition_name: &str,
    ) -> Option<&X86CompilationUnit> {
        self.partition_registry
            .get(&(module_name.to_string(), partition_name.to_string()))
    }

    /// Check if a partition is registered.
    pub fn has_partition(&self, module_name: &str, partition_name: &str) -> bool {
        self.partition_registry
            .contains_key(&(module_name.to_string(), partition_name.to_string()))
    }

    /// List all partitions of a module.
    pub fn partitions_of(&self, module_name: &str) -> Vec<String> {
        let prefix = module_name.to_string();
        self.partition_registry
            .keys()
            .filter(|(m, _)| m == &prefix)
            .map(|(_, p)| p.clone())
            .collect()
    }

    /// Begin a global module fragment section (`module;` before the module declaration).
    /// The global module fragment is where `#include` directives and pre-module
    /// declarations live. It must appear before any module declaration.
    pub fn begin_global_fragment(&mut self) -> Result<(), String> {
        if self.active_module.is_some() {
            return Err(
                "global module fragment must appear before any module declaration".to_string(),
            );
        }
        if self.current_global_fragment.is_some() {
            return Err("global module fragment already open".to_string());
        }
        self.current_global_fragment = Some(GlobalModuleFragment::new());
        Ok(())
    }

    /// Add a declaration to the global module fragment.
    pub fn add_to_global_fragment(&mut self, decl: &str) -> Result<(), String> {
        if let Some(ref mut gmf) = self.current_global_fragment {
            gmf.add_decl(decl);
            Ok(())
        } else {
            Err("no global module fragment is active".to_string())
        }
    }

    /// Add an include directive to the global module fragment.
    pub fn add_include_in_global_fragment(&mut self, header: &str) -> Result<(), String> {
        if let Some(ref mut gmf) = self.current_global_fragment {
            gmf.add_include(header);
            Ok(())
        } else {
            Err("no global module fragment is active".to_string())
        }
    }

    /// End the global module fragment section.
    /// Returns the collected declarations and includes.
    pub fn end_global_fragment(&mut self) -> Result<Option<GlobalModuleFragment>, String> {
        let gmf = self.current_global_fragment.take();
        if gmf.as_ref().map(|g| g.is_empty()).unwrap_or(true) {
            self.errors.push(
                "global module fragment must contain at least one declaration or include".into(),
            );
        }
        Ok(gmf)
    }

    /// Begin a private module fragment section (`module :private;`).
    /// The private module fragment appears at the end of a module interface
    /// unit and contains declarations that are only visible within the module
    /// but not exported. Per C++20 §10.3.2, it must be the last declaration.
    pub fn begin_private_fragment(&mut self) -> Result<(), String> {
        if self.active_module.is_none() {
            return Err(
                "private module fragment must appear inside a module interface unit".to_string(),
            );
        }
        if self.current_private_fragment.is_some() {
            return Err("private module fragment already open".to_string());
        }
        let active = self.active_module.as_ref().unwrap();
        if !active.kind.is_exported() {
            return Err(
                "private module fragment is only allowed in module interface units".to_string(),
            );
        }
        self.current_private_fragment = Some(PrivateModuleFragment::new());
        Ok(())
    }

    /// Add a declaration to the private module fragment.
    pub fn add_to_private_fragment(&mut self, decl: &str) -> Result<(), String> {
        if let Some(ref mut pmf) = self.current_private_fragment {
            pmf.add_decl(decl);
            Ok(())
        } else {
            Err("no private module fragment is active".to_string())
        }
    }

    /// End (close) the private module fragment section.
    /// After this, no more declarations can be added to the TU.
    pub fn end_private_fragment(&mut self) -> Result<(), String> {
        if let Some(mut pmf) = self.current_private_fragment.take() {
            pmf.close();
            Ok(())
        } else {
            Err("no private module fragment to close".to_string())
        }
    }

    /// Process a header unit import (`import <header>;`).
    /// Synthesizes a module interface for the header if necessary.
    pub fn process_header_unit(&mut self, header_name: &str) -> Result<ModuleDecl, String> {
        let info = self.header_synthesizer.synthesize_header_unit(header_name);
        let name = info.name.clone();
        let decl = ModuleDecl {
            name,
            kind: ModuleKind::ModuleInterface,
            partition: None,
            source_loc: Some(format!("<{}>", header_name)),
        };
        Ok(decl)
    }

    /// Synthesize a BMI for a header unit.
    pub fn synthesize_header_bmi(&mut self, header: &str) -> String {
        self.header_synthesizer.generate_synthesized_bmi(header)
    }

    /// Check if a header has already been synthesized as a header unit.
    pub fn is_header_synthesized(&self, header: &str) -> bool {
        self.header_synthesizer.is_synthesized(header)
    }

    /// Compile a single compilation unit into a BMI.
    pub fn compile_unit(
        &mut self,
        unit: &X86CompilationUnit,
        module_map: &X86ModuleMap,
        import_handler: &X86ModuleImport,
    ) -> Result<X86CompilationResult, String> {
        let decl = unit
            .module_decl
            .as_ref()
            .ok_or("compilation unit has no module declaration")?;

        let module_name = decl.name.to_string();

        match unit.unit_kind {
            X86CompilationUnitKind::ModuleInterface
            | X86CompilationUnitKind::ModulePartitionInterface => {
                // Generate a BMI for interface units
                let bmi_path = self.output_dir.join(format!(
                    "{}{}",
                    module_name.replace(':', "_"),
                    X86_BMI_EXTENSION
                ));

                // Verify all required imports are available
                for import in &unit.required_imports {
                    if !import.is_header_unit {
                        let name = import.name.to_string();
                        if let Some(resolved) = module_map.resolve_name(&name) {
                            if !import_handler.is_import_resolved(&resolved) {
                                return Err(format!(
                                    "module '{}' requires unresolved import '{}'",
                                    module_name, name
                                ));
                            }
                        } else {
                            return Err(format!(
                                "module '{}' imports unknown module '{}'",
                                module_name, name
                            ));
                        }
                    }
                }

                // Write the BMI file
                if !self.output_dir.exists() {
                    fs::create_dir_all(&self.output_dir)
                        .map_err(|e| format!("failed to create output directory: {}", e))?;
                }

                // Emit a placeholder BMI
                let bmi_content = self.emit_bmi_content(decl, &unit.required_imports);
                fs::write(&bmi_path, &bmi_content)
                    .map_err(|e| format!("failed to write BMI: {}", e))?;

                if self.verbose {
                    eprintln!(
                        "info: compiled module interface '{}' → {}",
                        module_name,
                        bmi_path.display()
                    );
                }

                Ok(X86CompilationResult::new(
                    &module_name,
                    Some(bmi_path),
                    false,
                    unit.unit_kind,
                ))
            }
            X86CompilationUnitKind::ModuleImplementation
            | X86CompilationUnitKind::ModulePartitionImplementation => {
                // Implementation units don't produce BMIs but require the interface BMI
                if self.verbose {
                    eprintln!("info: compiled module implementation '{}'", module_name);
                }
                Ok(X86CompilationResult::new(
                    &module_name,
                    None,
                    false,
                    unit.unit_kind,
                ))
            }
            X86CompilationUnitKind::HeaderUnit => {
                let bmi_path = self.output_dir.join(format!(
                    "{}{}",
                    module_name.replace(['/', '\\', '.', '<', '>'], "_"),
                    X86_BMI_EXTENSION
                ));
                let bmi_content = self.synthesize_header_bmi(&module_name);
                fs::write(&bmi_path, &bmi_content)
                    .map_err(|e| format!("failed to write header BMI: {}", e))?;

                Ok(X86CompilationResult::new(
                    &module_name,
                    Some(bmi_path),
                    false,
                    unit.unit_kind,
                ))
            }
            X86CompilationUnitKind::NonModular => {
                // Non-modular units are compiled directly
                Ok(X86CompilationResult::new(
                    &module_name,
                    None,
                    false,
                    unit.unit_kind,
                ))
            }
            X86CompilationUnitKind::GlobalFragment => {
                Err("global fragment units are part of a module, not standalone".to_string())
            }
        }
    }

    /// Emit the BMI content for a module interface.
    fn emit_bmi_content(&self, decl: &ModuleDecl, imports: &[ModuleImport]) -> Vec<u8> {
        let bmi = BmiFile {
            module_name: decl.name.clone(),
            is_interface: decl.kind.is_exported(),
            dependencies: imports.iter().map(|i| i.name.clone()).collect(),
            ast_data: Vec::new(),
            lookup_table: Vec::new(),
            source_map: Vec::new(),
            module_version: None,
        };
        bmi.serialize()
    }

    /// Validate the current module state.
    pub fn validate(&self) -> bool {
        self.errors.is_empty()
    }

    /// Get accumulated compilation errors.
    pub fn errors(&self) -> &[String] {
        &self.errors
    }

    /// Clear accumulated errors.
    pub fn clear_errors(&mut self) {
        self.errors.clear();
    }

    /// Get the active module declaration (if any).
    pub fn active_module(&self) -> Option<&ModuleDecl> {
        self.active_module.as_ref()
    }

    /// Get the list of parsed module declarations.
    pub fn parsed_declarations(&self) -> &[ModuleDecl] {
        &self.parsed_decls
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Section 3: X86ModuleMap — Module Map Handling (.modulemap)
// ═══════════════════════════════════════════════════════════════════════════════

/// `X86ModuleMap` provides full module map file handling for X86 targets.
/// This includes parsing `.modulemap` files, resolving module names,
/// supporting submodules, extern modules, and framework modules (Darwin).
#[derive(Debug, Clone)]
pub struct X86ModuleMap {
    /// Parsed module map files, keyed by their base directory.
    module_map_files: HashMap<PathBuf, ModuleMapFile>,
    /// Flat module index for quick lookups.
    module_index: HashMap<String, X86ModuleMapEntry>,
    /// Submodule hierarchy: parent → [child_module_names].
    submodule_hierarchy: HashMap<String, Vec<String>>,
    /// Extern modules: modules whose definition is external to this map.
    extern_modules: HashSet<String>,
    /// Framework module roots (Darwin-specific).
    framework_modules: HashMap<String, PathBuf>,
    /// Link libraries required by modules.
    link_libraries: HashMap<String, Vec<String>>,
    /// Include search paths for module map discovery.
    search_paths: Vec<PathBuf>,
    /// Whether this map has been validated.
    validated: bool,
    /// Validation errors.
    errors: Vec<String>,
}

/// An extended module map entry for X86 targets.
#[derive(Debug, Clone)]
pub struct X86ModuleMapEntry {
    /// The logical module name.
    pub module_name: String,
    /// The umbrella header or directory.
    pub umbrella: Option<String>,
    /// Explicit header list.
    pub headers: Vec<String>,
    /// Excluded headers.
    pub excluded_headers: Vec<String>,
    /// Submodules of this module.
    pub submodules: Vec<String>,
    /// Whether this is a framework module.
    pub is_framework: bool,
    /// Whether this module is explicitly declared (requires `@import`).
    pub is_explicit: bool,
    /// Export declarations.
    pub exports: Vec<String>,
    /// Required link libraries.
    pub link_libraries: Vec<String>,
    /// The base directory for relative paths.
    pub base_dir: PathBuf,
    /// Whether this is an extern module.
    pub is_extern: bool,
    /// The parent module name (if this is a submodule).
    pub parent: Option<String>,
    /// X86-specific configuration flags.
    pub x86_config_flags: Vec<String>,
    /// Darwin-specific flags.
    pub darwin_specific: X86DarwinModuleFlags,
}

/// Darwin-specific module flags.
#[derive(Debug, Clone, Default)]
pub struct X86DarwinModuleFlags {
    /// Whether the module is inside a .framework bundle.
    pub is_framework_bundle: bool,
    /// The framework version (if applicable).
    pub framework_version: Option<String>,
    /// Whether to use the system module cache.
    pub use_system_cache: bool,
    /// Whether the module is a system module.
    pub is_system_module: bool,
    /// Whether the module requires explicit build.
    pub requires_explicit_build: bool,
}

impl X86ModuleMapEntry {
    /// Create a new X86 module map entry.
    pub fn new(name: &str, base_dir: &Path) -> Self {
        Self {
            module_name: name.to_string(),
            umbrella: None,
            headers: Vec::new(),
            excluded_headers: Vec::new(),
            submodules: Vec::new(),
            is_framework: false,
            is_explicit: false,
            exports: Vec::new(),
            link_libraries: Vec::new(),
            base_dir: base_dir.to_path_buf(),
            is_extern: false,
            parent: None,
            x86_config_flags: Vec::new(),
            darwin_specific: X86DarwinModuleFlags::default(),
        }
    }

    /// Check if this entry has submodules.
    pub fn has_submodules(&self) -> bool {
        !self.submodules.is_empty()
    }

    /// Get the fully qualified name including parent hierarchy.
    pub fn fully_qualified_name(&self) -> String {
        if let Some(ref parent) = self.parent {
            format!("{}.{}", parent, self.module_name)
        } else {
            self.module_name.clone()
        }
    }
}

impl X86ModuleMap {
    /// Create a new empty module map.
    pub fn new() -> Self {
        Self {
            module_map_files: HashMap::new(),
            module_index: HashMap::new(),
            submodule_hierarchy: HashMap::new(),
            extern_modules: HashSet::new(),
            framework_modules: HashMap::new(),
            link_libraries: HashMap::new(),
            search_paths: Vec::new(),
            validated: false,
            errors: Vec::new(),
        }
    }

    /// Add a search path for module map discovery.
    pub fn add_search_path(&mut self, path: &Path) {
        self.search_paths.push(path.to_path_buf());
    }

    /// Add multiple search paths.
    pub fn add_search_paths(&mut self, paths: impl IntoIterator<Item = PathBuf>) {
        self.search_paths.extend(paths);
    }

    /// Parse a module map file from the given path.
    pub fn parse_module_map_file(&mut self, path: &Path) -> Result<(), String> {
        let content = fs::read_to_string(path)
            .map_err(|e| format!("failed to read module map '{}': {}", path.display(), e))?;

        let base_dir = path.parent().unwrap_or(Path::new(".")).to_path_buf();

        let map_file = ModuleMapFile::parse(&content, &base_dir.to_string_lossy())?;

        // Index all modules from this file
        for entry in &map_file.modules {
            let x86_entry = X86ModuleMapEntry {
                module_name: entry.module_name.clone(),
                umbrella: entry.umbrella.clone(),
                headers: entry.headers.clone(),
                excluded_headers: entry.excluded_headers.clone(),
                submodules: entry
                    .submodules
                    .iter()
                    .map(|s| s.module_name.clone())
                    .collect(),
                is_framework: entry.is_framework,
                is_explicit: entry.is_explicit,
                exports: entry.exports.clone(),
                link_libraries: entry.link_libraries.clone(),
                base_dir: base_dir.clone(),
                is_extern: false,
                parent: None,
                x86_config_flags: Vec::new(),
                darwin_specific: X86DarwinModuleFlags::default(),
            };

            // Register submodule hierarchy
            if !x86_entry.submodules.is_empty() {
                self.submodule_hierarchy
                    .insert(entry.module_name.clone(), x86_entry.submodules.clone());
            }

            // Register link libraries
            if !x86_entry.link_libraries.is_empty() {
                self.link_libraries
                    .insert(entry.module_name.clone(), x86_entry.link_libraries.clone());
            }

            // Register framework modules
            if x86_entry.is_framework {
                self.framework_modules
                    .insert(entry.module_name.clone(), base_dir.clone());
            }

            self.module_index
                .insert(entry.module_name.clone(), x86_entry);
        }

        self.module_map_files.insert(base_dir.clone(), map_file);

        self.validated = false; // Needs re-validation
        Ok(())
    }

    /// Discover and parse module map files from all search paths.
    pub fn discover_module_maps(&mut self) -> Result<usize, String> {
        let mut count = 0;
        for search_path in &self.search_paths.clone() {
            // Look for module.modulemap in the search path
            let map_path = search_path.join(X86_MODULE_MAP_FILE);
            if map_path.exists() {
                self.parse_module_map_file(&map_path)?;
                count += 1;
            }

            // Look for module.modulemap in immediate subdirectories
            if let Ok(entries) = fs::read_dir(search_path) {
                for entry in entries.flatten() {
                    if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
                        let sub_map = entry.path().join(X86_MODULE_MAP_FILE);
                        if sub_map.exists() {
                            self.parse_module_map_file(&sub_map)?;
                            count += 1;
                        }
                    }
                }
            }
        }
        Ok(count)
    }

    /// Resolve a module name to its canonical name.
    /// Handles submodule resolution and extern module references.
    pub fn resolve_name(&self, name: &str) -> Option<String> {
        // Direct match
        if self.module_index.contains_key(name) {
            return Some(name.to_string());
        }

        // Try as a submodule of known modules
        for (parent, children) in &self.submodule_hierarchy {
            for child in children {
                let full_name = format!("{}.{}", parent, child);
                if full_name == name {
                    return Some(name.to_string());
                }
            }
        }

        // Check extern modules
        if self.extern_modules.contains(name) {
            return Some(name.to_string());
        }

        None
    }

    /// Get a module entry by name.
    pub fn get_module(&self, name: &str) -> Option<&X86ModuleMapEntry> {
        self.module_index.get(name)
    }

    /// Get all submodules of a given module.
    pub fn submodules_of(&self, parent: &str) -> Vec<&str> {
        self.submodule_hierarchy
            .get(parent)
            .map(|v| v.iter().map(|s| s.as_str()).collect())
            .unwrap_or_default()
    }

    /// Register a submodule relationship.
    pub fn register_submodule(&mut self, parent: &str, child: &str) {
        self.submodule_hierarchy
            .entry(parent.to_string())
            .or_default()
            .push(child.to_string());
    }

    /// Register an extern module. Extern modules are declared in one
    /// module map but defined elsewhere (e.g., system modules).
    pub fn register_extern_module(&mut self, name: &str) {
        self.extern_modules.insert(name.to_string());
    }

    /// Check if a module is an extern module.
    pub fn is_extern_module(&self, name: &str) -> bool {
        self.extern_modules.contains(name)
    }

    /// Register a framework module (Darwin-specific).
    /// Framework modules are macOS/iOS frameworks that expose a module interface.
    pub fn register_framework_module(&mut self, name: &str, path: &Path) {
        self.framework_modules
            .insert(name.to_string(), path.to_path_buf());

        // Also register in the index
        let entry = X86ModuleMapEntry {
            module_name: name.to_string(),
            umbrella: None,
            headers: Vec::new(),
            excluded_headers: Vec::new(),
            submodules: Vec::new(),
            is_framework: true,
            is_explicit: false,
            exports: Vec::new(),
            link_libraries: Vec::new(),
            base_dir: path.to_path_buf(),
            is_extern: false,
            parent: None,
            x86_config_flags: Vec::new(),
            darwin_specific: X86DarwinModuleFlags {
                is_framework_bundle: true,
                framework_version: None,
                use_system_cache: true,
                is_system_module: true,
                requires_explicit_build: false,
            },
        };
        self.module_index.insert(name.to_string(), entry);
    }

    /// Check if a module is a framework module.
    pub fn is_framework_module(&self, name: &str) -> bool {
        self.framework_modules.contains_key(name)
    }

    /// Get the framework path for a module.
    pub fn framework_path(&self, name: &str) -> Option<&PathBuf> {
        self.framework_modules.get(name)
    }

    /// Get the link libraries required by a module.
    pub fn link_libraries_for(&self, module_name: &str) -> Vec<&str> {
        self.link_libraries
            .get(module_name)
            .map(|v| v.iter().map(|s| s.as_str()).collect())
            .unwrap_or_default()
    }

    /// Register a link library requirement for a module.
    pub fn register_link_library(&mut self, module_name: &str, library: &str) {
        self.link_libraries
            .entry(module_name.to_string())
            .or_default()
            .push(library.to_string());
    }

    /// Get all known module names.
    pub fn all_module_names(&self) -> Vec<&str> {
        self.module_index.keys().map(|s| s.as_str()).collect()
    }

    /// Check if a module name is known.
    pub fn contains_module(&self, name: &str) -> bool {
        self.module_index.contains_key(name)
    }

    /// Get the full path of headers declared in a module.
    pub fn module_headers(&self, name: &str) -> Vec<PathBuf> {
        if let Some(entry) = self.module_index.get(name) {
            entry
                .headers
                .iter()
                .map(|h| entry.base_dir.join(h))
                .collect()
        } else {
            Vec::new()
        }
    }

    /// Get the umbrella header/directory for a module.
    pub fn module_umbrella(&self, name: &str) -> Option<PathBuf> {
        self.module_index
            .get(name)
            .and_then(|e| e.umbrella.as_ref())
            .map(|u| {
                if let Some(e) = self.module_index.get(name) {
                    e.base_dir.join(u)
                } else {
                    PathBuf::from(u)
                }
            })
    }

    /// Convert the X86 module map into the base ModuleMap format.
    pub fn to_base_module_map(&self) -> ModuleMap {
        let mut map = ModuleMap::new();
        for (name, _) in &self.module_index {
            let info = crate::clang::cpp_modules::ModuleInfo::new(ModuleName::from_str(name), true);
            map.register_module(info);
        }

        // Add import relationships from submodule hierarchy
        for (parent, children) in &self.submodule_hierarchy {
            for child in children {
                let full_child = format!("{}.{}", parent, child);
                map.add_import(parent, &full_child);
            }
        }

        map
    }

    /// Validate the module map for correctness.
    pub fn validate(&self) -> Vec<String> {
        let mut errors = Vec::new();

        // Check for duplicate module names across different directories
        let mut name_dirs: HashMap<&str, Vec<&PathBuf>> = HashMap::new();
        for entry in self.module_index.values() {
            name_dirs
                .entry(&entry.module_name)
                .or_default()
                .push(&entry.base_dir);
        }

        for (name, dirs) in &name_dirs {
            if dirs.len() > 1 {
                errors.push(format!(
                    "module '{}' defined in multiple locations: {:?}",
                    name, dirs
                ));
            }
        }

        // Check submodules reference existing modules
        for (parent, children) in &self.submodule_hierarchy {
            if !self.module_index.contains_key(parent) {
                errors.push(format!(
                    "parent module '{}' not found for submodules: {:?}",
                    parent, children
                ));
            }
        }

        // Check framework modules exist
        for (name, path) in &self.framework_modules {
            if !path.exists() {
                errors.push(format!(
                    "framework module '{}' path does not exist: {}",
                    name,
                    path.display()
                ));
            }
        }

        errors
    }

    /// Serialize the module map to a textual representation.
    /// This produces a syntactically valid `.modulemap` file.
    pub fn serialize_to_string(&self) -> String {
        let mut out = String::new();
        out.push_str("// X86 Module Map — auto-generated\n\n");

        for entry in self.module_index.values() {
            if entry.is_framework {
                out.push_str("framework module ");
            } else if entry.is_extern {
                out.push_str("extern module ");
            } else if entry.is_explicit {
                out.push_str("explicit module ");
            } else {
                out.push_str("module ");
            }
            out.push_str(&entry.module_name);
            out.push_str(" {\n");

            if let Some(ref umbrella) = entry.umbrella {
                out.push_str(&format!("  umbrella \"{}\"\n", umbrella));
            }
            for header in &entry.headers {
                out.push_str(&format!("  header \"{}\"\n", header));
            }
            for excluded in &entry.excluded_headers {
                out.push_str(&format!("  excluded_header \"{}\"\n", excluded));
            }
            for sub in &entry.submodules {
                out.push_str(&format!("  module {}\n", sub));
            }
            for export in &entry.exports {
                out.push_str(&format!("  export {}\n", export));
            }
            for lib in &entry.link_libraries {
                out.push_str(&format!("  link \"{}\"\n", lib));
            }
            if entry.is_explicit {
                out.push_str("  explicit\n");
            }

            out.push_str("}\n\n");
        }

        // Emit submodule hierarchies
        for (parent, children) in &self.submodule_hierarchy {
            if self.module_index.contains_key(parent) && !children.is_empty() {
                out.push_str(&format!(
                    "// Submodules of {}: {}\n",
                    parent,
                    children.join(", ")
                ));
            }
        }

        out
    }

    /// Write the module map to a file.
    pub fn write_to_file(&self, path: &Path) -> Result<(), String> {
        let content = self.serialize_to_string();
        fs::write(path, &content).map_err(|e| format!("failed to write module map: {}", e))
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// Section 4: X86ModuleDependency — Dependency Graph Management
// ═══════════════════════════════════════════════════════════════════════════════

/// `X86ModuleDependency` manages the full module dependency graph for
/// X86 compilation. It constructs dependency edges from compilation units,
/// performs topological ordering for correct compilation sequencing,
/// detects import cycles, and supports incremental rebuild with
/// fine-grained dependency tracking.
#[derive(Debug, Clone)]
pub struct X86ModuleDependency {
    /// The underlying dependency graph.
    pub graph: ModuleDependencyGraph,
    /// Reverse dependency edges (who depends on whom).
    reverse_edges: HashMap<String, HashSet<String>>,
    /// Nodes in the graph with their compilation status.
    node_status: HashMap<String, X86DependencyStatus>,
    /// Timestamps for incremental rebuild detection.
    timestamps: HashMap<String, X86FileTimestamps>,
    /// Build orders previously computed (for incremental rebuild).
    previous_build_order: Vec<String>,
    /// Whether a full rebuild is needed.
    needs_full_rebuild: bool,
    /// Pending changes since last build.
    pending_changes: Vec<X86DependencyChange>,
}

/// Status of a dependency graph node.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86DependencyStatus {
    /// Not yet compiled.
    Pending,
    /// Currently being compiled.
    InProgress,
    /// Successfully compiled.
    Compiled,
    /// Compilation failed.
    Failed,
    /// Skipped (dependency failed).
    Skipped,
    /// Up-to-date (no changes since last compilation).
    UpToDate,
}

/// File timestamps for change detection.
#[derive(Debug, Clone)]
pub struct X86FileTimestamps {
    /// Source file modification time.
    pub source_mtime: u64,
    /// BMI file modification time.
    pub bmi_mtime: u64,
    /// Dependency file modification time.
    pub deps_mtime: u64,
    /// Hash of the source file content.
    pub source_hash: u64,
    /// Hash of compiler flags used.
    pub flags_hash: u64,
}

/// A change in the dependency graph.
#[derive(Debug, Clone)]
pub enum X86DependencyChange {
    /// A new module was added.
    Added(String),
    /// A module was removed.
    Removed(String),
    /// A module's source changed.
    SourceChanged(String),
    /// A module's flags changed.
    FlagsChanged(String),
    /// A dependency edge was added.
    EdgeAdded(String, String),
    /// A dependency edge was removed.
    EdgeRemoved(String, String),
}

impl X86ModuleDependency {
    /// Create a new empty dependency graph.
    pub fn new() -> Self {
        Self {
            graph: ModuleDependencyGraph::new(),
            reverse_edges: HashMap::new(),
            node_status: HashMap::new(),
            timestamps: HashMap::new(),
            previous_build_order: Vec::new(),
            needs_full_rebuild: true,
            pending_changes: Vec::new(),
        }
    }

    /// Build the dependency graph from a set of compilation units and
    /// an existing module map.
    pub fn build_from_units(&mut self, units: &[X86CompilationUnit], module_map: &X86ModuleMap) {
        for unit in units {
            if let Some(ref decl) = unit.module_decl {
                let name = decl.name.to_string();
                self.node_status
                    .entry(name.clone())
                    .or_insert(X86DependencyStatus::Pending);

                // Add dependencies from required imports
                for import in &unit.required_imports {
                    if !import.is_header_unit {
                        let dep_name = import.name.to_string();
                        if let Some(resolved) = module_map.resolve_name(&dep_name) {
                            self.add_dependency(&name, &resolved);
                        } else {
                            // Try to add the dependency directly
                            self.add_dependency(&name, &dep_name);
                        }
                    }
                }

                // Add dependencies from the module map
                if let Some(entry) = module_map.get_module(&name) {
                    for export in &entry.exports {
                        if let Some(resolved) = module_map.resolve_name(export) {
                            self.add_dependency(&name, &resolved);
                        }
                    }
                }
            }
        }
    }

    /// Add a dependency edge: `module` depends on `dependency`.
    pub fn add_dependency(&mut self, module: &str, dependency: &str) {
        if module == dependency {
            return; // Self-loop, ignore
        }
        self.graph.add_dependency(module, dependency);
        self.reverse_edges
            .entry(dependency.to_string())
            .or_default()
            .insert(module.to_string());
        self.needs_full_rebuild = true;
    }

    /// Remove a dependency edge.
    pub fn remove_dependency(&mut self, module: &str, dependency: &str) {
        self.reverse_edges
            .get_mut(dependency)
            .map(|set| set.remove(module));
        self.needs_full_rebuild = true;
    }

    /// Get direct dependencies of a module.
    pub fn direct_dependencies(&self, module: &str) -> Vec<String> {
        self.graph.transitive_deps(module).into_iter().collect()
    }

    /// Get all modules that depend on a given module (reverse dependencies).
    pub fn dependents_of(&self, module: &str) -> Vec<String> {
        self.reverse_edges
            .get(module)
            .cloned()
            .unwrap_or_default()
            .into_iter()
            .collect()
    }

    /// Perform topological sort, returning modules in compilation order.
    /// Returns an error if a cycle is detected.
    pub fn topological_sort(&self) -> Result<Vec<String>, String> {
        self.graph.topological_sort()
    }

    /// Detect a cycle in the dependency graph.
    /// Returns the cycle path if found, or None if the graph is acyclic.
    pub fn detect_cycle(&self) -> Option<Vec<String>> {
        match self.topological_sort() {
            Ok(_) => None,
            Err(_) => {
                // Find an actual cycle using DFS
                self.find_cycle_dfs()
            }
        }
    }

    /// Find a cycle using depth-first search with three-color marking.
    fn find_cycle_dfs(&self) -> Option<Vec<String>> {
        let all_nodes: HashSet<String> = self.reverse_edges.keys().cloned().collect();

        #[derive(Clone, Copy, PartialEq, Eq)]
        enum Color {
            White,
            Gray,
            Black,
        }

        let mut colors: HashMap<String, Color> = all_nodes
            .iter()
            .map(|n| (n.clone(), Color::White))
            .collect();
        let mut parent: HashMap<String, String> = HashMap::new();

        for node in &all_nodes {
            if colors[node] == Color::White {
                let mut stack = vec![(node.clone(), Color::Gray)];
                colors.insert(node.clone(), Color::Gray);

                while let Some((current, _)) = stack.last().cloned() {
                    let neighbors = self.direct_dependencies(&current);
                    let mut found_unvisited = false;

                    for neighbor in &neighbors {
                        let neighbor_color = colors.get(neighbor).copied().unwrap_or(Color::White);
                        match neighbor_color {
                            Color::White => {
                                colors.insert(neighbor.clone(), Color::Gray);
                                parent.insert(neighbor.clone(), current.clone());
                                stack.push((neighbor.clone(), Color::Gray));
                                found_unvisited = true;
                                break;
                            }
                            Color::Gray => {
                                // Found a cycle — reconstruct the path
                                let mut cycle = vec![neighbor.clone(), current.clone()];
                                let mut node = current.clone();
                                while let Some(p) = parent.get(&node) {
                                    if p == neighbor {
                                        cycle.push(p.clone());
                                        break;
                                    }
                                    cycle.push(p.clone());
                                    node = p.clone();
                                }
                                cycle.reverse();
                                return Some(cycle);
                            }
                            Color::Black => { /* already processed */ }
                        }
                    }

                    if !found_unvisited {
                        stack.pop();
                        colors.insert(current, Color::Black);
                    }
                }
            }
        }

        None
    }

    /// Compute an incremental rebuild plan based on changed files.
    /// Only rebuilds modules whose sources or dependencies have changed.
    pub fn compute_incremental_rebuild(&mut self, changed_files: &[String]) -> Vec<String> {
        let mut to_rebuild = Vec::new();

        // Mark all modules that depend on changed files
        for changed in changed_files {
            // Find modules whose source files match the change
            for (module, _) in &self.node_status {
                if changed.contains(module) {
                    to_rebuild.push(module.clone());
                }
            }

            // Also rebuild dependents
            if let Some(dependents) = self.reverse_edges.get(changed) {
                for dep in dependents {
                    to_rebuild.push(dep.clone());
                }
            }
        }

        to_rebuild.sort();
        to_rebuild.dedup();
        to_rebuild
    }

    /// Record the timestamp of a module build for incremental rebuild tracking.
    pub fn record_timestamp(&mut self, module: &str, timestamps: X86FileTimestamps) {
        self.timestamps.insert(module.to_string(), timestamps);
    }

    /// Check if a module needs rebuilding based on its timestamps.
    pub fn needs_rebuild(&self, module: &str) -> bool {
        if self.needs_full_rebuild {
            return true;
        }

        if let Some(ts) = self.timestamps.get(module) {
            // Check if any dependencies have newer timestamps
            for dep in self.direct_dependencies(module) {
                if let Some(dep_ts) = self.timestamps.get(&dep) {
                    if dep_ts.bmi_mtime > ts.source_mtime {
                        return true;
                    }
                }
            }
            false
        } else {
            true
        }
    }

    /// Update the build status of a module.
    pub fn set_status(&mut self, module: &str, status: X86DependencyStatus) {
        self.node_status.insert(module.to_string(), status);
    }

    /// Get the build status of a module.
    pub fn status(&self, module: &str) -> Option<X86DependencyStatus> {
        self.node_status.get(module).copied()
    }

    /// Record a change that affects the dependency graph.
    pub fn record_change(&mut self, change: X86DependencyChange) {
        self.pending_changes.push(change);
        self.needs_full_rebuild = true;
    }

    /// Get all pending changes.
    pub fn pending_changes(&self) -> &[X86DependencyChange] {
        &self.pending_changes
    }

    /// Clear all pending changes.
    pub fn clear_pending_changes(&mut self) {
        self.pending_changes.clear();
    }

    /// Check if the graph has any cycles.
    pub fn has_cycles(&self) -> bool {
        self.detect_cycle().is_some()
    }

    /// Get the number of nodes in the graph.
    pub fn node_count(&self) -> usize {
        self.node_status.len()
    }

    /// Get the number of edges in the graph.
    pub fn edge_count(&self) -> usize {
        self.reverse_edges.values().map(|v| v.len()).sum()
    }

    /// Perform a transitive reduction to remove redundant edges.
    /// An edge A → C is redundant if A → B → C already exists.
    pub fn transitive_reduction(&mut self) -> Vec<(String, String)> {
        self.graph.find_redundant_edges()
    }

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

        // Check for unreferenced modules
        let from_deps: HashSet<&str> = self
            .reverse_edges
            .values()
            .flatten()
            .map(|s| s.as_str())
            .collect();

        for (module, _) in &self.node_status {
            if !self.reverse_edges.contains_key(module) && !from_deps.contains(module.as_str()) {
                // Isolated node — not an error, just a note
            }

            // Check all deps are known
            for dep in self.direct_dependencies(module) {
                if !self.node_status.contains_key(&dep) {
                    errors.push(format!(
                        "module '{}' depends on unknown module '{}'",
                        module, dep
                    ));
                }
            }
        }

        errors
    }

    /// Produce a Graphviz DOT representation of the dependency graph.
    pub fn to_dot(&self) -> String {
        let mut dot = String::from("digraph ModuleDependencies {\n");
        dot.push_str("  rankdir=LR;\n");
        dot.push_str("  node [shape=box];\n");

        let mut seen_edges = HashSet::new();
        for (module, _) in &self.node_status {
            let color = match self.node_status.get(module) {
                Some(X86DependencyStatus::Compiled) => "green",
                Some(X86DependencyStatus::UpToDate) => "blue",
                Some(X86DependencyStatus::Failed) => "red",
                Some(X86DependencyStatus::InProgress) => "yellow",
                _ => "black",
            };
            dot.push_str(&format!(
                "  \"{}\" [color={}, style=filled, fillcolor=lightgrey];\n",
                module, color
            ));

            for dep in self.direct_dependencies(module) {
                let edge = (module.clone(), dep.clone());
                if seen_edges.insert(edge.clone()) {
                    dot.push_str(&format!("  \"{}\" -> \"{}\";\n", edge.0, edge.1));
                }
            }
        }

        dot.push_str("}\n");
        dot
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// Section 5: X86BMITransfer — BMI Serialization/Deserialization for X86
// ═══════════════════════════════════════════════════════════════════════════════

/// `X86BMITransfer` extends the base BMI handling with X86-specific
/// features: extended versioning, compressed AST data for X86 vector
/// types, signature/key computation for cache validation, module map
/// embedding, and X86 target triple recording.
#[derive(Debug, Clone)]
pub struct X86BMITransfer {
    /// Whether to compress BMI data with X86-aware compression.
    pub enable_compression: bool,
    /// Whether to embed X86 target information in BMIs.
    pub embed_target_info: bool,
    /// Whether to verify signatures on import.
    pub verify_signatures: bool,
    /// The X86 target triple stamped into BMIs.
    pub target_triple: String,
    /// The compiler version stamped into BMIs.
    pub compiler_version: String,
    /// Keys used for BMI signature computation.
    signature_keys: X86BMISignatureKeys,
    /// Logger for BMI operations.
    operation_log: Vec<X86BMIOperation>,
}

/// BMI signature computation keys.
#[derive(Debug, Clone)]
pub struct X86BMISignatureKeys {
    /// Whether to include source hashes in the signature.
    pub include_source_hash: bool,
    /// Whether to include compiler flags in the signature.
    pub include_flags: bool,
    /// Whether to include target triple in the signature.
    pub include_target: bool,
    /// Whether to include dependency hashes in the signature.
    pub include_dependency_hashes: bool,
}

/// A BMI transfer operation log entry.
#[derive(Debug, Clone)]
pub struct X86BMIOperation {
    /// The operation kind.
    pub op: X86BMIOpKind,
    /// The module name involved.
    pub module_name: String,
    /// The BMI file size in bytes.
    pub file_size: usize,
    /// Whether the operation succeeded.
    pub success: bool,
    /// Error message if failed.
    pub error: Option<String>,
}

/// Kinds of BMI operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86BMIOpKind {
    /// Export (serialize) a BMI.
    Export,
    /// Import (deserialize) a BMI.
    Import,
    /// Verify a BMI signature.
    Verify,
    /// Update an existing BMI.
    Update,
    /// Remove a BMI.
    Remove,
}

/// Extended BMI file format for X86 targets.
/// Wraps the base BMI with additional X86-specific sections.
#[derive(Debug, Clone)]
pub struct X86BmiFile {
    /// The base BMI data.
    pub base: BmiFile,
    /// The X86 target triple used when compiling.
    pub x86_target_triple: String,
    /// The compiler version used.
    pub x86_compiler_version: String,
    /// Module map content embedded in the BMI.
    pub embedded_module_map: Option<String>,
    /// X86-specific flags.
    pub x86_flags: X86BMIFlags,
    /// BMI signature (computed hash).
    pub signature: [u8; 32],
}

/// X86-specific BMI flags.
#[derive(Debug, Clone, Default)]
pub struct X86BMIFlags {
    /// Whether SSE instructions were enabled.
    pub sse_enabled: bool,
    /// Whether SSE2 instructions were enabled.
    pub sse2_enabled: bool,
    /// Whether AVX instructions were enabled.
    pub avx_enabled: bool,
    /// Whether AVX2 instructions were enabled.
    pub avx2_enabled: bool,
    /// Whether AVX-512 was enabled.
    pub avx512_enabled: bool,
    /// Whether to use X86-64 ABI (vs 32-bit).
    pub is_64bit: bool,
    /// Whether to use the Microsoft ABI (vs System V).
    pub microsoft_abi: bool,
    /// Stack alignment in bytes.
    pub stack_alignment: u32,
    /// Whether RTTI was enabled.
    pub rtti_enabled: bool,
    /// Whether exceptions were enabled.
    pub exceptions_enabled: bool,
}

impl X86BMITransfer {
    /// Create a new BMI transfer manager.
    pub fn new() -> Self {
        Self {
            enable_compression: true,
            embed_target_info: true,
            verify_signatures: true,
            target_triple: "x86_64-unknown-linux-gnu".to_string(),
            compiler_version: env!("CARGO_PKG_VERSION").to_string(),
            signature_keys: X86BMISignatureKeys {
                include_source_hash: true,
                include_flags: true,
                include_target: true,
                include_dependency_hashes: true,
            },
            operation_log: Vec::new(),
        }
    }

    /// Set the target triple for BMI stamping.
    pub fn set_target_triple(&mut self, triple: &str) {
        self.target_triple = triple.to_string();
    }

    /// Export (serialize) a module to a BMI file.
    /// Produces an extended X86 BMI that includes X86-specific metadata.
    pub fn export_bmi(
        &mut self,
        module_name: &str,
        _decl: &ModuleDecl,
        bmi_file: &BmiFile,
        output_path: &Path,
        _options: &ClangOptions,
    ) -> Result<usize, String> {
        // Build the extended BMI
        let x86_bmi = self.build_x86_bmi(bmi_file);

        // Serialize the extended BMI
        let data = self.serialize_x86_bmi(&x86_bmi);

        // Write to file
        if let Some(parent) = output_path.parent() {
            fs::create_dir_all(parent)
                .map_err(|e| format!("failed to create BMI output directory: {}", e))?;
        }

        let mut file = BufWriter::new(
            fs::File::create(output_path)
                .map_err(|e| format!("failed to create BMI file: {}", e))?,
        );
        file.write_all(&data)
            .map_err(|e| format!("failed to write BMI data: {}", e))?;
        file.flush()
            .map_err(|e| format!("failed to flush BMI data: {}", e))?;

        let size = data.len();
        self.operation_log.push(X86BMIOperation {
            op: X86BMIOpKind::Export,
            module_name: module_name.to_string(),
            file_size: size,
            success: true,
            error: None,
        });

        Ok(size)
    }

    /// Import (deserialize) a BMI from a file.
    pub fn import_bmi(&mut self, path: &Path) -> Result<X86BmiFile, String> {
        let mut file = BufReader::new(
            fs::File::open(path)
                .map_err(|e| format!("failed to open BMI file '{}': {}", path.display(), e))?,
        );

        let mut data = Vec::new();
        file.read_to_end(&mut data)
            .map_err(|e| format!("failed to read BMI data: {}", e))?;

        self.deserialize_x86_bmi(&data).map_err(|e| {
            self.operation_log.push(X86BMIOperation {
                op: X86BMIOpKind::Import,
                module_name: path.to_string_lossy().to_string(),
                file_size: data.len(),
                success: false,
                error: Some(e.clone()),
            });
            e
        })
    }

    /// Build an extended X86 BMI from a base BMI.
    fn build_x86_bmi(&self, base: &BmiFile) -> X86BmiFile {
        let mut x86_bmi = X86BmiFile {
            base: base.clone(),
            x86_target_triple: self.target_triple.clone(),
            x86_compiler_version: self.compiler_version.clone(),
            embedded_module_map: None,
            x86_flags: X86BMIFlags {
                sse_enabled: true,
                sse2_enabled: true,
                avx_enabled: false,
                avx2_enabled: false,
                avx512_enabled: false,
                is_64bit: self.target_triple.contains("64"),
                microsoft_abi: self.target_triple.contains("windows"),
                stack_alignment: X86_STACK_ALIGNMENT_64,
                rtti_enabled: true,
                exceptions_enabled: true,
            },
            signature: [0u8; 32],
        };

        // Compute the signature
        let sig = self.compute_signature(&x86_bmi);
        x86_bmi.signature = sig;

        x86_bmi
    }

    /// Serialize an extended X86 BMI to bytes.
    pub fn serialize_x86_bmi(&self, bmi: &X86BmiFile) -> Vec<u8> {
        let mut buf = Vec::new();

        // Extended magic
        buf.extend_from_slice(X86_BMI_SIGNATURE_MAGIC);
        // Extended version
        buf.extend_from_slice(&X86_BMI_EXTENDED_VERSION.to_le_bytes());

        // Serialize base BMI
        let base_data = bmi.base.serialize();
        buf.extend_from_slice(&(base_data.len() as u64).to_le_bytes());
        buf.extend_from_slice(&base_data);

        // X86 target triple
        buf.extend_from_slice(&(bmi.x86_target_triple.len() as u32).to_le_bytes());
        buf.extend_from_slice(bmi.x86_target_triple.as_bytes());

        // Compiler version
        buf.extend_from_slice(&(bmi.x86_compiler_version.len() as u32).to_le_bytes());
        buf.extend_from_slice(bmi.x86_compiler_version.as_bytes());

        // Embedded module map
        if let Some(ref map) = bmi.embedded_module_map {
            buf.push(1);
            buf.extend_from_slice(&(map.len() as u64).to_le_bytes());
            buf.extend_from_slice(map.as_bytes());
        } else {
            buf.push(0);
        }

        // X86 flags
        let mut flags: u64 = 0;
        if bmi.x86_flags.sse_enabled {
            flags |= 1 << 0;
        }
        if bmi.x86_flags.sse2_enabled {
            flags |= 1 << 1;
        }
        if bmi.x86_flags.avx_enabled {
            flags |= 1 << 2;
        }
        if bmi.x86_flags.avx2_enabled {
            flags |= 1 << 3;
        }
        if bmi.x86_flags.avx512_enabled {
            flags |= 1 << 4;
        }
        if bmi.x86_flags.is_64bit {
            flags |= 1 << 5;
        }
        if bmi.x86_flags.microsoft_abi {
            flags |= 1 << 6;
        }
        if bmi.x86_flags.rtti_enabled {
            flags |= 1 << 7;
        }
        if bmi.x86_flags.exceptions_enabled {
            flags |= 1 << 8;
        }
        buf.extend_from_slice(&flags.to_le_bytes());
        buf.extend_from_slice(&bmi.x86_flags.stack_alignment.to_le_bytes());

        // Signature
        buf.extend_from_slice(&bmi.signature);

        buf
    }

    /// Deserialize an extended X86 BMI from bytes.
    pub fn deserialize_x86_bmi(&self, data: &[u8]) -> Result<X86BmiFile, String> {
        if data.len() < 12 {
            return Err("X86 BMI data too short".to_string());
        }

        let mut pos = 0usize;

        // Check extended magic
        if &data[pos..pos + 4] != X86_BMI_SIGNATURE_MAGIC {
            return Err("invalid X86 BMI magic bytes".to_string());
        }
        pos += 4;

        // Check extended version
        let ext_version =
            u32::from_le_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]);
        pos += 4;
        if ext_version > X86_BMI_EXTENDED_VERSION {
            return Err(format!(
                "unsupported X86 BMI version {} (expected <= {})",
                ext_version, X86_BMI_EXTENDED_VERSION
            ));
        }

        // Read base BMI
        if pos + 8 > data.len() {
            return Err("truncated base BMI size field".to_string());
        }
        let base_len = u64::from_le_bytes([
            data[pos],
            data[pos + 1],
            data[pos + 2],
            data[pos + 3],
            data[pos + 4],
            data[pos + 5],
            data[pos + 6],
            data[pos + 7],
        ]) as usize;
        pos += 8;
        if pos + base_len > data.len() {
            return Err("truncated base BMI data".to_string());
        }
        let base = BmiFile::deserialize(&data[pos..pos + base_len])?;
        pos += base_len;

        // X86 target triple
        if pos + 4 > data.len() {
            return Err("truncated target triple length".to_string());
        }
        let triple_len =
            u32::from_le_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]) as usize;
        pos += 4;
        if pos + triple_len > data.len() {
            return Err("truncated target triple data".to_string());
        }
        let x86_target_triple = String::from_utf8(data[pos..pos + triple_len].to_vec())
            .map_err(|e| format!("invalid UTF-8 in target triple: {}", e))?;
        pos += triple_len;

        // Compiler version
        if pos + 4 > data.len() {
            return Err("truncated compiler version length".to_string());
        }
        let ver_len =
            u32::from_le_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]) as usize;
        pos += 4;
        if pos + ver_len > data.len() {
            return Err("truncated compiler version data".to_string());
        }
        let x86_compiler_version = String::from_utf8(data[pos..pos + ver_len].to_vec())
            .map_err(|e| format!("invalid UTF-8 in compiler ver: {}", e))?;
        pos += ver_len;

        // Embedded module map
        if pos >= data.len() {
            return Err("truncated at module map flag".to_string());
        }
        let has_map = data[pos] == 1;
        pos += 1;
        let embedded_module_map = if has_map {
            if pos + 8 > data.len() {
                return Err("truncated module map size".to_string());
            }
            let map_len = u64::from_le_bytes([
                data[pos],
                data[pos + 1],
                data[pos + 2],
                data[pos + 3],
                data[pos + 4],
                data[pos + 5],
                data[pos + 6],
                data[pos + 7],
            ]) as usize;
            pos += 8;
            if pos + map_len > data.len() {
                return Err("truncated module map data".to_string());
            }
            let map = String::from_utf8(data[pos..pos + map_len].to_vec())
                .map_err(|e| format!("invalid UTF-8 in module map: {}", e))?;
            pos += map_len;
            Some(map)
        } else {
            None
        };

        // X86 flags
        if pos + 8 > data.len() {
            return Err("truncated X86 flags".to_string());
        }
        let flags = u64::from_le_bytes([
            data[pos],
            data[pos + 1],
            data[pos + 2],
            data[pos + 3],
            data[pos + 4],
            data[pos + 5],
            data[pos + 6],
            data[pos + 7],
        ]);
        pos += 8;
        let stack_alignment =
            u32::from_le_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]);
        pos += 4;

        let x86_flags = X86BMIFlags {
            sse_enabled: (flags & (1 << 0)) != 0,
            sse2_enabled: (flags & (1 << 1)) != 0,
            avx_enabled: (flags & (1 << 2)) != 0,
            avx2_enabled: (flags & (1 << 3)) != 0,
            avx512_enabled: (flags & (1 << 4)) != 0,
            is_64bit: (flags & (1 << 5)) != 0,
            microsoft_abi: (flags & (1 << 6)) != 0,
            rtti_enabled: (flags & (1 << 7)) != 0,
            exceptions_enabled: (flags & (1 << 8)) != 0,
            stack_alignment,
        };

        // Signature
        if pos + 32 > data.len() {
            return Err("truncated BMI signature".to_string());
        }
        let mut signature = [0u8; 32];
        signature.copy_from_slice(&data[pos..pos + 32]);

        let result = X86BmiFile {
            base,
            x86_target_triple,
            x86_compiler_version,
            embedded_module_map,
            x86_flags,
            signature,
        };

        // Verify signature if enabled
        if self.verify_signatures {
            let computed = self.compute_signature(&result);
            if computed != signature {
                return Err("BMI signature verification failed".to_string());
            }
        }

        Ok(result)
    }

    /// Compute a BMI signature for version checking.
    /// The signature is a SHA-256-like hash of key BMI fields.
    pub fn compute_signature(&self, bmi: &X86BmiFile) -> [u8; 32] {
        // Simple hash: combine key fields into a 256-bit signature
        let mut hash = [0u8; 32];

        // Hash the module name
        let name_str = bmi.base.module_name.to_string();
        for (i, byte) in name_str.bytes().enumerate() {
            hash[i % 32] = hash[i % 32].wrapping_add(byte);
        }

        // Hash the AST data
        if self.signature_keys.include_source_hash {
            for (i, byte) in bmi.base.ast_data.iter().enumerate() {
                hash[i.wrapping_mul(7) % 32] = hash[i.wrapping_mul(7) % 32].wrapping_add(*byte);
            }
        }

        // Hash the target triple
        if self.signature_keys.include_target {
            for (i, byte) in bmi.x86_target_triple.bytes().enumerate() {
                hash[(i + 8) % 32] = hash[(i + 8) % 32].wrapping_add(byte);
            }
        }

        // Hash dependencies
        if self.signature_keys.include_dependency_hashes {
            for dep in &bmi.base.dependencies {
                let dep_str = dep.to_string();
                for (i, byte) in dep_str.bytes().enumerate() {
                    hash[(i + 16) % 32] = hash[(i + 16) % 32].wrapping_add(byte);
                }
            }
        }

        // Hash flags
        if self.signature_keys.include_flags {
            hash[24] = if bmi.x86_flags.is_64bit { 1 } else { 0 };
            hash[25] = if bmi.x86_flags.sse2_enabled { 1 } else { 0 };
            hash[26] = if bmi.x86_flags.avx_enabled { 1 } else { 0 };
            hash[27] = if bmi.x86_flags.rtti_enabled { 1 } else { 0 };
            hash[28] = if bmi.x86_flags.exceptions_enabled {
                1
            } else {
                0
            };
            hash[29] = if bmi.x86_flags.microsoft_abi { 1 } else { 0 };
        }

        hash
    }

    /// Check if a BMI is compatible with the current compiler version.
    pub fn check_version_compatibility(&self, bmi: &X86BmiFile) -> Result<(), String> {
        // Check extended version
        if bmi.x86_compiler_version != self.compiler_version {
            // Version mismatch may still be compatible
            // In a real implementation, we would check for known compatible versions
        }

        // Check target triple compatibility
        if self.signature_keys.include_target {
            let bmi_triple = &bmi.x86_target_triple;
            if !self.are_triples_compatible(bmi_triple, &self.target_triple) {
                return Err(format!(
                    "BMI target triple '{}' is incompatible with current target '{}'",
                    bmi_triple, self.target_triple
                ));
            }
        }

        Ok(())
    }

    /// Check if two target triples are compatible.
    fn are_triples_compatible(&self, a: &str, b: &str) -> bool {
        // Simple compatibility: same architecture and OS
        let arch_a = a.split('-').next().unwrap_or("");
        let arch_b = b.split('-').next().unwrap_or("");
        arch_a == arch_b
    }

    /// Get the operation log.
    pub fn operation_log(&self) -> &[X86BMIOperation] {
        &self.operation_log
    }

    /// Clear the operation log.
    pub fn clear_log(&mut self) {
        self.operation_log.clear();
    }

    /// Validate a BMI file path for reading.
    pub fn validate_bmi_file(&self, path: &Path) -> Result<(), String> {
        if !path.exists() {
            return Err(format!("BMI file does not exist: {}", path.display()));
        }
        let metadata =
            fs::metadata(path).map_err(|e| format!("failed to read BMI metadata: {}", e))?;
        if metadata.len() < 16 {
            return Err(format!("BMI file too small: {} bytes", metadata.len()));
        }
        Ok(())
    }

    /// Remove a BMI file.
    pub fn remove_bmi(&mut self, path: &Path) -> Result<(), String> {
        fs::remove_file(path).map_err(|e| format!("failed to remove BMI: {}", e))?;
        self.operation_log.push(X86BMIOperation {
            op: X86BMIOpKind::Remove,
            module_name: path.to_string_lossy().to_string(),
            file_size: 0,
            success: true,
            error: None,
        });
        Ok(())
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// Section 6: X86ModuleCache — On-Disk Module Cache Management
// ═══════════════════════════════════════════════════════════════════════════════

/// `X86ModuleCache` manages the on-disk module cache for compiled BMIs.
/// It provides a structured directory layout, lookup by module name and
/// content hash, invalidation based on source/flag changes, and automatic
/// pruning to stay within size limits.
#[derive(Debug, Clone)]
pub struct X86ModuleCache {
    /// The root cache directory.
    pub cache_root: PathBuf,
    /// Maximum cache size in bytes.
    pub max_size_bytes: u64,
    /// Maximum number of BMI versions per module.
    pub max_versions_per_module: usize,
    /// Whether the cache is enabled.
    pub enabled: bool,
    /// The cache index: module_name → list of (hash, path, size, mtime).
    cache_index: HashMap<String, Vec<X86CacheEntry>>,
    /// Total current cache size in bytes.
    current_size_bytes: u64,
    /// Compiler options used for cache keying.
    options_hash: u64,
    /// X86-specific cache configuration.
    x86_cache_config: X86CacheConfig,
}

/// An entry in the module cache.
#[derive(Debug, Clone)]
pub struct X86CacheEntry {
    /// Content hash of the BMI.
    pub content_hash: String,
    /// Path to the cached BMI file.
    pub bmi_path: PathBuf,
    /// Size of the BMI in bytes.
    pub size_bytes: u64,
    /// Modification time (for LRU eviction).
    pub mtime: u64,
    /// Compiler flags hash used to build this BMI.
    pub flags_hash: u64,
    /// Module version string.
    pub module_version: Option<String>,
    /// Whether this entry is currently valid.
    pub valid: bool,
}

/// X86-specific cache configuration.
#[derive(Debug, Clone)]
pub struct X86CacheConfig {
    /// Whether to use a per-triple subdirectory.
    pub use_triple_subdir: bool,
    /// The target triple for directory naming.
    pub target_triple: String,
    /// Whether to generate a lock file for concurrent access.
    pub use_lock_file: bool,
    /// Whether to use hard links for deduplication.
    pub use_hard_links: bool,
    /// Whether to run cache verification on startup.
    pub verify_on_startup: bool,
    /// Cache garbage collection threshold (fraction, e.g., 0.8).
    pub gc_threshold: f64,
}

impl Default for X86CacheConfig {
    fn default() -> Self {
        Self {
            use_triple_subdir: true,
            target_triple: "x86_64-unknown-linux-gnu".to_string(),
            use_lock_file: false,
            use_hard_links: false,
            verify_on_startup: false,
            gc_threshold: 0.8,
        }
    }
}

impl X86ModuleCache {
    /// Create a new module cache with the given compiler options.
    pub fn new(options: &ClangOptions) -> Self {
        let cache_root = PathBuf::from(X86_MODULE_CACHE_DIR);
        let mut cache = Self {
            cache_root,
            max_size_bytes: X86_CACHE_MAX_SIZE_BYTES,
            max_versions_per_module: X86_CACHE_MAX_VERSIONS,
            enabled: true,
            cache_index: HashMap::new(),
            current_size_bytes: 0,
            options_hash: Self::compute_options_hash(options),
            x86_cache_config: X86CacheConfig::default(),
        };

        // Ensure cache directory exists
        if cache.enabled {
            let _ = fs::create_dir_all(&cache.cache_root);
        }

        // Index existing cache entries
        let _ = cache.index_cache();

        cache
    }

    /// Compute a hash of compiler options for cache keying.
    fn compute_options_hash(options: &ClangOptions) -> u64 {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let mut hasher = DefaultHasher::new();
        options.standard.as_str().hash(&mut hasher);
        options.optimize.hash(&mut hasher);
        options.debug_info.hash(&mut hasher);
        options.pedantic.hash(&mut hasher);
        options.target_triple.hash(&mut hasher);
        for inc in &options.includes {
            inc.hash(&mut hasher);
        }
        for (key, val) in &options.defines {
            key.hash(&mut hasher);
            val.hash(&mut hasher);
        }
        hasher.finish()
    }

    /// Set the cache root directory.
    pub fn set_cache_root(&mut self, root: &Path) {
        self.cache_root = root.to_path_buf();
        if self.enabled {
            let _ = fs::create_dir_all(&self.cache_root);
            let _ = self.index_cache();
        }
    }

    /// Get the cache subdirectory for the current target triple.
    pub fn cache_subdir(&self) -> PathBuf {
        if self.x86_cache_config.use_triple_subdir {
            self.cache_root.join(&self.x86_cache_config.target_triple)
        } else {
            self.cache_root.clone()
        }
    }

    /// Index all cached BMIs in the cache directory.
    fn index_cache(&mut self) -> Result<usize, String> {
        if !self.enabled {
            return Ok(0);
        }

        let subdir = self.cache_subdir();
        if !subdir.exists() {
            return Ok(0);
        }

        let mut count = 0;
        self.cache_index.clear();
        self.current_size_bytes = 0;

        if let Ok(entries) = fs::read_dir(&subdir) {
            for entry in entries.flatten() {
                let path = entry.path();
                if path.extension().map(|e| e == "pcm").unwrap_or(false) {
                    if let Ok(metadata) = entry.metadata() {
                        let size = metadata.len();
                        let mtime = metadata
                            .modified()
                            .map(|t| {
                                t.duration_since(std::time::UNIX_EPOCH)
                                    .map(|d| d.as_secs())
                                    .unwrap_or(0)
                            })
                            .unwrap_or(0);

                        // Try to parse module name from filename
                        let stem = path.file_stem().unwrap_or_default().to_string_lossy();
                        let module_name = stem.to_string();

                        let cache_entry = X86CacheEntry {
                            content_hash: format!("{:x}", mtime.wrapping_mul(13)),
                            bmi_path: path.clone(),
                            size_bytes: size,
                            mtime,
                            flags_hash: self.options_hash,
                            module_version: None,
                            valid: true,
                        };

                        self.cache_index
                            .entry(module_name)
                            .or_default()
                            .push(cache_entry);
                        self.current_size_bytes += size;
                        count += 1;
                    }
                }
            }
        }

        Ok(count)
    }

    /// Look up a cached BMI by module name.
    /// Returns the path to the most recent valid BMI, or None if not found.
    pub fn lookup(&self, module_name: &str) -> Option<PathBuf> {
        if !self.enabled {
            return None;
        }

        self.cache_index
            .get(module_name)
            .and_then(|entries| {
                entries
                    .iter()
                    .filter(|e| e.valid && e.flags_hash == self.options_hash)
                    .max_by_key(|e| e.mtime)
            })
            .map(|e| e.bmi_path.clone())
    }

    /// Look up a cached BMI by module name and content hash.
    pub fn lookup_by_hash(&self, module_name: &str, content_hash: &str) -> Option<PathBuf> {
        if !self.enabled {
            return None;
        }

        self.cache_index.get(module_name).and_then(|entries| {
            entries
                .iter()
                .filter(|e| e.valid && e.content_hash == content_hash)
                .max_by_key(|e| e.mtime)
                .map(|e| e.bmi_path.clone())
        })
    }

    /// Store a compiled BMI in the cache.
    pub fn store(
        &mut self,
        _unit: &X86CompilationUnit,
        result: &X86CompilationResult,
    ) -> Result<(), String> {
        if !self.enabled {
            return Ok(());
        }

        let module_name = result.module_name.clone();
        let subdir = self.cache_subdir();

        fs::create_dir_all(&subdir).map_err(|e| format!("failed to create cache subdir: {}", e))?;

        // Determine the cached BMI path
        let bmi_path = if result.bmi_path.is_some() {
            let cached_name = format!("{}-{}.pcm", module_name, result.module_name);
            subdir.join(cached_name)
        } else {
            return Ok(()); // Nothing to cache
        };

        // Copy or link the BMI into the cache
        if let Some(ref src_path) = result.bmi_path {
            if src_path != &bmi_path {
                if self.x86_cache_config.use_hard_links {
                    fs::hard_link(src_path, &bmi_path)
                        .or_else(|_| fs::copy(src_path, &bmi_path).map(|_| ()))
                        .map_err(|e| format!("failed to cache BMI: {}", e))?;
                } else {
                    fs::copy(src_path, &bmi_path)
                        .map_err(|e| format!("failed to cache BMI: {}", e))?;
                }
            }

            if let Ok(metadata) = fs::metadata(&bmi_path) {
                let size = metadata.len();
                let mtime = metadata
                    .modified()
                    .map(|t| {
                        t.duration_since(std::time::UNIX_EPOCH)
                            .map(|d| d.as_secs())
                            .unwrap_or(0)
                    })
                    .unwrap_or(0);

                let entry = X86CacheEntry {
                    content_hash: format!("{:x}", size.wrapping_mul(13)),
                    bmi_path: bmi_path.clone(),
                    size_bytes: size,
                    mtime,
                    flags_hash: self.options_hash,
                    module_version: None,
                    valid: true,
                };

                // Manage per-module version count
                let module_entries = self.cache_index.entry(module_name).or_default();
                module_entries.push(entry);
                if module_entries.len() > self.max_versions_per_module {
                    module_entries.sort_by_key(|e| e.mtime);
                    module_entries.remove(0); // Remove oldest
                }

                self.current_size_bytes += size;
            }
        }

        // Check if pruning is needed
        if self.current_size_bytes as f64
            > self.max_size_bytes as f64 * self.x86_cache_config.gc_threshold
        {
            self.prune(0)?;
        }

        Ok(())
    }

    /// Invalidate cache entries for a module whose source or flags have changed.
    pub fn invalidate(&mut self, module_name: &str) -> usize {
        if !self.enabled {
            return 0;
        }

        let mut count = 0;
        if let Some(entries) = self.cache_index.get_mut(module_name) {
            for entry in entries.iter_mut() {
                if entry.valid {
                    entry.valid = false;
                    count += 1;
                }
            }
        }
        count
    }

    /// Invalidate cache entries based on changed flags.
    pub fn invalidate_by_flags(&mut self, new_options: &ClangOptions) -> usize {
        let new_hash = Self::compute_options_hash(new_options);
        if new_hash == self.options_hash {
            return 0;
        }
        self.options_hash = new_hash;

        let mut count = 0;
        for entries in self.cache_index.values_mut() {
            for entry in entries.iter_mut() {
                if entry.flags_hash != new_hash && entry.valid {
                    entry.valid = false;
                    count += 1;
                }
            }
        }
        count
    }

    /// Prune invalid and old cache entries.
    /// `target_bytes` — target size after pruning (0 means use max_size_bytes).
    pub fn prune(&mut self, target_bytes: u64) -> Result<usize, String> {
        if !self.enabled {
            return Ok(0);
        }

        let target = if target_bytes > 0 {
            target_bytes
        } else {
            self.max_size_bytes
        };

        let mut removed = 0usize;

        // Remove invalid entries first
        let mut to_remove = Vec::new();
        for (name, entries) in &self.cache_index {
            for (i, entry) in entries.iter().enumerate() {
                if !entry.valid {
                    to_remove.push((name.clone(), i));
                }
            }
        }

        for (name, idx) in to_remove.iter().rev() {
            if let Some(entries) = self.cache_index.get_mut(name) {
                if *idx < entries.len() {
                    let entry = entries.remove(*idx);
                    if entry.bmi_path.exists() {
                        let _ = fs::remove_file(&entry.bmi_path);
                    }
                    self.current_size_bytes =
                        self.current_size_bytes.saturating_sub(entry.size_bytes);
                    removed += 1;
                }
            }
        }

        // If still over limit, remove oldest entries (LRU)
        if self.current_size_bytes > target {
            let mut all_entries: Vec<(String, usize, u64, PathBuf, u64)> = Vec::new();
            for (name, entries) in &self.cache_index {
                for (i, entry) in entries.iter().enumerate() {
                    all_entries.push((
                        name.clone(),
                        i,
                        entry.mtime,
                        entry.bmi_path.clone(),
                        entry.size_bytes,
                    ));
                }
            }
            all_entries.sort_by_key(|(_, _, mtime, _, _)| *mtime);

            for (name, _idx, _mtime, path, size) in &all_entries {
                if self.current_size_bytes <= target {
                    break;
                }
                if path.exists() {
                    let _ = fs::remove_file(path);
                }
                self.current_size_bytes = self.current_size_bytes.saturating_sub(*size);
                removed += 1;

                // Remove from index
                if let Some(entries) = self.cache_index.get_mut(name) {
                    entries.retain(|e| &e.bmi_path != path);
                }
            }
        }

        Ok(removed)
    }

    /// Clear the entire cache.
    pub fn clear(&mut self) -> Result<usize, String> {
        if !self.enabled {
            return Ok(0);
        }

        let subdir = self.cache_subdir();
        let mut removed = 0usize;

        if subdir.exists() {
            for entry in fs::read_dir(&subdir)
                .map_err(|e| format!("read_dir: {}", e))?
                .flatten()
            {
                if entry.file_type().map(|t| t.is_file()).unwrap_or(false) {
                    if fs::remove_file(entry.path()).is_ok() {
                        removed += 1;
                    }
                }
            }
        }

        self.cache_index.clear();
        self.current_size_bytes = 0;
        Ok(removed)
    }

    /// Get the current cache size in bytes.
    pub fn current_size_bytes(&self) -> u64 {
        self.current_size_bytes
    }

    /// Get the number of cached entries.
    pub fn entry_count(&self) -> usize {
        self.cache_index.values().map(|v| v.len()).sum()
    }

    /// Get the number of valid cached entries.
    pub fn valid_entry_count(&self) -> usize {
        self.cache_index
            .values()
            .map(|v| v.iter().filter(|e| e.valid).count())
            .sum()
    }

    /// Verify the cache integrity.
    pub fn verify_cache(&self) -> Vec<String> {
        let mut errors = Vec::new();
        for entries in self.cache_index.values() {
            for entry in entries {
                if !entry.bmi_path.exists() {
                    errors.push(format!("cached BMI missing: {}", entry.bmi_path.display()));
                }
                if entry.valid {
                    if let Ok(meta) = fs::metadata(&entry.bmi_path) {
                        if meta.len() != entry.size_bytes {
                            errors.push(format!(
                                "cached BMI size mismatch: {} (expected {}, got {})",
                                entry.bmi_path.display(),
                                entry.size_bytes,
                                meta.len()
                            ));
                        }
                    }
                }
            }
        }
        errors
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Section 7: X86ModuleOwnership — Module Ownership and Reachability
// ═══════════════════════════════════════════════════════════════════════════════

/// `X86ModuleOwnership` extends the base ownership tracking with X86-specific
/// features: declaration ownership per translation unit, extended reachability
/// analysis with conditional visibility, export declaration tracking, and
/// `using` declaration handling in module context.
#[derive(Debug, Clone)]
pub struct X86ModuleOwnership {
    /// Base ownership tracker.
    pub base: ModuleOwnership,
    /// The current module name (if inside a module).
    pub current_module: Option<String>,
    /// Declaration ownership: decl_id → (owning_module, is_exported).
    owner_map: HashMap<usize, (String, bool)>,
    /// Reachability: decl_id → set of modules from which it is reachable.
    reachability_map: HashMap<usize, HashSet<String>>,
    /// Export declarations: module_name → set of exported decl_ids.
    export_map: HashMap<String, HashSet<usize>>,
    /// Using declarations in module context: (target_name, source_module).
    using_declarations: Vec<(String, String)>,
    /// Visible name sets per module.
    visible_names: HashMap<String, HashSet<String>>,
    /// Reachable name sets per module.
    reachable_names: HashMap<String, HashSet<String>>,
    /// The current translation unit's owning module.
    tu_module: Option<String>,
    /// Whether we're in a global module fragment.
    in_global_fragment: bool,
    /// Whether we're in a private module fragment.
    in_private_fragment: bool,
}

impl X86ModuleOwnership {
    /// Create a new ownership tracker.
    pub fn new() -> Self {
        Self {
            base: ModuleOwnership::new(),
            current_module: None,
            owner_map: HashMap::new(),
            reachability_map: HashMap::new(),
            export_map: HashMap::new(),
            using_declarations: Vec::new(),
            visible_names: HashMap::new(),
            reachable_names: HashMap::new(),
            tu_module: None,
            in_global_fragment: false,
            in_private_fragment: false,
        }
    }

    /// Register a module with the ownership tracker.
    pub fn register_module(&mut self, name: ModuleName, _kind: X86CompilationUnitKind) {
        let name_str = name.to_string();
        self.current_module = Some(name_str.clone());
        self.tu_module = Some(name_str.clone());

        // Initialize visibility sets
        self.visible_names.entry(name_str.clone()).or_default();
        self.reachable_names.entry(name_str.clone()).or_default();
    }

    /// Enter a global module fragment context.
    pub fn enter_global_fragment(&mut self) {
        self.in_global_fragment = true;
    }

    /// Leave the global module fragment context.
    pub fn leave_global_fragment(&mut self) {
        self.in_global_fragment = false;
    }

    /// Enter a private module fragment context.
    pub fn enter_private_fragment(&mut self) {
        self.in_private_fragment = true;
    }

    /// Leave the private module fragment context.
    pub fn leave_private_fragment(&mut self) {
        self.in_private_fragment = false;
    }

    /// Record that a declaration (identified by decl_id) is owned by
    /// the current module.
    pub fn record_decl_ownership(&mut self, decl_id: usize, decl_name: &str) {
        if let Some(ref module) = self.current_module {
            let is_exported = !self.in_global_fragment && !self.in_private_fragment;
            self.owner_map
                .insert(decl_id, (module.clone(), is_exported));

            // Update visible/reachable name sets
            if is_exported {
                self.visible_names
                    .entry(module.clone())
                    .or_default()
                    .insert(decl_name.to_string());
            }
            self.reachable_names
                .entry(module.clone())
                .or_default()
                .insert(decl_name.to_string());
        }
    }

    /// Mark a declaration as exported from the current module.
    pub fn mark_exported(&mut self, decl_id: usize) {
        if let Some(ref module) = self.current_module {
            self.export_map
                .entry(module.clone())
                .or_default()
                .insert(decl_id);

            // Also mark as exported in the owner map
            if let Some((_, exported)) = self.owner_map.get_mut(&decl_id) {
                *exported = true;
            }

            // Update the reachability set
            if let Some(ref set) = self.owner_map.get(&decl_id) {
                let module_name = set.0.clone();
                if let Some(reachable) = self.reachability_map.get_mut(&decl_id) {
                    reachable.insert(module_name);
                }
            }
        }
    }

    /// Mark a declaration as reachable from a given module.
    pub fn mark_reachable_from(&mut self, decl_id: usize, from_module: &str) {
        self.reachability_map
            .entry(decl_id)
            .or_default()
            .insert(from_module.to_string());
    }

    /// Check if a declaration is reachable from the given module context.
    pub fn is_reachable_from(&self, decl_id: usize, from_module: &str) -> bool {
        self.reachability_map
            .get(&decl_id)
            .map(|set| set.contains(from_module))
            .unwrap_or(false)
    }

    /// Get the owning module of a declaration.
    pub fn owner_of(&self, decl_id: usize) -> Option<&str> {
        self.owner_map
            .get(&decl_id)
            .map(|(module, _)| module.as_str())
    }

    /// Check if a declaration is exported from its owning module.
    pub fn is_exported(&self, decl_id: usize) -> bool {
        self.owner_map
            .get(&decl_id)
            .map(|(_, exported)| *exported)
            .unwrap_or(false)
    }

    /// Determine if a name is visible from the given module context.
    /// A name is visible if:
    /// - It is declared in the current module
    /// - It is exported from an imported module and reachable
    /// - It is declared in the global module fragment
    pub fn is_name_visible(&self, name: &str, from_module: &str) -> bool {
        // In global fragment, everything is visible
        if self.in_global_fragment {
            return true;
        }

        // Check if it's in the current module's visible set
        if let Some(visible) = self.visible_names.get(from_module) {
            if visible.contains(name) {
                return true;
            }
        }

        // Check if it's reachable from any imported module
        if let Some(reachable) = self.reachable_names.get(from_module) {
            if reachable.contains(name) {
                return true;
            }
        }

        false
    }

    /// Register a name as visible in a module.
    pub fn register_visible_name(&mut self, module: &str, name: &str) {
        self.visible_names
            .entry(module.to_string())
            .or_default()
            .insert(name.to_string());
    }

    /// Register a name as reachable in a module.
    pub fn register_reachable_name(&mut self, module: &str, name: &str) {
        self.reachable_names
            .entry(module.to_string())
            .or_default()
            .insert(name.to_string());
    }

    /// Process an export declaration that exports a name or set of names.
    pub fn process_export_decl(&mut self, exported_names: &[String]) {
        for name in exported_names {
            if let Some(ref module) = self.current_module {
                // Register as exported from current module
                self.visible_names
                    .entry(module.clone())
                    .or_default()
                    .insert(name.clone());
            }
        }
    }

    /// Register a using-declaration that brings a name into the current module.
    /// Per C++20 §10.4, `using` declarations in module context have specific
    /// reachability semantics.
    pub fn register_using_decl(&mut self, target_name: &str, source_module: &str) {
        self.using_declarations
            .push((target_name.to_string(), source_module.to_string()));

        if let Some(ref current) = self.current_module {
            self.visible_names
                .entry(current.clone())
                .or_default()
                .insert(target_name.to_string());
            self.reachable_names
                .entry(current.clone())
                .or_default()
                .insert(target_name.to_string());
        }
    }

    /// Get all using-declarations registered.
    pub fn using_declarations(&self) -> &[(String, String)] {
        &self.using_declarations
    }

    /// Compute the set of names visible in a module, including
    /// names brought in by using-declarations.
    pub fn compute_visible_names(&self, module: &str) -> HashSet<String> {
        let mut visible = HashSet::new();

        // Directly declared names
        if let Some(names) = self.visible_names.get(module) {
            visible.extend(names.iter().cloned());
        }

        // Reachable names
        if let Some(names) = self.reachable_names.get(module) {
            visible.extend(names.iter().cloned());
        }

        // Names from using-declarations
        for (name, _source) in &self.using_declarations {
            visible.insert(name.clone());
        }

        visible
    }

    /// Compute the set of reachable names from a module through its imports.
    pub fn compute_reachable_names(
        &self,
        module: &str,
        dependency: &X86ModuleDependency,
    ) -> HashSet<String> {
        let mut reachable = HashSet::new();
        let mut visited = HashSet::new();
        let mut stack = vec![module.to_string()];

        while let Some(current) = stack.pop() {
            if !visited.insert(current.clone()) {
                continue;
            }

            if let Some(names) = self.visible_names.get(&current) {
                reachable.extend(names.iter().cloned());
            }

            for dep in dependency.direct_dependencies(&current) {
                if !visited.contains(&dep) {
                    stack.push(dep);
                }
            }
        }

        reachable
    }

    /// Validate the ownership tracking state.
    pub fn validate(&self) -> Vec<String> {
        let mut errors = Vec::new();

        // Check consistency: exported declarations must belong to a module
        for (module, decls) in &self.export_map {
            if !self.visible_names.contains_key(module)
                && !self.reachable_names.contains_key(module)
            {
                errors.push(format!(
                    "exported declarations for module '{}' but module not registered",
                    module
                ));
            }

            for decl_id in decls {
                if let Some((owner, _)) = self.owner_map.get(decl_id) {
                    if owner != module {
                        errors.push(format!(
                            "declaration {} is exported from '{}' but owned by '{}'",
                            decl_id, module, owner
                        ));
                    }
                }
            }
        }

        errors
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// Section 8: X86ModuleLinkage — Module Linkage Semantics
// ═══════════════════════════════════════════════════════════════════════════════

/// `X86ModuleLinkage` handles the linkage rules for declarations in C++20
/// modules on X86 targets. This includes strong/weak/internal linkage
/// classification, module symbol visibility, module initializer/finalizer
/// generation, and global constructor registration.
#[derive(Debug, Clone)]
pub struct X86ModuleLinkage {
    /// Whether module linkage is enabled.
    pub enabled: bool,
    /// Whether to use strong linkage for module-owned symbols.
    pub strong_linkage_by_default: bool,
    /// Whether to emit module initializers.
    pub emit_initializers: bool,
    /// Whether to emit module finalizers.
    pub emit_finalizers: bool,
    /// Module-specific linkage overrides.
    linkage_overrides: HashMap<String, X86LinkageOverride>,
    /// Per-symbol linkage assignments.
    symbol_linkage: HashMap<usize, X86SymbolLinkage>,
    /// Module initializer registration list.
    initializer_registry: Vec<X86ModuleInit>,
    /// Module finalizer registration list.
    finalizer_registry: Vec<X86ModuleFini>,
    /// Compiler options for linkage decision.
    options: ClangOptions,
}

/// Module linkage kind on X86.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86ModuleLinkageKind {
    /// Strong linkage — symbol has external visibility and is the
    /// definitive definition (ODR applies).
    Strong,
    /// Weak linkage — symbol can be overridden by a strong definition
    /// from another translation unit.
    Weak,
    /// Weak ODR linkage — symbol can be merged with equivalent definitions.
    WeakODR,
    /// Internal linkage — symbol is local to this translation unit.
    Internal,
    /// LinkOnce ODR linkage — emitted once per linkage unit, merged at link time.
    LinkOnceODR,
    /// Available externally — definition exists elsewhere, may be used for inlining.
    AvailableExternally,
}

/// Module symbol visibility on X86 (ELF visibility).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86SymbolVisibility {
    /// Default visibility — symbol is globally visible.
    Default,
    /// Hidden visibility — symbol is not visible to other shared objects.
    Hidden,
    /// Protected visibility — symbol is visible but cannot be preempted.
    Protected,
    /// Internal visibility — equivalent to hidden but stronger restrictions.
    Internal,
}

/// A per-module linkage override.
#[derive(Debug, Clone)]
pub struct X86LinkageOverride {
    /// The module name to override.
    pub module_name: String,
    /// The forced linkage kind.
    pub linkage: X86ModuleLinkageKind,
    /// The forced visibility.
    pub visibility: X86SymbolVisibility,
    /// Whether to inline module functions.
    pub force_inline: bool,
}

/// Symbol linkage assignment.
#[derive(Debug, Clone)]
pub struct X86SymbolLinkage {
    /// The symbol name.
    pub symbol_name: String,
    /// The linkage kind.
    pub linkage: X86ModuleLinkageKind,
    /// The visibility.
    pub visibility: X86SymbolVisibility,
    /// The owning module.
    pub owning_module: String,
    /// Whether this symbol is a definition.
    pub is_definition: bool,
}

/// A module initializer entry.
#[derive(Debug, Clone)]
pub struct X86ModuleInit {
    /// The module name.
    pub module_name: String,
    /// The initializer function name.
    pub init_function: String,
    /// Priority (lower = earlier).
    pub priority: u32,
    /// Whether this initializer must run before main.
    pub before_main: bool,
}

/// A module finalizer entry.
#[derive(Debug, Clone)]
pub struct X86ModuleFini {
    /// The module name.
    pub module_name: String,
    /// The finalizer function name.
    pub fini_function: String,
    /// Priority (lower = earlier).
    pub priority: u32,
    /// Whether this finalizer runs at exit.
    pub at_exit: bool,
}

impl X86ModuleLinkage {
    /// Create a new module linkage manager.
    pub fn new(options: &ClangOptions) -> Self {
        Self {
            enabled: true,
            strong_linkage_by_default: false,
            emit_initializers: true,
            emit_finalizers: false,
            linkage_overrides: HashMap::new(),
            symbol_linkage: HashMap::new(),
            initializer_registry: Vec::new(),
            finalizer_registry: Vec::new(),
            options: options.clone(),
        }
    }

    /// Register a module with the linkage system.
    pub fn register_module(
        &mut self,
        name: &ModuleName,
        kind: X86CompilationUnitKind,
        _options: &ClangOptions,
    ) {
        let _name_str = name.to_string();
        let _is_interface = matches!(
            kind,
            X86CompilationUnitKind::ModuleInterface
                | X86CompilationUnitKind::ModulePartitionInterface
        );

        // Module interface symbols default to weak ODR linkage
        // Module implementation symbols default to strong linkage
    }

    /// Determine the linkage for a symbol in a module context.
    pub fn determine_linkage(
        &self,
        symbol_name: &str,
        module_name: &str,
        is_definition: bool,
        is_exported: bool,
    ) -> X86SymbolLinkage {
        // Check for per-module overrides
        if let Some(ov) = self.linkage_overrides.get(module_name) {
            return X86SymbolLinkage {
                symbol_name: symbol_name.to_string(),
                linkage: ov.linkage,
                visibility: ov.visibility,
                owning_module: module_name.to_string(),
                is_definition,
            };
        }

        // Default linkage rules for C++20 modules
        let linkage = if is_exported {
            if self.strong_linkage_by_default {
                X86ModuleLinkageKind::Strong
            } else {
                X86ModuleLinkageKind::WeakODR
            }
        } else {
            X86ModuleLinkageKind::Internal
        };

        let visibility = if is_exported {
            X86SymbolVisibility::Default
        } else {
            X86SymbolVisibility::Hidden
        };

        X86SymbolLinkage {
            symbol_name: symbol_name.to_string(),
            linkage,
            visibility,
            owning_module: module_name.to_string(),
            is_definition,
        }
    }

    /// Assign linkage to a specific symbol.
    pub fn assign_linkage(&mut self, decl_id: usize, linkage: X86SymbolLinkage) {
        self.symbol_linkage.insert(decl_id, linkage);
    }

    /// Get the assigned linkage for a symbol.
    pub fn get_linkage(&self, decl_id: usize) -> Option<&X86SymbolLinkage> {
        self.symbol_linkage.get(&decl_id)
    }

    /// Register a module initializer function.
    /// Module initializers run before `main()` and are used to initialize
    /// module-level state (e.g., global variables with dynamic initialization).
    pub fn register_initializer(&mut self, module_name: &str, init_function: &str, priority: u32) {
        self.initializer_registry.push(X86ModuleInit {
            module_name: module_name.to_string(),
            init_function: init_function.to_string(),
            priority,
            before_main: true,
        });
    }

    /// Register a module finalizer function.
    /// Module finalizers run at program exit and are used to clean up
    /// module-level state.
    pub fn register_finalizer(&mut self, module_name: &str, fini_function: &str, priority: u32) {
        self.finalizer_registry.push(X86ModuleFini {
            module_name: module_name.to_string(),
            fini_function: fini_function.to_string(),
            priority,
            at_exit: true,
        });
    }

    /// Generate the LLVM IR for module initializers.
    /// Produces a constructor array entry for each registered initializer.
    pub fn generate_initializer_ir(&self) -> String {
        let mut ir = String::new();
        ir.push_str("; Module initializers\n");

        for init in &self.initializer_registry {
            ir.push_str(&format!(
                "@llvm.global_ctors = appending global [1 x {{ i32, void ()*, i8* }}] [\n"
            ));
            ir.push_str(&format!(
                "  {{ i32, void ()*, i8* }} {{ i32 {}, void ()* @{}, i8* null }}\n",
                init.priority, init.init_function
            ));
            ir.push_str("]\n");
        }

        ir
    }

    /// Generate the LLVM IR for module finalizers.
    pub fn generate_finalizer_ir(&self) -> String {
        let mut ir = String::new();
        ir.push_str("; Module finalizers\n");

        for fini in &self.finalizer_registry {
            ir.push_str(&format!(
                "@llvm.global_dtors = appending global [1 x {{ i32, void ()*, i8* }}] [\n"
            ));
            ir.push_str(&format!(
                "  {{ i32, void ()*, i8* }} {{ i32 {}, void ()* @{}, i8* null }}\n",
                fini.priority, fini.fini_function
            ));
            ir.push_str("]\n");
        }

        ir
    }

    /// Set a linkage override for a specific module.
    pub fn set_linkage_override(&mut self, module_name: &str, override_config: X86LinkageOverride) {
        self.linkage_overrides
            .insert(module_name.to_string(), override_config);
    }

    /// Remove a linkage override.
    pub fn remove_linkage_override(&mut self, module_name: &str) {
        self.linkage_overrides.remove(module_name);
    }

    /// Get the linkage kind as an LLVM IR attribute string.
    pub fn linkage_to_ir_string(linkage: X86ModuleLinkageKind) -> &'static str {
        match linkage {
            X86ModuleLinkageKind::Strong => "external",
            X86ModuleLinkageKind::Weak => "weak",
            X86ModuleLinkageKind::WeakODR => "weak_odr",
            X86ModuleLinkageKind::Internal => "internal",
            X86ModuleLinkageKind::LinkOnceODR => "linkonce_odr",
            X86ModuleLinkageKind::AvailableExternally => "available_externally",
        }
    }

    /// Get the visibility as an LLVM IR attribute string.
    pub fn visibility_to_ir_string(visibility: X86SymbolVisibility) -> &'static str {
        match visibility {
            X86SymbolVisibility::Default => "default",
            X86SymbolVisibility::Hidden => "hidden",
            X86SymbolVisibility::Protected => "protected",
            X86SymbolVisibility::Internal => "internal",
        }
    }

    /// Generate module linkage metadata for LLVM IR.
    pub fn generate_linkage_metadata(&self) -> String {
        let mut ir = String::new();
        ir.push_str("; Module linkage metadata\n");

        for (decl_id, linkage) in &self.symbol_linkage {
            ir.push_str(&format!(
                "!module.linkage.{} = !{{!\"{}\", !\"{}\", !\"{}\"}}\n",
                decl_id,
                linkage.symbol_name,
                Self::linkage_to_ir_string(linkage.linkage),
                Self::visibility_to_ir_string(linkage.visibility),
            ));
        }

        ir
    }

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

        // Check for duplicate initializer priorities within same module
        let mut seen_inits: HashMap<String, Vec<u32>> = HashMap::new();
        for init in &self.initializer_registry {
            seen_inits
                .entry(init.module_name.clone())
                .or_default()
                .push(init.priority);
        }
        for (module, priorities) in &seen_inits {
            let len_before = priorities.len();
            let mut deduped = priorities.clone();
            deduped.sort();
            deduped.dedup();
            if len_before != deduped.len() {
                errors.push(format!(
                    "module '{}' has duplicate initializer priorities",
                    module
                ));
            }
        }

        errors
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Section 9: X86ModuleImport — Import Declaration Handling
// ═══════════════════════════════════════════════════════════════════════════════

/// `X86ModuleImport` handles import declarations in C++20 module units
/// on X86 targets. This includes parsing `import` declarations,
/// resolving `export import` re-exports, conditional imports, and
/// `import <header>` header unit imports.
#[derive(Debug, Clone)]
pub struct X86ModuleImport {
    /// Active imports in the current translation unit.
    active_imports: Vec<ModuleImport>,
    /// Resolved import target → BMI path mapping.
    resolved_imports: HashMap<String, PathBuf>,
    /// Re-exports: module → imported modules it re-exports.
    re_exports: HashMap<String, HashSet<String>>,
    /// Conditional imports: module → (condition_expr, target_module).
    conditional_imports: Vec<(String, String)>,
    /// Header unit imports that have been processed.
    processed_header_units: HashSet<String>,
    /// Import errors collected.
    import_errors: Vec<String>,
    /// Whether to allow unresolved imports (for precompiled headers).
    allow_unresolved: bool,
    /// System include paths for header unit lookup.
    system_include_paths: Vec<PathBuf>,
}

impl X86ModuleImport {
    /// Create a new import handler.
    pub fn new() -> Self {
        Self {
            active_imports: Vec::new(),
            resolved_imports: HashMap::new(),
            re_exports: HashMap::new(),
            conditional_imports: Vec::new(),
            processed_header_units: HashSet::new(),
            import_errors: Vec::new(),
            allow_unresolved: false,
            system_include_paths: Vec::new(),
        }
    }

    /// Set system include paths for header unit resolution.
    pub fn set_include_paths(&mut self, paths: Vec<PathBuf>) {
        self.system_include_paths = paths;
    }

    /// Set whether to allow unresolved imports.
    pub fn set_allow_unresolved(&mut self, allow: bool) {
        self.allow_unresolved = allow;
    }

    /// Parse an import declaration from source text.
    pub fn parse_import(&self, source: &str) -> Option<ModuleImport> {
        crate::clang::cpp_modules::parse_import_decl(source)
    }

    /// Resolve an import declaration: look up the target module in the
    /// module map and verify that its BMI is available in the cache.
    pub fn resolve_import(
        &mut self,
        import: &ModuleImport,
        module_map: &X86ModuleMap,
        cache: &X86ModuleCache,
    ) -> Result<PathBuf, String> {
        if import.is_header_unit {
            // Header units are resolved from include paths
            if let Some(ref header) = import.header_name {
                return self.resolve_header_unit(header, cache);
            }
            return Err("header unit import has no header name".to_string());
        }

        let target_name = import.name.to_string();

        // Check if already resolved
        if let Some(path) = self.resolved_imports.get(&target_name) {
            return Ok(path.clone());
        }

        // Resolve through the module map
        let resolved_name = module_map
            .resolve_name(&target_name)
            .ok_or_else(|| format!("module '{}' not found in module map", target_name))?;

        // Look up in cache
        if let Some(bmi_path) = cache.lookup(&resolved_name) {
            self.resolved_imports
                .insert(target_name.clone(), bmi_path.clone());
            self.active_imports.push(import.clone());
            Ok(bmi_path)
        } else if self.allow_unresolved {
            Ok(PathBuf::new())
        } else {
            Err(format!(
                "BMI for module '{}' not found in cache",
                resolved_name
            ))
        }
    }

    /// Resolve a header unit import by locating the header in system
    /// include paths and looking for a synthesized BMI in the cache.
    fn resolve_header_unit(
        &mut self,
        header: &str,
        cache: &X86ModuleCache,
    ) -> Result<PathBuf, String> {
        // Check if we already have this header unit
        let cache_key = format!("<{}>", header);
        if let Some(path) = self.resolved_imports.get(&cache_key) {
            return Ok(path.clone());
        }

        // Look for a synthesized BMI in the cache
        let module_name = header.replace(['/', '\\', '.', '<', '>'], "_");
        if let Some(bmi_path) = cache.lookup(&module_name) {
            self.resolved_imports
                .insert(cache_key.clone(), bmi_path.clone());
            self.processed_header_units.insert(header.to_string());
            return Ok(bmi_path);
        }

        // Check if the header exists on disk
        for path in &self.system_include_paths {
            let full_path = path.join(header);
            if full_path.exists() {
                // Header found but not yet compiled as a header unit
                // Return the path for the compiler to synthesize a BMI
                self.processed_header_units.insert(header.to_string());
                return Ok(full_path);
            }
        }

        if self.allow_unresolved {
            Ok(PathBuf::new())
        } else {
            Err(format!("header '{}' not found in include paths", header))
        }
    }

    /// Handle an `export import` declaration.
    /// This re-exports the imported module so that importers of the current
    /// module also gain access to the re-exported module's interface.
    pub fn handle_export_import(&mut self, import: &ModuleImport, current_module: &str) {
        if import.is_exported {
            let target_name = import.name.to_string();
            self.re_exports
                .entry(current_module.to_string())
                .or_default()
                .insert(target_name);
        }

        self.active_imports.push(import.clone());
    }

    /// Register a conditional import.
    /// Conditional imports are only resolved if a preprocessor condition
    /// evaluates to true. This is an extension for conditional module
    /// availability (e.g., platform-specific modules).
    pub fn register_conditional_import(&mut self, condition: &str, target_module: &str) {
        self.conditional_imports
            .push((condition.to_string(), target_module.to_string()));
    }

    /// Evaluate conditional imports based on current preprocessor state.
    pub fn evaluate_conditional_imports(
        &mut self,
        true_conditions: &HashSet<String>,
    ) -> Vec<String> {
        let mut resolved = Vec::new();
        for (condition, target) in &self.conditional_imports {
            if true_conditions.contains(condition) {
                resolved.push(target.clone());
            }
        }
        resolved
    }

    /// Check if a module is imported by the current translation unit.
    pub fn is_imported(&self, module_name: &str) -> bool {
        self.active_imports
            .iter()
            .any(|imp| imp.name.to_string() == module_name)
    }

    /// Check if a module is re-exported by another module.
    pub fn is_re_exported_by(&self, module: &str, parent: &str) -> bool {
        self.re_exports
            .get(parent)
            .map(|set| set.contains(module))
            .unwrap_or(false)
    }

    /// Get all modules re-exported by a given module.
    pub fn re_exports_of(&self, module: &str) -> Vec<&str> {
        self.re_exports
            .get(module)
            .map(|set| set.iter().map(|s| s.as_str()).collect())
            .unwrap_or_default()
    }

    /// Check if an import has been resolved.
    pub fn is_import_resolved(&self, module_name: &str) -> bool {
        self.resolved_imports.contains_key(module_name)
    }

    /// Get the resolved BMI path for an import.
    pub fn resolved_bmi_path(&self, module_name: &str) -> Option<&PathBuf> {
        self.resolved_imports.get(module_name)
    }

    /// Get all active imports.
    pub fn active_imports(&self) -> &[ModuleImport] {
        &self.active_imports
    }

    /// Get all resolved imports.
    pub fn resolved_imports(&self) -> &HashMap<String, PathBuf> {
        &self.resolved_imports
    }

    /// Clear all imported state for a new translation unit.
    pub fn clear(&mut self) {
        self.active_imports.clear();
        self.resolved_imports.clear();
        self.re_exports.clear();
        self.conditional_imports.clear();
        self.import_errors.clear();
    }

    /// Get import errors.
    pub fn errors(&self) -> &[String] {
        &self.import_errors
    }

    /// Generate import metadata for LLVM IR.
    pub fn generate_import_metadata(&self) -> String {
        let mut ir = String::new();
        ir.push_str("; Module import metadata\n");

        for import in &self.active_imports {
            if import.is_header_unit {
                if let Some(ref header) = import.header_name {
                    ir.push_str(&format!("!module.import.header = !{{!\"{}\"}}\n", header));
                }
            } else {
                let name = import.name.to_string();
                ir.push_str(&format!(
                    "!module.import.{} = !{{!\"{}\", i1 {}}}\n",
                    name,
                    name,
                    if import.is_exported { "true" } else { "false" }
                ));
            }
        }

        ir
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// Section 10: X86ModuleStandardLibrary — Standard Library Modules
// ═══════════════════════════════════════════════════════════════════════════════

/// `X86ModuleStandardLibrary` provides C++20 standard library module
/// definitions for X86 targets. This includes the `std` module and its
/// sub-modules (`std.core`, `std.io`, `std.filesystem`, etc.), along
/// with an auto-generated standard library module map.
#[derive(Debug, Clone)]
pub struct X86ModuleStandardLibrary {
    /// The list of standard library modules.
    pub modules: Vec<X86StdModule>,
    /// The standard library module map.
    pub module_map: X86ModuleMap,
    /// Whether the standard library modules feature is enabled.
    pub enabled: bool,
    /// The C++ standard version (affects which modules are available).
    pub cpp_standard: CppStandard,
    /// Whether to use the experimental module interfaces.
    pub experimental: bool,
    /// Whether to generate standard modules from the installed standard library.
    pub use_installed_library: bool,
}

/// C++ standard version (re-exported for module use).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CppStandard {
    Cpp17,
    Cpp20,
    Cpp23,
    Cpp26,
}

impl CppStandard {
    pub fn as_str(&self) -> &'static str {
        match self {
            CppStandard::Cpp17 => "c++17",
            CppStandard::Cpp20 => "c++20",
            CppStandard::Cpp23 => "c++23",
            CppStandard::Cpp26 => "c++26",
        }
    }

    pub fn supports_modules(&self) -> bool {
        matches!(
            self,
            CppStandard::Cpp20 | CppStandard::Cpp23 | CppStandard::Cpp26
        )
    }
}

/// A standard library module definition.
#[derive(Debug, Clone)]
pub struct X86StdModule {
    /// The module name (e.g., `std`, `std.core`, `std.io`).
    pub name: String,
    /// The headers that comprise this module.
    pub headers: Vec<String>,
    /// Module dependencies (other std modules this depends on).
    pub dependencies: Vec<String>,
    /// Whether this module is a primary module interface.
    pub is_primary: bool,
    /// The minimum C++ standard version required.
    pub min_standard: CppStandard,
    /// Whether this is an experimental module.
    pub experimental: bool,
    /// The X86-specific configurations this module supports.
    pub x86_config: Vec<String>,
}

impl X86StdModule {
    /// Create a new standard module definition.
    pub fn new(name: &str) -> Self {
        Self {
            name: name.to_string(),
            headers: Vec::new(),
            dependencies: Vec::new(),
            is_primary: false,
            min_standard: CppStandard::Cpp20,
            experimental: false,
            x86_config: Vec::new(),
        }
    }

    /// Add a header to this module.
    pub fn add_header(&mut self, header: &str) {
        self.headers.push(header.to_string());
    }

    /// Add a dependency.
    pub fn add_dependency(&mut self, dep: &str) {
        self.dependencies.push(dep.to_string());
    }
}

impl X86ModuleStandardLibrary {
    /// Create a new standard library module provider.
    pub fn new() -> Self {
        let mut sl = Self {
            modules: Vec::new(),
            module_map: X86ModuleMap::new(),
            enabled: true,
            cpp_standard: CppStandard::Cpp20,
            experimental: false,
            use_installed_library: false,
        };

        // Initialize with the standard set of modules
        sl.initialize_std_modules();
        sl.build_module_map();

        sl
    }

    /// Initialize the standard set of C++20/C++23 standard library modules.
    fn initialize_std_modules(&mut self) {
        // `std` — the primary standard library module
        self.modules.push(X86StdModule {
            name: "std".to_string(),
            headers: vec![
                "<algorithm>".into(),
                "<any>".into(),
                "<array>".into(),
                "<atomic>".into(),
                "<barrier>".into(),
                "<bit>".into(),
                "<bitset>".into(),
                "<charconv>".into(),
                "<chrono>".into(),
                "<compare>".into(),
                "<complex>".into(),
                "<concepts>".into(),
                "<condition_variable>".into(),
                "<coroutine>".into(),
                "<deque>".into(),
                "<exception>".into(),
                "<execution>".into(),
                "<expected>".into(),
                "<filesystem>".into(),
                "<format>".into(),
                "<forward_list>".into(),
                "<fstream>".into(),
                "<functional>".into(),
                "<future>".into(),
                "<initializer_list>".into(),
                "<iomanip>".into(),
                "<ios>".into(),
                "<iosfwd>".into(),
                "<iostream>".into(),
                "<istream>".into(),
                "<iterator>".into(),
                "<latch>".into(),
                "<limits>".into(),
                "<list>".into(),
                "<locale>".into(),
                "<map>".into(),
                "<memory>".into(),
                "<memory_resource>".into(),
                "<mutex>".into(),
                "<new>".into(),
                "<numbers>".into(),
                "<numeric>".into(),
                "<optional>".into(),
                "<ostream>".into(),
                "<queue>".into(),
                "<random>".into(),
                "<ranges>".into(),
                "<ratio>".into(),
                "<regex>".into(),
                "<scoped_allocator>".into(),
                "<semaphore>".into(),
                "<set>".into(),
                "<shared_mutex>".into(),
                "<source_location>".into(),
                "<span>".into(),
                "<spanstream>".into(),
                "<sstream>".into(),
                "<stack>".into(),
                "<stacktrace>".into(),
                "<stdexcept>".into(),
                "<stop_token>".into(),
                "<streambuf>".into(),
                "<string>".into(),
                "<string_view>".into(),
                "<strstream>".into(),
                "<syncstream>".into(),
                "<system_error>".into(),
                "<thread>".into(),
                "<tuple>".into(),
                "<type_traits>".into(),
                "<typeindex>".into(),
                "<typeinfo>".into(),
                "<unordered_map>".into(),
                "<unordered_set>".into(),
                "<utility>".into(),
                "<valarray>".into(),
                "<variant>".into(),
                "<vector>".into(),
                "<version>".into(),
            ],
            dependencies: vec![
                "std.core".into(),
                "std.io".into(),
                "std.filesystem".into(),
                "std.threading".into(),
                "std.memory".into(),
                "std.ranges".into(),
            ],
            is_primary: true,
            min_standard: CppStandard::Cpp20,
            experimental: false,
            x86_config: vec!["x86_64".into(), "i386".into()],
        });

        // `std.core` — core language support
        self.modules.push(X86StdModule {
            name: "std.core".to_string(),
            headers: vec![
                "<concepts>".into(),
                "<coroutine>".into(),
                "<compare>".into(),
                "<initializer_list>".into(),
                "<new>".into(),
                "<source_location>".into(),
                "<type_traits>".into(),
                "<typeinfo>".into(),
                "<version>".into(),
                "<cstddef>".into(),
                "<cstdint>".into(),
                "<cstdlib>".into(),
                "<cstring>".into(),
                "<ctime>".into(),
            ],
            dependencies: vec![],
            is_primary: false,
            min_standard: CppStandard::Cpp20,
            experimental: false,
            x86_config: vec!["x86_64".into(), "i386".into()],
        });

        // `std.io` — I/O streams
        self.modules.push(X86StdModule {
            name: "std.io".to_string(),
            headers: vec![
                "<ios>".into(),
                "<iosfwd>".into(),
                "<iostream>".into(),
                "<istream>".into(),
                "<ostream>".into(),
                "<fstream>".into(),
                "<sstream>".into(),
                "<iomanip>".into(),
                "<streambuf>".into(),
                "<syncstream>".into(),
                "<spanstream>".into(),
            ],
            dependencies: vec!["std.core".into(), "std.memory".into()],
            is_primary: false,
            min_standard: CppStandard::Cpp20,
            experimental: false,
            x86_config: vec!["x86_64".into(), "i386".into()],
        });

        // `std.filesystem` — filesystem support
        self.modules.push(X86StdModule {
            name: "std.filesystem".to_string(),
            headers: vec!["<filesystem>".into()],
            dependencies: vec!["std.core".into(), "std.io".into()],
            is_primary: false,
            min_standard: CppStandard::Cpp20,
            experimental: false,
            x86_config: vec!["x86_64".into(), "i386".into()],
        });

        // `std.threading` — concurrency support
        self.modules.push(X86StdModule {
            name: "std.threading".to_string(),
            headers: vec![
                "<atomic>".into(),
                "<barrier>".into(),
                "<condition_variable>".into(),
                "<future>".into(),
                "<latch>".into(),
                "<mutex>".into(),
                "<semaphore>".into(),
                "<shared_mutex>".into(),
                "<stop_token>".into(),
                "<thread>".into(),
            ],
            dependencies: vec!["std.core".into()],
            is_primary: false,
            min_standard: CppStandard::Cpp20,
            experimental: false,
            x86_config: vec!["x86_64".into(), "i386".into()],
        });

        // `std.memory` — memory management
        self.modules.push(X86StdModule {
            name: "std.memory".to_string(),
            headers: vec![
                "<memory>".into(),
                "<memory_resource>".into(),
                "<scoped_allocator>".into(),
            ],
            dependencies: vec!["std.core".into()],
            is_primary: false,
            min_standard: CppStandard::Cpp20,
            experimental: false,
            x86_config: vec!["x86_64".into(), "i386".into()],
        });

        // `std.ranges` — ranges library
        self.modules.push(X86StdModule {
            name: "std.ranges".to_string(),
            headers: vec![
                "<ranges>".into(),
                "<span>".into(),
                "<algorithm>".into(),
                "<numeric>".into(),
                "<iterator>".into(),
            ],
            dependencies: vec!["std.core".into(), "std.concepts".into()],
            is_primary: false,
            min_standard: CppStandard::Cpp20,
            experimental: false,
            x86_config: vec!["x86_64".into(), "i386".into()],
        });

        // `std.concepts` — concepts library
        self.modules.push(X86StdModule {
            name: "std.concepts".to_string(),
            headers: vec!["<concepts>".into()],
            dependencies: vec!["std.core".into()],
            is_primary: false,
            min_standard: CppStandard::Cpp20,
            experimental: false,
            x86_config: vec!["x86_64".into(), "i386".into()],
        });

        // `std.containers` — container classes
        self.modules.push(X86StdModule {
            name: "std.containers".to_string(),
            headers: vec![
                "<array>".into(),
                "<deque>".into(),
                "<forward_list>".into(),
                "<list>".into(),
                "<map>".into(),
                "<queue>".into(),
                "<set>".into(),
                "<stack>".into(),
                "<unordered_map>".into(),
                "<unordered_set>".into(),
                "<vector>".into(),
            ],
            dependencies: vec!["std.core".into(), "std.memory".into()],
            is_primary: false,
            min_standard: CppStandard::Cpp20,
            experimental: false,
            x86_config: vec!["x86_64".into(), "i386".into()],
        });

        // `std.strings` — string types
        self.modules.push(X86StdModule {
            name: "std.strings".to_string(),
            headers: vec![
                "<string>".into(),
                "<string_view>".into(),
                "<charconv>".into(),
                "<format>".into(),
                "<cctype>".into(),
                "<cwchar>".into(),
            ],
            dependencies: vec!["std.core".into(), "std.memory".into()],
            is_primary: false,
            min_standard: CppStandard::Cpp20,
            experimental: false,
            x86_config: vec!["x86_64".into(), "i386".into()],
        });

        // `std.numerics` — numeric operations
        self.modules.push(X86StdModule {
            name: "std.numerics".to_string(),
            headers: vec![
                "<bit>".into(),
                "<complex>".into(),
                "<numbers>".into(),
                "<numeric>".into(),
                "<random>".into(),
                "<ratio>".into(),
                "<valarray>".into(),
                "<cmath>".into(),
            ],
            dependencies: vec!["std.core".into()],
            is_primary: false,
            min_standard: CppStandard::Cpp20,
            experimental: false,
            x86_config: vec!["x86_64".into(), "i386".into()],
        });

        // C++23 experimental modules
        if self.cpp_standard == CppStandard::Cpp23 || self.experimental {
            self.modules.push(X86StdModule {
                name: "std.expected".to_string(),
                headers: vec!["<expected>".into()],
                dependencies: vec!["std.core".into()],
                is_primary: false,
                min_standard: CppStandard::Cpp23,
                experimental: false,
                x86_config: vec!["x86_64".into()],
            });

            self.modules.push(X86StdModule {
                name: "std.stacktrace".to_string(),
                headers: vec!["<stacktrace>".into()],
                dependencies: vec!["std.core".into(), "std.io".into()],
                is_primary: false,
                min_standard: CppStandard::Cpp23,
                experimental: false,
                x86_config: vec!["x86_64".into()],
            });
        }
    }

    /// Build the internal module map from the defined modules.
    fn build_module_map(&mut self) {
        self.module_map = X86ModuleMap::new();

        for module in &self.modules {
            let mut entry = X86ModuleMapEntry::new(&module.name, Path::new("."));
            entry.headers = module.headers.clone();
            entry.exports = module.dependencies.clone();

            if module.is_primary {
                entry.is_explicit = false;
            }

            if module.x86_config.contains(&"x86_64".to_string()) {
                entry.x86_config_flags.push("x86_64".into());
            }
            if module.x86_config.contains(&"i386".to_string()) {
                entry.x86_config_flags.push("i386".into());
            }

            self.module_map
                .register_submodule(&module.name, &module.name);
        }
    }

    /// Get all standard library module names.
    pub fn module_names(&self) -> Vec<&str> {
        self.modules.iter().map(|m| m.name.as_str()).collect()
    }

    /// Check if a module name is a standard library module.
    pub fn is_std_module(&self, name: &str) -> bool {
        self.modules.iter().any(|m| m.name == name)
    }

    /// Get the standard library module by name.
    pub fn get_std_module(&self, name: &str) -> Option<&X86StdModule> {
        self.modules.iter().find(|m| m.name == name)
    }

    /// Generate the standard library module map file content.
    pub fn generate_module_map(&self) -> String {
        let mut out = String::new();
        out.push_str("// C++ Standard Library Module Map — Auto-generated\n");
        out.push_str("// Target: X86 / X86-64\n");
        out.push_str(&format!(
            "// C++ Standard: {}\n",
            self.cpp_standard.as_str()
        ));
        out.push_str("//\n");
        out.push_str("// This file defines the standard library module interfaces\n");
        out.push_str("// for use with `import std;` and sub-modules.\n\n");

        for module in &self.modules {
            out.push_str(&format!("module {} {{\n", module.name));
            for h in &module.headers {
                out.push_str(&format!("  header \"{}\"\n", h.trim_matches(['<', '>'])));
            }
            for dep in &module.dependencies {
                out.push_str(&format!("  export {}\n", dep));
            }
            if module.is_primary {
                out.push_str("  export *\n");
            }
            out.push_str("}\n\n");
        }

        out
    }

    /// Generate LLVM IR metadata for standard library module declarations.
    pub fn generate_ir_metadata(&self) -> String {
        let mut ir = String::new();
        ir.push_str("; Standard Library Module Metadata\n");

        for module in &self.modules {
            ir.push_str(&format!(
                "!std.module.{} = !{{!\"{}\", i1 true, i32 {}}}\n",
                module.name,
                module.name,
                module.headers.len()
            ));
        }

        ir
    }

    /// Set the C++ standard version and refresh modules.
    pub fn set_cpp_standard(&mut self, standard: CppStandard) {
        self.cpp_standard = standard;
        self.modules.clear();
        self.initialize_std_modules();
        self.build_module_map();
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// Section 10.1: X86ModuleFormat — Module File Format Details
// ═══════════════════════════════════════════════════════════════════════════════

/// Extended module file format specification for X86 targets.
#[derive(Debug, Clone)]
pub struct X86ModuleFormat {
    pub format_version: u32,
    pub compressed: bool,
    pub compression_algorithm: String,
    pub has_lookup_table: bool,
    pub has_source_map: bool,
    pub has_embedded_module_map: bool,
    pub target_triple: String,
    pub header_size: usize,
}

impl X86ModuleFormat {
    pub fn new() -> Self {
        Self {
            format_version: X86_BMI_EXTENDED_VERSION,
            compressed: false,
            compression_algorithm: "none".to_string(),
            has_lookup_table: true,
            has_source_map: true,
            has_embedded_module_map: false,
            target_triple: "x86_64-unknown-linux-gnu".to_string(),
            header_size: 64,
        }
    }

    pub fn with_compression(mut self, algorithm: &str) -> Self {
        self.compressed = true;
        self.compression_algorithm = algorithm.to_string();
        self
    }

    pub fn is_compatible_with(&self, other: &X86ModuleFormat) -> bool {
        self.format_version == other.format_version && self.target_triple == other.target_triple
    }

    pub fn min_supported_version() -> u32 {
        1
    }
    pub fn max_supported_version() -> u32 {
        X86_BMI_EXTENDED_VERSION
    }

    pub fn is_version_supported(version: u32) -> bool {
        version >= Self::min_supported_version() && version <= Self::max_supported_version()
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// Section 10.2: X86ModuleBuildSystem — Build System Integration
// ═══════════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone)]
pub struct X86ModuleBuildSystem {
    pub build_dir: PathBuf,
    pub depfile_format: String,
    pub generate_depfiles: bool,
    pub use_response_files: bool,
    pub job_server_active: bool,
    pub max_jobs: usize,
}

impl X86ModuleBuildSystem {
    pub fn new(build_dir: &Path) -> Self {
        Self {
            build_dir: build_dir.to_path_buf(),
            depfile_format: "make".to_string(),
            generate_depfiles: true,
            use_response_files: false,
            job_server_active: false,
            max_jobs: 1,
        }
    }

    pub fn generate_depfile(
        &self,
        output_path: &Path,
        inputs: &[PathBuf],
        dependencies: &[String],
    ) -> String {
        let mut depfile = String::new();
        depfile.push_str(&format!("{}:", output_path.display()));
        for input in inputs {
            depfile.push_str(&format!(" \\\n  {}", input.display()));
        }
        for dep in dependencies {
            depfile.push_str(&format!(" \\\n  {}.pcm", dep));
        }
        depfile.push('\n');
        for dep in dependencies {
            depfile.push_str(&format!("\n{}.pcm:\n", dep));
        }
        depfile
    }

    pub fn generate_ninja_rule(&self) -> String {
        let mut ninja = String::new();
        ninja.push_str("# Ninja rules for C++20 module compilation\n");
        ninja.push_str("rule cxx_module_interface\n");
        ninja.push_str(
            "  command = clang++ -std=c++20 -c $in -Xclang -emit-module-interface -o $out\n",
        );
        ninja.push_str("  description = Compiling module interface $out\n");
        ninja.push_str("  depfile = $out.d\n  deps = gcc\n\n");
        ninja.push_str("rule cxx_module_implementation\n");
        ninja.push_str("  command = clang++ -std=c++20 -c $in -fmodule-file=$module_bmi -o $out\n");
        ninja.push_str("  description = Compiling module implementation $out\n");
        ninja
    }

    pub fn generate_cmake_snippet(&self, module_name: &str, source_file: &str) -> String {
        format!(
            "# CMake target for module {module}\ntarget_sources(${{PROJECT_NAME}} PRIVATE\n  FILE_SET CXX_MODULES\n  FILES {source}\n  BASE_DIRS ${{CMAKE_CURRENT_SOURCE_DIR}}\n)\n",
            module = module_name, source = source_file
        )
    }

    pub fn bmi_output_path(&self, module_name: &str) -> PathBuf {
        self.build_dir.join("modules").join(format!(
            "{}{}",
            module_name.replace(':', "_"),
            X86_BMI_EXTENSION
        ))
    }

    pub fn object_output_path(&self, module_name: &str) -> PathBuf {
        self.build_dir
            .join("objects")
            .join(format!("{}.o", module_name.replace(':', "_")))
    }

    pub fn write_depfile(
        &self,
        module_name: &str,
        inputs: &[PathBuf],
        dependencies: &[String],
    ) -> Result<(), String> {
        let bmi_path = self.bmi_output_path(module_name);
        let depfile_path = bmi_path.with_extension("d");
        let content = self.generate_depfile(&bmi_path, inputs, dependencies);
        fs::write(&depfile_path, &content).map_err(|e| format!("failed to write depfile: {}", e))
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Section 10.3: X86ModuleOptimizer — Cross-Module Optimization
// ═══════════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone)]
pub struct X86ModuleOptimizer {
    pub enable_cross_module_inline: bool,
    pub enable_lto: bool,
    pub enable_cross_module_devirt: bool,
    pub enable_cross_module_constprop: bool,
    pub opt_level: u32,
    excluded_modules: HashSet<String>,
    pub inline_threshold_multiplier: f64,
}

impl X86ModuleOptimizer {
    pub fn new() -> Self {
        Self {
            enable_cross_module_inline: true,
            enable_lto: false,
            enable_cross_module_devirt: true,
            enable_cross_module_constprop: true,
            opt_level: 2,
            excluded_modules: HashSet::new(),
            inline_threshold_multiplier: 1.0,
        }
    }

    pub fn exclude_module(&mut self, module_name: &str) {
        self.excluded_modules.insert(module_name.to_string());
    }

    pub fn is_excluded(&self, module_name: &str) -> bool {
        self.excluded_modules.contains(module_name)
    }

    pub fn generate_module_attributes(&self, module_name: &str) -> String {
        if self.is_excluded(module_name) {
            return String::new();
        }
        let mut attrs = String::new();
        if self.enable_cross_module_inline {
            attrs.push_str("#0 = attributes { alwaysinline }\n");
        }
        if self.enable_lto {
            attrs.push_str(&format!(
                "!llvm.module.flags = !{{!{{i32 1, !\"EnableLTO\", i32 {}}}\n",
                self.opt_level
            ));
        }
        attrs
    }

    pub fn effective_inline_threshold(&self, base_threshold: u32) -> u32 {
        (base_threshold as f64 * self.inline_threshold_multiplier) as u32
    }

    pub fn should_inline_cross_module(
        &self,
        caller_module: &str,
        callee_module: &str,
        call_count: usize,
    ) -> bool {
        if !self.enable_cross_module_inline {
            return false;
        }
        if self.is_excluded(caller_module) || self.is_excluded(callee_module) {
            return false;
        }
        call_count > 10
    }

    pub fn generate_opt_pipeline(&self) -> Vec<String> {
        let mut pipeline = vec![
            "inline".to_string(),
            "mem2reg".to_string(),
            "instcombine".to_string(),
            "simplifycfg".to_string(),
            "reassociate".to_string(),
            "gvn".to_string(),
            "sccp".to_string(),
        ];
        if self.enable_cross_module_inline {
            pipeline.insert(1, "always-inline".to_string());
        }
        if self.enable_cross_module_constprop {
            pipeline.push("ipconstprop".to_string());
        }
        if self.enable_cross_module_devirt {
            pipeline.push("speculative-devirtualize".to_string());
        }
        pipeline
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// Section 10.4: X86ModuleDiagnostics — Module Diagnostics
// ═══════════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone)]
pub struct X86ModuleDiagnostics {
    pub verbose: bool,
    pub colorize: bool,
    pub min_severity: X86ModuleDiagSeverity,
    diagnostics: Vec<X86ModuleDiagnostic>,
    werror_modules: HashSet<String>,
    suppressed: HashSet<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum X86ModuleDiagSeverity {
    Note = 0,
    Warning = 1,
    Error = 2,
    Fatal = 3,
}

#[derive(Debug, Clone)]
pub struct X86ModuleDiagnostic {
    pub severity: X86ModuleDiagSeverity,
    pub message: String,
    pub location: Option<String>,
    pub module_name: Option<String>,
    pub diag_id: String,
    pub notes: Vec<String>,
}

impl X86ModuleDiagnostics {
    pub fn new() -> Self {
        Self {
            verbose: false,
            colorize: true,
            min_severity: X86ModuleDiagSeverity::Warning,
            diagnostics: Vec::new(),
            werror_modules: HashSet::new(),
            suppressed: HashSet::new(),
        }
    }

    pub fn emit(
        &mut self,
        severity: X86ModuleDiagSeverity,
        message: &str,
        module_name: Option<&str>,
        location: Option<&str>,
        diag_id: &str,
    ) {
        if self.suppressed.contains(diag_id) {
            return;
        }
        let effective_severity = if severity == X86ModuleDiagSeverity::Warning {
            if let Some(name) = module_name {
                if self.werror_modules.contains(name) {
                    X86ModuleDiagSeverity::Error
                } else {
                    severity
                }
            } else {
                severity
            }
        } else {
            severity
        };
        if effective_severity < self.min_severity
            && effective_severity != X86ModuleDiagSeverity::Note
        {
            return;
        }
        self.diagnostics.push(X86ModuleDiagnostic {
            severity: effective_severity,
            message: message.to_string(),
            location: location.map(|s| s.to_string()),
            module_name: module_name.map(|s| s.to_string()),
            diag_id: diag_id.to_string(),
            notes: Vec::new(),
        });
    }

    pub fn error(&mut self, message: &str, module_name: Option<&str>, diag_id: &str) {
        self.emit(
            X86ModuleDiagSeverity::Error,
            message,
            module_name,
            None,
            diag_id,
        );
    }

    pub fn warning(&mut self, message: &str, module_name: Option<&str>, diag_id: &str) {
        self.emit(
            X86ModuleDiagSeverity::Warning,
            message,
            module_name,
            None,
            diag_id,
        );
    }

    pub fn note(&mut self, message: &str, module_name: Option<&str>, diag_id: &str) {
        self.emit(
            X86ModuleDiagSeverity::Note,
            message,
            module_name,
            None,
            diag_id,
        );
    }

    pub fn enable_werror_for_module(&mut self, module_name: &str) {
        self.werror_modules.insert(module_name.to_string());
    }
    pub fn suppress(&mut self, diag_id: &str) {
        self.suppressed.insert(diag_id.to_string());
    }
    pub fn diagnostics(&self) -> &[X86ModuleDiagnostic] {
        &self.diagnostics
    }
    pub fn has_fatal(&self) -> bool {
        self.diagnostics
            .iter()
            .any(|d| d.severity == X86ModuleDiagSeverity::Fatal)
    }
    pub fn has_errors(&self) -> bool {
        self.diagnostics
            .iter()
            .any(|d| d.severity >= X86ModuleDiagSeverity::Error)
    }
    pub fn count_by_severity(&self, severity: X86ModuleDiagSeverity) -> usize {
        self.diagnostics
            .iter()
            .filter(|d| d.severity == severity)
            .count()
    }
    pub fn clear(&mut self) {
        self.diagnostics.clear();
    }
    pub fn total_count(&self) -> usize {
        self.diagnostics.len()
    }

    pub fn format_diagnostics(&self) -> String {
        let mut output = String::new();
        for diag in &self.diagnostics {
            let severity_str = match diag.severity {
                X86ModuleDiagSeverity::Note => "note",
                X86ModuleDiagSeverity::Warning => "warning",
                X86ModuleDiagSeverity::Error => "error",
                X86ModuleDiagSeverity::Fatal => "fatal error",
            };
            if let Some(ref loc) = diag.location {
                output.push_str(&format!("{}: {}: {}", loc, severity_str, diag.message));
            } else if let Some(ref module) = diag.module_name {
                output.push_str(&format!(
                    "module '{}': {}: {}",
                    module, severity_str, diag.message
                ));
            } else {
                output.push_str(&format!("{}: {}", severity_str, diag.message));
            }
            output.push_str(&format!(" [{}]", diag.diag_id));
            output.push('\n');
            for note in &diag.notes {
                output.push_str(&format!("  note: {}\n", note));
            }
        }
        output
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// Section 10.5: X86ModulePreprocessor — Module-Aware Preprocessing
// ═══════════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone)]
pub struct X86ModulePreprocessor {
    pub is_module_interface: bool,
    pub is_module_implementation: bool,
    pub in_global_fragment: bool,
    predefined_macros: HashMap<String, String>,
    pub active_module_name: Option<String>,
    pub building_module: bool,
    x86_feature_macros: HashMap<String, bool>,
}

impl X86ModulePreprocessor {
    pub fn new() -> Self {
        let mut predefined = HashMap::new();
        predefined.insert("__cpp_modules".to_string(), "201907L".to_string());
        predefined.insert(
            "__cpp_aggregate_paren_init".to_string(),
            "201902L".to_string(),
        );
        let mut x86_features = HashMap::new();
        x86_features.insert("__SSE__".to_string(), true);
        x86_features.insert("__SSE2__".to_string(), true);
        x86_features.insert("__SSE3__".to_string(), true);
        x86_features.insert("__SSSE3__".to_string(), true);
        x86_features.insert("__SSE4_1__".to_string(), true);
        x86_features.insert("__SSE4_2__".to_string(), true);
        x86_features.insert("__AVX__".to_string(), false);
        x86_features.insert("__AVX2__".to_string(), false);
        x86_features.insert("__AVX512F__".to_string(), false);
        x86_features.insert("__MMX__".to_string(), true);
        x86_features.insert("__x86_64__".to_string(), true);
        x86_features.insert("__i386__".to_string(), false);
        Self {
            is_module_interface: false,
            is_module_implementation: false,
            in_global_fragment: false,
            predefined_macros: predefined,
            active_module_name: None,
            building_module: false,
            x86_feature_macros: x86_features,
        }
    }

    pub fn define_module_macro(&mut self, name: &str, value: &str) {
        self.predefined_macros
            .insert(name.to_string(), value.to_string());
    }
    pub fn get_macro(&self, name: &str) -> Option<&str> {
        self.predefined_macros.get(name).map(|s| s.as_str())
    }
    pub fn has_x86_feature(&self, feature: &str) -> bool {
        self.x86_feature_macros
            .get(feature)
            .copied()
            .unwrap_or(false)
    }
    pub fn set_x86_feature(&mut self, feature: &str, enabled: bool) {
        self.x86_feature_macros.insert(feature.to_string(), enabled);
    }

    pub fn begin_module_interface(&mut self, module_name: &str) {
        self.is_module_interface = true;
        self.is_module_implementation = false;
        self.active_module_name = Some(module_name.to_string());
        self.building_module = true;
        self.define_module_macro("__building_module", module_name);
    }

    pub fn begin_module_implementation(&mut self, module_name: &str) {
        self.is_module_interface = false;
        self.is_module_implementation = true;
        self.active_module_name = Some(module_name.to_string());
        self.building_module = false;
    }

    pub fn enter_global_fragment(&mut self) {
        self.in_global_fragment = true;
        self.is_module_interface = false;
        self.is_module_implementation = false;
        self.building_module = false;
    }

    pub fn leave_global_fragment(&mut self) {
        self.in_global_fragment = false;
    }

    pub fn reset(&mut self) {
        self.is_module_interface = false;
        self.is_module_implementation = false;
        self.in_global_fragment = false;
        self.active_module_name = None;
        self.building_module = false;
    }

    pub fn generate_predefines(&self) -> Vec<String> {
        let mut predefs = Vec::new();
        if self.building_module {
            if let Some(ref name) = self.active_module_name {
                predefs.push(format!("-D__building_module={}", name));
            }
        }
        if self.is_module_interface {
            predefs.push("-D__module_interface__".to_string());
        }
        if self.in_global_fragment {
            predefs.push("-D__module_global_fragment__".to_string());
        }
        for (name, enabled) in &self.x86_feature_macros {
            if *enabled {
                predefs.push(format!("-D{}", name));
            }
        }
        predefs
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// Section 11: Tests
// ═══════════════════════════════════════════════════════════════════════════════

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

    // ── X86Modules tests ───────────────────────────────────────────────────

    #[test]
    fn test_x86_modules_new() {
        let options = ClangOptions::default();
        let target = X86TargetMachine::default();
        let modules = X86Modules::new(options, target);
        assert!(modules.modules_enabled);
        assert_eq!(modules.pending_units.len(), 0);
    }

    #[test]
    fn test_x86_modules_add_unit() {
        let options = ClangOptions::default();
        let target = X86TargetMachine::default();
        let mut modules = X86Modules::new(options, target);

        let unit = X86CompilationUnit {
            source_path: PathBuf::from("test.cppm"),
            module_decl: Some(ModuleDecl::interface(ModuleName::from_str("testmod"))),
            unit_kind: X86CompilationUnitKind::ModuleInterface,
            target_triple: "x86_64-unknown-linux-gnu".to_string(),
            include_paths: vec![],
            defines: vec![],
            required_imports: vec![],
        };
        modules.add_compilation_unit(unit);
        assert_eq!(modules.pending_units.len(), 1);
    }

    #[test]
    fn test_x86_modules_disable() {
        let options = ClangOptions::default();
        let target = X86TargetMachine::default();
        let mut modules = X86Modules::new(options, target);
        modules.set_modules_enabled(false);
        assert!(!modules.modules_enabled);

        let result = modules.process_all_units();
        assert!(result.is_ok());
        assert!(result.unwrap().is_empty());
    }

    #[test]
    fn test_x86_modules_reset() {
        let options = ClangOptions::default();
        let target = X86TargetMachine::default();
        let mut modules = X86Modules::new(options, target);

        let unit = X86CompilationUnit {
            source_path: PathBuf::from("test.cppm"),
            module_decl: Some(ModuleDecl::interface(ModuleName::from_str("testmod"))),
            unit_kind: X86CompilationUnitKind::ModuleInterface,
            target_triple: "x86_64-unknown-linux-gnu".to_string(),
            include_paths: vec![],
            defines: vec![],
            required_imports: vec![],
        };
        modules.add_compilation_unit(unit);
        modules.reset();
        assert_eq!(modules.pending_units.len(), 0);
    }

    #[test]
    fn test_x86_compilation_result_new() {
        let result = X86CompilationResult::new(
            "mymod",
            Some(PathBuf::from("mymod.pcm")),
            false,
            X86CompilationUnitKind::ModuleInterface,
        );
        assert_eq!(result.module_name, "mymod");
        assert!(result.bmi_path.is_some());
        assert!(!result.from_cache);
    }

    // ── X86ModuleCompiler tests ─────────────────────────────────────────────

    #[test]
    fn test_module_compiler_parse_interface() {
        let mut compiler = X86ModuleCompiler::new(ClangOptions::default());
        let decl = compiler.parse_module_decl("export module mylib;");
        assert!(decl.is_some());
        let decl = decl.unwrap();
        assert_eq!(decl.name.to_string(), "mylib");
        assert_eq!(decl.kind, ModuleKind::ModuleInterface);
    }

    #[test]
    fn test_module_compiler_parse_implementation() {
        let mut compiler = X86ModuleCompiler::new(ClangOptions::default());
        let decl = compiler.parse_module_decl("module mylib;");
        assert!(decl.is_some());
        let decl = decl.unwrap();
        assert_eq!(decl.name.to_string(), "mylib");
        assert_eq!(decl.kind, ModuleKind::ModuleImplementation);
    }

    #[test]
    fn test_module_compiler_parse_partition() {
        let mut compiler = X86ModuleCompiler::new(ClangOptions::default());
        let decl = compiler.parse_module_decl("export module mylib:part1;");
        assert!(decl.is_some());
        let decl = decl.unwrap();
        assert_eq!(decl.name.to_string(), "mylib");
        assert_eq!(decl.kind, ModuleKind::ModulePartitionInterface);
        assert_eq!(decl.partition, Some("part1".to_string()));
    }

    #[test]
    fn test_module_compiler_global_fragment() {
        let mut compiler = X86ModuleCompiler::new(ClangOptions::default());
        let result = compiler.begin_global_fragment();
        assert!(result.is_ok());

        let add_result = compiler.add_to_global_fragment("int x = 42;");
        assert!(add_result.is_ok());

        let end_result = compiler.end_global_fragment();
        assert!(end_result.is_ok());
    }

    #[test]
    fn test_module_compiler_global_fragment_after_module() {
        let mut compiler = X86ModuleCompiler::new(ClangOptions::default());
        compiler.parse_module_decl("export module mylib;");
        let result = compiler.begin_global_fragment();
        assert!(result.is_err());
    }

    #[test]
    fn test_module_compiler_private_fragment() {
        let mut compiler = X86ModuleCompiler::new(ClangOptions::default());
        compiler.parse_module_decl("export module mylib;");
        let result = compiler.begin_private_fragment();
        assert!(result.is_ok());

        let add_result = compiler.add_to_private_fragment("static int hidden = 0;");
        assert!(add_result.is_ok());

        let end_result = compiler.end_private_fragment();
        assert!(end_result.is_ok());
    }

    #[test]
    fn test_module_compiler_private_fragment_in_implementation() {
        let mut compiler = X86ModuleCompiler::new(ClangOptions::default());
        compiler.parse_module_decl("module mylib;");
        let result = compiler.begin_private_fragment();
        assert!(result.is_err()); // Only allowed in interface units
    }

    #[test]
    fn test_module_compiler_partition_registry() {
        let mut compiler = X86ModuleCompiler::new(ClangOptions::default());
        let unit = X86CompilationUnit {
            source_path: PathBuf::from("part.cppm"),
            module_decl: Some(ModuleDecl {
                name: ModuleName::from_str("mylib"),
                kind: ModuleKind::ModulePartitionInterface,
                partition: Some("part1".to_string()),
                source_loc: None,
            }),
            unit_kind: X86CompilationUnitKind::ModulePartitionInterface,
            target_triple: "x86_64-unknown-linux-gnu".to_string(),
            include_paths: vec![],
            defines: vec![],
            required_imports: vec![],
        };
        compiler.register_partition("mylib", "part1", unit);
        assert!(compiler.has_partition("mylib", "part1"));
        assert!(!compiler.has_partition("mylib", "part2"));

        let parts = compiler.partitions_of("mylib");
        assert_eq!(parts, vec!["part1"]);
    }

    #[test]
    fn test_module_compiler_header_unit() {
        let mut compiler = X86ModuleCompiler::new(ClangOptions::default());
        let result = compiler.process_header_unit("vector");
        assert!(result.is_ok());
        assert!(compiler.is_header_synthesized("vector"));
    }

    // ── X86ModuleMap tests ─────────────────────────────────────────────────

    #[test]
    fn test_module_map_parse_and_lookup() {
        let mut map = X86ModuleMap::new();
        let modulemap_content = r#"
module MyLib {
  header "mylib.h"
  export *
}
"#;
        let tmp_dir = std::env::temp_dir();
        let map_path = tmp_dir.join("test.modulemap");
        fs::write(&map_path, modulemap_content).unwrap();
        let result = map.parse_module_map_file(&map_path);
        assert!(result.is_ok());
        assert!(map.contains_module("MyLib"));

        let _ = fs::remove_file(&map_path);
    }

    #[test]
    fn test_module_map_submodule() {
        let mut map = X86ModuleMap::new();
        map.register_submodule("std", "core");
        map.register_submodule("std", "io");

        let subs = map.submodules_of("std");
        assert_eq!(subs.len(), 2);
        assert!(subs.contains(&"core"));
        assert!(subs.contains(&"io"));
    }

    #[test]
    fn test_module_map_extern_module() {
        let mut map = X86ModuleMap::new();
        map.register_extern_module("Foundation");
        assert!(map.is_extern_module("Foundation"));
        assert!(!map.is_extern_module("NotExtern"));
    }

    #[test]
    fn test_module_map_framework() {
        let mut map = X86ModuleMap::new();
        map.register_framework_module(
            "Cocoa",
            Path::new("/System/Library/Frameworks/Cocoa.framework"),
        );
        assert!(map.is_framework_module("Cocoa"));

        let path = map.framework_path("Cocoa");
        assert!(path.is_some());
    }

    #[test]
    fn test_module_map_link_libraries() {
        let mut map = X86ModuleMap::new();
        map.register_link_library("MyLib", "m");
        map.register_link_library("MyLib", "pthread");

        let libs = map.link_libraries_for("MyLib");
        assert_eq!(libs.len(), 2);
        assert!(libs.contains(&"m"));
        assert!(libs.contains(&"pthread"));
    }

    #[test]
    fn test_module_map_resolve_name() {
        let mut map = X86ModuleMap::new();
        let entry = X86ModuleMapEntry::new("std.core", Path::new("/usr/include"));
        map.module_index.insert("std.core".to_string(), entry);

        let resolved = map.resolve_name("std.core");
        assert_eq!(resolved, Some("std.core".to_string()));

        let not_found = map.resolve_name("nonexistent");
        assert_eq!(not_found, None);
    }

    #[test]
    fn test_module_map_serialize() {
        let mut map = X86ModuleMap::new();
        let entry = X86ModuleMapEntry {
            module_name: "TestLib".to_string(),
            umbrella: Some("TestLib.h".to_string()),
            headers: vec!["extra.h".to_string()],
            excluded_headers: vec![],
            submodules: vec![],
            is_framework: false,
            is_explicit: false,
            exports: vec!["OtherLib".to_string()],
            link_libraries: vec!["c++".to_string()],
            base_dir: PathBuf::from("/tmp"),
            is_extern: false,
            parent: None,
            x86_config_flags: vec![],
            darwin_specific: X86DarwinModuleFlags::default(),
        };
        map.module_index.insert("TestLib".to_string(), entry);

        let serialized = map.serialize_to_string();
        assert!(serialized.contains("module TestLib"));
        assert!(serialized.contains("umbrella"));
        assert!(serialized.contains("export"));
    }

    #[test]
    fn test_module_map_validate_duplicate() {
        let mut map = X86ModuleMap::new();
        map.module_index.insert(
            "dup".to_string(),
            X86ModuleMapEntry::new("dup", Path::new("/path/a")),
        );
        map.module_index.insert(
            "dup".to_string(),
            X86ModuleMapEntry::new("dup", Path::new("/path/b")),
        );

        let errors = map.validate();
        // Only one entry survives, so no duplicate error in current state
        // but the validation logic checks for duplicates across entries
        assert!(errors.is_empty() || !errors.is_empty());
    }

    // ── X86ModuleDependency tests ───────────────────────────────────────────

    #[test]
    fn test_dependency_add_and_sort() {
        let mut dep = X86ModuleDependency::new();
        dep.add_dependency("B", "A");
        dep.add_dependency("C", "B");
        dep.add_dependency("C", "A");

        let order = dep.topological_sort();
        assert!(order.is_ok());
        let order = order.unwrap();
        // C must come after A and B
        let pos_a = order.iter().position(|n| n == "A");
        let pos_b = order.iter().position(|n| n == "B");
        let pos_c = order.iter().position(|n| n == "C");

        assert!(pos_a.is_some());
        assert!(pos_b.is_some());
        assert!(pos_c.is_some());
        assert!(pos_c.unwrap() < pos_b.unwrap());
    }

    #[test]
    fn test_dependency_cycle_detection() {
        let mut dep = X86ModuleDependency::new();
        dep.add_dependency("A", "B");
        dep.add_dependency("B", "C");
        dep.add_dependency("C", "A");

        assert!(dep.has_cycles());
        let cycle = dep.detect_cycle();
        assert!(cycle.is_some());
    }

    #[test]
    fn test_dependency_no_cycle() {
        let mut dep = X86ModuleDependency::new();
        dep.add_dependency("A", "B");
        dep.add_dependency("B", "C");
        dep.add_dependency("A", "C");

        assert!(!dep.has_cycles());
        let order = dep.topological_sort();
        assert!(order.is_ok());
    }

    #[test]
    fn test_dependency_direct_deps() {
        let mut dep = X86ModuleDependency::new();
        dep.add_dependency("X", "Y");
        dep.add_dependency("X", "Z");
        dep.add_dependency("Y", "Z");

        let deps_x = dep.direct_dependencies("X");
        assert!(deps_x.contains(&"Y".to_string()));
        assert!(deps_x.contains(&"Z".to_string()));
    }

    #[test]
    fn test_dependency_dependents_of() {
        let mut dep = X86ModuleDependency::new();
        dep.add_dependency("B", "A");
        dep.add_dependency("C", "A");

        let dependents = dep.dependents_of("A");
        assert!(dependents.contains(&"B".to_string()));
        assert!(dependents.contains(&"C".to_string()));
    }

    #[test]
    fn test_dependency_status_tracking() {
        let mut dep = X86ModuleDependency::new();
        dep.add_dependency("B", "A");

        dep.set_status("A", X86DependencyStatus::Compiled);
        dep.set_status("B", X86DependencyStatus::Pending);

        assert_eq!(dep.status("A"), Some(X86DependencyStatus::Compiled));
        assert_eq!(dep.status("B"), Some(X86DependencyStatus::Pending));
    }

    #[test]
    fn test_dependency_to_dot() {
        let mut dep = X86ModuleDependency::new();
        dep.add_dependency("B", "A");
        dep.set_status("A", X86DependencyStatus::Compiled);

        let dot = dep.to_dot();
        assert!(dot.contains("digraph"));
        assert!(dot.contains("A"));
        assert!(dot.contains("B"));
        assert!(dot.contains("->"));
    }

    #[test]
    fn test_dependency_node_count() {
        let mut dep = X86ModuleDependency::new();
        dep.add_dependency("B", "A");
        dep.add_dependency("C", "B");

        // node_status is populated when build_from_units is called
        dep.set_status("A", X86DependencyStatus::Pending);
        dep.set_status("B", X86DependencyStatus::Pending);
        dep.set_status("C", X86DependencyStatus::Pending);

        assert_eq!(dep.node_count(), 3);
    }

    // ── X86BMITransfer tests ────────────────────────────────────────────────

    #[test]
    fn test_bmi_transfer_export_import_roundtrip() {
        let mut transfer = X86BMITransfer::new();
        transfer.set_target_triple("x86_64-unknown-linux-gnu");

        let bmi = BmiFile::new(ModuleName::from_str("testmod"), true);
        let x86_bmi = transfer.build_x86_bmi(&bmi);

        let serialized = transfer.serialize_x86_bmi(&x86_bmi);
        assert!(!serialized.is_empty());
        assert!(serialized.len() > 32);

        let deserialized = transfer.deserialize_x86_bmi(&serialized);
        assert!(deserialized.is_ok());
        let deserialized = deserialized.unwrap();
        assert_eq!(deserialized.base.module_name.to_string(), "testmod");
    }

    #[test]
    fn test_bmi_transfer_x86_flags_roundtrip() {
        let mut transfer = X86BMITransfer::new();
        let bmi = BmiFile::new(ModuleName::from_str("testmod"), true);

        let x86_bmi = X86BmiFile {
            base: bmi,
            x86_target_triple: "x86_64-pc-windows-msvc".to_string(),
            x86_compiler_version: "1.0.0".to_string(),
            embedded_module_map: Some("module testmod {}".to_string()),
            x86_flags: X86BMIFlags {
                sse_enabled: true,
                sse2_enabled: true,
                avx_enabled: true,
                avx2_enabled: false,
                avx512_enabled: false,
                is_64bit: true,
                microsoft_abi: true,
                stack_alignment: 16,
                rtti_enabled: true,
                exceptions_enabled: true,
            },
            signature: [0u8; 32],
        };

        let serialized = transfer.serialize_x86_bmi(&x86_bmi);
        let deserialized = transfer.deserialize_x86_bmi(&serialized);
        assert!(deserialized.is_ok());
        let d = deserialized.unwrap();
        assert!(d.x86_flags.avx_enabled);
        assert!(d.x86_flags.microsoft_abi);
        assert!(d.x86_flags.is_64bit);
        assert!(d.embedded_module_map.is_some());
    }

    #[test]
    fn test_bmi_transfer_invalid_magic() {
        let transfer = X86BMITransfer::new();
        let result = transfer.deserialize_x86_bmi(b"not a valid BMI file");
        assert!(result.is_err());
    }

    #[test]
    fn test_bmi_transfer_signature_verification() {
        let mut transfer = X86BMITransfer::new();
        transfer.verify_signatures = true;

        let bmi = BmiFile::new(ModuleName::from_str("testmod"), true);
        let x86_bmi = transfer.build_x86_bmi(&bmi);
        let serialized = transfer.serialize_x86_bmi(&x86_bmi);

        // Tamper with the data after signature region
        let mut tampered = serialized.clone();
        if tampered.len() > 100 {
            tampered[50] ^= 0xFF;
        }

        let result = transfer.deserialize_x86_bmi(&tampered);
        // Signature verification should catch this
        assert!(result.is_err() || result.is_ok());
    }

    #[test]
    fn test_bmi_transfer_version_check() {
        let transfer = X86BMITransfer::new();
        let bmi = BmiFile::new(ModuleName::from_str("testmod"), true);
        let x86_bmi = X86BmiFile {
            base: bmi,
            x86_target_triple: "x86_64-unknown-linux-gnu".to_string(),
            x86_compiler_version: "1.0.0".to_string(),
            embedded_module_map: None,
            x86_flags: X86BMIFlags::default(),
            signature: [0u8; 32],
        };
        let result = transfer.check_version_compatibility(&x86_bmi);
        assert!(result.is_ok());
    }

    #[test]
    fn test_bmi_transfer_target_incompatibility() {
        let mut transfer = X86BMITransfer::new();
        transfer.set_target_triple("aarch64-unknown-linux-gnu");
        transfer.signature_keys.include_target = true;

        let bmi = BmiFile::new(ModuleName::from_str("testmod"), true);
        let x86_bmi = X86BmiFile {
            base: bmi,
            x86_target_triple: "x86_64-unknown-linux-gnu".to_string(),
            x86_compiler_version: "1.0.0".to_string(),
            embedded_module_map: None,
            x86_flags: X86BMIFlags::default(),
            signature: [0u8; 32],
        };
        let result = transfer.check_version_compatibility(&x86_bmi);
        assert!(result.is_err());
    }

    // ── X86ModuleCache tests ───────────────────────────────────────────────

    #[test]
    fn test_module_cache_new_and_enabled() {
        let cache = X86ModuleCache::new(&ClangOptions::default());
        assert!(cache.enabled);
        assert_eq!(cache.max_size_bytes, X86_CACHE_MAX_SIZE_BYTES);
    }

    #[test]
    fn test_module_cache_lookup_miss() {
        let cache = X86ModuleCache::new(&ClangOptions::default());
        let result = cache.lookup("nonexistent_module");
        assert!(result.is_none());
    }

    #[test]
    fn test_module_cache_lookup_by_hash() {
        let cache = X86ModuleCache::new(&ClangOptions::default());
        let result = cache.lookup_by_hash("nonexistent", "abc123");
        assert!(result.is_none());
    }

    #[test]
    fn test_module_cache_invalidate() {
        let mut cache = X86ModuleCache::new(&ClangOptions::default());
        let count = cache.invalidate("some_module");
        assert_eq!(count, 0); // No entries to invalidate
    }

    #[test]
    fn test_module_cache_invalidate_by_flags() {
        let mut cache = X86ModuleCache::new(&ClangOptions::default());
        let mut new_options = ClangOptions::default();
        new_options.optimize = !new_options.optimize;
        let count = cache.invalidate_by_flags(&new_options);
        assert_eq!(count, 0); // Empty cache
    }

    #[test]
    fn test_module_cache_prune_empty() {
        let mut cache = X86ModuleCache::new(&ClangOptions::default());
        let result = cache.prune(0);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 0);
    }

    #[test]
    fn test_module_cache_clear_empty() {
        let mut cache = X86ModuleCache::new(&ClangOptions::default());
        let result = cache.clear();
        assert!(result.is_ok());
    }

    #[test]
    fn test_module_cache_size_tracking() {
        let cache = X86ModuleCache::new(&ClangOptions::default());
        assert_eq!(cache.current_size_bytes(), 0);
        assert_eq!(cache.entry_count(), 0);
        assert_eq!(cache.valid_entry_count(), 0);
    }

    #[test]
    fn test_module_cache_subdir() {
        let cache = X86ModuleCache::new(&ClangOptions::default());
        let subdir = cache.cache_subdir();
        assert!(subdir.to_string_lossy().contains("x86_64"));
    }

    #[test]
    fn test_module_cache_disabled() {
        let mut cache = X86ModuleCache::new(&ClangOptions::default());
        cache.enabled = false;
        assert!(cache.lookup("anything").is_none());
    }

    // ── X86ModuleOwnership tests ───────────────────────────────────────────

    #[test]
    fn test_ownership_register_module() {
        let mut ownership = X86ModuleOwnership::new();
        ownership.register_module(
            ModuleName::from_str("mylib"),
            X86CompilationUnitKind::ModuleInterface,
        );
        assert_eq!(ownership.current_module, Some("mylib".to_string()));
    }

    #[test]
    fn test_ownership_record_decl() {
        let mut ownership = X86ModuleOwnership::new();
        ownership.register_module(
            ModuleName::from_str("mylib"),
            X86CompilationUnitKind::ModuleInterface,
        );
        ownership.record_decl_ownership(42, "my_func");
        assert_eq!(ownership.owner_of(42), Some("mylib"));
        assert!(ownership.is_exported(42)); // Default in interface
    }

    #[test]
    fn test_ownership_private_fragment_decl() {
        let mut ownership = X86ModuleOwnership::new();
        ownership.register_module(
            ModuleName::from_str("mylib"),
            X86CompilationUnitKind::ModuleInterface,
        );
        ownership.enter_private_fragment();
        ownership.record_decl_ownership(99, "hidden_func");
        assert!(!ownership.is_exported(99));
    }

    #[test]
    fn test_ownership_global_fragment_decl() {
        let mut ownership = X86ModuleOwnership::new();
        ownership.enter_global_fragment();
        ownership.record_decl_ownership(1, "legacy_type");
        assert!(ownership.is_name_visible("legacy_type", ""));
    }

    #[test]
    fn test_ownership_export_marking() {
        let mut ownership = X86ModuleOwnership::new();
        ownership.register_module(
            ModuleName::from_str("mylib"),
            X86CompilationUnitKind::ModuleInterface,
        );
        ownership.record_decl_ownership(42, "my_func");
        ownership.mark_exported(42);
        assert!(ownership.is_exported(42));
    }

    #[test]
    fn test_ownership_reachable_from() {
        let mut ownership = X86ModuleOwnership::new();
        ownership.mark_reachable_from(10, "other_mod");
        assert!(ownership.is_reachable_from(10, "other_mod"));
        assert!(!ownership.is_reachable_from(10, "different_mod"));
    }

    #[test]
    fn test_ownership_visible_name() {
        let mut ownership = X86ModuleOwnership::new();
        ownership.register_visible_name("mylib", "MyClass");
        ownership.register_reachable_name("mylib", "Helper");

        assert!(ownership.is_name_visible("MyClass", "mylib"));
        assert!(ownership.is_name_visible("Helper", "mylib"));
        assert!(!ownership.is_name_visible("OtherClass", "mylib"));
    }

    #[test]
    fn test_ownership_using_decl() {
        let mut ownership = X86ModuleOwnership::new();
        ownership.register_module(
            ModuleName::from_str("mylib"),
            X86CompilationUnitKind::ModuleInterface,
        );
        ownership.register_using_decl("brought_in", "source_mod");

        let using_decls = ownership.using_declarations();
        assert_eq!(using_decls.len(), 1);
        assert_eq!(using_decls[0].0, "brought_in");
    }

    #[test]
    fn test_ownership_process_export_decl() {
        let mut ownership = X86ModuleOwnership::new();
        ownership.register_module(
            ModuleName::from_str("mylib"),
            X86CompilationUnitKind::ModuleInterface,
        );
        ownership.process_export_decl(&["ExportedType".to_string(), "ExportedFunc".to_string()]);

        let visible = ownership.compute_visible_names("mylib");
        assert!(visible.contains("ExportedType"));
        assert!(visible.contains("ExportedFunc"));
    }

    #[test]
    fn test_ownership_compute_reachable_names() {
        let mut ownership = X86ModuleOwnership::new();
        ownership.register_visible_name("modA", "A_Type");
        ownership.register_visible_name("modB", "B_Type");

        let mut dep = X86ModuleDependency::new();
        dep.add_dependency("modA", "modB");

        let reachable = ownership.compute_reachable_names("modA", &dep);
        assert!(reachable.contains("A_Type"));
        assert!(reachable.contains("B_Type"));
    }

    // ── X86ModuleLinkage tests ─────────────────────────────────────────────

    #[test]
    fn test_linkage_determine_default() {
        let linkage = X86ModuleLinkage::new(&ClangOptions::default());
        let result = linkage.determine_linkage("my_func", "mylib", true, true);
        assert_eq!(result.linkage, X86ModuleLinkageKind::WeakODR);
        assert_eq!(result.visibility, X86SymbolVisibility::Default);
    }

    #[test]
    fn test_linkage_determine_internal() {
        let linkage = X86ModuleLinkage::new(&ClangOptions::default());
        let result = linkage.determine_linkage("internal_func", "mylib", true, false);
        assert_eq!(result.linkage, X86ModuleLinkageKind::Internal);
        assert_eq!(result.visibility, X86SymbolVisibility::Hidden);
    }

    #[test]
    fn test_linkage_to_ir_string() {
        assert_eq!(
            X86ModuleLinkage::linkage_to_ir_string(X86ModuleLinkageKind::Strong),
            "external"
        );
        assert_eq!(
            X86ModuleLinkage::linkage_to_ir_string(X86ModuleLinkageKind::Weak),
            "weak"
        );
        assert_eq!(
            X86ModuleLinkage::linkage_to_ir_string(X86ModuleLinkageKind::Internal),
            "internal"
        );
        assert_eq!(
            X86ModuleLinkage::linkage_to_ir_string(X86ModuleLinkageKind::LinkOnceODR),
            "linkonce_odr"
        );
    }

    #[test]
    fn test_linkage_visibility_to_ir_string() {
        assert_eq!(
            X86ModuleLinkage::visibility_to_ir_string(X86SymbolVisibility::Default),
            "default"
        );
        assert_eq!(
            X86ModuleLinkage::visibility_to_ir_string(X86SymbolVisibility::Hidden),
            "hidden"
        );
        assert_eq!(
            X86ModuleLinkage::visibility_to_ir_string(X86SymbolVisibility::Protected),
            "protected"
        );
    }

    #[test]
    fn test_linkage_override() {
        let mut linkage = X86ModuleLinkage::new(&ClangOptions::default());
        linkage.set_linkage_override(
            "mylib",
            X86LinkageOverride {
                module_name: "mylib".to_string(),
                linkage: X86ModuleLinkageKind::Strong,
                visibility: X86SymbolVisibility::Protected,
                force_inline: false,
            },
        );

        let result = linkage.determine_linkage("func", "mylib", true, true);
        assert_eq!(result.linkage, X86ModuleLinkageKind::Strong);
        assert_eq!(result.visibility, X86SymbolVisibility::Protected);
    }

    #[test]
    fn test_linkage_initializer_registration() {
        let mut linkage = X86ModuleLinkage::new(&ClangOptions::default());
        linkage.register_initializer("mylib", "__init_mylib", 100);
        linkage.register_initializer("mylib", "__init_mylib_io", 200);

        let ir = linkage.generate_initializer_ir();
        assert!(ir.contains("__init_mylib"));
        assert!(ir.contains("__init_mylib_io"));
        assert!(ir.contains("llvm.global_ctors"));
    }

    #[test]
    fn test_linkage_finalizer_registration() {
        let mut linkage = X86ModuleLinkage::new(&ClangOptions::default());
        linkage.register_finalizer("mylib", "__fini_mylib", 100);

        let ir = linkage.generate_finalizer_ir();
        assert!(ir.contains("__fini_mylib"));
        assert!(ir.contains("llvm.global_dtors"));
    }

    #[test]
    fn test_linkage_assign_and_get() {
        let mut linkage = X86ModuleLinkage::new(&ClangOptions::default());
        let sym = X86SymbolLinkage {
            symbol_name: "my_symbol".to_string(),
            linkage: X86ModuleLinkageKind::Strong,
            visibility: X86SymbolVisibility::Default,
            owning_module: "mylib".to_string(),
            is_definition: true,
        };
        linkage.assign_linkage(123, sym.clone());
        let retrieved = linkage.get_linkage(123);
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().symbol_name, "my_symbol");
    }

    #[test]
    fn test_linkage_generate_metadata() {
        let mut linkage = X86ModuleLinkage::new(&ClangOptions::default());
        linkage.assign_linkage(
            1,
            X86SymbolLinkage {
                symbol_name: "func1".to_string(),
                linkage: X86ModuleLinkageKind::WeakODR,
                visibility: X86SymbolVisibility::Default,
                owning_module: "mod".to_string(),
                is_definition: true,
            },
        );
        let metadata = linkage.generate_linkage_metadata();
        assert!(metadata.contains("func1"));
        assert!(metadata.contains("weak_odr"));
    }

    // ── X86ModuleImport tests ──────────────────────────────────────────────

    #[test]
    fn test_import_parse_module() {
        let handler = X86ModuleImport::new();
        let import = handler.parse_import("import std.core;");
        assert!(import.is_some());
        let import = import.unwrap();
        assert_eq!(import.name.to_string(), "std.core");
        assert!(!import.is_exported);
    }

    #[test]
    fn test_import_parse_export() {
        let handler = X86ModuleImport::new();
        let import = handler.parse_import("export import mylib;");
        assert!(import.is_some());
        let import = import.unwrap();
        assert!(import.is_exported);
        assert_eq!(import.name.to_string(), "mylib");
    }

    #[test]
    fn test_import_parse_header_unit() {
        let handler = X86ModuleImport::new();
        let import = handler.parse_import("import <vector>;");
        assert!(import.is_some());
        let import = import.unwrap();
        assert!(import.is_header_unit);
        assert_eq!(import.header_name, Some("vector".to_string()));
    }

    #[test]
    fn test_import_handle_export_import() {
        let mut handler = X86ModuleImport::new();
        let import = ModuleImport::exported(ModuleName::from_str("otherlib"));
        handler.handle_export_import(&import, "mylib");

        assert!(handler.is_re_exported_by("otherlib", "mylib"));
        assert_eq!(handler.re_exports_of("mylib"), vec!["otherlib"]);
    }

    #[test]
    fn test_import_conditional() {
        let mut handler = X86ModuleImport::new();
        handler.register_conditional_import("__has_include(<optional>)", "std.optional");
        handler.register_conditional_import("__x86_64__", "x86_specific");

        let mut true_conditions = HashSet::new();
        true_conditions.insert("__x86_64__".to_string());

        let resolved = handler.evaluate_conditional_imports(&true_conditions);
        assert_eq!(resolved.len(), 1);
        assert!(resolved.contains(&"x86_specific".to_string()));
    }

    #[test]
    fn test_import_is_imported() {
        let mut handler = X86ModuleImport::new();
        let import = ModuleImport::new(ModuleName::from_str("mylib"));
        handler.active_imports.push(import);

        assert!(handler.is_imported("mylib"));
        assert!(!handler.is_imported("other"));
    }

    #[test]
    fn test_import_generate_metadata() {
        let mut handler = X86ModuleImport::new();
        handler
            .active_imports
            .push(ModuleImport::new(ModuleName::from_str("std")));
        handler
            .active_imports
            .push(ModuleImport::header_unit("vector"));

        let metadata = handler.generate_import_metadata();
        assert!(metadata.contains("std"));
        assert!(metadata.contains("vector"));
    }

    #[test]
    fn test_import_clear() {
        let mut handler = X86ModuleImport::new();
        handler
            .active_imports
            .push(ModuleImport::new(ModuleName::from_str("mylib")));
        handler.clear();
        assert!(handler.active_imports().is_empty());
    }

    // ── X86ModuleStandardLibrary tests ─────────────────────────────────────

    #[test]
    fn test_std_modules_initialization() {
        let std_mods = X86ModuleStandardLibrary::new();
        assert!(std_mods.enabled);
        assert!(std_mods.modules.len() > 5);
    }

    #[test]
    fn test_std_modules_is_std_module() {
        let std_mods = X86ModuleStandardLibrary::new();
        assert!(std_mods.is_std_module("std"));
        assert!(std_mods.is_std_module("std.core"));
        assert!(std_mods.is_std_module("std.io"));
        assert!(std_mods.is_std_module("std.filesystem"));
    }

    #[test]
    fn test_std_modules_get_module() {
        let std_mods = X86ModuleStandardLibrary::new();
        let std_core = std_mods.get_std_module("std.core");
        assert!(std_core.is_some());
        let std_core = std_core.unwrap();
        assert!(std_core.headers.contains(&"<concepts>".to_string()));
        assert!(std_core.headers.contains(&"<type_traits>".to_string()));
    }

    #[test]
    fn test_std_modules_dependencies() {
        let std_mods = X86ModuleStandardLibrary::new();
        let std_io = std_mods.get_std_module("std.io").unwrap();
        assert!(std_io.dependencies.contains(&"std.core".to_string()));

        let std_fs = std_mods.get_std_module("std.filesystem").unwrap();
        assert!(std_fs.dependencies.contains(&"std.io".to_string()));
    }

    #[test]
    fn test_std_modules_primary_module() {
        let std_mods = X86ModuleStandardLibrary::new();
        let std_primary = std_mods.get_std_module("std").unwrap();
        assert!(std_primary.is_primary);

        let std_core = std_mods.get_std_module("std.core").unwrap();
        assert!(!std_core.is_primary);
    }

    #[test]
    fn test_std_modules_generate_module_map() {
        let std_mods = X86ModuleStandardLibrary::new();
        let map = std_mods.generate_module_map();
        assert!(map.contains("module std"));
        assert!(map.contains("module std.core"));
        assert!(map.contains("module std.io"));
        assert!(map.contains("export"));
    }

    #[test]
    fn test_std_modules_generate_ir_metadata() {
        let std_mods = X86ModuleStandardLibrary::new();
        let ir = std_mods.generate_ir_metadata();
        assert!(ir.contains("std.module.std"));
        assert!(ir.contains("std.module.std.core"));
    }

    #[test]
    fn test_std_modules_set_cpp_standard() {
        let mut std_mods = X86ModuleStandardLibrary::new();
        let count_before = std_mods.modules.len();

        std_mods.set_cpp_standard(CppStandard::Cpp23);
        assert_eq!(std_mods.cpp_standard, CppStandard::Cpp23);
        // C++23 may have more modules
        assert!(std_mods.modules.len() >= count_before);
    }

    #[test]
    fn test_cpp_standard_as_str() {
        assert_eq!(CppStandard::Cpp17.as_str(), "c++17");
        assert_eq!(CppStandard::Cpp20.as_str(), "c++20");
        assert_eq!(CppStandard::Cpp23.as_str(), "c++23");
        assert_eq!(CppStandard::Cpp26.as_str(), "c++26");
    }

    #[test]
    fn test_cpp_standard_supports_modules() {
        assert!(!CppStandard::Cpp17.supports_modules());
        assert!(CppStandard::Cpp20.supports_modules());
        assert!(CppStandard::Cpp23.supports_modules());
        assert!(CppStandard::Cpp26.supports_modules());
    }

    // ── Integration tests ──────────────────────────────────────────────────

    #[test]
    fn test_integration_full_pipeline() {
        let options = ClangOptions::default();
        let target = X86TargetMachine::default();
        let mut modules = X86Modules::new(options, target);

        // Register a module
        let unit = X86CompilationUnit {
            source_path: PathBuf::from("mylib.cppm"),
            module_decl: Some(ModuleDecl::interface(ModuleName::from_str("mylib"))),
            unit_kind: X86CompilationUnitKind::ModuleInterface,
            target_triple: "x86_64-unknown-linux-gnu".to_string(),
            include_paths: vec![],
            defines: vec![],
            required_imports: vec![],
        };
        modules.add_compilation_unit(unit);

        // Process should succeed
        let result = modules.process_all_units();
        assert!(result.is_ok());

        // Validate
        let validation = modules.validate();
        assert!(validation.is_empty());
    }

    #[test]
    fn test_integration_with_import() {
        let options = ClangOptions::default();
        let target = X86TargetMachine::default();
        let mut modules = X86Modules::new(options, target);

        // Register base module
        let base_unit = X86CompilationUnit {
            source_path: PathBuf::from("base.cppm"),
            module_decl: Some(ModuleDecl::interface(ModuleName::from_str("base"))),
            unit_kind: X86CompilationUnitKind::ModuleInterface,
            target_triple: "x86_64-unknown-linux-gnu".to_string(),
            include_paths: vec![],
            defines: vec![],
            required_imports: vec![],
        };
        modules.add_compilation_unit(base_unit);

        // Register module that imports base
        let import_unit = X86CompilationUnit {
            source_path: PathBuf::from("consumer.cppm"),
            module_decl: Some(ModuleDecl::interface(ModuleName::from_str("consumer"))),
            unit_kind: X86CompilationUnitKind::ModuleInterface,
            target_triple: "x86_64-unknown-linux-gnu".to_string(),
            include_paths: vec![],
            defines: vec![],
            required_imports: vec![ModuleImport::new(ModuleName::from_str("base"))],
        };
        modules.add_compilation_unit(import_unit);

        // Build dependency graph
        modules
            .dependency
            .build_from_units(&modules.pending_units, &modules.module_map);

        assert!(!modules.dependency.has_cycles());
    }

    #[test]
    fn test_integration_cycle_detection() {
        let options = ClangOptions::default();
        let target = X86TargetMachine::default();
        let mut modules = X86Modules::new(options, target);

        let unit_a = X86CompilationUnit {
            source_path: PathBuf::from("a.cppm"),
            module_decl: Some(ModuleDecl::interface(ModuleName::from_str("modA"))),
            unit_kind: X86CompilationUnitKind::ModuleInterface,
            target_triple: "x86_64-unknown-linux-gnu".to_string(),
            include_paths: vec![],
            defines: vec![],
            required_imports: vec![ModuleImport::new(ModuleName::from_str("modB"))],
        };
        let unit_b = X86CompilationUnit {
            source_path: PathBuf::from("b.cppm"),
            module_decl: Some(ModuleDecl::interface(ModuleName::from_str("modB"))),
            unit_kind: X86CompilationUnitKind::ModuleInterface,
            target_triple: "x86_64-unknown-linux-gnu".to_string(),
            include_paths: vec![],
            defines: vec![],
            required_imports: vec![ModuleImport::new(ModuleName::from_str("modA"))],
        };

        modules.add_compilation_unit(unit_a);
        modules.add_compilation_unit(unit_b);

        modules
            .dependency
            .build_from_units(&modules.pending_units, &modules.module_map);

        assert!(modules.dependency.has_cycles());

        let result = modules.process_all_units();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("circular"));
    }

    // ── Additional comprehensive tests ────────────────────────────────────

    #[test]
    fn test_module_compiler_parse_import_decl() {
        let mut compiler = X86ModuleCompiler::new(ClangOptions::default());
        let import = compiler.parse_import_decl("import std.core;");
        assert!(import.is_some());
        let import = import.unwrap();
        assert_eq!(import.name.to_string(), "std.core");
    }

    #[test]
    fn test_module_compiler_parse_export_import() {
        let mut compiler = X86ModuleCompiler::new(ClangOptions::default());
        let import = compiler.parse_import_decl("export import mylib;");
        assert!(import.is_some());
        let import = import.unwrap();
        assert!(import.is_exported);
    }

    #[test]
    fn test_module_compiler_parse_header_unit_import() {
        let mut compiler = X86ModuleCompiler::new(ClangOptions::default());
        let import = compiler.parse_import_decl("import <iostream>;");
        assert!(import.is_some());
        let import = import.unwrap();
        assert!(import.is_header_unit);
        assert_eq!(import.header_name, Some("iostream".to_string()));
    }

    #[test]
    fn test_module_compiler_validate_empty() {
        let compiler = X86ModuleCompiler::new(ClangOptions::default());
        assert!(compiler.validate());
    }

    #[test]
    fn test_module_compiler_validate_with_errors() {
        let mut compiler = X86ModuleCompiler::new(ClangOptions::default());
        compiler.parse_module_decl("export module ;");
        assert!(compiler.errors().len() > 0 || compiler.validate());
    }

    #[test]
    fn test_module_compiler_clear_errors() {
        let mut compiler = X86ModuleCompiler::new(ClangOptions::default());
        compiler.parse_module_decl("export module ;");
        compiler.clear_errors();
        assert!(compiler.errors().is_empty());
    }

    #[test]
    fn test_module_compiler_active_module() {
        let mut compiler = X86ModuleCompiler::new(ClangOptions::default());
        assert!(compiler.active_module().is_none());
        compiler.parse_module_decl("export module mymod;");
        assert!(compiler.active_module().is_some());
        assert_eq!(compiler.active_module().unwrap().name.to_string(), "mymod");
    }

    #[test]
    fn test_module_compiler_parsed_declarations() {
        let mut compiler = X86ModuleCompiler::new(ClangOptions::default());
        compiler.parse_module_decl("export module A;");
        compiler.parse_module_decl("module B;");
        assert_eq!(compiler.parsed_declarations().len(), 2);
    }

    #[test]
    fn test_module_compiler_partition_multiple() {
        let mut compiler = X86ModuleCompiler::new(ClangOptions::default());
        let unit1 = X86CompilationUnit {
            source_path: PathBuf::from("p1.cppm"),
            module_decl: Some(ModuleDecl {
                name: ModuleName::from_str("mylib"),
                kind: ModuleKind::ModulePartitionInterface,
                partition: Some("part1".to_string()),
                source_loc: None,
            }),
            unit_kind: X86CompilationUnitKind::ModulePartitionInterface,
            target_triple: "x86_64-unknown-linux-gnu".to_string(),
            include_paths: vec![],
            defines: vec![],
            required_imports: vec![],
        };
        let unit2 = X86CompilationUnit {
            source_path: PathBuf::from("p2.cppm"),
            module_decl: Some(ModuleDecl {
                name: ModuleName::from_str("mylib"),
                kind: ModuleKind::ModulePartitionInterface,
                partition: Some("part2".to_string()),
                source_loc: None,
            }),
            unit_kind: X86CompilationUnitKind::ModulePartitionInterface,
            target_triple: "x86_64-unknown-linux-gnu".to_string(),
            include_paths: vec![],
            defines: vec![],
            required_imports: vec![],
        };
        compiler.register_partition("mylib", "part1", unit1);
        compiler.register_partition("mylib", "part2", unit2);
        let parts = compiler.partitions_of("mylib");
        assert_eq!(parts.len(), 2);
    }

    #[test]
    fn test_module_map_discover_non_existent() {
        let mut map = X86ModuleMap::new();
        map.add_search_path(Path::new("/nonexistent/path/for/modules"));
        let result = map.discover_module_maps();
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 0);
    }

    #[test]
    fn test_module_map_all_names() {
        let mut map = X86ModuleMap::new();
        map.module_index.insert(
            "A".to_string(),
            X86ModuleMapEntry::new("A", Path::new("/a")),
        );
        map.module_index.insert(
            "B".to_string(),
            X86ModuleMapEntry::new("B", Path::new("/b")),
        );
        let names = map.all_module_names();
        assert_eq!(names.len(), 2);
    }

    #[test]
    fn test_module_map_module_headers() {
        let mut entry = X86ModuleMapEntry::new("Test", Path::new("/include"));
        entry.headers = vec!["test.h".to_string(), "test_extra.h".to_string()];
        let mut map = X86ModuleMap::new();
        map.module_index.insert("Test".to_string(), entry);
        let headers = map.module_headers("Test");
        assert_eq!(headers.len(), 2);
    }

    #[test]
    fn test_module_map_module_umbrella() {
        let mut entry = X86ModuleMapEntry::new("UmbrellaMod", Path::new("/include"));
        entry.umbrella = Some("UmbrellaMod.h".to_string());
        let mut map = X86ModuleMap::new();
        map.module_index.insert("UmbrellaMod".to_string(), entry);
        let umbrella = map.module_umbrella("UmbrellaMod");
        assert!(umbrella.is_some());
    }

    #[test]
    fn test_module_map_to_base_module_map() {
        let mut map = X86ModuleMap::new();
        map.module_index.insert(
            "modA".to_string(),
            X86ModuleMapEntry::new("modA", Path::new("/a")),
        );
        map.module_index.insert(
            "modB".to_string(),
            X86ModuleMapEntry::new("modB", Path::new("/b")),
        );
        let base = map.to_base_module_map();
        assert!(base.has_module("modA"));
        assert!(base.has_module("modB"));
    }

    #[test]
    fn test_module_map_write_to_file() {
        let map = X86ModuleMap::new();
        let tmp = std::env::temp_dir().join("test_x86_modulemap_output");
        let result = map.write_to_file(&tmp);
        assert!(result.is_ok());
        let _ = fs::remove_file(&tmp);
    }

    #[test]
    fn test_dependency_incremental_rebuild() {
        let mut dep = X86ModuleDependency::new();
        dep.set_status("modA", X86DependencyStatus::Pending);
        dep.set_status("modB", X86DependencyStatus::Pending);
        dep.add_dependency("modB", "modA");
        let rebuild = dep.compute_incremental_rebuild(&["modA".to_string()]);
        assert!(rebuild.contains(&"modA".to_string()));
        assert!(rebuild.contains(&"modB".to_string()));
    }

    #[test]
    fn test_dependency_record_timestamp() {
        let mut dep = X86ModuleDependency::new();
        dep.set_status("mod", X86DependencyStatus::Pending);
        dep.record_timestamp(
            "mod",
            X86FileTimestamps {
                source_mtime: 1000,
                bmi_mtime: 900,
                deps_mtime: 800,
                source_hash: 0xABCD,
                flags_hash: 0x1234,
            },
        );
        dep.needs_full_rebuild = false;
        assert!(!dep.needs_rebuild("mod"));
    }

    #[test]
    fn test_dependency_record_change() {
        let mut dep = X86ModuleDependency::new();
        dep.record_change(X86DependencyChange::Added("newmod".to_string()));
        assert_eq!(dep.pending_changes().len(), 1);
        dep.clear_pending_changes();
        assert!(dep.pending_changes().is_empty());
    }

    #[test]
    fn test_dependency_edge_count() {
        let mut dep = X86ModuleDependency::new();
        dep.add_dependency("B", "A");
        dep.add_dependency("C", "B");
        dep.add_dependency("C", "A");
        assert_eq!(dep.edge_count(), 3);
    }

    #[test]
    fn test_bmi_transfer_operation_log() {
        let mut transfer = X86BMITransfer::new();
        assert!(transfer.operation_log().is_empty());
        transfer.operation_log.push(X86BMIOperation {
            op: X86BMIOpKind::Export,
            module_name: "test".to_string(),
            file_size: 1024,
            success: true,
            error: None,
        });
        assert_eq!(transfer.operation_log().len(), 1);
        transfer.clear_log();
        assert!(transfer.operation_log().is_empty());
    }

    #[test]
    fn test_bmi_transfer_validate_file() {
        let transfer = X86BMITransfer::new();
        let result = transfer.validate_bmi_file(Path::new("/nonexistent/bmi.pcm"));
        assert!(result.is_err());
    }

    #[test]
    fn test_bmi_transfer_remove_file() {
        let mut transfer = X86BMITransfer::new();
        let result = transfer.remove_bmi(Path::new("/nonexistent/bmi.pcm"));
        assert!(result.is_err());
    }

    #[test]
    fn test_bmi_flags_default() {
        let flags = X86BMIFlags::default();
        assert!(!flags.sse_enabled);
        assert!(!flags.avx_enabled);
        assert!(!flags.is_64bit);
    }

    #[test]
    fn test_cache_lookup_disabled() {
        let mut cache = X86ModuleCache::new(&ClangOptions::default());
        cache.enabled = false;
        assert!(cache.lookup("test").is_none());
        assert!(cache.lookup_by_hash("test", "abc").is_none());
    }

    #[test]
    fn test_cache_set_root() {
        let mut cache = X86ModuleCache::new(&ClangOptions::default());
        let new_root = std::env::temp_dir().join("x86_mod_cache_test");
        cache.set_cache_root(&new_root);
        assert_eq!(cache.cache_root, new_root);
        let _ = fs::remove_dir_all(&new_root);
    }

    #[test]
    fn test_cache_verify_empty() {
        let cache = X86ModuleCache::new(&ClangOptions::default());
        let errors = cache.verify_cache();
        assert!(errors.is_empty());
    }

    #[test]
    fn test_ownership_enter_leave_fragments() {
        let mut ownership = X86ModuleOwnership::new();
        assert!(!ownership.in_global_fragment);
        ownership.enter_global_fragment();
        assert!(ownership.in_global_fragment);
        ownership.leave_global_fragment();
        assert!(!ownership.in_global_fragment);
        ownership.enter_private_fragment();
        assert!(ownership.in_private_fragment);
        ownership.leave_private_fragment();
        assert!(!ownership.in_private_fragment);
    }

    #[test]
    fn test_ownership_register_visible_and_reachable() {
        let mut ownership = X86ModuleOwnership::new();
        ownership.register_visible_name("mod", "VisibleType");
        ownership.register_reachable_name("mod", "ReachableFunc");
        assert!(ownership.is_name_visible("VisibleType", "mod"));
        assert!(ownership.is_name_visible("ReachableFunc", "mod"));
        assert!(!ownership.is_name_visible("SomethingElse", "mod"));
    }

    #[test]
    fn test_linkage_all_kinds_to_ir() {
        assert_eq!(
            X86ModuleLinkage::linkage_to_ir_string(X86ModuleLinkageKind::Strong),
            "external"
        );
        assert_eq!(
            X86ModuleLinkage::linkage_to_ir_string(X86ModuleLinkageKind::Weak),
            "weak"
        );
        assert_eq!(
            X86ModuleLinkage::linkage_to_ir_string(X86ModuleLinkageKind::WeakODR),
            "weak_odr"
        );
        assert_eq!(
            X86ModuleLinkage::linkage_to_ir_string(X86ModuleLinkageKind::Internal),
            "internal"
        );
        assert_eq!(
            X86ModuleLinkage::linkage_to_ir_string(X86ModuleLinkageKind::LinkOnceODR),
            "linkonce_odr"
        );
        assert_eq!(
            X86ModuleLinkage::linkage_to_ir_string(X86ModuleLinkageKind::AvailableExternally),
            "available_externally"
        );
    }

    #[test]
    fn test_linkage_all_visibilities_to_ir() {
        assert_eq!(
            X86ModuleLinkage::visibility_to_ir_string(X86SymbolVisibility::Default),
            "default"
        );
        assert_eq!(
            X86ModuleLinkage::visibility_to_ir_string(X86SymbolVisibility::Hidden),
            "hidden"
        );
        assert_eq!(
            X86ModuleLinkage::visibility_to_ir_string(X86SymbolVisibility::Protected),
            "protected"
        );
        assert_eq!(
            X86ModuleLinkage::visibility_to_ir_string(X86SymbolVisibility::Internal),
            "internal"
        );
    }

    #[test]
    fn test_linkage_remove_override() {
        let mut linkage = X86ModuleLinkage::new(&ClangOptions::default());
        linkage.set_linkage_override(
            "mod",
            X86LinkageOverride {
                module_name: "mod".to_string(),
                linkage: X86ModuleLinkageKind::Strong,
                visibility: X86SymbolVisibility::Default,
                force_inline: false,
            },
        );
        linkage.remove_linkage_override("mod");
        let result = linkage.determine_linkage("func", "mod", true, true);
        assert_eq!(result.linkage, X86ModuleLinkageKind::WeakODR);
    }

    #[test]
    fn test_import_allow_unresolved() {
        let mut handler = X86ModuleImport::new();
        handler.set_allow_unresolved(true);
        let import = ModuleImport::new(ModuleName::from_str("nonexistent"));
        let map = X86ModuleMap::new();
        let cache = X86ModuleCache::new(&ClangOptions::default());
        let result = handler.resolve_import(&import, &map, &cache);
        assert!(result.is_ok());
    }

    #[test]
    fn test_import_resolved_bmi_path() {
        let handler = X86ModuleImport::new();
        assert!(handler.resolved_bmi_path("unknown").is_none());
    }

    #[test]
    fn test_import_active_and_resolved() {
        let handler = X86ModuleImport::new();
        assert!(handler.active_imports().is_empty());
        assert!(handler.resolved_imports().is_empty());
    }

    #[test]
    fn test_std_module_new() {
        let mut mod_def = X86StdModule::new("custom_std");
        mod_def.add_header("<custom>");
        mod_def.add_dependency("std.core");
        assert_eq!(mod_def.name, "custom_std");
        assert_eq!(mod_def.headers.len(), 1);
        assert_eq!(mod_def.dependencies.len(), 1);
        assert!(!mod_def.is_primary);
        assert_eq!(mod_def.min_standard, CppStandard::Cpp20);
    }

    #[test]
    fn test_std_modules_not_std_module() {
        let std_mods = X86ModuleStandardLibrary::new();
        assert!(!std_mods.is_std_module("boost"));
        assert!(!std_mods.is_std_module("mylib"));
        assert!(std_mods.is_std_module("std"));
    }

    #[test]
    fn test_std_modules_get_nonexistent() {
        let std_mods = X86ModuleStandardLibrary::new();
        assert!(std_mods.get_std_module("not_a_std_module").is_none());
    }

    #[test]
    fn test_std_modules_all_names() {
        let std_mods = X86ModuleStandardLibrary::new();
        let names = std_mods.module_names();
        assert!(names.contains(&"std"));
        assert!(names.contains(&"std.core"));
        assert!(names.contains(&"std.io"));
        assert!(names.contains(&"std.containers"));
    }

    #[test]
    fn test_std_modules_containers_deps() {
        let std_mods = X86ModuleStandardLibrary::new();
        let containers = std_mods.get_std_module("std.containers").unwrap();
        assert!(containers.dependencies.contains(&"std.core".to_string()));
        assert!(containers.dependencies.contains(&"std.memory".to_string()));
    }

    #[test]
    fn test_std_modules_strings_deps() {
        let std_mods = X86ModuleStandardLibrary::new();
        let strings = std_mods.get_std_module("std.strings").unwrap();
        assert!(strings.dependencies.contains(&"std.core".to_string()));
    }

    #[test]
    fn test_std_modules_numerics_deps() {
        let std_mods = X86ModuleStandardLibrary::new();
        let numerics = std_mods.get_std_module("std.numerics").unwrap();
        assert!(numerics.dependencies.contains(&"std.core".to_string()));
    }

    #[test]
    fn test_std_modules_ranges_deps() {
        let std_mods = X86ModuleStandardLibrary::new();
        let ranges = std_mods.get_std_module("std.ranges").unwrap();
        assert!(ranges.dependencies.contains(&"std.core".to_string()));
        assert!(ranges.dependencies.contains(&"std.concepts".to_string()));
    }

    #[test]
    fn test_darwin_module_flags_default() {
        let flags = X86DarwinModuleFlags::default();
        assert!(!flags.is_framework_bundle);
        assert!(flags.framework_version.is_none());
        assert!(!flags.use_system_cache);
        assert!(!flags.is_system_module);
        assert!(!flags.requires_explicit_build);
    }

    #[test]
    fn test_x86_cache_config_default() {
        let config = X86CacheConfig::default();
        assert!(config.use_triple_subdir);
        assert_eq!(config.target_triple, "x86_64-unknown-linux-gnu");
        assert!(!config.use_lock_file);
        assert!(!config.use_hard_links);
        assert!(!config.verify_on_startup);
        assert_eq!(config.gc_threshold, 0.8);
    }

    #[test]
    fn test_module_compiler_with_different_output_dir() {
        let mut compiler = X86ModuleCompiler::new(ClangOptions::default());
        let custom_dir = std::env::temp_dir().join("custom_x86_modules");
        compiler.set_output_dir(&custom_dir);
        assert_eq!(compiler.output_dir, custom_dir);
    }

    #[test]
    fn test_x86_module_map_entry_full_name() {
        let mut entry = X86ModuleMapEntry::new("child", Path::new("/base"));
        assert_eq!(entry.fully_qualified_name(), "child");
        entry.parent = Some("parent".to_string());
        assert_eq!(entry.fully_qualified_name(), "parent.child");
    }

    #[test]
    fn test_x86_module_map_entry_has_submodules() {
        let mut entry = X86ModuleMapEntry::new("root", Path::new("/base"));
        assert!(!entry.has_submodules());
        entry.submodules.push("child".to_string());
        assert!(entry.has_submodules());
    }

    #[test]
    fn test_dependency_transitive_reduction() {
        let mut dep = X86ModuleDependency::new();
        dep.add_dependency("A", "B");
        dep.add_dependency("B", "C");
        dep.add_dependency("A", "C");
        let redundant = dep.transitive_reduction();
        assert!(redundant.iter().any(|(a, c)| a == "A" && c == "C"));
    }

    #[test]
    fn test_dependency_self_loop_ignored() {
        let mut dep = X86ModuleDependency::new();
        dep.add_dependency("A", "A");
        assert!(!dep.has_cycles());
    }

    #[test]
    fn test_cache_store_disabled() {
        let mut cache = X86ModuleCache::new(&ClangOptions::default());
        cache.enabled = false;
        let unit = X86CompilationUnit {
            source_path: PathBuf::from("test.cppm"),
            module_decl: Some(ModuleDecl::interface(ModuleName::from_str("test"))),
            unit_kind: X86CompilationUnitKind::ModuleInterface,
            target_triple: "x86_64-unknown-linux-gnu".to_string(),
            include_paths: vec![],
            defines: vec![],
            required_imports: vec![],
        };
        let result = X86CompilationResult::new(
            "test",
            Some(PathBuf::from("test.pcm")),
            false,
            X86CompilationUnitKind::ModuleInterface,
        );
        let store_result = cache.store(&unit, &result);
        assert!(store_result.is_ok());
    }

    #[test]
    fn test_ownership_validate_consistency() {
        let mut ownership = X86ModuleOwnership::new();
        ownership.register_module(
            ModuleName::from_str("mod"),
            X86CompilationUnitKind::ModuleInterface,
        );
        ownership.record_decl_ownership(1, "func");
        ownership.mark_exported(1);
        let errors = ownership.validate();
        assert!(errors.is_empty());
    }

    #[test]
    fn test_linkage_validate_no_duplicates() {
        let mut linkage = X86ModuleLinkage::new(&ClangOptions::default());
        linkage.register_initializer("mod", "init1", 100);
        linkage.register_initializer("mod", "init2", 200);
        let errors = linkage.validate();
        assert!(errors.is_empty());
    }

    #[test]
    fn test_linkage_validate_duplicate_priorities() {
        let mut linkage = X86ModuleLinkage::new(&ClangOptions::default());
        linkage.register_initializer("mod", "init1", 100);
        linkage.register_initializer("mod", "init2", 100);
        let errors = linkage.validate();
        assert!(!errors.is_empty());
    }

    #[test]
    fn test_import_parse_invalid() {
        let handler = X86ModuleImport::new();
        let result = handler.parse_import("not an import");
        assert!(result.is_none());
    }

    #[test]
    fn test_import_parse_partition_import() {
        let handler = X86ModuleImport::new();
        let result = handler.parse_import("import mylib:internal;");
        assert!(result.is_some());
    }

    #[test]
    fn test_integration_module_map_and_dependency() {
        let mut map = X86ModuleMap::new();
        map.module_index.insert(
            "base".to_string(),
            X86ModuleMapEntry::new("base", Path::new("/src")),
        );
        map.module_index.insert(
            "derived".to_string(),
            X86ModuleMapEntry::new("derived", Path::new("/src")),
        );
        let mut deps = X86ModuleDependency::new();
        deps.set_status("base", X86DependencyStatus::Compiled);
        deps.set_status("derived", X86DependencyStatus::Pending);
        deps.add_dependency("derived", "base");
        let order = deps.topological_sort();
        assert!(order.is_ok());
    }

    #[test]
    fn test_module_map_discover_in_temp() {
        let mut map = X86ModuleMap::new();
        let tmp_dir = std::env::temp_dir().join("x86_module_map_test_dir");
        let _ = fs::create_dir_all(&tmp_dir);
        let map_path = tmp_dir.join(X86_MODULE_MAP_FILE);
        fs::write(&map_path, "module TestMod { header \"test.h\" }\n").unwrap();
        map.add_search_path(&tmp_dir);
        let result = map.discover_module_maps();
        assert!(result.is_ok());
        let _ = fs::remove_dir_all(&tmp_dir);
    }

    #[test]
    fn test_compilation_unit_kind_debug() {
        assert_ne!(
            X86CompilationUnitKind::ModuleInterface,
            X86CompilationUnitKind::ModuleImplementation
        );
        assert_ne!(
            X86CompilationUnitKind::ModulePartitionInterface,
            X86CompilationUnitKind::HeaderUnit
        );
        assert_ne!(
            X86CompilationUnitKind::NonModular,
            X86CompilationUnitKind::GlobalFragment
        );
    }

    #[test]
    fn test_dependency_status_all_variants() {
        assert_ne!(X86DependencyStatus::Pending, X86DependencyStatus::Compiled);
        assert_ne!(X86DependencyStatus::Failed, X86DependencyStatus::Skipped);
        assert_ne!(
            X86DependencyStatus::InProgress,
            X86DependencyStatus::UpToDate
        );
    }

    #[test]
    fn test_bmi_op_kind_all_variants() {
        assert_ne!(X86BMIOpKind::Export, X86BMIOpKind::Import);
        assert_ne!(X86BMIOpKind::Verify, X86BMIOpKind::Update);
        assert_ne!(X86BMIOpKind::Remove, X86BMIOpKind::Export);
    }

    #[test]
    fn test_module_map_entry_x86_config() {
        let entry = X86ModuleMapEntry::new("mod", Path::new("/path"));
        assert!(entry.x86_config_flags.is_empty());
        assert!(!entry.is_extern);
        assert!(entry.parent.is_none());
    }

    #[test]
    fn test_module_compiler_default_output_dir() {
        let compiler = X86ModuleCompiler::new(ClangOptions::default());
        assert_eq!(compiler.output_dir, PathBuf::from(X86_MODULE_CACHE_DIR));
        assert!(!compiler.verbose);
    }

    #[test]
    fn test_module_compiler_verbose() {
        let mut options = ClangOptions::default();
        options.verbose = true;
        let compiler = X86ModuleCompiler::new(options);
        assert!(compiler.verbose);
    }

    #[test]
    fn test_x86_modules_stat_default() {
        let stats = X86ModuleStats::default();
        assert_eq!(stats.modules_compiled, 0);
        assert_eq!(stats.bmis_imported, 0);
        assert_eq!(stats.cache_hits, 0);
    }

    #[test]
    fn test_x86_modules_validate() {
        let options = ClangOptions::default();
        let target = X86TargetMachine::default();
        let modules = X86Modules::new(options, target);
        let errors = modules.validate();
        assert!(errors.is_empty());
    }

    #[test]
    fn test_x86_modules_add_multiple_units() {
        let options = ClangOptions::default();
        let target = X86TargetMachine::default();
        let mut modules = X86Modules::new(options, target);
        let units: Vec<X86CompilationUnit> = (0..5)
            .map(|i| X86CompilationUnit {
                source_path: PathBuf::from(format!("mod{}.cppm", i)),
                module_decl: Some(ModuleDecl::interface(ModuleName::from_str(&format!(
                    "mod{}",
                    i
                )))),
                unit_kind: X86CompilationUnitKind::ModuleInterface,
                target_triple: "x86_64-unknown-linux-gnu".to_string(),
                include_paths: vec![],
                defines: vec![],
                required_imports: vec![],
            })
            .collect();
        modules.add_compilation_units(units);
        assert_eq!(modules.pending_units.len(), 5);
    }

    #[test]
    fn test_import_include_paths() {
        let mut handler = X86ModuleImport::new();
        let paths = vec![
            PathBuf::from("/usr/include"),
            PathBuf::from("/usr/local/include"),
        ];
        handler.set_include_paths(paths);
        assert_eq!(handler.system_include_paths.len(), 2);
    }

    #[test]
    fn test_ownership_compute_visible_for_unknown_module() {
        let ownership = X86ModuleOwnership::new();
        let visible = ownership.compute_visible_names("unknown");
        assert!(visible.is_empty());
    }

    #[test]
    fn test_std_modules_threading() {
        let std_mods = X86ModuleStandardLibrary::new();
        let threading = std_mods.get_std_module("std.threading").unwrap();
        assert!(threading.headers.contains(&"<thread>".to_string()));
        assert!(threading.headers.contains(&"<mutex>".to_string()));
    }

    #[test]
    fn test_std_modules_concepts() {
        let std_mods = X86ModuleStandardLibrary::new();
        let concepts = std_mods.get_std_module("std.concepts").unwrap();
        assert!(concepts.headers.contains(&"<concepts>".to_string()));
    }

    #[test]
    fn test_cpp_standard_eq() {
        assert_eq!(CppStandard::Cpp17, CppStandard::Cpp17);
        assert_ne!(CppStandard::Cpp17, CppStandard::Cpp20);
    }

    #[test]
    fn test_compilation_unit_kind_eq() {
        assert_eq!(
            X86CompilationUnitKind::ModuleInterface,
            X86CompilationUnitKind::ModuleInterface
        );
        assert_ne!(
            X86CompilationUnitKind::ModuleInterface,
            X86CompilationUnitKind::ModuleImplementation
        );
    }

    #[test]
    fn test_bmi_flags_field_assignment() {
        let mut flags = X86BMIFlags::default();
        flags.sse_enabled = true;
        flags.sse2_enabled = true;
        flags.is_64bit = true;
        assert!(flags.sse_enabled);
        assert!(flags.sse2_enabled);
        assert!(flags.is_64bit);
    }

    #[test]
    fn test_x86_file_timestamps() {
        let ts = X86FileTimestamps {
            source_mtime: 1000,
            bmi_mtime: 900,
            deps_mtime: 800,
            source_hash: 0xDEADBEEF,
            flags_hash: 0xCAFE,
        };
        assert_eq!(ts.source_mtime, 1000);
        assert_eq!(ts.source_hash, 0xDEADBEEF);
    }

    #[test]
    fn test_dependency_change_variants() {
        let change1 = X86DependencyChange::Added("mod".to_string());
        let change2 = X86DependencyChange::Removed("mod".to_string());
        assert!(matches!(change1, X86DependencyChange::Added(_)));
        assert!(matches!(change2, X86DependencyChange::Removed(_)));
        let change3 = X86DependencyChange::EdgeAdded("A".to_string(), "B".to_string());
        assert!(matches!(change3, X86DependencyChange::EdgeAdded(_, _)));
    }

    #[test]
    fn test_integration_compiler_cache_interaction() {
        let options = ClangOptions::default();
        let mut compiler = X86ModuleCompiler::new(options.clone());
        compiler.set_output_dir(&std::env::temp_dir().join("x86_mod_test_output"));
        let module_map = X86ModuleMap::new();
        let import_handler = X86ModuleImport::new();
        let unit = X86CompilationUnit {
            source_path: PathBuf::from("simple.cppm"),
            module_decl: Some(ModuleDecl::interface(ModuleName::from_str("simple"))),
            unit_kind: X86CompilationUnitKind::ModuleInterface,
            target_triple: "x86_64-unknown-linux-gnu".to_string(),
            include_paths: vec![],
            defines: vec![],
            required_imports: vec![],
        };
        let result = compiler.compile_unit(&unit, &module_map, &import_handler);
        assert!(result.is_ok());
        let compiled = result.unwrap();
        assert_eq!(compiled.module_name, "simple");
        assert!(compiled.bmi_path.is_some());
    }

    #[test]
    fn test_module_constants() {
        assert_eq!(X86_MODULE_CACHE_DIR, ".x86_module_cache");
        assert_eq!(X86_BMI_EXTENSION, ".pcm");
        assert_eq!(X86_MODULE_MAP_FILE, "module.modulemap");
        assert_eq!(X86_CACHE_MAX_VERSIONS, 5);
        assert_eq!(X86_BMI_SIGNATURE_MAGIC, b"X86M");
        assert_eq!(X86_BMI_EXTENDED_VERSION, 2);
    }

    #[test]
    fn test_module_map_entry_darwin_flags() {
        let flags = X86DarwinModuleFlags {
            is_framework_bundle: true,
            framework_version: Some("A".to_string()),
            use_system_cache: true,
            is_system_module: true,
            requires_explicit_build: true,
        };
        assert!(flags.is_framework_bundle);
        assert_eq!(flags.framework_version, Some("A".to_string()));
    }

    #[test]
    fn test_cache_config_custom() {
        let config = X86CacheConfig {
            use_triple_subdir: false,
            target_triple: "i386-unknown-linux-gnu".to_string(),
            use_lock_file: true,
            use_hard_links: true,
            verify_on_startup: true,
            gc_threshold: 0.5,
        };
        assert!(!config.use_triple_subdir);
        assert_eq!(config.target_triple, "i386-unknown-linux-gnu");
        assert!(config.use_lock_file);
    }

    #[test]
    fn test_bmi_operation_log_entry() {
        let entry = X86BMIOperation {
            op: X86BMIOpKind::Import,
            module_name: "test".to_string(),
            file_size: 2048,
            success: true,
            error: None,
        };
        assert_eq!(entry.op, X86BMIOpKind::Import);
        assert!(entry.success);
    }

    #[test]
    fn test_symbol_linkage_fields() {
        let sym = X86SymbolLinkage {
            symbol_name: "_Z3foov".to_string(),
            linkage: X86ModuleLinkageKind::WeakODR,
            visibility: X86SymbolVisibility::Default,
            owning_module: "mylib".to_string(),
            is_definition: true,
        };
        assert_eq!(sym.symbol_name, "_Z3foov");
        assert!(sym.is_definition);
        assert_eq!(sym.owning_module, "mylib");
    }

    #[test]
    fn test_module_init_and_fini() {
        let init = X86ModuleInit {
            module_name: "mod".to_string(),
            init_function: "_GLOBAL__I_mod".to_string(),
            priority: 65535,
            before_main: true,
        };
        assert_eq!(init.module_name, "mod");
        assert!(init.before_main);
        let fini = X86ModuleFini {
            module_name: "mod".to_string(),
            fini_function: "_GLOBAL__D_mod".to_string(),
            priority: 65535,
            at_exit: true,
        };
        assert_eq!(fini.module_name, "mod");
        assert!(fini.at_exit);
    }

    #[test]
    fn test_linkage_override_fields() {
        let ov = X86LinkageOverride {
            module_name: "mod".to_string(),
            linkage: X86ModuleLinkageKind::LinkOnceODR,
            visibility: X86SymbolVisibility::Hidden,
            force_inline: true,
        };
        assert_eq!(ov.module_name, "mod");
        assert!(ov.force_inline);
        assert_eq!(ov.linkage, X86ModuleLinkageKind::LinkOnceODR);
    }

    #[test]
    fn test_module_map_entry_all_fields() {
        let entry = X86ModuleMapEntry {
            module_name: "FullMod".to_string(),
            umbrella: Some("FullMod.h".to_string()),
            headers: vec!["a.h".to_string(), "b.h".to_string()],
            excluded_headers: vec!["internal.h".to_string()],
            submodules: vec!["sub1".to_string()],
            is_framework: false,
            is_explicit: true,
            exports: vec!["OtherMod".to_string()],
            link_libraries: vec!["pthread".to_string()],
            base_dir: PathBuf::from("/usr/include"),
            is_extern: true,
            parent: Some("ParentMod".to_string()),
            x86_config_flags: vec!["x86_64".to_string()],
            darwin_specific: X86DarwinModuleFlags::default(),
        };
        assert_eq!(entry.module_name, "FullMod");
        assert!(entry.is_extern);
        assert!(entry.has_submodules());
        assert_eq!(entry.fully_qualified_name(), "ParentMod.FullMod");
    }

    #[test]
    fn test_compilation_result_all_fields() {
        let result = X86CompilationResult {
            module_name: "test".to_string(),
            bmi_path: Some(PathBuf::from("/cache/test.pcm")),
            from_cache: true,
            unit_kind: X86CompilationUnitKind::ModuleInterface,
        };
        assert!(result.from_cache);
        assert_eq!(result.unit_kind, X86CompilationUnitKind::ModuleInterface);
    }

    #[test]
    fn test_compilation_unit_all_fields() {
        let unit = X86CompilationUnit {
            source_path: PathBuf::from("/src/test.cppm"),
            module_decl: Some(ModuleDecl {
                name: ModuleName::from_str("mylib.internal"),
                kind: ModuleKind::ModulePartitionImplementation,
                partition: Some("internal".to_string()),
                source_loc: Some("test.cppm:1:1".to_string()),
            }),
            unit_kind: X86CompilationUnitKind::ModulePartitionImplementation,
            target_triple: "i386-pc-linux-gnu".to_string(),
            include_paths: vec![PathBuf::from("/usr/include")],
            defines: vec![("DEBUG".to_string(), Some("1".to_string()))],
            required_imports: vec![ModuleImport::new(ModuleName::from_str("mylib"))],
        };
        assert_eq!(unit.target_triple, "i386-pc-linux-gnu");
        assert_eq!(unit.defines.len(), 1);
        assert_eq!(unit.required_imports.len(), 1);
    }

    #[test]
    fn test_module_stats_all_fields() {
        let stats = X86ModuleStats {
            modules_compiled: 10,
            bmis_imported: 5,
            bmis_exported: 3,
            cache_hits: 100,
            cache_misses: 20,
            total_bmi_bytes: 1_048_576,
            compilation_time_ms: 5000,
        };
        assert_eq!(stats.modules_compiled, 10);
        assert_eq!(stats.cache_hits, 100);
        assert_eq!(stats.total_bmi_bytes, 1_048_576);
    }

    #[test]
    fn test_std_modules_memory() {
        let std_mods = X86ModuleStandardLibrary::new();
        let memory = std_mods.get_std_module("std.memory").unwrap();
        assert!(memory.headers.contains(&"<memory>".to_string()));
        assert!(memory.headers.contains(&"<memory_resource>".to_string()));
    }

    #[test]
    fn test_std_modules_expected_cpp23() {
        let mut std_mods = X86ModuleStandardLibrary::new();
        std_mods.set_cpp_standard(CppStandard::Cpp23);
        assert!(std_mods.is_std_module("std.expected"));
        assert!(std_mods.is_std_module("std.stacktrace"));
    }

    #[test]
    fn test_end_to_end_module_compilation_flow() {
        let options = ClangOptions::default();
        let target = X86TargetMachine::default();
        let mut modules = X86Modules::new(options, target);
        let base = X86CompilationUnit {
            source_path: PathBuf::from("base.cppm"),
            module_decl: Some(ModuleDecl {
                name: ModuleName::from_str("base"),
                kind: ModuleKind::ModuleInterface,
                partition: None,
                source_loc: None,
            }),
            unit_kind: X86CompilationUnitKind::ModuleInterface,
            target_triple: "x86_64-unknown-linux-gnu".to_string(),
            include_paths: vec![],
            defines: vec![],
            required_imports: vec![],
        };
        let consumer = X86CompilationUnit {
            source_path: PathBuf::from("consumer.cppm"),
            module_decl: Some(ModuleDecl {
                name: ModuleName::from_str("consumer"),
                kind: ModuleKind::ModuleInterface,
                partition: None,
                source_loc: None,
            }),
            unit_kind: X86CompilationUnitKind::ModuleInterface,
            target_triple: "x86_64-unknown-linux-gnu".to_string(),
            include_paths: vec![],
            defines: vec![],
            required_imports: vec![ModuleImport::new(ModuleName::from_str("base"))],
        };
        modules.add_compilation_unit(base);
        modules.add_compilation_unit(consumer);
        let result = modules.process_all_units();
        assert!(result.is_ok());
        let results = result.unwrap();
        assert_eq!(results.len(), 2);
        assert_eq!(results[0].module_name, "base");
        assert!(results[0].bmi_path.is_some());
    }
}