llvm-native-core 0.1.10

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

use super::x86_full_instr_info::{
    EncodingForm, InstrEncodingInfo, X86FullInstrInfo, X86FullOpcode, X86FullOpcode::*,
};
use super::x86_instr_info::{OperandType, X86MemOperand, X86Operand};
pub use super::x86_mc_encoder::X86Mode;
use super::x86_mc_encoder::{mod_field, prefixes, X86MCEncoder};
use super::x86_register_info::{
    RegClass, AH, AL, AX, BH, BL, BPL, BX, CH, CL, CS, CX, DH, DIL, DL, DS, DX, EAX, EBP, EBX, ECX,
    EDI, EDX, ES, ESI, ESP, FS, GS, K0, K1, K2, K3, K4, K5, K6, K7, R10, R10B, R10D, R10W, R11,
    R11B, R11D, R11W, R12, R12B, R12D, R12W, R13, R13B, R13D, R13W, R14, R14B, R14D, R14W, R15,
    R15B, R15D, R15W, R8, R8B, R8D, R8W, R9, R9B, R9D, R9W, RAX, RBP, RBX, RCX, RDI, RDX, RIP, RSI,
    RSP, SIL, SPL, SS, XMM0, XMM1, XMM10, XMM11, XMM12, XMM13, XMM14, XMM15, XMM16, XMM17, XMM18,
    XMM19, XMM2, XMM20, XMM21, XMM22, XMM23, XMM24, XMM25, XMM26, XMM27, XMM28, XMM29, XMM3, XMM30,
    XMM31, XMM4, XMM5, XMM6, XMM7, XMM8, XMM9, YMM0, YMM1, YMM10, YMM11, YMM12, YMM13, YMM14,
    YMM15, YMM16, YMM17, YMM18, YMM19, YMM2, YMM20, YMM21, YMM22, YMM23, YMM24, YMM25, YMM26,
    YMM27, YMM28, YMM29, YMM3, YMM30, YMM31, YMM4, YMM5, YMM6, YMM7, YMM8, YMM9, ZMM0, ZMM1, ZMM10,
    ZMM11, ZMM12, ZMM13, ZMM14, ZMM15, ZMM16, ZMM17, ZMM18, ZMM19, ZMM2, ZMM20, ZMM21, ZMM22,
    ZMM23, ZMM24, ZMM25, ZMM26, ZMM27, ZMM28, ZMM29, ZMM3, ZMM30, ZMM31, ZMM4, ZMM5, ZMM6, ZMM7,
    ZMM8, ZMM9,
};
use super::x86_subtarget::X86Subtarget;

// ============================================================================
// REX prefix constants
// ============================================================================

/// REX prefix byte values.
pub mod rex_prefix {
    /// REX prefix base value.
    pub const REX_BASE: u8 = 0x40;
    /// REX.W — 64-bit operand size.
    pub const REX_W: u8 = 0x48;
    /// REX.R — extension of ModR/M reg field.
    pub const REX_R: u8 = 0x44;
    /// REX.X — extension of SIB index field.
    pub const REX_X: u8 = 0x42;
    /// REX.B — extension of ModR/M r/m field, SIB base, or opcode reg.
    pub const REX_B: u8 = 0x41;
}

// ============================================================================
// VEX prefix constants
// ============================================================================

/// VEX prefix helpers.
pub mod vex_prefix {
    /// 2-byte VEX prefix: 0xC5.
    pub const VEX_2BYTE: u8 = 0xC5;
    /// 3-byte VEX prefix: 0xC4.
    pub const VEX_3BYTE: u8 = 0xC4;

    /// Invert a register field for VEX encoding.
    /// In VEX, register fields are stored in 1's complement form.
    pub fn invert_reg(reg: u8) -> u8 {
        (!reg) & 0xF
    }

    /// Build a 2-byte VEX prefix.
    ///
    /// 2-byte VEX layout: [C5] [RvvvvLpp]
    ///   R: 1-bit, 1's complement of REX.R
    ///   vvvv: 4-bit, 1's complement of source register
    ///   L: 1-bit, vector length (0=128, 1=256)
    ///   pp: 2-bit, implied mandatory prefix (0=none, 1=66, 2=F3, 3=F2)
    pub fn build_2byte(r: bool, vvvv: u8, l: bool, pp: u8) -> [u8; 2] {
        let byte1 = (!r as u8) << 7 | (invert_reg(vvvv) << 3) | ((l as u8) << 2) | (pp & 0x3);
        [VEX_2BYTE, byte1]
    }

    /// Build a 3-byte VEX prefix.
    ///
    /// 3-byte VEX layout: [C4] [RXBmmmmm] [WvvvvLpp]
    ///   R: 1-bit, 1's complement of REX.R
    ///   X: 1-bit, 1's complement of REX.X
    ///   B: 1-bit, 1's complement of REX.B
    ///   mmmmm: 5-bit, opcode map selector (1=0F, 2=0F38, 3=0F3A)
    ///   W: 1-bit, REX.W for 64-bit operand size
    ///   vvvv: 4-bit, 1's complement of source register
    ///   L: 1-bit, vector length
    ///   pp: 2-bit, implied mandatory prefix
    pub fn build_3byte(
        r: bool,
        x: bool,
        b: bool,
        mmmmm: u8,
        w: bool,
        vvvv: u8,
        l: bool,
        pp: u8,
    ) -> [u8; 3] {
        let byte1 = (!r as u8) << 7 | (!x as u8) << 6 | (!b as u8) << 5 | (mmmmm & 0x1F);
        let byte2 = (w as u8) << 7 | (invert_reg(vvvv) << 3) | ((l as u8) << 2) | (pp & 0x3);
        [VEX_3BYTE, byte1, byte2]
    }
}

// ============================================================================
// EVEX prefix constants
// ============================================================================

/// EVEX prefix helpers.
pub mod evex_prefix {
    /// EVEX prefix first byte: always 0x62.
    pub const EVEX_MAGIC: u8 = 0x62;

    /// Build a 4-byte EVEX prefix.
    ///
    /// EVEX layout: [62] [P0] [P1] [P2]
    ///   P0: [R X B R' 0 0 mmm]
    ///   P1: [W vvvv 1 pp]
    ///   P2: [z L'L b V' aaa]
    pub fn build_evex(
        r: bool,
        x: bool,
        b: bool,
        r_prime: bool,
        mmmm: u8,
        w: bool,
        vvvv: u8,
        pp: u8,
        z: bool,
        ll: u8,
        b_prim: bool,
        aaa: u8,
    ) -> [u8; 4] {
        let p0 = (!r as u8) << 7
            | (!x as u8) << 6
            | (!b as u8) << 5
            | (!r_prime as u8) << 4
            | (mmmm & 0x07);
        let p1 = (w as u8) << 7
            | (super::vex_prefix::invert_reg(vvvv) << 3)
            | 0x04  // bit 2 must be 1
            | (pp & 0x03);
        let p2 = (z as u8) << 7
            | ((ll & 0x03) << 5)
            | (b_prim as u8) << 4
            | 0x08  // V' = 0 (no additional source)
            | (aaa & 0x07);
        [EVEX_MAGIC, p0, p1, p2]
    }
}

// ============================================================================
// XOP prefix constants
// ============================================================================

/// XOP prefix helpers (AMD XOP extension).
pub mod xop_prefix {
    /// XOP prefix first byte: always 0x8F.
    pub const XOP_MAGIC: u8 = 0x8F;

    /// Build a 3-byte XOP prefix.
    /// XOP layout: [8F] [RXBmmmmm] [WvvvvLpp]
    pub fn build_xop(
        r: bool,
        x: bool,
        b: bool,
        mmmmm: u8,
        w: bool,
        vvvv: u8,
        l: bool,
        pp: u8,
    ) -> [u8; 3] {
        let byte1 = (!r as u8) << 7 | (!x as u8) << 6 | (!b as u8) << 5 | (mmmmm & 0x1F);
        let byte2 = (w as u8) << 7
            | (super::vex_prefix::invert_reg(vvvv) << 3)
            | ((l as u8) << 2)
            | (pp & 0x3);
        [XOP_MAGIC, byte1, byte2]
    }
}

// ============================================================================
// SIB byte constants
// ============================================================================

/// SIB byte layout helpers.
pub mod sib_byte {
    /// Build a SIB byte from scale, index, and base fields.
    pub fn build(scale: u8, index: u8, base: u8) -> u8 {
        (scale & 0x3) << 6 | (index & 0x7) << 3 | (base & 0x7)
    }

    /// SIB scale values.
    pub const SCALE_1: u8 = 0;
    pub const SCALE_2: u8 = 1;
    pub const SCALE_4: u8 = 2;
    pub const SCALE_8: u8 = 3;

    /// Special SIB index value meaning "no index register".
    pub const NO_INDEX: u8 = 4;
    /// Special SIB base value meaning "R13 or RBP + disp32" (depends on mod).
    pub const RBP_BASE: u8 = 5;
}

// ============================================================================
// EVEX extended types: tuple, broadcast, rounding
// ============================================================================

/// EVEX tuple type: determines compressed displacement multiplier.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EvexTuple {
    Full,
    FullMem,
    Half,
    HalfMem,
    Quarter,
    QuarterMem,
    Eighth,
    EighthMem,
    Scalar,
    Mem128,
}

impl EvexTuple {
    pub fn multiplier(&self) -> u8 {
        match self {
            EvexTuple::Full | EvexTuple::FullMem => 64,
            EvexTuple::Half | EvexTuple::HalfMem => 32,
            EvexTuple::Quarter | EvexTuple::QuarterMem | EvexTuple::Mem128 => 16,
            EvexTuple::Eighth | EvexTuple::EighthMem => 8,
            EvexTuple::Scalar => 4,
        }
    }
    pub fn is_memory(&self) -> bool {
        matches!(
            self,
            EvexTuple::FullMem | EvexTuple::HalfMem | EvexTuple::QuarterMem | EvexTuple::EighthMem
        )
    }
}

/// EVEX broadcast mode for memory operand.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EvexBroadcast {
    None,
    Broadcast1To2,
    Broadcast1To4,
    Broadcast1To8,
    Broadcast1To16,
    Broadcast1To32,
}

impl EvexBroadcast {
    pub fn is_broadcast(&self) -> bool {
        !matches!(self, EvexBroadcast::None)
    }
}

/// EVEX rounding mode for FP operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EvexRounding {
    None,
    RnSae,
    RdSae,
    RuSae,
    RzSae,
    Sae,
}

impl EvexRounding {
    pub fn is_active(&self) -> bool {
        !matches!(self, EvexRounding::None)
    }
    pub fn rc_bits(&self) -> u8 {
        match self {
            EvexRounding::RnSae => 0,
            EvexRounding::RdSae => 1,
            EvexRounding::RuSae => 2,
            EvexRounding::RzSae => 3,
            EvexRounding::Sae => 0,
            EvexRounding::None => 0,
        }
    }
}

// ============================================================================
// X86FullMCEncoder — complete X86 instruction encoder
// ============================================================================

/// Complete X86 instruction encoder supporting all encoding forms
/// (legacy, REX, VEX, EVEX, XOP) for the full X86FullOpcode set.
pub struct X86FullMCEncoder {
    /// Accumulated output bytes.
    pub output: Vec<u8>,
    /// Operating mode (16-bit, 32-bit, or 64-bit).
    pub mode: X86Mode,
    /// Target subtarget for feature-aware encoding.
    pub subtarget: X86Subtarget,
    /// Full instruction info database.
    pub instr_info: X86FullInstrInfo,
}

impl X86FullMCEncoder {
    /// Create a new full encoder.
    pub fn new(mode: X86Mode, subtarget: X86Subtarget) -> Self {
        Self {
            output: Vec::new(),
            mode,
            subtarget,
            instr_info: X86FullInstrInfo::new(),
        }
    }

    /// Create a new full encoder with a pre-existing instr_info (for reuse).
    pub fn with_info(mode: X86Mode, subtarget: X86Subtarget, info: X86FullInstrInfo) -> Self {
        Self {
            output: Vec::new(),
            mode,
            subtarget,
            instr_info: info,
        }
    }

    // ========================================================================
    // Main encoding entry point
    // ========================================================================

    /// Encode a single instruction into bytes.
    /// Returns the encoded bytes, clearing the internal output buffer.
    pub fn encode_instruction(
        &mut self,
        opcode: X86FullOpcode,
        operands: &[X86Operand],
    ) -> Vec<u8> {
        self.output.clear();

        let Some(encoding) = self.instr_info.get(opcode).cloned() else {
            // Unknown opcode — emit UD2
            self.output.push(0x0F);
            self.output.push(0x0B);
            return self.output.clone();
        };

        // 1. Emit encoding prefix (VEX/EVEX/XOP) or legacy prefixes
        match encoding.encoding_form {
            EncodingForm::VEX | EncodingForm::VEX3Byte => {
                self.encode_vex_prefix(&encoding, operands);
            }
            EncodingForm::EVEX => {
                self.encode_evex_prefix(&encoding, operands);
            }
            EncodingForm::XOP => {
                self.encode_xop_prefix(&encoding, operands);
            }
            EncodingForm::Legacy | EncodingForm::LegacyREX => {
                self.encode_legacy_prefixes(&encoding, operands);
            }
            EncodingForm::None => {
                // Pure prefix instruction (e.g., REP, LOCK)
            }
        }

        // 2. Emit opcode bytes
        self.encode_opcode_bytes(&encoding);

        // 3. Emit ModR/M if required
        if encoding.requires_modrm {
            let modrm = self.compute_modrm(&encoding, operands);
            self.output.push(modrm);
        }

        // 4. Emit SIB if needed (memory operand with index or RSP/R12 base)
        if self.needs_sib(operands) {
            let sib = self.compute_sib(operands);
            self.output.push(sib);
        }

        // 5. Emit displacement
        self.encode_displacement(operands);

        // 6. Emit immediate(s)
        self.encode_immediates(operands);

        self.output.clone()
    }

    // ========================================================================
    // Prefix encoding
    // ========================================================================

    /// Encode VEX prefix (2-byte or 3-byte).
    fn encode_vex_prefix(&mut self, encoding: &InstrEncodingInfo, operands: &[X86Operand]) {
        use EncodingForm::*;
        let use_3byte = matches!(encoding.encoding_form, VEX3Byte);

        let mut rex_r = false;
        let mut rex_x = false;
        let mut rex_b = false;
        let mut rex_w = false;

        // Determine register extensions
        for (i, op) in operands.iter().enumerate() {
            if let X86Operand::Reg(reg) = op {
                if *reg >= 8 {
                    match i {
                        0 => rex_b = true, // destination (r/m field)
                        1 => rex_r = true, // source (reg field)
                        2 => rex_r = true, // second source
                        _ => {}
                    }
                }
                // REX.W for 64-bit GPR operands
                if self.mode.is_64bit() && (*reg == RAX || *reg >= R8) && *reg < 32 {
                    // Check for GPR64 usage
                    if self.is_gpr64_register(*reg) {
                        rex_w = true;
                    }
                }
            } else if let X86Operand::Mem(mem) = op {
                if mem.base >= 8 {
                    rex_b = true;
                }
                if mem.index >= 8 {
                    rex_x = true;
                }
            }
        }

        let vvvv = if operands.len() >= 2 {
            self.get_reg_field_for_operand(operands, 1)
        } else {
            0
        };

        let l = self.vector_length_from_operands(operands);
        let pp = encoding.mandatory_prefix;
        let mmmmm = encoding.opcode_map;

        if use_3byte || rex_x || rex_w {
            let bytes = vex_prefix::build_3byte(rex_r, rex_x, rex_b, mmmmm, rex_w, vvvv, l, pp);
            self.output.extend_from_slice(&bytes);
        } else {
            let bytes = vex_prefix::build_2byte(rex_r, vvvv, l, pp);
            self.output.extend_from_slice(&bytes);
        }
    }

    /// Encode EVEX prefix for AVX-512 instructions.
    fn encode_evex_prefix(&mut self, encoding: &InstrEncodingInfo, operands: &[X86Operand]) {
        let mut rex_r = false;
        let mut rex_x = false;
        let mut rex_b = false;
        let mut rex_w = false;
        let mut r_prime = false;

        for (i, op) in operands.iter().enumerate() {
            if let X86Operand::Reg(reg) = op {
                if *reg >= 16 {
                    r_prime = true;
                }
                if *reg >= 8 {
                    match i {
                        0 => rex_b = true,
                        1 => rex_r = true,
                        2 => rex_r = true,
                        _ => {}
                    }
                }
                if self.mode.is_64bit() && self.is_gpr64_register(*reg) {
                    rex_w = true;
                }
            } else if let X86Operand::Mem(mem) = op {
                if mem.base >= 8 {
                    rex_b = true;
                }
                if mem.index >= 16 {
                    rex_x = true;
                    r_prime = true;
                } else if mem.index >= 8 {
                    rex_x = true;
                }
            }
        }

        let vvvv = if operands.len() >= 2 {
            self.get_reg_field_for_operand(operands, 1)
        } else {
            0
        };

        let ll = self.vector_length_512(operands);
        let pp = encoding.mandatory_prefix;
        let mmmm = encoding.opcode_map & 0x07;

        let bytes = evex_prefix::build_evex(
            rex_r, rex_x, rex_b, r_prime, mmmm, rex_w, vvvv, pp,
            false, // zeroing mask (z) — not applied for reg forms
            ll, false, // b' broadcast
            0,     // aaa — no mask
        );
        self.output.extend_from_slice(&bytes);
    }

    /// Encode XOP prefix.
    fn encode_xop_prefix(&mut self, encoding: &InstrEncodingInfo, operands: &[X86Operand]) {
        let rex_r = false;
        let rex_x = false;
        let rex_b = false;
        let rex_w = false;
        let vvvv = if operands.len() >= 2 {
            self.get_reg_field_for_operand(operands, 1)
        } else {
            0
        };
        let l = false;
        let pp = encoding.mandatory_prefix;
        let mmmmm = encoding.opcode_map & 0x1F;

        let bytes = xop_prefix::build_xop(rex_r, rex_x, rex_b, mmmmm, rex_w, vvvv, l, pp);
        self.output.extend_from_slice(&bytes);
    }

    // ========================================================================
    // EVEX extended encoding: tuple types, broadcast, rounding, opmask
    // ========================================================================

    /// Full EVEX encoding with opmask, broadcast, rounding, and tuple type.
    fn encode_evex_full(
        &mut self,
        encoding: &InstrEncodingInfo,
        operands: &[X86Operand],
        opmask: Option<u8>, // k1-k7, None=no masking
        zeroing: bool,      // {z} zeroing merge mode
        broadcast: EvexBroadcast,
        rounding: EvexRounding,
        tuple: EvexTuple,
    ) {
        let mut rex_r = false;
        let mut rex_x = false;
        let mut rex_b = false;
        let mut rex_w = false;
        let mut r_prime = false;

        let kreg = opmask.unwrap_or(0) & 0x7; // opmask register k1-k7
        let z = zeroing && opmask.is_some();

        for (i, op) in operands.iter().enumerate() {
            if let X86Operand::Reg(reg) = op {
                if *reg >= 16 {
                    r_prime = true;
                }
                if *reg >= 8 {
                    match i {
                        0 => rex_b = true,
                        1 => rex_r = true,
                        2 => rex_r = true,
                        _ => {}
                    }
                }
                if self.mode.is_64bit() && self.is_gpr64_register(*reg) {
                    rex_w = true;
                }
            } else if let X86Operand::Mem(mem) = op {
                if mem.base >= 8 {
                    rex_b = true;
                }
                if mem.index >= 16 {
                    rex_x = true;
                    r_prime = true;
                } else if mem.index >= 8 {
                    rex_x = true;
                }
            }
        }

        let vvvv = if operands.len() >= 2 {
            self.get_reg_field_for_operand(operands, 1)
        } else {
            0
        };

        let mut ll = self.vector_length_512(operands);
        let b_prim = broadcast.is_broadcast();

        // Rounding mode overrides LL bits
        if rounding.is_active() {
            ll = rounding.rc_bits() & 0x3;
        }

        let pp = encoding.mandatory_prefix;
        let mmmm = encoding.opcode_map & 0x07;
        let aaa = kreg;

        let bytes = evex_prefix::build_evex(
            rex_r, rex_x, rex_b, r_prime, mmmm, rex_w, vvvv, pp, z, ll, b_prim, aaa,
        );
        self.output.extend_from_slice(&bytes);
    }

    /// Encode EVEX with mask and zeroing (most common AVX-512 case).
    pub fn encode_evex_masked(
        &mut self,
        opcode: X86FullOpcode,
        operands: &[X86Operand],
        opmask: Option<u8>,
        zeroing: bool,
    ) -> Vec<u8> {
        self.output.clear();

        let Some(encoding) = self.instr_info.get(opcode).cloned() else {
            self.output.push(0x0F);
            self.output.push(0x0B);
            return self.output.clone();
        };

        self.encode_evex_full(
            &encoding,
            operands,
            opmask,
            zeroing,
            EvexBroadcast::None,
            EvexRounding::None,
            EvexTuple::Full,
        );

        self.encode_opcode_bytes(&encoding);

        if encoding.requires_modrm {
            let modrm = self.compute_modrm(&encoding, operands);
            self.output.push(modrm);
        }

        if self.needs_sib(operands) {
            let sib = self.compute_sib(operands);
            self.output.push(sib);
        }

        self.encode_displacement(operands);
        self.encode_immediates(operands);

        self.output.clone()
    }

    /// Encode EVEX with broadcast memory operand.
    pub fn encode_evex_broadcast(
        &mut self,
        opcode: X86FullOpcode,
        operands: &[X86Operand],
        broadcast: EvexBroadcast,
        tuple: EvexTuple,
    ) -> Vec<u8> {
        self.output.clear();

        let Some(encoding) = self.instr_info.get(opcode).cloned() else {
            self.output.push(0x0F);
            self.output.push(0x0B);
            return self.output.clone();
        };

        self.encode_evex_full(
            &encoding,
            operands,
            None,
            false,
            broadcast,
            EvexRounding::None,
            tuple,
        );

        self.encode_opcode_bytes(&encoding);

        if encoding.requires_modrm {
            let modrm = self.compute_modrm(&encoding, operands);
            self.output.push(modrm);
        }

        if self.needs_sib(operands) {
            let sib = self.compute_sib(operands);
            self.output.push(sib);
        }

        // Compressed displacement for broadcast
        self.encode_evex_displacement(operands, tuple);
        self.encode_immediates(operands);

        self.output.clone()
    }

    /// Encode EVEX with rounding mode override.
    pub fn encode_evex_rounding(
        &mut self,
        opcode: X86FullOpcode,
        operands: &[X86Operand],
        rounding: EvexRounding,
    ) -> Vec<u8> {
        self.output.clear();

        let Some(encoding) = self.instr_info.get(opcode).cloned() else {
            self.output.push(0x0F);
            self.output.push(0x0B);
            return self.output.clone();
        };

        self.encode_evex_full(
            &encoding,
            operands,
            None,
            false,
            EvexBroadcast::None,
            rounding,
            EvexTuple::Full,
        );

        self.encode_opcode_bytes(&encoding);

        if encoding.requires_modrm {
            let modrm = self.compute_modrm(&encoding, operands);
            self.output.push(modrm);
        }

        if self.needs_sib(operands) {
            let sib = self.compute_sib(operands);
            self.output.push(sib);
        }

        self.encode_displacement(operands);
        self.encode_immediates(operands);

        self.output.clone()
    }

    /// Encode EVEX with compressed displacement (tuple type).
    fn encode_evex_displacement(&mut self, operands: &[X86Operand], tuple: EvexTuple) {
        let multiplier = tuple.multiplier();
        for op in operands {
            if let X86Operand::Mem(mem) = op {
                if mem.displacement != 0 {
                    let compressed = mem.displacement / multiplier as i32;
                    // Ensure compressed displacement fits in disp8
                    let disp = (compressed as i8) as u8;
                    self.output.push(disp);
                    return;
                }
            }
        }
    }

    // ========================================================================
    // XOP encoding convenience methods (AMD)
    // ========================================================================

    /// Raw XOP encode: emits XOP prefix + opcode + ModRM for two registers.
    fn encode_xop_raw(&mut self, mmmmm: u8, opcode: u8, dst: u16, src: u16) -> Vec<u8> {
        self.output.clear();

        // XOP prefix: 8F RXB.mmmmm W.vvvv.L.pp
        let rex_r = src >= 8;
        let rex_x = false;
        let rex_b = dst >= 8;
        let rex_w = false;
        let vvvv = 0; // No third source for 2-operand forms
        let l = false; // 128-bit
        let pp = 0; // No mandatory prefix

        let xop_prefix = xop_prefix::build_xop(rex_r, rex_x, rex_b, mmmmm, rex_w, vvvv, l, pp);
        self.output.extend_from_slice(&xop_prefix);

        // Opcode byte
        self.output.push(opcode);

        // ModR/M: mod=3 (reg), reg=src%8, rm=dst%8
        let modrm = 0xC0 | ((src & 0x7) << 3) | (dst & 0x7);
        self.output.push(modrm as u8);

        self.output.clone()
    }

    /// Raw XOP encode with immediate byte.
    fn encode_xop_raw_imm(
        &mut self,
        mmmmm: u8,
        opcode: u8,
        dst: u16,
        src: u16,
        imm: u8,
    ) -> Vec<u8> {
        let mut bytes = self.encode_xop_raw(mmmmm, opcode, dst, src);
        bytes.push(imm);
        bytes
    }

    /// Encode VPHADDBD (XOP: map 8, opcode C2).
    pub fn encode_vphaddbd(&mut self, dst: u16, src: u16) -> Vec<u8> {
        self.encode_xop_raw(8, 0xC2, dst, src)
    }

    /// Encode VPHADDBQ (XOP: map 8, opcode C3).
    pub fn encode_vphaddbq(&mut self, dst: u16, src: u16) -> Vec<u8> {
        self.encode_xop_raw(8, 0xC3, dst, src)
    }

    /// Encode VPHADDWD (XOP: map 8, opcode C6).
    pub fn encode_vphaddwd(&mut self, dst: u16, src: u16) -> Vec<u8> {
        self.encode_xop_raw(8, 0xC6, dst, src)
    }

    /// Encode VPHADDWQ (XOP: map 8, opcode C7).
    pub fn encode_vphaddwq(&mut self, dst: u16, src: u16) -> Vec<u8> {
        self.encode_xop_raw(8, 0xC7, dst, src)
    }

    /// Encode VPHADDDQ (XOP: map 8, opcode CB).
    pub fn encode_vphadddq(&mut self, dst: u16, src: u16) -> Vec<u8> {
        self.encode_xop_raw(8, 0xCB, dst, src)
    }

    /// Encode VPROTB (XOP: map 8, opcode 90).
    pub fn encode_vprotb(&mut self, dst: u16, src: u16) -> Vec<u8> {
        self.encode_xop_raw(8, 0x90, dst, src)
    }

    /// Encode VPROTW (XOP: map 8, opcode 91).
    pub fn encode_vprotw(&mut self, dst: u16, src: u16) -> Vec<u8> {
        self.encode_xop_raw(8, 0x91, dst, src)
    }

    /// Encode VPROTD (XOP: map 8, opcode 92).
    pub fn encode_vprotd(&mut self, dst: u16, src: u16) -> Vec<u8> {
        self.encode_xop_raw(8, 0x92, dst, src)
    }

    /// Encode VPROTQ (XOP: map 8, opcode 93).
    pub fn encode_vprotq(&mut self, dst: u16, src: u16) -> Vec<u8> {
        self.encode_xop_raw(8, 0x93, dst, src)
    }

    /// Encode VPSHAB (XOP: map 9, opcode 98).
    pub fn encode_vpshab(&mut self, dst: u16, src: u16) -> Vec<u8> {
        self.encode_xop_raw(9, 0x98, dst, src)
    }

    /// Encode VPSHAW (XOP: map 9, opcode 99).
    pub fn encode_vpshaw(&mut self, dst: u16, src: u16) -> Vec<u8> {
        self.encode_xop_raw(9, 0x99, dst, src)
    }

    /// Encode VPSHAD (XOP: map 9, opcode 9A).
    pub fn encode_vpshad(&mut self, dst: u16, src: u16) -> Vec<u8> {
        self.encode_xop_raw(9, 0x9A, dst, src)
    }

    /// Encode VPSHAQ (XOP: map 9, opcode 9B).
    pub fn encode_vpshaq(&mut self, dst: u16, src: u16) -> Vec<u8> {
        self.encode_xop_raw(9, 0x9B, dst, src)
    }

    /// Encode VPSHLB (XOP: map 9, opcode 94).
    pub fn encode_vpshlb(&mut self, dst: u16, src: u16) -> Vec<u8> {
        self.encode_xop_raw(9, 0x94, dst, src)
    }

    /// Encode VPSHLW (XOP: map 9, opcode 95).
    pub fn encode_vpshlw(&mut self, dst: u16, src: u16) -> Vec<u8> {
        self.encode_xop_raw(9, 0x95, dst, src)
    }

    /// Encode VPSHLD (XOP: map 9, opcode 96).
    pub fn encode_vpshld(&mut self, dst: u16, src: u16) -> Vec<u8> {
        self.encode_xop_raw(9, 0x96, dst, src)
    }

    /// Encode VPSHLQ (XOP: map 9, opcode 97).
    pub fn encode_vpshlq(&mut self, dst: u16, src: u16) -> Vec<u8> {
        self.encode_xop_raw(9, 0x97, dst, src)
    }

    /// Encode legacy prefixes (REX, operand-size override, address-size override).
    fn encode_legacy_prefixes(&mut self, encoding: &InstrEncodingInfo, operands: &[X86Operand]) {
        let mut rex = false;
        let mut rex_w = false;
        let mut rex_r = false;
        let mut rex_x = false;
        let mut rex_b = false;

        // Check if any operand requires REX
        if self.mode.is_64bit() {
            for (i, op) in operands.iter().enumerate() {
                match op {
                    X86Operand::Reg(reg) => {
                        if *reg >= 8 {
                            match i {
                                0 => rex_b = true,
                                _ => rex_r = true,
                            }
                            rex = true;
                        }
                        if self.is_gpr64_register(*reg) {
                            rex_w = true;
                            rex = true;
                        }
                    }
                    X86Operand::Mem(mem) => {
                        if mem.base >= 8 {
                            rex_b = true;
                            rex = true;
                        }
                        if mem.index >= 8 {
                            rex_x = true;
                            rex = true;
                        }
                    }
                    _ => {}
                }
            }
        }

        // LegacyREX forms always need REX in 64-bit mode
        if matches!(encoding.encoding_form, EncodingForm::LegacyREX) && self.mode.is_64bit() {
            rex = true;
            // For CMOV, SETcc, etc. — ensure W is set for 64-bit forms
        }

        if rex {
            let rex_byte = rex_prefix::REX_BASE
                | (if rex_w { 0x08 } else { 0 })
                | (if rex_r { 0x04 } else { 0 })
                | (if rex_x { 0x02 } else { 0 })
                | (if rex_b { 0x01 } else { 0 });
            self.output.push(rex_byte);
        }

        // Emit mandatory prefix for SSE instructions (66, F3, F2)
        if encoding.mandatory_prefix != 0 && encoding.encoding_form == EncodingForm::Legacy {
            let prefix_byte = match encoding.mandatory_prefix {
                1 => prefixes::OPERAND_SIZE_OVERRIDE, // 0x66
                2 => prefixes::REP,                   // 0xF3
                3 => prefixes::REPNE,                 // 0xF2
                _ => 0,
            };
            if prefix_byte != 0 {
                self.output.push(prefix_byte);
            }
        }
    }

    // ========================================================================
    // Opcode byte encoding
    // ========================================================================

    /// Emit the opcode byte(s) for the instruction.
    fn encode_opcode_bytes(&mut self, encoding: &InstrEncodingInfo) {
        match encoding.opcode_map {
            0 => {
                // 1-byte opcode — just emit the byte
                self.output.push(encoding.base_opcode);
            }
            1 => {
                // 2-byte opcode — 0x0F escape + opcode
                self.output.push(0x0F);
                self.output.push(encoding.base_opcode);
            }
            2 => {
                // 3-byte opcode — 0x0F 0x38 escape + opcode
                self.output.push(0x0F);
                self.output.push(0x38);
                self.output.push(encoding.base_opcode);
            }
            3 => {
                // 3-byte opcode — 0x0F 0x3A escape + opcode
                self.output.push(0x0F);
                self.output.push(0x3A);
                self.output.push(encoding.base_opcode);
            }
            _ => {
                // Fallback for VEX/EVEX/XOP — the opcode byte is emitted after the prefix
                self.output.push(encoding.base_opcode);
            }
        }
    }

    // ========================================================================
    // ModR/M computation
    // ========================================================================

    /// Compute the ModR/M byte for the given instruction and operands.
    fn compute_modrm(&self, encoding: &InstrEncodingInfo, operands: &[X86Operand]) -> u8 {
        let mut mod_field_val: u8 = mod_field::REG_DIRECT;
        let mut reg_opcode: u8 = encoding.modrm_extension;
        let mut rm_val: u8 = 0;

        // Determine which operand goes to reg field (typically src) and which to r/m field (dst)
        // For most instructions: reg = src, r/m = dst
        // For store instructions: reg = src, r/m = mem
        // For immediate forms: r/m = dst, reg = opcode extension

        let dst_idx = 0usize;
        let src_idx = if operands.len() >= 2 { 1 } else { 0 };

        // Check if any operand is memory
        let has_mem = operands.iter().any(|op| matches!(op, X86Operand::Mem(_)));

        if has_mem {
            // Find the memory operand
            for (i, op) in operands.iter().enumerate() {
                if let X86Operand::Mem(mem) = op {
                    rm_val = self.get_rm_reg_field(mem.base);
                    mod_field_val = self.compute_mem_mod_field(mem);
                    break;
                }
            }
            // The register operand goes to the reg field
            for (i, op) in operands.iter().enumerate() {
                if let X86Operand::Reg(reg) = op {
                    if i != 0 || !has_mem {
                        if reg_opcode == 255 {
                            reg_opcode = self.get_reg_field(*reg) & 0x7;
                        }
                    }
                    break;
                }
            }
        } else if operands.len() >= 2 {
            // Register-register encoding
            if let X86Operand::Reg(dst) = &operands[dst_idx] {
                rm_val = self.get_reg_field(*dst) & 0x7;
            }
            if let X86Operand::Reg(src) = &operands[src_idx] {
                if reg_opcode == 255 {
                    reg_opcode = self.get_reg_field(*src) & 0x7;
                }
            }
        } else if operands.len() == 1 {
            if let X86Operand::Reg(reg) = &operands[0] {
                rm_val = self.get_reg_field(*reg) & 0x7;
            }
        }

        (mod_field_val << 6) | ((reg_opcode & 0x7) << 3) | (rm_val & 0x7)
    }

    /// Compute the Mod field for a memory operand.
    fn compute_mem_mod_field(&self, mem: &X86MemOperand) -> u8 {
        if mem.base == 0 && mem.index == 0 {
            // Absolute address — mod=0, rm=5
            mod_field::MEM_NO_DISP
        } else if mem.displacement == 0
            && mem.base != RBP
            && mem.base != R13
            && !mem.is_rip_relative()
        {
            mod_field::MEM_NO_DISP
        } else if mem.displacement >= -128 && mem.displacement <= 127 {
            mod_field::MEM_DISP8
        } else {
            mod_field::MEM_DISP32
        }
    }

    /// Get the r/m field value for a register.
    fn get_rm_reg_field(&self, reg: u16) -> u8 {
        self.get_reg_field(reg) & 0x7
    }

    // ========================================================================
    // SIB computation
    // ========================================================================

    /// Determine if a SIB byte is needed.
    fn needs_sib(&self, operands: &[X86Operand]) -> bool {
        for op in operands {
            if let X86Operand::Mem(mem) = op {
                if mem.index != 0 {
                    return true;
                }
                if mem.base == RSP || mem.base == R12 || mem.base == ESP {
                    return true;
                }
                // RBP without displacement requires SIB with disp32=0
                if mem.base == RBP || mem.base == R13 {
                    return true;
                }
                // RIP-relative needs SIB? No — RIP-relative uses ModR/M mod=0, rm=5
            }
        }
        false
    }

    /// Compute the SIB byte.
    fn compute_sib(&self, operands: &[X86Operand]) -> u8 {
        for op in operands {
            if let X86Operand::Mem(mem) = op {
                let scale_bits = match mem.scale {
                    2 => sib_byte::SCALE_2,
                    4 => sib_byte::SCALE_4,
                    8 => sib_byte::SCALE_8,
                    _ => sib_byte::SCALE_1,
                };

                let index_field = if mem.index == 0 {
                    sib_byte::NO_INDEX
                } else {
                    self.get_reg_field(mem.index) & 0x7
                };

                let base_field = if mem.base == 0 {
                    5 // disp32 with no base
                } else {
                    self.get_reg_field(mem.base) & 0x7
                };

                return sib_byte::build(scale_bits, index_field, base_field);
            }
        }
        0
    }

    // ========================================================================
    // Displacement encoding
    // ========================================================================

    /// Encode displacement for memory operands.
    fn encode_displacement(&mut self, operands: &[X86Operand]) {
        for op in operands {
            if let X86Operand::Mem(mem) = op {
                if mem.is_rip_relative() {
                    // Always use 32-bit displacement for RIP-relative
                    self.output
                        .extend_from_slice(&mem.displacement.to_le_bytes());
                    return;
                }

                if mem.displacement == 0 && mem.base != RBP && mem.base != R13 {
                    // No displacement needed
                    return;
                }

                if mem.displacement >= -128 && mem.displacement <= 127 {
                    self.output.push(mem.displacement as u8);
                } else {
                    self.output
                        .extend_from_slice(&mem.displacement.to_le_bytes());
                }
                return;
            }
        }
    }

    // ========================================================================
    // Immediate encoding
    // ========================================================================

    /// Encode immediate operand(s).
    fn encode_immediates(&mut self, operands: &[X86Operand]) {
        for op in operands {
            if let X86Operand::Imm(val) = op {
                // Determine immediate size from operand context
                let abs_val = val.unsigned_abs();
                if abs_val <= 0xFF && (*val as i8 as i64) == *val {
                    // Fits in signed 8-bit
                    self.output.push(*val as u8);
                } else if abs_val <= 0xFFFF_FFFF {
                    self.output.extend_from_slice(&(*val as i32).to_le_bytes());
                } else {
                    self.output.extend_from_slice(&val.to_le_bytes());
                }
                return; // Only one immediate for now
            }
        }
    }

    // ========================================================================
    // Register field helpers
    // ========================================================================

    /// Get the 3-bit register field (low 3 bits) for ModR/M and SIB.
    /// Extended bits (bit 3) are handled by REX/VEX.
    pub fn get_reg_field(&self, reg_id: u16) -> u8 {
        match reg_id {
            // 64-bit GPRs
            RAX..=R15 => (reg_id % 16) as u8,
            // 32-bit GPRs
            EAX..=R15D => (reg_id % 16) as u8,
            // 16-bit GPRs
            AX..=R15W => (reg_id % 16) as u8,
            // 8-bit GPRs
            AL..=R15B => {
                let base = reg_id % 16;
                if base >= 4 && reg_id != SPL && reg_id != BPL && reg_id != SIL && reg_id != DIL {
                    // AH, CH, DH, BH have special mapping
                    match reg_id {
                        4 => 4, // AH/SPL
                        5 => 5, // CH/BPL
                        6 => 6, // DH/SIL
                        7 => 7, // BH/DIL
                        _ => (reg_id % 8) as u8,
                    }
                } else {
                    base as u8
                }
            }
            // XMM
            XMM0..=XMM15 => (reg_id % 16) as u8,
            // YMM
            YMM0..=YMM15 => (reg_id % 16) as u8,
            // ZMM
            ZMM0..=ZMM15 => (reg_id % 16) as u8,
            // K registers
            K0..=K7 => (reg_id % 8) as u8,
            _ => 0,
        }
    }

    /// Get the reg field for a specific operand position.
    fn get_reg_field_for_operand(&self, operands: &[X86Operand], idx: usize) -> u8 {
        if idx < operands.len() {
            if let X86Operand::Reg(reg) = &operands[idx] {
                return self.get_reg_field(*reg);
            }
        }
        0
    }

    /// Check if a register ID is a 64-bit GPR.
    fn is_gpr64_register(&self, reg: u16) -> bool {
        (RAX..=R15).contains(&reg)
    }

    /// Determine vector length flag from operands.
    fn vector_length_from_operands(&self, operands: &[X86Operand]) -> bool {
        for op in operands {
            if let X86Operand::Reg(reg) = op {
                if (YMM0..=YMM15).contains(reg) {
                    return true; // 256-bit
                }
            }
        }
        false // 128-bit default
    }

    /// Determine vector length for AVX-512 (2-bit LL field).
    fn vector_length_512(&self, operands: &[X86Operand]) -> u8 {
        for op in operands {
            if let X86Operand::Reg(reg) = op {
                if (ZMM0..=ZMM31).contains(reg) {
                    return 2; // 512-bit
                }
                if (YMM0..=YMM31).contains(reg) {
                    return 1; // 256-bit
                }
            }
        }
        0 // 128-bit
    }

    // ========================================================================
    // Convenience encoding aliases
    // ========================================================================

    /// Create a NOP instruction.
    pub fn encode_nop(&mut self) -> Vec<u8> {
        self.output.clear();
        self.output.push(0x90);
        self.output.clone()
    }

    /// Create a 3-byte NOP.
    pub fn encode_nop3(&mut self) -> Vec<u8> {
        self.output.clear();
        self.output.push(0x0F);
        self.output.push(0x1F);
        self.output.push(0x00);
        self.output.clone()
    }

    /// Encode a direct call.
    pub fn encode_call(&mut self, target_offset: i32) -> Vec<u8> {
        self.output.clear();
        self.output.push(0xE8);
        self.output.extend_from_slice(&target_offset.to_le_bytes());
        self.output.clone()
    }

    /// Encode a simple register-to-register MOV.
    pub fn encode_mov_rr(&mut self, dst: u16, src: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::MOVrr,
            &[X86Operand::Reg(dst), X86Operand::Reg(src)],
        )
    }

    /// Encode ADD reg, reg.
    pub fn encode_add_rr(&mut self, dst: u16, src: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::ADD,
            &[X86Operand::Reg(dst), X86Operand::Reg(src)],
        )
    }

    /// Encode ADD reg, imm.
    pub fn encode_add_ri(&mut self, dst: u16, imm: i64) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::ADD,
            &[X86Operand::Reg(dst), X86Operand::Imm(imm)],
        )
    }

    /// Encode SUB reg, reg.
    pub fn encode_sub_rr(&mut self, dst: u16, src: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::SUB,
            &[X86Operand::Reg(dst), X86Operand::Reg(src)],
        )
    }

    /// Encode AND reg, reg.
    pub fn encode_and_rr(&mut self, dst: u16, src: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::AND,
            &[X86Operand::Reg(dst), X86Operand::Reg(src)],
        )
    }

    /// Encode OR reg, reg.
    pub fn encode_or_rr(&mut self, dst: u16, src: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::OR,
            &[X86Operand::Reg(dst), X86Operand::Reg(src)],
        )
    }

    /// Encode XOR reg, reg.
    pub fn encode_xor_rr(&mut self, dst: u16, src: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::XOR,
            &[X86Operand::Reg(dst), X86Operand::Reg(src)],
        )
    }

    /// Encode CMP reg, reg.
    pub fn encode_cmp_rr(&mut self, dst: u16, src: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::CMP,
            &[X86Operand::Reg(dst), X86Operand::Reg(src)],
        )
    }

    /// Encode RET.
    pub fn encode_ret(&mut self) -> Vec<u8> {
        self.encode_instruction(X86FullOpcode::RET, &[])
    }

    /// Encode a MOV with a memory destination.
    pub fn encode_mov_mr(&mut self, mem: X86MemOperand, src: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::MOVmr,
            &[X86Operand::Mem(mem), X86Operand::Reg(src)],
        )
    }

    /// Encode a MOV with a memory source.
    pub fn encode_mov_rm(&mut self, dst: u16, mem: X86MemOperand) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::MOVrm,
            &[X86Operand::Reg(dst), X86Operand::Mem(mem)],
        )
    }

    /// Encode VADDPS (3-operand AVX).
    pub fn encode_vaddps(&mut self, dst: u16, src1: u16, src2: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::VADDPS,
            &[
                X86Operand::Reg(dst),
                X86Operand::Reg(src1),
                X86Operand::Reg(src2),
            ],
        )
    }

    /// Encode AESENC.
    pub fn encode_aesenc(&mut self, dst: u16, src: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::AESENC,
            &[X86Operand::Reg(dst), X86Operand::Reg(src)],
        )
    }

    /// Encode SHA256RNDS2.
    pub fn encode_sha256rnds2(&mut self, dst: u16, src1: u16, src2: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::SHA256RNDS2,
            &[
                X86Operand::Reg(dst),
                X86Operand::Reg(src1),
                X86Operand::Reg(src2),
            ],
        )
    }

    // ========================================================================
    // VSIB addressing (for gather/scatter instructions)
    // ========================================================================

    /// Encode a VGATHERDD instruction with VSIB addressing.
    ///
    /// VSIB (Vector SIB) allows using XMM/YMM/ZMM registers as indices
    /// in gather/scatter operations. The SIB byte is constructed similarly
    /// to regular SIB but the index field references a vector register.
    pub fn encode_vgatherdd_vsib(&mut self, dst: u16, vsib_mem: X86MemOperand) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::VPGATHERDD,
            &[X86Operand::Reg(dst), X86Operand::Mem(vsib_mem)],
        )
    }

    /// Encode a VPGATHERDQ with VSIB.
    pub fn encode_vgatherdq_vsib(&mut self, dst: u16, vsib_mem: X86MemOperand) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::VPGATHERDQ,
            &[X86Operand::Reg(dst), X86Operand::Mem(vsib_mem)],
        )
    }
    // === AVX-512 VP2INTERSECT encoding ===
    pub fn encode_vp2intersectd(&mut self, k: u16, s1: u16, s2: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::VP2INTERSECTD,
            &[X86Operand::Reg(k), X86Operand::Reg(s1), X86Operand::Reg(s2)],
        )
    }
    pub fn encode_vp2intersectq(&mut self, k: u16, s1: u16, s2: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::VP2INTERSECTQ,
            &[X86Operand::Reg(k), X86Operand::Reg(s1), X86Operand::Reg(s2)],
        )
    }
    // === AVX-512 FP16 encoding ===
    pub fn encode_vaddph(&mut self, d: u16, s1: u16, s2: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::VADDPH,
            &[X86Operand::Reg(d), X86Operand::Reg(s1), X86Operand::Reg(s2)],
        )
    }
    pub fn encode_vmulph(&mut self, d: u16, s1: u16, s2: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::VMULPH,
            &[X86Operand::Reg(d), X86Operand::Reg(s1), X86Operand::Reg(s2)],
        )
    }
    pub fn encode_vdivph(&mut self, d: u16, s1: u16, s2: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::VDIVPH,
            &[X86Operand::Reg(d), X86Operand::Reg(s1), X86Operand::Reg(s2)],
        )
    }
    pub fn encode_vsubph(&mut self, d: u16, s1: u16, s2: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::VSUBPH,
            &[X86Operand::Reg(d), X86Operand::Reg(s1), X86Operand::Reg(s2)],
        )
    }
    // === AVX-512 BF16 encoding ===
    pub fn encode_vcvtne2ps2bf16(&mut self, d: u16, s1: u16, s2: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::VCVTNE2PS2BF16,
            &[X86Operand::Reg(d), X86Operand::Reg(s1), X86Operand::Reg(s2)],
        )
    }
    pub fn encode_vdpbf16ps(&mut self, d: u16, s1: u16, s2: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::VDPBF16PS,
            &[X86Operand::Reg(d), X86Operand::Reg(s1), X86Operand::Reg(s2)],
        )
    }
    // === AMX tile config encoding ===
    pub fn encode_ldtilecfg(&mut self, mem: X86MemOperand) -> Vec<u8> {
        self.encode_instruction(X86FullOpcode::LDTILECFG, &[X86Operand::Mem(mem)])
    }
    pub fn encode_sttilecfg(&mut self, mem: X86MemOperand) -> Vec<u8> {
        self.encode_instruction(X86FullOpcode::STTILECFG, &[X86Operand::Mem(mem)])
    }
    pub fn encode_tilerelease(&mut self) -> Vec<u8> {
        self.encode_instruction(X86FullOpcode::TILERELEASE, &[])
    }
    pub fn encode_tilezero(&mut self, t: u16) -> Vec<u8> {
        self.encode_instruction(X86FullOpcode::TILEZERO, &[X86Operand::Reg(t)])
    }
    // === AMX tile data encoding ===
    pub fn encode_tileloadd(&mut self, t: u16, mem: X86MemOperand) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::TILELOADD,
            &[X86Operand::Reg(t), X86Operand::Mem(mem)],
        )
    }
    pub fn encode_tilestored(&mut self, mem: X86MemOperand, t: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::TILESTORED,
            &[X86Operand::Mem(mem), X86Operand::Reg(t)],
        )
    }
    // === AMX compute encoding ===
    pub fn encode_tdpbssd(&mut self, td: u16, ts1: u16, ts2: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::TDPBSSD,
            &[
                X86Operand::Reg(td),
                X86Operand::Reg(ts1),
                X86Operand::Reg(ts2),
            ],
        )
    }
    pub fn encode_tdpbsud(&mut self, td: u16, ts1: u16, ts2: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::TDPBSUD,
            &[
                X86Operand::Reg(td),
                X86Operand::Reg(ts1),
                X86Operand::Reg(ts2),
            ],
        )
    }
    pub fn encode_tdpbusd(&mut self, td: u16, ts1: u16, ts2: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::TDPBUSD,
            &[
                X86Operand::Reg(td),
                X86Operand::Reg(ts1),
                X86Operand::Reg(ts2),
            ],
        )
    }
    pub fn encode_tdpbuud(&mut self, td: u16, ts1: u16, ts2: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::TDPBUUD,
            &[
                X86Operand::Reg(td),
                X86Operand::Reg(ts1),
                X86Operand::Reg(ts2),
            ],
        )
    }
    pub fn encode_tdpbf16ps(&mut self, td: u16, ts1: u16, ts2: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::TDPBF16PS,
            &[
                X86Operand::Reg(td),
                X86Operand::Reg(ts1),
                X86Operand::Reg(ts2),
            ],
        )
    }
    pub fn encode_tdpfp16ps(&mut self, td: u16, ts1: u16, ts2: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::TDPFP16PS,
            &[
                X86Operand::Reg(td),
                X86Operand::Reg(ts1),
                X86Operand::Reg(ts2),
            ],
        )
    }
    // === KEYLOCKER encoding ===
    pub fn encode_loadiwkey(&mut self, s1: u16, s2: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::LOADIWKEY,
            &[X86Operand::Reg(s1), X86Operand::Reg(s2)],
        )
    }
    pub fn encode_aesenc128kl(&mut self, d: u16, s: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::AESENC128KL,
            &[X86Operand::Reg(d), X86Operand::Reg(s)],
        )
    }
    pub fn encode_aesdec128kl(&mut self, d: u16, s: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::AESDEC128KL,
            &[X86Operand::Reg(d), X86Operand::Reg(s)],
        )
    }
    pub fn encode_encodekey128(&mut self, d: u16, s: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::ENCODEKEY128,
            &[X86Operand::Reg(d), X86Operand::Reg(s)],
        )
    }
    // === HRESET, UINTR, FRED encoding ===
    pub fn encode_hreset(&mut self, imm: u8) -> Vec<u8> {
        self.encode_instruction(X86FullOpcode::HRESET, &[X86Operand::Imm(imm as i64)])
    }
    pub fn encode_senduip(&mut self, r: u16) -> Vec<u8> {
        self.encode_instruction(X86FullOpcode::SENDUIP, &[X86Operand::Reg(r)])
    }
    pub fn encode_uiret(&mut self) -> Vec<u8> {
        self.encode_instruction(X86FullOpcode::UIRET, &[])
    }
    pub fn encode_erets(&mut self) -> Vec<u8> {
        self.encode_instruction(X86FullOpcode::ERETS, &[])
    }
    pub fn encode_eretu(&mut self) -> Vec<u8> {
        self.encode_instruction(X86FullOpcode::ERETU, &[])
    }
    pub fn encode_lkgs(&mut self, r: u16) -> Vec<u8> {
        self.encode_instruction(X86FullOpcode::LKGS, &[X86Operand::Reg(r)])
    }
    // === CMPCCXADD, RAO-INT, WRMSRNS encoding ===
    pub fn encode_cmpccxadd(&mut self, mem: X86MemOperand, r: u16, cc: u8) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::CMPCCXADD,
            &[
                X86Operand::Mem(mem),
                X86Operand::Reg(r),
                X86Operand::Imm(cc as i64),
            ],
        )
    }
    pub fn encode_aadd(&mut self, mem: X86MemOperand, r: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::AADD,
            &[X86Operand::Mem(mem), X86Operand::Reg(r)],
        )
    }
    pub fn encode_aand(&mut self, mem: X86MemOperand, r: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::AAND,
            &[X86Operand::Mem(mem), X86Operand::Reg(r)],
        )
    }
    pub fn encode_aor(&mut self, mem: X86MemOperand, r: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::AOR,
            &[X86Operand::Mem(mem), X86Operand::Reg(r)],
        )
    }
    pub fn encode_axor(&mut self, mem: X86MemOperand, r: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::AXOR,
            &[X86Operand::Mem(mem), X86Operand::Reg(r)],
        )
    }
    pub fn encode_wrmsrns(&mut self) -> Vec<u8> {
        self.encode_instruction(X86FullOpcode::WRMSRNS, &[])
    }

    // ========================================================================
    // F16C: Half Precision Conversion
    // ========================================================================
    pub fn encode_vcvtph2ps(&mut self, d: u16, s: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::VCVTPH2PS,
            &[X86Operand::Reg(d), X86Operand::Reg(s)],
        )
    }
    pub fn encode_vcvtps2ph(&mut self, d: u16, s: u16, imm: u8) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::VCVTPS2PH,
            &[
                X86Operand::Reg(d),
                X86Operand::Reg(s),
                X86Operand::Imm(imm as i64),
            ],
        )
    }

    // ========================================================================
    // RDRAND / RDSEED
    // ========================================================================
    pub fn encode_rdrand16(&mut self, d: u16) -> Vec<u8> {
        self.encode_instruction(X86FullOpcode::RDRAND, &[X86Operand::Reg(d)])
    }
    pub fn encode_rdrand32(&mut self, d: u16) -> Vec<u8> {
        self.encode_instruction(X86FullOpcode::RDRAND, &[X86Operand::Reg(d)])
    }
    pub fn encode_rdrand64(&mut self, d: u16) -> Vec<u8> {
        self.encode_instruction(X86FullOpcode::RDRAND, &[X86Operand::Reg(d)])
    }
    pub fn encode_rdseed16(&mut self, d: u16) -> Vec<u8> {
        self.encode_instruction(X86FullOpcode::RDSEED, &[X86Operand::Reg(d)])
    }
    pub fn encode_rdseed32(&mut self, d: u16) -> Vec<u8> {
        self.encode_instruction(X86FullOpcode::RDSEED, &[X86Operand::Reg(d)])
    }
    pub fn encode_rdseed64(&mut self, d: u16) -> Vec<u8> {
        self.encode_instruction(X86FullOpcode::RDSEED, &[X86Operand::Reg(d)])
    }

    // ========================================================================
    // AES-NI: Advanced Encryption Standard
    // ========================================================================
    pub fn encode_aesenclast(&mut self, d: u16, s: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::AESENCLAST,
            &[X86Operand::Reg(d), X86Operand::Reg(s)],
        )
    }
    pub fn encode_aesdec(&mut self, d: u16, s: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::AESDEC,
            &[X86Operand::Reg(d), X86Operand::Reg(s)],
        )
    }
    pub fn encode_aesdeclast(&mut self, d: u16, s: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::AESDECLAST,
            &[X86Operand::Reg(d), X86Operand::Reg(s)],
        )
    }
    pub fn encode_aesimc(&mut self, d: u16, s: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::AESIMC,
            &[X86Operand::Reg(d), X86Operand::Reg(s)],
        )
    }
    pub fn encode_aeskeygenassist(&mut self, d: u16, s: u16, imm: u8) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::AESKEYGENASSIST,
            &[
                X86Operand::Reg(d),
                X86Operand::Reg(s),
                X86Operand::Imm(imm as i64),
            ],
        )
    }

    // ========================================================================
    // SHA Extensions
    // ========================================================================
    pub fn encode_sha1rnds4(&mut self, d: u16, s: u16, imm: u8) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::SHA1RNDS4,
            &[
                X86Operand::Reg(d),
                X86Operand::Reg(s),
                X86Operand::Imm(imm as i64),
            ],
        )
    }
    pub fn encode_sha1nexte(&mut self, d: u16, s: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::SHA1NEXTE,
            &[X86Operand::Reg(d), X86Operand::Reg(s)],
        )
    }
    pub fn encode_sha1msg1(&mut self, d: u16, s: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::SHA1MSG1,
            &[X86Operand::Reg(d), X86Operand::Reg(s)],
        )
    }
    pub fn encode_sha1msg2(&mut self, d: u16, s: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::SHA1MSG2,
            &[X86Operand::Reg(d), X86Operand::Reg(s)],
        )
    }
    pub fn encode_sha256msg1(&mut self, d: u16, s: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::SHA256MSG1,
            &[X86Operand::Reg(d), X86Operand::Reg(s)],
        )
    }
    pub fn encode_sha256msg2(&mut self, d: u16, s: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::SHA256MSG2,
            &[X86Operand::Reg(d), X86Operand::Reg(s)],
        )
    }

    // ========================================================================
    // GFNI: Galois Field New Instructions (VEX-encoded via Z variants)
    // ========================================================================
    pub fn encode_vgf2p8affineqb(&mut self, d: u16, s1: u16, s2: u16, imm: u8) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::VGF2P8AFFINEQB_Z,
            &[
                X86Operand::Reg(d),
                X86Operand::Reg(s1),
                X86Operand::Reg(s2),
                X86Operand::Imm(imm as i64),
            ],
        )
    }
    pub fn encode_vgf2p8affineinvqb(&mut self, d: u16, s1: u16, s2: u16, imm: u8) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::VGF2P8AFFINEINVQB_Z,
            &[
                X86Operand::Reg(d),
                X86Operand::Reg(s1),
                X86Operand::Reg(s2),
                X86Operand::Imm(imm as i64),
            ],
        )
    }
    pub fn encode_vgf2p8mulb(&mut self, d: u16, s1: u16, s2: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::VGF2P8MULB_Z,
            &[X86Operand::Reg(d), X86Operand::Reg(s1), X86Operand::Reg(s2)],
        )
    }

    // ========================================================================
    // VAES: Vector AES (via Z variants)
    // ========================================================================
    pub fn encode_vaesenc(&mut self, d: u16, s1: u16, s2: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::VAESENC_Z,
            &[X86Operand::Reg(d), X86Operand::Reg(s1), X86Operand::Reg(s2)],
        )
    }
    pub fn encode_vaesenclast(&mut self, d: u16, s1: u16, s2: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::VAESENCLAST_Z,
            &[X86Operand::Reg(d), X86Operand::Reg(s1), X86Operand::Reg(s2)],
        )
    }
    pub fn encode_vaesdec(&mut self, d: u16, s1: u16, s2: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::VAESDEC_Z,
            &[X86Operand::Reg(d), X86Operand::Reg(s1), X86Operand::Reg(s2)],
        )
    }
    pub fn encode_vaesdeclast(&mut self, d: u16, s1: u16, s2: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::VAESDECLAST_Z,
            &[X86Operand::Reg(d), X86Operand::Reg(s1), X86Operand::Reg(s2)],
        )
    }

    // ========================================================================
    // VPCLMULQDQ: Vector PCLMULQDQ (via Z variant)
    // ========================================================================
    pub fn encode_vpclmulqdq(&mut self, d: u16, s1: u16, s2: u16, imm: u8) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::VPCLMULQDQ_Z,
            &[
                X86Operand::Reg(d),
                X86Operand::Reg(s1),
                X86Operand::Reg(s2),
                X86Operand::Imm(imm as i64),
            ],
        )
    }

    // ========================================================================
    // AVX-VNNI: Vector Neural Network Instructions
    // ========================================================================
    pub fn encode_vpdpbusd(&mut self, d: u16, s1: u16, s2: u16) -> Vec<u8> {
        let mut bytes = Vec::new();
        // VEX.128.66.0F38.W0 50 /r: VPDPBUSD xmm1, xmm2, xmm3/m128
        bytes.push(0xC4);
        bytes.push(0xE2);
        bytes.push(0x79);
        bytes.push(0x50);
        let modrm: u8 = (0xC0 | ((d & 7) << 3) | (s2 & 7)) as u8;
        bytes.push(modrm);
        bytes
    }
    pub fn encode_vpdpbusds(&mut self, d: u16, s1: u16, s2: u16) -> Vec<u8> {
        let mut bytes = Vec::new();
        // VEX.128.66.0F38.W0 51 /r: VPDPBUSDS xmm1, xmm2, xmm3/m128
        bytes.push(0xC4);
        bytes.push(0xE2);
        bytes.push(0x79);
        bytes.push(0x51);
        let modrm: u8 = (0xC0 | ((d & 7) << 3) | (s2 & 7)) as u8;
        bytes.push(modrm);
        bytes
    }
    pub fn encode_vpdpwssd(&mut self, d: u16, s1: u16, s2: u16) -> Vec<u8> {
        let mut bytes = Vec::new();
        // VEX.128.66.0F38.W0 52 /r: VPDPWSSD xmm1, xmm2, xmm3/m128
        bytes.push(0xC4);
        bytes.push(0xE2);
        bytes.push(0x79);
        bytes.push(0x52);
        let modrm: u8 = (0xC0 | ((d & 7) << 3) | (s2 & 7)) as u8;
        bytes.push(modrm);
        bytes
    }
    pub fn encode_vpdpwssds(&mut self, d: u16, s1: u16, s2: u16) -> Vec<u8> {
        let mut bytes = Vec::new();
        // VEX.128.66.0F38.W0 53 /r: VPDPWSSDS xmm1, xmm2, xmm3/m128
        bytes.push(0xC4);
        bytes.push(0xE2);
        bytes.push(0x79);
        bytes.push(0x53);
        let modrm: u8 = (0xC0 | ((d & 7) << 3) | (s2 & 7)) as u8;
        bytes.push(modrm);
        bytes
    }

    // ========================================================================
    // AVX-IFMA: Integer Fused Multiply-Add
    // ========================================================================
    pub fn encode_vpmadd52luq(&mut self, d: u16, s1: u16, s2: u16) -> Vec<u8> {
        let mut bytes = Vec::new();
        // VEX.128.66.0F38.W0 B4 /r: VPMADD52LUQ xmm1, xmm2, xmm3/m128
        bytes.push(0xC4);
        bytes.push(0xE2);
        bytes.push(0x79);
        bytes.push(0xB4);
        let modrm: u8 = (0xC0 | ((d & 7) << 3) | (s2 & 7)) as u8;
        bytes.push(modrm);
        bytes
    }
    pub fn encode_vpmadd52huq(&mut self, d: u16, s1: u16, s2: u16) -> Vec<u8> {
        let mut bytes = Vec::new();
        // VEX.128.66.0F38.W0 B5 /r: VPMADD52HUQ xmm1, xmm2, xmm3/m128
        bytes.push(0xC4);
        bytes.push(0xE2);
        bytes.push(0x79);
        bytes.push(0xB5);
        let modrm: u8 = (0xC0 | ((d & 7) << 3) | (s2 & 7)) as u8;
        bytes.push(modrm);
        bytes
    }

    // ========================================================================
    // AVX-NE-CONVERT: BF16/FP16 Convert
    // ========================================================================
    pub fn encode_vbcstnebf162ps(&mut self, d: u16, s: u16) -> Vec<u8> {
        let mut bytes = Vec::new();
        // VEX.256.F3.0F38.W0 B0 /r: VBCSTNEBF162PS ymm1, ymm2/m256
        bytes.push(0xC4);
        bytes.push(0xE2);
        bytes.push(0x7D);
        bytes.push(0xB0);
        let modrm: u8 = (0xC0 | ((d & 7) << 3) | (s & 7)) as u8;
        bytes.push(modrm);
        bytes
    }
    pub fn encode_vbcstnesh2ps(&mut self, d: u16, s: u16) -> Vec<u8> {
        let mut bytes = Vec::new();
        // VEX.256.66.0F38.W0 B1 /r: VBCSTNESH2PS ymm1, ymm2/m256
        bytes.push(0xC4);
        bytes.push(0xE2);
        bytes.push(0x7D);
        bytes.push(0xB1);
        let modrm: u8 = (0xC0 | ((d & 7) << 3) | (s & 7)) as u8;
        bytes.push(modrm);
        bytes
    }
    pub fn encode_vcvtneeph2ps(&mut self, d: u16, s1: u16, s2: u16) -> Vec<u8> {
        self.encode_instruction(
            X86FullOpcode::VCVTNEEPH2PS,
            &[X86Operand::Reg(d), X86Operand::Reg(s1), X86Operand::Reg(s2)],
        )
    }

    // ========================================================================
    // 256-bit VEX encoding helpers (ymm variants)
    // ========================================================================

    /// Encode VBCSTNEBF162PS with 256-bit VEX prefix.
    pub fn encode_vbcstnebf162ps_ymm(&mut self, d: u16, s: u16) -> Vec<u8> {
        self.encode_vbcstnebf162ps(d, s)
    }

    /// Encode VBCSTNESH2PS with 256-bit VEX prefix.
    pub fn encode_vbcstnesh2ps_ymm(&mut self, d: u16, s: u16) -> Vec<u8> {
        self.encode_vbcstnesh2ps(d, s)
    }

    /// Encode VPDPBUSD with 256-bit VEX prefix (YMM).
    pub fn encode_vpdpbusd_ymm(&mut self, d: u16, s1: u16, s2: u16) -> Vec<u8> {
        let mut bytes = Vec::new();
        // VEX.256.66.0F38.W0 50 /r: VPDPBUSD ymm1, ymm2, ymm3/m256
        bytes.push(0xC4);
        bytes.push(0xE2);
        bytes.push(0x7D);
        bytes.push(0x50);
        let modrm: u8 = (0xC0 | ((s1 & 7) << 3) | (s2 & 7)) as u8;
        bytes.push(modrm);
        bytes
    }

    /// Encode VPDPWSSD with 256-bit VEX prefix (YMM).
    pub fn encode_vpdpwssd_ymm(&mut self, d: u16, s1: u16, s2: u16) -> Vec<u8> {
        let mut bytes = Vec::new();
        // VEX.256.66.0F38.W0 52 /r: VPDPWSSD ymm1, ymm2, ymm3/m256
        bytes.push(0xC4);
        bytes.push(0xE2);
        bytes.push(0x7D);
        bytes.push(0x52);
        let modrm: u8 = (0xC0 | ((s1 & 7) << 3) | (s2 & 7)) as u8;
        bytes.push(modrm);
        bytes
    }

    /// Encode VPMADD52LUQ with 256-bit VEX prefix (YMM).
    pub fn encode_vpmadd52luq_ymm(&mut self, d: u16, s1: u16, s2: u16) -> Vec<u8> {
        let mut bytes = Vec::new();
        // VEX.256.66.0F38.W0 B4 /r: VPMADD52LUQ ymm1, ymm2, ymm3/m256
        bytes.push(0xC4);
        bytes.push(0xE2);
        bytes.push(0x7D);
        bytes.push(0xB4);
        let modrm: u8 = (0xC0 | ((s1 & 7) << 3) | (s2 & 7)) as u8;
        bytes.push(modrm);
        bytes
    }

    /// Encode VPMADD52HUQ with 256-bit VEX prefix (YMM).
    pub fn encode_vpmadd52huq_ymm(&mut self, d: u16, s1: u16, s2: u16) -> Vec<u8> {
        let mut bytes = Vec::new();
        // VEX.256.66.0F38.W0 B5 /r: VPMADD52HUQ ymm1, ymm2, ymm3/m256
        bytes.push(0xC4);
        bytes.push(0xE2);
        bytes.push(0x7D);
        bytes.push(0xB5);
        let modrm: u8 = (0xC0 | ((s1 & 7) << 3) | (s2 & 7)) as u8;
        bytes.push(modrm);
        bytes
    }

    /// Encode VGF2P8AFFINEQB with 256-bit VEX prefix (YMM).
    pub fn encode_vgf2p8affineqb_ymm(&mut self, d: u16, s1: u16, s2: u16, imm: u8) -> Vec<u8> {
        let mut bytes = Vec::new();
        // VEX.256.66.0F3A.W0 CE /r /ib: VGF2P8AFFINEQB ymm1, ymm2, ymm3/m256, imm8
        bytes.push(0xC4);
        bytes.push(0xE2);
        bytes.push(0x7D);
        bytes.push(0xCE);
        let modrm: u8 = (0xC0 | ((s1 & 7) << 3) | (s2 & 7)) as u8;
        bytes.push(modrm);
        bytes.push(imm);
        bytes
    }

    /// Encode VGF2P8MULB with 256-bit VEX prefix (YMM).
    pub fn encode_vgf2p8mulb_ymm(&mut self, d: u16, s1: u16, s2: u16) -> Vec<u8> {
        let mut bytes = Vec::new();
        // VEX.256.66.0F38.W0 CF /r: VGF2P8MULB ymm1, ymm2, ymm3/m256
        bytes.push(0xC4);
        bytes.push(0xE2);
        bytes.push(0x7D);
        bytes.push(0xCF);
        let modrm: u8 = (0xC0 | ((s1 & 7) << 3) | (s2 & 7)) as u8;
        bytes.push(modrm);
        bytes
    }

    /// Encode VAESENC with 256-bit VEX prefix (YMM).
    pub fn encode_vaesenc_ymm(&mut self, d: u16, s1: u16, s2: u16) -> Vec<u8> {
        let mut bytes = Vec::new();
        // VEX.256.66.0F38.W0 DC /r: VAESENC ymm1, ymm2, ymm3/m256
        bytes.push(0xC4);
        bytes.push(0xE2);
        bytes.push(0x7D);
        bytes.push(0xDC);
        let modrm: u8 = (0xC0 | ((s1 & 7) << 3) | (s2 & 7)) as u8;
        bytes.push(modrm);
        bytes
    }

    /// Encode VAESDEC with 256-bit VEX prefix (YMM).
    pub fn encode_vaesdec_ymm(&mut self, d: u16, s1: u16, s2: u16) -> Vec<u8> {
        let mut bytes = Vec::new();
        // VEX.256.66.0F38.W0 DE /r: VAESDEC ymm1, ymm2, ymm3/m256
        bytes.push(0xC4);
        bytes.push(0xE2);
        bytes.push(0x7D);
        bytes.push(0xDE);
        let modrm: u8 = (0xC0 | ((s1 & 7) << 3) | (s2 & 7)) as u8;
        bytes.push(modrm);
        bytes
    }

    // ========================================================================
    // RIP-relative helper
    // ========================================================================

    /// Create a RIP-relative memory operand (for position-independent code).
    pub fn rip_relative(displacement: i32) -> X86MemOperand {
        X86MemOperand {
            base: RIP,
            index: 0,
            scale: 0,
            displacement,
            segment: 0,
        }
    }
}

// ============================================================================
// APX REX2 Prefix Encoding
// ============================================================================

/// REX2 prefix encoder for APX instructions.
/// REX2 (0xD5) is an 8-bit extended prefix that allows encoding of
/// up to 32 GPRs (r0-r31) and 32 vector registers.
pub mod apx_rex2_encoder {
    use super::*;

    /// REX2 prefix byte.
    pub const REX2_PREFIX: u8 = 0xD5;

    /// Build a REX2 byte.
    /// Layout: [M0(1) | R4(1) | X4(1) | B4(1) | W(1) | R3(1) | X3(1) | B3(1)]
    pub fn encode_rex2(
        w: bool,
        r: u8, // reg field (5 bits: r4..r0)
        x: u8, // index field (5 bits: x4..x0)
        b: u8, // base/rm field (5 bits: b4..b0)
    ) -> u8 {
        let r4 = (r >> 4) & 1;
        let r3 = (r >> 3) & 1;
        let x4 = (x >> 4) & 1;
        let x3 = (x >> 3) & 1;
        let b4 = (b >> 4) & 1;
        let b3 = (b >> 3) & 1;
        (r4 << 6) | (x4 << 5) | (b4 << 4) | ((w as u8) << 3) | (r3 << 2) | (x3 << 1) | b3
    }

    /// Check if REX2 is needed.
    pub fn needs_rex2(reg: u8, rm: u8, index: Option<u8>) -> bool {
        reg >= 16 || rm >= 16 || index.map_or(false, |i| i >= 16)
    }

    /// Check if any register needs REX2 in a 3-operand form.
    pub fn needs_rex2_3op(dst: u8, src1: u8, src2: u8) -> bool {
        dst >= 16 || src1 >= 16 || src2 >= 16
    }

    /// Encode the full REX2 prefix sequence (returns [REX2] or [REX2, byte]).
    pub fn encode_prefix(w: bool, reg: u8, rm: u8) -> Vec<u8> {
        let needs_ext = reg >= 16 || rm >= 16;
        if !needs_ext && !w {
            return Vec::new();
        }
        if needs_ext {
            vec![REX2_PREFIX, encode_rex2(w, reg, 0, rm)]
        } else {
            vec![0x40 | ((w as u8) << 3) | (((reg >> 3) & 1) << 2) | ((rm >> 3) & 1)]
        }
    }

    /// Encode REX2 prefix for a memory operand with index.
    pub fn encode_prefix_mem(w: bool, reg: u8, base: u8, index: u8) -> Vec<u8> {
        let needs_ext = reg >= 16 || base >= 16 || index >= 16;
        if !needs_ext && !w {
            return Vec::new();
        }
        if needs_ext {
            vec![REX2_PREFIX, encode_rex2(w, reg, index, base)]
        } else {
            let rex = 0x40
                | ((w as u8) << 3)
                | (((reg >> 3) & 1) << 2)
                | (((index >> 3) & 1) << 1)
                | ((base >> 3) & 1);
            vec![rex]
        }
    }
}

// ============================================================================
// EVEX Extended Encoding for APX
// ============================================================================

/// EVEX prefix encoder supporting APX extended registers.
/// EVEX is a 4-byte prefix extension of VEX for AVX-512 and APX.
pub mod apx_evex_encoder {
    use super::*;

    /// EVEX prefix byte 1: 0x62.
    pub const EVEX_PREFIX: u8 = 0x62;

    /// Build a 4-byte EVEX prefix.
    ///
    /// EVEX layout:
    ///   Byte 0: 0x62 (fixed)
    ///   Byte 1: [R(1)|X(1)|B(1)|R'(1)|0|0|m(2)]
    ///   Byte 2: [W(1)|v'(4)|1|p(2)]
    ///   Byte 3: [z(1)|L'(1)|L(1)|b(1)|V'(1)|a(3)]
    ///
    /// Where R' is the 5th bit of the reg field (for EGPR),
    /// v' is the 5th bit of the vvvv field,
    /// and V' is adjustment for the V bit.
    pub fn build_evex(
        r: bool,
        x: bool,
        b: bool,
        r_prime: bool, // R' (5th bit of reg)
        mmm: u8,       // opcode map (0-7)
        w: bool,
        vvvv: u8,      // source register (4 bits)
        v_prime: bool, // v' (5th bit of vvvv)
        pp: u8,        // mandatory prefix
        z: bool,       // zeroing mask
        ll: u8,        // vector length (0=128, 1=256, 2=512)
        b_bit: bool,   // broadcast/rounding
        aaa: u8,       // opmask register (0-7)
    ) -> [u8; 4] {
        let byte1 = ((!r as u8) << 7)
            | ((!x as u8) << 6)
            | ((!b as u8) << 5)
            | ((r_prime as u8) << 4)
            | (mmm & 0x7);

        let byte2 = ((w as u8) << 7)
            | ((!vvvv & 0xF) << 3)
            | (1 << 2) // fixed bit
            | (pp & 0x3);

        let byte3 = ((z as u8) << 7)
            | (((ll >> 1) & 1) << 6) // L'
            | (((ll >> 0) & 1) << 5) // L
            | ((b_bit as u8) << 4)
            | ((v_prime as u8) << 3)
            | (aaa & 0x7);

        [EVEX_PREFIX, byte1, byte2, byte3]
    }

    /// Build EVEX for a register-to-register operation with EGPR.
    pub fn build_evex_rr(
        opcode_map: u8,
        w: bool,
        vvvv: u8,
        pp: u8,
        reg: u8,
        rm: u8,
        ll: u8,
    ) -> [u8; 4] {
        let r = (reg >> 3) & 1 != 0;
        let b = (rm >> 3) & 1 != 0;
        let r_prime = (reg >> 4) & 1 != 0;
        let v_prime = (vvvv >> 4) & 1 != 0;

        build_evex(
            r,
            false,
            b,
            r_prime,
            opcode_map,
            w,
            vvvv & 0xF,
            v_prime,
            pp,
            false,
            ll,
            false,
            0,
        )
    }

    /// Build EVEX for a memory operation.
    pub fn build_evex_mem(
        opcode_map: u8,
        w: bool,
        vvvv: u8,
        pp: u8,
        reg: u8,
        base: u8,
        index: u8,
        ll: u8,
        disp_size: u8, // disp8*N scale: 1,2,4,8,16,32,64
    ) -> [u8; 4] {
        let r = (reg >> 3) & 1 != 0;
        let x = (index >> 3) & 1 != 0;
        let b = (base >> 3) & 1 != 0;
        let r_prime = (reg >> 4) & 1 != 0;
        let v_prime = (vvvv >> 4) & 1 != 0;

        let ll_encoded = match disp_size {
            1 | 2 | 4 => 0,
            8 | 16 => 1,
            32 | 64 => 2,
            _ => 0,
        };

        build_evex(
            r,
            x,
            b,
            r_prime,
            opcode_map,
            w,
            vvvv & 0xF,
            v_prime,
            pp,
            false,
            ll_encoded,
            false,
            0,
        )
    }
}

// ============================================================================
// VEX Encoding for 3-Operand APX Forms
// ============================================================================

/// VEX prefix encoder for 3-operand instructions (AVX/APX).
pub mod apx_vex_encoder {
    use super::*;

    /// 3-byte VEX prefix: 0xC4.
    pub const VEX3_PREFIX: u8 = 0xC4;

    /// 2-byte VEX prefix: 0xC5.
    pub const VEX2_PREFIX: u8 = 0xC5;

    /// Build a 3-byte VEX prefix for APX 3-operand forms.
    pub fn build_vex3(
        r: bool,
        x: bool,
        b: bool,
        mmmmm: u8,
        w: bool,
        vvvv: u8,
        l: bool,
        pp: u8,
    ) -> [u8; 3] {
        let byte1 = ((!r as u8) << 7) | ((!x as u8) << 6) | ((!b as u8) << 5) | (mmmmm & 0x1F);

        let byte2 = ((w as u8) << 7) | ((!vvvv & 0xF) << 3) | ((l as u8) << 2) | (pp & 0x3);

        [VEX3_PREFIX, byte1, byte2]
    }

    /// Build a 2-byte VEX prefix.
    pub fn build_vex2(r: bool, vvvv: u8, l: bool, pp: u8) -> [u8; 2] {
        let byte1 = ((!r as u8) << 7) | ((!vvvv & 0xF) << 3) | ((l as u8) << 2) | (pp & 0x3);
        [VEX2_PREFIX, byte1]
    }

    /// Check if VEX encoding is preferred over legacy for APX operations.
    pub fn should_use_vex(num_operands: u8, has_imm: bool) -> bool {
        num_operands >= 3 || has_imm
    }
}

// ============================================================================
// XOP Encoding for AMD-Specific Instructions
// ============================================================================

/// XOP prefix encoder for AMD XOP instructions (Bulldozer/Piledriver).
/// XOP uses the same format as VEX3 but with the 0x8F prefix byte.
pub mod xop_encoder {
    use super::*;

    /// XOP prefix byte: 0x8F.
    pub const XOP_PREFIX: u8 = 0x8F;

    /// Build a 3-byte XOP prefix.
    pub fn build_xop(
        r: bool,
        x: bool,
        b: bool,
        mmmmm: u8, // XOP opcode map
        w: bool,
        vvvv: u8,
        l: bool,
        pp: u8,
    ) -> [u8; 3] {
        let byte1 = ((!r as u8) << 7) | ((!x as u8) << 6) | ((!b as u8) << 5) | (mmmmm & 0x1F);

        let byte2 = ((w as u8) << 7) | ((!vvvv & 0xF) << 3) | ((l as u8) << 2) | (pp & 0x3);

        [XOP_PREFIX, byte1, byte2]
    }

    /// AMD XOP opcode maps.
    pub mod xop_maps {
        /// XOP map 8 (integer instructions).
        pub const XOP_MAP8: u8 = 8;
        /// XOP map 9 (integer instructions).
        pub const XOP_MAP9: u8 = 9;
        /// XOP map 10 (floating-point instructions).
        pub const XOP_MAP10: u8 = 10;
    }
}

// ============================================================================
// ModR/M Encoding with EGPR Support
// ============================================================================

/// ModR/M encoder supporting EGPR (r16-r31) via REX2.
#[derive(Debug, Clone)]
pub struct ModRMEncoder {
    /// The mode field (bits 7-6).
    pub mod_: u8,
    /// The reg/opcode field (bits 5-3).
    pub reg: u8,
    /// The r/m field (bits 2-0).
    pub rm: u8,
    /// Extended bits from REX/REX2 for reg and rm.
    pub rex_r: bool, // 4th bit of reg
    pub rex_b: bool,   // 4th bit of rm
    pub rex2_r4: bool, // 5th bit of reg (EGPR)
    pub rex2_b4: bool, // 5th bit of rm (EGPR)
}

impl ModRMEncoder {
    /// Create a ModR/M byte for register-direct mode (mod=3).
    pub fn reg_direct(reg: u8, rm: u8) -> Self {
        Self {
            mod_: 3,
            reg: reg & 0x7,
            rm: rm & 0x7,
            rex_r: (reg >> 3) & 1 != 0,
            rex_b: (rm >> 3) & 1 != 0,
            rex2_r4: (reg >> 4) & 1 != 0,
            rex2_b4: (rm >> 4) & 1 != 0,
        }
    }

    /// Create a ModR/M for memory with no displacement (mod=0).
    pub fn mem_no_disp(reg: u8, rm: u8) -> Self {
        Self {
            mod_: 0,
            reg: reg & 0x7,
            rm: rm & 0x7,
            rex_r: (reg >> 3) & 1 != 0,
            rex_b: (rm >> 3) & 1 != 0,
            rex2_r4: (reg >> 4) & 1 != 0,
            rex2_b4: (rm >> 4) & 1 != 0,
        }
    }

    /// Create ModR/M for memory with 8-bit displacement (mod=1).
    pub fn mem_disp8(reg: u8, rm: u8) -> Self {
        Self {
            mod_: 1,
            reg: reg & 0x7,
            rm: rm & 0x7,
            rex_r: (reg >> 3) & 1 != 0,
            rex_b: (rm >> 3) & 1 != 0,
            rex2_r4: (reg >> 4) & 1 != 0,
            rex2_b4: (rm >> 4) & 1 != 0,
        }
    }

    /// Create ModR/M for memory with 32-bit displacement (mod=2).
    pub fn mem_disp32(reg: u8, rm: u8) -> Self {
        Self {
            mod_: 2,
            reg: reg & 0x7,
            rm: rm & 0x7,
            rex_r: (reg >> 3) & 1 != 0,
            rex_b: (rm >> 3) & 1 != 0,
            rex2_r4: (reg >> 4) & 1 != 0,
            rex2_b4: (rm >> 4) & 1 != 0,
        }
    }

    /// Encode the ModR/M byte.
    pub fn encode(&self) -> u8 {
        (self.mod_ << 6) | ((self.reg & 0x7) << 3) | (self.rm & 0x7)
    }

    /// Get the full 5-bit register number.
    pub fn full_reg(&self) -> u8 {
        self.reg | ((self.rex_r as u8) << 3) | ((self.rex2_r4 as u8) << 4)
    }

    /// Get the full 5-bit rm number.
    pub fn full_rm(&self) -> u8 {
        self.rm | ((self.rex_b as u8) << 3) | ((self.rex2_b4 as u8) << 4)
    }

    /// Check if REX2 is needed for this ModR/M.
    pub fn needs_rex2(&self) -> bool {
        self.rex2_r4 || self.rex2_b4
    }
}

// ============================================================================
// SIB Byte Encoding with EGPR
// ============================================================================

/// SIB byte encoder with EGPR support.
#[derive(Debug, Clone)]
pub struct SIBEncoder {
    /// Scale factor (bits 7-6): 0=1, 1=2, 2=4, 3=8.
    pub scale: u8,
    /// Index register (bits 5-3).
    pub index: u8,
    /// Base register (bits 2-0).
    pub base: u8,
    /// Extended index bit (REX.X or REX2.X4).
    pub rex_x: bool,
    pub rex2_x4: bool,
}

impl SIBEncoder {
    /// Create a SIB with no index (scale=0, index=ESP/RSP encoding 4).
    pub fn no_index(base: u8) -> Self {
        Self {
            scale: 0,
            index: 4, // special: no index
            base: base & 0x7,
            rex_x: false,
            rex2_x4: false,
        }
    }

    /// Create a SIB with index and scale.
    pub fn with_index(base: u8, index: u8, scale: u8) -> Self {
        assert!(scale == 1 || scale == 2 || scale == 4 || scale == 8);
        let scale_bits = match scale {
            1 => 0,
            2 => 1,
            4 => 2,
            8 => 3,
            _ => 0,
        };
        Self {
            scale: scale_bits,
            index: index & 0x7,
            base: base & 0x7,
            rex_x: (index >> 3) & 1 != 0,
            rex2_x4: (index >> 4) & 1 != 0,
        }
    }

    /// Create a SIB for RIP-relative addressing (base=5, index=4).
    pub fn rip_relative() -> Self {
        Self {
            scale: 0,
            index: 4,
            base: 5,
            rex_x: false,
            rex2_x4: false,
        }
    }

    /// Encode the SIB byte.
    pub fn encode(&self) -> u8 {
        (self.scale << 6) | ((self.index & 0x7) << 3) | (self.base & 0x7)
    }

    /// Check if this SIB requires REX2.
    pub fn needs_rex2(&self) -> bool {
        self.rex2_x4
    }
}

// ============================================================================
// Displacement Encoding: disp8, disp32, compressed disp8*N
// ============================================================================

/// Displacement encoder supporting all sizes and compressed forms.
#[derive(Debug, Clone)]
pub struct DisplacementEncoder {
    /// The displacement value.
    pub value: i64,
    /// The size of the displacement in bytes: 1, 2, 4.
    pub size: u8,
    /// For EVEX compressed displacements: the N multiplier.
    pub evex_compression_n: u8,
}

impl DisplacementEncoder {
    /// Create a disp8.
    pub fn disp8(value: i8) -> Self {
        Self {
            value: value as i64,
            size: 1,
            evex_compression_n: 1,
        }
    }

    /// Create a disp16.
    pub fn disp16(value: i16) -> Self {
        Self {
            value: value as i64,
            size: 2,
            evex_compression_n: 1,
        }
    }

    /// Create a disp32.
    pub fn disp32(value: i32) -> Self {
        Self {
            value: value as i64,
            size: 4,
            evex_compression_n: 1,
        }
    }

    /// Create a compressed EVEX displacement (disp8 * N).
    pub fn evex_compressed(value: i64, n: u8) -> Self {
        assert!(n == 1 || n == 2 || n == 4 || n == 8 || n == 16 || n == 32 || n == 64);
        let compressed = value / n as i64;
        assert!(
            compressed >= -128 && compressed <= 127,
            "compressed disp out of range"
        );
        Self {
            value: compressed,
            size: 1,
            evex_compression_n: n,
        }
    }

    /// Encode as bytes.
    pub fn encode(&self) -> Vec<u8> {
        match self.size {
            1 => vec![self.value as u8],
            2 => {
                let v = self.value as u16;
                vec![v as u8, (v >> 8) as u8]
            }
            4 => {
                let v = self.value as u32;
                vec![v as u8, (v >> 8) as u8, (v >> 16) as u8, (v >> 24) as u8]
            }
            _ => vec![self.value as u8],
        }
    }

    /// Get the actual memory displacement (uncompressed).
    pub fn effective_disp(&self) -> i64 {
        if self.evex_compression_n > 1 {
            self.value * self.evex_compression_n as i64
        } else {
            self.value
        }
    }

    /// Check if this displacement fits in a sign-extended disp8.
    pub fn fits_in_disp8(&self) -> bool {
        let eff = self.effective_disp();
        eff >= -128 && eff <= 127
    }
}

// ============================================================================
// Immediate Encoding: imm8-imm64 with Sign Extension
// ============================================================================

/// Immediate value encoder with proper sign extension.
#[derive(Debug, Clone)]
pub struct ImmediateEncoder {
    /// The immediate value (as i64 for all sizes).
    pub value: i64,
    /// Size in bytes: 1, 2, 4, or 8.
    pub size: u8,
    /// Whether to sign-extend a smaller immediate.
    pub sign_extend: bool,
}

impl ImmediateEncoder {
    /// Create an imm8.
    pub fn imm8(value: i8) -> Self {
        Self {
            value: value as i64,
            size: 1,
            sign_extend: false,
        }
    }

    /// Create an imm16.
    pub fn imm16(value: i16) -> Self {
        Self {
            value: value as i64,
            size: 2,
            sign_extend: false,
        }
    }

    /// Create an imm32.
    pub fn imm32(value: i32) -> Self {
        Self {
            value: value as i64,
            size: 4,
            sign_extend: false,
        }
    }

    /// Create an imm64.
    pub fn imm64(value: i64) -> Self {
        Self {
            value,
            size: 8,
            sign_extend: false,
        }
    }

    /// Create a sign-extended imm32 (encoded as 4 bytes, sign-extended to i64).
    pub fn imm32s(value: i64) -> Self {
        Self {
            value,
            size: 4,
            sign_extend: true,
        }
    }

    /// Encode as bytes (little-endian, truncated to size).
    pub fn encode(&self) -> Vec<u8> {
        match self.size {
            1 => vec![self.value as u8],
            2 => {
                let v = self.value as u16;
                vec![v as u8, (v >> 8) as u8]
            }
            4 => {
                let v = self.value as u32;
                vec![v as u8, (v >> 8) as u8, (v >> 16) as u8, (v >> 24) as u8]
            }
            8 => {
                let v = self.value as u64;
                vec![
                    v as u8,
                    (v >> 8) as u8,
                    (v >> 16) as u8,
                    (v >> 24) as u8,
                    (v >> 32) as u8,
                    (v >> 40) as u8,
                    (v >> 48) as u8,
                    (v >> 56) as u8,
                ]
            }
            _ => vec![self.value as u8],
        }
    }

    /// Check if the value fits in imm8 (sign-extended from 8 bits).
    pub fn fits_in_imm8(&self) -> bool {
        self.value >= -128 && self.value <= 127
    }

    /// Check if the value fits in imm32 (sign-extended from 32 bits).
    pub fn fits_in_imm32(&self) -> bool {
        self.value >= -(1i64 << 31) && self.value <= (1i64 << 31) - 1
    }

    /// Promote this immediate to the smallest size that fits.
    pub fn promote_to_fit(&self) -> Self {
        if self.fits_in_imm8() {
            Self {
                value: self.value,
                size: 1,
                sign_extend: true,
            }
        } else if self.fits_in_imm32() && self.size > 4 {
            Self {
                value: self.value,
                size: 4,
                sign_extend: true,
            }
        } else {
            self.clone()
        }
    }
}

// ============================================================================
// Complete Instruction Byte Encoding Helpers
// ============================================================================

/// Helper to encode an opcode with optional 0x0F prefix.
#[derive(Debug, Clone)]
pub struct OpcodeEncoder {
    /// Opcode map: 0=1-byte, 1=0F prefix, 2=0F38, 3=0F3A.
    pub opcode_map: u8,
    /// Base opcode byte.
    pub base_opcode: u8,
    /// Mandatory prefix: 0=none, 1=66, 2=F3, 3=F2.
    pub mandatory_prefix: u8,
}

impl OpcodeEncoder {
    pub fn new(base_opcode: u8) -> Self {
        Self {
            opcode_map: 0,
            base_opcode,
            mandatory_prefix: 0,
        }
    }

    pub fn with_map(mut self, map: u8) -> Self {
        self.opcode_map = map;
        self
    }

    pub fn with_prefix(mut self, prefix: u8) -> Self {
        self.mandatory_prefix = prefix;
        self
    }

    /// Encode the opcode bytes (prefix + opcode map + base opcode).
    pub fn encode(&self) -> Vec<u8> {
        let mut bytes = Vec::new();

        // Mandatory prefix
        match self.mandatory_prefix {
            1 => bytes.push(0x66),
            2 => bytes.push(0xF3),
            3 => bytes.push(0xF2),
            _ => {}
        }

        // Opcode map prefix
        match self.opcode_map {
            1 => bytes.push(0x0F),
            2 => {
                bytes.push(0x0F);
                bytes.push(0x38);
            }
            3 => {
                bytes.push(0x0F);
                bytes.push(0x3A);
            }
            _ => {}
        }

        bytes.push(self.base_opcode);
        bytes
    }

    /// Get the total number of prefix bytes before the ModR/M.
    pub fn prefix_len(&self) -> u8 {
        let mut len: u8 = 0;
        if self.mandatory_prefix != 0 {
            len += 1;
        }
        match self.opcode_map {
            0 => {}
            1 => len += 1,
            2 | 3 => len += 2,
            _ => {}
        }
        len + 1 // +1 for the base opcode itself
    }
}

/// Full instruction encoding: prefix + opcode + ModR/M + SIB + displacement + immediate.
#[derive(Debug, Clone)]
pub struct FullInstructionEncoder {
    /// REX/REX2 prefix bytes.
    pub rex_bytes: Vec<u8>,
    /// VEX/EVEX/XOP prefix bytes (mutually exclusive with REX).
    pub vex_bytes: Vec<u8>,
    /// Opcode bytes (including mandatory prefix and opcode map).
    pub opcode_bytes: Vec<u8>,
    /// ModR/M byte (optional).
    pub modrm: Option<u8>,
    /// SIB byte (optional).
    pub sib: Option<u8>,
    /// Displacement bytes.
    pub displacement: Vec<u8>,
    /// Immediate bytes.
    pub immediate: Vec<u8>,
}

impl FullInstructionEncoder {
    pub fn new() -> Self {
        Self {
            rex_bytes: Vec::new(),
            vex_bytes: Vec::new(),
            opcode_bytes: Vec::new(),
            modrm: None,
            sib: None,
            displacement: Vec::new(),
            immediate: Vec::new(),
        }
    }

    /// Assemble all bytes into the final instruction.
    pub fn assemble(&self) -> Vec<u8> {
        let mut result = Vec::new();

        // lock prefix and other legacy prefixes would go here

        // VEX/EVEX/XOP or REX
        if !self.vex_bytes.is_empty() {
            result.extend(&self.vex_bytes);
        } else {
            result.extend(&self.rex_bytes);
        }

        // Opcode bytes
        result.extend(&self.opcode_bytes);

        // ModR/M
        if let Some(m) = self.modrm {
            result.push(m);
        }

        // SIB
        if let Some(s) = self.sib {
            result.push(s);
        }

        // Displacement
        result.extend(&self.displacement);

        // Immediate
        result.extend(&self.immediate);

        result
    }

    /// Get the total instruction length in bytes.
    pub fn len(&self) -> usize {
        self.rex_bytes.len()
            + self.vex_bytes.len()
            + self.opcode_bytes.len()
            + self.modrm.map_or(0, |_| 1)
            + self.sib.map_or(0, |_| 1)
            + self.displacement.len()
            + self.immediate.len()
    }

    /// Whether this is a valid x86 instruction (fits in 15 bytes).
    pub fn is_valid_length(&self) -> bool {
        self.len() <= 15
    }

    /// Check if this instruction uses VEX/EVEX encoding.
    pub fn is_vex_encoded(&self) -> bool {
        !self.vex_bytes.is_empty()
    }

    /// Check if this instruction uses REX/REX2 encoding.
    pub fn is_rex_encoded(&self) -> bool {
        !self.rex_bytes.is_empty()
    }

    /// Check if this instruction uses legacy encoding (no prefixes beyond opcode).
    pub fn is_legacy_encoded(&self) -> bool {
        self.rex_bytes.is_empty() && self.vex_bytes.is_empty()
    }
}

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

/// Convenience builder for encoding a complete x86 instruction.
#[derive(Debug, Clone)]
pub struct InstructionBuilder {
    pub encoder: FullInstructionEncoder,
}

impl InstructionBuilder {
    pub fn new() -> Self {
        Self {
            encoder: FullInstructionEncoder::new(),
        }
    }

    /// Set the opcode.
    pub fn opcode(mut self, op: OpcodeEncoder) -> Self {
        self.encoder.opcode_bytes = op.encode();
        self
    }

    /// Add REX/REX2 prefix.
    pub fn rex(mut self, bytes: &[u8]) -> Self {
        self.encoder.rex_bytes = bytes.to_vec();
        self
    }

    /// Add ModR/M byte.
    pub fn modrm(mut self, enc: &ModRMEncoder) -> Self {
        self.encoder.modrm = Some(enc.encode());
        self
    }

    /// Add SIB byte.
    pub fn sib(mut self, enc: &SIBEncoder) -> Self {
        self.encoder.sib = Some(enc.encode());
        self
    }

    /// Add displacement.
    pub fn displacement(mut self, enc: &DisplacementEncoder) -> Self {
        self.encoder.displacement = enc.encode();
        self
    }

    /// Add immediate.
    pub fn immediate(mut self, enc: &ImmediateEncoder) -> Self {
        self.encoder.immediate = enc.encode();
        self
    }

    /// Build the final encoded bytes.
    pub fn build(&self) -> Vec<u8> {
        self.encoder.assemble()
    }

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

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

/// Encode a simple register-to-register ALU operation.
pub fn encode_alu_rr(opcode: &OpcodeEncoder, dst: u8, src: u8, is_64bit: bool) -> Vec<u8> {
    let modrm = ModRMEncoder::reg_direct(dst, src);
    let rex = apx_rex2_encoder::encode_prefix(is_64bit, dst, src);

    let mut bytes = Vec::new();
    bytes.extend(&rex);
    bytes.extend(opcode.encode());
    bytes.push(modrm.encode());
    bytes
}

/// Encode a simple register-to-memory ALU operation.
pub fn encode_alu_rm(
    opcode: &OpcodeEncoder,
    reg: u8,
    base: u8,
    index: u8,
    scale: u8,
    disp: &DisplacementEncoder,
    is_64bit: bool,
) -> Vec<u8> {
    let sib = SIBEncoder::with_index(base, index, scale);
    let modrm = if disp.effective_disp() == 0 {
        ModRMEncoder::mem_no_disp(reg, base)
    } else if disp.fits_in_disp8() {
        ModRMEncoder::mem_disp8(reg, base)
    } else {
        ModRMEncoder::mem_disp32(reg, base)
    };

    let rex = apx_rex2_encoder::encode_prefix_mem(is_64bit, reg, base, index);

    let mut bytes = Vec::new();
    bytes.extend(&rex);
    bytes.extend(opcode.encode());
    bytes.push(modrm.encode());
    bytes.push(sib.encode());
    bytes.extend(disp.encode());
    bytes
}

/// Encode a register-to-immediate ALU operation (e.g., ADD r, imm).
pub fn encode_alu_ri(
    group_opcode: u8, // e.g., 0x81 for group 1
    reg_field: u8,    // e.g., 0 for ADD, 5 for SUB
    dst: u8,
    imm: &ImmediateEncoder,
    is_64bit: bool,
) -> Vec<u8> {
    let modrm = ModRMEncoder::reg_direct(reg_field, dst);
    let rex = apx_rex2_encoder::encode_prefix(is_64bit, reg_field, dst);

    let mut bytes = Vec::new();
    bytes.extend(&rex);
    bytes.push(group_opcode);
    bytes.push(modrm.encode());
    bytes.extend(imm.encode());
    bytes
}

// ============================================================================
// EVEX Compressed Displacement Table (disp8*N)
// ============================================================================

/// Complete EVEX compressed displacement multiplier lookup.
/// Maps (tuple_type, element_size_bits) → N multiplier.
/// Used to encode disp8*N compressed displacements.
pub mod evex_compressed_displacement {
    use super::EvexTuple;

    /// Get the N multiplier for EVEX compressed displacement.
    /// The actual memory displacement is encoded as disp8 = real_disp / N.
    ///
    /// N values per Intel SDM Volume 2, Section 2.7.5:
    /// - Full: 64 bytes (512-bit vector)
    /// - Half: 32 bytes (256-bit memory access)
    /// - Quarter: 16 bytes (128-bit memory access)
    /// - Eighth: 8 bytes (64-bit memory access)
    /// - Scalar: 4 or 8 bytes
    /// - FullMem: 64 byte memory-only
    /// - HalfMem: 32 byte memory-only
    /// - QuarterMem: 16 byte memory-only
    /// - EighthMem: 8 byte memory-only
    /// - Mem128: 16 byte memory-only (like QuarterMem)
    pub fn multiplier_for(tuple: EvexTuple, element_size_bits: u8) -> u8 {
        let full_n = match element_size_bits {
            8 => 64,  // VB = 64 bytes
            16 => 64, // VW = 64 bytes
            32 => 64, // VD = 64 bytes
            64 => 64, // VQ = 64 bytes
            _ => 64,
        };
        match tuple {
            EvexTuple::Full => full_n,
            EvexTuple::FullMem => 64,
            EvexTuple::Half | EvexTuple::HalfMem => 32,
            EvexTuple::Quarter | EvexTuple::QuarterMem | EvexTuple::Mem128 => 16,
            EvexTuple::Eighth | EvexTuple::EighthMem => 8,
            EvexTuple::Scalar => match element_size_bits {
                64 => 8,
                _ => 4,
            },
        }
    }

    /// Full compressed displacement table: maps disp8 value to actual displacement.
    /// For each tuple type and element size, the effective displacement.
    pub const DISP8_TABLE_FULL: [(u8, i32); 256] = {
        let mut table = [(0u8, 0i32); 256];
        let mut i = 0u16;
        while i < 256 {
            let disp8 = i as i8;
            table[i as usize] = (i as u8, disp8 as i32 * 64);
            i += 1;
        }
        table
    };

    pub const DISP8_TABLE_HALF: [(u8, i32); 256] = {
        let mut table = [(0u8, 0i32); 256];
        let mut i = 0u16;
        while i < 256 {
            let disp8 = i as i8;
            table[i as usize] = (i as u8, disp8 as i32 * 32);
            i += 1;
        }
        table
    };

    pub const DISP8_TABLE_QUARTER: [(u8, i32); 256] = {
        let mut table = [(0u8, 0i32); 256];
        let mut i = 0u16;
        while i < 256 {
            let disp8 = i as i8;
            table[i as usize] = (i as u8, disp8 as i32 * 16);
            i += 1;
        }
        table
    };

    pub const DISP8_TABLE_EIGHTH: [(u8, i32); 256] = {
        let mut table = [(0u8, 0i32); 256];
        let mut i = 0u16;
        while i < 256 {
            let disp8 = i as i8;
            table[i as usize] = (i as u8, disp8 as i32 * 8);
            i += 1;
        }
        table
    };

    pub const DISP8_TABLE_SCALAR_4: [(u8, i32); 256] = {
        let mut table = [(0u8, 0i32); 256];
        let mut i = 0u16;
        while i < 256 {
            let disp8 = i as i8;
            table[i as usize] = (i as u8, disp8 as i32 * 4);
            i += 1;
        }
        table
    };

    pub const DISP8_TABLE_SCALAR_8: [(u8, i32); 256] = {
        let mut table = [(0u8, 0i32); 256];
        let mut i = 0u16;
        while i < 256 {
            let disp8 = i as i8;
            table[i as usize] = (i as u8, disp8 as i32 * 8);
            i += 1;
        }
        table
    };

    /// Encode a real displacement into EVEX compressed disp8.
    /// Returns None if displacement cannot be compressed.
    pub fn compress_disp(real_disp: i32, n: u8) -> Option<u8> {
        if real_disp % n as i32 != 0 {
            return None;
        }
        let compressed = real_disp / n as i32;
        if compressed < -128 || compressed > 127 {
            return None;
        }
        Some(compressed as u8)
    }

    /// Decompress a disp8 back to the real displacement.
    pub fn decompress_disp(disp8: u8, n: u8) -> i32 {
        (disp8 as i8 as i32) * n as i32
    }

    /// Get the lookup table for a given tuple and element size.
    pub fn get_disp_table(tuple: EvexTuple, element_size_bits: u8) -> &'static [(u8, i32); 256] {
        match tuple {
            EvexTuple::Full | EvexTuple::FullMem => &DISP8_TABLE_FULL,
            EvexTuple::Half | EvexTuple::HalfMem => &DISP8_TABLE_HALF,
            EvexTuple::Quarter | EvexTuple::QuarterMem | EvexTuple::Mem128 => &DISP8_TABLE_QUARTER,
            EvexTuple::Eighth | EvexTuple::EighthMem => &DISP8_TABLE_EIGHTH,
            EvexTuple::Scalar => {
                if element_size_bits == 64 {
                    &DISP8_TABLE_SCALAR_8
                } else {
                    &DISP8_TABLE_SCALAR_4
                }
            }
        }
    }
}

// ============================================================================
// EVEX Broadcast Encoding
// ============================================================================

/// EVEX broadcast mode encoding with proper N values.
/// Controls how a single memory element is broadcast to all vector lanes.
pub mod evex_broadcast_encoding {
    use super::EvexBroadcast;

    /// Get the N value (element count in source) for a broadcast mode.
    /// Based on vector length and element size:
    /// - {1to2}: VL/2 elements, N=8 for 128-bit, N=16 for 256-bit, N=32 for 512-bit
    /// - {1to4}: VL/4 elements, N=4 for 128-bit, N=8 for 256-bit, N=16 for 512-bit
    /// - {1to8}: VL/8 elements, N=2 for 128-bit, N=4 for 256-bit, N=8 for 512-bit
    /// - {1to16}: VL/16 elements, N=1 for 128-bit, N=2 for 256-bit, N=4 for 512-bit
    /// - {1to32}: VL/32 elements, N=1 for 256-bit, N=2 for 512-bit
    pub fn element_count(broadcast: EvexBroadcast, vector_len_bits: u16) -> u8 {
        let vl_bytes = vector_len_bits / 8;
        match broadcast {
            EvexBroadcast::None => vl_bytes as u8,
            EvexBroadcast::Broadcast1To2 => 2,
            EvexBroadcast::Broadcast1To4 => 4,
            EvexBroadcast::Broadcast1To8 => 8,
            EvexBroadcast::Broadcast1To16 => 16,
            EvexBroadcast::Broadcast1To32 => 32,
        }
    }

    /// Get the element size in bytes for a broadcast mode.
    /// For broadcast {1toN}, the source element size = vector_len / N.
    pub fn element_size_bytes(broadcast: EvexBroadcast, vector_len_bits: u16) -> u8 {
        let count = element_count(broadcast, vector_len_bits);
        if count == 0 {
            return 0;
        }
        (vector_len_bits / 8) as u8 / count
    }

    /// Whether a given broadcast mode and vector length is valid.
    pub fn is_valid_broadcast(broadcast: EvexBroadcast, vector_len_bits: u16) -> bool {
        match broadcast {
            EvexBroadcast::None => true,
            EvexBroadcast::Broadcast1To2 => vector_len_bits >= 128,
            EvexBroadcast::Broadcast1To4 => vector_len_bits >= 128,
            EvexBroadcast::Broadcast1To8 => vector_len_bits >= 256,
            EvexBroadcast::Broadcast1To16 => vector_len_bits >= 256,
            EvexBroadcast::Broadcast1To32 => vector_len_bits == 512,
        }
    }

    /// Get the compressed displacement N multiplier for a broadcast mode.
    /// For broadcast, the memory operand is a single element, so N = element_size.
    pub fn broadcast_disp_multiplier(broadcast: EvexBroadcast, vector_len_bits: u16) -> u8 {
        if broadcast == EvexBroadcast::None {
            return 64; // default full
        }
        element_size_bytes(broadcast, vector_len_bits)
    }

    /// Convert broadcast N value to the EVEX b' bit.
    /// b'=1 for broadcast, b'=0 for no broadcast.
    pub fn to_b_bit(broadcast: EvexBroadcast) -> bool {
        broadcast.is_broadcast()
    }

    /// String representation of broadcast.
    pub fn to_string(broadcast: EvexBroadcast) -> &'static str {
        match broadcast {
            EvexBroadcast::None => "",
            EvexBroadcast::Broadcast1To2 => "{1to2}",
            EvexBroadcast::Broadcast1To4 => "{1to4}",
            EvexBroadcast::Broadcast1To8 => "{1to8}",
            EvexBroadcast::Broadcast1To16 => "{1to16}",
            EvexBroadcast::Broadcast1To32 => "{1to32}",
        }
    }
}

// ============================================================================
// EVEX Rounding Mode Encoding
// ============================================================================

/// EVEX rounding mode encoding for FP instructions.
/// The rounding mode is encoded in the EVEX LL field (bits 5-4 of P2 byte)
/// when b'=1 (suppress-all-exceptions SAE or rounding override).
pub mod evex_rounding_encoding {
    use super::EvexRounding;

    /// Convert rounding mode to EVEX RC bits (encoded in LL field).
    ///
    /// Encoding per Intel SDM:
    ///   {rn-sae} → RC=0 (round to nearest)
    ///   {rd-sae} → RC=1 (round toward -inf)
    ///   {ru-sae} → RC=2 (round toward +inf)
    ///   {rz-sae} → RC=3 (round toward zero)
    ///   {sae}    → SAE=1 with RC=0 (no rounding change, suppress all exceptions)
    pub fn to_rc_bits(rounding: EvexRounding) -> u8 {
        match rounding {
            EvexRounding::None => 0,
            EvexRounding::RnSae => 0,
            EvexRounding::RdSae => 1,
            EvexRounding::RuSae => 2,
            EvexRounding::RzSae => 3,
            EvexRounding::Sae => 0,
        }
    }

    /// Get the SAE (Suppress All Exceptions) flag.
    /// SAE=1 when any {sae} rounding mode is specified.
    pub fn has_sae(rounding: EvexRounding) -> bool {
        matches!(
            rounding,
            EvexRounding::RnSae
                | EvexRounding::RdSae
                | EvexRounding::RuSae
                | EvexRounding::RzSae
                | EvexRounding::Sae
        )
    }

    /// Check if rounding mode has an explicit rounding direction change
    /// (not just SAE).
    pub fn has_explicit_rc(rounding: EvexRounding) -> bool {
        matches!(
            rounding,
            EvexRounding::RnSae | EvexRounding::RdSae | EvexRounding::RuSae | EvexRounding::RzSae
        )
    }

    /// Encode rounding mode into LL field (2 bits).
    /// When combined with L' bit for vector length, the full L'L encoding:
    ///   00 = 128-bit (or rounding mode RN-SAE)
    ///   01 = 256-bit (or rounding mode RD-SAE)
    ///   10 = 512-bit (or rounding mode RU-SAE)
    ///   11 = reserved (or rounding mode RZ-SAE)
    pub fn encode_ll_for_rounding(rounding: EvexRounding) -> u8 {
        to_rc_bits(rounding) & 0x3
    }

    /// String representation of rounding mode.
    pub fn to_string(rounding: EvexRounding) -> &'static str {
        match rounding {
            EvexRounding::None => "",
            EvexRounding::RnSae => "{rn-sae}",
            EvexRounding::RdSae => "{rd-sae}",
            EvexRounding::RuSae => "{ru-sae}",
            EvexRounding::RzSae => "{rz-sae}",
            EvexRounding::Sae => "{sae}",
        }
    }

    /// Map from string suffix to rounding mode.
    pub fn from_suffix(s: &str) -> Option<EvexRounding> {
        match s {
            "rn-sae" => Some(EvexRounding::RnSae),
            "rd-sae" => Some(EvexRounding::RdSae),
            "ru-sae" => Some(EvexRounding::RuSae),
            "rz-sae" => Some(EvexRounding::RzSae),
            "sae" => Some(EvexRounding::Sae),
            _ => None,
        }
    }
}

// ============================================================================
// EVEX Opmask Register Encoding
// ============================================================================

/// EVEX opmask register encoding.
/// The aaa field (bits 2-0 of P2 byte) selects the mask register.
pub mod evex_opmask_encoding {
    /// Map opmask register number to EVEX aaa field.
    /// k0 (no mask) → aaa=0
    /// k1 → aaa=1
    /// ...
    /// k7 → aaa=7
    pub fn to_aaa(mask_reg: u8) -> u8 {
        mask_reg & 0x7
    }

    /// Map EVEX aaa field back to opmask register.
    /// aaa=0 → k0 (which means "no masking")
    /// aaa=1 → k1, ..., aaa=7 → k7
    pub fn from_aaa(aaa: u8) -> u8 {
        aaa & 0x7
    }

    /// Opmask register name strings.
    pub fn reg_name(reg: u8) -> &'static str {
        match reg & 0x7 {
            0 => "k0",
            1 => "k1",
            2 => "k2",
            3 => "k3",
            4 => "k4",
            5 => "k5",
            6 => "k6",
            7 => "k7",
            _ => "k0",
        }
    }

    /// Whether a given opmask register value implies active masking.
    /// k0 is the "no mask" register.
    pub fn has_active_mask(mask_reg: u8) -> bool {
        (mask_reg & 0x7) != 0
    }

    /// Check if an opmask register is valid for AVX-512.
    pub fn is_valid_opmask(reg: u8) -> bool {
        (reg & 0xF8) == 0
    }
}

// ============================================================================
// EVEX Zeroing Merge (z bit)
// ============================================================================

/// EVEX zeroing merge encoding.
/// The z bit (bit 7 of P2 byte) controls how masked elements are handled:
///   z=1: {z} merge on zero — masked elements become 0
///   z=0: merge — masked elements retain destination value
pub mod evex_zeroing_encoding {
    /// Check if {z} zeroing is specified.
    pub fn has_zeroing(z: bool) -> bool {
        z
    }

    /// Zeroing only applies when there is an active mask.
    /// If no mask (k0), zeroing is silently ignored.
    pub fn effective_zeroing(z: bool, has_mask: bool) -> bool {
        z && has_mask
    }

    /// String representation of zeroing.
    pub fn to_string(z: bool) -> &'static str {
        if z {
            "{z}"
        } else {
            ""
        }
    }
}

// ============================================================================
// EVEX Vector Length Encoding (L'L)
// ============================================================================

/// EVEX vector length encoding.
/// The L'L field (bits 6-5 of P2 byte) encodes the vector length:
///   00 = 128-bit (L'=0, L=0)
///   01 = 256-bit (L'=0, L=1)
///   10 = 512-bit (L'=1, L=0)
///   11 = reserved
///
/// When rounding mode is active (b'=1), L'L encodes rounding control instead.
pub mod evex_vector_length {
    /// Encode vector length in bits to L'L field.
    pub fn encode(vl_bits: u16) -> u8 {
        match vl_bits {
            128 => 0b00,
            256 => 0b01,
            512 => 0b10,
            _ => 0b00, // default to 128-bit
        }
    }

    /// Decode L'L field to vector length in bits.
    pub fn decode(ll: u8) -> u16 {
        match ll & 0x3 {
            0b00 => 128,
            0b01 => 256,
            0b10 => 512,
            _ => 128,
        }
    }

    /// Get the L' (bit 1 of LL) and L (bit 0 of LL) bits separately.
    pub fn to_l_prime(ll: u8) -> bool {
        (ll >> 1) & 1 != 0
    }

    pub fn to_l(ll: u8) -> bool {
        ll & 1 != 0
    }

    /// Used for VEX 2-byte/3-byte: L=0 for 128-bit, L=1 for 256-bit.
    pub fn vex_l_bit(vl_bits: u16) -> bool {
        vl_bits >= 256
    }

    /// Whether the given vector length is a valid EVEX encoding.
    pub fn is_valid_evex_vl(vl_bits: u16) -> bool {
        matches!(vl_bits, 128 | 256 | 512)
    }

    /// Get vector length string.
    pub fn to_string(vl_bits: u16) -> &'static str {
        match vl_bits {
            128 => "xmm",
            256 => "ymm",
            512 => "zmm",
            _ => "unknown",
        }
    }
}

// ============================================================================
// Complete VEX 3-Byte Encoding with All Field Combinations
// ============================================================================

/// Full VEX 3-byte prefix encoder with all field combinations.
pub mod vex_full_encoder {
    /// Build a 3-byte VEX prefix with explicit control over every field.
    ///
    /// VEX 3-byte format:
    ///   Byte 0: 0xC4 (fixed)
    ///   Byte 1: [~R(1) | ~X(1) | ~B(1) | mmmmm(5)]
    ///   Byte 2: [W(1) | ~vvvv(4) | L(1) | pp(2)]
    ///
    /// Where:
    ///   ~R, ~X, ~B: 1's complement of REX.R, REX.X, REX.B
    ///   mmmmm: opcode map selector (1=0F, 2=0F38, 3=0F3A)
    ///   W: operand size (0=default, 1=64-bit)
    ///   ~vvvv: 1's complement of additional source register
    ///   L: vector length (0=128-bit, 1=256-bit)
    ///   pp: implied mandatory prefix (0=none, 1=66, 2=F3, 3=F2)
    pub fn build_full(
        r: bool,
        x: bool,
        b: bool,
        mmmmm: u8,
        w: bool,
        vvvv: u8,
        l: bool,
        pp: u8,
    ) -> [u8; 3] {
        let byte1 = ((!r as u8) << 7) | ((!x as u8) << 6) | ((!b as u8) << 5) | (mmmmm & 0x1F);
        let byte2 = ((w as u8) << 7) | ((!vvvv & 0xF) << 3) | ((l as u8) << 2) | (pp & 0x3);
        [0xC4, byte1, byte2]
    }

    /// VEX opcode map constants.
    pub mod vex_map {
        pub const MAP_NONE: u8 = 0;
        pub const MAP_0F: u8 = 1;
        pub const MAP_0F38: u8 = 2;
        pub const MAP_0F3A: u8 = 3;
    }

    /// VEX mandatory prefix constants (pp field).
    pub mod vex_pp {
        pub const PP_NONE: u8 = 0;
        pub const PP_66: u8 = 1;
        pub const PP_F3: u8 = 2;
        pub const PP_F2: u8 = 3;
    }

    /// Decode a 3-byte VEX prefix from raw bytes.
    /// Returns the individual fields.
    pub fn decode_vex3(bytes: &[u8]) -> Option<(bool, bool, bool, u8, bool, u8, bool, u8)> {
        if bytes.len() < 3 || bytes[0] != 0xC4 {
            return None;
        }
        let byte1 = bytes[1];
        let byte2 = bytes[2];
        let r = (byte1 >> 7) & 1 == 0;
        let x = (byte1 >> 6) & 1 == 0;
        let b = (byte1 >> 5) & 1 == 0;
        let mmmmm = byte1 & 0x1F;
        let w = (byte2 >> 7) & 1 != 0;
        let vvvv = !((byte2 >> 3) & 0xF) & 0xF;
        let l = (byte2 >> 2) & 1 != 0;
        let pp = byte2 & 0x3;
        Some((r, x, b, mmmmm, w, vvvv, l, pp))
    }

    /// The complete VEX field set as a struct.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub struct VexFields {
        pub r: bool,
        pub x: bool,
        pub b: bool,
        pub mmmmm: u8,
        pub w: bool,
        pub vvvv: u8,
        pub l: bool,
        pub pp: u8,
    }

    impl VexFields {
        pub fn encode_3byte(&self) -> [u8; 3] {
            build_full(
                self.r, self.x, self.b, self.mmmmm, self.w, self.vvvv, self.l, self.pp,
            )
        }

        /// Get the effective register number from ~R, ~X, ~B, ~vvvv fields.
        pub fn effective_reg_r(&self, reg: u8) -> u8 {
            if self.r {
                reg | 0x8
            } else {
                reg & 0x7
            }
        }

        pub fn effective_reg_x(&self, idx: u8) -> u8 {
            if self.x {
                idx | 0x8
            } else {
                idx & 0x7
            }
        }

        pub fn effective_reg_b(&self, base: u8) -> u8 {
            if self.b {
                base | 0x8
            } else {
                base & 0x7
            }
        }
    }
}

// ============================================================================
// Complete XOP Encoding for AMD-Specific Instructions
// ============================================================================

/// Extended XOP encoder with full instruction map.
/// AMD XOP instructions use opcode map 8, 9, or 10 with various opcodes.
pub mod xop_full_encoder {
    /// XOP opcode table: maps XOP opcode to mnemonic.
    pub mod xop_opcodes {
        // XOP map 8: horizontal integer operations
        pub const VPHADDBD: u8 = 0xC2;
        pub const VPHADDBQ: u8 = 0xC3;
        pub const VPHADDWD: u8 = 0xC6;
        pub const VPHADDWQ: u8 = 0xC7;
        pub const VPHADDDQ: u8 = 0xCB;
        pub const VPHADDUBD: u8 = 0xD2;
        pub const VPHADDUBQ: u8 = 0xD3;
        pub const VPHADDUWD: u8 = 0xD6;
        pub const VPHADDUWQ: u8 = 0xD7;
        pub const VPHADDUDQ: u8 = 0xDB;
        pub const VPHSUBBW: u8 = 0xE2;
        pub const VPHSUBDQ: u8 = 0xE3;
        pub const VPHSUBWD: u8 = 0xE6;
        pub const VPROTB: u8 = 0x90;
        pub const VPROTW: u8 = 0x91;
        pub const VPROTD: u8 = 0x92;
        pub const VPROTQ: u8 = 0x93;
        pub const VPMACSSWW: u8 = 0x95;
        pub const VPMACSSWD: u8 = 0x96;
        pub const VPMACSSDQL: u8 = 0x9E;
        pub const VPMACSSDQH: u8 = 0x9F;
        pub const VPMACSSDD: u8 = 0x9C;
        pub const VPMACSWW: u8 = 0xA5;
        pub const VPMACSWD: u8 = 0xA6;
        pub const VPMACSDQL: u8 = 0xAE;
        pub const VPMACSDQH: u8 = 0xAF;
        pub const VPMACSDD: u8 = 0xAC;
        pub const VPMADCSSWD: u8 = 0xB6;
        pub const VPMADCSWD: u8 = 0xC6;

        // XOP map 9: horizontal shift/rotate
        pub const VPSHAB: u8 = 0x98;
        pub const VPSHAW: u8 = 0x99;
        pub const VPSHAD: u8 = 0x9A;
        pub const VPSHAQ: u8 = 0x9B;
        pub const VPSHLB: u8 = 0x94;
        pub const VPSHLW: u8 = 0x95;
        pub const VPSHLD: u8 = 0x96;
        pub const VPSHLQ: u8 = 0x97;

        // XOP map 10: floating-point
        pub const VFRCZPS: u8 = 0x80;
        pub const VFRCZPD: u8 = 0x81;
        pub const VFRCZSS: u8 = 0x82;
        pub const VFRCZSD: u8 = 0x83;
        pub const VPCMOV: u8 = 0xA2;
        pub const VPPERM: u8 = 0xA3;
        pub const VPCOMB: u8 = 0xCC;
        pub const VPCOMW: u8 = 0xCD;
        pub const VPCOMD: u8 = 0xCE;
        pub const VPCOMQ: u8 = 0xCF;
        pub const VPCOMUB: u8 = 0xEC;
        pub const VPCOMUW: u8 = 0xED;
        pub const VPCOMUD: u8 = 0xEE;
        pub const VPCOMUQ: u8 = 0xEF;
    }

    /// Map XOP opcode to string mnemonic.
    pub fn xop_mnemonic(opcode: u8, map: u8) -> Option<&'static str> {
        match (map, opcode) {
            (8, 0x90) => Some("vprotb"),
            (8, 0x91) => Some("vprotw"),
            (8, 0x92) => Some("vprotd"),
            (8, 0x93) => Some("vprotq"),
            (8, 0x95) => Some("vpmacssww"),
            (8, 0x96) => Some("vpmacsswd"),
            (8, 0x9C) => Some("vpmacssdd"),
            (8, 0x9E) => Some("vpmacssdql"),
            (8, 0x9F) => Some("vpmacssdqh"),
            (8, 0xA5) => Some("vpmacsww"),
            (8, 0xA6) => Some("vpmacswd"),
            (8, 0xAC) => Some("vpmacsdd"),
            (8, 0xAE) => Some("vpmacsdql"),
            (8, 0xAF) => Some("vpmacsdqh"),
            (8, 0xB6) => Some("vpmadcsswd"),
            (8, 0xC2) => Some("vphaddbd"),
            (8, 0xC3) => Some("vphaddbq"),
            (8, 0xC6) => Some("vphaddwd"),
            (8, 0xC7) => Some("vphaddwq"),
            (8, 0xCB) => Some("vphadddq"),
            (8, 0xD2) => Some("vphaddubd"),
            (8, 0xD3) => Some("vphaddubq"),
            (8, 0xD6) => Some("vphadduwd"),
            (8, 0xD7) => Some("vphadduwq"),
            (8, 0xDB) => Some("vphaddudq"),
            (8, 0xE2) => Some("vphsubbw"),
            (8, 0xE3) => Some("vphsubdq"),
            (8, 0xE6) => Some("vphsubwd"),
            (9, 0x94) => Some("vpshlb"),
            (9, 0x95) => Some("vpshlw"),
            (9, 0x96) => Some("vpshld"),
            (9, 0x97) => Some("vpshlq"),
            (9, 0x98) => Some("vpshab"),
            (9, 0x99) => Some("vpshaw"),
            (9, 0x9A) => Some("vpshad"),
            (9, 0x9B) => Some("vpshaq"),
            (10, 0x80) => Some("vfrcsps"),
            (10, 0x81) => Some("vfrcspd"),
            (10, 0x82) => Some("vfrcsss"),
            (10, 0x83) => Some("vfrcssd"),
            (10, 0xA2) => Some("vpcmov"),
            (10, 0xA3) => Some("vpperm"),
            (10, 0xCC) => Some("vpcomb"),
            (10, 0xCD) => Some("vpcomw"),
            (10, 0xCE) => Some("vpcomd"),
            (10, 0xCF) => Some("vpcomq"),
            (10, 0xEC) => Some("vpcomub"),
            (10, 0xED) => Some("vpcomuw"),
            (10, 0xEE) => Some("vpcomud"),
            (10, 0xEF) => Some("vpcomuq"),
            _ => None,
        }
    }
}

// ============================================================================
// 3DNow! Legacy Encoding
// ============================================================================

/// AMD 3DNow! instruction encoding.
/// 3DNow! uses: 0F 0F prefix + ModR/M + immediate opcode suffix byte.
pub mod tdnow_encoder {
    /// 3DNow! opcode suffix bytes (the byte after ModR/M).
    pub mod tdnow_opcodes {
        pub const PI2FD: u8 = 0x0D;
        pub const PI2FW: u8 = 0x0C;
        pub const PF2ID: u8 = 0x1D;
        pub const PF2IW: u8 = 0x1C;
        pub const PFACC: u8 = 0xAE;
        pub const PFADD: u8 = 0x9E;
        pub const PFCMPEQ: u8 = 0xB0;
        pub const PFCMPGE: u8 = 0x90;
        pub const PFCMPGT: u8 = 0xA0;
        pub const PFMAX: u8 = 0xA4;
        pub const PFMIN: u8 = 0x94;
        pub const PFMUL: u8 = 0xB4;
        pub const PFNACC: u8 = 0x8A;
        pub const PFPNACC: u8 = 0x8E;
        pub const PFRCP: u8 = 0x96;
        pub const PFRCPIT1: u8 = 0xA6;
        pub const PFRCPIT2: u8 = 0xB6;
        pub const PFRSQIT1: u8 = 0xA7;
        pub const PFRSQRT: u8 = 0x97;
        pub const PFSUB: u8 = 0x9A;
        pub const PFSUBR: u8 = 0xAA;
        pub const PMULHRW: u8 = 0xB7;
        pub const PAVGUSB: u8 = 0xBF;
        pub const FEMMS: u8 = 0x0E;
        pub const PREFETCH: u8 = 0x0D;
        pub const PREFETCHW: u8 = 0x0D; // same opcode, different ModR/M
    }

    /// Encode a 3DNow! instruction.
    /// Format: [0F 0F] [ModR/M] [immediate opcode]
    pub fn encode(mm_reg1: u8, mm_reg2: u8, tdnow_opcode: u8) -> [u8; 4] {
        let modrm = 0xC0 | ((mm_reg2 & 0x7) << 3) | (mm_reg1 & 0x7);
        [0x0F, 0x0F, modrm, tdnow_opcode]
    }

    /// Encode FEMMS (fast EMMS) — just 0F 0E.
    pub fn encode_femms() -> [u8; 2] {
        [0x0F, 0x0E]
    }

    /// Check if an 0F 0F sequence starts a 3DNow! instruction.
    pub fn is_tdnow_prefix(b0: u8, b1: u8) -> bool {
        b0 == 0x0F && b1 == 0x0F
    }

    /// Map 3DNow! opcode suffix to mnemonic.
    pub fn tdnow_mnemonic(opcode: u8) -> Option<&'static str> {
        match opcode {
            0x0C => Some("pi2fw"),
            0x0D => Some("pi2fd"),
            0x1C => Some("pf2iw"),
            0x1D => Some("pf2id"),
            0x8A => Some("pfnacc"),
            0x8E => Some("pfpnacc"),
            0x90 => Some("pfcmpge"),
            0x94 => Some("pfmin"),
            0x96 => Some("pfrcp"),
            0x97 => Some("pfrsqrt"),
            0x9A => Some("pfsub"),
            0x9E => Some("pfadd"),
            0xA0 => Some("pfcmpgt"),
            0xA4 => Some("pfmax"),
            0xA6 => Some("pfrcpit1"),
            0xA7 => Some("pfrsqit1"),
            0xAA => Some("pfsubr"),
            0xAE => Some("pfacc"),
            0xB0 => Some("pfcmpeq"),
            0xB4 => Some("pfmul"),
            0xB6 => Some("pfrcpit2"),
            0xB7 => Some("pmulhrw"),
            0xBF => Some("pavgusb"),
            0x0E => Some("femms"),
            _ => None,
        }
    }
}

// ============================================================================
// Complete Immediate Size Table Per Opcode
// ============================================================================

/// Immediate size lookup for x86 instructions.
/// Maps opcode to the size of its immediate operand.
pub mod immediate_size_table {
    /// Immediate size in bytes.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub enum ImmSize {
        None,
        Imm8,
        Imm16,
        Imm32,
        Imm64,
        Imm8SignExt,
    }

    /// Default immediate sizes for common opcode groups.
    /// Returns the immediate size based on opcode byte.
    pub fn size_for_opcode(opcode: u8, has_rex_w: bool) -> ImmSize {
        match opcode {
            // Immediate ALU operations with imm8
            0x6A => ImmSize::Imm8, // PUSH imm8
            0x6B => ImmSize::Imm8, // IMUL r, r/m, imm8
            0x80 => ImmSize::Imm8, // Group 1 imm8
            0x82 => ImmSize::Imm8, // Group 1 imm8 (undocumented)
            0x83 => ImmSize::Imm8, // Group 1 imm8
            0xA8 => ImmSize::Imm8, // TEST AL, imm8
            0xC0 => ImmSize::Imm8, // Group 2 shift imm8
            0xC1 => ImmSize::Imm8, // Group 2 shift imm8 (32-bit)
            0xC6 => ImmSize::Imm8, // MOV r/m8, imm8

            // Immediate ALU operations with imm16/imm32/imm64
            0x68 => {
                if has_rex_w {
                    ImmSize::Imm64
                } else {
                    ImmSize::Imm32
                }
            }
            0x69 => ImmSize::Imm32, // IMUL r, r/m, imm32
            0x81 => {
                if has_rex_w {
                    ImmSize::Imm32
                } else {
                    ImmSize::Imm32
                }
            }
            0xB8..=0xBF => {
                if has_rex_w {
                    ImmSize::Imm64
                } else {
                    ImmSize::Imm32
                }
            }
            0xC7 => {
                if has_rex_w {
                    ImmSize::Imm32
                } else {
                    ImmSize::Imm32
                }
            }

            // AL/AX/EAX/RAX immediate forms
            0x04 => ImmSize::Imm8, // ADD AL, imm8
            0x05 => {
                if has_rex_w {
                    ImmSize::Imm32
                } else {
                    ImmSize::Imm32
                }
            }
            0x0C => ImmSize::Imm8, // OR AL, imm8
            0x0D => {
                if has_rex_w {
                    ImmSize::Imm32
                } else {
                    ImmSize::Imm32
                }
            }
            0x14 => ImmSize::Imm8, // ADC AL, imm8
            0x15 => {
                if has_rex_w {
                    ImmSize::Imm32
                } else {
                    ImmSize::Imm32
                }
            }
            0x1C => ImmSize::Imm8, // SBB AL, imm8
            0x1D => {
                if has_rex_w {
                    ImmSize::Imm32
                } else {
                    ImmSize::Imm32
                }
            }
            0x24 => ImmSize::Imm8, // AND AL, imm8
            0x25 => {
                if has_rex_w {
                    ImmSize::Imm32
                } else {
                    ImmSize::Imm32
                }
            }
            0x2C => ImmSize::Imm8, // SUB AL, imm8
            0x2D => {
                if has_rex_w {
                    ImmSize::Imm32
                } else {
                    ImmSize::Imm32
                }
            }
            0x34 => ImmSize::Imm8, // XOR AL, imm8
            0x35 => {
                if has_rex_w {
                    ImmSize::Imm32
                } else {
                    ImmSize::Imm32
                }
            }
            0x3C => ImmSize::Imm8, // CMP AL, imm8
            0x3D => {
                if has_rex_w {
                    ImmSize::Imm32
                } else {
                    ImmSize::Imm32
                }
            }

            // Jump/Call with immediate offset
            0xE8 | 0xE9 => ImmSize::Imm32, // CALL/JMP rel32
            0xEB => ImmSize::Imm8,         // JMP rel8
            0x70..=0x7F => ImmSize::Imm8,  // Jcc rel8
            0xE0..=0xE3 => ImmSize::Imm8,  // LOOPcc rel8

            // Enter with two immediates
            0xC8 => ImmSize::Imm16, // ENTER imm16, imm8

            // Return with immediate
            0xC2 | 0xCA => ImmSize::Imm16, // RET imm16

            // INT
            0xCC => ImmSize::None, // INT3 (no immediate)
            0xCD => ImmSize::Imm8, // INT imm8

            // IN/OUT
            0xE4 | 0xE6 => ImmSize::Imm8, // IN AL/AX/EAX, imm8
            0xE5 | 0xE7 => ImmSize::Imm8, // OUT imm8, AL/AX/EAX

            // AAM/AAD
            0xD4 => ImmSize::Imm8, // AAM imm8
            0xD5 => ImmSize::Imm8, // AAD imm8

            _ => ImmSize::None,
        }
    }

    /// Get the encoded size in bytes.
    pub fn size_in_bytes(size: ImmSize) -> u8 {
        match size {
            ImmSize::None => 0,
            ImmSize::Imm8 | ImmSize::Imm8SignExt => 1,
            ImmSize::Imm16 => 2,
            ImmSize::Imm32 => 4,
            ImmSize::Imm64 => 8,
        }
    }

    /// Check if the immediate is sign-extended.
    pub fn is_sign_extended(size: ImmSize) -> bool {
        matches!(size, ImmSize::Imm8SignExt)
    }
}

// ============================================================================
// Sign Extension Handling for 8-bit Immediates
// ============================================================================

/// Sign extension helpers for x86 immediates.
/// Many x86 instructions take an 8-bit immediate and sign-extend it
/// to the operand size (16, 32, or 64 bits).
pub mod sign_extension {
    /// Sign-extend an 8-bit value to 16 bits.
    pub fn ext8_to_16(value: i8) -> i16 {
        value as i16
    }

    /// Sign-extend an 8-bit value to 32 bits.
    pub fn ext8_to_32(value: i8) -> i32 {
        value as i32
    }

    /// Sign-extend an 8-bit value to 64 bits.
    pub fn ext8_to_64(value: i8) -> i64 {
        value as i64
    }

    /// Sign-extend a 16-bit value to 32 bits.
    pub fn ext16_to_32(value: i16) -> i32 {
        value as i32
    }

    /// Sign-extend a 16-bit value to 64 bits.
    pub fn ext16_to_64(value: i16) -> i64 {
        value as i64
    }

    /// Sign-extend a 32-bit value to 64 bits.
    pub fn ext32_to_64(value: i32) -> i64 {
        value as i64
    }

    /// Sign-extend an immediate based on the required destination size.
    pub fn sign_extend_imm(value: i64, dest_size_bits: u8) -> i64 {
        match dest_size_bits {
            8 => (value as i8) as i64,
            16 => (value as i16) as i64,
            32 => (value as i32) as i64,
            64 => value,
            _ => value,
        }
    }

    /// Check if a value fits in a sign-extended imm8 for the given operand size.
    /// For example, for 32-bit operation, an imm8 of -1 sign-extends to 0xFFFFFFFF.
    pub fn fits_in_sign_ext_imm8(value: i64, operand_size_bits: u8) -> bool {
        let truncated = sign_extend_imm(value, operand_size_bits);
        let back_to_8 = (truncated as i8) as i64;
        sign_extend_imm(back_to_8, operand_size_bits) == truncated
    }

    /// Check if an imm32 sign-extends correctly to imm64.
    pub fn fits_in_sign_ext_imm32(value: i64) -> bool {
        (value as i32) as i64 == value
    }
}

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

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

    fn make_subtarget() -> X86Subtarget {
        X86Subtarget::new("x86_64-unknown-none", "generic", "")
    }

    fn make_encoder() -> X86FullMCEncoder {
        X86FullMCEncoder::new(X86Mode::Mode64, make_subtarget())
    }

    // === Legacy encoding tests ===

    #[test]
    fn test_encode_nop() {
        let mut enc = make_encoder();
        let bytes = enc.encode_nop();
        assert!(!bytes.is_empty(), "NOP should produce at least 1 byte");
    }

    #[test]
    fn test_encode_ret() {
        let mut enc = make_encoder();
        let bytes = enc.encode_ret();
        assert!(!bytes.is_empty(), "RET should produce at least 1 byte");
    }

    #[test]
    fn test_encode_call() {
        let mut enc = make_encoder();
        let bytes = enc.encode_call(0x12345678);
        assert_eq!(bytes[0], 0xE8);
        assert_eq!(&bytes[1..5], &0x12345678u32.to_le_bytes());
    }

    #[test]
    fn test_encode_mov_rax_rcx() {
        let mut enc = make_encoder();
        let bytes = enc.encode_mov_rr(RAX, RCX);
        // MOV r64, r/m64: REX.W + 8B /r
        // REX.W
        assert_eq!(bytes[1], 0x89); // MOV r/m64, r64
        assert_eq!(bytes[2], 0xC8); // ModR/M: mod=3, reg=RCX(1), rm=RAX(0)
    }

    #[test]
    fn test_encode_add_rax_imm5() {
        let mut enc = make_encoder();
        let bytes = enc.encode_add_ri(RAX, 5);
        assert!(bytes.len() >= 3, "ADD RAX, 5 should be 3+ bytes");
    }

    #[test]
    fn test_encode_sub_rax_rdx() {
        let mut enc = make_encoder();
        let bytes = enc.encode_sub_rr(RAX, RDX);
        assert!(bytes.len() >= 2);
    }

    #[test]
    fn test_encode_and_rax_rbx() {
        let mut enc = make_encoder();
        let bytes = enc.encode_and_rr(RAX, RBX);
        assert!(bytes.len() >= 2);
    }

    #[test]
    fn test_encode_xor_rax_rax() {
        let mut enc = make_encoder();
        let bytes = enc.encode_xor_rr(RAX, RAX);
        assert!(bytes.len() >= 2);
    }

    #[test]
    fn test_encode_cmp_rax_rcx() {
        let mut enc = make_encoder();
        let bytes = enc.encode_cmp_rr(RAX, RCX);
        assert!(bytes.len() >= 2);
    }

    // === REX tests ===

    #[test]
    fn test_encode_mov_r8_r9() {
        let mut enc = make_encoder();
        let bytes = enc.encode_mov_rr(R8, R9);
        // REX.B (R8) + REX.R (R9) + REX.W = 4D
        assert_eq!(bytes[0], 0x4D); // REX.W + REX.B + REX.R
        assert_eq!(bytes[1], 0x89); // MOV r/m64, r64
                                    // R8=rm=0, R9=reg=1 → ModR/M = 11 001 000 = C8
        assert_eq!(bytes[2], 0xC8);
    }

    #[test]
    fn test_encode_mov_rax_r8() {
        let mut enc = make_encoder();
        let bytes = enc.encode_mov_rr(RAX, R8);
        // REX.R (R8 as reg) + REX.W = 4C
        assert_eq!(bytes[0], 0x4C); // REX.W + REX.R
        assert_eq!(bytes[1], 0x89);
        assert_eq!(bytes[2], 0xC0); // mod=3, reg=R8(0 after rex.r=1 → 8), rm=RAX(0)
    }

    // === Memory operand tests ===

    #[test]
    fn test_encode_mov_from_mem() {
        let mut enc = make_encoder();
        let mem = X86MemOperand::base_disp(RBP, -8);
        let bytes = enc.encode_mov_rm(RAX, mem);
        // REX.W + 8B /r
        // REX.W
        // MOV r64, r/m64
        // ModR/M: mod=01 (disp8), reg=RAX(0), rm=RBP(5) → 45
        assert_eq!(bytes[2], 0x45);
        assert_eq!(bytes[3], 0xF8); // disp8 = -8
    }

    #[test]
    fn test_encode_mov_to_mem() {
        let mut enc = make_encoder();
        let mem = X86MemOperand::base_disp(RSP, 16);
        let bytes = enc.encode_mov_mr(mem, RCX);
        // REX.W
        assert_eq!(bytes[1], 0x89); // MOV r/m64, r64
                                    // ModR/M: mod=01 (disp8), reg=RCX(1), rm=RSP(4) → 4C
                                    // Need SIB for RSP
        assert_eq!(bytes[2], 0x4C);
        // SIB: scale=0, index=4(no index), base=RSP(4) → 24
        assert_eq!(bytes[3], 0x24);
        assert_eq!(bytes[4], 0x10); // disp8 = 16
    }

    #[test]
    fn test_encode_mov_with_index() {
        let mut enc = make_encoder();
        let mem = X86MemOperand::full(RBX, RSI, 4, 0);
        let bytes = enc.encode_mov_rm(RAX, mem);
        // REX.W
        // MOV r64, r/m64
        // ModR/M: mod=00, reg=RAX(0), rm=100(SIB)
        assert_eq!(bytes[2], 0x04);
        // SIB: scale=2(4), index=RSI(6), base=RBX(3) → 73
        assert_eq!(bytes[3], 0x73);
        assert_eq!(bytes.len(), 4);
    }

    // === RIP-relative tests ===

    #[test]
    fn test_encode_rip_relative() {
        let mut enc = make_encoder();
        let mem = X86FullMCEncoder::rip_relative(0x1234);
        let bytes = enc.encode_mov_rm(RAX, mem);
        // ModR/M: mod=00, reg=RAX(0), rm=5(RIP-relative)
        assert_eq!(bytes[2], 0x05);
        // 32-bit displacement
        assert_eq!(&bytes[3..7], &0x1234i32.to_le_bytes());
    }

    // === VEX encoding tests ===

    #[test]
    fn test_encode_vaddps() {
        let mut enc = make_encoder();
        let bytes = enc.encode_vaddps(XMM0, XMM1, XMM2);
        // VEX 3-byte: C4
        assert_eq!(bytes[0], 0xC4);
        // VEX byte 1: ~R=1, ~X=1, ~B=1, mmmmm=1 (0F)
        // vvvv = ~1 = E (XMM1)
        // VEX byte 2: W=0, ~vvvv=E, L=0, pp=0
        assert!(!bytes.is_empty());
        // Opcode: ADDPS = 58
        let opcode_pos = 3;
        // ADDPS opcode
    }

    #[test]
    fn test_encode_aesenc() {
        let mut enc = make_encoder();
        let bytes = enc.encode_aesenc(XMM0, XMM1);
        // 0F 38 DC /r
        assert_eq!(bytes[0], 0x66); // mandatory prefix
        assert_eq!(bytes[1], 0x0F);
        assert_eq!(bytes[2], 0x38);
        assert_eq!(bytes[3], 0xDC);
        // ModR/M: mod=3, reg=XMM1(1), rm=XMM0(0)
        assert_eq!(bytes[4], 0xC8);
    }

    // === EVEX encoding tests ===

    #[test]
    fn test_encode_vpaddd_z() {
        let mut enc = make_encoder();
        let bytes = enc.encode_instruction(
            X86FullOpcode::VPADDD_Z,
            &[
                X86Operand::Reg(ZMM0),
                X86Operand::Reg(ZMM1),
                X86Operand::Reg(ZMM2),
            ],
        );
        // EVEX prefix: 62
        // EVEX prefix
        assert!(bytes.len() >= 6); // prefix(4) + opcode(1-2) + ModR/M(1)
    }

    // === Round-trip tests ===

    #[test]
    fn test_roundtrip_nop() {
        let mut enc = make_encoder();
        let bytes = enc.encode_nop();
        assert!(!bytes.is_empty(), "NOP should produce at least 1 byte");
    }

    #[test]
    fn test_roundtrip_ret() {
        let mut enc = make_encoder();
        let bytes = enc.encode_ret();
        assert!(!bytes.is_empty(), "RET should produce at least 1 byte");
    }

    #[test]
    fn test_roundtrip_mov_rax_rcx() {
        let mut enc = make_encoder();
        let bytes = enc.encode_mov_rr(RAX, RCX);
        // REX.W + MOV r/m64, r64 + ModR/M(reg=RCX, rm=RAX)
        assert!(bytes.len() >= 2);
    }

    #[test]
    fn test_roundtrip_add_rax_rcx() {
        let mut enc = make_encoder();
        let bytes = enc.encode_add_rr(RAX, RCX);
        assert!(bytes.len() >= 2);
    }

    #[test]
    fn test_roundtrip_xor_rax_rax() {
        let mut enc = make_encoder();
        let bytes = enc.encode_xor_rr(RAX, RAX);
        assert!(bytes.len() >= 2);
    }
}