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
//! X86 VEX Prefix Encoding — complete VEX prefix generation, field
//! encoding/decoding, compression (3-byte→2-byte), register restrictions,
//! vector length selection, and instruction length computation for AVX,
//! AVX2, FMA, BMI, and BMI2 instructions.
//!
//! ## VEX Encoding Overview
//!
//! The VEX (Vector Extension) prefix is a multi-byte prefix used by Intel
//! AVX and AVX2 instructions. It replaces the legacy REX prefix and
//! mandatory SIMD prefixes (66/F2/F3) with a more compact encoding,
//! supporting:
//!
//! * **2-byte VEX** (0xC5): For 128-bit instructions with all registers
//!   in the low 8 (XMM0-XMM7 / YMM0-YMM7), no X/B/W bits needed.
//! * **3-byte VEX** (0xC4): For 256-bit instructions, or instructions
//!   needing extended registers (XMM8-XMM15 / YMM8-YMM15), or 64-bit
//!   operand size (W bit).
//!
//! ## VEX Fields
//!
//! | Field  | Bits | Description                                      |
//! |--------|------|--------------------------------------------------|
//! | R      | 1    | 1's complement of REX.R (ModR/M reg extension)   |
//! | X      | 1    | 1's complement of REX.X (SIB index extension)    |
//! | B      | 1    | 1's complement of REX.B (ModR/M r/m extension)   |
//! | mmmmm  | 5    | Opcode map (00001=0F, 00010=0F38, 00011=0F3A)   |
//! | W      | 1    | REX.W (64-bit operand size)                      |
//! | vvvv   | 4    | 1's complement of non-destructive source reg     |
//! | L      | 1    | Vector length (0=128-bit, 1=256-bit)             |
//! | pp     | 2    | Implied mandatory prefix (00=none,01=66,10=F3,11=F2) |
//!
//! ## 2-byte VEX Layout
//! ```
//! Byte 0: [1 1 0 0 0 1 0 1] = 0xC5
//! Byte 1: [R v v v v L p p]
//! ```
//!
//! ## 3-byte VEX Layout
//! ```
//! Byte 0: [1 1 0 0 0 1 0 0] = 0xC4
//! Byte 1: [R X B m m m m m]
//! Byte 2: [W v v v v L p p]
//! ```
//!
//! Clean-room behavioral reconstruction from:
//! - Intel® 64 and IA-32 Architectures Software Developer's Manual, Vol 2A
//! - AMD64 Architecture Programmer's Manual, Volume 3
//! - Zero LLVM source code consultation
//! - Black-box oracle interrogation

use std::fmt;

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    VEX Prefix Constants                                     ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

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

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

/// VEX mmmmm field: opcode map 0F (legacy two-byte escape).
pub const VEX_MMMMM_0F: u8 = 0x01;

/// VEX mmmmm field: opcode map 0F38 (three-byte escape).
pub const VEX_MMMMM_0F38: u8 = 0x02;

/// VEX mmmmm field: opcode map 0F3A (three-byte escape).
pub const VEX_MMMMM_0F3A: u8 = 0x03;

/// VEX pp field: no implied mandatory prefix.
pub const VEX_PP_NONE: u8 = 0x00;

/// VEX pp field: implied 0x66 prefix.
pub const VEX_PP_66: u8 = 0x01;

/// VEX pp field: implied 0xF3 prefix.
pub const VEX_PP_F3: u8 = 0x02;

/// VEX pp field: implied 0xF2 prefix.
pub const VEX_PP_F2: u8 = 0x03;

/// VEX.L = 0: 128-bit vector width.
pub const VEX_L_128: bool = false;

/// VEX.L = 1: 256-bit vector width.
pub const VEX_L_256: bool = true;

/// Maximum number of bits in the inverted register field.
pub const VEX_REG_MASK: u8 = 0x0F;

/// Mask for the upper bit of a register number (bit 3).
pub const VEX_REG_HIGH_BIT: u8 = 0x08;

///  3-byte VEX prefix byte 1 always has bit 7..5 as inverted R/X/B, bits 4..0 as mmmmm
const VEX3_BYTE1_R_MASK: u8 = 0x80;
const VEX3_BYTE1_X_MASK: u8 = 0x40;
const VEX3_BYTE1_B_MASK: u8 = 0x20;
const VEX3_BYTE1_MMMMM_MASK: u8 = 0x1F;

/// 3-byte VEX prefix byte 2 always has W, vvvv, L, pp
const VEX3_BYTE2_W_MASK: u8 = 0x80;
const VEX3_BYTE2_VVVV_MASK: u8 = 0x78;
const VEX3_BYTE2_L_MASK: u8 = 0x04;
const VEX3_BYTE2_PP_MASK: u8 = 0x03;

/// 2-byte VEX prefix byte 1 always has ~R, vvvv, L, pp
const VEX2_BYTE1_R_MASK: u8 = 0x80;
const VEX2_BYTE1_VVVV_MASK: u8 = 0x78;
const VEX2_BYTE1_L_MASK: u8 = 0x04;
const VEX2_BYTE1_PP_MASK: u8 = 0x03;

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    VEX Opcode Map Enumeration                              ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

/// VEX opcode map selector (mmmmm field).
///
/// Determines which opcode table the instruction's opcode byte selects from.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum VexOpcodeMap {
    /// Map 1: 0F escape (two-byte opcodes like ADDPS, ANDPS, etc.)
    Map0F = 0x01,
    /// Map 2: 0F38 escape (three-byte opcodes like AESENC, PSHUFB, etc.)
    Map0F38 = 0x02,
    /// Map 3: 0F3A escape (three-byte opcodes like ROUNDPS, PALIGNR, etc.)
    Map0F3A = 0x03,
}

impl VexOpcodeMap {
    /// Return the mmmmm field value for this opcode map.
    pub const fn mmmmm(&self) -> u8 {
        *self as u8
    }

    /// Create a VexOpcodeMap from raw mmmmm bits.
    pub const fn from_mmmmm(mmmmm: u8) -> Option<Self> {
        match mmmmm {
            0x01 => Some(Self::Map0F),
            0x02 => Some(Self::Map0F38),
            0x03 => Some(Self::Map0F3A),
            _ => None,
        }
    }

    /// Human-readable name for this opcode map.
    pub const fn name(&self) -> &'static str {
        match self {
            Self::Map0F => "0F",
            Self::Map0F38 => "0F38",
            Self::Map0F3A => "0F3A",
        }
    }

    /// Number of legacy prefix escape bytes emitted for this map (when not using VEX).
    pub const fn escape_byte_count(&self) -> u8 {
        match self {
            Self::Map0F => 1,   // 0F
            Self::Map0F38 => 2, // 0F 38
            Self::Map0F3A => 2, // 0F 3A
        }
    }

    /// Return the legacy escape bytes that would be emitted without VEX.
    pub fn escape_bytes(&self) -> Vec<u8> {
        match self {
            Self::Map0F => vec![0x0F],
            Self::Map0F38 => vec![0x0F, 0x38],
            Self::Map0F3A => vec![0x0F, 0x3A],
        }
    }
}

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

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    VEX Mandatory Prefix Enumeration                        ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

/// VEX mandatory prefix encoding (pp field).
///
/// The VEX.pp field encodes the implied mandatory SIMD prefix that would
/// precede the instruction in legacy encoding. AVX encodes this as a 2-bit
/// field rather than emitting actual prefix bytes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum VexMandatoryPrefix {
    /// No mandatory prefix (pp = 00).
    None = 0x00,
    /// 0x66 prefix (pp = 01).
    P66 = 0x01,
    /// 0xF3 prefix (pp = 10).
    PF3 = 0x02,
    /// 0xF2 prefix (pp = 11).
    PF2 = 0x03,
}

impl VexMandatoryPrefix {
    /// Return the pp field bits for this mandatory prefix.
    pub const fn pp_bits(&self) -> u8 {
        *self as u8
    }

    /// Return the legacy prefix byte for this mandatory prefix (if any).
    pub const fn prefix_byte(&self) -> Option<u8> {
        match self {
            Self::None => None,
            Self::P66 => Some(0x66),
            Self::PF3 => Some(0xF3),
            Self::PF2 => Some(0xF2),
        }
    }

    /// Create a VexMandatoryPrefix from pp bits.
    pub const fn from_pp(pp: u8) -> Option<Self> {
        match pp & 0x03 {
            0x00 => Some(Self::None),
            0x01 => Some(Self::P66),
            0x02 => Some(Self::PF3),
            0x03 => Some(Self::PF2),
            _ => None,
        }
    }

    /// Create a VexMandatoryPrefix from a legacy prefix byte.
    pub const fn from_byte(byte: u8) -> Self {
        match byte {
            0x66 => Self::P66,
            0xF3 => Self::PF3,
            0xF2 => Self::PF2,
            _ => Self::None,
        }
    }

    /// Human-readable name.
    pub const fn name(&self) -> &'static str {
        match self {
            Self::None => "none",
            Self::P66 => "66",
            Self::PF3 => "F3",
            Self::PF2 => "F2",
        }
    }
}

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

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    VEX Vector Length Enumeration                           ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

/// VEX.L field encoding — selects vector width.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum VexVectorLength {
    /// 128-bit vectors (XMM registers), L=0.
    #[default]
    L128 = 0,
    /// 256-bit vectors (YMM registers), L=1.
    L256 = 1,
}

impl VexVectorLength {
    /// Return the L bit value.
    pub const fn l_bit(&self) -> bool {
        match self {
            Self::L128 => false,
            Self::L256 => true,
        }
    }

    /// Total vector width in bytes.
    pub const fn width_bytes(&self) -> u8 {
        match self {
            Self::L128 => 16,
            Self::L256 => 32,
        }
    }

    /// Total vector width in bits.
    pub const fn width_bits(&self) -> u16 {
        match self {
            Self::L128 => 128,
            Self::L256 => 256,
        }
    }

    /// Create from L bit value.
    pub const fn from_l_bit(l: bool) -> Self {
        if l {
            Self::L256
        } else {
            Self::L128
        }
    }

    /// XMM/YMM register prefix character.
    pub const fn reg_prefix(&self) -> &'static str {
        match self {
            Self::L128 => "xmm",
            Self::L256 => "ymm",
        }
    }
}

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

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    VEX Register Encoding Helpers                           ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

/// Invert a 4-bit register number for VEX encoding.
///
/// In VEX prefixes, register fields (R, X, B, vvvv) are stored in
/// 1's complement form: the stored value is ~register[3:0].
///
/// # Examples
/// ```
/// assert_eq!(vex_invert_reg(0), 0x0F);  // ~0 = 15
/// assert_eq!(vex_invert_reg(8), 0x07);  // ~8 = 7
/// assert_eq!(vex_invert_reg(15), 0x00); // ~15 = 0
/// ```
#[inline]
pub const fn vex_invert_reg(reg: u8) -> u8 {
    (!reg) & VEX_REG_MASK
}

/// Recover the original register number from its VEX inverted form.
#[inline]
pub const fn vex_recover_reg(inverted: u8) -> u8 {
    (!inverted) & VEX_REG_MASK
}

/// Check if a register requires the VEX.R bit (register number >= 8).
#[inline]
pub const fn vex_reg_needs_r(reg: u8) -> bool {
    (reg & VEX_REG_HIGH_BIT) != 0
}

/// Check if a register requires the VEX.X bit (register number >= 8).
#[inline]
pub const fn vex_reg_needs_x(reg: u8) -> bool {
    (reg & VEX_REG_HIGH_BIT) != 0
}

/// Check if a register requires the VEX.B bit (register number >= 8).
#[inline]
pub const fn vex_reg_needs_b(reg: u8) -> bool {
    (reg & VEX_REG_HIGH_BIT) != 0
}

/// Extract the lower 3 bits of a register number for ModR/M encoding.
#[inline]
pub const fn vex_reg_low3(reg: u8) -> u8 {
    reg & 0x07
}

/// Check if any register in a set needs extended register encoding (>XMM7/YMM7).
#[inline]
pub fn vex_any_extended_reg(regs: &[u8]) -> bool {
    for &r in regs {
        if r >= 8 {
            return true;
        }
    }
    false
}

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    VEX Prefix Configuration                                ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

/// Complete VEX prefix configuration for encoding.
///
/// This struct captures all the fields needed to emit either a 2-byte
/// or 3-byte VEX prefix.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct VexPrefixConfig {
    /// VEX.R: 1's complement of ModR/M reg extension (register >= 8).
    pub r: bool,
    /// VEX.X: 1's complement of SIB index extension (3-byte VEX only).
    pub x: bool,
    /// VEX.B: 1's complement of ModR/M r/m extension (register >= 8).
    pub b: bool,
    /// VEX.W: 64-bit operand size (3-byte VEX only).
    pub w: bool,
    /// VEX.mmmmm: opcode map selector.
    pub mmmmm: u8,
    /// VEX.vvvv: 1's complement of first source register.
    pub vvvv: u8,
    /// VEX.L: vector length (0=128, 1=256).
    pub l: bool,
    /// VEX.pp: implied mandatory prefix.
    pub pp: u8,
}

impl Default for VexPrefixConfig {
    fn default() -> Self {
        Self {
            r: false,
            x: false,
            b: false,
            w: false,
            mmmmm: VEX_MMMMM_0F,
            vvvv: 0,
            l: false,
            pp: VEX_PP_NONE,
        }
    }
}

impl VexPrefixConfig {
    /// Create a new VexPrefixConfig with defaults.
    pub const fn new() -> Self {
        Self {
            r: false,
            x: false,
            b: false,
            w: false,
            mmmmm: VEX_MMMMM_0F,
            vvvv: 0,
            l: false,
            pp: VEX_PP_NONE,
        }
    }

    /// Set the opcode map.
    pub fn with_map(mut self, map: VexOpcodeMap) -> Self {
        self.mmmmm = map.mmmmm();
        self
    }

    /// Set the mandatory prefix.
    pub fn with_prefix(mut self, pfx: VexMandatoryPrefix) -> Self {
        self.pp = pfx.pp_bits();
        self
    }

    /// Set the vector length.
    pub fn with_vector_length(mut self, vl: VexVectorLength) -> Self {
        self.l = vl.l_bit();
        self
    }

    /// Set the destination/non-destructive source register (vvvv).
    pub fn with_vvvv(mut self, reg: u8) -> Self {
        self.vvvv = vex_invert_reg(reg & VEX_REG_MASK);
        self
    }

    /// Set REX.R equivalent from a ModR/M reg field register.
    pub fn with_reg_r(mut self, reg: u8) -> Self {
        self.r = vex_reg_needs_r(reg);
        self
    }

    /// Set REX.X equivalent from an SIB index register.
    pub fn with_reg_x(mut self, reg: u8) -> Self {
        self.x = vex_reg_needs_x(reg);
        self
    }

    /// Set REX.B equivalent from a ModR/M r/m or SIB base register.
    pub fn with_reg_b(mut self, reg: u8) -> Self {
        self.b = vex_reg_needs_b(reg);
        self
    }

    /// Set the W bit for 64-bit operand size.
    pub fn with_w(mut self, w: bool) -> Self {
        self.w = w;
        self
    }

    /// Build config from raw register numbers (not inverted).
    pub fn from_registers(
        map: VexOpcodeMap,
        prefix: VexMandatoryPrefix,
        vl: VexVectorLength,
        vvvv_reg: u8,
        modrm_reg: u8,
        modrm_rm: u8,
        sib_index: Option<u8>,
        w: bool,
    ) -> Self {
        let mut cfg = Self::new()
            .with_map(map)
            .with_prefix(prefix)
            .with_vector_length(vl)
            .with_vvvv(vvvv_reg)
            .with_reg_r(modrm_reg)
            .with_reg_b(modrm_rm)
            .with_w(w);

        if let Some(idx) = sib_index {
            cfg = cfg.with_reg_x(idx);
        }

        cfg
    }

    /// Check if this configuration can be encoded as a 2-byte VEX prefix.
    ///
    /// 2-byte VEX can be used when:
    /// - mmmmm == 1 (opcode map 0F)
    /// - W == 0 (no 64-bit operand size)
    /// - X == 0 (no SIB index extension needed)
    /// - B == 0 (no r/m extension needed)
    /// - R == 0 (no reg extension needed)
    pub fn can_use_2byte_vex(&self) -> bool {
        self.mmmmm == VEX_MMMMM_0F && !self.w && !self.x && !self.b && !self.r
    }

    /// Attempt to compress a 3-byte VEX configuration to 2-byte.
    /// Returns None if compression is not possible.
    pub fn try_compress_to_2byte(&self) -> Option<VexPrefixConfig> {
        if self.can_use_2byte_vex() {
            let mut compressed = *self;
            compressed.x = false;
            compressed.w = false;
            Some(compressed)
        } else {
            None
        }
    }

    /// Returns the number of prefix bytes this configuration will emit.
    pub fn prefix_byte_count(&self) -> u8 {
        if self.can_use_2byte_vex() {
            2
        } else {
            3
        }
    }
}

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    VEX Prefix Builder                                      ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

/// VEX prefix encoder — builds the raw byte sequences for VEX2 and VEX3.
pub struct VexPrefixBuilder;

impl VexPrefixBuilder {
    /// Build a 2-byte VEX prefix: `[C5] [RvvvvLpp]`
    ///
    /// # Arguments
    /// * `r` - Inverted R bit (1 means reg < 8, 0 means reg >= 8 stored as 1's complement)
    /// * `vvvv` - 1's complement of source register
    /// * `l` - Vector length (0=128, 1=256)
    /// * `pp` - Mandatory prefix encoding
    ///
    /// # Example
    /// ```
    /// // VEX2 for vaddps xmm0, xmm1, xmm2: R=1, vvvv=~2, L=0, pp=none
    /// let bytes = VexPrefixBuilder::build_2byte(true, vex_invert_reg(2), false, VEX_PP_NONE);
    /// assert_eq!(bytes[0], 0xC5);
    /// ```
    #[inline]
    pub fn build_2byte(r: bool, vvvv: u8, l: bool, pp: u8) -> [u8; 2] {
        let byte1: u8 = ((!r as u8) << 7)
            | ((vvvv & VEX_REG_MASK) << 3)
            | ((l as u8) << 2)
            | (pp & VEX3_BYTE2_PP_MASK);
        [VEX2_PREFIX, byte1]
    }

    /// Build a 2-byte VEX prefix from a VexPrefixConfig.
    #[inline]
    pub fn build_2byte_from_config(config: &VexPrefixConfig) -> [u8; 2] {
        Self::build_2byte(config.r, config.vvvv, config.l, config.pp)
    }

    /// Build a 3-byte VEX prefix: `[C4] [RXBmmmmm] [WvvvvLpp]`
    #[inline]
    pub fn build_3byte(
        r: bool,
        x: bool,
        b: bool,
        mmmmm: u8,
        w: bool,
        vvvv: u8,
        l: bool,
        pp: u8,
    ) -> [u8; 3] {
        let byte1: u8 = ((!r as u8) << 7)
            | ((!x as u8) << 6)
            | ((!b as u8) << 5)
            | (mmmmm & VEX3_BYTE1_MMMMM_MASK);
        let byte2: u8 = ((w as u8) << 7)
            | ((vvvv & VEX_REG_MASK) << 3)
            | ((l as u8) << 2)
            | (pp & VEX3_BYTE2_PP_MASK);
        [VEX3_PREFIX, byte1, byte2]
    }

    /// Build a 3-byte VEX prefix from a VexPrefixConfig.
    #[inline]
    pub fn build_3byte_from_config(config: &VexPrefixConfig) -> [u8; 3] {
        Self::build_3byte(
            config.r,
            config.x,
            config.b,
            config.mmmmm,
            config.w,
            config.vvvv,
            config.l,
            config.pp,
        )
    }

    /// Build the appropriate VEX prefix (2-byte or 3-byte) from config.
    /// Automatically selects the most compact encoding.
    pub fn build(config: &VexPrefixConfig) -> Vec<u8> {
        if config.can_use_2byte_vex() {
            let bytes = Self::build_2byte_from_config(config);
            bytes.to_vec()
        } else {
            let bytes = Self::build_3byte_from_config(config);
            bytes.to_vec()
        }
    }

    /// Build a 2-byte VEX using register numbers directly (not inverted).
    /// This is a convenience wrapper.
    pub fn build_2byte_from_regs(r_reg: u8, vvvv_reg: u8, l: bool, pp: u8) -> [u8; 2] {
        let r_inv = vex_reg_needs_r(r_reg);
        let vvvv_inv = vex_invert_reg(vvvv_reg);
        Self::build_2byte(r_inv, vvvv_inv, l, pp)
    }

    /// Build a 3-byte VEX using register numbers directly (not inverted).
    /// This is a convenience wrapper.
    pub fn build_3byte_from_regs(
        r_reg: u8,
        x_reg: u8,
        b_reg: u8,
        mmmmm: u8,
        w: bool,
        vvvv_reg: u8,
        l: bool,
        pp: u8,
    ) -> [u8; 3] {
        let r_inv = vex_reg_needs_r(r_reg);
        let x_inv = vex_reg_needs_x(x_reg);
        let b_inv = vex_reg_needs_b(b_reg);
        let vvvv_inv = vex_invert_reg(vvvv_reg);
        Self::build_3byte(r_inv, x_inv, b_inv, mmmmm, w, vvvv_inv, l, pp)
    }
}

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    VEX Prefix Decoder                                      ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

/// Decoded VEX prefix fields — after parsing the raw bytes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct VexDecodedPrefix {
    /// True if the prefix was a 3-byte VEX (0xC4), false if 2-byte (0xC5).
    pub is_3byte: bool,
    /// VEX.R bit (from byte1[7] for 2-byte, byte2[7] for 3-byte), inverted.
    pub r: bool,
    /// VEX.X bit (3-byte VEX only, byte2[6]), inverted.
    pub x: bool,
    /// VEX.B bit (3-byte VEX only, byte2[5]), inverted.
    pub b: bool,
    /// VEX.mmmmm field: opcode map selector.
    pub mmmmm: u8,
    /// VEX.W bit: 64-bit operand size (3-byte VEX only).
    pub w: bool,
    /// VEX.vvvv field: inverted source register.
    pub vvvv: u8,
    /// VEX.L bit: vector length.
    pub l: bool,
    /// VEX.pp field: implied mandatory prefix.
    pub pp: u8,
}

impl VexDecodedPrefix {
    /// Decode a 2-byte VEX prefix from bytes `[0xC5, byte1]`.
    pub fn decode_2byte(vex_byte1: u8) -> Self {
        Self {
            is_3byte: false,
            r: (vex_byte1 & VEX2_BYTE1_R_MASK) == 0,
            x: false,
            b: false,
            mmmmm: VEX_MMMMM_0F, // 2-byte VEX always map 0F
            w: false,            // 2-byte VEX has no W bit
            vvvv: (vex_byte1 >> 3) & VEX_REG_MASK,
            l: (vex_byte1 & VEX2_BYTE1_L_MASK) != 0,
            pp: vex_byte1 & VEX2_BYTE1_PP_MASK,
        }
    }

    /// Decode a 3-byte VEX prefix from bytes `[0xC4, byte1, byte2]`.
    pub fn decode_3byte(vex_byte1: u8, vex_byte2: u8) -> Self {
        Self {
            is_3byte: true,
            r: (vex_byte1 & VEX3_BYTE1_R_MASK) == 0,
            x: (vex_byte1 & VEX3_BYTE1_X_MASK) == 0,
            b: (vex_byte1 & VEX3_BYTE1_B_MASK) == 0,
            mmmmm: vex_byte1 & VEX3_BYTE1_MMMMM_MASK,
            w: (vex_byte2 & VEX3_BYTE2_W_MASK) != 0,
            vvvv: (vex_byte2 >> 3) & VEX_REG_MASK,
            l: (vex_byte2 & VEX3_BYTE2_L_MASK) != 0,
            pp: vex_byte2 & VEX3_BYTE2_PP_MASK,
        }
    }

    /// Decode a VEX prefix from a byte slice, returning the decoded fields
    /// and the number of bytes consumed.
    pub fn decode(bytes: &[u8]) -> Option<(Self, usize)> {
        if bytes.is_empty() {
            return None;
        }
        match bytes[0] {
            VEX2_PREFIX if bytes.len() >= 2 => Some((Self::decode_2byte(bytes[1]), 2)),
            VEX3_PREFIX if bytes.len() >= 3 => Some((Self::decode_3byte(bytes[1], bytes[2]), 3)),
            _ => None,
        }
    }

    /// Get the effective ModR/M reg field register number (after de-inverting R).
    pub fn effective_reg_r(&self, reg: u8) -> u8 {
        if self.r {
            reg & 0x07
        } else {
            reg | VEX_REG_HIGH_BIT
        }
    }

    /// Get the effective SIB index register (after de-inverting X).
    pub fn effective_reg_x(&self, reg: u8) -> u8 {
        if self.x {
            reg & 0x07
        } else {
            reg | VEX_REG_HIGH_BIT
        }
    }

    /// Get the effective ModR/M r/m or SIB base register (after de-inverting B).
    pub fn effective_reg_b(&self, reg: u8) -> u8 {
        if self.b {
            reg & 0x07
        } else {
            reg | VEX_REG_HIGH_BIT
        }
    }

    /// Recover the true source register from vvvv field (de-invert).
    pub fn true_vvvv(&self) -> u8 {
        vex_recover_reg(self.vvvv)
    }

    /// Get the opcode map from the mmmmm field.
    pub fn opcode_map(&self) -> Option<VexOpcodeMap> {
        VexOpcodeMap::from_mmmmm(self.mmmmm)
    }

    /// Get the mandatory prefix from the pp field.
    pub fn mandatory_prefix(&self) -> VexMandatoryPrefix {
        VexMandatoryPrefix::from_pp(self.pp).unwrap_or(VexMandatoryPrefix::None)
    }

    /// Get the vector length from the L bit.
    pub fn vector_length(&self) -> VexVectorLength {
        VexVectorLength::from_l_bit(self.l)
    }

    /// Convert to a VexPrefixConfig for re-encoding.
    pub fn to_config(&self) -> VexPrefixConfig {
        VexPrefixConfig {
            r: self.r,
            x: self.x,
            b: self.b,
            w: self.w,
            mmmmm: self.mmmmm,
            vvvv: self.vvvv,
            l: self.l,
            pp: self.pp,
        }
    }
}

impl fmt::Display for VexDecodedPrefix {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let ty = if self.is_3byte { "VEX3" } else { "VEX2" };
        write!(
            f,
            "{} R={} X={} B={} W={} mmmmm={:05b} vvvv={:04b} L={} pp={:02b}",
            ty, self.r, self.x, self.b, self.w, self.mmmmm, self.vvvv, self.l, self.pp
        )
    }
}

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    VEX Instruction Length Computation                      ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

/// Compute the total length of a VEX-encoded instruction.
///
/// VEX instruction format:
/// ```
/// [VEX Prefix] [Opcode] [ModR/M] [SIB] [Displacement] [Immediate]
/// ```
///
/// The VEX prefix replaces legacy prefixes and escape bytes.
#[derive(Debug, Clone)]
pub struct VexInstructionLength;

impl VexInstructionLength {
    /// Compute the VEX prefix size (2 or 3 bytes).
    pub fn vex_prefix_size(config: &VexPrefixConfig) -> u8 {
        if config.can_use_2byte_vex() {
            2
        } else {
            3
        }
    }

    /// Compute the total instruction length for a VEX-encoded instruction.
    ///
    /// # Arguments
    /// * `config` - VEX prefix configuration
    /// * `opcode_size` - Number of opcode bytes (typically 1)
    /// * `has_modrm` - Whether the instruction has a ModR/M byte
    /// * `has_sib` - Whether a SIB byte follows ModR/M
    /// * `disp_size` - Displacement size in bytes (0, 1, or 4)
    /// * `imm_size` - Immediate size in bytes (0, 1, 2, 4, or 8)
    pub fn compute(
        config: &VexPrefixConfig,
        opcode_size: u8,
        has_modrm: bool,
        has_sib: bool,
        disp_size: u8,
        imm_size: u8,
    ) -> u16 {
        let vex_size = Self::vex_prefix_size(config) as u16;
        let op_size = opcode_size as u16;
        let modrm_byte = if has_modrm { 1u16 } else { 0 };
        let sib_byte = if has_sib { 1u16 } else { 0 };
        let disp_bytes = disp_size as u16;
        let imm_bytes = imm_size as u16;

        vex_size + op_size + modrm_byte + sib_byte + disp_bytes + imm_bytes
    }

    /// Maximum possible VEX instruction length (15 bytes per x86-64 limit).
    pub const MAX_LENGTH: u8 = 15;

    /// Check if a given instruction length is valid (<= 15 bytes for x86-64).
    pub fn is_valid_length(length: u16) -> bool {
        length <= Self::MAX_LENGTH as u16
    }

    /// Compute bytes saved by using VEX encoding compared to legacy encoding.
    ///
    /// Legacy encoding would use:
    /// - Optional REX prefix (1 byte)
    /// - Optional mandatory prefix (1 byte: 66, F3, or F2)
    /// - Escape bytes (1 for 0F, 2 for 0F38/0F3A)
    ///
    /// VEX replaces all of these with 2-3 bytes.
    pub fn bytes_saved_vs_legacy(config: &VexPrefixConfig, uses_rex: bool) -> i8 {
        let legacy_bytes: i8 = {
            let rex = if uses_rex { 1 } else { 0 };
            let pfx = if config.pp != VEX_PP_NONE { 1 } else { 0 };
            let esc = match config.mmmmm {
                VEX_MMMMM_0F => 1,
                VEX_MMMMM_0F38 | VEX_MMMMM_0F3A => 2,
                _ => 0,
            };
            rex + pfx + esc
        };

        let vex_bytes = if config.can_use_2byte_vex() { 2 } else { 3 };

        legacy_bytes - vex_bytes
    }

    /// Quick estimate of a VEX instruction length for common AVX patterns.
    ///
    /// Typical AVX instruction:
    /// - 2-byte VEX + 1 opcode + ModR/M = 4 bytes (reg-reg)
    /// - 2-byte VEX + 1 opcode + ModR/M + disp8 = 5 bytes (reg-mem, simple disp)
    /// - 3-byte VEX + 1 opcode + ModR/M + SIB + disp32 = 9 bytes (complex addressing)
    pub fn estimate_common(
        config: &VexPrefixConfig,
        is_memory: bool,
        needs_sib: bool,
        disp_is_32bit: bool,
        has_imm8: bool,
    ) -> u16 {
        let op_size: u16 = 1;
        let modrm: u16 = 1;
        let sib: u16 = if needs_sib { 1 } else { 0 };
        let disp: u16 = if is_memory {
            if disp_is_32bit {
                4
            } else {
                1
            }
        } else {
            0
        };
        let imm: u16 = if has_imm8 { 1 } else { 0 };
        let vex = Self::vex_prefix_size(config) as u16;

        vex + op_size + modrm + sib + disp + imm
    }
}

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    VEX Prefix Compression Logic                            ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

/// VEX prefix compressor — attempts to reduce 3-byte VEX to 2-byte VEX
/// when the instruction's register usage allows it.
#[derive(Debug, Clone)]
pub struct VexPrefixCompressor;

impl VexPrefixCompressor {
    /// Determine if a 3-byte VEX can be compressed to 2-byte.
    ///
    /// Compression is possible when ALL of these are true:
    /// 1. Opcode map is 0F (mmmmm == 1)
    /// 2. W bit is 0 (no 64-bit operand size override)
    /// 3. X bit is 0 (no SIB index extension needed — all index regs < 8)
    /// 4. B bit is 0 (no r/m or base extension — all base/rm regs < 8)
    /// 5. R bit is 0 (no reg extension — destination reg < 8)
    pub fn can_compress(config: &VexPrefixConfig) -> bool {
        config.mmmmm == VEX_MMMMM_0F && !config.w && !config.x && !config.b && !config.r
    }

    /// Attempt compression. Returns the compressed 2-byte config,
    /// or the original 3-byte config if compression is impossible.
    pub fn compress(config: VexPrefixConfig) -> VexPrefixConfig {
        if Self::can_compress(&config) {
            VexPrefixConfig {
                r: false,
                x: false,
                b: false,
                w: false,
                mmmmm: VEX_MMMMM_0F,
                vvvv: config.vvvv,
                l: config.l,
                pp: config.pp,
            }
        } else {
            config
        }
    }

    /// Check if a register assignment would PREVENT compression.
    ///
    /// Given a set of registers, determine if 2-byte VEX is impossible.
    pub fn would_prevent_compression(
        modrm_reg: u8,
        modrm_rm: u8,
        sib_index: Option<u8>,
        w: bool,
        mmmmm: u8,
    ) -> bool {
        mmmmm != VEX_MMMMM_0F
            || w
            || vex_reg_needs_r(modrm_reg)
            || vex_reg_needs_b(modrm_rm)
            || sib_index.map_or(false, vex_reg_needs_x)
    }

    /// Get the set of conditions that prevent 2-byte VEX compression.
    pub fn compression_blockers(config: &VexPrefixConfig) -> Vec<&'static str> {
        let mut blockers = Vec::new();
        if config.mmmmm != VEX_MMMMM_0F {
            blockers.push("opcode map is not 0F");
        }
        if config.w {
            blockers.push("W bit is set (64-bit operand)");
        }
        if config.x {
            blockers.push("X bit is set (extended index register)");
        }
        if config.b {
            blockers.push("B bit is set (extended base/r_m register)");
        }
        if config.r {
            blockers.push("R bit is set (extended reg register)");
        }
        blockers
    }

    /// Create a 2-byte VEX config from simple parameters.
    /// Returns None if 2-byte VEX cannot be used.
    pub fn try_make_2byte(vvvv: u8, l: bool, pp: u8) -> Option<VexPrefixConfig> {
        let cfg = VexPrefixConfig {
            r: false,
            x: false,
            b: false,
            w: false,
            mmmmm: VEX_MMMMM_0F,
            vvvv,
            l,
            pp,
        };
        if cfg.can_use_2byte_vex() {
            Some(cfg)
        } else {
            None
        }
    }
}

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    VEX Register Encoding Restrictions                      ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

/// VEX register encoding validator and restriction checker.
///
/// VEX encoding has specific restrictions on which registers can be used,
/// primarily related to the inverted encoding of R/X/B bits.
#[derive(Debug, Clone)]
pub struct VexRegisterRestrictions;

impl VexRegisterRestrictions {
    /// Maximum XMM/YMM register index accessible via VEX encoding.
    pub const MAX_VEX_REG: u8 = 15;

    /// Check if a register number is valid for VEX encoding.
    pub fn is_valid_vex_reg(reg: u8) -> bool {
        reg <= Self::MAX_VEX_REG
    }

    /// Validate that all register operands are within valid VEX range (0-15).
    ///
    /// Returns Ok(()) if all valid, Err with message if any invalid.
    pub fn validate_registers(regs: &[u8]) -> Result<(), String> {
        for (i, &reg) in regs.iter().enumerate() {
            if !Self::is_valid_vex_reg(reg) {
                return Err(format!(
                    "Register operand {} has invalid VEX register number {} (max {})",
                    i,
                    reg,
                    Self::MAX_VEX_REG
                ));
            }
        }
        Ok(())
    }

    /// Determine the minimum VEX encoding (2-byte vs 3-byte) for a set of registers.
    ///
    /// Returns true if 2-byte VEX can be used.
    pub fn can_use_2byte(
        dest_reg: u8,
        src1_reg: u8,
        src2_reg: u8,
        opcode_map: VexOpcodeMap,
        needs_w: bool,
    ) -> bool {
        if opcode_map != VexOpcodeMap::Map0F || needs_w {
            return false;
        }
        !vex_reg_needs_r(dest_reg) && !vex_reg_needs_b(src2_reg) && !vex_reg_needs_x(src1_reg)
    }

    /// Get the full VEX encoding type for a given register configuration.
    pub fn required_vex_type(config: &VexPrefixConfig) -> VexEncodingType {
        if config.can_use_2byte_vex() {
            VexEncodingType::Vex2Byte
        } else {
            VexEncodingType::Vex3Byte
        }
    }

    /// Check if the vvvv register requires the V' bit (always 0 for VEX, used in EVEX).
    /// In VEX, vvvv is always exactly 4 bits; there is no V' extension.
    pub fn vvvv_is_high_register(_vvvv: u8) -> bool {
        false // VEX vvvv is always 4-bit; no V' extension like EVEX
    }

    /// Maximum number of explicit register operands in a VEX instruction.
    pub const MAX_EXPLICIT_OPERANDS: u8 = 4; // dest + src1 + src2 + src3/mem

    /// The VEX.L bit restricts the instruction to operate on either XMM
    /// (L=0, 128-bit) or YMM (L=1, 256-bit) registers. No mixing allowed.
    pub fn validate_l_bit_for_registers(l: bool, regs: &[u8]) -> Result<(), String> {
        // All SIMD registers in AVX can be used with either L=0 or L=1.
        // The L bit simply selects between XMM and YMM interpretation.
        // This is always valid as long as registers are in range.
        if !l {
            // L=0: 128-bit — valid for all XMM/YMM regs
            Ok(())
        } else {
            // L=1: 256-bit — valid for all YMM regs (0-15)
            Self::validate_registers(regs)
        }
    }
}

/// VEX encoding type: 2-byte or 3-byte.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VexEncodingType {
    /// 2-byte VEX (0xC5 prefix) — compact encoding for 128-bit instructions.
    Vex2Byte,
    /// 3-byte VEX (0xC4 prefix) — full encoding for 256-bit or extended regs.
    Vex3Byte,
}

impl VexEncodingType {
    /// Number of prefix bytes.
    pub const fn byte_count(&self) -> u8 {
        match self {
            Self::Vex2Byte => 2,
            Self::Vex3Byte => 3,
        }
    }

    /// Human-readable name.
    pub const fn name(&self) -> &'static str {
        match self {
            Self::Vex2Byte => "VEX.128",
            Self::Vex3Byte => "VEX.256",
        }
    }
}

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

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    VEX-Encoded Instruction Builder                         ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

/// Complete VEX-encoded instruction representation.
///
/// This struct holds all components needed to assemble a full VEX instruction.
#[derive(Debug, Clone)]
pub struct VexEncodedInstruction {
    /// VEX prefix bytes.
    pub vex_prefix: Vec<u8>,
    /// Opcode byte(s).
    pub opcode: Vec<u8>,
    /// ModR/M byte (optional).
    pub modrm: Option<u8>,
    /// SIB byte (optional).
    pub sib: Option<u8>,
    /// Displacement bytes (0, 1, or 4 bytes).
    pub displacement: Vec<u8>,
    /// Immediate bytes (0, 1, 2, 4, or 8 bytes).
    pub immediate: Vec<u8>,
    /// Encoding type used.
    pub encoding_type: VexEncodingType,
}

impl VexEncodedInstruction {
    /// Create a new VEX-encoded instruction with a given encoding type.
    pub fn new(encoding_type: VexEncodingType) -> Self {
        Self {
            vex_prefix: Vec::new(),
            opcode: Vec::new(),
            modrm: None,
            sib: None,
            displacement: Vec::new(),
            immediate: Vec::new(),
            encoding_type,
        }
    }

    /// Assemble the full instruction bytes.
    pub fn assemble(&self) -> Vec<u8> {
        let mut bytes = Vec::with_capacity(self.total_length() as usize);
        bytes.extend_from_slice(&self.vex_prefix);
        bytes.extend_from_slice(&self.opcode);
        if let Some(modrm) = self.modrm {
            bytes.push(modrm);
        }
        if let Some(sib) = self.sib {
            bytes.push(sib);
        }
        bytes.extend_from_slice(&self.displacement);
        bytes.extend_from_slice(&self.immediate);
        bytes
    }

    /// Compute total instruction length.
    pub fn total_length(&self) -> u16 {
        let mut len: u16 = 0;
        len += self.vex_prefix.len() as u16;
        len += self.opcode.len() as u16;
        if self.modrm.is_some() {
            len += 1;
        }
        if self.sib.is_some() {
            len += 1;
        }
        len += self.displacement.len() as u16;
        len += self.immediate.len() as u16;
        len
    }

    /// Check if instruction length is valid (<= 15 bytes).
    pub fn is_valid(&self) -> bool {
        self.total_length() <= 15
    }

    /// Get the encoding type description.
    pub fn encoding_description(&self) -> &'static str {
        self.encoding_type.name()
    }
}

impl fmt::Display for VexEncodedInstruction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let bytes = self.assemble();
        write!(f, "VEX[{}] ", bytes.len())?;
        for b in &bytes {
            write!(f, "{:02X} ", b)?;
        }
        Ok(())
    }
}

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    VEX Instruction Templates (Common AVX)                  ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

/// Pre-built VEX encoding templates for common AVX instruction patterns.
#[derive(Debug, Clone)]
pub struct VexInstructionTemplate {
    /// Opcode map to use.
    pub map: VexOpcodeMap,
    /// Mandatory prefix.
    pub prefix: VexMandatoryPrefix,
    /// Vector length (128 or 256).
    pub vector_length: VexVectorLength,
    /// Opcode byte.
    pub opcode: u8,
    /// Whether this template has a ModR/M byte.
    pub has_modrm: bool,
    /// Whether W=1 (64-bit operand) is allowed.
    pub allows_w: bool,
    /// Whether this instruction is commutative (src1 and src2 can swap).
    pub is_commutative: bool,
}

impl VexInstructionTemplate {
    /// Create a new VEX template.
    pub const fn new(
        map: VexOpcodeMap,
        prefix: VexMandatoryPrefix,
        vector_length: VexVectorLength,
        opcode: u8,
        has_modrm: bool,
    ) -> Self {
        Self {
            map,
            prefix,
            vector_length,
            opcode,
            has_modrm,
            allows_w: false,
            is_commutative: false,
        }
    }

    /// Create a VEX template with W=1 support for 64-bit operations.
    pub const fn with_w(mut self, w: bool) -> Self {
        self.allows_w = w;
        self
    }

    /// Create a commutative VEX template.
    pub const fn commutative(mut self) -> Self {
        self.is_commutative = true;
        self
    }

    /// Build a VexPrefixConfig from this template and register assignments.
    pub fn build_config(
        &self,
        dest_reg: u8,
        src1_reg: u8,
        src2_or_mem_reg: u8,
        w: bool,
    ) -> VexPrefixConfig {
        VexPrefixConfig::from_registers(
            self.map,
            self.prefix,
            self.vector_length,
            src1_reg,
            dest_reg,
            src2_or_mem_reg,
            None, // no SIB index
            w,
        )
    }

    /// Build a VEX-encoded instruction from this template.
    pub fn encode_rrr(&self, dest_reg: u8, src1_reg: u8, src2_reg: u8) -> VexEncodedInstruction {
        let config = self.build_config(dest_reg, src1_reg, src2_reg, false);
        let encoding_type = if config.can_use_2byte_vex() {
            VexEncodingType::Vex2Byte
        } else {
            VexEncodingType::Vex3Byte
        };

        let vex_bytes = VexPrefixBuilder::build(&config);
        let modrm = Self::encode_modrm_reg_reg(dest_reg, src2_reg);

        VexEncodedInstruction {
            vex_prefix: vex_bytes,
            opcode: vec![self.opcode],
            modrm: Some(modrm),
            sib: None,
            displacement: vec![],
            immediate: vec![],
            encoding_type,
        }
    }

    /// Encode a ModR/M byte for register-register operations.
    /// Mod=11 (register direct), reg=dest, rm=src2
    fn encode_modrm_reg_reg(reg_field: u8, rm_field: u8) -> u8 {
        0xC0 | ((reg_field & 0x07) << 3) | (rm_field & 0x07)
    }
}

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    Common AVX Instruction Templates                        ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

/// Catalog of common AVX instruction templates (VEX-encoded).
pub struct VexTemplateCatalog;

impl VexTemplateCatalog {
    /// VADDPS — Add Packed Single-Precision Floating-Point Values
    pub const VADDPS: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F,
        VexMandatoryPrefix::None,
        VexVectorLength::L128,
        0x58,
        true,
    );

    /// VADDPS 256-bit variant
    pub const VADDPS_YMM: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F,
        VexMandatoryPrefix::None,
        VexVectorLength::L256,
        0x58,
        true,
    );

    /// VMULPS — Multiply Packed Single-Precision
    pub const VMULPS: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F,
        VexMandatoryPrefix::None,
        VexVectorLength::L128,
        0x59,
        true,
    );

    /// VMULPS 256-bit variant
    pub const VMULPS_YMM: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F,
        VexMandatoryPrefix::None,
        VexVectorLength::L256,
        0x59,
        true,
    );

    /// VSUBPS — Subtract Packed Single-Precision
    pub const VSUBPS: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F,
        VexMandatoryPrefix::None,
        VexVectorLength::L128,
        0x5C,
        true,
    );

    /// VDIVPS — Divide Packed Single-Precision
    pub const VDIVPS: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F,
        VexMandatoryPrefix::None,
        VexVectorLength::L128,
        0x5E,
        true,
    );

    /// VANDPS — Bitwise AND Packed Single-Precision
    pub const VANDPS: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F,
        VexMandatoryPrefix::None,
        VexVectorLength::L128,
        0x54,
        true,
    );

    /// VORPS — Bitwise OR Packed Single-Precision
    pub const VORPS: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F,
        VexMandatoryPrefix::None,
        VexVectorLength::L128,
        0x56,
        true,
    );

    /// VXORPS — Bitwise XOR Packed Single-Precision
    pub const VXORPS: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F,
        VexMandatoryPrefix::None,
        VexVectorLength::L128,
        0x57,
        true,
    );

    /// VADDPD — Add Packed Double-Precision
    pub const VADDPD: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F,
        VexMandatoryPrefix::P66,
        VexVectorLength::L128,
        0x58,
        true,
    );

    /// VMULPD — Multiply Packed Double-Precision
    pub const VMULPD: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F,
        VexMandatoryPrefix::P66,
        VexVectorLength::L128,
        0x59,
        true,
    );

    /// VPADDB — Add Packed Byte Integers
    pub const VPADDB: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F,
        VexMandatoryPrefix::P66,
        VexVectorLength::L128,
        0xFC,
        true,
    );

    /// VPADDW — Add Packed Word Integers
    pub const VPADDW: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F,
        VexMandatoryPrefix::P66,
        VexVectorLength::L128,
        0xFD,
        true,
    );

    /// VPADDD — Add Packed Doubleword Integers
    pub const VPADDD: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F,
        VexMandatoryPrefix::P66,
        VexVectorLength::L128,
        0xFE,
        true,
    );

    /// VPADDQ — Add Packed Quadword Integers
    pub const VPADDQ: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F,
        VexMandatoryPrefix::P66,
        VexVectorLength::L128,
        0xD4,
        true,
    );

    /// VPSUBB — Subtract Packed Byte Integers
    pub const VPSUBB: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F,
        VexMandatoryPrefix::P66,
        VexVectorLength::L128,
        0xF8,
        true,
    );

    /// VPSUBW — Subtract Packed Word Integers
    pub const VPSUBW: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F,
        VexMandatoryPrefix::P66,
        VexVectorLength::L128,
        0xF9,
        true,
    );

    /// VPSUBD — Subtract Packed Doubleword Integers
    pub const VPSUBD: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F,
        VexMandatoryPrefix::P66,
        VexVectorLength::L128,
        0xFA,
        true,
    );

    /// VPMULLW — Multiply Packed Signed Word Integers
    pub const VPMULLW: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F,
        VexMandatoryPrefix::P66,
        VexVectorLength::L128,
        0xD5,
        true,
    );

    /// VPMULLD — Multiply Packed Signed Doubleword Integers (AVX2)
    pub const VPMULLD: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F38,
        VexMandatoryPrefix::P66,
        VexVectorLength::L128,
        0x40,
        true,
    );

    /// VFMADD132PS — Fused Multiply-Add Packed Single (FMA)
    pub const VFMADD132PS: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F38,
        VexMandatoryPrefix::P66,
        VexVectorLength::L128,
        0x98,
        true,
    );

    /// VFMADD213PS — Fused Multiply-Add Packed Single (FMA)
    pub const VFMADD213PS: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F38,
        VexMandatoryPrefix::P66,
        VexVectorLength::L128,
        0xA8,
        true,
    );

    /// VFMADD231PS — Fused Multiply-Add Packed Single (FMA)
    pub const VFMADD231PS: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F38,
        VexMandatoryPrefix::P66,
        VexVectorLength::L128,
        0xB8,
        true,
    );

    /// VPERM2F128 — Permute Floating-Point Values (AVX)
    pub const VPERM2F128: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F3A,
        VexMandatoryPrefix::P66,
        VexVectorLength::L256,
        0x06,
        true,
    );

    /// VPERMILPS — Permute Single-Precision Floating-Point Values
    pub const VPERMILPS_REG: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F38,
        VexMandatoryPrefix::P66,
        VexVectorLength::L128,
        0x0C,
        true,
    );

    /// VBROADCASTSS — Broadcast Single-Precision to 128/256 bits
    pub const VBROADCASTSS: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F38,
        VexMandatoryPrefix::P66,
        VexVectorLength::L128,
        0x18,
        true,
    );

    /// VZEROUPPER — Zero Upper 128 bits of all YMM registers
    pub const VZEROUPPER: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F,
        VexMandatoryPrefix::None,
        VexVectorLength::L128,
        0x77,
        false,
    );

    /// VZEROALL — Zero All YMM registers
    pub const VZEROALL: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F,
        VexMandatoryPrefix::None,
        VexVectorLength::L256,
        0x77,
        false,
    );

    /// ANDN — Logical AND NOT (BMI1)
    pub const ANDN: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F38,
        VexMandatoryPrefix::None,
        VexVectorLength::L128,
        0xF2,
        true,
    );

    /// BEXTR — Bit Field Extract (BMI1)
    pub const BEXTR: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F38,
        VexMandatoryPrefix::None,
        VexVectorLength::L128,
        0xF7,
        true,
    );

    /// BLSI — Extract Lowest Set Isolated Bit (BMI1)
    pub const BLSI: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F38,
        VexMandatoryPrefix::None,
        VexVectorLength::L128,
        0xF3,
        true,
    );

    /// BLSMSK — Get Mask Up to Lowest Set Bit (BMI1)
    pub const BLSMSK: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F38,
        VexMandatoryPrefix::None,
        VexVectorLength::L128,
        0xF3,
        true,
    );

    /// BLSR — Reset Lowest Set Bit (BMI1)
    pub const BLSR: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F38,
        VexMandatoryPrefix::None,
        VexVectorLength::L128,
        0xF3,
        true,
    );

    /// BZHI — Zero High Bits Starting with Specified Bit Position (BMI2)
    pub const BZHI: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F38,
        VexMandatoryPrefix::None,
        VexVectorLength::L128,
        0xF5,
        true,
    );

    /// MULX — Unsigned Multiply Without Affecting Flags (BMI2)
    pub const MULX: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F38,
        VexMandatoryPrefix::PF2,
        VexVectorLength::L128,
        0xF6,
        true,
    );

    /// PDEP — Parallel Bits Deposit (BMI2)
    pub const PDEP: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F38,
        VexMandatoryPrefix::PF2,
        VexVectorLength::L128,
        0xF5,
        true,
    );

    /// PEXT — Parallel Bits Extract (BMI2)
    pub const PEXT: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F38,
        VexMandatoryPrefix::PF3,
        VexVectorLength::L128,
        0xF5,
        true,
    );

    /// RORX — Rotate Right Logical Without Affecting Flags (BMI2)
    pub const RORX: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F3A,
        VexMandatoryPrefix::PF2,
        VexVectorLength::L128,
        0xF0,
        true,
    );

    /// SHA1RNDS4 — SHA1 Round (SHA-NI)
    pub const SHA1RNDS4: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F3A,
        VexMandatoryPrefix::None,
        VexVectorLength::L128,
        0xCC,
        true,
    );

    /// VAESENC — AES Encrypt Round (VAES / AVX)
    pub const VAESENC: VexInstructionTemplate = VexInstructionTemplate::new(
        VexOpcodeMap::Map0F38,
        VexMandatoryPrefix::P66,
        VexVectorLength::L128,
        0xDC,
        true,
    );

    /// Return all VEX templates in the catalog.
    pub fn all_templates() -> Vec<(&'static str, VexInstructionTemplate)> {
        vec![
            ("vaddps", Self::VADDPS),
            ("vaddps_ymm", Self::VADDPS_YMM),
            ("vmulps", Self::VMULPS),
            ("vmulps_ymm", Self::VMULPS_YMM),
            ("vsubps", Self::VSUBPS),
            ("vdivps", Self::VDIVPS),
            ("vandps", Self::VANDPS),
            ("vorps", Self::VORPS),
            ("vxorps", Self::VXORPS),
            ("vaddpd", Self::VADDPD),
            ("vmulpd", Self::VMULPD),
            ("vpaddb", Self::VPADDB),
            ("vpaddw", Self::VPADDW),
            ("vpaddd", Self::VPADDD),
            ("vpaddq", Self::VPADDQ),
            ("vpsubb", Self::VPSUBB),
            ("vpsubw", Self::VPSUBW),
            ("vpsubd", Self::VPSUBD),
            ("vpmullw", Self::VPMULLW),
            ("vpmulld", Self::VPMULLD),
            ("vfmadd132ps", Self::VFMADD132PS),
            ("vfmadd213ps", Self::VFMADD213PS),
            ("vfmadd231ps", Self::VFMADD231PS),
            ("vperm2f128", Self::VPERM2F128),
            ("vpermilps", Self::VPERMILPS_REG),
            ("vbroadcastss", Self::VBROADCASTSS),
            ("vzeroupper", Self::VZEROUPPER),
            ("vzeroall", Self::VZEROALL),
            ("andn", Self::ANDN),
            ("bextr", Self::BEXTR),
            ("blsi", Self::BLSI),
            ("blsmsk", Self::BLSMSK),
            ("blsr", Self::BLSR),
            ("bzhi", Self::BZHI),
            ("mulx", Self::MULX),
            ("pdep", Self::PDEP),
            ("pext", Self::PEXT),
            ("rorx", Self::RORX),
            ("sha1rnds4", Self::SHA1RNDS4),
            ("vaesenc", Self::VAESENC),
        ]
    }
}

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    Main X86VEXEncoding Struct                              ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

/// Main entry point for X86 VEX prefix encoding.
///
/// `X86VEXEncoding` provides the complete interface for VEX prefix generation,
/// decoding, compression, and instruction length computation. It encapsulates
/// all the logic needed to produce correct VEX-encoded x86 instructions for
/// AVX, AVX2, FMA, BMI, BMI2, and related instruction set extensions.
///
/// # Examples
///
/// ```ignore
/// use crate::x86::x86_vex_encoding::X86VEXEncoding;
///
/// let encoding = X86VEXEncoding::new();
///
/// // Build a 2-byte VEX prefix for vaddps xmm0, xmm1, xmm2
/// let config = encoding.config_for_rrr(
///     VexOpcodeMap::Map0F, VexMandatoryPrefix::None,
///     VexVectorLength::L128, 1, 0, 2, false
/// );
/// let bytes = encoding.encode_vex_prefix(&config);
/// assert_eq!(bytes.len(), 2); // 2-byte VEX (all regs < 8, map 0F)
/// ```
#[derive(Debug, Clone, Default)]
pub struct X86VEXEncoding {
    /// Template catalog for common instructions.
    pub templates: std::collections::HashMap<String, VexInstructionTemplate>,
    /// Default vector length for new encodings.
    pub default_vector_length: VexVectorLength,
    /// Whether to prefer 2-byte VEX when possible.
    pub prefer_2byte: bool,
}

impl X86VEXEncoding {
    /// Create a new X86VEXEncoding with defaults.
    pub fn new() -> Self {
        let mut templates = std::collections::HashMap::new();
        for (name, tmpl) in VexTemplateCatalog::all_templates() {
            templates.insert(name.to_string(), tmpl);
        }
        Self {
            templates,
            default_vector_length: VexVectorLength::L128,
            prefer_2byte: true,
        }
    }

    /// Set the default vector length.
    pub fn with_default_vl(mut self, vl: VexVectorLength) -> Self {
        self.default_vector_length = vl;
        self
    }

    /// Disable 2-byte VEX preference (always use 3-byte).
    pub fn without_2byte_compression(mut self) -> Self {
        self.prefer_2byte = false;
        self
    }

    /// Create a VexPrefixConfig for a register-register-register operation.
    pub fn config_for_rrr(
        &self,
        map: VexOpcodeMap,
        prefix: VexMandatoryPrefix,
        vl: VexVectorLength,
        src1_reg: u8,
        dest_reg: u8,
        src2_reg: u8,
        w: bool,
    ) -> VexPrefixConfig {
        VexPrefixConfig::from_registers(map, prefix, vl, src1_reg, dest_reg, src2_reg, None, w)
    }

    /// Create a VexPrefixConfig for a register-register-memory operation.
    pub fn config_for_rrm(
        &self,
        map: VexOpcodeMap,
        prefix: VexMandatoryPrefix,
        vl: VexVectorLength,
        src1_reg: u8,
        dest_reg: u8,
        mem_base_reg: u8,
        mem_index_reg: Option<u8>,
        w: bool,
    ) -> VexPrefixConfig {
        VexPrefixConfig::from_registers(
            map,
            prefix,
            vl,
            src1_reg,
            dest_reg,
            mem_base_reg,
            mem_index_reg,
            w,
        )
    }

    /// Encode a VEX prefix from a configuration.
    /// Automatically selects 2-byte or 3-byte based on config and preferences.
    pub fn encode_vex_prefix(&self, config: &VexPrefixConfig) -> Vec<u8> {
        let effective_config = if self.prefer_2byte {
            VexPrefixCompressor::compress(*config)
        } else {
            *config
        };
        VexPrefixBuilder::build(&effective_config)
    }

    /// Encode a VEX2 prefix directly from register fields.
    pub fn encode_vex2(&self, r: bool, vvvv: u8, l: bool, pp: u8) -> [u8; 2] {
        VexPrefixBuilder::build_2byte(r, vvvv, l, pp)
    }

    /// Encode a VEX3 prefix directly from all fields.
    pub fn encode_vex3(
        &self,
        r: bool,
        x: bool,
        b: bool,
        mmmmm: u8,
        w: bool,
        vvvv: u8,
        l: bool,
        pp: u8,
    ) -> [u8; 3] {
        VexPrefixBuilder::build_3byte(r, x, b, mmmmm, w, vvvv, l, pp)
    }

    /// Compute the VEX instruction length for a given configuration.
    pub fn compute_length(
        &self,
        config: &VexPrefixConfig,
        opcode_size: u8,
        has_modrm: bool,
        has_sib: bool,
        disp_size: u8,
        imm_size: u8,
    ) -> u16 {
        VexInstructionLength::compute(config, opcode_size, has_modrm, has_sib, disp_size, imm_size)
    }

    /// Look up a template by name and encode it with provided registers.
    pub fn encode_from_template(
        &self,
        template_name: &str,
        dest_reg: u8,
        src1_reg: u8,
        src2_reg: u8,
    ) -> Option<VexEncodedInstruction> {
        let template = self.templates.get(template_name)?;
        Some(template.encode_rrr(dest_reg, src1_reg, src2_reg))
    }

    /// Check whether a VEX configuration can use 2-byte encoding.
    pub fn can_use_2byte(&self, config: &VexPrefixConfig) -> bool {
        config.can_use_2byte_vex()
    }

    /// Get the compression blockers for a configuration that requires 3-byte VEX.
    pub fn compression_blockers(&self, config: &VexPrefixConfig) -> Vec<&'static str> {
        VexPrefixCompressor::compression_blockers(config)
    }

    /// Decode a VEX prefix from raw bytes.
    pub fn decode_vex(&self, bytes: &[u8]) -> Option<(VexDecodedPrefix, usize)> {
        VexDecodedPrefix::decode(bytes)
    }

    /// Validate that all registers are valid for VEX encoding.
    pub fn validate_registers(&self, regs: &[u8]) -> Result<(), String> {
        VexRegisterRestrictions::validate_registers(regs)
    }

    /// Compute the bytes saved by using VEX vs legacy encoding.
    pub fn bytes_saved(&self, config: &VexPrefixConfig, uses_rex: bool) -> i8 {
        VexInstructionLength::bytes_saved_vs_legacy(config, uses_rex)
    }
}

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    VEX Bit-Pattern Reference Tables                        ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

/// Complete reference table of all 2-byte VEX byte1 encodings (RvvvvLpp).
///
/// This table maps the byte1 value (0x00-0xFF) to its decoded fields.
pub struct Vex2Byte1Table;

impl Vex2Byte1Table {
    /// All valid VEX2 byte1 values (R=1 or R=0 matching the register usage).
    pub fn all_combinations() -> Vec<(bool, u8, bool, u8)> {
        let mut results = Vec::new();
        for byte1 in 0x00u8..=0xFFu8 {
            let r = (byte1 & VEX2_BYTE1_R_MASK) == 0;
            let vvvv = (byte1 >> 3) & VEX_REG_MASK;
            let l = (byte1 & VEX2_BYTE1_L_MASK) != 0;
            let pp = byte1 & VEX2_BYTE1_PP_MASK;
            results.push((r, vvvv, l, pp));
        }
        results
    }

    /// Decode a VEX2 byte1 value into its fields.
    pub fn decode(byte1: u8) -> (bool, u8, bool, u8) {
        let r = (byte1 & VEX2_BYTE1_R_MASK) == 0;
        let vvvv = (byte1 >> 3) & VEX_REG_MASK;
        let l = (byte1 & VEX2_BYTE1_L_MASK) != 0;
        let pp = byte1 & VEX2_BYTE1_PP_MASK;
        (r, vvvv, l, pp)
    }
}

/// Complete reference table of all 3-byte VEX byte1+byte2 encodings.
pub struct Vex3ByteTable;

impl Vex3ByteTable {
    /// All valid mmmmm values for 3-byte VEX.
    pub const VALID_MMMMM: [u8; 3] = [VEX_MMMMM_0F, VEX_MMMMM_0F38, VEX_MMMMM_0F3A];

    /// Decode a VEX3 byte1+byte2 pair into a VexPrefixConfig.
    pub fn decode_to_config(byte1: u8, byte2: u8) -> VexPrefixConfig {
        let r = (byte1 & VEX3_BYTE1_R_MASK) == 0;
        let x = (byte1 & VEX3_BYTE1_X_MASK) == 0;
        let b = (byte1 & VEX3_BYTE1_B_MASK) == 0;
        let mmmmm = byte1 & VEX3_BYTE1_MMMMM_MASK;
        let w = (byte2 & VEX3_BYTE2_W_MASK) != 0;
        let vvvv = (byte2 >> 3) & VEX_REG_MASK;
        let l = (byte2 & VEX3_BYTE2_L_MASK) != 0;
        let pp = byte2 & VEX3_BYTE2_PP_MASK;

        VexPrefixConfig {
            r,
            x,
            b,
            w,
            mmmmm,
            vvvv,
            l,
            pp,
        }
    }

    /// Generate all valid VEX3 byte1 values for a given mmmmm.
    pub fn valid_byte1_values(mmmmm: u8) -> Vec<u8> {
        let mut result = Vec::new();
        for rx_bits in 0u8..8u8 {
            let byte1 = ((rx_bits & 0x04) << 5) // R
                | ((rx_bits & 0x02) << 5)        // X
                | ((rx_bits & 0x01) << 5)        // B
                | (mmmmm & VEX3_BYTE1_MMMMM_MASK);
            result.push(byte1);
        }
        result
    }
}

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    VEX to Legacy Encoding Translator                       ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

/// Translate VEX-encoded instructions back to equivalent legacy encoding
/// (for CPUs that do not support AVX).
///
/// This is useful for:
/// - Disassembly output formatting
/// - Instruction emulation on older CPUs
/// - Code size estimation for mixed VEX/legacy code
#[derive(Debug, Clone)]
pub struct VexToLegacyTranslator;

impl VexToLegacyTranslator {
    /// Translate a VexDecodedPrefix into the equivalent legacy prefix bytes
    /// (REX + mandatory prefix + escape bytes).
    pub fn translate_prefix(decoded: &VexDecodedPrefix) -> Vec<u8> {
        let mut bytes = Vec::new();

        // REX prefix (if any of R, X, B, W bits are needed)
        let needs_rex = decoded.r || decoded.x || decoded.b || decoded.w;
        if needs_rex {
            let mut rex: u8 = 0x40;
            if decoded.w {
                rex |= 0x08;
            }
            if decoded.r {
                rex |= 0x04;
            }
            if decoded.x {
                rex |= 0x02;
            }
            if decoded.b {
                rex |= 0x01;
            }
            bytes.push(rex);
        }

        // Mandatory prefix
        match decoded.mandatory_prefix() {
            VexMandatoryPrefix::P66 => bytes.push(0x66),
            VexMandatoryPrefix::PF3 => bytes.push(0xF3),
            VexMandatoryPrefix::PF2 => bytes.push(0xF2),
            VexMandatoryPrefix::None => {}
        }

        // Escape bytes
        if let Some(map) = decoded.opcode_map() {
            bytes.extend(map.escape_bytes());
        }

        bytes
    }

    /// Compute total legacy prefix length for a VEX instruction.
    pub fn legacy_prefix_length(decoded: &VexDecodedPrefix) -> u8 {
        Self::translate_prefix(decoded).len() as u8
    }

    /// Compare VEX prefix length vs legacy prefix length.
    /// Returns positive if VEX saves bytes, negative if legacy is smaller.
    pub fn compare_lengths(decoded: &VexDecodedPrefix) -> i8 {
        let vex_len = if decoded.is_3byte { 3 } else { 2 };
        let legacy_len = Self::legacy_prefix_length(decoded) as i8;
        legacy_len - vex_len
    }
}

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    VEX Assembly Printer / Formatter                        ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

/// Pretty-printer for VEX-encoded instructions (for disassembly/debug output).
#[derive(Debug, Clone)]
pub struct VexAssemblyPrinter;

impl VexAssemblyPrinter {
    /// Format a VexDecodedPrefix as a human-readable string.
    pub fn format_prefix(decoded: &VexDecodedPrefix) -> String {
        let mut s = String::new();
        s.push_str(if decoded.is_3byte { "VEX3" } else { "VEX2" });
        s.push_str(&format!(
            " R={} X={} B={} W={} mmmmm={:05b} vvvv={:04b} L={} pp={:02b}",
            decoded.r as u8,
            decoded.x as u8,
            decoded.b as u8,
            decoded.w as u8,
            decoded.mmmmm,
            decoded.vvvv,
            decoded.l as u8,
            decoded.pp,
        ));
        s
    }

    /// Format a VexPrefixConfig as a human-readable string.
    pub fn format_config(config: &VexPrefixConfig) -> String {
        let form = if config.can_use_2byte_vex() {
            "VEX2"
        } else {
            "VEX3"
        };
        format!(
            "{} R={} X={} B={} W={} mmmmm={:05b} vvvv={:04b} L={} pp={:02b}",
            form,
            config.r as u8,
            config.x as u8,
            config.b as u8,
            config.w as u8,
            config.mmmmm,
            config.vvvv,
            config.l as u8,
            config.pp,
        )
    }

    /// Format a VexEncodedInstruction as hex bytes.
    pub fn format_instruction(instr: &VexEncodedInstruction) -> String {
        let bytes = instr.assemble();
        let mut s = String::new();
        for (i, b) in bytes.iter().enumerate() {
            if i > 0 {
                s.push(' ');
            }
            s.push_str(&format!("{:02X}", b));
        }
        s
    }

    /// Disassemble VEX prefix bytes back to field descriptions.
    pub fn disassemble_prefix(bytes: &[u8]) -> Option<String> {
        let (decoded, _) = VexDecodedPrefix::decode(bytes)?;
        Some(Self::format_prefix(&decoded))
    }

    /// Print a full VEX instruction in Intel syntax.
    pub fn print_intel_syntax(
        mnemonic: &str,
        decoded: &VexDecodedPrefix,
        dest_reg: u8,
        src1_reg: u8,
        src2_reg: u8,
    ) -> String {
        let vl = decoded.vector_length();
        let reg_prefix = vl.reg_prefix();
        format!(
            "{} {}{}, {}{}, {}{}",
            mnemonic,
            reg_prefix,
            decoded.effective_reg_r(dest_reg),
            reg_prefix,
            decoded.true_vvvv(),
            reg_prefix,
            decoded.effective_reg_b(src2_reg),
        )
    }
}

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    VEX Field Validation Utilities                          ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

/// Validate that all fields of a VexPrefixConfig are consistent and valid.
#[derive(Debug, Clone)]
pub struct VexFieldValidator;

impl VexFieldValidator {
    /// Validate a complete VexPrefixConfig.
    pub fn validate(config: &VexPrefixConfig) -> Result<(), Vec<String>> {
        let mut errors = Vec::new();

        // mmmmm must be 1, 2, or 3 for valid VEX opcode maps
        if config.mmmmm < 1 || config.mmmmm > 3 {
            errors.push(format!(
                "Invalid mmmmm value: {} (expected 1=0F, 2=0F38, or 3=0F3A)",
                config.mmmmm
            ));
        }

        // pp must be 0-3
        if config.pp > 3 {
            errors.push(format!("Invalid pp value: {} (expected 0-3)", config.pp));
        }

        // vvvv is always stored 1's complement; any 4-bit value is valid

        // In 2-byte VEX mode, mmmmm must be 1 and W/X/B must be 0
        if config.can_use_2byte_vex() {
            if config.mmmmm != VEX_MMMMM_0F {
                errors.push("2-byte VEX requires mmmmm=1 (map 0F)".to_string());
            }
            if config.w {
                errors.push("2-byte VEX cannot encode W=1".to_string());
            }
            if config.x {
                errors.push("2-byte VEX cannot encode X=1".to_string());
            }
            if config.b {
                errors.push("2-byte VEX cannot encode B=1".to_string());
            }
        }

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

    /// Quick check: Is this a valid VEX mmmmm value?
    pub fn is_valid_mmmmm(mmmmm: u8) -> bool {
        matches!(mmmmm, VEX_MMMMM_0F | VEX_MMMMM_0F38 | VEX_MMMMM_0F3A)
    }

    /// Quick check: Is this a valid VEX pp value?
    pub fn is_valid_pp(pp: u8) -> bool {
        pp <= 3
    }
}

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    VEX Encoding for Specific Instruction Families          ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

/// Specialized VEX encoders for specific instruction families.
#[derive(Debug, Clone)]
pub struct VexFamilyEncoder;

impl VexFamilyEncoder {
    /// Encode AVX 128-bit packed single-precision arithmetic (reg, reg, reg).
    ///
    /// Covers VADDPS, VSUBPS, VMULPS, VDIVPS, VMINPS, VMAXPS.
    /// Opcode map: 0F, pp=00.
    pub fn encode_avx_128_ps(opcode: u8, dest: u8, src1: u8, src2: u8) -> VexEncodedInstruction {
        let config = VexPrefixConfig::from_registers(
            VexOpcodeMap::Map0F,
            VexMandatoryPrefix::None,
            VexVectorLength::L128,
            src1,
            dest,
            src2,
            None,
            false,
        );
        let encoding_type = if config.can_use_2byte_vex() {
            VexEncodingType::Vex2Byte
        } else {
            VexEncodingType::Vex3Byte
        };
        let vex_bytes = VexPrefixBuilder::build(&config);
        let modrm = 0xC0 | ((dest & 0x07) << 3) | (src2 & 0x07);

        VexEncodedInstruction {
            vex_prefix: vex_bytes,
            opcode: vec![opcode],
            modrm: Some(modrm),
            sib: None,
            displacement: vec![],
            immediate: vec![],
            encoding_type,
        }
    }

    /// Encode AVX 256-bit packed single-precision arithmetic (reg, reg, reg).
    pub fn encode_avx_256_ps(opcode: u8, dest: u8, src1: u8, src2: u8) -> VexEncodedInstruction {
        let config = VexPrefixConfig::from_registers(
            VexOpcodeMap::Map0F,
            VexMandatoryPrefix::None,
            VexVectorLength::L256,
            src1,
            dest,
            src2,
            None,
            false,
        );
        let encoding_type = VexEncodingType::Vex3Byte;
        let vex_bytes = VexPrefixBuilder::build_3byte_from_config(&config).to_vec();
        let modrm = 0xC0 | ((dest & 0x07) << 3) | (src2 & 0x07);

        VexEncodedInstruction {
            vex_prefix: vex_bytes,
            opcode: vec![opcode],
            modrm: Some(modrm),
            sib: None,
            displacement: vec![],
            immediate: vec![],
            encoding_type,
        }
    }

    /// Encode AVX packed double-precision arithmetic (reg, reg, reg).
    ///
    /// Covers VADDPD, VSUBPD, VMULPD, VDIVPD.
    /// Opcode map: 0F, pp=66.
    pub fn encode_avx_pd(
        opcode: u8,
        dest: u8,
        src1: u8,
        src2: u8,
        vl: VexVectorLength,
    ) -> VexEncodedInstruction {
        let config = VexPrefixConfig::from_registers(
            VexOpcodeMap::Map0F,
            VexMandatoryPrefix::P66,
            vl,
            src1,
            dest,
            src2,
            None,
            false,
        );
        let encoding_type = if config.can_use_2byte_vex() {
            VexEncodingType::Vex2Byte
        } else {
            VexEncodingType::Vex3Byte
        };
        let vex_bytes = VexPrefixBuilder::build(&config);
        let modrm = 0xC0 | ((dest & 0x07) << 3) | (src2 & 0x07);

        VexEncodedInstruction {
            vex_prefix: vex_bytes,
            opcode: vec![opcode],
            modrm: Some(modrm),
            sib: None,
            displacement: vec![],
            immediate: vec![],
            encoding_type,
        }
    }

    /// Encode AVX integer packed arithmetic (reg, reg, reg).
    ///
    /// Covers VPADDB/W/D/Q, VPSUBB/W/D/Q, etc.
    /// Opcode map: 0F, pp=66.
    pub fn encode_avx_int_packed(
        opcode: u8,
        dest: u8,
        src1: u8,
        src2: u8,
        vl: VexVectorLength,
    ) -> VexEncodedInstruction {
        Self::encode_avx_pd(opcode, dest, src1, src2, vl)
    }

    /// Encode FMA3 instruction (VFMADD132PS, etc.).
    ///
    /// Opcode map: 0F38, pp varies.
    pub fn encode_fma3(
        opcode: u8,
        prefix: VexMandatoryPrefix,
        dest: u8,
        src1: u8,
        src2: u8,
        vl: VexVectorLength,
    ) -> VexEncodedInstruction {
        let config = VexPrefixConfig::from_registers(
            VexOpcodeMap::Map0F38,
            prefix,
            vl,
            src1,
            dest,
            src2,
            None,
            false,
        );
        let encoding_type = if config.can_use_2byte_vex() {
            VexEncodingType::Vex2Byte
        } else {
            VexEncodingType::Vex3Byte
        };
        let vex_bytes = VexPrefixBuilder::build(&config);
        let modrm = 0xC0 | ((dest & 0x07) << 3) | (src2 & 0x07);

        VexEncodedInstruction {
            vex_prefix: vex_bytes,
            opcode: vec![opcode],
            modrm: Some(modrm),
            sib: None,
            displacement: vec![],
            immediate: vec![],
            encoding_type,
        }
    }

    /// Encode BMI1 instruction.
    ///
    /// BMI1 instructions use VEX encoding with GPR operands (32/64-bit).
    /// Opcode map: 0F38, pp=none (or 66/F2/F3 for some).
    pub fn encode_bmi1(
        opcode: u8,
        prefix: VexMandatoryPrefix,
        dest: u8,
        src1: u8,
        src2: u8,
        w: bool,
    ) -> VexEncodedInstruction {
        let config = VexPrefixConfig::from_registers(
            VexOpcodeMap::Map0F38,
            prefix,
            VexVectorLength::L128,
            src1,
            dest,
            src2,
            None,
            w,
        );
        let encoding_type = if config.can_use_2byte_vex() {
            VexEncodingType::Vex2Byte
        } else {
            VexEncodingType::Vex3Byte
        };
        let vex_bytes = VexPrefixBuilder::build(&config);
        let modrm = 0xC0 | ((dest & 0x07) << 3) | (src2 & 0x07);

        VexEncodedInstruction {
            vex_prefix: vex_bytes,
            opcode: vec![opcode],
            modrm: Some(modrm),
            sib: None,
            displacement: vec![],
            immediate: vec![],
            encoding_type,
        }
    }

    /// Encode a VEX instruction with an immediate byte (e.g., SHA1RNDS4, RORX).
    pub fn encode_vex_with_imm8(
        map: VexOpcodeMap,
        prefix: VexMandatoryPrefix,
        vl: VexVectorLength,
        opcode: u8,
        dest: u8,
        src1: u8,
        src2: u8,
        imm8: u8,
    ) -> VexEncodedInstruction {
        let config =
            VexPrefixConfig::from_registers(map, prefix, vl, src1, dest, src2, None, false);
        let encoding_type = if config.can_use_2byte_vex() {
            VexEncodingType::Vex2Byte
        } else {
            VexEncodingType::Vex3Byte
        };
        let vex_bytes = VexPrefixBuilder::build(&config);
        let modrm = 0xC0 | ((dest & 0x07) << 3) | (src2 & 0x07);

        VexEncodedInstruction {
            vex_prefix: vex_bytes,
            opcode: vec![opcode],
            modrm: Some(modrm),
            sib: None,
            displacement: vec![],
            immediate: vec![imm8],
            encoding_type,
        }
    }

    /// Encode VZEROUPPER (clears upper 128 bits of all YMM registers).
    ///
    /// VEX.128.0F.WIG 77 — No ModR/M, no operands.
    pub fn encode_vzeroupper() -> VexEncodedInstruction {
        let config = VexPrefixConfig {
            r: false,
            x: false,
            b: false,
            w: false,
            mmmmm: VEX_MMMMM_0F,
            vvvv: 0xF, // all ones = no source register
            l: false,
            pp: VEX_PP_NONE,
        };
        let vex_bytes = VexPrefixBuilder::build_2byte_from_config(&config).to_vec();

        VexEncodedInstruction {
            vex_prefix: vex_bytes,
            opcode: vec![0x77],
            modrm: None,
            sib: None,
            displacement: vec![],
            immediate: vec![],
            encoding_type: VexEncodingType::Vex2Byte,
        }
    }

    /// Encode VZEROALL (zeros all YMM registers).
    ///
    /// VEX.256.0F.WIG 77 — No ModR/M, no operands.
    pub fn encode_vzeroall() -> VexEncodedInstruction {
        let config = VexPrefixConfig {
            r: false,
            x: false,
            b: false,
            w: false,
            mmmmm: VEX_MMMMM_0F,
            vvvv: 0xF,
            l: true, // L=1 for 256-bit
            pp: VEX_PP_NONE,
        };
        let vex_bytes = VexPrefixBuilder::build_3byte_from_config(&config).to_vec();

        VexEncodedInstruction {
            vex_prefix: vex_bytes,
            opcode: vec![0x77],
            modrm: None,
            sib: None,
            displacement: vec![],
            immediate: vec![],
            encoding_type: VexEncodingType::Vex3Byte,
        }
    }

    /// Encode VLDMXCSR / VSTMXCSR (AVX versions of LDMXCSR/STMXCSR).
    ///
    /// VEX.LZ.0F.WIG AE — LDMXCSR m32
    /// VEX.LZ.0F.WIG AE — STMXCSR m32
    /// LZ means L must be 0.
    pub fn encode_vldmxcsr(mem_op: bool) -> VexEncodedInstruction {
        let config = VexPrefixConfig {
            r: false,
            x: false,
            b: false,
            w: false,
            mmmmm: VEX_MMMMM_0F,
            vvvv: 0xF,
            l: false,
            pp: VEX_PP_NONE,
        };
        let vex_bytes = if config.can_use_2byte_vex() {
            VexPrefixBuilder::build_2byte_from_config(&config).to_vec()
        } else {
            VexPrefixBuilder::build_3byte_from_config(&config).to_vec()
        };
        let encoding_type = if config.can_use_2byte_vex() {
            VexEncodingType::Vex2Byte
        } else {
            VexEncodingType::Vex3Byte
        };

        let modrm = if mem_op {
            0x04 // Mod=00, reg=0, rm=100 (SIB follows)
        } else {
            0xC0 // Mod=11, reg=0, rm=0 (register — unusual for LDMXCSR)
        };

        VexEncodedInstruction {
            vex_prefix: vex_bytes,
            opcode: vec![0xAE],
            modrm: Some(modrm),
            sib: None,
            displacement: vec![],
            immediate: vec![],
            encoding_type,
        }
    }
}

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    VEX WIG / LIG Bit Convention Utilities                  ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

/// VEX WIG (W Ignored) and LIG (L Ignored) convention helpers.
///
/// Many VEX instructions specify WIG (W-bit is ignored) or LIG (L-bit is
/// ignored). These helpers manage the proper encoding of such bits.
#[derive(Debug, Clone)]
pub struct VexWigLigConventions;

impl VexWigLigConventions {
    /// WIG: The W bit is ignored. Can be set to either 0 or 1.
    /// Intel recommends setting W=0 for WIG instructions.
    pub const WIG_W_VALUE: bool = false;

    /// LIG: The L bit is ignored. Intel requires L=0 for LIG instructions
    /// on some processors, but generally 0 is safe.
    pub const LIG_L_VALUE: bool = false;

    /// Apply WIG convention (force W=0 for W-ignored instructions).
    pub fn apply_wig(config: &mut VexPrefixConfig) {
        config.w = false;
    }

    /// Apply LIG convention (force L=0 for L-ignored instructions).
    pub fn apply_lig(config: &mut VexPrefixConfig) {
        config.l = false;
    }

    /// Apply both WIG and LIG conventions.
    pub fn apply_wig_lig(config: &mut VexPrefixConfig) {
        config.w = false;
        config.l = false;
    }

    /// Check if an instruction is WIG based on its opcode map and opcode.
    /// This is a heuristic — most SIMD floating-point instructions are WIG.
    pub fn is_likely_wig(map: VexOpcodeMap, _opcode: u8) -> bool {
        // Most AVX floating-point instructions are WIG.
        // 64-bit integer operations typically use W=1.
        matches!(map, VexOpcodeMap::Map0F)
    }

    /// Check if an instruction is LIG based on its behavior.
    /// Instructions that are inherently scalar (operating on a single element)
    /// are typically LIG.
    pub fn is_likely_lig(is_scalar: bool) -> bool {
        is_scalar
    }
}

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    Tests                                                    ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

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

    // ── VEX Constants ──────────────────────────────────────────────────────────

    #[test]
    fn test_vex_constants() {
        assert_eq!(VEX2_PREFIX, 0xC5);
        assert_eq!(VEX3_PREFIX, 0xC4);
        assert_eq!(VEX_MMMMM_0F, 0x01);
        assert_eq!(VEX_MMMMM_0F38, 0x02);
        assert_eq!(VEX_MMMMM_0F3A, 0x03);
        assert_eq!(VEX_PP_NONE, 0x00);
        assert_eq!(VEX_PP_66, 0x01);
        assert_eq!(VEX_PP_F3, 0x02);
        assert_eq!(VEX_PP_F2, 0x03);
    }

    // ── Register Inversion ─────────────────────────────────────────────────────

    #[test]
    fn test_vex_invert_reg() {
        assert_eq!(vex_invert_reg(0), 0x0F);
        assert_eq!(vex_invert_reg(1), 0x0E);
        assert_eq!(vex_invert_reg(7), 0x08);
        assert_eq!(vex_invert_reg(8), 0x07);
        assert_eq!(vex_invert_reg(15), 0x00);
    }

    #[test]
    fn test_vex_recover_reg() {
        for reg in 0..16u8 {
            let inv = vex_invert_reg(reg);
            let rec = vex_recover_reg(inv);
            assert_eq!(rec, reg, "round-trip failed for reg {}", reg);
        }
    }

    #[test]
    fn test_vex_reg_needs_extension() {
        assert!(!vex_reg_needs_r(0));
        assert!(!vex_reg_needs_r(7));
        assert!(vex_reg_needs_r(8));
        assert!(vex_reg_needs_r(15));

        assert!(!vex_reg_needs_x(0));
        assert!(vex_reg_needs_x(8));

        assert!(!vex_reg_needs_b(0));
        assert!(vex_reg_needs_b(8));
    }

    // ── Opcode Map ─────────────────────────────────────────────────────────────

    #[test]
    fn test_vex_opcode_map_mmmmm() {
        assert_eq!(VexOpcodeMap::Map0F.mmmmm(), 1);
        assert_eq!(VexOpcodeMap::Map0F38.mmmmm(), 2);
        assert_eq!(VexOpcodeMap::Map0F3A.mmmmm(), 3);
    }

    #[test]
    fn test_vex_opcode_map_from_mmmmm() {
        assert_eq!(VexOpcodeMap::from_mmmmm(1), Some(VexOpcodeMap::Map0F));
        assert_eq!(VexOpcodeMap::from_mmmmm(2), Some(VexOpcodeMap::Map0F38));
        assert_eq!(VexOpcodeMap::from_mmmmm(3), Some(VexOpcodeMap::Map0F3A));
        assert_eq!(VexOpcodeMap::from_mmmmm(0), None);
        assert_eq!(VexOpcodeMap::from_mmmmm(4), None);
    }

    #[test]
    fn test_vex_opcode_map_escape_byte_count() {
        assert_eq!(VexOpcodeMap::Map0F.escape_byte_count(), 1);
        assert_eq!(VexOpcodeMap::Map0F38.escape_byte_count(), 2);
        assert_eq!(VexOpcodeMap::Map0F3A.escape_byte_count(), 2);
    }

    // ── Mandatory Prefix ───────────────────────────────────────────────────────

    #[test]
    fn test_vex_mandatory_prefix_pp_bits() {
        assert_eq!(VexMandatoryPrefix::None.pp_bits(), 0);
        assert_eq!(VexMandatoryPrefix::P66.pp_bits(), 1);
        assert_eq!(VexMandatoryPrefix::PF3.pp_bits(), 2);
        assert_eq!(VexMandatoryPrefix::PF2.pp_bits(), 3);
    }

    #[test]
    fn test_vex_mandatory_prefix_from_pp() {
        assert_eq!(
            VexMandatoryPrefix::from_pp(0),
            Some(VexMandatoryPrefix::None)
        );
        assert_eq!(
            VexMandatoryPrefix::from_pp(1),
            Some(VexMandatoryPrefix::P66)
        );
        assert_eq!(
            VexMandatoryPrefix::from_pp(2),
            Some(VexMandatoryPrefix::PF3)
        );
        assert_eq!(
            VexMandatoryPrefix::from_pp(3),
            Some(VexMandatoryPrefix::PF2)
        );
    }

    #[test]
    fn test_vex_mandatory_prefix_from_byte() {
        assert_eq!(VexMandatoryPrefix::from_byte(0x66), VexMandatoryPrefix::P66);
        assert_eq!(VexMandatoryPrefix::from_byte(0xF3), VexMandatoryPrefix::PF3);
        assert_eq!(VexMandatoryPrefix::from_byte(0xF2), VexMandatoryPrefix::PF2);
        assert_eq!(
            VexMandatoryPrefix::from_byte(0x00),
            VexMandatoryPrefix::None
        );
    }

    // ── Vector Length ──────────────────────────────────────────────────────────

    #[test]
    fn test_vex_vector_length() {
        assert_eq!(VexVectorLength::L128.l_bit(), false);
        assert_eq!(VexVectorLength::L256.l_bit(), true);
        assert_eq!(VexVectorLength::L128.width_bytes(), 16);
        assert_eq!(VexVectorLength::L256.width_bytes(), 32);
        assert_eq!(VexVectorLength::L128.width_bits(), 128);
        assert_eq!(VexVectorLength::L256.width_bits(), 256);
        assert_eq!(VexVectorLength::L128.reg_prefix(), "xmm");
        assert_eq!(VexVectorLength::L256.reg_prefix(), "ymm");
        assert_eq!(VexVectorLength::from_l_bit(false), VexVectorLength::L128);
        assert_eq!(VexVectorLength::from_l_bit(true), VexVectorLength::L256);
    }

    // ── VexPrefixConfig ────────────────────────────────────────────────────────

    #[test]
    fn test_vex_prefix_config_default() {
        let cfg = VexPrefixConfig::default();
        assert_eq!(cfg.r, false);
        assert_eq!(cfg.x, false);
        assert_eq!(cfg.b, false);
        assert_eq!(cfg.w, false);
        assert_eq!(cfg.mmmmm, VEX_MMMMM_0F);
        assert_eq!(cfg.pp, VEX_PP_NONE);
    }

    #[test]
    fn test_vex_prefix_config_can_use_2byte() {
        // All registers < 8, map=0F, no W: 2-byte possible
        let cfg = VexPrefixConfig::new()
            .with_map(VexOpcodeMap::Map0F)
            .with_vvvv(1);
        assert!(cfg.can_use_2byte_vex());

        // Map 0F38: 3-byte required
        let cfg = VexPrefixConfig::new().with_map(VexOpcodeMap::Map0F38);
        assert!(!cfg.can_use_2byte_vex());

        // Map 0F with extended reg: 3-byte required
        let cfg = VexPrefixConfig::new()
            .with_map(VexOpcodeMap::Map0F)
            .with_reg_r(8);
        assert!(!cfg.can_use_2byte_vex());

        // Map 0F with W=1: 3-byte required
        let cfg = VexPrefixConfig::new()
            .with_map(VexOpcodeMap::Map0F)
            .with_w(true);
        assert!(!cfg.can_use_2byte_vex());
    }

    #[test]
    fn test_vex_prefix_config_prefix_byte_count() {
        let cfg = VexPrefixConfig::new().with_map(VexOpcodeMap::Map0F);
        assert_eq!(cfg.prefix_byte_count(), 2);

        let cfg = VexPrefixConfig::new().with_map(VexOpcodeMap::Map0F38);
        assert_eq!(cfg.prefix_byte_count(), 3);
    }

    // ── VexPrefixBuilder ───────────────────────────────────────────────────────

    #[test]
    fn test_build_vex2_basic() {
        // VEX2: R=1 (reg < 8), vvvv=~2=0xD, L=0, pp=00
        // byte1 = 1_1101_0_00 = 0xE8
        let bytes = VexPrefixBuilder::build_2byte(true, 0x0D, false, VEX_PP_NONE);
        assert_eq!(bytes[0], 0xC5);
        assert_eq!(bytes[1], 0xE8);
    }

    #[test]
    fn test_build_vex2_from_regs() {
        // vaddps xmm0, xmm1, xmm2: dest=0, src1=1, src2=2
        // R=dest<8 so R=1(inverted=0), vvvv=~1=0xE, L=0, pp=0
        // byte1: 1(R)xxx_0_E_0_00 = 0b1_1110_0_00 = 0xF0? No wait...
        // R=1 means (~R stored as 0), vvvv=~1=0xE << 3 = 0x70, L=0, pp=0
        // byte1 = 0x00 | 0x70 | 0x00 | 0x00 = 0x70
        let bytes = VexPrefixBuilder::build_2byte_from_regs(0, 1, false, VEX_PP_NONE);
        assert_eq!(bytes[0], 0xC5);
        assert_eq!(bytes[1], 0x70);
    }

    #[test]
    fn test_build_vex3_basic() {
        // VEX3: R=1, X=1, B=1, mmmmm=0F=1, W=0, vvvv=~1=0xE, L=0, pp=0
        // byte1: 0_0_0_00001 = 0x01
        // byte2: 0_1110_0_00 = 0x70
        let bytes = VexPrefixBuilder::build_3byte(
            true,
            true,
            true,
            VEX_MMMMM_0F,
            false,
            0x0E,
            false,
            VEX_PP_NONE,
        );
        assert_eq!(bytes[0], 0xC4);
        assert_eq!(bytes[1], 0x01);
        assert_eq!(bytes[2], 0x70);
    }

    #[test]
    fn test_build_vex3_with_w() {
        // VEX3: R=0 (extended), X=1, B=1, mmmmm=0F, W=1, vvvv=~8=7, L=1, pp=F2=3
        // byte1: 1_0_0_00001 = 0x81
        // byte2: 1_0111_1_11 = 0xBF
        let bytes = VexPrefixBuilder::build_3byte(
            false,
            true,
            true,
            VEX_MMMMM_0F,
            true,
            0x07,
            true,
            VEX_PP_F2,
        );
        assert_eq!(bytes[0], 0xC4);
        assert_eq!(bytes[1], 0x81);
        assert_eq!(bytes[2], 0xBF);
    }

    #[test]
    fn test_build_vex_auto_select() {
        // Should auto-select 2-byte VEX
        let cfg = VexPrefixConfig::new()
            .with_map(VexOpcodeMap::Map0F)
            .with_vvvv(1)
            .with_reg_r(0)
            .with_reg_b(0);
        let bytes = VexPrefixBuilder::build(&cfg);
        assert_eq!(bytes.len(), 2);
        assert_eq!(bytes[0], 0xC5);

        // Should auto-select 3-byte VEX (extended reg)
        let cfg = VexPrefixConfig::new()
            .with_map(VexOpcodeMap::Map0F)
            .with_vvvv(1)
            .with_reg_r(8);
        let bytes = VexPrefixBuilder::build(&cfg);
        assert_eq!(bytes.len(), 3);
        assert_eq!(bytes[0], 0xC4);
    }

    // ── VexDecodedPrefix ───────────────────────────────────────────────────────

    #[test]
    fn test_decode_vex2() {
        // C5 E8 = VEX2 with R=1, vvvv=0xD, L=0, pp=0
        let decoded = VexDecodedPrefix::decode_2byte(0xE8);
        assert!(!decoded.is_3byte);
        assert!(decoded.r);
        assert!(!decoded.x);
        assert!(!decoded.b);
        assert_eq!(decoded.mmmmm, VEX_MMMMM_0F);
        assert!(!decoded.w);
        assert_eq!(decoded.vvvv, 0x0D);
        assert_eq!(decoded.true_vvvv(), 2); // ~0xD = 2
        assert!(!decoded.l);
        assert_eq!(decoded.pp, VEX_PP_NONE);
    }

    #[test]
    fn test_decode_vex3() {
        // C4 01 70 = VEX3: R=1, X=1, B=1, mmmmm=1, W=0, vvvv=0xE, L=0, pp=0
        let decoded = VexDecodedPrefix::decode_3byte(0x01, 0x70);
        assert!(decoded.is_3byte);
        assert!(decoded.r);
        assert!(decoded.x);
        assert!(decoded.b);
        assert_eq!(decoded.mmmmm, 1);
        assert!(!decoded.w);
        assert_eq!(decoded.vvvv, 0x0E);
        assert_eq!(decoded.true_vvvv(), 1); // ~0xE = 1
        assert!(!decoded.l);
        assert_eq!(decoded.pp, VEX_PP_NONE);
    }

    #[test]
    fn test_decode_vex_from_slice() {
        // 2-byte VEX
        let (decoded, len) = VexDecodedPrefix::decode(&[0xC5, 0xF8]).unwrap();
        assert_eq!(len, 2);
        assert!(!decoded.is_3byte);

        // 3-byte VEX
        let (decoded, len) = VexDecodedPrefix::decode(&[0xC4, 0xE1, 0x78]).unwrap();
        assert_eq!(len, 3);
        assert!(decoded.is_3byte);

        // Not a VEX prefix
        assert!(VexDecodedPrefix::decode(&[0x90]).is_none()); // NOP
        assert!(VexDecodedPrefix::decode(&[]).is_none());
    }

    #[test]
    fn test_vex_decoded_effective_reg() {
        // R=1 (reg < 8): effective_reg of 3 = 3
        let decoded = VexDecodedPrefix::decode_2byte(0xE8);
        assert_eq!(decoded.effective_reg_r(3), 3);

        // R=0 (reg >= 8): effective_reg of 3 = 11 (0x0B)
        let decoded = VexDecodedPrefix::decode_3byte(0x81, 0x70);
        assert_eq!(decoded.effective_reg_r(3), 11);
    }

    // ── Instruction Length ─────────────────────────────────────────────────────

    #[test]
    fn test_vex_instruction_length_reg_reg() {
        // 2-byte VEX + 1 opcode + ModR/M = 4 bytes
        let cfg = VexPrefixConfig::new().with_map(VexOpcodeMap::Map0F);
        let len = VexInstructionLength::compute(&cfg, 1, true, false, 0, 0);
        assert_eq!(len, 4);
    }

    #[test]
    fn test_vex_instruction_length_with_disp() {
        let cfg = VexPrefixConfig::new().with_map(VexOpcodeMap::Map0F);
        let len = VexInstructionLength::compute(&cfg, 1, true, true, 4, 0);
        // 2(VEX) + 1(op) + 1(modrm) + 1(sib) + 4(disp32) = 9
        assert_eq!(len, 9);
    }

    #[test]
    fn test_vex_instruction_length_3byte_with_imm() {
        let cfg = VexPrefixConfig::new()
            .with_map(VexOpcodeMap::Map0F)
            .with_reg_r(8);
        let len = VexInstructionLength::compute(&cfg, 1, true, false, 0, 1);
        // 3(VEX) + 1(op) + 1(modrm) + 1(imm8) = 6
        assert_eq!(len, 6);
    }

    #[test]
    fn test_vex_max_length() {
        assert_eq!(VexInstructionLength::MAX_LENGTH, 15);
        assert!(VexInstructionLength::is_valid_length(15));
        assert!(!VexInstructionLength::is_valid_length(16));
    }

    // ── Prefix Compression ─────────────────────────────────────────────────────

    #[test]
    fn test_vex_compress_3to2() {
        let cfg = VexPrefixConfig {
            r: false,
            x: false,
            b: false,
            w: false,
            mmmmm: VEX_MMMMM_0F,
            vvvv: 0x0E,
            l: false,
            pp: VEX_PP_NONE,
        };
        let compressed = VexPrefixCompressor::compress(cfg);
        assert!(compressed.can_use_2byte_vex());
    }

    #[test]
    fn test_vex_cannot_compress_map_0f38() {
        let cfg = VexPrefixConfig {
            r: false,
            x: false,
            b: false,
            w: false,
            mmmmm: VEX_MMMMM_0F38,
            vvvv: 0x0E,
            l: false,
            pp: VEX_PP_NONE,
        };
        assert!(!VexPrefixCompressor::can_compress(&cfg));
    }

    #[test]
    fn test_vex_cannot_compress_extended_reg() {
        let cfg = VexPrefixConfig {
            r: false, // R=0 means extended destination register
            x: false,
            b: false,
            w: false,
            mmmmm: VEX_MMMMM_0F,
            vvvv: 0x0E,
            l: false,
            pp: VEX_PP_NONE,
        };
        assert!(!VexPrefixCompressor::can_compress(&cfg));
    }

    #[test]
    fn test_vex_compression_blockers() {
        let cfg = VexPrefixConfig {
            r: true,
            x: false,
            b: true,
            w: true,
            mmmmm: VEX_MMMMM_0F38,
            vvvv: 0x0E,
            l: false,
            pp: VEX_PP_NONE,
        };
        let blockers = VexPrefixCompressor::compression_blockers(&cfg);
        assert!(blockers.len() >= 3);
    }

    // ── Register Restrictions ──────────────────────────────────────────────────

    #[test]
    fn test_vex_register_restrictions_valid() {
        assert!(VexRegisterRestrictions::validate_registers(&[0, 1, 7, 15]).is_ok());
        assert!(VexRegisterRestrictions::validate_registers(&[16]).is_err());
    }

    #[test]
    fn test_vex_max_reg() {
        assert_eq!(VexRegisterRestrictions::MAX_VEX_REG, 15);
    }

    // ── VEX Template Catalog ───────────────────────────────────────────────────

    #[test]
    fn test_vex_template_catalog_has_templates() {
        let templates = VexTemplateCatalog::all_templates();
        assert!(templates.len() >= 30);
    }

    #[test]
    fn test_vex_template_encode_vaddps() {
        let tmpl = VexTemplateCatalog::VADDPS;
        let instr = tmpl.encode_rrr(0, 1, 2);
        // vaddps xmm0, xmm1, xmm2: VEX2 (all regs < 8, map 0F, pp=none)
        assert_eq!(instr.encoding_type, VexEncodingType::Vex2Byte);
        assert_eq!(instr.opcode, vec![0x58]);
        assert!(instr.modrm.is_some());
        assert_eq!(instr.total_length(), 4); // 2-byte VEX + opcode + ModR/M
    }

    #[test]
    fn test_vex_template_encode_vaddps_ymm() {
        let tmpl = VexTemplateCatalog::VADDPS_YMM;
        let instr = tmpl.encode_rrr(0, 1, 2);
        // vaddps ymm0, ymm1, ymm2: VEX3 (L=1 requires 3-byte)
        assert_eq!(instr.encoding_type, VexEncodingType::Vex3Byte);
        assert_eq!(instr.opcode, vec![0x58]);
        assert_eq!(instr.total_length(), 5); // 3-byte VEX + opcode + ModR/M
    }

    #[test]
    fn test_vex_template_encode_vzeroupper() {
        let tmpl = VexTemplateCatalog::VZEROUPPER;
        assert!(!tmpl.has_modrm); // No ModR/M
        assert_eq!(tmpl.opcode, 0x77);
        assert_eq!(tmpl.map, VexOpcodeMap::Map0F);
        assert_eq!(tmpl.vector_length, VexVectorLength::L128);
    }

    // ── X86VEXEncoding ─────────────────────────────────────────────────────────

    #[test]
    fn test_x86_vex_encoding_new() {
        let encoding = X86VEXEncoding::new();
        assert!(encoding.templates.len() >= 30);
        assert!(encoding.prefer_2byte);
    }

    #[test]
    fn test_x86_vex_encoding_encode_from_template() {
        let encoding = X86VEXEncoding::new();
        let instr = encoding.encode_from_template("vaddps", 0, 1, 2).unwrap();
        assert_eq!(instr.opcode, vec![0x58]);
        assert_eq!(instr.encoding_type, VexEncodingType::Vex2Byte);

        let instr = encoding
            .encode_from_template("vperm2f128", 0, 1, 2)
            .unwrap();
        assert_eq!(instr.opcode, vec![0x06]);
        // VPERM2F128 uses Map0F3A, so 3-byte VEX
        assert_eq!(instr.encoding_type, VexEncodingType::Vex3Byte);
    }

    #[test]
    fn test_x86_vex_encoding_config_for_rrr() {
        let encoding = X86VEXEncoding::new();
        let cfg = encoding.config_for_rrr(
            VexOpcodeMap::Map0F,
            VexMandatoryPrefix::None,
            VexVectorLength::L128,
            1, // src1 = xmm1
            0, // dest = xmm0
            2, // src2 = xmm2
            false,
        );
        // All regs < 8, map 0F => 2-byte
        assert!(cfg.can_use_2byte_vex());
    }

    #[test]
    fn test_x86_vex_encoding_validate_registers() {
        let encoding = X86VEXEncoding::new();
        assert!(encoding.validate_registers(&[0, 7, 15]).is_ok());
        assert!(encoding.validate_registers(&[16]).is_err());
    }

    // ── VexFamilyEncoder ───────────────────────────────────────────────────────

    #[test]
    fn test_family_encoder_avx_128_ps() {
        let instr = VexFamilyEncoder::encode_avx_128_ps(0x58, 0, 1, 2);
        assert_eq!(instr.opcode, vec![0x58]);
        assert_eq!(instr.encoding_type, VexEncodingType::Vex2Byte);
        assert!(instr.modrm.is_some());
    }

    #[test]
    fn test_family_encoder_avx_256_ps() {
        let instr = VexFamilyEncoder::encode_avx_256_ps(0x58, 0, 1, 2);
        assert_eq!(instr.opcode, vec![0x58]);
        assert_eq!(instr.encoding_type, VexEncodingType::Vex3Byte);
    }

    #[test]
    fn test_family_encoder_avx_pd() {
        let instr = VexFamilyEncoder::encode_avx_pd(0x58, 0, 1, 2, VexVectorLength::L128);
        assert_eq!(instr.opcode, vec![0x58]);
    }

    #[test]
    fn test_family_encoder_bmi1() {
        // ANDN rax, rbx, rcx (W=1 for 64-bit)
        let instr = VexFamilyEncoder::encode_bmi1(0xF2, VexMandatoryPrefix::None, 0, 3, 1, true);
        assert_eq!(instr.opcode, vec![0xF2]);
        // With W=1, must be VEX3
        assert_eq!(instr.encoding_type, VexEncodingType::Vex3Byte);
    }

    #[test]
    fn test_family_encoder_vzeroupper() {
        let instr = VexFamilyEncoder::encode_vzeroupper();
        assert_eq!(instr.opcode, vec![0x77]);
        assert!(instr.modrm.is_none());
        assert_eq!(instr.encoding_type, VexEncodingType::Vex2Byte);
    }

    #[test]
    fn test_family_encoder_vzeroall() {
        let instr = VexFamilyEncoder::encode_vzeroall();
        assert_eq!(instr.opcode, vec![0x77]);
        assert!(instr.modrm.is_none());
        assert_eq!(instr.encoding_type, VexEncodingType::Vex3Byte);
    }

    // ── VexToLegacyTranslator ──────────────────────────────────────────────────

    #[test]
    fn test_vex_to_legacy_translator() {
        let decoded = VexDecodedPrefix::decode_2byte(0xE8);
        let legacy = VexToLegacyTranslator::translate_prefix(&decoded);
        // No REX, no prefix, 0F escape = just 0x0F
        assert_eq!(legacy, vec![0x0F]);
    }

    #[test]
    fn test_vex_to_legacy_with_rex_and_prefix() {
        // VEX3: R=0, X=0, B=0, mmmmm=0F, W=1, vvvv=~8=7, L=0, pp=66
        // byte1 = 1_1_1_00001 = 0xE1
        // byte2 = 1_0111_0_01 = 0xB9
        let decoded = VexDecodedPrefix::decode_3byte(0xE1, 0xB9);
        let legacy = VexToLegacyTranslator::translate_prefix(&decoded);
        // REX.WRXB = 0x4F
        // pp=66 => 0x66
        // 0F
        assert_eq!(legacy, vec![0x4F, 0x66, 0x0F]);
    }

    #[test]
    fn test_vex_compare_lengths() {
        let decoded = VexDecodedPrefix::decode_2byte(0xE8);
        // 2-byte VEX vs 1-byte 0F => legacy saves 1
        // Actually: VEX=2, legacy=1, so compare = 1-2 = -1 (VEX is bigger)
        let cmp = VexToLegacyTranslator::compare_lengths(&decoded);
        assert_eq!(cmp, -1);

        // VEX3 with REX+0F38 => VEX=3, legacy=3, compare=0
        let decoded = VexDecodedPrefix::decode_3byte(0xE2, 0x78);
        let cmp = VexToLegacyTranslator::compare_lengths(&decoded);
        assert_eq!(cmp, 0); // 3 - 3 = 0
    }

    // ── VexAssemblyPrinter ─────────────────────────────────────────────────────

    #[test]
    fn test_assembly_printer() {
        let decoded = VexDecodedPrefix::decode_2byte(0xE8);
        let s = VexAssemblyPrinter::format_prefix(&decoded);
        assert!(s.contains("VEX2"));
        assert!(s.contains("R="));
        assert!(s.contains("L="));
        assert!(s.contains("pp="));
    }

    #[test]
    fn test_assembly_printer_intel_syntax() {
        let decoded = VexDecodedPrefix::decode_2byte(0x70); // R=1, vvvv=~1=0xE
        let s = VexAssemblyPrinter::print_intel_syntax("vaddps", &decoded, 0, 1, 2);
        assert!(s.contains("vaddps"));
        assert!(s.contains("xmm0"));
        assert!(s.contains("xmm1"));
        assert!(s.contains("xmm2"));
    }

    // ── VexFieldValidator ──────────────────────────────────────────────────────

    #[test]
    fn test_field_validator_valid() {
        let cfg = VexPrefixConfig::new()
            .with_map(VexOpcodeMap::Map0F)
            .with_prefix(VexMandatoryPrefix::P66);
        assert!(VexFieldValidator::validate(&cfg).is_ok());
    }

    #[test]
    fn test_field_validator_invalid_mmmmm() {
        let cfg = VexPrefixConfig {
            mmmmm: 0,
            ..VexPrefixConfig::default()
        };
        assert!(VexFieldValidator::validate(&cfg).is_err());
    }

    #[test]
    fn test_field_validator_invalid_pp() {
        let cfg = VexPrefixConfig {
            pp: 4,
            ..VexPrefixConfig::default()
        };
        assert!(VexFieldValidator::validate(&cfg).is_err());
    }

    // ── VexWigLigConventions ───────────────────────────────────────────────────

    #[test]
    fn test_wig_lig_conventions() {
        let mut cfg = VexPrefixConfig::new()
            .with_map(VexOpcodeMap::Map0F)
            .with_w(true)
            .with_vector_length(VexVectorLength::L256);

        VexWigLigConventions::apply_wig(&mut cfg);
        assert!(!cfg.w);

        VexWigLigConventions::apply_lig(&mut cfg);
        assert!(!cfg.l);
    }

    // ── Integration Tests ──────────────────────────────────────────────────────

    #[test]
    fn test_roundtrip_vex2_encode_decode() {
        // Encode a VEX2 prefix
        let bytes = VexPrefixBuilder::build_2byte(true, 0x0E, false, VEX_PP_NONE);
        assert_eq!(bytes, [0xC5, 0x70]);

        // Decode it back
        let (decoded, len) = VexDecodedPrefix::decode(&bytes).unwrap();
        assert_eq!(len, 2);
        assert!(!decoded.is_3byte);
        assert!(decoded.r);
        assert_eq!(decoded.vvvv, 0x0E);
        assert_eq!(decoded.true_vvvv(), 1);
        assert!(!decoded.l);
        assert_eq!(decoded.pp, VEX_PP_NONE);
    }

    #[test]
    fn test_roundtrip_vex3_encode_decode() {
        let bytes = VexPrefixBuilder::build_3byte(
            false,
            true,
            true,
            VEX_MMMMM_0F38,
            true,
            0x07,
            true,
            VEX_PP_66,
        );
        assert_eq!(bytes[0], 0xC4);

        let (decoded, len) = VexDecodedPrefix::decode(&bytes).unwrap();
        assert_eq!(len, 3);
        assert!(decoded.is_3byte);
        assert!(!decoded.r);
        assert!(decoded.x);
        assert!(decoded.b);
        assert_eq!(decoded.mmmmm, VEX_MMMMM_0F38);
        assert!(decoded.w);
        assert_eq!(decoded.vvvv, 0x07);
        assert_eq!(decoded.true_vvvv(), 8);
        assert!(decoded.l);
        assert_eq!(decoded.pp, VEX_PP_66);
    }

    #[test]
    fn test_full_instruction_assemble() {
        // vaddps xmm0, xmm1, xmm2
        let cfg = VexPrefixConfig::new()
            .with_map(VexOpcodeMap::Map0F)
            .with_vvvv(1)
            .with_reg_r(0)
            .with_reg_b(2);

        let mut instr = VexEncodedInstruction::new(VexEncodingType::Vex2Byte);
        instr.vex_prefix = VexPrefixBuilder::build(&cfg);
        instr.opcode = vec![0x58];
        instr.modrm = Some(0xC0 | ((0 & 0x07) << 3) | (2 & 0x07)); // Mod=11, reg=xmm0, rm=xmm2

        let assembled = instr.assemble();
        // 2-byte VEX + 0x58 + ModR/M = 4 bytes
        assert_eq!(assembled.len(), 4);
        assert!(instr.is_valid());
    }

    #[test]
    fn test_all_vex_templates_valid() {
        for (_name, tmpl) in VexTemplateCatalog::all_templates() {
            let instr = tmpl.encode_rrr(0, 1, 2);
            assert!(instr.is_valid(), "Template produced invalid instruction");
        }
    }

    #[test]
    fn test_vex_byte1_table_all_combinations() {
        let combos = Vex2Byte1Table::all_combinations();
        assert_eq!(combos.len(), 256);
    }

    #[test]
    fn test_vex3_valid_mmmmm_values() {
        assert_eq!(Vex3ByteTable::VALID_MMMMM.len(), 3);
        assert!(Vex3ByteTable::VALID_MMMMM.contains(&VEX_MMMMM_0F));
        assert!(Vex3ByteTable::VALID_MMMMM.contains(&VEX_MMMMM_0F38));
        assert!(Vex3ByteTable::VALID_MMMMM.contains(&VEX_MMMMM_0F3A));
    }

    #[test]
    fn test_vex3_byte1_values_for_each_map() {
        for &mmmmm in &Vex3ByteTable::VALID_MMMMM {
            let values = Vex3ByteTable::valid_byte1_values(mmmmm);
            assert_eq!(values.len(), 8); // 2^3 RXB combinations
        }
    }

    #[test]
    fn test_vex_encoding_type_byte_count() {
        assert_eq!(VexEncodingType::Vex2Byte.byte_count(), 2);
        assert_eq!(VexEncodingType::Vex3Byte.byte_count(), 3);
    }

    #[test]
    fn test_all_vex_opcodes_nonzero() {
        for (_name, tmpl) in VexTemplateCatalog::all_templates() {
            assert!(tmpl.opcode != 0, "Template has zero opcode");
        }
    }

    #[test]
    fn test_vex_config_from_registers() {
        let cfg = VexPrefixConfig::from_registers(
            VexOpcodeMap::Map0F38,
            VexMandatoryPrefix::P66,
            VexVectorLength::L256,
            1,        // vvvv
            8,        // modrm_reg (extended -> R=0)
            9,        // modrm_rm (extended -> B=0)
            Some(10), // sib_index (extended -> X=0)
            true,     // W=1
        );
        assert!(!cfg.r); // extended reg: R is 0 (false means R'=0, which means reg>=8)
        assert!(!cfg.x); // extended index
        assert!(!cfg.b); // extended rm
        assert!(cfg.w);
        assert_eq!(cfg.mmmmm, VEX_MMMMM_0F38);
        assert_eq!(cfg.pp, VEX_PP_66);
        assert!(cfg.l);
    }

    #[test]
    fn test_vex_bytes_saved() {
        // Simple case: VEX2 vs legacy (0F escape only)
        let cfg = VexPrefixConfig::new().with_map(VexOpcodeMap::Map0F);
        let saved = VexInstructionLength::bytes_saved_vs_legacy(&cfg, false);
        // legacy: 0F = 1 byte, VEX2 = 2 bytes => 1-2 = -1 (VEX is 1 byte larger)
        assert_eq!(saved, -1);

        // Complex case: REX + prefix + 0F38 vs VEX3
        let cfg = VexPrefixConfig::new()
            .with_map(VexOpcodeMap::Map0F38)
            .with_prefix(VexMandatoryPrefix::P66);
        let saved = VexInstructionLength::bytes_saved_vs_legacy(&cfg, true);
        // legacy: REX(1) + 66(1) + 0F38(2) = 4, VEX3 = 3 => 4-3 = +1
        assert_eq!(saved, 1);
    }
}