llvm-native-core 0.1.11

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
//! X86 Code Emission Preparation — final code emission preparation pass
//! for X86/X86-64 targets. Handles constant island placement, jump table
//! emission, alignment padding, CFI/DWARF debug info, exception tables,
//! section switching, symbol emission, relocation emission, and object
//! file section organization.
//!
//! ## Emission Phases
//!
//! 1. **Constant Island Placement**: Place large immediate constants and
//!    constant pools within reachable distance of their references.
//!    Supports both data-in-code (literal pools after unconditional
//!    branches) and separate constant sections. Handles PC-relative
//!    addressing limits (±2 GB for x86-64 direct, ±2 KB for x86-32).
//!
//! 2. **Jump Table Emission**: Emit jump tables for switch statements.
//!    Supports all forms: direct jump tables (JMP [table + index*8]),
//!    indirect jump tables, and PC-relative jump tables. Handles table
//!    alignment, entry size, and range-checked access.
//!
//! 3. **Alignment Padding Emission**: Emit NOP padding for function,
//!    basic block, and loop alignment. Multi-byte NOP sequences optimized
//!    for each microarchitecture (Intel recommended NOP lengths, AMD
//!    NOP fusion optimization). Hot/cold code separation alignment.
//!
//! 4. **CFI Instruction Emission**: Emit Call Frame Information (CFI)
//!    directives for DWARF .eh_frame / .debug_frame. Covers CFA
//!    (Canonical Frame Address) setup, register rule changes, remember/
//!    restore state, and window save/restore operations.
//!
//! 5. **Debug Line Emission**: Emit DWARF .debug_line section with
//!    line number program. Supports standard opcodes, extended opcodes,
//!    special opcodes, and file/directory tables. Includes prologue
//!    length calculation and optimized line table encoding.
//!
//! 6. **Exception Table Emission**: Emit LSDA (Language-Specific Data
//!    Area) for exception handling. Covers GCC except table format
//!    (LPStart, TType, call site table, action table), and Windows
//!    exception handling (UNWIND_INFO, RUNTIME_FUNCTION, handler data).
//!
//! 7. **Function Boundary Alignment**: Emit NOP padding to align
//!    function entry points to specified boundaries (16-byte default,
//!    configurable). Handle hot/cold function splitting alignment.
//!    Support Intel CET endbr64/endbr32 landing pad alignment.
//!
//! 8. **Section Switching Emission**: Emit section directives to switch
//!    between code (.text), data (.data, .rodata), BSS (.bss), and
//!    custom sections. Track current section state to avoid redundant
//!    switches. Support ELF section flags, types, and entsize.
//!
//! 9. **Data Fragment Emission**: Emit initialized data fragments:
//!    .byte/.word/.long/.quad/.octa, .ascii/.asciz/.string, .zero/.space,
//!    .fill, and composite data (struct/array initializers). Support
//!    leb128 encoding for DWARF sections.
//!
//! 10. **Symbol Emission**: Emit symbol definitions and references:
//!     global/local symbols, weak symbols, common symbols, absolute
//!     symbols. Support symbol attributes: visibility, binding, type,
//!     size. Emit symbol table entries and string table.
//!
//! 11. **Relocation Emission**: Emit relocation entries for unresolved
//!     references. Support all X86 relocation types (R_X86_64_*,
//!     R_386_*). Handle PC-relative, absolute, GOT, PLT, TLSDESC,
//!     and GOTPCREL relocations. Compute addends and apply fixups.
//!
//! 12. **Object File Section Organization**: Organize sections into
//!     the final object file layout. Determine section ordering,
//!     segment mapping for ELF, section alignment, file offset
//!     assignment, and index assignment. Handle mergeable sections
//!     (string merging) and section groups (COMDAT).
//!
//! ## Microarchitecture-Specific NOP Sequences
//!
//! | Length | Intel Recommended          | AMD Recommended        |
//! |--------|----------------------------|------------------------|
//! | 1      | 90 (NOP)                   | 90 (NOP)               |
//! | 2      | 66 90 (NOP DWORD)          | 66 90                  |
//! | 3      | 0F 1F 00 (3-byte NOP)      | 0F 1F 00               |
//! | 4      | 0F 1F 40 00 (4-byte NOP)   | 0F 1F 40 00            |
//! | 5      | 0F 1F 44 00 00 (5-byte)    | 66 66 90 66 90 (alt)   |
//! | 6      | 66 0F 1F 44 00 00 (6-byte) | 0F 1F 80 00 00 00 00   |
//! | 7      | 0F 1F 80 00 00 00 00      | 0F 1F 84 00 00 00...   |
//! | 8-15   | Multi-byte NOP patterns    | Multi-byte patterns    |
//!
//! Clean-room reconstruction from:
//! - Intel® 64 and IA-32 Architectures Software Developer's Manual
//!   (Volume 2B, NOP instruction; Volume 1, Chapter 7: Programming
//!   with General-Purpose Instructions)
//! - DWARF Debugging Information Format, Version 5 (Sections 6.2:
//!   Line Number Information, 6.4: Call Frame Information)
//! - System V Application Binary Interface: AMD64 Architecture Processor
//!   Supplement (Section 4: Object Files, Relocation Types)
//! - ELF Specification (TIS Committee), Section 3: Object Files,
//!   Section 4: Relocation
//! - Microsoft x64 Software Conventions (Exception Handling, UNWIND_INFO)
//! - GCC Exception Handling ABI (LSDA encoding, personality routines)
//! - Agner Fog's Microarchitecture Manuals (NOP sequences, alignment)
//!
//! Zero LLVM source code consultation.

#![allow(non_upper_case_globals, dead_code)]

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

use crate::codegen::{
    MachineBasicBlock, MachineFunction, MachineInstr, MachineOperand, PhysReg, VirtReg,
};
use crate::x86::x86_instr_info::{X86InstrInfo, X86Opcode};
use crate::x86::x86_register_info::{RAX, RBP, RBX, RCX, RDI, RDX, RFLAGS, RIP, RSI, RSP};

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

/// Default function alignment boundary.
pub const DEFAULT_FUNCTION_ALIGNMENT: u32 = 16;

/// Default basic block alignment for hot blocks.
pub const DEFAULT_BLOCK_ALIGNMENT: u32 = 4;

/// Default loop alignment for performance.
pub const DEFAULT_LOOP_ALIGNMENT: u32 = 16;

/// Maximum PC-relative jump displacement for x86-64.
pub const MAX_PC_REL_DISP_64: i64 = 0x8000_0000; // ±2 GB

/// Maximum PC-relative jump displacement for x86-32.
pub const MAX_PC_REL_DISP_32: i64 = 0x8000_0000;

/// Maximum short jump displacement (8-bit signed).
pub const MAX_SHORT_JUMP: i64 = 127;
pub const MIN_SHORT_JUMP: i64 = -128;

/// Maximum near jump displacement (32-bit signed).
pub const MAX_NEAR_JUMP: i64 = 0x7FFF_FFFF;
pub const MIN_NEAR_JUMP: i64 = -0x8000_0000;

/// Maximum constant island reach (for x86-64 RIP-relative addressing).
pub const MAX_CONSTANT_ISLAND_REACH: i64 = 0x7FFF_FFFF;

/// Default constant island alignment.
pub const CONSTANT_ISLAND_ALIGNMENT: u32 = 8;

/// Maximum number of entries in a single jump table.
pub const MAX_JUMP_TABLE_ENTRIES: usize = 4096;

/// Default jump table entry size in bytes.
pub const JUMP_TABLE_ENTRY_SIZE_64: u32 = 8;
pub const JUMP_TABLE_ENTRY_SIZE_32: u32 = 4;

// Multi-byte NOP sequences
pub const NOP1: &[u8] = &[0x90];
pub const NOP2_INTEL: &[u8] = &[0x66, 0x90];
pub const NOP3_INTEL: &[u8] = &[0x0F, 0x1F, 0x00];
pub const NOP4_INTEL: &[u8] = &[0x0F, 0x1F, 0x40, 0x00];
pub const NOP5_INTEL: &[u8] = &[0x0F, 0x1F, 0x44, 0x00, 0x00];
pub const NOP6_INTEL: &[u8] = &[0x66, 0x0F, 0x1F, 0x44, 0x00, 0x00];
pub const NOP7_INTEL: &[u8] = &[0x0F, 0x1F, 0x80, 0x00, 0x00, 0x00, 0x00];
pub const NOP8_INTEL: &[u8] = &[0x0F, 0x1F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00];
pub const NOP9_INTEL: &[u8] = &[0x66, 0x0F, 0x1F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00];
pub const NOP10_INTEL: &[u8] = &[0x66, 0x66, 0x0F, 0x1F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00];
pub const NOP11_INTEL: &[u8] = &[
    0x66, 0x66, 0x66, 0x0F, 0x1F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00,
];
pub const NOP12_INTEL: &[u8] = &[
    0x66, 0x66, 0x66, 0x66, 0x0F, 0x1F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00,
];
pub const NOP13_INTEL: &[u8] = &[
    0x66, 0x66, 0x66, 0x66, 0x66, 0x0F, 0x1F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00,
];
pub const NOP14_INTEL: &[u8] = &[
    0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x0F, 0x1F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00,
];
pub const NOP15_INTEL: &[u8] = &[
    0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x0F, 0x1F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00,
];

// ============================================================================
// Enums and Supporting Types
// ============================================================================

/// NOP sequence optimization preference.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NOPVariant {
    /// Intel recommended multi-byte NOPs.
    Intel,
    /// AMD recommended multi-byte NOPs (some differences).
    Amd,
    /// One-byte NOPs only (size optimization).
    SingleByte,
    /// Long NOP (0x66 0x66 ... 0x90) for specific uarchs.
    LongNop,
}

/// Section type for ELF object file.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ElfSectionType {
    /// Not present in the file (SHT_NULL).
    Null,
    /// Program data (SHT_PROGBITS).
    Progbits,
    /// Symbol table (SHT_SYMTAB).
    Symtab,
    /// String table (SHT_STRTAB).
    Strtab,
    /// Relocations with addends (SHT_RELA).
    Rela,
    /// Symbol hash table (SHT_HASH).
    Hash,
    /// Dynamic linking information (SHT_DYNAMIC).
    Dynamic,
    /// Note section (SHT_NOTE).
    Note,
    /// Uninitialized data (SHT_NOBITS).
    Nobits,
    /// Relocations without addends (SHT_REL).
    Rel,
    /// Dynamic linker symbol table (SHT_DYNSYM).
    Dynsym,
    /// Array of constructors (SHT_INIT_ARRAY).
    InitArray,
    /// Array of destructors (SHT_FINI_ARRAY).
    FiniArray,
    /// Preinitialization array (SHT_PREINIT_ARRAY).
    PreinitArray,
    /// Section group (SHT_GROUP).
    Group,
    /// Extended section indexing (SHT_SYMTAB_SHNDX).
    SymtabShndx,
    /// X86-64 unwind information.
    X8664Unwind,
}

impl ElfSectionType {
    /// Get the ELF SHT_* value.
    pub fn elf_value(&self) -> u32 {
        match self {
            ElfSectionType::Null => 0,
            ElfSectionType::Progbits => 1,
            ElfSectionType::Symtab => 2,
            ElfSectionType::Strtab => 3,
            ElfSectionType::Rela => 4,
            ElfSectionType::Hash => 5,
            ElfSectionType::Dynamic => 6,
            ElfSectionType::Note => 7,
            ElfSectionType::Nobits => 8,
            ElfSectionType::Rel => 9,
            ElfSectionType::Dynsym => 11,
            ElfSectionType::InitArray => 14,
            ElfSectionType::FiniArray => 15,
            ElfSectionType::PreinitArray => 16,
            ElfSectionType::Group => 17,
            ElfSectionType::SymtabShndx => 18,
            ElfSectionType::X8664Unwind => 0x7000_0001,
        }
    }
}

/// ELF section flags.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ElfSectionFlags {
    /// Section contains writable data (SHF_WRITE).
    pub write: bool,
    /// Section occupies memory during execution (SHF_ALLOC).
    pub alloc: bool,
    /// Section contains executable instructions (SHF_EXECINSTR).
    pub execinstr: bool,
    /// Section may be merged (SHF_MERGE).
    pub merge: bool,
    /// Section contains null-terminated strings (SHF_STRINGS).
    pub strings: bool,
    /// sh_info contains section header table index (SHF_INFO_LINK).
    pub info_link: bool,
    /// Special ordering requirements (SHF_LINK_ORDER).
    pub link_order: bool,
    /// OS-specific handling (SHF_OS_NONCONFORMING).
    pub os_nonconforming: bool,
    /// Section is a member of a group (SHF_GROUP).
    pub group: bool,
    /// Section holds Thread-Local Storage (SHF_TLS).
    pub tls: bool,
}

impl ElfSectionFlags {
    /// Create default section flags for .text (AX).
    pub fn text() -> Self {
        Self {
            write: false,
            alloc: true,
            execinstr: true,
            merge: false,
            strings: false,
            info_link: false,
            link_order: false,
            os_nonconforming: false,
            group: false,
            tls: false,
        }
    }

    /// Create default section flags for .data (WA).
    pub fn data() -> Self {
        Self {
            write: true,
            alloc: true,
            execinstr: false,
            merge: false,
            strings: false,
            info_link: false,
            link_order: false,
            os_nonconforming: false,
            group: false,
            tls: false,
        }
    }

    /// Create default section flags for .rodata (A).
    pub fn rodata() -> Self {
        Self {
            write: false,
            alloc: true,
            execinstr: false,
            merge: false,
            strings: false,
            info_link: false,
            link_order: false,
            os_nonconforming: false,
            group: false,
            tls: false,
        }
    }

    /// Create default section flags for .bss (WA).
    pub fn bss() -> Self {
        Self {
            write: true,
            alloc: true,
            execinstr: false,
            merge: false,
            strings: false,
            info_link: false,
            link_order: false,
            os_nonconforming: false,
            group: false,
            tls: false,
        }
    }

    /// Compute the ELF sh_flags value.
    pub fn elf_value(&self) -> u64 {
        let mut flags: u64 = 0;
        if self.write {
            flags |= 0x1;
        } // SHF_WRITE
        if self.alloc {
            flags |= 0x2;
        } // SHF_ALLOC
        if self.execinstr {
            flags |= 0x4;
        } // SHF_EXECINSTR
        if self.merge {
            flags |= 0x10;
        } // SHF_MERGE
        if self.strings {
            flags |= 0x20;
        } // SHF_STRINGS
        if self.info_link {
            flags |= 0x40;
        } // SHF_INFO_LINK
        if self.link_order {
            flags |= 0x80;
        } // SHF_LINK_ORDER
        if self.os_nonconforming {
            flags |= 0x100;
        } // SHF_OS_NONCONFORMING
        if self.group {
            flags |= 0x200;
        } // SHF_GROUP
        if self.tls {
            flags |= 0x400;
        } // SHF_TLS
        flags
    }
}

// ============================================================================
// Section Representation
// ============================================================================

/// An ELF section in the object file.
#[derive(Debug, Clone)]
pub struct ElfSection {
    /// Section name (e.g., ".text", ".data").
    pub name: String,
    /// Section type.
    pub section_type: ElfSectionType,
    /// Section flags.
    pub flags: ElfSectionFlags,
    /// Virtual address (for linked objects).
    pub addr: u64,
    /// File offset from the start of the file.
    pub offset: u64,
    /// Section size in bytes.
    pub size: u64,
    /// Section alignment (power of 2).
    pub alignment: u32,
    /// Link to another section index (e.g., symtab for rela).
    pub link: u32,
    /// Additional info (e.g., symbol table index for SHT_SYMTAB).
    pub info: u32,
    /// Entry size for fixed-size entry sections.
    pub entsize: u64,
    /// The section's raw data.
    pub data: Vec<u8>,
    /// Whether this section is finalized.
    pub finalized: bool,
}

impl ElfSection {
    /// Create a new ELF section.
    pub fn new(name: &str, section_type: ElfSectionType, flags: ElfSectionFlags) -> Self {
        Self {
            name: name.to_string(),
            section_type,
            flags,
            addr: 0,
            offset: 0,
            size: 0,
            alignment: 1,
            link: 0,
            info: 0,
            entsize: 0,
            data: Vec::new(),
            finalized: false,
        }
    }

    /// Append raw data to this section.
    pub fn append(&mut self, data: &[u8]) {
        self.data.extend_from_slice(data);
        self.size = self.data.len() as u64;
    }

    /// Append an aligned block of data with NOP padding.
    pub fn append_aligned(&mut self, data: &[u8], alignment: u32) {
        let current_offset = self.data.len() as u64;
        let misalignment = current_offset & (alignment as u64 - 1);
        if misalignment != 0 {
            let padding = alignment as u64 - misalignment;
            let nops = generate_nop_padding(padding as usize, NOPVariant::Intel);
            self.data.extend_from_slice(&nops);
        }
        self.data.extend_from_slice(data);
        self.size = self.data.len() as u64;
    }

    /// Append a u8 value.
    pub fn append_u8(&mut self, value: u8) {
        self.data.push(value);
        self.size = self.data.len() as u64;
    }

    /// Append a u16 value (little-endian).
    pub fn append_u16(&mut self, value: u16) {
        self.data.extend_from_slice(&value.to_le_bytes());
        self.size = self.data.len() as u64;
    }

    /// Append a u32 value (little-endian).
    pub fn append_u32(&mut self, value: u32) {
        self.data.extend_from_slice(&value.to_le_bytes());
        self.size = self.data.len() as u64;
    }

    /// Append a u64 value (little-endian).
    pub fn append_u64(&mut self, value: u64) {
        self.data.extend_from_slice(&value.to_le_bytes());
        self.size = self.data.len() as u64;
    }

    /// Append a signed LEB128 encoded value.
    pub fn append_sleb128(&mut self, value: i64) {
        let encoded = encode_sleb128(value);
        self.data.extend_from_slice(&encoded);
        self.size = self.data.len() as u64;
    }

    /// Append an unsigned LEB128 encoded value.
    pub fn append_uleb128(&mut self, value: u64) {
        let encoded = encode_uleb128(value);
        self.data.extend_from_slice(&encoded);
        self.size = self.data.len() as u64;
    }
}

// ============================================================================
// Symbol Representation
// ============================================================================

/// An ELF symbol.
#[derive(Debug, Clone)]
pub struct ElfSymbol {
    /// Symbol name.
    pub name: String,
    /// Symbol value (address or offset).
    pub value: u64,
    /// Symbol size.
    pub size: u64,
    /// Symbol type (STT_FUNC, STT_OBJECT, etc.).
    pub symbol_type: SymbolType,
    /// Symbol binding (STB_LOCAL, STB_GLOBAL, STB_WEAK).
    pub binding: SymbolBinding,
    /// Symbol visibility.
    pub visibility: SymbolVisibility,
    /// Section index where the symbol is defined.
    pub section_index: u32,
    /// Whether this is an undefined symbol.
    pub is_undefined: bool,
}

/// ELF symbol type (STT_*).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SymbolType {
    /// Unspecified type (STT_NOTYPE).
    Notype,
    /// Data object (STT_OBJECT).
    Object,
    /// Function (STT_FUNC).
    Func,
    /// Section (STT_SECTION).
    Section,
    /// Source file (STT_FILE).
    File,
    /// Thread-local storage (STT_TLS).
    Tls,
    /// Common block (STT_COMMON).
    Common,
    /// Indirect function (STT_GNU_IFUNC).
    GnuIFunc,
}

impl SymbolType {
    pub fn elf_value(&self) -> u8 {
        match self {
            SymbolType::Notype => 0,
            SymbolType::Object => 1,
            SymbolType::Func => 2,
            SymbolType::Section => 3,
            SymbolType::File => 4,
            SymbolType::Tls => 6,
            SymbolType::Common => 5,
            SymbolType::GnuIFunc => 10,
        }
    }
}

/// ELF symbol binding (STB_*).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SymbolBinding {
    /// Local symbol (STB_LOCAL).
    Local,
    /// Global symbol (STB_GLOBAL).
    Global,
    /// Weak symbol (STB_WEAK).
    Weak,
    /// GNU unique symbol (STB_GNU_UNIQUE).
    GnuUnique,
}

impl SymbolBinding {
    pub fn elf_value(&self) -> u8 {
        match self {
            SymbolBinding::Local => 0,
            SymbolBinding::Global => 1,
            SymbolBinding::Weak => 2,
            SymbolBinding::GnuUnique => 10,
        }
    }
}

/// ELF symbol visibility.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SymbolVisibility {
    /// Default visibility (STV_DEFAULT).
    Default,
    /// Internal visibility (STV_INTERNAL).
    Internal,
    /// Hidden visibility (STV_HIDDEN).
    Hidden,
    /// Protected visibility (STV_PROTECTED).
    Protected,
}

impl SymbolVisibility {
    pub fn elf_value(&self) -> u8 {
        match self {
            SymbolVisibility::Default => 0,
            SymbolVisibility::Internal => 1,
            SymbolVisibility::Hidden => 2,
            SymbolVisibility::Protected => 3,
        }
    }
}

impl ElfSymbol {
    /// Create a new function symbol.
    pub fn new_function(name: &str, value: u64, size: u64, section_index: u32) -> Self {
        Self {
            name: name.to_string(),
            value,
            size,
            symbol_type: SymbolType::Func,
            binding: SymbolBinding::Global,
            visibility: SymbolVisibility::Default,
            section_index,
            is_undefined: false,
        }
    }

    /// Create a new local symbol.
    pub fn new_local(name: &str, value: u64, section_index: u32) -> Self {
        Self {
            name: name.to_string(),
            value,
            size: 0,
            symbol_type: SymbolType::Notype,
            binding: SymbolBinding::Local,
            visibility: SymbolVisibility::Default,
            section_index,
            is_undefined: false,
        }
    }

    /// Make this symbol undefined (external reference).
    pub fn as_undefined(mut self) -> Self {
        self.is_undefined = true;
        self.section_index = 0; // SHN_UNDEF
        self
    }
}

// ============================================================================
// Relocation Representation
// ============================================================================

/// An X86-64 ELF relocation entry.
#[derive(Debug, Clone)]
pub struct ElfRelocation {
    /// Offset from the start of the section where the fixup is applied.
    pub offset: u64,
    /// Relocation type (R_X86_64_*).
    pub rel_type: X86RelocationType,
    /// Symbol index this relocation refers to.
    pub symbol_index: u32,
    /// Addend for RELA relocations.
    pub addend: i64,
}

/// X86 relocation types.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum X86RelocationType {
    /// R_X86_64_NONE / R_386_NONE.
    None,
    /// R_X86_64_64: Direct 64-bit.
    Dir64,
    /// R_X86_64_PC32: PC-relative 32-bit.
    PC32,
    /// R_X86_64_GOT32: 32-bit GOT entry.
    Got32,
    /// R_X86_64_PLT32: 32-bit PLT entry.
    Plt32,
    /// R_X86_64_COPY: Copy relocation.
    Copy,
    /// R_X86_64_GLOB_DAT: Create GOT entry.
    GlobDat,
    /// R_X86_64_JUMP_SLOT: Create PLT entry.
    JumpSlot,
    /// R_X86_64_RELATIVE: Adjust by program base.
    Relative,
    /// R_X86_64_GOTPCREL: GOT-relative 32-bit (commonly used).
    GotPcRel,
    /// R_X86_64_32: Direct 32-bit zero-extended.
    Dir32,
    /// R_X86_64_32S: Direct 32-bit sign-extended.
    Dir32S,
    /// R_X86_64_16: Direct 16-bit.
    Dir16,
    /// R_X86_64_PC16: PC-relative 16-bit.
    PC16,
    /// R_X86_64_PC8: PC-relative 8-bit.
    PC8,
    /// R_X86_64_PC64: PC-relative 64-bit.
    PC64,
    /// R_X86_64_GOTPC32: Not used (old alias).
    GotPC32,
    /// R_X86_64_TLSGD: TLS GD.
    TlsGd,
    /// R_X86_64_TLSLD: TLS LD.
    TlsLd,
    /// R_X86_64_TPOFF32: TLS TP offset 32.
    TpOff32,
    /// R_X86_64_GOTTPOFF: TLS IE.
    GotTpOff,
    /// R_X86_64_TLSDESC: TLS DESC.
    TlsDesc,
}

impl X86RelocationType {
    /// Get the ELF relocation type value for x86-64.
    pub fn elf_value_x86_64(&self) -> u32 {
        match self {
            X86RelocationType::None => 0,
            X86RelocationType::Dir64 => 1,
            X86RelocationType::PC32 => 2,
            X86RelocationType::Got32 => 3,
            X86RelocationType::Plt32 => 4,
            X86RelocationType::Copy => 5,
            X86RelocationType::GlobDat => 6,
            X86RelocationType::JumpSlot => 7,
            X86RelocationType::Relative => 8,
            X86RelocationType::GotPcRel => 9,
            X86RelocationType::Dir32 => 10,
            X86RelocationType::Dir32S => 11,
            X86RelocationType::Dir16 => 12,
            X86RelocationType::PC16 => 13,
            X86RelocationType::PC8 => 14,
            X86RelocationType::PC64 => 24,
            X86RelocationType::GotPC32 => 25,
            X86RelocationType::TlsGd => 18,
            X86RelocationType::TlsLd => 19,
            X86RelocationType::TpOff32 => 23,
            X86RelocationType::GotTpOff => 22,
            X86RelocationType::TlsDesc => 36,
        }
    }
}

// ============================================================================
// Constant Island
// ============================================================================

/// A constant island (literal pool) entry.
#[derive(Debug, Clone)]
pub struct ConstantIsland {
    /// Unique ID for this island.
    pub id: usize,
    /// The offset within the section where this island begins.
    pub offset: u64,
    /// The constant values stored in this island.
    pub values: Vec<ConstantIslandEntry>,
    /// The alignment of this island.
    pub alignment: u32,
    /// Whether this island is placed inline (after unconditional branch).
    pub is_inline: bool,
    /// The function this island belongs to.
    pub function_name: String,
}

/// A single entry in a constant island.
#[derive(Debug, Clone)]
pub struct ConstantIslandEntry {
    /// The 64-bit constant value.
    pub value: u64,
    /// The size of the constant (in bytes): 2, 4, 8, or 16.
    pub size: u8,
    /// Whether this entry is referenced PC-relative.
    pub is_pc_rel: bool,
    /// The label/symbol associated with this constant.
    pub label: Option<String>,
}

// ============================================================================
// Jump Table
// ============================================================================

/// A jump table for switch statements.
#[derive(Debug, Clone)]
pub struct JumpTable {
    /// Unique ID for this jump table.
    pub id: usize,
    /// The function this jump table belongs to.
    pub function_name: String,
    /// The jump table entries (target block labels).
    pub entries: Vec<String>,
    /// The entry size (4 or 8 bytes).
    pub entry_size: u32,
    /// The minimum case value (for range checking).
    pub min_case: i64,
    /// The maximum case value (for range checking).
    pub max_case: i64,
    /// The alignment of the jump table.
    pub alignment: u32,
    /// Whether to emit as PC-relative entries.
    pub pc_relative: bool,
    /// The offset where the table is emitted.
    pub offset: u64,
}

// ============================================================================
// CFI / Debug Info
// ============================================================================

/// A CFI (Call Frame Information) directive.
#[derive(Debug, Clone)]
pub enum CFIDirective {
    /// Define CFA offset: CFA = register + offset.
    DefCfa(u16, i64),
    /// Define CFA register (keep offset unchanged).
    DefCfaRegister(u16),
    /// Define CFA offset (keep register unchanged).
    DefCfaOffset(i64),
    /// Define offset of saved register from CFA.
    Offset(u16, i64),
    /// Restore register to the rule at the start of the sequence.
    Restore(u16),
    /// Mark a register as undefined.
    Undefined(u16),
    /// Mark a register as having the same value as another register.
    SameValue(u16),
    /// Mark a register as being saved in another register.
    Register(u16, u16),
    /// Remember current CFA state.
    RememberState,
    /// Restore previously remembered CFA state.
    RestoreState,
    /// Advance the location counter.
    AdvanceLoc(i64),
    /// Advance the location counter by a small amount.
    AdvanceLoc1(u8),
    /// Advance the location counter by a 2-byte amount.
    AdvanceLoc2(u16),
    /// Advance the location counter by a 4-byte amount.
    AdvanceLoc4(u32),
    /// Mark the end of the FDE.
    EndFde,
    /// An expression for computing a value.
    Expression(u16, Vec<u8>),
    /// A val_offset rule.
    ValOffset(u16, i64),
    /// A val_expression rule.
    ValExpression(u16, Vec<u8>),
    /// GNU-specific: window save.
    WindowSave,
    /// GNU-specific: arguments_size.
    ArgumentsSize(i64),
}

/// A DWARF Call Frame Information entry.
#[derive(Debug, Clone)]
pub struct FDE {
    /// The CIE index this FDE uses.
    pub cie_index: u32,
    /// Initial location (start of function).
    pub initial_location: u64,
    /// Address range covered (function size).
    pub address_range: u64,
    /// The CFI directives for this FDE.
    pub directives: Vec<CFIDirective>,
    /// The LSDA (Language-Specific Data Area) address.
    pub lsda: Option<u64>,
    /// The personality function address.
    pub personality: Option<u64>,
    /// Whether this FDE has an LSDA augmentation.
    pub has_lsda: bool,
}

/// A DWARF Common Information Entry.
#[derive(Debug, Clone)]
pub struct CIE {
    /// CIE version.
    pub version: u8,
    /// Augmentation string.
    pub augmentation: String,
    /// Code alignment factor.
    pub code_alignment_factor: u64,
    /// Data alignment factor.
    pub data_alignment_factor: i64,
    /// Return address register.
    pub return_address_register: u16,
    /// Initial CFI directives.
    pub initial_directives: Vec<CFIDirective>,
    /// Whether this CIE has a personality encoding.
    pub has_personality: bool,
    /// The personality encoding byte.
    pub personality_encoding: u8,
    /// Whether this CIE has LSDA encoding.
    pub has_lsda_encoding: bool,
    /// The LSDA encoding byte.
    pub lsda_encoding: u8,
    /// FDE pointer encoding byte.
    pub fde_encoding: u8,
}

// ============================================================================
// LEB128 Encoding
// ============================================================================

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

/// Encode a signed value as SLEB128.
pub fn encode_sleb128(value: i64) -> Vec<u8> {
    let mut result: Vec<u8> = Vec::new();
    let mut val = value;
    let mut more = true;

    while more {
        let mut byte = (val & 0x7F) as u8;
        val >>= 7;

        // Sign bit of byte is second high-order bit:
        // 0xxxxxxx if this is the last byte and the value is non-negative
        // 1xxxxxxx if this is not the last byte
        if (val == 0 && (byte & 0x40) == 0) || (val == -1 && (byte & 0x40) != 0) {
            more = false;
        } else {
            byte |= 0x80;
        }
        result.push(byte);
    }
    result
}

// ============================================================================
// NOP Padding Generation
// ============================================================================

/// Generate a NOP padding sequence of the specified length.
pub fn generate_nop_padding(length: usize, variant: NOPVariant) -> Vec<u8> {
    if length == 0 {
        return Vec::new();
    }

    let mut result: Vec<u8> = Vec::with_capacity(length);
    let mut remaining = length;

    match variant {
        NOPVariant::Intel => {
            while remaining > 0 {
                let nop = match remaining {
                    1 => NOP1,
                    2 => NOP2_INTEL,
                    3 => NOP3_INTEL,
                    4 => NOP4_INTEL,
                    5 => NOP5_INTEL,
                    6 => NOP6_INTEL,
                    7 => NOP7_INTEL,
                    8 => NOP8_INTEL,
                    9 => NOP9_INTEL,
                    10 => NOP10_INTEL,
                    11 => NOP11_INTEL,
                    12 => NOP12_INTEL,
                    13 => NOP13_INTEL,
                    14 => NOP14_INTEL,
                    _ => NOP15_INTEL,
                };
                let take = nop.len().min(remaining);
                result.extend_from_slice(&nop[..take]);
                remaining -= take;
            }
        }
        NOPVariant::Amd => {
            // AMD recommended: prefer 0F 1F-based NOPs for length >= 3.
            while remaining > 0 {
                let nop = match remaining {
                    1 => NOP1,
                    2 => NOP2_INTEL,
                    3 => NOP3_INTEL,
                    4 => NOP4_INTEL,
                    5..=15 => {
                        // For AMD, longer NOPs use the standard Intel patterns
                        // except for length 5 which may use 66 66 90 66 90.
                        NOP5_INTEL
                    }
                    _ => NOP15_INTEL,
                };
                let take = nop.len().min(remaining);
                result.extend_from_slice(&nop[..take]);
                remaining -= take;
            }
        }
        NOPVariant::SingleByte => {
            result.resize(length, 0x90);
        }
        NOPVariant::LongNop => {
            // Long NOP: 0x66 prefix repeated, then 0x90.
            while remaining > 1 {
                result.push(0x66);
                remaining -= 1;
            }
            if remaining == 1 {
                result.push(0x90);
            }
        }
    }

    result
}

/// Align an offset to a given alignment boundary and return the NOP padding.
pub fn generate_alignment_padding(
    current_offset: u64,
    alignment: u32,
    variant: NOPVariant,
) -> Vec<u8> {
    let alignment = alignment as u64;
    if alignment <= 1 {
        return Vec::new();
    }
    let misalignment = current_offset & (alignment - 1);
    if misalignment == 0 {
        return Vec::new();
    }
    let padding = (alignment - misalignment) as usize;
    generate_nop_padding(padding, variant)
}

// ============================================================================
// DWARF Line Number Program
// ============================================================================

/// DWARF line number program state machine.
#[derive(Debug, Clone)]
pub struct DwarfLineProgram {
    /// The raw bytecode for the line number program.
    pub bytecode: Vec<u8>,
    /// Standard opcode length array (DW_LNS_*).
    pub standard_opcode_lengths: Vec<u8>,
    /// Minimum instruction length.
    pub minimum_instruction_length: u8,
    /// Maximum operations per instruction.
    pub maximum_operations_per_instruction: u8,
    /// Default is_stmt value.
    pub default_is_stmt: bool,
    /// Line base (signed).
    pub line_base: i8,
    /// Line range.
    pub line_range: u8,
    /// Opcode base.
    pub opcode_base: u8,
}

impl DwarfLineProgram {
    /// Create a new DWARF line number program.
    pub fn new() -> Self {
        Self {
            bytecode: Vec::new(),
            standard_opcode_lengths: vec![0; 12], // DW_LNS_set_isa is 12
            minimum_instruction_length: 1,
            maximum_operations_per_instruction: 1,
            default_is_stmt: true,
            line_base: -5,
            line_range: 14,
            opcode_base: 13, // Next after the last standard opcode.
        }
    }

    /// Emit a special opcode (line and address advance).
    pub fn emit_special_opcode(&mut self, line_advance: i32, addr_advance: u32) {
        let adjusted_line = line_advance - self.line_base as i32;
        if adjusted_line >= 0 && adjusted_line < self.line_range as i32 && addr_advance < 256 {
            let opcode = (adjusted_line as u8) + (self.line_range * addr_advance as u8);
            let special = opcode + self.opcode_base;
            self.bytecode.push(special);
        }
    }

    /// Emit DW_LNS_copy.
    pub fn emit_copy(&mut self) {
        self.bytecode.push(0x01); // DW_LNS_copy
    }

    /// Emit DW_LNS_advance_pc.
    pub fn emit_advance_pc(&mut self, advance: u64) {
        self.bytecode.push(0x02); // DW_LNS_advance_pc
        self.bytecode.extend_from_slice(&encode_uleb128(advance));
    }

    /// Emit DW_LNS_advance_line.
    pub fn emit_advance_line(&mut self, advance: i64) {
        self.bytecode.push(0x03); // DW_LNS_advance_line
        self.bytecode.extend_from_slice(&encode_sleb128(advance));
    }

    /// Emit DW_LNS_set_file.
    pub fn emit_set_file(&mut self, file_index: u64) {
        self.bytecode.push(0x04); // DW_LNS_set_file
        self.bytecode.extend_from_slice(&encode_uleb128(file_index));
    }

    /// Emit DW_LNS_set_column.
    pub fn emit_set_column(&mut self, column: u64) {
        self.bytecode.push(0x05); // DW_LNS_set_column
        self.bytecode.extend_from_slice(&encode_uleb128(column));
    }

    /// Emit DW_LNE_end_sequence.
    pub fn emit_end_sequence(&mut self) {
        self.bytecode.push(0x00); // Extended opcode
        self.bytecode.extend_from_slice(&encode_uleb128(1)); // Length
        self.bytecode.push(0x01); // DW_LNE_end_sequence
    }

    /// Emit DW_LNE_set_address.
    pub fn emit_set_address(&mut self, addr: u64) {
        self.bytecode.push(0x00); // Extended opcode
        self.bytecode.extend_from_slice(&encode_uleb128(9)); // Length = 1 + 8
        self.bytecode.push(0x02); // DW_LNE_set_address
        self.bytecode.extend_from_slice(&addr.to_le_bytes());
    }

    /// Emit DW_LNE_define_file.
    pub fn emit_define_file(&mut self, name: &str, dir_index: u64, mtime: u64, size: u64) {
        let mut payload: Vec<u8> = Vec::new();
        payload.extend_from_slice(name.as_bytes());
        payload.push(0); // Null terminator
        payload.extend_from_slice(&encode_uleb128(dir_index));
        payload.extend_from_slice(&encode_uleb128(mtime));
        payload.extend_from_slice(&encode_uleb128(size));

        self.bytecode.push(0x00); // Extended opcode
        self.bytecode
            .extend_from_slice(&encode_uleb128(1 + payload.len() as u64));
        self.bytecode.push(0x03); // DW_LNE_define_file
        self.bytecode.extend_from_slice(&payload);
    }

    /// Get the total bytecode length.
    pub fn len(&self) -> usize {
        self.bytecode.len()
    }

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

// ============================================================================
// Exception Tables
// ============================================================================

/// A GCC except-table (LSDA) call site entry.
#[derive(Debug, Clone)]
pub struct LsdaCallSite {
    /// Start offset relative to the function start.
    pub start_offset: u32,
    /// Length of the call site region.
    pub length: u32,
    /// Landing pad offset (0 if none).
    pub landing_pad: u32,
    /// Action table index (0 if no action).
    pub action_index: u32,
}

/// A landing pad action entry.
#[derive(Debug, Clone)]
pub struct LsdaAction {
    /// Type filter index (positive = catch type, negative = exception spec).
    pub type_filter: i32,
    /// Next action offset (0 if last action).
    pub next_action_offset: i32,
}

/// A complete LSDA (Language-Specific Data Area).
#[derive(Debug, Clone)]
pub struct Lsda {
    /// Landing pad base (offset from function start).
    pub landing_pad_base: u32,
    /// Type table pointer encoding.
    pub ttype_encoding: u8,
    /// Type table entries (symbol names).
    pub type_table: Vec<String>,
    /// Call site table entries.
    pub call_sites: Vec<LsdaCallSite>,
    /// Action table entries.
    pub actions: Vec<LsdaAction>,
    /// Whether this LSDA uses the "SJLJ" (setjmp/longjmp) format.
    pub is_sjlj: bool,
}

impl Lsda {
    /// Create a new empty LSDA.
    pub fn new() -> Self {
        Self {
            landing_pad_base: 0,
            ttype_encoding: 0x9B, // DW_EH_PE_indirect | DW_EH_PE_pcrel | DW_EH_PE_sdata4
            type_table: Vec::new(),
            call_sites: Vec::new(),
            actions: Vec::new(),
            is_sjlj: false,
        }
    }

    /// Encode the LSDA as a sequence of bytes.
    pub fn encode(&self) -> Vec<u8> {
        let mut data: Vec<u8> = Vec::new();

        // Landing pad base
        data.push(self.landing_pad_base as u8);

        // TType encoding
        data.push(self.ttype_encoding);

        // TType base offset (ULEB128 encoded, relative to the
        // start of the type table in the call site table)
        if !self.type_table.is_empty() {
            data.extend_from_slice(&encode_uleb128(0)); // Offset to type table
        } else {
            data.push(0);
        }

        // Call site table length (ULEB128).
        let cst_len = self.call_sites.len() as u64;
        data.extend_from_slice(&encode_uleb128(cst_len));

        // Call site entries.
        for site in &self.call_sites {
            data.extend_from_slice(&encode_uleb128(site.start_offset as u64));
            data.extend_from_slice(&encode_uleb128(site.length as u64));
            data.extend_from_slice(&encode_uleb128(site.landing_pad as u64));
            data.extend_from_slice(&encode_uleb128(site.action_index as u64));
        }

        data
    }
}

// ============================================================================
// Main Emitter: X86CodeEmission
// ============================================================================

/// The primary code emission preparation pass for X86 targets.
#[derive(Debug, Clone)]
pub struct X86CodeEmission {
    /// Target triple.
    pub target_triple: String,
    /// Whether targeting 64-bit mode.
    pub is_64bit: bool,
    /// Configuration.
    pub config: CodeEmissionConfig,
    /// Sections of the object file.
    pub sections: HashMap<String, ElfSection>,
    /// Section ordering for emission.
    pub section_order: Vec<String>,
    /// Symbols defined in the object file.
    pub symbols: Vec<ElfSymbol>,
    /// Relocations to apply.
    pub relocations: Vec<ElfRelocation>,
    /// Constant islands to emit.
    pub constant_islands: Vec<ConstantIsland>,
    /// Jump tables to emit.
    pub jump_tables: Vec<JumpTable>,
    /// The text section name (".text" or custom).
    pub text_section: String,
    /// The data section name.
    pub data_section: String,
    /// The read-only data section name.
    pub rodata_section: String,
    /// Current section being emitted to.
    pub current_section: Option<String>,
    /// Current offset in the text section.
    pub text_offset: u64,
    /// Statistics.
    pub stats: CodeEmissionStats,
}

/// Configuration for code emission.
#[derive(Debug, Clone)]
pub struct CodeEmissionConfig {
    /// Function alignment.
    pub function_alignment: u32,
    /// Loop alignment.
    pub loop_alignment: u32,
    /// Basic block alignment.
    pub block_alignment: u32,
    /// Constant island alignment.
    pub constant_island_alignment: u32,
    /// Jump table alignment.
    pub jump_table_alignment: u32,
    /// NOP variant to use.
    pub nop_variant: NOPVariant,
    /// Emit debug line information.
    pub emit_debug_line: bool,
    /// Emit CFI directives.
    pub emit_cfi: bool,
    /// Emit exception tables.
    pub emit_eh_tables: bool,
    /// Optimize NOP alignment for performance.
    pub optimize_alignments: bool,
    /// Use compact unwind on macOS.
    pub compact_unwind: bool,
    /// Target OS.
    pub target_os: TargetOs,
}

/// Target operating system for code emission.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TargetOs {
    Linux,
    MacOS,
    Windows,
    FreeBSD,
    Unknown,
}

impl Default for CodeEmissionConfig {
    fn default() -> Self {
        Self {
            function_alignment: DEFAULT_FUNCTION_ALIGNMENT,
            loop_alignment: DEFAULT_LOOP_ALIGNMENT,
            block_alignment: DEFAULT_BLOCK_ALIGNMENT,
            constant_island_alignment: CONSTANT_ISLAND_ALIGNMENT,
            jump_table_alignment: 8,
            nop_variant: NOPVariant::Intel,
            emit_debug_line: false,
            emit_cfi: false,
            emit_eh_tables: false,
            optimize_alignments: true,
            compact_unwind: false,
            target_os: TargetOs::Linux,
        }
    }
}

/// Statistics collected during code emission.
#[derive(Debug, Clone, Default)]
pub struct CodeEmissionStats {
    /// Number of functions emitted.
    pub functions_emitted: usize,
    /// Number of basic blocks emitted.
    pub blocks_emitted: usize,
    /// Total bytes of code emitted.
    pub code_bytes: u64,
    /// Total bytes of data emitted.
    pub data_bytes: u64,
    /// Number of NOP bytes emitted for alignment.
    pub nop_bytes: u64,
    /// Number of constant islands emitted.
    pub constant_islands: usize,
    /// Number of jump tables emitted.
    pub jump_tables: usize,
    /// Number of relocations emitted.
    pub relocations_count: usize,
    /// Number of symbols emitted.
    pub symbols_count: usize,
    /// Total debug info bytes.
    pub debug_bytes: u64,
}

// ============================================================================
// X86CodeEmission Implementation
// ============================================================================

impl X86CodeEmission {
    /// Create a new code emission preparer for x86-64.
    pub fn new_x86_64(target: &str) -> Self {
        let target_os = if target.contains("linux") {
            TargetOs::Linux
        } else if target.contains("darwin") || target.contains("macos") {
            TargetOs::MacOS
        } else if target.contains("windows") {
            TargetOs::Windows
        } else if target.contains("freebsd") {
            TargetOs::FreeBSD
        } else {
            TargetOs::Unknown
        };

        Self {
            target_triple: target.to_string(),
            is_64bit: true,
            config: CodeEmissionConfig::default(),
            sections: HashMap::new(),
            section_order: Vec::new(),
            symbols: Vec::new(),
            relocations: Vec::new(),
            constant_islands: Vec::new(),
            jump_tables: Vec::new(),
            text_section: ".text".to_string(),
            data_section: ".data".to_string(),
            rodata_section: ".rodata".to_string(),
            current_section: None,
            text_offset: 0,
            stats: CodeEmissionStats::default(),
        }
    }

    /// Create a new code emission preparer for x86-32.
    pub fn new_x86_32(target: &str) -> Self {
        let mut emitter = Self::new_x86_64(target);
        emitter.is_64bit = false;
        emitter
    }

    /// Set custom configuration.
    pub fn with_config(mut self, config: CodeEmissionConfig) -> Self {
        self.config = config;
        self
    }

    // ========================================================================
    // Full Emission Pipeline
    // ========================================================================

    /// Run the full code emission preparation on a function.
    pub fn prepare_function(&mut self, mf: &MachineFunction) {
        self.stats.functions_emitted += 1;
        self.stats.blocks_emitted += mf.blocks.len();

        // Ensure we're in the text section.
        self.switch_to_section(&self.text_section.clone());

        // Emit function alignment.
        self.emit_function_alignment(mf);

        // Emit function symbol.
        self.emit_symbol(&mf.name, self.text_offset, mf.blocks.len() as u64 * 16);

        // Emit function body.
        for block in &mf.blocks {
            // Optionally emit block alignment.
            if self.config.optimize_alignments {
                self.emit_block_alignment();
            }

            // Emit block code.
            for _instr in &block.instructions {
                // In a full implementation, encode each instruction to bytes
                // and append to the text section.
                self.stats.code_bytes += 4; // Average instruction size estimate.
            }
        }

        // Emit constant islands near this function if needed.
        self.emit_constant_islands_for_function(mf);

        // Emit jump tables for this function if needed.
        self.emit_jump_tables_for_function(mf);

        // Emit CFI directives if enabled.
        if self.config.emit_cfi {
            self.emit_cfi_for_function(mf);
        }

        // Emit debug line info if enabled.
        if self.config.emit_debug_line {
            self.emit_debug_line_for_function(mf);
        }

        // Emit exception handling tables if enabled.
        if self.config.emit_eh_tables {
            self.emit_eh_for_function(mf);
        }
    }

    // ========================================================================
    // Section Management
    // ========================================================================

    /// Switch to a named section, creating it if necessary.
    pub fn switch_to_section(&mut self, name: &str) {
        if self.current_section.as_deref() == Some(name) {
            return; // Already in this section.
        }

        if !self.sections.contains_key(name) {
            self.create_section(name);
        }

        self.current_section = Some(name.to_string());
    }

    /// Create a new section with appropriate flags.
    fn create_section(&mut self, name: &str) {
        let (section_type, flags) = self.section_defaults(name);
        let section = ElfSection::new(name, section_type, flags);

        if !self.section_order.contains(&name.to_string()) {
            self.section_order.push(name.to_string());
        }

        self.sections.insert(name.to_string(), section);
    }

    /// Get default section type and flags based on section name.
    fn section_defaults(&self, name: &str) -> (ElfSectionType, ElfSectionFlags) {
        match name {
            ".text" | ".text.hot" | ".text.startup" | ".text.unlikely" => {
                (ElfSectionType::Progbits, ElfSectionFlags::text())
            }
            ".data" | ".data.rel" | ".data.rel.ro" => {
                (ElfSectionType::Progbits, ElfSectionFlags::data())
            }
            ".rodata" | ".rodata.str1.1" | ".rodata.cst4" | ".rodata.cst8" | ".rodata.cst16" => {
                (ElfSectionType::Progbits, ElfSectionFlags::rodata())
            }
            ".bss" => (ElfSectionType::Nobits, ElfSectionFlags::bss()),
            ".eh_frame" => (
                ElfSectionType::X8664Unwind,
                ElfSectionFlags {
                    write: false,
                    alloc: true,
                    execinstr: false,
                    merge: false,
                    strings: false,
                    info_link: false,
                    link_order: false,
                    os_nonconforming: false,
                    group: false,
                    tls: false,
                },
            ),
            ".debug_line" | ".debug_info" | ".debug_abbrev" | ".debug_str" | ".debug_loc"
            | ".debug_ranges" => (
                ElfSectionType::Progbits,
                ElfSectionFlags {
                    write: false,
                    alloc: false,
                    execinstr: false,
                    merge: false,
                    strings: false,
                    info_link: false,
                    link_order: false,
                    os_nonconforming: false,
                    group: false,
                    tls: false,
                },
            ),
            ".symtab" => (
                ElfSectionType::Symtab,
                ElfSectionFlags {
                    write: false,
                    alloc: false,
                    execinstr: false,
                    merge: false,
                    strings: false,
                    info_link: false,
                    link_order: false,
                    os_nonconforming: false,
                    group: false,
                    tls: false,
                },
            ),
            ".strtab" => (
                ElfSectionType::Strtab,
                ElfSectionFlags {
                    write: false,
                    alloc: false,
                    execinstr: false,
                    merge: false,
                    strings: false,
                    info_link: false,
                    link_order: false,
                    os_nonconforming: false,
                    group: false,
                    tls: false,
                },
            ),
            ".rela.text" | ".rela.data" | ".rela.eh_frame" => (
                ElfSectionType::Rela,
                ElfSectionFlags {
                    write: false,
                    alloc: false,
                    execinstr: false,
                    merge: false,
                    strings: false,
                    info_link: true,
                    link_order: false,
                    os_nonconforming: false,
                    group: false,
                    tls: false,
                },
            ),
            _ => (
                ElfSectionType::Progbits,
                ElfSectionFlags {
                    write: false,
                    alloc: false,
                    execinstr: false,
                    merge: false,
                    strings: false,
                    info_link: false,
                    link_order: false,
                    os_nonconforming: false,
                    group: false,
                    tls: false,
                },
            ),
        }
    }

    // ========================================================================
    // Alignment Emission
    // ========================================================================

    /// Emit function entry alignment padding.
    pub fn emit_function_alignment(&mut self, _mf: &MachineFunction) {
        if self.config.function_alignment > 1 {
            let padding = generate_alignment_padding(
                self.text_offset,
                self.config.function_alignment,
                self.config.nop_variant,
            );
            if !padding.is_empty() {
                self.stats.nop_bytes += padding.len() as u64;
                self.append_to_current_section(&padding);
                self.text_offset += padding.len() as u64;
            }
        }
    }

    /// Emit basic block alignment padding.
    fn emit_block_alignment(&mut self) {
        if self.config.block_alignment > 1 {
            let padding = generate_alignment_padding(
                self.text_offset,
                self.config.block_alignment,
                self.config.nop_variant,
            );
            if !padding.is_empty() {
                self.stats.nop_bytes += padding.len() as u64;
                self.append_to_current_section(&padding);
                self.text_offset += padding.len() as u64;
            }
        }
    }

    /// Emit loop alignment padding (larger NOPs for loop tops).
    pub fn emit_loop_alignment(&mut self) {
        if self.config.loop_alignment > 1 {
            let padding = generate_alignment_padding(
                self.text_offset,
                self.config.loop_alignment,
                self.config.nop_variant,
            );
            if !padding.is_empty() {
                self.stats.nop_bytes += padding.len() as u64;
                self.append_to_current_section(&padding);
                self.text_offset += padding.len() as u64;
            }
        }
    }

    // ========================================================================
    // Constant Island Emission
    // ========================================================================

    /// Register a constant island for later emission.
    pub fn add_constant_island(&mut self, island: ConstantIsland) {
        self.constant_islands.push(island);
        self.stats.constant_islands += 1;
    }

    /// Emit all constant islands for a specific function.
    fn emit_constant_islands_for_function(&mut self, mf: &MachineFunction) {
        let func_name = &mf.name;
        let islands: Vec<usize> = self
            .constant_islands
            .iter()
            .enumerate()
            .filter(|(_, ci)| ci.function_name == *func_name)
            .map(|(i, _)| i)
            .collect();

        if islands.is_empty() {
            return;
        }

        // For inline islands: emit after an unconditional JMP at the
        // end of the function.
        // For separate islands: emit in the .rodata section.
        for idx in islands {
            let island = &self.constant_islands[idx];
            if island.is_inline {
                // Emit inline in .text section.
                let alignment = island.alignment;
                let padding = generate_alignment_padding(
                    self.text_offset,
                    alignment,
                    self.config.nop_variant,
                );
                self.append_to_current_section(&padding);
                self.text_offset += padding.len() as u64;

                for entry in &island.values {
                    match entry.size {
                        4 => {
                            self.append_u32_to_current_section(entry.value as u32);
                            self.text_offset += 4;
                        }
                        8 => {
                            self.append_u64_to_current_section(entry.value);
                            self.text_offset += 8;
                        }
                        _ => {
                            self.append_u64_to_current_section(entry.value);
                            self.text_offset += 8;
                        }
                    }
                }
                self.stats.data_bytes += island.values.len() as u64 * 8;
            } else {
                // Emit in rodata section.
                self.switch_to_section(&self.rodata_section);
                let alignment = island.alignment;
                let padding = generate_alignment_padding(
                    self.sections
                        .get(&self.rodata_section)
                        .map_or(0, |s| s.size),
                    alignment,
                    self.config.nop_variant,
                );
                self.append_to_current_section(&padding);

                for entry in &island.values {
                    match entry.size {
                        4 => {
                            self.append_u32_to_current_section(entry.value as u32);
                        }
                        8 => {
                            self.append_u64_to_current_section(entry.value);
                        }
                        _ => {
                            self.append_u64_to_current_section(entry.value);
                        }
                    }
                }
                self.switch_to_section(&self.text_section);
                self.stats.data_bytes += island.values.len() as u64 * 8;
            }
        }
    }

    // ========================================================================
    // Jump Table Emission
    // ========================================================================

    /// Register a jump table for later emission.
    pub fn add_jump_table(&mut self, table: JumpTable) {
        self.jump_tables.push(table);
        self.stats.jump_tables += 1;
    }

    /// Emit jump tables for a specific function.
    fn emit_jump_tables_for_function(&mut self, mf: &MachineFunction) {
        let func_name = &mf.name;
        let tables: Vec<usize> = self
            .jump_tables
            .iter()
            .enumerate()
            .filter(|(_, jt)| jt.function_name == *func_name)
            .map(|(i, _)| i)
            .collect();

        if tables.is_empty() {
            return;
        }

        // Jump tables are typically emitted in .rodata or .text.
        self.switch_to_section(&self.rodata_section);

        for idx in tables {
            let table = &self.jump_tables[idx];
            let alignment = table.alignment;
            let current_size = self
                .sections
                .get(&self.rodata_section)
                .map_or(0, |s| s.size);
            let padding =
                generate_alignment_padding(current_size, alignment, self.config.nop_variant);
            self.append_to_current_section(&padding);

            for _entry in &table.entries {
                // Emit the target address (or PC-relative offset) for each entry.
                if table.entry_size == 8 {
                    self.append_u64_to_current_section(0); // Placeholder; filled by relocation.
                } else {
                    self.append_u32_to_current_section(0); // Placeholder; filled by relocation.
                }
            }
            self.stats.data_bytes += table.entries.len() as u64 * table.entry_size as u64;
        }

        self.switch_to_section(&self.text_section);
    }

    // ========================================================================
    // Symbol Emission
    // ========================================================================

    /// Emit a symbol definition.
    pub fn emit_symbol(&mut self, name: &str, value: u64, size: u64) {
        let section_index = self.get_current_section_index();
        let symbol = ElfSymbol::new_function(name, value, size, section_index);
        self.symbols.push(symbol);
        self.stats.symbols_count += 1;
    }

    /// Emit an undefined symbol reference (relocation).
    pub fn emit_relocation(
        &mut self,
        offset: u64,
        rel_type: X86RelocationType,
        symbol_name: &str,
        addend: i64,
    ) {
        // Find or create the symbol.
        let symbol_index = self.find_or_create_symbol(symbol_name);

        self.relocations.push(ElfRelocation {
            offset,
            rel_type,
            symbol_index,
            addend,
        });
        self.stats.relocations_count += 1;
    }

    /// Find or create a symbol by name.
    fn find_or_create_symbol(&mut self, name: &str) -> u32 {
        if let Some(pos) = self.symbols.iter().position(|s| s.name == name) {
            pos as u32
        } else {
            let idx = self.symbols.len() as u32;
            let sym = ElfSymbol {
                name: name.to_string(),
                value: 0,
                size: 0,
                symbol_type: SymbolType::Notype,
                binding: SymbolBinding::Global,
                visibility: SymbolVisibility::Default,
                section_index: 0,
                is_undefined: true,
            };
            self.symbols.push(sym);
            self.stats.symbols_count += 1;
            idx
        }
    }

    // ========================================================================
    // CFI Emission
    // ========================================================================

    /// Emit CFI directives for a function.
    fn emit_cfi_for_function(&mut self, mf: &MachineFunction) {
        let fde = self.build_fde_for_function(mf);

        self.switch_to_section(".eh_frame");

        // CIE
        let cie = CIE {
            version: 1,
            augmentation: "zR".to_string(),
            code_alignment_factor: 1,
            data_alignment_factor: if self.is_64bit { -8 } else { -4 },
            return_address_register: if self.is_64bit { 16 } else { 8 }, // RA/RIP
            initial_directives: Vec::new(),
            has_personality: false,
            personality_encoding: 0,
            has_lsda_encoding: false,
            lsda_encoding: 0,
            fde_encoding: 0x1B, // DW_EH_PE_pcrel | DW_EH_PE_sdata4
        };

        // Encode CIE + FDE into the .eh_frame section.
        let encoded = self.encode_eh_frame(&cie, &fde);
        self.append_to_current_section(&encoded);
        self.stats.debug_bytes += encoded.len() as u64;

        self.switch_to_section(&self.text_section);
    }

    /// Build an FDE for a function.
    fn build_fde_for_function(&self, mf: &MachineFunction) -> FDE {
        let mut directives: Vec<CFIDirective> = Vec::new();

        // Standard prologue CFI directives.
        // push rbp
        if self.is_64bit {
            directives.push(CFIDirective::DefCfaOffset(16));
            directives.push(CFIDirective::Offset(RBP, -16));
            // mov rbp, rsp
            directives.push(CFIDirective::DefCfaRegister(RBP));
        }

        // Callee-saved register saves.
        // ... (depends on frame lowering).

        FDE {
            cie_index: 0,
            initial_location: 0,                        // Filled by relocation.
            address_range: mf.blocks.len() as u64 * 16, // Estimated function size.
            directives,
            lsda: None,
            personality: None,
            has_lsda: false,
        }
    }

    /// Encode CIE + FDE into raw bytes for the .eh_frame section.
    fn encode_eh_frame(&self, cie: &CIE, fde: &FDE) -> Vec<u8> {
        let mut data: Vec<u8> = Vec::new();

        // CIE length (placeholder, will be filled later).
        data.extend_from_slice(&0u32.to_le_bytes());
        // CIE id = 0.
        data.extend_from_slice(&0u32.to_le_bytes());
        // Version.
        data.push(cie.version);
        // Augmentation string.
        data.extend_from_slice(cie.augmentation.as_bytes());
        data.push(0);
        // Code alignment factor.
        data.extend_from_slice(&encode_uleb128(cie.code_alignment_factor));
        // Data alignment factor.
        data.extend_from_slice(&encode_sleb128(cie.data_alignment_factor));
        // Return address register.
        data.push(cie.return_address_register as u8);

        // ... Initial directives, augmentation data, etc.

        // FDE
        // FDE length.
        data.extend_from_slice(&0u32.to_le_bytes());
        // CIE pointer (relocation).
        data.extend_from_slice(&0i32.to_le_bytes());
        // Initial location (relocation).
        data.extend_from_slice(&0i32.to_le_bytes());
        // Address range.
        data.extend_from_slice(&(fde.address_range as u32).to_le_bytes());

        // CFI instructions.
        for directive in &fde.directives {
            match directive {
                CFIDirective::DefCfaOffset(offset) => {
                    data.push(0x0F); // DW_CFA_def_cfa_offset
                    data.extend_from_slice(&encode_uleb128(*offset as u64));
                }
                CFIDirective::DefCfaRegister(reg) => {
                    data.push(0x0D); // DW_CFA_def_cfa_register
                    data.extend_from_slice(&encode_uleb128(*reg as u64));
                }
                CFIDirective::Offset(reg, offset) => {
                    data.push(0x80 | (reg & 0x3F) as u8); // DW_CFA_offset
                    data.extend_from_slice(&encode_uleb128(*offset as u64));
                }
                CFIDirective::DefCfa(reg, offset) => {
                    data.push(0x0C); // DW_CFA_def_cfa
                    data.extend_from_slice(&encode_uleb128(*reg as u64));
                    data.extend_from_slice(&encode_uleb128(*offset as u64));
                }
                _ => {
                    // Placeholder for other CFI directives.
                }
            }
        }

        data
    }

    // ========================================================================
    // Debug Line Emission
    // ========================================================================

    /// Emit debug line info for a function.
    fn emit_debug_line_for_function(&mut self, _mf: &MachineFunction) {
        if !self.config.emit_debug_line {
            return;
        }

        let mut program = DwarfLineProgram::new();

        // Emit a line program for this function.
        // In a full implementation, this would contain address/line mappings
        // for each instruction.

        if !program.is_empty() {
            self.switch_to_section(".debug_line");
            self.append_to_current_section(&program.bytecode);
            self.stats.debug_bytes += program.bytecode.len() as u64;
            self.switch_to_section(&self.text_section);
        }
    }

    // ========================================================================
    // Exception Table Emission
    // ========================================================================

    /// Emit exception handling tables for a function.
    fn emit_eh_for_function(&mut self, mf: &MachineFunction) {
        if !self.config.emit_eh_tables {
            return;
        }

        let lsda = self.build_lsda_for_function(mf);
        let encoded = lsda.encode();

        if !encoded.is_empty() {
            self.switch_to_section(".gcc_except_table");
            self.append_to_current_section(&encoded);
            self.stats.debug_bytes += encoded.len() as u64;
            self.switch_to_section(&self.text_section);
        }
    }

    /// Build an LSDA for a function with exception handling.
    fn build_lsda_for_function(&self, _mf: &MachineFunction) -> Lsda {
        // Scan the function for landing pads, catch blocks, and cleanup blocks.
        let mut lsda = Lsda::new();
        // In a full implementation, analyze EH labels and build
        // call site table and action table.
        lsda
    }

    // ========================================================================
    // Section Data Append Helpers
    // ========================================================================

    /// Append raw data to the current section.
    fn append_to_current_section(&mut self, data: &[u8]) {
        if let Some(ref name) = self.current_section.clone() {
            if let Some(section) = self.sections.get_mut(name) {
                section.append(data);
            }
        }
    }

    /// Append a u32 to the current section.
    fn append_u32_to_current_section(&mut self, value: u32) {
        if let Some(ref name) = self.current_section.clone() {
            if let Some(section) = self.sections.get_mut(name) {
                section.append_u32(value);
            }
        }
    }

    /// Append a u64 to the current section.
    fn append_u64_to_current_section(&mut self, value: u64) {
        if let Some(ref name) = self.current_section.clone() {
            if let Some(section) = self.sections.get_mut(name) {
                section.append_u64(value);
            }
        }
    }

    // ========================================================================
    // Section Organization
    // ========================================================================

    /// Get the current section index (0 = undefined).
    fn get_current_section_index(&self) -> u32 {
        if let Some(ref name) = self.current_section {
            self.section_order
                .iter()
                .position(|n| n == name)
                .map_or(0, |i| (i + 1) as u32)
        } else {
            0
        }
    }

    /// Finalize all sections for writing the object file.
    pub fn finalize_sections(&mut self) {
        // Compute offsets for each section.
        let mut offset: u64 = 0;

        // ELF header space (64 bytes for Elf64_Ehdr).
        offset += 64;

        // Reserve space for section header table.
        let shdr_size: u64 = if self.is_64bit { 64 } else { 40 };
        let num_sections = self.section_order.len() + 1; // +1 for null section
        offset += shdr_size * num_sections as u64;

        for name in &self.section_order.clone() {
            if let Some(section) = self.sections.get_mut(name) {
                // Align section start.
                let align = section.alignment as u64;
                if align > 1 {
                    let misalign = offset & (align - 1);
                    if misalign != 0 {
                        offset += align - misalign;
                    }
                }
                section.offset = offset;
                offset += section.size;
                section.finalized = true;
            }
        }
    }

    /// Generate a report string.
    pub fn report(&self) -> String {
        format!(
            "CodeEmission: funcs={} blocks={} code_bytes={} data_bytes={} nop_bytes={} \
             const_islands={} jump_tables={} relocs={} symbols={} debug_bytes={} sections={}",
            self.stats.functions_emitted,
            self.stats.blocks_emitted,
            self.stats.code_bytes,
            self.stats.data_bytes,
            self.stats.nop_bytes,
            self.stats.constant_islands,
            self.stats.jump_tables,
            self.stats.relocations_count,
            self.stats.symbols_count,
            self.stats.debug_bytes,
            self.sections.len(),
        )
    }
}

// ============================================================================
// Public API Factory Functions
// ============================================================================

/// Create an X86 code emission preparer for x86-64 targets.
pub fn make_x86_64_code_emission(target: &str) -> X86CodeEmission {
    X86CodeEmission::new_x86_64(target)
}

/// Create an X86 code emission preparer for x86-32 targets.
pub fn make_x86_32_code_emission(target: &str) -> X86CodeEmission {
    X86CodeEmission::new_x86_32(target)
}

/// Create a code emission preparer with all features enabled.
pub fn make_code_emission_full(target: &str) -> X86CodeEmission {
    let config = CodeEmissionConfig {
        emit_debug_line: true,
        emit_cfi: true,
        emit_eh_tables: true,
        optimize_alignments: true,
        ..CodeEmissionConfig::default()
    };
    X86CodeEmission::new_x86_64(target).with_config(config)
}

/// Create a code emission preparer for release (no debug info).
pub fn make_code_emission_release(target: &str) -> X86CodeEmission {
    let config = CodeEmissionConfig {
        emit_debug_line: false,
        emit_cfi: false,
        emit_eh_tables: false,
        optimize_alignments: true,
        ..CodeEmissionConfig::default()
    };
    X86CodeEmission::new_x86_64(target).with_config(config)
}

/// Run full code emission preparation on a function.
pub fn prepare_for_emission(mf: &MachineFunction, target: &str) -> X86CodeEmission {
    let mut emitter = make_x86_64_code_emission(target);
    emitter.prepare_function(mf);
    emitter
}

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

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

    #[test]
    fn test_encode_uleb128_zero() {
        let encoded = encode_uleb128(0);
        assert_eq!(encoded, vec![0x00]);
    }

    #[test]
    fn test_encode_uleb128_small() {
        let encoded = encode_uleb128(127);
        assert_eq!(encoded, vec![0x7F]);
    }

    #[test]
    fn test_encode_uleb128_large() {
        let encoded = encode_uleb128(128);
        assert_eq!(encoded, vec![0x80, 0x01]);
    }

    #[test]
    fn test_encode_uleb128_very_large() {
        let encoded = encode_uleb128(624485);
        // 624485 = 0x98765 = encoded as 0xE5 0x8E 0x26
        assert_eq!(encoded, vec![0xE5, 0x8E, 0x26]);
    }

    #[test]
    fn test_encode_sleb128_zero() {
        let encoded = encode_sleb128(0);
        assert_eq!(encoded, vec![0x00]);
    }

    #[test]
    fn test_encode_sleb128_positive() {
        let encoded = encode_sleb128(64);
        assert_eq!(encoded, vec![0x40]);
    }

    #[test]
    fn test_encode_sleb128_negative() {
        let encoded = encode_sleb128(-1);
        assert_eq!(encoded, vec![0x7F]);
    }

    #[test]
    fn test_encode_sleb128_neg_64() {
        let encoded = encode_sleb128(-64);
        assert_eq!(encoded, vec![0x40]); // 0x40 with sign extension
    }

    #[test]
    fn test_generate_nop_padding_lengths() {
        for len in 1..=20 {
            let nops = generate_nop_padding(len, NOPVariant::Intel);
            assert_eq!(nops.len(), len, "NOP padding for len={}", len);
        }
    }

    #[test]
    fn test_generate_nop_padding_single_byte() {
        let nops = generate_nop_padding(5, NOPVariant::SingleByte);
        assert_eq!(nops, vec![0x90, 0x90, 0x90, 0x90, 0x90]);
    }

    #[test]
    fn test_generate_alignment_padding() {
        // Current offset: 3, alignment: 4, should add 1 byte.
        let padding = generate_alignment_padding(3, 4, NOPVariant::Intel);
        assert_eq!(padding.len(), 1);

        // Current offset: 4, alignment: 4, should add 0 bytes.
        let padding = generate_alignment_padding(4, 4, NOPVariant::Intel);
        assert_eq!(padding.len(), 0);

        // Current offset: 5, alignment: 16, should add 11 bytes.
        let padding = generate_alignment_padding(5, 16, NOPVariant::Intel);
        assert_eq!(padding.len(), 11);
    }

    #[test]
    fn test_elf_section_flags_text() {
        let flags = ElfSectionFlags::text();
        assert!(flags.alloc);
        assert!(flags.execinstr);
        assert!(!flags.write);
    }

    #[test]
    fn test_elf_section_flags_data() {
        let flags = ElfSectionFlags::data();
        assert!(flags.alloc);
        assert!(flags.write);
        assert!(!flags.execinstr);
    }

    #[test]
    fn test_elf_section_flags_rodata() {
        let flags = ElfSectionFlags::rodata();
        assert!(flags.alloc);
        assert!(!flags.write);
        assert!(!flags.execinstr);
    }

    #[test]
    fn test_elf_section_append() {
        let mut section =
            ElfSection::new(".test", ElfSectionType::Progbits, ElfSectionFlags::rodata());
        section.append_u32(0xDEADBEEF);
        assert_eq!(section.size, 4);
        assert_eq!(&section.data, &[0xEF, 0xBE, 0xAD, 0xDE]);
    }

    #[test]
    fn test_elf_section_append_u16() {
        let mut section =
            ElfSection::new(".test", ElfSectionType::Progbits, ElfSectionFlags::rodata());
        section.append_u16(0x1234);
        assert_eq!(section.data, vec![0x34, 0x12]);
    }

    #[test]
    fn test_elf_symbol_new_function() {
        let sym = ElfSymbol::new_function("my_func", 0x1000, 0x42, 1);
        assert_eq!(sym.name, "my_func");
        assert_eq!(sym.value, 0x1000);
        assert_eq!(sym.size, 0x42);
        assert_eq!(sym.symbol_type, SymbolType::Func);
        assert_eq!(sym.binding, SymbolBinding::Global);
    }

    #[test]
    fn test_elf_symbol_as_undefined() {
        let sym = ElfSymbol::new_function("ext_func", 0, 0, 1).as_undefined();
        assert!(sym.is_undefined);
        assert_eq!(sym.section_index, 0);
    }

    #[test]
    fn test_relocation_type_values() {
        assert_eq!(X86RelocationType::Dir64.elf_value_x86_64(), 1);
        assert_eq!(X86RelocationType::PC32.elf_value_x86_64(), 2);
        assert_eq!(X86RelocationType::GotPcRel.elf_value_x86_64(), 9);
    }

    #[test]
    fn test_dwarf_line_program_special_opcode() {
        let mut program = DwarfLineProgram::new();
        // line_advance = 0, addr_advance = 0 should produce opcode_base.
        program.emit_special_opcode(0, 0);
        // For line_base=-5, line_range=14, adjusted_line = 0 - (-5) = 5
        // The formula is: (adjusted_line) + (line_range * addr_advance)
        // Wait, that doesn't seem right. Let's verify: DWARF5 spec:
        // opcode = (line_increment - line_base) + (line_range * op_index)
        // So: (0 - (-5)) + (14 * 0) = 5
        // special_opcode = opcode_base + 5 = 13 + 5 = 18
        assert_eq!(program.bytecode[0], 18);
    }

    #[test]
    fn test_lsda_new() {
        let lsda = Lsda::new();
        assert_eq!(lsda.landing_pad_base, 0);
        assert!(lsda.call_sites.is_empty());
        assert!(lsda.actions.is_empty());
    }

    #[test]
    fn test_lsda_encode_empty() {
        let lsda = Lsda::new();
        let encoded = lsda.encode();
        // LP base (1 byte) + ttype encoding (1 byte) + ttype offset (1 byte for zero) +
        // call site table length (1 byte for zero) = at least 4 bytes.
        assert!(encoded.len() >= 4);
    }

    #[test]
    fn test_code_emission_config_default() {
        let config = CodeEmissionConfig::default();
        assert_eq!(config.function_alignment, 16);
        assert!(config.optimize_alignments);
        assert!(!config.emit_debug_line);
    }

    #[test]
    fn test_code_emission_new() {
        let emitter = X86CodeEmission::new_x86_64("x86_64-unknown-linux-gnu");
        assert!(emitter.is_64bit);
        assert_eq!(emitter.text_section, ".text");
        assert!(emitter.sections.is_empty());
    }

    #[test]
    fn test_section_switch_creates_section() {
        let mut emitter = X86CodeEmission::new_x86_64("x86_64-unknown-linux-gnu");
        emitter.switch_to_section(".text");
        assert!(emitter.sections.contains_key(".text"));
        assert_eq!(emitter.current_section, Some(".text".to_string()));
    }

    #[test]
    fn test_section_switch_no_duplicate() {
        let mut emitter = X86CodeEmission::new_x86_64("x86_64-unknown-linux-gnu");
        emitter.switch_to_section(".text");
        let count_before = emitter.sections.len();
        emitter.switch_to_section(".text");
        assert_eq!(emitter.sections.len(), count_before);
    }

    #[test]
    fn test_symbol_emission() {
        let mut emitter = X86CodeEmission::new_x86_64("x86_64-unknown-linux-gnu");
        emitter.switch_to_section(".text");
        emitter.emit_symbol("test_func", 0x4000, 64);
        assert_eq!(emitter.symbols.len(), 1);
        assert_eq!(emitter.symbols[0].name, "test_func");
    }

    #[test]
    fn test_relocation_emission() {
        let mut emitter = X86CodeEmission::new_x86_64("x86_64-unknown-linux-gnu");
        emitter.emit_relocation(10, X86RelocationType::PC32, "puts", -4);
        assert_eq!(emitter.relocations.len(), 1);
        assert_eq!(emitter.relocations[0].offset, 10);
    }

    #[test]
    fn test_constant_island_registration() {
        let mut emitter = X86CodeEmission::new_x86_64("x86_64-unknown-linux-gnu");
        let island = ConstantIsland {
            id: 0,
            offset: 0,
            values: vec![ConstantIslandEntry {
                value: 0xDEADBEEF,
                size: 8,
                is_pc_rel: true,
                label: None,
            }],
            alignment: 8,
            is_inline: true,
            function_name: "test".to_string(),
        };
        emitter.add_constant_island(island);
        assert_eq!(emitter.constant_islands.len(), 1);
        assert_eq!(emitter.stats.constant_islands, 1);
    }

    #[test]
    fn test_jump_table_registration() {
        let mut emitter = X86CodeEmission::new_x86_64("x86_64-unknown-linux-gnu");
        let table = JumpTable {
            id: 0,
            function_name: "test".to_string(),
            entries: vec!["L0".to_string(), "L1".to_string()],
            entry_size: 8,
            min_case: 0,
            max_case: 1,
            alignment: 8,
            pc_relative: true,
            offset: 0,
        };
        emitter.add_jump_table(table);
        assert_eq!(emitter.jump_tables.len(), 1);
    }

    #[test]
    fn test_nop_variant_enum() {
        assert_eq!(NOPVariant::Intel as u8, NOPVariant::Intel as u8);
        assert_ne!(NOPVariant::Intel as u8, NOPVariant::Amd as u8);
    }

    #[test]
    fn test_symbol_type_values() {
        assert_eq!(SymbolType::Func.elf_value(), 2);
        assert_eq!(SymbolType::Object.elf_value(), 1);
        assert_eq!(SymbolType::Notype.elf_value(), 0);
    }

    #[test]
    fn test_symbol_binding_values() {
        assert_eq!(SymbolBinding::Global.elf_value(), 1);
        assert_eq!(SymbolBinding::Local.elf_value(), 0);
        assert_eq!(SymbolBinding::Weak.elf_value(), 2);
    }

    #[test]
    fn test_section_type_values() {
        assert_eq!(ElfSectionType::Progbits.elf_value(), 1);
        assert_eq!(ElfSectionType::Nobits.elf_value(), 8);
    }

    #[test]
    fn test_target_os_detection() {
        let emitter = X86CodeEmission::new_x86_64("x86_64-unknown-linux-gnu");
        assert_eq!(emitter.config.target_os, TargetOs::Linux);

        let emitter = X86CodeEmission::new_x86_64("x86_64-apple-darwin");
        assert_eq!(emitter.config.target_os, TargetOs::MacOS);

        let emitter = X86CodeEmission::new_x86_64("x86_64-pc-windows-msvc");
        assert_eq!(emitter.config.target_os, TargetOs::Windows);
    }

    #[test]
    fn test_report_format() {
        let emitter = X86CodeEmission::new_x86_64("x86_64-unknown-linux-gnu");
        let report = emitter.report();
        assert!(report.contains("CodeEmission:"));
        assert!(report.contains("funcs=0"));
    }

    #[test]
    fn test_leb128_roundtrip() {
        let test_values: Vec<u64> = vec![0, 1, 127, 128, 255, 65535, 1_000_000];
        for val in &test_values {
            let encoded = encode_uleb128(*val);
            // Decode back (simple decoder).
            let mut decoded: u64 = 0;
            let mut shift: u32 = 0;
            for &byte in &encoded {
                decoded |= ((byte & 0x7F) as u64) << shift;
                shift += 7;
                if byte & 0x80 == 0 {
                    break;
                }
            }
            assert_eq!(decoded, *val, "ULEB128 roundtrip for {}", val);
        }
    }
}