llvm-native-core 0.1.11

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
//! RISC-V Vector Extension (RVV 1.0) Instruction Selection.
//!
//! Clean-room behavioral reconstruction from the RISC-V "V" Vector
//! Extension specification (version 1.0). This module maps vector
//! IR operations to RISC-V vector machine instructions.
//!
//! ## Coverage
//! - **Integer vector ops**: VADD, VSUB, VMUL, VDIV, VRSUB, VAND, VOR, VXOR
//! - **FP vector ops**: VFADD, VFSUB, VFMUL, VFDIV, VFSQRT, VFMADD,
//!   VFNMADD, VFMSUB, VFNMSUB
//! - **Comparison**: integer and FP vector comparisons
//! - **Reduction**: integer and FP reductions
//! - **Slide**: VSLIDEUP, VSLIDEDOWN, VSLIDE1UP, VSLIDE1DOWN
//! - **Gather/Scatter**: VLUXEI, VSOXEI
//! - **Compress**: VCOMPRESS
//! - **Permute**: VRGATHER, VMV, VMERGE
//! - **Mask**: VMAND, VMOR, VXOR, VMNOT
//! - **Type conversion**: VSEXT, VZEXT, VFCVT
//! - **VL configuration**: dynamic vector length management
//!
//! Zero LLVM source code consultation.

use super::riscv_instr_info::RiscVOpcode;
use super::riscv_register_info::*;
use std::collections::HashMap;

// ═══════════════════════════════════════════════════════════════════════════════
// RVV Opcodes
// ═══════════════════════════════════════════════════════════════════════════════

/// RISC-V V-extension pseudo-opcodes for instruction selection.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RiscVVectorOpcode {
    // Integer Vector Arithmetic (VV, VX, VI variants implied)
    VAddVV,
    VAddVX,
    VAddVI,
    VSubVV,
    VSubVX,
    VMulVV,
    VMulVX,
    VDivVV,
    VDivVX,
    VRSubVV,
    VRSubVX,
    // Integer Logical
    VAndVV,
    VAndVX,
    VAndVI,
    VOrVV,
    VOrVX,
    VOrVI,
    VXorVV,
    VXorVX,
    VXorVI,
    // Integer Shift
    VSllVV,
    VSllVX,
    VSllVI,
    VSrlVV,
    VSrlVX,
    VSrlVI,
    VSraVV,
    VSraVX,
    VSraVI,
    // Integer Min/Max
    VMinVV,
    VMinVX,
    VMaxVV,
    VMaxVX,
    VMinuVV,
    VMaxuVV,
    // FP Vector Arithmetic
    VFAddVV,
    VFAddVF,
    VFSubVV,
    VFSubVF,
    VFMulVV,
    VFMulVF,
    VFDivVV,
    VFDivVF,
    VFSqrtV,
    // FP Fused Multiply-Add
    VFMAddVV,
    VFMAddVF,
    VFNMAddVV,
    VFNMAddVF,
    VFMSubVV,
    VFMSubVF,
    VFNMSubVV,
    VFNMSubVF,
    // FP Min/Max/Sign
    VFMinVV,
    VFMinVF,
    VFMaxVV,
    VFMaxVF,
    VFSgnjVV,
    VFSgnjVF,
    VFSgnjnVV,
    VFSgnjxVV,
    // Integer Comparisons
    VMSeqVV,
    VMSeqVX,
    VMSeqVI,
    VMSneVV,
    VMSneVX,
    VMSneVI,
    VMSltVV,
    VMSltVX,
    VMSltuVV,
    VMSltuVX,
    VMSleVV,
    VMSleVX,
    VMSleVI,
    VMSleuVV,
    VMSgtVV,
    VMSgtVX,
    VMSgtuVV,
    // FP Comparisons
    VMFEqVV,
    VMFEqVF,
    VMFNeVV,
    VMFNeVF,
    VMFLtVV,
    VMFLtVF,
    VMFLeVV,
    VMFLeVF,
    VMFGtVV,
    VMFGtVF,
    VMFGeVV,
    VMFGeVF,
    // Integer Reduction
    VRedSumVS,
    VRedMaxVS,
    VRedMinVS,
    VRedAndVS,
    VRedOrVS,
    VRedXorVS,
    VRedMaxuVS,
    VRedMinuVS,
    // FP Reduction
    VFredosumVS,
    VFredusumVS,
    VFredmaxVS,
    VFredminVS,
    // Slide
    VSlideupVX,
    VSlideupVI,
    VSlidedownVX,
    VSlidedownVI,
    VSlide1upVX,
    VSlide1downVX,
    VFSlide1upVF,
    VFSlide1downVF,
    // Indexed Load/Store (Gather/Scatter)
    VLuxei8V,
    VLuxei16V,
    VLuxei32V,
    VLuxei64V,
    VLoxei8V,
    VLoxei16V,
    VLoxei32V,
    VLoxei64V,
    VSuxei8V,
    VSuxei16V,
    VSuxei32V,
    VSuxei64V,
    VSoxei8V,
    VSoxei16V,
    VSoxei32V,
    VSoxei64V,
    // Compress
    VCompressVM,
    // Permute
    VRGatherVV,
    VRGatherVX,
    VRGatherei16VV,
    VMvVV,
    VMvVX,
    VMvVI,
    VMergeVVM,
    VMergeVXM,
    VMergeVIM,
    VMVnV,
    // Mask Logic
    VMandMM,
    VMnandMM,
    VMandnMM,
    VMxorMM,
    VMorMM,
    VMnorMM,
    VMornMM,
    VMxnorMM,
    VMMvM,
    VMCpyM,
    VMClrM,
    VMSetM,
    VMNotM,
    VMSbfM,
    VMSifM,
    VMsofM,
    // Type Conversion
    VSextVF2,
    VSextVF4,
    VSextVF8,
    VZextVF2,
    VZextVF4,
    VZextVF8,
    VFcvt_xu_fV,
    VFcvt_x_fV,
    VFcvt_rtz_xu_fV,
    VFcvt_rtz_x_fV,
    VFcvt_f_xuV,
    VFcvt_f_xV,
    VFcvt_f_fV,
    VFwcvt_xu_fV,
    VFwcvt_x_fV,
    VFwcvt_rtz_xu_fV,
    VFwcvt_rtz_x_fV,
    VFwcvt_f_xuV,
    VFwcvt_f_xV,
    VFwcvt_f_fV,
    VFncvt_xu_fV,
    VFncvt_x_fV,
    VFncvt_rtz_xu_fV,
    VFncvt_rtz_x_fV,
    VFncvt_f_xuV,
    VFncvt_f_xV,
    VFncvt_f_fV,
    VFncvt_rod_f_fV,
}

impl RiscVVectorOpcode {
    /// Get the assembly mnemonic for the vector opcode.
    pub fn mnemonic(&self) -> &'static str {
        match self {
            // Integer arithmetic
            RiscVVectorOpcode::VAddVV | RiscVVectorOpcode::VAddVX | RiscVVectorOpcode::VAddVI => {
                "vadd"
            }
            RiscVVectorOpcode::VSubVV | RiscVVectorOpcode::VSubVX => "vsub",
            RiscVVectorOpcode::VMulVV | RiscVVectorOpcode::VMulVX => "vmul",
            RiscVVectorOpcode::VDivVV | RiscVVectorOpcode::VDivVX => "vdiv",
            RiscVVectorOpcode::VRSubVV | RiscVVectorOpcode::VRSubVX => "vrsub",
            // Logical
            RiscVVectorOpcode::VAndVV | RiscVVectorOpcode::VAndVX | RiscVVectorOpcode::VAndVI => {
                "vand"
            }
            RiscVVectorOpcode::VOrVV | RiscVVectorOpcode::VOrVX | RiscVVectorOpcode::VOrVI => "vor",
            RiscVVectorOpcode::VXorVV | RiscVVectorOpcode::VXorVX | RiscVVectorOpcode::VXorVI => {
                "vxor"
            }
            // Shift
            RiscVVectorOpcode::VSllVV | RiscVVectorOpcode::VSllVX | RiscVVectorOpcode::VSllVI => {
                "vsll"
            }
            RiscVVectorOpcode::VSrlVV | RiscVVectorOpcode::VSrlVX | RiscVVectorOpcode::VSrlVI => {
                "vsrl"
            }
            RiscVVectorOpcode::VSraVV | RiscVVectorOpcode::VSraVX | RiscVVectorOpcode::VSraVI => {
                "vsra"
            }
            // FP arithmetic
            RiscVVectorOpcode::VFAddVV | RiscVVectorOpcode::VFAddVF => "vfadd",
            RiscVVectorOpcode::VFSubVV | RiscVVectorOpcode::VFSubVF => "vfsub",
            RiscVVectorOpcode::VFMulVV | RiscVVectorOpcode::VFMulVF => "vfmul",
            RiscVVectorOpcode::VFDivVV | RiscVVectorOpcode::VFDivVF => "vfdiv",
            RiscVVectorOpcode::VFSqrtV => "vfsqrt",
            // FMA
            RiscVVectorOpcode::VFMAddVV | RiscVVectorOpcode::VFMAddVF => "vfmadd",
            RiscVVectorOpcode::VFNMAddVV | RiscVVectorOpcode::VFNMAddVF => "vfnmadd",
            RiscVVectorOpcode::VFMSubVV | RiscVVectorOpcode::VFMSubVF => "vfmsub",
            RiscVVectorOpcode::VFNMSubVV | RiscVVectorOpcode::VFNMSubVF => "vfnmsub",
            // Integer comparison
            RiscVVectorOpcode::VMSeqVV
            | RiscVVectorOpcode::VMSeqVX
            | RiscVVectorOpcode::VMSeqVI => "vmseq",
            RiscVVectorOpcode::VMSneVV
            | RiscVVectorOpcode::VMSneVX
            | RiscVVectorOpcode::VMSneVI => "vmsne",
            RiscVVectorOpcode::VMSltVV | RiscVVectorOpcode::VMSltVX => "vmslt",
            RiscVVectorOpcode::VMSltuVV | RiscVVectorOpcode::VMSltuVX => "vmsltu",
            RiscVVectorOpcode::VMSleVV
            | RiscVVectorOpcode::VMSleVX
            | RiscVVectorOpcode::VMSleVI => "vmsle",
            RiscVVectorOpcode::VMSleuVV => "vmsleu",
            RiscVVectorOpcode::VMSgtVV | RiscVVectorOpcode::VMSgtVX => "vmsgt",
            RiscVVectorOpcode::VMSgtuVV => "vmsgtu",
            // FP comparison
            RiscVVectorOpcode::VMFEqVV | RiscVVectorOpcode::VMFEqVF => "vmfeq",
            RiscVVectorOpcode::VMFNeVV | RiscVVectorOpcode::VMFNeVF => "vmfne",
            RiscVVectorOpcode::VMFLtVV | RiscVVectorOpcode::VMFLtVF => "vmflt",
            RiscVVectorOpcode::VMFLeVV | RiscVVectorOpcode::VMFLeVF => "vmfle",
            RiscVVectorOpcode::VMFGtVV | RiscVVectorOpcode::VMFGtVF => "vmfgt",
            RiscVVectorOpcode::VMFGeVV | RiscVVectorOpcode::VMFGeVF => "vmfge",
            // Reduction
            RiscVVectorOpcode::VRedSumVS => "vredsum",
            RiscVVectorOpcode::VRedMaxVS => "vredmax",
            RiscVVectorOpcode::VRedMinVS => "vredmin",
            RiscVVectorOpcode::VRedAndVS => "vredand",
            RiscVVectorOpcode::VRedOrVS => "vredor",
            RiscVVectorOpcode::VRedXorVS => "vredxor",
            RiscVVectorOpcode::VRedMaxuVS => "vredmaxu",
            RiscVVectorOpcode::VRedMinuVS => "vredminu",
            RiscVVectorOpcode::VFredosumVS => "vfredosum",
            RiscVVectorOpcode::VFredusumVS => "vfredusum",
            RiscVVectorOpcode::VFredmaxVS => "vfredmax",
            RiscVVectorOpcode::VFredminVS => "vfredmin",
            // Slide
            RiscVVectorOpcode::VSlideupVX | RiscVVectorOpcode::VSlideupVI => "vslideup",
            RiscVVectorOpcode::VSlidedownVX | RiscVVectorOpcode::VSlidedownVI => "vslidedown",
            RiscVVectorOpcode::VSlide1upVX => "vslide1up",
            RiscVVectorOpcode::VSlide1downVX => "vslide1down",
            RiscVVectorOpcode::VFSlide1upVF => "vfslide1up",
            RiscVVectorOpcode::VFSlide1downVF => "vfslide1down",
            // Indexed
            RiscVVectorOpcode::VLuxei8V => "vluxei8",
            RiscVVectorOpcode::VLuxei16V => "vluxei16",
            RiscVVectorOpcode::VLuxei32V => "vluxei32",
            RiscVVectorOpcode::VLuxei64V => "vluxei64",
            RiscVVectorOpcode::VLoxei8V => "vloxei8",
            RiscVVectorOpcode::VLoxei16V => "vloxei16",
            RiscVVectorOpcode::VLoxei32V => "vloxei32",
            RiscVVectorOpcode::VLoxei64V => "vloxei64",
            RiscVVectorOpcode::VSuxei8V => "vsuxei8",
            RiscVVectorOpcode::VSuxei16V => "vsuxei16",
            RiscVVectorOpcode::VSuxei32V => "vsuxei32",
            RiscVVectorOpcode::VSuxei64V => "vsuxei64",
            RiscVVectorOpcode::VSoxei8V => "vsoxei8",
            RiscVVectorOpcode::VSoxei16V => "vsoxei16",
            RiscVVectorOpcode::VSoxei32V => "vsoxei32",
            RiscVVectorOpcode::VSoxei64V => "vsoxei64",
            // Compress
            RiscVVectorOpcode::VCompressVM => "vcompress",
            // Permute
            RiscVVectorOpcode::VRGatherVV | RiscVVectorOpcode::VRGatherVX => "vrgather",
            RiscVVectorOpcode::VRGatherei16VV => "vrgatherei16",
            RiscVVectorOpcode::VMvVV | RiscVVectorOpcode::VMvVX | RiscVVectorOpcode::VMvVI => "vmv",
            RiscVVectorOpcode::VMergeVVM
            | RiscVVectorOpcode::VMergeVXM
            | RiscVVectorOpcode::VMergeVIM => "vmerge",
            RiscVVectorOpcode::VMVnV => "vmvn",
            // Mask
            RiscVVectorOpcode::VMandMM
            | RiscVVectorOpcode::VMnandMM
            | RiscVVectorOpcode::VMandnMM => "vmand",
            RiscVVectorOpcode::VMorMM | RiscVVectorOpcode::VMnorMM | RiscVVectorOpcode::VMornMM => {
                "vmor"
            }
            RiscVVectorOpcode::VMxorMM | RiscVVectorOpcode::VMxnorMM => "vmxor",
            RiscVVectorOpcode::VMMvM | RiscVVectorOpcode::VMCpyM => "vmmv",
            RiscVVectorOpcode::VMClrM => "vmclr",
            RiscVVectorOpcode::VMSetM => "vmset",
            RiscVVectorOpcode::VMNotM => "vmnot",
            RiscVVectorOpcode::VMSbfM => "vmsbf",
            RiscVVectorOpcode::VMSifM => "vmsif",
            RiscVVectorOpcode::VMsofM => "vmsof",
            // Conversion
            RiscVVectorOpcode::VSextVF2
            | RiscVVectorOpcode::VSextVF4
            | RiscVVectorOpcode::VSextVF8 => "vsext",
            RiscVVectorOpcode::VZextVF2
            | RiscVVectorOpcode::VZextVF4
            | RiscVVectorOpcode::VZextVF8 => "vzext",
            _ => "v???",
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// RVV Vector Length / Type Configuration
// ═══════════════════════════════════════════════════════════════════════════════

/// SEW (Selected Element Width) for vector operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RVVSEW {
    E8 = 8,
    E16 = 16,
    E32 = 32,
    E64 = 64,
}

impl RVVSEW {
    pub fn bits(&self) -> u32 {
        *self as u32
    }
}

/// LMUL (Vector Length Multiplier).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RVVLMUL {
    MF8, // 1/8
    MF4, // 1/4
    MF2, // 1/2
    M1,  // 1
    M2,  // 2
    M4,  // 4
    M8,  // 8
}

impl RVVLMUL {
    pub fn fraction(&self) -> f64 {
        match self {
            RVVLMUL::MF8 => 0.125,
            RVVLMUL::MF4 => 0.25,
            RVVLMUL::MF2 => 0.5,
            RVVLMUL::M1 => 1.0,
            RVVLMUL::M2 => 2.0,
            RVVLMUL::M4 => 4.0,
            RVVLMUL::M8 => 8.0,
        }
    }

    pub fn encoding(&self) -> u32 {
        match self {
            RVVLMUL::MF8 => 5,
            RVVLMUL::MF4 => 6,
            RVVLMUL::MF2 => 7,
            RVVLMUL::M1 => 0,
            RVVLMUL::M2 => 1,
            RVVLMUL::M4 => 2,
            RVVLMUL::M8 => 3,
        }
    }
}

/// Vector length (VL) configuration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RVVConfig {
    pub sew: RVVSEW,
    pub lmul: RVVLMUL,
    pub vl: u64,   // Vector length (number of elements)
    pub vlen: u64, // Hardware VLEN in bits
    pub tail_agnostic: bool,
    pub mask_agnostic: bool,
    pub masked: bool, // Whether to use mask
}

impl RVVConfig {
    pub fn new(vlen_bits: u64) -> Self {
        Self {
            sew: RVVSEW::E32,
            lmul: RVVLMUL::M1,
            vl: vlen_bits / 32,
            vlen: vlen_bits,
            tail_agnostic: true,
            mask_agnostic: true,
            masked: false,
        }
    }

    /// Set SEW and compute VL.
    pub fn with_sew(mut self, sew: RVVSEW) -> Self {
        self.sew = sew;
        self.vl = (self.lmul.fraction() * (self.vlen as f64 / sew.bits() as f64)) as u64;
        self
    }

    /// Set LMUL and recompute VL.
    pub fn with_lmul(mut self, lmul: RVVLMUL) -> Self {
        self.lmul = lmul;
        self.vl = (lmul.fraction() * (self.vlen as f64 / self.sew.bits() as f64)) as u64;
        self
    }

    /// Enable masking.
    pub fn with_mask(mut self) -> Self {
        self.masked = true;
        self
    }

    /// Compute the total vector register group size in bits.
    pub fn vreg_bits(&self) -> u64 {
        (self.vlen as f64 * self.lmul.fraction()) as u64
    }

    /// Check if a configuration is valid.
    pub fn is_valid(&self) -> bool {
        // VLMAX = LMUL * VLEN / SEW
        let vlmax = (self.vlen as f64 * self.lmul.fraction() / self.sew.bits() as f64) as u64;
        self.vl > 0 && self.vl <= vlmax
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// RVV Instruction Selection Patterns
// ═══════════════════════════════════════════════════════════════════════════════

/// RVV instruction selection result: maps IR op to RVV machine opcode.
#[derive(Debug, Clone)]
pub struct RVVISelResult {
    pub opcode: RiscVVectorOpcode,
    pub dest_reg: u32,
    pub src1_reg: u32,
    pub src2_reg: u32,
    pub mask_reg: Option<u32>,
    pub config: RVVConfig,
    pub immediate: Option<i64>,
}

/// The RVV instruction selector.
pub struct RiscVVectorISel {
    /// ISel patterns: (ir_opcode, type_info) → RVV opcode
    patterns: Vec<VectorISelPattern>,
    /// VLEN bits for the target hardware.
    vlen_bits: u64,
    /// Whether V extension is available.
    has_v_extension: bool,
    /// Current vector configuration.
    config: RVVConfig,
    /// Mapping from virtual vector registers to physical vregs.
    vreg_map: HashMap<u32, u32>,
}

#[derive(Debug, Clone)]
struct VectorISelPattern {
    /// LLVM IR scalar opcode (e.g., Add, FAdd).
    ir_opcode: u32,
    /// Operand type kind: i8/i16/i32/i64/f16/f32/f64.
    type_width: u32,
    /// Whether the type is floating-point.
    is_fp: bool,
    /// Whether second operand is a scalar (VX/VI form).
    scalar_op2: bool,
    /// Whether second operand is an immediate.
    imm_op2: bool,
    /// The resulting RVV opcode.
    rvv_opcode: RiscVVectorOpcode,
}

impl RiscVVectorISel {
    pub fn new(vlen_bits: u64, has_v_extension: bool) -> Self {
        let mut patterns = vec![];

        // Register all ISel patterns
        Self::register_integer_arith_patterns(&mut patterns);
        Self::register_integer_logical_patterns(&mut patterns);
        Self::register_integer_shift_patterns(&mut patterns);
        Self::register_integer_compare_patterns(&mut patterns);
        Self::register_fp_arith_patterns(&mut patterns);
        Self::register_fp_compare_patterns(&mut patterns);
        Self::register_fp_fma_patterns(&mut patterns);
        Self::register_reduction_patterns(&mut patterns);
        Self::register_slide_patterns(&mut patterns);
        Self::register_gather_scatter_patterns(&mut patterns);
        Self::register_permute_patterns(&mut patterns);
        Self::register_mask_patterns(&mut patterns);
        Self::register_conversion_patterns(&mut patterns);

        Self {
            patterns,
            vlen_bits,
            has_v_extension,
            config: RVVConfig::new(vlen_bits),
            vreg_map: HashMap::new(),
        }
    }

    /// Register integer vector arithmetic patterns.
    fn register_integer_arith_patterns(patterns: &mut Vec<VectorISelPattern>) {
        let int_widths = [8, 16, 32, 64];
        for &w in &int_widths {
            // VV forms
            patterns.push(VectorISelPattern {
                ir_opcode: 0x01, /* Add */
                type_width: w,
                is_fp: false,
                scalar_op2: false,
                imm_op2: false,
                rvv_opcode: RiscVVectorOpcode::VAddVV,
            });
            patterns.push(VectorISelPattern {
                ir_opcode: 0x02, /* Sub */
                type_width: w,
                is_fp: false,
                scalar_op2: false,
                imm_op2: false,
                rvv_opcode: RiscVVectorOpcode::VSubVV,
            });
            patterns.push(VectorISelPattern {
                ir_opcode: 0x03, /* Mul */
                type_width: w,
                is_fp: false,
                scalar_op2: false,
                imm_op2: false,
                rvv_opcode: RiscVVectorOpcode::VMulVV,
            });
            // VX forms
            patterns.push(VectorISelPattern {
                ir_opcode: 0x01,
                type_width: w,
                is_fp: false,
                scalar_op2: true,
                imm_op2: false,
                rvv_opcode: RiscVVectorOpcode::VAddVX,
            });
            patterns.push(VectorISelPattern {
                ir_opcode: 0x02,
                type_width: w,
                is_fp: false,
                scalar_op2: true,
                imm_op2: false,
                rvv_opcode: RiscVVectorOpcode::VSubVX,
            });
            // VI forms (for Add/Sub with small immediates)
            patterns.push(VectorISelPattern {
                ir_opcode: 0x01,
                type_width: w,
                is_fp: false,
                scalar_op2: false,
                imm_op2: true,
                rvv_opcode: RiscVVectorOpcode::VAddVI,
            });
        }
    }

    /// Register integer logical patterns.
    fn register_integer_logical_patterns(patterns: &mut Vec<VectorISelPattern>) {
        let int_widths = [8, 16, 32, 64];
        for &w in &int_widths {
            patterns.push(VectorISelPattern {
                ir_opcode: 0x10, /* And */
                type_width: w,
                is_fp: false,
                scalar_op2: false,
                imm_op2: false,
                rvv_opcode: RiscVVectorOpcode::VAndVV,
            });
            patterns.push(VectorISelPattern {
                ir_opcode: 0x11, /* Or */
                type_width: w,
                is_fp: false,
                scalar_op2: false,
                imm_op2: false,
                rvv_opcode: RiscVVectorOpcode::VOrVV,
            });
            patterns.push(VectorISelPattern {
                ir_opcode: 0x12, /* Xor */
                type_width: w,
                is_fp: false,
                scalar_op2: false,
                imm_op2: false,
                rvv_opcode: RiscVVectorOpcode::VXorVV,
            });
        }
    }

    /// Register integer shift patterns.
    fn register_integer_shift_patterns(patterns: &mut Vec<VectorISelPattern>) {
        let int_widths = [8, 16, 32, 64];
        for &w in &int_widths {
            patterns.push(VectorISelPattern {
                ir_opcode: 0x20, /* Shl */
                type_width: w,
                is_fp: false,
                scalar_op2: false,
                imm_op2: false,
                rvv_opcode: RiscVVectorOpcode::VSllVV,
            });
            patterns.push(VectorISelPattern {
                ir_opcode: 0x21, /* LShr */
                type_width: w,
                is_fp: false,
                scalar_op2: false,
                imm_op2: false,
                rvv_opcode: RiscVVectorOpcode::VSrlVV,
            });
            patterns.push(VectorISelPattern {
                ir_opcode: 0x22, /* AShr */
                type_width: w,
                is_fp: false,
                scalar_op2: false,
                imm_op2: false,
                rvv_opcode: RiscVVectorOpcode::VSraVV,
            });
        }
    }

    /// Register integer comparison patterns.
    fn register_integer_compare_patterns(patterns: &mut Vec<VectorISelPattern>) {
        let int_widths = [8, 16, 32, 64];
        for &w in &int_widths {
            // EQ
            patterns.push(VectorISelPattern {
                ir_opcode: 0x30, /* ICmp EQ */
                type_width: w,
                is_fp: false,
                scalar_op2: false,
                imm_op2: false,
                rvv_opcode: RiscVVectorOpcode::VMSeqVV,
            });
            // NE
            patterns.push(VectorISelPattern {
                ir_opcode: 0x31, /* ICmp NE */
                type_width: w,
                is_fp: false,
                scalar_op2: false,
                imm_op2: false,
                rvv_opcode: RiscVVectorOpcode::VMSneVV,
            });
            // SLT (signed)
            patterns.push(VectorISelPattern {
                ir_opcode: 0x32, /* ICmp SLT */
                type_width: w,
                is_fp: false,
                scalar_op2: false,
                imm_op2: false,
                rvv_opcode: RiscVVectorOpcode::VMSltVV,
            });
            // ULT (unsigned)
            patterns.push(VectorISelPattern {
                ir_opcode: 0x33, /* ICmp ULT */
                type_width: w,
                is_fp: false,
                scalar_op2: false,
                imm_op2: false,
                rvv_opcode: RiscVVectorOpcode::VMSltuVV,
            });
        }
    }

    /// Register FP arithmetic patterns.
    fn register_fp_arith_patterns(patterns: &mut Vec<VectorISelPattern>) {
        let fp_widths = [16, 32, 64];
        for &w in &fp_widths {
            patterns.push(VectorISelPattern {
                ir_opcode: 0x40, /* FAdd */
                type_width: w,
                is_fp: true,
                scalar_op2: false,
                imm_op2: false,
                rvv_opcode: RiscVVectorOpcode::VFAddVV,
            });
            patterns.push(VectorISelPattern {
                ir_opcode: 0x41, /* FSub */
                type_width: w,
                is_fp: true,
                scalar_op2: false,
                imm_op2: false,
                rvv_opcode: RiscVVectorOpcode::VFSubVV,
            });
            patterns.push(VectorISelPattern {
                ir_opcode: 0x42, /* FMul */
                type_width: w,
                is_fp: true,
                scalar_op2: false,
                imm_op2: false,
                rvv_opcode: RiscVVectorOpcode::VFMulVV,
            });
            patterns.push(VectorISelPattern {
                ir_opcode: 0x43, /* FDiv */
                type_width: w,
                is_fp: true,
                scalar_op2: false,
                imm_op2: false,
                rvv_opcode: RiscVVectorOpcode::VFDivVV,
            });
            patterns.push(VectorISelPattern {
                ir_opcode: 0x44, /* FSqrt */
                type_width: w,
                is_fp: true,
                scalar_op2: false,
                imm_op2: false,
                rvv_opcode: RiscVVectorOpcode::VFSqrtV,
            });
        }
    }

    /// Register FP comparison patterns.
    fn register_fp_compare_patterns(patterns: &mut Vec<VectorISelPattern>) {
        let fp_widths = [16, 32, 64];
        for &w in &fp_widths {
            patterns.push(VectorISelPattern {
                ir_opcode: 0x50, /* FCmp OEQ */
                type_width: w,
                is_fp: true,
                scalar_op2: false,
                imm_op2: false,
                rvv_opcode: RiscVVectorOpcode::VMFEqVV,
            });
            patterns.push(VectorISelPattern {
                ir_opcode: 0x51, /* FCmp ONE */
                type_width: w,
                is_fp: true,
                scalar_op2: false,
                imm_op2: false,
                rvv_opcode: RiscVVectorOpcode::VMFNeVV,
            });
            patterns.push(VectorISelPattern {
                ir_opcode: 0x52, /* FCmp OLT */
                type_width: w,
                is_fp: true,
                scalar_op2: false,
                imm_op2: false,
                rvv_opcode: RiscVVectorOpcode::VMFLtVV,
            });
            patterns.push(VectorISelPattern {
                ir_opcode: 0x53, /* FCmp OLE */
                type_width: w,
                is_fp: true,
                scalar_op2: false,
                imm_op2: false,
                rvv_opcode: RiscVVectorOpcode::VMFLeVV,
            });
        }
    }

    /// Register FP fused multiply-add patterns.
    fn register_fp_fma_patterns(patterns: &mut Vec<VectorISelPattern>) {
        let fp_widths = [16, 32, 64];
        for &w in &fp_widths {
            patterns.push(VectorISelPattern {
                ir_opcode: 0x60, /* FMA */
                type_width: w,
                is_fp: true,
                scalar_op2: false,
                imm_op2: false,
                rvv_opcode: RiscVVectorOpcode::VFMAddVV,
            });
            patterns.push(VectorISelPattern {
                ir_opcode: 0x61, /* FNMAdd */
                type_width: w,
                is_fp: true,
                scalar_op2: false,
                imm_op2: false,
                rvv_opcode: RiscVVectorOpcode::VFNMAddVV,
            });
        }
    }

    /// Register reduction patterns.
    fn register_reduction_patterns(patterns: &mut Vec<VectorISelPattern>) {
        // Integer reductions
        patterns.push(VectorISelPattern {
            ir_opcode: 0x70, /* VECREDUCE_ADD */
            type_width: 32,
            is_fp: false,
            scalar_op2: false,
            imm_op2: false,
            rvv_opcode: RiscVVectorOpcode::VRedSumVS,
        });
        patterns.push(VectorISelPattern {
            ir_opcode: 0x71, /* VECREDUCE_SMAX */
            type_width: 32,
            is_fp: false,
            scalar_op2: false,
            imm_op2: false,
            rvv_opcode: RiscVVectorOpcode::VRedMaxVS,
        });
        patterns.push(VectorISelPattern {
            ir_opcode: 0x72, /* VECREDUCE_SMIN */
            type_width: 32,
            is_fp: false,
            scalar_op2: false,
            imm_op2: false,
            rvv_opcode: RiscVVectorOpcode::VRedMinVS,
        });
        // FP reductions
        patterns.push(VectorISelPattern {
            ir_opcode: 0x73, /* VECREDUCE_FADD */
            type_width: 32,
            is_fp: true,
            scalar_op2: false,
            imm_op2: false,
            rvv_opcode: RiscVVectorOpcode::VFredusumVS,
        });
    }

    /// Register slide patterns.
    fn register_slide_patterns(patterns: &mut Vec<VectorISelPattern>) {
        patterns.push(VectorISelPattern {
            ir_opcode: 0x80, /* SLIDEUP */
            type_width: 32,
            is_fp: false,
            scalar_op2: true,
            imm_op2: false,
            rvv_opcode: RiscVVectorOpcode::VSlideupVX,
        });
        patterns.push(VectorISelPattern {
            ir_opcode: 0x81, /* SLIDEDOWN */
            type_width: 32,
            is_fp: false,
            scalar_op2: true,
            imm_op2: false,
            rvv_opcode: RiscVVectorOpcode::VSlidedownVX,
        });
    }

    /// Register gather/scatter patterns.
    fn register_gather_scatter_patterns(patterns: &mut Vec<VectorISelPattern>) {
        let widths = [8, 16, 32, 64];
        for &w in &widths {
            patterns.push(VectorISelPattern {
                ir_opcode: 0x90, /* MGATHER */
                type_width: w,
                is_fp: false,
                scalar_op2: false,
                imm_op2: false,
                rvv_opcode: match w {
                    8 => RiscVVectorOpcode::VLuxei8V,
                    16 => RiscVVectorOpcode::VLuxei16V,
                    32 => RiscVVectorOpcode::VLuxei32V,
                    _ => RiscVVectorOpcode::VLuxei64V,
                },
            });
            patterns.push(VectorISelPattern {
                ir_opcode: 0x91, /* MSCATTER */
                type_width: w,
                is_fp: false,
                scalar_op2: false,
                imm_op2: false,
                rvv_opcode: match w {
                    8 => RiscVVectorOpcode::VSuxei8V,
                    16 => RiscVVectorOpcode::VSuxei16V,
                    32 => RiscVVectorOpcode::VSuxei32V,
                    _ => RiscVVectorOpcode::VSuxei64V,
                },
            });
        }
    }

    /// Register permute patterns.
    fn register_permute_patterns(patterns: &mut Vec<VectorISelPattern>) {
        patterns.push(VectorISelPattern {
            ir_opcode: 0xA0, /* SHUFFLE_VECTOR (vrgather) */
            type_width: 32,
            is_fp: false,
            scalar_op2: false,
            imm_op2: false,
            rvv_opcode: RiscVVectorOpcode::VRGatherVV,
        });
        patterns.push(VectorISelPattern {
            ir_opcode: 0xA1, /* VSELECT (vmerge) */
            type_width: 32,
            is_fp: false,
            scalar_op2: false,
            imm_op2: false,
            rvv_opcode: RiscVVectorOpcode::VMergeVVM,
        });
    }

    /// Register mask logic patterns.
    fn register_mask_patterns(patterns: &mut Vec<VectorISelPattern>) {
        patterns.push(VectorISelPattern {
            ir_opcode: 0xB0, /* AND (mask) */
            type_width: 1,
            is_fp: false,
            scalar_op2: false,
            imm_op2: false,
            rvv_opcode: RiscVVectorOpcode::VMandMM,
        });
        patterns.push(VectorISelPattern {
            ir_opcode: 0xB1, /* OR (mask) */
            type_width: 1,
            is_fp: false,
            scalar_op2: false,
            imm_op2: false,
            rvv_opcode: RiscVVectorOpcode::VMorMM,
        });
        patterns.push(VectorISelPattern {
            ir_opcode: 0xB2, /* XOR (mask) */
            type_width: 1,
            is_fp: false,
            scalar_op2: false,
            imm_op2: false,
            rvv_opcode: RiscVVectorOpcode::VMxorMM,
        });
        patterns.push(VectorISelPattern {
            ir_opcode: 0xB3, /* NOT (mask) */
            type_width: 1,
            is_fp: false,
            scalar_op2: false,
            imm_op2: false,
            rvv_opcode: RiscVVectorOpcode::VMNotM,
        });
    }

    /// Register type conversion patterns.
    fn register_conversion_patterns(patterns: &mut Vec<VectorISelPattern>) {
        // SEXT
        patterns.push(VectorISelPattern {
            ir_opcode: 0xC0, /* SEXT */
            type_width: 32,
            is_fp: false,
            scalar_op2: false,
            imm_op2: false,
            rvv_opcode: RiscVVectorOpcode::VSextVF2,
        });
        // ZEXT
        patterns.push(VectorISelPattern {
            ir_opcode: 0xC1, /* ZEXT */
            type_width: 32,
            is_fp: false,
            scalar_op2: false,
            imm_op2: false,
            rvv_opcode: RiscVVectorOpcode::VZextVF2,
        });
        // FCVT (float → int)
        patterns.push(VectorISelPattern {
            ir_opcode: 0xC2, /* FP_TO_SINT */
            type_width: 32,
            is_fp: true,
            scalar_op2: false,
            imm_op2: false,
            rvv_opcode: RiscVVectorOpcode::VFcvt_x_fV,
        });
        // FCVT (int → float)
        patterns.push(VectorISelPattern {
            ir_opcode: 0xC3, /* SINT_TO_FP */
            type_width: 32,
            is_fp: false,
            scalar_op2: false,
            imm_op2: false,
            rvv_opcode: RiscVVectorOpcode::VFcvt_f_xV,
        });
    }

    // ── Instruction selection logic ──────────────────────────────────────

    /// Select an RVV vector instruction for a given IR operation.
    pub fn select(
        &self,
        ir_opcode: u32,
        type_width: u32,
        is_fp: bool,
        scalar_op2: bool,
        imm_op2: bool,
    ) -> Option<RiscVVectorOpcode> {
        if !self.has_v_extension {
            return None;
        }
        for pattern in &self.patterns {
            if pattern.ir_opcode == ir_opcode
                && pattern.type_width == type_width
                && pattern.is_fp == is_fp
                && pattern.scalar_op2 == scalar_op2
                && pattern.imm_op2 == imm_op2
            {
                return Some(pattern.rvv_opcode);
            }
        }
        None
    }

    /// Determine the appropriate SEW for a given type width.
    pub fn sew_for_width(width: u32) -> Option<RVVSEW> {
        match width {
            8 => Some(RVVSEW::E8),
            16 => Some(RVVSEW::E16),
            32 => Some(RVVSEW::E32),
            64 => Some(RVVSEW::E64),
            _ => None,
        }
    }

    /// Compute vtype encoding from configuration.
    pub fn vtype_encoding(config: &RVVConfig) -> u32 {
        let sew_enc = match config.sew {
            RVVSEW::E8 => 0,
            RVVSEW::E16 => 1,
            RVVSEW::E32 => 2,
            RVVSEW::E64 => 3,
        };
        let lmul_enc = config.lmul.encoding();
        let ta = if config.tail_agnostic { 1u32 } else { 0 };
        let ma = if config.mask_agnostic { 1u32 } else { 0 };
        (sew_enc & 0x7) | ((lmul_enc & 0x7) << 3) | (ta << 6) | (ma << 7)
    }

    /// Manage virtual-to-physical vector register mapping.
    pub fn alloc_vreg(&mut self, vreg: u32) -> u32 {
        let next = self.vreg_map.len() as u32;
        *self.vreg_map.entry(vreg).or_insert(next)
    }

    /// Get the physical vector register for a virtual one.
    pub fn get_vreg(&self, vreg: u32) -> Option<u32> {
        self.vreg_map.get(&vreg).copied()
    }

    /// Set the current vector configuration.
    pub fn set_config(&mut self, config: RVVConfig) {
        self.config = config;
    }

    /// Get the current vector configuration.
    pub fn config(&self) -> &RVVConfig {
        &self.config
    }

    /// Check if the V extension is enabled.
    pub fn has_v(&self) -> bool {
        self.has_v_extension
    }
}

impl Default for RiscVVectorISel {
    fn default() -> Self {
        Self::new(128, true)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// RVV Assembly Emission
// ═══════════════════════════════════════════════════════════════════════════════

/// Emit assembly text for RVV instructions.
pub struct RVVAsmEmitter;

impl RVVAsmEmitter {
    /// Emit a vector assembly instruction.
    pub fn emit(
        opcode: RiscVVectorOpcode,
        vd: u32,
        vs1: u32,
        vs2: u32,
        config: &RVVConfig,
        mask: Option<u32>,
    ) -> String {
        let mut s = String::new();
        if config.masked || mask.is_some() {
            s.push_str("v0.t, ");
        }
        let mnemonic = opcode.mnemonic();
        s.push_str(&format!(
            "{mnemonic}.v{}{}",
            match config.sew {
                RVVSEW::E8 => "v",
                RVVSEW::E16 => "v",
                RVVSEW::E32 => "v",
                RVVSEW::E64 => "v",
            },
            ""
        ));
        s.push_str(&format!(" v{vd}, v{vs1}, v{vs2}"));
        if config.tail_agnostic {
            s.push_str(", ta");
        }
        if config.mask_agnostic {
            s.push_str(", ma");
        }
        s
    }

    /// Emit a VSETVLI instruction to configure VL.
    pub fn emit_vsetvli(vl: u64, config: &RVVConfig) -> String {
        format!(
            "vsetvli x0, {}, e{}, m{}, ta, ma",
            vl,
            match config.sew {
                RVVSEW::E8 => "8",
                RVVSEW::E16 => "16",
                RVVSEW::E32 => "32",
                RVVSEW::E64 => "64",
            },
            match config.lmul {
                RVVLMUL::MF8 => "f8",
                RVVLMUL::MF4 => "f4",
                RVVLMUL::MF2 => "f2",
                RVVLMUL::M1 => "1",
                RVVLMUL::M2 => "2",
                RVVLMUL::M4 => "4",
                RVVLMUL::M8 => "8",
            }
        )
    }

    /// Emit a vector load instruction.
    pub fn emit_vle(
        vd: u32,
        base_reg: u32,
        offset: i64,
        sew: RVVSEW,
        config: &RVVConfig,
    ) -> String {
        let sew_suffix = match sew {
            RVVSEW::E8 => "8",
            RVVSEW::E16 => "16",
            RVVSEW::E32 => "32",
            RVVSEW::E64 => "64",
        };
        let mut s = format!("vle{sew_suffix}.v v{vd}, ({offset})");
        if config.masked {
            s.push_str(", v0.t");
        }
        s
    }

    /// Emit a vector store instruction.
    pub fn emit_vse(
        vs3: u32,
        base_reg: u32,
        offset: i64,
        sew: RVVSEW,
        config: &RVVConfig,
    ) -> String {
        let sew_suffix = match sew {
            RVVSEW::E8 => "8",
            RVVSEW::E16 => "16",
            RVVSEW::E32 => "32",
            RVVSEW::E64 => "64",
        };
        let mut s = format!("vse{sew_suffix}.v v{vs3}, ({offset})");
        if config.masked {
            s.push_str(", v0.t");
        }
        s
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Tests
// ═══════════════════════════════════════════════════════════════════════════════

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

    #[test]
    fn test_rvv_isel_add() {
        let isel = RiscVVectorISel::new(128, true);
        let op = isel.select(0x01, 32, false, false, false);
        assert_eq!(op, Some(RiscVVectorOpcode::VAddVV));
    }

    #[test]
    fn test_rvv_isel_add_scalar() {
        let isel = RiscVVectorISel::new(128, true);
        let op = isel.select(0x01, 32, false, true, false);
        assert_eq!(op, Some(RiscVVectorOpcode::VAddVX));
    }

    #[test]
    fn test_rvv_isel_fadd() {
        let isel = RiscVVectorISel::new(128, true);
        let op = isel.select(0x40, 32, true, false, false);
        assert_eq!(op, Some(RiscVVectorOpcode::VFAddVV));
    }

    #[test]
    fn test_rvv_isel_no_v_ext() {
        let isel = RiscVVectorISel::new(128, false);
        let op = isel.select(0x01, 32, false, false, false);
        assert_eq!(op, None);
    }

    #[test]
    fn test_sew_for_width() {
        assert_eq!(RiscVVectorISel::sew_for_width(8), Some(RVVSEW::E8));
        assert_eq!(RiscVVectorISel::sew_for_width(16), Some(RVVSEW::E16));
        assert_eq!(RiscVVectorISel::sew_for_width(32), Some(RVVSEW::E32));
        assert_eq!(RiscVVectorISel::sew_for_width(64), Some(RVVSEW::E64));
        assert_eq!(RiscVVectorISel::sew_for_width(128), None);
    }

    #[test]
    fn test_rvv_config() {
        let config = RVVConfig::new(256);
        assert_eq!(config.vlen, 256);
        assert_eq!(config.sew, RVVSEW::E32);
        assert_eq!(config.vl, 8); // 256/32 = 8

        let config2 = RVVConfig::new(256).with_sew(RVVSEW::E16);
        assert_eq!(config2.vl, 16); // 256/16 = 16
    }

    #[test]
    fn test_rvv_config_with_lmul() {
        let config = RVVConfig::new(256)
            .with_sew(RVVSEW::E32)
            .with_lmul(RVVLMUL::M2);
        assert_eq!(config.vl, 16); // 2 * 256/32 = 16
    }

    #[test]
    fn test_rvv_vtype_encoding() {
        let config = RVVConfig::new(128).with_sew(RVVSEW::E32);
        // sew=2, lmul=0 (M1), ta=1, ma=1
        let vtype = RiscVVectorISel::vtype_encoding(&config);
        assert_eq!(vtype & 0x7, 2); // SEW
        assert_eq!((vtype >> 3) & 0x7, 0); // LMUL
        assert_eq!((vtype >> 6) & 0x1, 1); // ta
        assert_eq!((vtype >> 7) & 0x1, 1); // ma
    }

    #[test]
    fn test_rvv_isel_masks() {
        let isel = RiscVVectorISel::new(128, true);
        let op = isel.select(0xB0, 1, false, false, false);
        assert_eq!(op, Some(RiscVVectorOpcode::VMandMM));

        let op2 = isel.select(0xB1, 1, false, false, false);
        assert_eq!(op2, Some(RiscVVectorOpcode::VMorMM));
    }

    #[test]
    fn test_rvv_isel_reductions() {
        let isel = RiscVVectorISel::new(128, true);
        let op = isel.select(0x70, 32, false, false, false);
        assert_eq!(op, Some(RiscVVectorOpcode::VRedSumVS));

        let op2 = isel.select(0x73, 32, true, false, false);
        assert_eq!(op2, Some(RiscVVectorOpcode::VFredusumVS));
    }

    #[test]
    fn test_rvv_isel_conversions() {
        let isel = RiscVVectorISel::new(128, true);
        let op = isel.select(0xC0, 32, false, false, false);
        assert_eq!(op, Some(RiscVVectorOpcode::VSextVF2));

        let op2 = isel.select(0xC1, 32, false, false, false);
        assert_eq!(op2, Some(RiscVVectorOpcode::VZextVF2));
    }

    #[test]
    fn test_vreg_allocation() {
        let mut isel = RiscVVectorISel::new(128, true);
        let p0 = isel.alloc_vreg(10);
        let p1 = isel.alloc_vreg(20);
        let p2 = isel.alloc_vreg(10); // same vreg → same physical
        assert_eq!(p0, 0);
        assert_eq!(p1, 1);
        assert_eq!(p2, 0);
    }

    #[test]
    fn test_asm_emitter_vsetvli() {
        let config = RVVConfig::new(128).with_sew(RVVSEW::E32);
        let asm = RVVAsmEmitter::emit_vsetvli(4, &config);
        assert!(asm.contains("vsetvli"));
        assert!(asm.contains("e32"));
        assert!(asm.contains("m1"));
    }

    #[test]
    fn test_asm_emitter_vector_op() {
        let config = RVVConfig::new(128).with_sew(RVVSEW::E32);
        let asm = RVVAsmEmitter::emit(RiscVVectorOpcode::VAddVV, 1, 2, 3, &config, None);
        assert!(asm.contains("vadd"));
        assert!(asm.contains("v1"));
    }

    #[test]
    fn test_asm_emitter_masked() {
        let mut config = RVVConfig::new(128).with_sew(RVVSEW::E32);
        config.masked = true;
        let asm = RVVAsmEmitter::emit(RiscVVectorOpcode::VAddVV, 1, 2, 3, &config, Some(0));
        assert!(asm.contains("v0.t"));
        assert!(asm.contains("vadd"));
    }

    #[test]
    fn test_lmul_encoding() {
        assert_eq!(RVVLMUL::MF8.encoding(), 5);
        assert_eq!(RVVLMUL::MF4.encoding(), 6);
        assert_eq!(RVVLMUL::MF2.encoding(), 7);
        assert_eq!(RVVLMUL::M1.encoding(), 0);
        assert_eq!(RVVLMUL::M2.encoding(), 1);
        assert_eq!(RVVLMUL::M4.encoding(), 2);
        assert_eq!(RVVLMUL::M8.encoding(), 3);
    }
}