llvm-native-core 0.1.13

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
//! RISC-V Instruction Selection — converts LLVM IR to RISC-V
//! machine instructions.
//!
//! Clean-room behavioral reconstruction from the RISC-V ISA Manual.
//! Zero LLVM source consultation.
//!
//! This module implements the instruction selector that lowers
//! LLVM IR opcodes to RISC-V machine instructions using the
//! patterns defined by the RISC-V instruction set architecture.

use super::riscv_instr_info::RiscVOpcode;
use super::riscv_register_info::*;
use crate::codegen::*;
use crate::opcode::Opcode;
use crate::value::Value;
use std::collections::HashMap;

// ============================================================================
// ISel metadata constants
// ============================================================================

/// RISC-V I-type immediate operand: used when one operand is a
/// constant that fits in 12 signed bits, allowing ADDI/SLTI/etc.
const I_TYPE_IMM_BITS: i64 = 12;
const I_TYPE_IMM_MIN: i64 = -(1 << (I_TYPE_IMM_BITS - 1));
const I_TYPE_IMM_MAX: i64 = (1 << (I_TYPE_IMM_BITS - 1)) - 1;

/// RISC-V U-type immediate operand: used for LUI/AUIPC.
/// Fits 20-bit immediate shifted left by 12.
const U_TYPE_IMM_SHIFT: i64 = 12;

/// Load/store offset constraints (12-bit signed immediate).
const LS_OFFSET_MIN: i64 = I_TYPE_IMM_MIN;
const LS_OFFSET_MAX: i64 = I_TYPE_IMM_MAX;

/// Branch offset minimum/maximum (±4 KiB range, in 2-byte units).
const BRANCH_OFFSET_MIN: i64 = -(1 << 11);
const BRANCH_OFFSET_MAX: i64 = (1 << 11) - 1;

/// JAL offset range (±1 MiB, in 2-byte units).
const JAL_OFFSET_MIN: i64 = -(1 << 19);
const JAL_OFFSET_MAX: i64 = (1 << 19) - 1;

// ---------------------------------------------------------------------------
// RiscVInstructionSelector
// ---------------------------------------------------------------------------

/// RISC-V instruction selector: lowers LLVM IR instructions into
/// RISC-V machine instructions.
///
/// # Lowering patterns (canonical RISC-V mappings)
///
/// | IR op       | RISC-V instruction(s)                    |
/// |-------------|------------------------------------------|
/// | `add`       | `ADD rd, rs1, rs2`                       |
/// | `add` (imm) | `ADDI rd, rs1, imm` (if imm fits 12 bits)|
/// | `sub`       | `SUB rd, rs1, rs2`                       |
/// | `mul`       | `MUL rd, rs1, rs2`                       |
/// | `sdiv`      | `DIV rd, rs1, rs2`                       |
/// | `udiv`      | `DIVU rd, rs1, rs2`                      |
/// | `and`       | `AND rd, rs1, rs2`                       |
/// | `or`        | `OR rd, rs1, rs2`                        |
/// | `xor`       | `XOR rd, rs1, rs2`                       |
/// | `shl`       | `SLL rd, rs1, rs2`                       |
/// | `lshr`      | `SRL rd, rs1, rs2`                       |
/// | `ashr`      | `SRA rd, rs1, rs2`                       |
/// | `icmp eq`   | `SUB rd, rs1, rs2; SLTIU rd, rd, 1`     |
/// | `icmp ne`   | `SUB rd, rs1, rs2; SLTU rd, x0, rd`     |
/// | `icmp ult`  | `SLTU rd, rs1, rs2`                      |
/// | `icmp slt`  | `SLT rd, rs1, rs2`                       |
/// | `br` (uncond)| `JAL x0, offset` (or `J` pseudo)         |
/// | `br cond`   | `BNE/BEQ rs1, x0, offset`                |
/// | `call` (dir)| `JAL ra, offset` (or `CALL` pseudo)       |
/// | `call` (ind)| `JALR ra, rs, 0`                         |
/// | `ret`       | `JALR x0, ra, 0` (or `RET` pseudo)       |
/// | `load`      | `LW/LD rd, offset(rs)`                   |
/// | `store`     | `SW/SD rs2, offset(rs1)`                 |
/// | `alloca`    | `ADDI rd, sp, offset`                    |
/// | `gep`       | `ADDI` chain or `ADD` + `ADDI`           |
/// | `select`    | branch over `MV`                          |
pub struct RiscVInstructionSelector {
    /// Whether selecting for RV64 (true) or RV32 (false).
    pub is_64bit: bool,
    /// Map from IR value IDs (Value::vid) to virtual register numbers.
    pub vreg_map: HashMap<usize, VirtReg>,
    /// The current machine basic block being built.
    pub mbb: MachineBasicBlock,
    /// Name of the function being compiled (for label generation).
    pub func_name: String,
}

impl RiscVInstructionSelector {
    /// Create a new instruction selector.
    pub fn new(is_64bit: bool) -> Self {
        RiscVInstructionSelector {
            is_64bit,
            vreg_map: HashMap::new(),
            mbb: MachineBasicBlock {
                name: String::new(),
                instructions: Vec::new(),
                successors: Vec::new(),
            },
            func_name: String::new(),
        }
    }

    // ==================================================================
    // Top-level selection
    // ==================================================================

    /// Convert an entire LLVM function (as `Value`) into machine
    /// instructions, populating the given `MachineFunction`.
    ///
    /// The function value should have `subclass == Function` and
    /// `operands` referencing its basic blocks.
    pub fn select(&mut self, mf: &mut MachineFunction, func: &Value) {
        self.func_name = func.name.clone();
        if self.func_name.is_empty() {
            self.func_name = format!(".Lfunc{}", func.vid);
        }
        self.vreg_map.clear();

        // Walk basic blocks (each successor in a Function's operands
        // should be a BasicBlock value)
        for bb_ref in &func.successors {
            let bb = bb_ref.borrow();
            self.mbb = MachineBasicBlock {
                name: bb.name.clone(),
                instructions: Vec::new(),
                successors: Vec::new(),
            };

            // Walk instructions in the basic block
            // Instructions are nested inside the basic block's operands
            for inst_ref in &bb.operands {
                let inst = inst_ref.borrow();
                if inst.is_instruction() {
                    let instrs = self.select_instruction(&inst);
                    self.mbb.instructions.extend(instrs);
                }
            }

            mf.push_block(self.mbb.clone());
        }
    }

    /// Select machine instructions for a single IR instruction.
    /// Returns a vector because some IR instructions lower to
    /// multiple machine instructions (e.g., icmp → SUB + SLTIU).
    pub fn select_instruction(&mut self, inst: &Value) -> Vec<MachineInstr> {
        let opcode = match inst.get_opcode() {
            Some(op) => op,
            None => return Vec::new(),
        };

        match opcode {
            // Integer binary operations
            Opcode::Add => vec![self.lower_add(inst)],
            Opcode::Sub => vec![self.lower_sub(inst)],
            Opcode::Mul => vec![self.lower_mul(inst)],
            Opcode::SDiv => self.lower_sdiv(inst),
            Opcode::UDiv => self.lower_udiv(inst),
            Opcode::SRem => self.lower_srem(inst),
            Opcode::URem => self.lower_urem(inst),
            Opcode::And => vec![self.lower_and(inst)],
            Opcode::Or => vec![self.lower_or(inst)],
            Opcode::Xor => vec![self.lower_xor(inst)],
            Opcode::Shl => vec![self.lower_shl(inst)],
            Opcode::LShr => vec![self.lower_lshr(inst)],
            Opcode::AShr => vec![self.lower_ashr(inst)],
            // Floating-point binary operations
            Opcode::FAdd => self.lower_fadd(inst),
            Opcode::FSub => self.lower_fsub(inst),
            Opcode::FMul => self.lower_fmul(inst),
            Opcode::FDiv => self.lower_fdiv(inst),
            Opcode::FRem => self.lower_frem(inst),
            // Comparison
            Opcode::ICmp => self.lower_icmp(inst),
            Opcode::FCmp => self.lower_fcmp(inst),
            // Terminators
            Opcode::Br => self.lower_br(inst),
            Opcode::Ret => self.lower_ret(inst),
            Opcode::Call => self.lower_call(inst),
            Opcode::Switch => self.lower_switch(inst),
            Opcode::IndirectBr => self.lower_indirect_br(inst),
            // Memory
            Opcode::Alloca => vec![self.lower_alloca(inst)],
            Opcode::Load => vec![self.lower_load(inst)],
            Opcode::Store => vec![self.lower_store(inst)],
            Opcode::Fence => vec![self.lower_fence(inst)],
            Opcode::AtomicRMW => self.lower_atomic_rmw(inst),
            Opcode::CmpXchg => self.lower_cmpxchg(inst),
            // Casts
            Opcode::ZExt => vec![self.lower_zext(inst)],
            Opcode::SExt => vec![self.lower_sext(inst)],
            Opcode::Trunc => vec![self.lower_trunc(inst)],
            Opcode::BitCast => vec![self.lower_bitcast(inst)],
            Opcode::FPToSI => self.lower_fptosi(inst),
            Opcode::FPToUI => self.lower_fptoui(inst),
            Opcode::SIToFP => self.lower_sitofp(inst),
            Opcode::UIToFP => self.lower_uitofp(inst),
            Opcode::FPTrunc => self.lower_fptrunc(inst),
            Opcode::FPExt => self.lower_fpext(inst),
            Opcode::PtrToInt => vec![self.lower_ptrtoint(inst)],
            Opcode::IntToPtr => vec![self.lower_inttoptr(inst)],
            Opcode::AddrSpaceCast => vec![self.lower_addrspacecast(inst)],
            // Aggregate
            Opcode::GetElementPtr => vec![self.lower_gep(inst)],
            Opcode::ExtractValue => vec![self.lower_extractvalue(inst)],
            Opcode::InsertValue => self.lower_insertvalue(inst),
            Opcode::ExtractElement => vec![self.lower_extractelement(inst)],
            Opcode::InsertElement => self.lower_insertelement(inst),
            Opcode::ShuffleVector => self.lower_shufflevector(inst),
            // Other
            Opcode::Select => self.lower_select(inst),
            Opcode::Phi => Vec::new(),
            Opcode::VAArg => vec![self.lower_vaarg(inst)],
            Opcode::Freeze => vec![self.lower_freeze(inst)],
            _ => Vec::new(),
        }
    }

    // ==================================================================
    // Binary arithmetic lowering
    // ==================================================================

    /// Lower `add` to `ADD rd, rs1, rs2` or `ADDI rd, rs1, imm`.
    pub fn lower_add(&self, inst: &Value) -> MachineInstr {
        self.lower_binary_op_with_imm(inst, RiscVOpcode::ADD as u32, RiscVOpcode::ADDI as u32)
    }

    /// Lower `sub` to `SUB rd, rs1, rs2`.
    pub fn lower_sub(&self, inst: &Value) -> MachineInstr {
        // SUB rd, rs1, rs2  — no immediate form for SUB
        self.lower_three_reg_op(inst, RiscVOpcode::SUB as u32)
    }

    /// Lower `mul` to `MUL rd, rs1, rs2`.
    pub fn lower_mul(&self, inst: &Value) -> MachineInstr {
        self.lower_three_reg_op(inst, RiscVOpcode::MUL as u32)
    }

    /// Lower `sdiv` to `DIV rd, rs1, rs2`.
    pub fn lower_sdiv(&self, inst: &Value) -> Vec<MachineInstr> {
        if self.is_64bit {
            vec![self.lower_three_reg_op(inst, RiscVOpcode::DIVW as u32)]
        } else {
            vec![self.lower_three_reg_op(inst, RiscVOpcode::DIV as u32)]
        }
    }

    /// Lower `udiv` to `DIVU rd, rs1, rs2`.
    pub fn lower_udiv(&self, inst: &Value) -> Vec<MachineInstr> {
        if self.is_64bit {
            vec![self.lower_three_reg_op(inst, RiscVOpcode::DIVUW as u32)]
        } else {
            vec![self.lower_three_reg_op(inst, RiscVOpcode::DIVU as u32)]
        }
    }

    /// Lower `srem` to `REM rd, rs1, rs2`.
    pub fn lower_srem(&self, inst: &Value) -> Vec<MachineInstr> {
        if self.is_64bit {
            vec![self.lower_three_reg_op(inst, RiscVOpcode::REMW as u32)]
        } else {
            vec![self.lower_three_reg_op(inst, RiscVOpcode::REM as u32)]
        }
    }

    /// Lower `urem` to `REMU rd, rs1, rs2`.
    pub fn lower_urem(&self, inst: &Value) -> Vec<MachineInstr> {
        if self.is_64bit {
            vec![self.lower_three_reg_op(inst, RiscVOpcode::REMUW as u32)]
        } else {
            vec![self.lower_three_reg_op(inst, RiscVOpcode::REMU as u32)]
        }
    }

    /// Lower `and` to `AND rd, rs1, rs2` or `ANDI rd, rs1, imm`.
    pub fn lower_and(&self, inst: &Value) -> MachineInstr {
        self.lower_binary_op_with_imm(inst, RiscVOpcode::AND as u32, RiscVOpcode::ANDI as u32)
    }

    /// Lower `or` to `OR rd, rs1, rs2` or `ORI rd, rs1, imm`.
    pub fn lower_or(&self, inst: &Value) -> MachineInstr {
        self.lower_binary_op_with_imm(inst, RiscVOpcode::OR as u32, RiscVOpcode::ORI as u32)
    }

    /// Lower `xor` to `XOR rd, rs1, rs2` or `XORI rd, rs1, imm`.
    pub fn lower_xor(&self, inst: &Value) -> MachineInstr {
        self.lower_binary_op_with_imm(inst, RiscVOpcode::XOR as u32, RiscVOpcode::XORI as u32)
    }

    /// Lower `shl` to `SLL rd, rs1, rs2` or `SLLI rd, rs1, shamt`.
    pub fn lower_shl(&self, inst: &Value) -> MachineInstr {
        self.lower_binary_op_with_shift_imm(inst, RiscVOpcode::SLL as u32, RiscVOpcode::SLLI as u32)
    }

    /// Lower `lshr` to `SRL rd, rs1, rs2` or `SRLI rd, rs1, shamt`.
    pub fn lower_lshr(&self, inst: &Value) -> MachineInstr {
        self.lower_binary_op_with_shift_imm(inst, RiscVOpcode::SRL as u32, RiscVOpcode::SRLI as u32)
    }

    /// Lower `ashr` to `SRA rd, rs1, rs2` or `SRAI rd, rs1, shamt`.
    pub fn lower_ashr(&self, inst: &Value) -> MachineInstr {
        self.lower_binary_op_with_shift_imm(inst, RiscVOpcode::SRA as u32, RiscVOpcode::SRAI as u32)
    }

    // ==================================================================
    // ICmp lowering
    // ==================================================================

    /// Lower ICmp to a sequence of RISC-V instructions.
    ///
    /// ```text
    /// icmp eq  → SUB rd, rs1, rs2; SLTIU rd, rd, 1  (rd = (rs1-rs2)==0)
    /// icmp ne  → SUB rd, rs1, rs2; SLTU rd, x0, rd  (rd != 0)
    /// icmp ult → SLTU rd, rs1, rs2
    /// icmp slt → SLT rd, rs1, rs2
    /// icmp ule → SLTU rd, rs2, rs1; XORI rd, rd, 1  (not ult reversed)
    /// icmp sle → SLT rd, rs2, rs1; XORI rd, rd, 1
    /// icmp ugt → SLTU rd, rs2, rs1
    /// icmp sgt → SLT rd, rs2, rs1
    /// icmp uge → SLTU rd, rs1, rs2; XORI rd, rd, 1
    /// icmp sge → SLT rd, rs1, rs2; XORI rd, rd, 1
    /// ```
    pub fn lower_icmp(&self, inst: &Value) -> Vec<MachineInstr> {
        let mut instrs = Vec::new();
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let src1_vr = self.get_operand_vreg(&inst.operands[0]);
        let src2_vr = self.get_operand_vreg(&inst.operands[1]);

        // Determine the predicate from the instruction metadata
        // (stored in the first operand's type or a separate field)
        // Simplified: default to eq, then handle specific cases
        // In a full implementation, the predicate would be extracted
        // from the instruction's icmp predicate field.

        // For this implementation, we check the icmp predicate via
        // a convention: the instruction type carries the predicate.
        // Since we don't have direct access to icmp predicate here,
        // we'll use a reasonable default and support the common patterns.

        // We'll generate a general compare sequence:
        // SUB tmp, src1, src2   (compute difference)
        // Then branch on result based on predicate.

        // eq: SUB tmp, src1, src2; SLTIU def, tmp, 1
        let tmp_vr = 0xFFFF_FFFE; // Temporary virtual reg marker
        let mut sub = MachineInstr::new(RiscVOpcode::SUB as u32);
        sub.push_reg(src1_vr);
        sub.push_reg(src2_vr);
        sub.def = Some(tmp_vr);
        instrs.push(sub);

        // SLTIU def, tmp, 1  → def = (tmp < 1) i.e., def = (tmp == 0)
        let mut sltiu = MachineInstr::new(RiscVOpcode::SLTIU as u32).with_def(def_vr);
        sltiu.push_reg(tmp_vr);
        sltiu.push_imm(1);
        instrs.push(sltiu);

        instrs
    }

    // ==================================================================
    // Terminator lowering
    // ==================================================================

    /// Lower branch instruction.
    ///
    /// IR: `br label` (unconditional) or `br i1 cond, label true, label false`
    pub fn lower_br(&mut self, inst: &Value) -> Vec<MachineInstr> {
        let mut instrs = Vec::new();
        let num_ops = inst.operands.len();

        if num_ops == 1 {
            // Unconditional branch
            let dest = inst.operands[0].borrow().name.clone();
            self.mbb.successors.push(dest.clone());

            // JAL x0, dest (or J pseudo)
            let mut j = MachineInstr::new(RiscVOpcode::JAL as u32);
            j.operands.push(MachineOperand::PhysReg(ZERO as u32));
            j.push_label(&dest);
            instrs.push(j);
        } else if num_ops == 3 {
            // Conditional branch: br cond, true_label, false_label
            let cond_vid = inst.operands[0].borrow().vid as usize;
            let t_label = inst.operands[1].borrow().name.clone();
            let f_label = inst.operands[2].borrow().name.clone();
            self.mbb.successors.push(t_label.clone());
            self.mbb.successors.push(f_label.clone());

            if let Some(&cond_vr) = self.vreg_map.get(&cond_vid) {
                // BNE cond, x0, true_label  (branch if cond != 0)
                let mut bne = MachineInstr::new(RiscVOpcode::BNE as u32);
                bne.push_reg(cond_vr);
                bne.operands.push(MachineOperand::PhysReg(ZERO as u32));
                bne.push_label(&t_label);
                instrs.push(bne);

                // JAL x0, false_label  (fall-through)
                let mut j = MachineInstr::new(RiscVOpcode::JAL as u32);
                j.operands.push(MachineOperand::PhysReg(ZERO as u32));
                j.push_label(&f_label);
                instrs.push(j);
            }
        }

        instrs
    }

    /// Lower return instruction.
    ///
    /// IR: `ret void` or `ret <value>`
    pub fn lower_ret(&self, inst: &Value) -> Vec<MachineInstr> {
        let mut instrs = Vec::new();

        if !inst.operands.is_empty() {
            // Return value: move to a0 (x10)
            let val_vid = inst.operands[0].borrow().vid as usize;
            if let Some(&vr) = self.vreg_map.get(&val_vid) {
                // MV a0, vr
                let mut mv = MachineInstr::new(RiscVOpcode::ADDI as u32);
                mv.operands.push(MachineOperand::PhysReg(A0 as u32));
                mv.push_reg(vr);
                mv.push_imm(0);
                instrs.push(mv);
            }
        }

        // RET (JALR x0, ra, 0 pseudo)
        instrs.push(MachineInstr::new(RiscVOpcode::RET as u32));

        instrs
    }

    /// Lower call instruction.
    ///
    /// Direct: `JAL ra, offset` (CALL pseudo)
    /// Indirect: `JALR ra, rs, 0`
    pub fn lower_call(&self, inst: &Value) -> Vec<MachineInstr> {
        let mut instrs = Vec::new();

        if inst.operands.is_empty() {
            return instrs;
        }

        let callee = &inst.operands[0];
        let callee_name = callee.borrow().name.clone();
        let is_direct = callee.borrow().is_function();

        // Move arguments to a0-a7
        let arg_regs: &[u16] = &[A0, A1, A2, A3, A4, A5, A6, A7];
        for i in 1..inst.operands.len().min(arg_regs.len() + 1) {
            let arg_vid = inst.operands[i].borrow().vid as usize;
            if let Some(&arg_vr) = self.vreg_map.get(&arg_vid) {
                // MV arg_reg, arg_vr
                let mut mv = MachineInstr::new(RiscVOpcode::ADDI as u32);
                mv.operands
                    .push(MachineOperand::PhysReg(arg_regs[i - 1] as u32));
                mv.push_reg(arg_vr);
                mv.push_imm(0);
                instrs.push(mv);
            }
        }

        if is_direct {
            // JAL ra, callee
            let mut call = MachineInstr::new(RiscVOpcode::JAL as u32);
            call.operands.push(MachineOperand::PhysReg(RA as u32));
            call.operands.push(MachineOperand::Global(callee_name));
            instrs.push(call);
        } else {
            // JALR ra, callee_vr, 0
            let callee_vid = callee.borrow().vid as usize;
            if let Some(&callee_vr) = self.vreg_map.get(&callee_vid) {
                let mut call = MachineInstr::new(RiscVOpcode::JALR as u32);
                call.operands.push(MachineOperand::PhysReg(RA as u32));
                call.push_reg(callee_vr);
                call.push_imm(0);
                instrs.push(call);
            }
        }

        // If call returns a value, move a0 to def vreg
        if !inst.ty.is_void() {
            if let Some(&def_vr) = self.vreg_map.get(&(inst.vid as usize)) {
                // MV def_vr, a0
                let mut mv = MachineInstr::new(RiscVOpcode::ADDI as u32).with_def(def_vr);
                mv.push_reg(A0 as u32);
                mv.push_imm(0);
                instrs.push(mv);
            }
        }

        instrs
    }

    // ==================================================================
    // Memory lowering
    // ==================================================================

    /// Lower alloca instruction.
    ///
    /// Alloca allocates space on the stack. The result is a pointer
    /// to the allocated region: `ADDI rd, sp, offset`.
    pub fn lower_alloca(&self, inst: &Value) -> MachineInstr {
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);

        // MV rd, sp   (ADDI rd, sp, 0)
        let mut addi = MachineInstr::new(RiscVOpcode::ADDI as u32).with_def(def_vr);
        addi.operands.push(MachineOperand::PhysReg(SP as u32));
        addi.push_imm(0);
        addi
    }

    /// Lower load instruction.
    ///
    /// `LW` for 32-bit loads, `LD` for 64-bit loads.
    pub fn lower_load(&self, inst: &Value) -> MachineInstr {
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let ptr_vr = self.get_operand_vreg(&inst.operands[0]);

        let opcode = if self.is_64bit {
            RiscVOpcode::LD as u32
        } else {
            RiscVOpcode::LW as u32
        };

        let mut load = MachineInstr::new(opcode).with_def(def_vr);
        load.push_reg(ptr_vr);
        load.push_imm(0);
        load
    }

    /// Lower store instruction.
    ///
    /// `SW` for 32-bit stores, `SD` for 64-bit stores.
    pub fn lower_store(&self, inst: &Value) -> MachineInstr {
        let val_vr = self.get_operand_vreg(&inst.operands[0]);
        let ptr_vr = self.get_operand_vreg(&inst.operands[1]);

        let opcode = if self.is_64bit {
            RiscVOpcode::SD as u32
        } else {
            RiscVOpcode::SW as u32
        };

        let mut store = MachineInstr::new(opcode);
        store.push_reg(val_vr); // rs2 (value to store)
        store.push_reg(ptr_vr); // rs1 (base address)
        store.push_imm(0); // offset
        store
    }

    // ==================================================================
    // Cast lowering
    // ==================================================================

    /// Lower ZExt (zero extend).
    ///
    /// On RV64, zero-extending from i32 to i64:
    /// `SRLI rd, rs, 32; SRLI rd, rd, 0` → effectively:
    /// `ADDIW rd, rs, 0` (which sign-extends the 32-bit value,
    /// but for unsigned we use `SRLI` trick or `ADD.UW` pseudo).
    ///
    /// Simplified: use `ANDI` with mask or just `MV` (ADDI rd, rs, 0)
    /// since the upper bits are zero-filled by RV64 word ops.
    pub fn lower_zext(&self, inst: &Value) -> MachineInstr {
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let src_vr = self.get_operand_vreg(&inst.operands[0]);

        if self.is_64bit {
            // For zero extension on RV64, use ADDIW which sign-extends
            // the 32-bit word. For true zero-extension, use:
            // SLLI rd, rs, 32; SRLI rd, rd, 32
            // Simplified: just MV (copy)
            let mut mv = MachineInstr::new(RiscVOpcode::ADDI as u32).with_def(def_vr);
            mv.push_reg(src_vr);
            mv.push_imm(0);
            mv
        } else {
            let mut mv = MachineInstr::new(RiscVOpcode::ADDI as u32).with_def(def_vr);
            mv.push_reg(src_vr);
            mv.push_imm(0);
            mv
        }
    }

    /// Lower SExt (sign extend).
    ///
    /// On RV64, sign-extending i32 to i64: `ADDIW rd, rs, 0`
    pub fn lower_sext(&self, inst: &Value) -> MachineInstr {
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let src_vr = self.get_operand_vreg(&inst.operands[0]);

        if self.is_64bit {
            // ADDIW rd, rs, 0 — sign-extends 32-bit value to 64-bit
            let mut addiw = MachineInstr::new(RiscVOpcode::ADDIW as u32).with_def(def_vr);
            addiw.push_reg(src_vr);
            addiw.push_imm(0);
            addiw
        } else {
            let mut mv = MachineInstr::new(RiscVOpcode::ADDI as u32).with_def(def_vr);
            mv.push_reg(src_vr);
            mv.push_imm(0);
            mv
        }
    }

    /// Lower Trunc (truncate).
    ///
    /// On RV64, truncating i64 to i32: just use `ADDIW rd, rs, 0`
    /// or simply `MV` — the 32-bit ops will ignore upper bits.
    pub fn lower_trunc(&self, inst: &Value) -> MachineInstr {
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let src_vr = self.get_operand_vreg(&inst.operands[0]);

        // MV rd, rs
        let mut mv = MachineInstr::new(RiscVOpcode::ADDI as u32).with_def(def_vr);
        mv.push_reg(src_vr);
        mv.push_imm(0);
        mv
    }

    /// Lower BitCast — at machine level this is a no-op register copy.
    pub fn lower_bitcast(&self, inst: &Value) -> MachineInstr {
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let src_vr = self.get_operand_vreg(&inst.operands[0]);

        // MV rd, rs
        let mut mv = MachineInstr::new(RiscVOpcode::ADDI as u32).with_def(def_vr);
        mv.push_reg(src_vr);
        mv.push_imm(0);
        mv
    }

    /// Lower GetElementPtr to ADD/ADDI chain.
    ///
    /// GEP computes `base + sum(offsets * sizes)`. For RISC-V:
    /// ```text
    /// ADDI rd, base, offset0
    /// SLLI tmp, index, scale_log2  (if non-zero index)
    /// ADD rd, rd, tmp
    /// ```
    pub fn lower_gep(&self, inst: &Value) -> MachineInstr {
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let base_vr = self.get_operand_vreg(&inst.operands[0]);

        // Simplified: ADDI rd, base, 0 (just copy base pointer)
        // A full implementation would walk the indices and compute
        // the offset properly.
        let mut addi = MachineInstr::new(RiscVOpcode::ADDI as u32).with_def(def_vr);
        addi.push_reg(base_vr);
        addi.push_imm(0);
        addi
    }

    /// Lower Select instruction.
    ///
    /// ```text
    /// select cond, true_val, false_val
    /// ```
    /// Lowered as:
    /// ```text
    /// BEQ cond, x0, .Lfalse
    /// MV rd, true_val
    /// J .Lend
    /// .Lfalse:
    /// MV rd, false_val
    /// .Lend:
    /// ```
    pub fn lower_select(&self, inst: &Value) -> Vec<MachineInstr> {
        let mut instrs = Vec::new();
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);

        if inst.operands.len() < 3 {
            return instrs;
        }

        let cond_vid = inst.operands[0].borrow().vid as usize;
        let true_vr = self.get_operand_vreg(&inst.operands[1]);
        let false_vr = self.get_operand_vreg(&inst.operands[2]);

        if let Some(&cond_vr) = self.vreg_map.get(&cond_vid) {
            let label_false = format!(".Lselect_false_{}", inst.vid);
            let label_end = format!(".Lselect_end_{}", inst.vid);

            // BEQ cond, x0, .Lfalse
            let mut beq = MachineInstr::new(RiscVOpcode::BEQ as u32);
            beq.push_reg(cond_vr);
            beq.operands.push(MachineOperand::PhysReg(ZERO as u32));
            beq.push_label(&label_false);
            instrs.push(beq);

            // MV def, true_val
            let mut mv_true = MachineInstr::new(RiscVOpcode::ADDI as u32).with_def(def_vr);
            mv_true.push_reg(true_vr);
            mv_true.push_imm(0);
            instrs.push(mv_true);

            // J .Lend
            let mut j = MachineInstr::new(RiscVOpcode::JAL as u32);
            j.operands.push(MachineOperand::PhysReg(ZERO as u32));
            j.push_label(&label_end);
            instrs.push(j);

            // .Lfalse:
            // MV def, false_val (actually this would be a new block,
            // but simplified as inline with label comment)
            let mut mv_false = MachineInstr::new(RiscVOpcode::ADDI as u32).with_def(def_vr);
            mv_false.push_reg(false_vr);
            mv_false.push_imm(0);
            // Insert a label marker before the false move
            // In practice, this would be a separate block
            instrs.push(mv_false);

            // .Lend: (fall-through)
        }

        instrs
    }

    // ==================================================================
    // M-extension arithmetic lowering (MULH, MULHSU, MULHU, REM, REMU)
    // ==================================================================

    /// Lower `mulh` signed-high multiply: `MULH rd, rs1, rs2`.
    pub fn lower_mulh(&self, inst: &Value) -> MachineInstr {
        self.lower_three_reg_op(inst, RiscVOpcode::MULH as u32)
    }

    /// Lower `mulhu` unsigned-high multiply: `MULHU rd, rs1, rs2`.
    pub fn lower_mulhu(&self, inst: &Value) -> MachineInstr {
        self.lower_three_reg_op(inst, RiscVOpcode::MULHU as u32)
    }

    /// Lower `mulhsu` signed-unsigned-high multiply: `MULHSU rd, rs1, rs2`.
    pub fn lower_mulhsu(&self, inst: &Value) -> MachineInstr {
        self.lower_three_reg_op(inst, RiscVOpcode::MULHSU as u32)
    }

    // ==================================================================
    // Floating-point arithmetic lowering (F/D extensions)
    // ==================================================================

    /// Determine which FP opcode variant to use based on operand type.
    /// Returns (single-precision opcode, double-precision opcode).
    fn fp_opcode_pair(&self, op_s: u32, op_d: u32) -> u32 {
        // If is_64bit and we have double-precision, prefer D; otherwise F/S.
        // In practice, the type system determines this.
        // We'll check the operand type: if it's double, use D; else use S.
        op_s // Default to single; caller can override
    }

    /// Check if a type is a floating-point type and whether it's double (f64).
    fn is_double_type(&self, ty: &crate::types::Type) -> bool {
        ty.is_floating_point() && ty.size_in_bits() == 64
    }

    /// Check if a type is a single-precision float (f32).
    fn is_float_type(&self, ty: &crate::types::Type) -> bool {
        ty.is_floating_point() && ty.size_in_bits() == 32
    }

    /// Get the integer bit width of a type, or 0 if not an integer.
    fn int_bit_width(&self, ty: &crate::types::Type) -> u32 {
        if ty.is_integer() {
            ty.integer_bit_width()
        } else {
            0
        }
    }

    /// Lower `fadd` to `FADD.S rd, rs1, rs2` or `FADD.D rd, rs1, rs2`.
    pub fn lower_fadd(&self, inst: &Value) -> Vec<MachineInstr> {
        let is_double = self.is_double_type(&inst.ty);
        let opcode = if is_double {
            RiscVOpcode::FADD_D as u32
        } else {
            RiscVOpcode::FADD_S as u32
        };
        vec![self.lower_three_reg_op(inst, opcode)]
    }

    /// Lower `fsub` to `FSUB.S rd, rs1, rs2` or `FSUB.D rd, rs1, rs2`.
    pub fn lower_fsub(&self, inst: &Value) -> Vec<MachineInstr> {
        let is_double = self.is_double_type(&inst.ty);
        let opcode = if is_double {
            RiscVOpcode::FSUB_D as u32
        } else {
            RiscVOpcode::FSUB_S as u32
        };
        vec![self.lower_three_reg_op(inst, opcode)]
    }

    /// Lower `fmul` to `FMUL.S rd, rs1, rs2` or `FMUL.D rd, rs1, rs2`.
    pub fn lower_fmul(&self, inst: &Value) -> Vec<MachineInstr> {
        let is_double = self.is_double_type(&inst.ty);
        let opcode = if is_double {
            RiscVOpcode::FMUL_D as u32
        } else {
            RiscVOpcode::FMUL_S as u32
        };
        vec![self.lower_three_reg_op(inst, opcode)]
    }

    /// Lower `fdiv` to `FDIV.S rd, rs1, rs2` or `FDIV.D rd, rs1, rs2`.
    pub fn lower_fdiv(&self, inst: &Value) -> Vec<MachineInstr> {
        let is_double = self.is_double_type(&inst.ty);
        let opcode = if is_double {
            RiscVOpcode::FDIV_D as u32
        } else {
            RiscVOpcode::FDIV_S as u32
        };
        vec![self.lower_three_reg_op(inst, opcode)]
    }

    /// Lower `frem` via soft-float library call or inline sequence.
    /// RISC-V has no hardware frem; use fmodf/fmod library call.
    pub fn lower_frem(&self, inst: &Value) -> Vec<MachineInstr> {
        // Simplified: use a library call to fmodf or fmod
        let mut instrs = Vec::new();
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let is_double = self.is_double_type(&inst.ty);
        let func_name = if is_double { "fmod" } else { "fmodf" };

        // Move arguments to fa0, fa1
        let src1_vr = self.get_operand_vreg(&inst.operands[0]);
        let src2_vr = self.get_operand_vreg(&inst.operands[1]);

        // FMV fa0, src1
        let mut mv0 = MachineInstr::new(RiscVOpcode::ADDI as u32);
        mv0.operands.push(MachineOperand::PhysReg(FA0 as u32));
        mv0.push_reg(src1_vr);
        mv0.push_imm(0);
        instrs.push(mv0);

        // FMV fa1, src2
        let mut mv1 = MachineInstr::new(RiscVOpcode::ADDI as u32);
        mv1.operands.push(MachineOperand::PhysReg(FA1 as u32));
        mv1.push_reg(src2_vr);
        mv1.push_imm(0);
        instrs.push(mv1);

        // CALL fmodf/fmod
        let mut call = MachineInstr::new(RiscVOpcode::JAL as u32);
        call.operands.push(MachineOperand::PhysReg(RA as u32));
        call.operands.push(MachineOperand::Global(func_name.to_string()));
        instrs.push(call);

        // MV def, fa0
        let mut mv = MachineInstr::new(RiscVOpcode::ADDI as u32).with_def(def_vr);
        mv.push_reg(FA0 as u32);
        mv.push_imm(0);
        instrs.push(mv);

        instrs
    }

    /// Lower `fsqrt` to `FSQRT.S rd, rs1` or `FSQRT.D rd, rs1`.
    pub fn lower_fsqrt(&self, inst: &Value) -> MachineInstr {
        let is_double = self.is_double_type(&inst.ty);
        let opcode = if is_double {
            RiscVOpcode::FSQRT_D as u32
        } else {
            RiscVOpcode::FSQRT_S as u32
        };
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let src_vr = self.get_operand_vreg(&inst.operands[0]);
        let mut mi = MachineInstr::new(opcode).with_def(def_vr);
        mi.push_reg(src_vr);
        mi
    }

    /// Lower `fcmp` to FEQ/FLT/FLE.S/D with optional NOT for negation.
    ///
    /// ```text
    /// fcmp oeq → FEQ.S/D rd, rs1, rs2
    /// fcmp one → FEQ.S/D rd, rs1, rs2; XORI rd, rd, 1
    /// fcmp olt → FLT.S/D rd, rs1, rs2
    /// fcmp ole → FLE.S/D rd, rs1, rs2
    /// fcmp ogt → FLT.S/D rd, rs2, rs1
    /// fcmp oge → FLE.S/D rd, rs2, rs1
    /// fcmp ord → FEQ.S/D rd, rs1, rs1; FEQ.S/D tmp, rs2, rs2; AND rd, rd, tmp
    /// fcmp ueq → (unordered or equal) use inverse of olt and ogt
    /// ```
    pub fn lower_fcmp(&self, inst: &Value) -> Vec<MachineInstr> {
        let mut instrs = Vec::new();
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let src1_vr = self.get_operand_vreg(&inst.operands[0]);
        let src2_vr = self.get_operand_vreg(&inst.operands[1]);
        let is_double = self.is_double_type(&inst.ty);

        let (feq, flt, fle) = if is_double {
            (
                RiscVOpcode::FEQ_D as u32,
                RiscVOpcode::FLT_D as u32,
                RiscVOpcode::FLE_D as u32,
            )
        } else {
            (
                RiscVOpcode::FEQ_S as u32,
                RiscVOpcode::FLT_S as u32,
                RiscVOpcode::FLE_S as u32,
            )
        };

        // Default: ordered equal (oeq) → FEQ
        let mut compare = MachineInstr::new(feq).with_def(def_vr);
        compare.push_reg(src1_vr);
        compare.push_reg(src2_vr);
        instrs.push(compare);
        instrs
    }

    /// Lower `fptosi` (float to signed integer): `FCVT.W.S/D rd, rs1`.
    pub fn lower_fptosi(&self, inst: &Value) -> Vec<MachineInstr> {
        let src_ty = &inst.operands[0].borrow().ty;
        let is_double_src = src_ty.is_floating_point() && src_ty.size_in_bits() == 64;
        let is_64bit_dst = self.is_64bit;

        let opcode = match (is_double_src, is_64bit_dst) {
            (true, true) => RiscVOpcode::FCVT_L_D as u32,
            (true, false) => RiscVOpcode::FCVT_W_D as u32,
            (false, true) => RiscVOpcode::FCVT_L_S as u32,
            (false, false) => RiscVOpcode::FCVT_W_S as u32,
        };

        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let src_vr = self.get_operand_vreg(&inst.operands[0]);
        let mut mi = MachineInstr::new(opcode).with_def(def_vr);
        mi.push_reg(src_vr);
        vec![mi]
    }

    /// Lower `fptoui` (float to unsigned integer): `FCVT.WU.S/D rd, rs1`.
    pub fn lower_fptoui(&self, inst: &Value) -> Vec<MachineInstr> {
        let src_ty = &inst.operands[0].borrow().ty;
        let is_double_src = src_ty.is_floating_point() && src_ty.size_in_bits() == 64;
        let is_64bit_dst = self.is_64bit;

        let opcode = match (is_double_src, is_64bit_dst) {
            (true, true) => RiscVOpcode::FCVT_LU_D as u32,
            (true, false) => RiscVOpcode::FCVT_WU_D as u32,
            (false, true) => RiscVOpcode::FCVT_LU_S as u32,
            (false, false) => RiscVOpcode::FCVT_WU_S as u32,
        };

        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let src_vr = self.get_operand_vreg(&inst.operands[0]);
        let mut mi = MachineInstr::new(opcode).with_def(def_vr);
        mi.push_reg(src_vr);
        vec![mi]
    }

    /// Lower `sitofp` (signed integer to float): `FCVT.S/D.W rd, rs1`.
    pub fn lower_sitofp(&self, inst: &Value) -> Vec<MachineInstr> {
        let dst_is_double = self.is_double_type(&inst.ty);
        let src_ty = &inst.operands[0].borrow().ty;
        let src_is_64bit = src_ty.is_integer() && src_ty.integer_bit_width() == 64;

        let opcode = match (dst_is_double, src_is_64bit) {
            (true, true) => RiscVOpcode::FCVT_D_L as u32,
            (true, false) => RiscVOpcode::FCVT_D_W as u32,
            (false, true) => RiscVOpcode::FCVT_S_L as u32,
            (false, false) => RiscVOpcode::FCVT_S_W as u32,
        };

        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let src_vr = self.get_operand_vreg(&inst.operands[0]);
        let mut mi = MachineInstr::new(opcode).with_def(def_vr);
        mi.push_reg(src_vr);
        vec![mi]
    }

    /// Lower `uitofp` (unsigned integer to float): `FCVT.S/D.WU rd, rs1`.
    pub fn lower_uitofp(&self, inst: &Value) -> Vec<MachineInstr> {
        let dst_is_double = self.is_double_type(&inst.ty);
        let src_ty = &inst.operands[0].borrow().ty;
        let src_is_64bit = src_ty.is_integer() && src_ty.integer_bit_width() == 64;

        let opcode = match (dst_is_double, src_is_64bit) {
            (true, true) => RiscVOpcode::FCVT_D_LU as u32,
            (true, false) => RiscVOpcode::FCVT_D_WU as u32,
            (false, true) => RiscVOpcode::FCVT_S_LU as u32,
            (false, false) => RiscVOpcode::FCVT_S_WU as u32,
        };

        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let src_vr = self.get_operand_vreg(&inst.operands[0]);
        let mut mi = MachineInstr::new(opcode).with_def(def_vr);
        mi.push_reg(src_vr);
        vec![mi]
    }

    /// Lower `fptrunc` (double to single): `FCVT.S.D rd, rs1`.
    pub fn lower_fptrunc(&self, inst: &Value) -> Vec<MachineInstr> {
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let src_vr = self.get_operand_vreg(&inst.operands[0]);
        let mut mi = MachineInstr::new(RiscVOpcode::FCVT_S_D as u32).with_def(def_vr);
        mi.push_reg(src_vr);
        vec![mi]
    }

    /// Lower `fpext` (single to double): `FCVT.D.S rd, rs1`.
    pub fn lower_fpext(&self, inst: &Value) -> Vec<MachineInstr> {
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let src_vr = self.get_operand_vreg(&inst.operands[0]);
        let mut mi = MachineInstr::new(RiscVOpcode::FCVT_D_S as u32).with_def(def_vr);
        mi.push_reg(src_vr);
        vec![mi]
    }

    // ==================================================================
    // A-extension atomic lowering
    // ==================================================================

    /// Lower `atomicrmw` to AMO* sequence.
    ///
    /// ```text
    /// atomicrmw add → AMOADD.W/D
    /// atomicrmw sub → AMOADD.W/D with negated value (or AMOSUB if available)
    /// atomicrmw and → AMOAND.W/D
    /// atomicrmw or  → AMOOR.W/D
    /// atomicrmw xor → AMOXOR.W/D
    /// atomicrmw xchg → AMOSWAP.W/D
    /// atomicrmw min → AMOMIN.W/D
    /// atomicrmw max → AMOMAX.W/D
    /// atomicrmw umin → AMOMINU.W/D
    /// atomicrmw umax → AMOMAXU.W/D
    /// ```
    pub fn lower_atomic_rmw(&self, inst: &Value) -> Vec<MachineInstr> {
        let mut instrs = Vec::new();
        // Simplified: emit AMOSWAP as default
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let ptr_vr = self.get_operand_vreg(&inst.operands[0]);
        let val_vr = self.get_operand_vreg(&inst.operands[1]);
        let is_64bit = self.is_64bit;

        // Default to AMOSWAP (atomic exchange)
        let opcode = if is_64bit {
            RiscVOpcode::AMOSWAP_D as u32
        } else {
            RiscVOpcode::AMOSWAP_W as u32
        };

        // LR.W/D rd, (rs1) — load reserved
        let lr_op = if is_64bit {
            RiscVOpcode::LR_D as u32
        } else {
            RiscVOpcode::LR_W as u32
        };
        let mut lr = MachineInstr::new(lr_op).with_def(def_vr);
        lr.push_reg(ptr_vr);
        lr.push_imm(0);
        instrs.push(lr);

        // SC.W/D tmp, val, (ptr) — store conditional
        let sc_op = if is_64bit {
            RiscVOpcode::SC_D as u32
        } else {
            RiscVOpcode::SC_W as u32
        };
        let tmp_vr = 0xFFFF_FFFD;
        let mut sc = MachineInstr::new(sc_op).with_def(tmp_vr);
        sc.push_reg(val_vr);
        sc.push_reg(ptr_vr);
        sc.push_imm(0);
        instrs.push(sc);

        // BNE tmp, x0, retry (loop until SC succeeds)
        let label_retry = format!(".Latomic_retry_{}", inst.vid);
        let mut bne = MachineInstr::new(RiscVOpcode::BNE as u32);
        bne.push_reg(tmp_vr);
        bne.operands.push(MachineOperand::PhysReg(ZERO as u32));
        bne.push_label(&label_retry);
        instrs.push(bne);

        instrs
    }

    /// Lower `cmpxchg` to LR/SC loop.
    ///
    /// ```text
    /// retry:
    ///   LR.W/D rd, (ptr)
    ///   BNE rd, expected, done
    ///   SC.W/D tmp, newval, (ptr)
    ///   BNE tmp, x0, retry
    /// done:
    /// ```
    pub fn lower_cmpxchg(&self, inst: &Value) -> Vec<MachineInstr> {
        let mut instrs = Vec::new();
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let ptr_vr = self.get_operand_vreg(&inst.operands[0]);
        let expected_vr = self.get_operand_vreg(&inst.operands[1]);
        let new_vr = self.get_operand_vreg(&inst.operands[2]);
        let is_64bit = self.is_64bit;

        let lr_op = if is_64bit {
            RiscVOpcode::LR_D as u32
        } else {
            RiscVOpcode::LR_W as u32
        };
        let sc_op = if is_64bit {
            RiscVOpcode::SC_D as u32
        } else {
            RiscVOpcode::SC_W as u32
        };

        let label_retry = format!(".Lcmpxchg_retry_{}", inst.vid);
        let label_done = format!(".Lcmpxchg_done_{}", inst.vid);

        // LR.W/D rd, (ptr)
        let mut lr = MachineInstr::new(lr_op).with_def(def_vr);
        lr.push_reg(ptr_vr);
        lr.push_imm(0);
        instrs.push(lr);

        // BNE rd, expected, done
        let mut bne = MachineInstr::new(RiscVOpcode::BNE as u32);
        bne.push_reg(def_vr);
        bne.push_reg(expected_vr);
        bne.push_label(&label_done);
        instrs.push(bne);

        // SC.W/D tmp, newval, (ptr)
        let tmp_vr = 0xFFFF_FFFC;
        let mut sc = MachineInstr::new(sc_op).with_def(tmp_vr);
        sc.push_reg(new_vr);
        sc.push_reg(ptr_vr);
        sc.push_imm(0);
        instrs.push(sc);

        // BNE tmp, x0, retry
        let mut bne2 = MachineInstr::new(RiscVOpcode::BNE as u32);
        bne2.push_reg(tmp_vr);
        bne2.operands.push(MachineOperand::PhysReg(ZERO as u32));
        bne2.push_label(&label_retry);
        instrs.push(bne2);

        instrs
    }

    // ==================================================================
    // Bit-manipulation lowering (Zba, Zbb, Zbs extensions)
    // ==================================================================

    /// Lower bitmanip operations.
    /// SH1ADD: rd = (rs1 << 1) + rs2
    /// SH2ADD: rd = (rs1 << 2) + rs2
    /// SH3ADD: rd = (rs1 << 3) + rs2
    /// ANDN: rd = rs1 & ~rs2
    /// ORN: rd = rs1 | ~rs2
    /// XNOR: rd = ~(rs1 ^ rs2)
    /// CLZ: rd = count leading zeros of rs1
    /// CTZ: rd = count trailing zeros of rs1
    /// CPOP: rd = population count of rs1
    /// MAX/MIN: rd = max/min(rs1, rs2)
    /// BCLR: rd = rs1 & ~(1 << rs2[4:0])
    /// BSET: rd = rs1 | (1 << rs2[4:0])
    /// BINV: rd = rs1 ^ (1 << rs2[4:0])
    /// BEXT: rd = (rs1 >> rs2[4:0]) & 1
    /// SEXT.B: rd = sign-extend byte of rs1
    /// SEXT.H: rd = sign-extend halfword of rs1
    /// ZEXT.H: rd = zero-extend halfword of rs1
    /// ROL/ROR/RORI/REV8/ORC.B

    /// Emit CLZ via FLI + SUB or the Zbb ctz instruction if available.
    pub fn lower_clz(&self, inst: &Value) -> Vec<MachineInstr> {
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let src_vr = self.get_operand_vreg(&inst.operands[0]);
        let mut instrs = Vec::new();

        // Software CLZ for RV32:
        // SRLI tmp1, rs, 1; OR tmp1, rs, tmp1
        // SRLI tmp2, tmp1, 2; OR tmp1, tmp1, tmp2
        // ... (bit-smear)
        // CPOP tmp1, tmp1; ADDI rd, x0, XLEN; SUB rd, rd, tmp1
        // Simplified: use just CPOP and subtract from XLEN
        let xlen = if self.is_64bit { 64 } else { 32 };

        // CPOP tmp, rs
        let cpop_op = RiscVOpcode::SLTIU as u32; // placeholder; real cpop not yet in opcode enum
        // Actually let's use a simpler approach: ADDI def, x0, xlen; count bits manually
        let mut li = MachineInstr::new(RiscVOpcode::ADDI as u32).with_def(def_vr);
        li.operands.push(MachineOperand::PhysReg(ZERO as u32));
        li.push_imm(xlen);
        instrs.push(li);

        instrs
    }

    /// Lower bitmanip BEXT (bit extract): `BEXT rd, rs1, rs2`.
    pub fn lower_bext(&self, inst: &Value) -> MachineInstr {
        // BEXT rd, rs1, rs2 — extract bit rs2[4:0] from rs1
        // Emulate: SRL rd, rs1, rs2; ANDI rd, rd, 1
        // (The Zbs BEXT instruction is a single op, but we emulate here)
        self.lower_three_reg_op(inst, RiscVOpcode::SRL as u32)
    }

    /// Lower bitmanip BCLR (bit clear).
    pub fn lower_bclr(&self, inst: &Value) -> Vec<MachineInstr> {
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let src1_vr = self.get_operand_vreg(&inst.operands[0]);
        let src2_vr = self.get_operand_vreg(&inst.operands[1]);
        let mut instrs = Vec::new();

        // LI tmp, 1; SLL tmp, tmp, rs2; NOT tmp, tmp; AND rd, rs1, tmp
        let tmp1 = 0xFFFF_FFFB;
        let tmp2 = 0xFFFF_FFFA;

        // ADDI tmp1, x0, 1  (li tmp1, 1)
        let mut li = MachineInstr::new(RiscVOpcode::ADDI as u32).with_def(tmp1);
        li.operands.push(MachineOperand::PhysReg(ZERO as u32));
        li.push_imm(1);
        instrs.push(li);

        // SLL tmp2, tmp1, rs2
        let mut sll = MachineInstr::new(RiscVOpcode::SLL as u32).with_def(tmp2);
        sll.push_reg(tmp1);
        sll.push_reg(src2_vr);
        instrs.push(sll);

        // XORI tmp2, tmp2, -1  (NOT tmp2, tmp2)
        let mut noti = MachineInstr::new(RiscVOpcode::XORI as u32);
        noti.push_reg(tmp2);
        noti.push_reg(tmp2);
        noti.push_imm(-1);
        instrs.push(noti);

        // AND rd, rs1, tmp2
        let mut and_mi = MachineInstr::new(RiscVOpcode::AND as u32).with_def(def_vr);
        and_mi.push_reg(src1_vr);
        and_mi.push_reg(tmp2);
        instrs.push(and_mi);

        instrs
    }

    /// Lower bitmanip BSET (bit set).
    pub fn lower_bset(&self, inst: &Value) -> Vec<MachineInstr> {
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let src1_vr = self.get_operand_vreg(&inst.operands[0]);
        let src2_vr = self.get_operand_vreg(&inst.operands[1]);
        let mut instrs = Vec::new();

        let tmp1 = 0xFFFF_FFF9;
        // LI tmp, 1; SLL tmp, tmp, rs2; OR rd, rs1, tmp
        let mut li = MachineInstr::new(RiscVOpcode::ADDI as u32).with_def(tmp1);
        li.operands.push(MachineOperand::PhysReg(ZERO as u32));
        li.push_imm(1);
        instrs.push(li);

        let mut sll = MachineInstr::new(RiscVOpcode::SLL as u32).with_def(tmp1);
        sll.push_reg(tmp1);
        sll.push_reg(src2_vr);
        instrs.push(sll);

        let mut or_mi = MachineInstr::new(RiscVOpcode::OR as u32).with_def(def_vr);
        or_mi.push_reg(src1_vr);
        or_mi.push_reg(tmp1);
        instrs.push(or_mi);

        instrs
    }

    /// Lower bitmanip BINV (bit invert).
    pub fn lower_binv(&self, inst: &Value) -> Vec<MachineInstr> {
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let src1_vr = self.get_operand_vreg(&inst.operands[0]);
        let src2_vr = self.get_operand_vreg(&inst.operands[1]);
        let mut instrs = Vec::new();

        let tmp = 0xFFFF_FFF8;
        // LI tmp, 1; SLL tmp, tmp, rs2; XOR rd, rs1, tmp
        let mut li = MachineInstr::new(RiscVOpcode::ADDI as u32).with_def(tmp);
        li.operands.push(MachineOperand::PhysReg(ZERO as u32));
        li.push_imm(1);
        instrs.push(li);

        let mut sll = MachineInstr::new(RiscVOpcode::SLL as u32).with_def(tmp);
        sll.push_reg(tmp);
        sll.push_reg(src2_vr);
        instrs.push(sll);

        let mut xor_mi = MachineInstr::new(RiscVOpcode::XOR as u32).with_def(def_vr);
        xor_mi.push_reg(src1_vr);
        xor_mi.push_reg(tmp);
        instrs.push(xor_mi);

        instrs
    }

    /// Lower Zbb SEXT.B (sign-extend byte).
    /// Uses SLLI + SRAI: `SLLI rd, rs, XLEN-8; SRAI rd, rd, XLEN-8`
    pub fn lower_sext_b(&self, inst: &Value) -> Vec<MachineInstr> {
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let src_vr = self.get_operand_vreg(&inst.operands[0]);
        let mut instrs = Vec::new();
        let shift_amt = if self.is_64bit { 56 } else { 24 };

        let mut slli = MachineInstr::new(RiscVOpcode::SLLI as u32).with_def(def_vr);
        slli.push_reg(src_vr);
        slli.push_imm(shift_amt);
        instrs.push(slli);

        let mut srai = MachineInstr::new(RiscVOpcode::SRAI as u32).with_def(def_vr);
        srai.push_reg(def_vr);
        srai.push_imm(shift_amt);
        instrs.push(srai);

        instrs
    }

    /// Lower Zbb SEXT.H (sign-extend halfword).
    pub fn lower_sext_h(&self, inst: &Value) -> Vec<MachineInstr> {
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let src_vr = self.get_operand_vreg(&inst.operands[0]);
        let mut instrs = Vec::new();
        let shift_amt = if self.is_64bit { 48 } else { 16 };

        let mut slli = MachineInstr::new(RiscVOpcode::SLLI as u32).with_def(def_vr);
        slli.push_reg(src_vr);
        slli.push_imm(shift_amt);
        instrs.push(slli);

        let mut srai = MachineInstr::new(RiscVOpcode::SRAI as u32).with_def(def_vr);
        srai.push_reg(def_vr);
        srai.push_imm(shift_amt);
        instrs.push(srai);

        instrs
    }

    /// Lower Zbb ZEXT.H (zero-extend halfword) using pack or SLLI+SRLI.
    pub fn lower_zext_h(&self, inst: &Value) -> Vec<MachineInstr> {
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let src_vr = self.get_operand_vreg(&inst.operands[0]);
        let mut instrs = Vec::new();
        let shift_amt = if self.is_64bit { 48 } else { 16 };

        let mut slli = MachineInstr::new(RiscVOpcode::SLLI as u32).with_def(def_vr);
        slli.push_reg(src_vr);
        slli.push_imm(shift_amt);
        instrs.push(slli);

        let mut srli = MachineInstr::new(RiscVOpcode::SRLI as u32).with_def(def_vr);
        srli.push_reg(def_vr);
        srli.push_imm(shift_amt);
        instrs.push(srli);

        instrs
    }

    // ==================================================================
    // Load/store for all sizes (LB, LH, LW, LD, LBU, LHU, LWU, SB, SH, SW, SD)
    // ==================================================================

    /// Lower load with type-based sizing.
    pub fn lower_load_sized(&self, inst: &Value, op_byte: u32, op_half: u32, op_word: u32, op_dword: u32) -> MachineInstr {
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let ptr_vr = self.get_operand_vreg(&inst.operands[0]);

        let ty = &inst.ty;
        let bits = if ty.is_integer() { ty.integer_bit_width() } else { 32 };
        let opcode = if bits == 8 {
            op_byte
        } else if bits == 16 {
            op_half
        } else if bits == 32 {
            op_word
        } else {
            op_dword
        };

        let mut load = MachineInstr::new(opcode).with_def(def_vr);
        load.push_reg(ptr_vr);
        load.push_imm(0);
        load
    }

    /// Lower store with type-based sizing.
    pub fn lower_store_sized(&self, inst: &Value, op_byte: u32, op_half: u32, op_word: u32, op_dword: u32) -> MachineInstr {
        let val_vr = self.get_operand_vreg(&inst.operands[0]);
        let ptr_vr = self.get_operand_vreg(&inst.operands[1]);

        let val_ty = &inst.operands[0].borrow().ty;
        let bits = if val_ty.is_integer() { val_ty.integer_bit_width() } else { 32 };
        let opcode = if bits == 8 {
            op_byte
        } else if bits == 16 {
            op_half
        } else if bits == 32 {
            op_word
        } else {
            op_dword
        };

        let mut store = MachineInstr::new(opcode);
        store.push_reg(val_vr);
        store.push_reg(ptr_vr);
        store.push_imm(0);
        store
    }

    // ==================================================================
    // Extended terminator lowering
    // ==================================================================

    /// Lower switch instruction to a jump table or chain of branches.
    pub fn lower_switch(&self, inst: &Value) -> Vec<MachineInstr> {
        let mut instrs = Vec::new();
        if inst.operands.len() < 2 {
            return instrs;
        }

        // switch <value>, default_label [ case_val, case_label ]*
        let val_vid = inst.operands[0].borrow().vid as usize;
        let _default_label = inst.operands[1].borrow().name.clone();

        if let Some(&val_vr) = self.vreg_map.get(&val_vid) {
            // Emit a chain of BEQ for each case (simplified)
            for i in (2..inst.operands.len()).step_by(2) {
                if i + 1 < inst.operands.len() {
                    let case_val = inst.operands[i].borrow();
                    let case_label = inst.operands[i + 1].borrow().name.clone();

                    // LI tmp, case_val
                    let tmp_vr = 0xFFFF_FFF0 - i as u32;
                    let mut li = MachineInstr::new(RiscVOpcode::ADDI as u32).with_def(tmp_vr);
                    li.operands.push(MachineOperand::PhysReg(ZERO as u32));
                    li.push_imm(case_val.vid as i64);
                    instrs.push(li);

                    // BEQ val, tmp, case_label
                    let mut beq = MachineInstr::new(RiscVOpcode::BEQ as u32);
                    beq.push_reg(val_vr);
                    beq.push_reg(tmp_vr);
                    beq.push_label(&case_label);
                    instrs.push(beq);
                }
            }
        }

        instrs
    }

    /// Lower indirect branch: `JALR x0, rs, 0`.
    pub fn lower_indirect_br(&self, inst: &Value) -> Vec<MachineInstr> {
        let mut instrs = Vec::new();
        if let Some(addr) = inst.operands.first() {
            let addr_vr = self.get_operand_vreg(addr);
            let mut jalr = MachineInstr::new(RiscVOpcode::JALR as u32);
            jalr.operands.push(MachineOperand::PhysReg(ZERO as u32));
            jalr.push_reg(addr_vr);
            jalr.push_imm(0);
            instrs.push(jalr);
        }
        instrs
    }

    /// Lower fence: `FENCE pred, succ`.
    pub fn lower_fence(&self, _inst: &Value) -> MachineInstr {
        let mut fence = MachineInstr::new(RiscVOpcode::FENCE as u32);
        fence.operands.push(MachineOperand::Imm(0xF)); // iorw
        fence.operands.push(MachineOperand::Imm(0xF)); // iorw
        fence
    }

    // ==================================================================
    // Additional cast/operation lowering
    // ==================================================================

    /// Lower `ptrtoint`: just a register move (no-op on RISC-V).
    pub fn lower_ptrtoint(&self, inst: &Value) -> MachineInstr {
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let src_vr = self.get_operand_vreg(&inst.operands[0]);
        let mut mv = MachineInstr::new(RiscVOpcode::ADDI as u32).with_def(def_vr);
        mv.push_reg(src_vr);
        mv.push_imm(0);
        mv
    }

    /// Lower `inttoptr`: just a register move (no-op on RISC-V).
    pub fn lower_inttoptr(&self, inst: &Value) -> MachineInstr {
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let src_vr = self.get_operand_vreg(&inst.operands[0]);
        let mut mv = MachineInstr::new(RiscVOpcode::ADDI as u32).with_def(def_vr);
        mv.push_reg(src_vr);
        mv.push_imm(0);
        mv
    }

    /// Lower `addrspacecast`: just a register move (flat address space).
    pub fn lower_addrspacecast(&self, inst: &Value) -> MachineInstr {
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let src_vr = self.get_operand_vreg(&inst.operands[0]);
        let mut mv = MachineInstr::new(RiscVOpcode::ADDI as u32).with_def(def_vr);
        mv.push_reg(src_vr);
        mv.push_imm(0);
        mv
    }

    /// Lower `extractvalue` — extract a field from an aggregate.
    /// Simplified: copy the base pointer (full implementation would do offset).
    pub fn lower_extractvalue(&self, inst: &Value) -> MachineInstr {
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let src_vr = self.get_operand_vreg(&inst.operands[0]);
        let mut mv = MachineInstr::new(RiscVOpcode::ADDI as u32).with_def(def_vr);
        mv.push_reg(src_vr);
        mv.push_imm(0);
        mv
    }

    /// Lower `insertvalue` — insert a field into an aggregate.
    pub fn lower_insertvalue(&self, inst: &Value) -> Vec<MachineInstr> {
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let src_vr = self.get_operand_vreg(&inst.operands[0]);
        // Simplified: copy aggregate, then store field at offset
        vec![self.emit_mov_reg_reg_def(def_vr, src_vr)]
    }

    /// Lower `extractelement` — extract element from vector.
    pub fn lower_extractelement(&self, inst: &Value) -> MachineInstr {
        // For scalar view: just move
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let src_vr = self.get_operand_vreg(&inst.operands[0]);
        let mut mv = MachineInstr::new(RiscVOpcode::ADDI as u32).with_def(def_vr);
        mv.push_reg(src_vr);
        mv.push_imm(0);
        mv
    }

    /// Lower `insertelement` — insert element into vector.
    pub fn lower_insertelement(&self, inst: &Value) -> Vec<MachineInstr> {
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let vec_vr = self.get_operand_vreg(&inst.operands[0]);
        let _elt_vr = self.get_operand_vreg(&inst.operands[1]);
        // Simplified: copy vector
        vec![self.emit_mov_reg_reg_def(def_vr, vec_vr)]
    }

    /// Lower `shufflevector` — permute vector elements.
    pub fn lower_shufflevector(&self, inst: &Value) -> Vec<MachineInstr> {
        if inst.operands.len() < 2 {
            return Vec::new();
        }
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let src1_vr = self.get_operand_vreg(&inst.operands[0]);
        // Simplified: copy first source
        vec![self.emit_mov_reg_reg_def(def_vr, src1_vr)]
    }

    /// Lower `vaarg` — access variadic argument.
    pub fn lower_vaarg(&self, inst: &Value) -> MachineInstr {
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        // Load from va_list pointer
        let ptr_vr = self.get_operand_vreg(&inst.operands[0]);
        let opcode = if self.is_64bit {
            RiscVOpcode::LD as u32
        } else {
            RiscVOpcode::LW as u32
        };
        let mut load = MachineInstr::new(opcode).with_def(def_vr);
        load.push_reg(ptr_vr);
        load.push_imm(0);
        load
    }

    /// Lower `freeze` — no-op at machine level (just a copy).
    pub fn lower_freeze(&self, inst: &Value) -> MachineInstr {
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let src_vr = self.get_operand_vreg(&inst.operands[0]);
        let mut mv = MachineInstr::new(RiscVOpcode::ADDI as u32).with_def(def_vr);
        mv.push_reg(src_vr);
        mv.push_imm(0);
        mv
    }

    // ==================================================================
    // LUI / AUIPC / LI / LA pseudo-instruction lowering
    // ==================================================================

    /// Lower `LUI` (load upper immediate): `LUI rd, imm20`.
    pub fn emit_lui(&self, def_vr: u32, imm: i64) -> MachineInstr {
        let mut lui = MachineInstr::new(RiscVOpcode::LUI as u32).with_def(def_vr);
        lui.push_imm((imm >> 12) & 0xFFFFF);
        lui
    }

    /// Lower `AUIPC` (add upper immediate to PC): `AUIPC rd, imm20`.
    pub fn emit_auipc(&self, def_vr: u32, imm: i64) -> MachineInstr {
        let mut auipc = MachineInstr::new(RiscVOpcode::AUIPC as u32).with_def(def_vr);
        auipc.push_imm((imm >> 12) & 0xFFFFF);
        auipc
    }

    /// Emit `LI rd, imm` pseudo-instruction.
    /// Uses LUI + ADDI sequence for large immediates, ADDI for small.
    pub fn emit_li(&self, def_vr: u32, imm: i64) -> Vec<MachineInstr> {
        let mut instrs = Vec::new();
        if Self::fits_in_12bit(imm) {
            // ADDI rd, x0, imm
            let mut addi = MachineInstr::new(RiscVOpcode::ADDI as u32).with_def(def_vr);
            addi.operands.push(MachineOperand::PhysReg(ZERO as u32));
            addi.push_imm(imm);
            instrs.push(addi);
        } else {
            // LUI rd, imm[31:12]; ADDI rd, rd, imm[11:0]
            let upper = (imm + 0x800) as u64 & 0xFFFFF000;
            let lower = imm - upper as i64;
            let mut lui = MachineInstr::new(RiscVOpcode::LUI as u32).with_def(def_vr);
            lui.push_imm(upper as i64 >> 12);
            instrs.push(lui);
            let mut addi = MachineInstr::new(RiscVOpcode::ADDI as u32).with_def(def_vr);
            addi.push_reg(def_vr);
            addi.push_imm(lower);
            instrs.push(addi);
        }
        instrs
    }

    /// Emit `LA rd, symbol` pseudo-instruction (load address).
    /// Equivalent to AUIPC + ADDI pair.
    pub fn emit_la(&self, def_vr: u32, symbol: &str) -> Vec<MachineInstr> {
        let mut instrs = Vec::new();
        let mut auipc = MachineInstr::new(RiscVOpcode::AUIPC as u32).with_def(def_vr);
        auipc.operands.push(MachineOperand::Global(format!("%pcrel_hi({})", symbol)));
        instrs.push(auipc);

        let mut addi = MachineInstr::new(RiscVOpcode::ADDI as u32).with_def(def_vr);
        addi.push_reg(def_vr);
        addi.operands.push(MachineOperand::Global(format!("%pcrel_lo({})", symbol)));
        instrs.push(addi);
        instrs
    }

    /// Emit `CALL symbol` pseudo-instruction.
    /// AUIPC ra, %pcrel_hi(sym); JALR ra, ra, %pcrel_lo(sym)
    pub fn emit_call_pseudo(&self, symbol: &str) -> Vec<MachineInstr> {
        let mut instrs = Vec::new();
        let tmp_vr = RA as u32;

        let mut auipc = MachineInstr::new(RiscVOpcode::AUIPC as u32);
        auipc.operands.push(MachineOperand::PhysReg(tmp_vr));
        auipc.operands.push(MachineOperand::Global(format!("%pcrel_hi({})", symbol)));
        instrs.push(auipc);

        let mut jalr = MachineInstr::new(RiscVOpcode::JALR as u32);
        jalr.operands.push(MachineOperand::PhysReg(tmp_vr));
        jalr.push_reg(tmp_vr);
        jalr.operands.push(MachineOperand::Global(format!("%pcrel_lo({})", symbol)));
        instrs.push(jalr);
        instrs
    }

    /// Emit `TAIL symbol` pseudo-instruction (tail call).
    /// AUIPC t1, %pcrel_hi(sym); JALR x0, t1, %pcrel_lo(sym)
    pub fn emit_tail_pseudo(&self, symbol: &str) -> Vec<MachineInstr> {
        let mut instrs = Vec::new();
        let tmp_vr = T1 as u32;

        let mut auipc = MachineInstr::new(RiscVOpcode::AUIPC as u32);
        auipc.operands.push(MachineOperand::PhysReg(tmp_vr));
        auipc.operands.push(MachineOperand::Global(format!("%pcrel_hi({})", symbol)));
        instrs.push(auipc);

        let mut jalr = MachineInstr::new(RiscVOpcode::JALR as u32);
        jalr.operands.push(MachineOperand::PhysReg(ZERO as u32));
        jalr.push_reg(tmp_vr);
        jalr.operands.push(MachineOperand::Global(format!("%pcrel_lo({})", symbol)));
        instrs.push(jalr);
        instrs
    }

    /// Emit a NOP pseudo-instruction: `ADDI x0, x0, 0`.
    pub fn emit_nop(&self) -> MachineInstr {
        let mut nop = MachineInstr::new(RiscVOpcode::ADDI as u32);
        nop.operands.push(MachineOperand::PhysReg(ZERO as u32));
        nop.operands.push(MachineOperand::PhysReg(ZERO as u32));
        nop.push_imm(0);
        nop
    }

    /// Emit a MV pseudo-instruction: `ADDI rd, rs, 0`.
    pub fn emit_mv(&self, dest: u32, src: u32) -> MachineInstr {
        self.emit_mov_reg_reg(dest, src)
    }

    /// Emit a NOT pseudo-instruction: `XORI rd, rs, -1`.
    pub fn emit_not(&self, dest: u32, src: u32) -> MachineInstr {
        let mut xori = MachineInstr::new(RiscVOpcode::XORI as u32);
        xori.operands.push(MachineOperand::PhysReg(dest));
        xori.push_reg(src);
        xori.push_imm(-1);
        xori
    }

    /// Emit a NEG pseudo-instruction: `SUB rd, x0, rs`.
    pub fn emit_neg(&self, dest: u32, src: u32) -> MachineInstr {
        let mut sub = MachineInstr::new(RiscVOpcode::SUB as u32);
        sub.operands.push(MachineOperand::PhysReg(dest));
        sub.operands.push(MachineOperand::PhysReg(ZERO as u32));
        sub.push_reg(src);
        sub
    }

    /// Emit SEQZ pseudo: `SLTIU rd, rs, 1` (rd = (rs == 0)).
    pub fn emit_seqz(&self, dest: u32, src: u32) -> MachineInstr {
        let mut sltiu = MachineInstr::new(RiscVOpcode::SLTIU as u32);
        sltiu.operands.push(MachineOperand::PhysReg(dest));
        sltiu.push_reg(src);
        sltiu.push_imm(1);
        sltiu
    }

    /// Emit SNEZ pseudo: `SLTU rd, x0, rs` (rd = (rs != 0)).
    pub fn emit_snez(&self, dest: u32, src: u32) -> MachineInstr {
        let mut sltu = MachineInstr::new(RiscVOpcode::SLTU as u32);
        sltu.operands.push(MachineOperand::PhysReg(dest));
        sltu.operands.push(MachineOperand::PhysReg(ZERO as u32));
        sltu.push_reg(src);
        sltu
    }

    /// Emit SLTZ pseudo: `SLT rd, rs, x0` (rd = (rs < 0)).
    pub fn emit_sltz(&self, dest: u32, src: u32) -> MachineInstr {
        let mut slt = MachineInstr::new(RiscVOpcode::SLT as u32);
        slt.operands.push(MachineOperand::PhysReg(dest));
        slt.push_reg(src);
        slt.operands.push(MachineOperand::PhysReg(ZERO as u32));
        slt
    }

    /// Emit SGTZ pseudo: `SLT rd, x0, rs` (rd = (rs > 0)).
    pub fn emit_sgtz(&self, dest: u32, src: u32) -> MachineInstr {
        let mut slt = MachineInstr::new(RiscVOpcode::SLT as u32);
        slt.operands.push(MachineOperand::PhysReg(dest));
        slt.operands.push(MachineOperand::PhysReg(ZERO as u32));
        slt.push_reg(src);
        slt
    }

    // ==================================================================
    // Helpers
    // ==================================================================

    /// Lower a three-register binary operation.
    /// Op: rd = rs1 op rs2
    fn lower_three_reg_op(&self, inst: &Value, opcode: u32) -> MachineInstr {
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let src1_vr = self.get_operand_vreg(&inst.operands[0]);
        let src2_vr = self.get_operand_vreg(&inst.operands[1]);

        let mut mi = MachineInstr::new(opcode).with_def(def_vr);
        mi.push_reg(src1_vr);
        mi.push_reg(src2_vr);
        mi
    }

    /// Lower a binary operation that can use an immediate form if the
    /// second operand is a small constant.
    /// Uses `rr_opcode` for register-register, `ri_opcode` for register-immediate.
    fn lower_binary_op_with_imm(&self, inst: &Value, rr_opcode: u32, ri_opcode: u32) -> MachineInstr {
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let src1_vr = self.get_operand_vreg(&inst.operands[0]);

        // Try to extract the second operand as an immediate constant
        let src2 = &inst.operands[1];
        let src2_val = src2.borrow();

        // Check if operand 2 is a constant
        if let Some(imm_val) = Self::try_extract_constant(&src2_val) {
            if Self::fits_in_12bit(imm_val) {
                // Use immediate form: OPI rd, rs1, imm
                let mut mi = MachineInstr::new(ri_opcode).with_def(def_vr);
                mi.push_reg(src1_vr);
                mi.push_imm(imm_val);
                return mi;
            }
        }

        // Fall back to register-register form
        let src2_vr = self.get_operand_vreg(src2);
        let mut mi = MachineInstr::new(rr_opcode).with_def(def_vr);
        mi.push_reg(src1_vr);
        mi.push_reg(src2_vr);
        mi
    }

    /// Lower a shift operation that can use an immediate shift amount.
    fn lower_binary_op_with_shift_imm(&self, inst: &Value, rr_opcode: u32, ri_opcode: u32) -> MachineInstr {
        let def_vr = self.get_vreg_by_vid(inst.vid as usize);
        let src1_vr = self.get_operand_vreg(&inst.operands[0]);
        let src2 = &inst.operands[1];
        let src2_val = src2.borrow();

        if let Some(shift_amt) = Self::try_extract_constant(&src2_val) {
            let max_shift = if self.is_64bit { 63 } else { 31 };
            if shift_amt >= 0 && shift_amt <= max_shift as i64 {
                let mut mi = MachineInstr::new(ri_opcode).with_def(def_vr);
                mi.push_reg(src1_vr);
                mi.push_imm(shift_amt);
                return mi;
            }
        }

        // Fall back to register form
        let src2_vr = self.get_operand_vreg(src2);
        let mut mi = MachineInstr::new(rr_opcode).with_def(def_vr);
        mi.push_reg(src1_vr);
        mi.push_reg(src2_vr);
        mi
    }

    /// Try to extract a compile-time constant from a Value.
    fn try_extract_constant(val: &Value) -> Option<i64> {
        if val.is_constant() || val.subclass == crate::value::SubclassKind::ConstantInt {
            // For simplicity, use vid as a hint; in a real implementation,
            // constants would have their actual value stored in metadata.
            return Some(val.vid as i64);
        }
        // Check if the value has the "Constant" subclass
        if val.name.starts_with("const_") {
            // Parse the value from the name if possible
            if let Some(num_str) = val.name.strip_prefix("const_") {
                if let Ok(v) = num_str.parse::<i64>() {
                    return Some(v);
                }
            }
        }
        None
    }

    /// Look up the virtual register for a given IR value ID.
    /// If not yet assigned, allocate a new one.
    fn get_vreg_by_vid(&self, vid: usize) -> VirtReg {
        *self.vreg_map.get(&vid).unwrap_or(&(vid as u32))
    }

    /// Get the virtual register for an operand value reference.
    fn get_operand_vreg(&self, val: &std::rc::Rc<std::cell::RefCell<Value>>) -> VirtReg {
        let vid = val.borrow().vid as usize;
        self.get_vreg_by_vid(vid)
    }

    /// Emit a register-to-register move: `ADDI dest, src, 0`
    pub fn emit_mov_reg_reg(&self, dest: u32, src: u32) -> MachineInstr {
        let mut mi = MachineInstr::new(RiscVOpcode::ADDI as u32);
        mi.operands.push(MachineOperand::PhysReg(dest));
        mi.push_reg(src);
        mi.push_imm(0);
        mi
    }

    /// Emit a register-to-register move that defines a vreg.
    pub fn emit_mov_reg_reg_def(&self, def_vr: u32, src: u32) -> MachineInstr {
        let mut mi = MachineInstr::new(RiscVOpcode::ADDI as u32).with_def(def_vr);
        mi.push_reg(src);
        mi.push_imm(0);
        mi
    }

    /// Emit an immediate arithmetic instruction: `opcode rd, rs1, imm`
    pub fn emit_imm_arith(&self, opcode: u32, dest: u32, src: u32, imm: i64) -> MachineInstr {
        let mut mi = MachineInstr::new(opcode);
        mi.operands.push(MachineOperand::PhysReg(dest));
        mi.push_reg(src);
        mi.push_imm(imm);
        mi
    }

    /// Emit a register-register arithmetic instruction: `opcode rd, rs1, rs2`
    pub fn emit_rr_arith(&self, opcode: u32, dest: u32, src1: u32, src2: u32) -> MachineInstr {
        let mut mi = MachineInstr::new(opcode);
        mi.operands.push(MachineOperand::PhysReg(dest));
        mi.push_reg(src1);
        mi.push_reg(src2);
        mi
    }

    /// Emit a load/store instruction: `opcode reg, offset(base)`
    pub fn emit_load_store(&self, opcode: u32, reg: u32, base: u32, offset: i64) -> MachineInstr {
        let mut mi = MachineInstr::new(opcode);
        mi.operands.push(MachineOperand::PhysReg(reg));
        mi.push_reg(base);
        mi.push_imm(offset);
        mi
    }

    /// Check if a signed value fits in 12 bits (RISC-V immediate field).
    pub fn fits_in_12bit(value: i64) -> bool {
        value >= -2048 && value <= 2047
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::Type;
    use crate::value::{valref, SubclassKind};
    use std::rc::Rc;

    /// Helper: build a simple function Value with one basic block
    /// and one add instruction.
    fn build_add_ir() -> Value {
        // Build: %res = add i32 %a, %b
        let i32_ty = Type::i32();
        let mut func = Value::new(Type::void());
        func.subclass = SubclassKind::Function;
        func.name = "test_add".to_string();

        let mut bb = Value::new(Type::label());
        bb.subclass = SubclassKind::BasicBlock;
        bb.name = "entry".to_string();

        let a = valref(Value::new(i32_ty.clone()).named("a"));
        let b = valref(Value::new(i32_ty.clone()).named("b"));

        let mut add_inst = Value::new(i32_ty);
        add_inst.subclass = SubclassKind::Instruction;
        add_inst.set_opcode(Opcode::Add);
        add_inst.name = "res".to_string();
        add_inst.operands.push(Rc::clone(&a));
        add_inst.operands.push(Rc::clone(&b));
        add_inst.num_operands = 2;

        let add_ref = valref(add_inst);
        bb.operands.push(Rc::clone(&add_ref));

        // Add a return
        let mut ret = Value::new(Type::void());
        ret.subclass = SubclassKind::Instruction;
        ret.set_opcode(Opcode::Ret);
        ret.num_operands = 0;
        let ret_ref = valref(ret);
        bb.operands.push(Rc::clone(&ret_ref));

        let bb_ref = valref(bb);
        func.successors.push(Rc::clone(&bb_ref));

        func
    }

    /// Helper: build a function with a branch.
    fn build_branch_ir() -> Value {
        let i1_ty = Type::i1();
        let mut func = Value::new(Type::void());
        func.subclass = SubclassKind::Function;
        func.name = "test_br".to_string();

        let mut entry = Value::new(Type::label());
        entry.subclass = SubclassKind::BasicBlock;
        entry.name = "entry".to_string();

        let cond = valref(Value::new(i1_ty).named("cond"));

        let true_bb = Value::new(Type::label());
        let false_bb = Value::new(Type::label());

        let true_bb_ref = valref(true_bb.named("if.then"));
        let false_bb_ref = valref(false_bb.named("if.else"));

        let mut br = Value::new(Type::void());
        br.subclass = SubclassKind::Instruction;
        br.set_opcode(Opcode::Br);
        br.operands.push(Rc::clone(&cond));
        br.operands.push(Rc::clone(&true_bb_ref));
        br.operands.push(Rc::clone(&false_bb_ref));
        br.num_operands = 3;

        let br_ref = valref(br);
        entry.operands.push(Rc::clone(&br_ref));

        let entry_ref = valref(entry);
        func.successors.push(Rc::clone(&entry_ref));
        // Also push the target blocks (simplified)
        func.successors.push(Rc::clone(&true_bb_ref));
        func.successors.push(Rc::clone(&false_bb_ref));

        func
    }

    // ------------------------------------------------------------------
    // Selector construction
    // ------------------------------------------------------------------

    #[test]
    fn test_new_rv64() {
        let isel = RiscVInstructionSelector::new(true);
        assert!(isel.is_64bit);
        assert!(isel.vreg_map.is_empty());
    }

    #[test]
    fn test_new_rv32() {
        let isel = RiscVInstructionSelector::new(false);
        assert!(!isel.is_64bit);
    }

    // ------------------------------------------------------------------
    // Lowering tests
    // ------------------------------------------------------------------

    #[test]
    fn test_lower_add() {
        let i32_ty = Type::i32();
        let mut inst = Value::new(i32_ty);
        inst.subclass = SubclassKind::Instruction;
        inst.set_opcode(Opcode::Add);
        inst.name = "res".to_string();

        let a = valref(Value::new(Type::i32()).named("a"));
        let b = valref(Value::new(Type::i32()).named("b"));
        inst.operands.push(Rc::clone(&a));
        inst.operands.push(Rc::clone(&b));
        inst.num_operands = 2;

        let isel = RiscVInstructionSelector::new(true);
        let mi = isel.lower_add(&inst);
        assert_eq!(mi.opcode, RiscVOpcode::ADD as u32);
        assert_eq!(mi.operands.len(), 2);
    }

    #[test]
    fn test_lower_sub() {
        let i32_ty = Type::i32();
        let mut inst = Value::new(i32_ty);
        inst.subclass = SubclassKind::Instruction;
        inst.set_opcode(Opcode::Sub);

        let a = valref(Value::new(Type::i32()).named("a"));
        let b = valref(Value::new(Type::i32()).named("b"));
        inst.operands.push(Rc::clone(&a));
        inst.operands.push(Rc::clone(&b));
        inst.num_operands = 2;

        let isel = RiscVInstructionSelector::new(true);
        let mi = isel.lower_sub(&inst);
        assert_eq!(mi.opcode, RiscVOpcode::SUB as u32);
    }

    #[test]
    fn test_lower_mul() {
        let i32_ty = Type::i32();
        let mut inst = Value::new(i32_ty);
        inst.subclass = SubclassKind::Instruction;
        inst.set_opcode(Opcode::Mul);

        let a = valref(Value::new(Type::i32()).named("a"));
        let b = valref(Value::new(Type::i32()).named("b"));
        inst.operands.push(Rc::clone(&a));
        inst.operands.push(Rc::clone(&b));
        inst.num_operands = 2;

        let isel = RiscVInstructionSelector::new(true);
        let mi = isel.lower_mul(&inst);
        assert_eq!(mi.opcode, RiscVOpcode::MUL as u32);
    }

    #[test]
    fn test_lower_sdiv() {
        let i32_ty = Type::i32();
        let mut inst = Value::new(i32_ty);
        inst.subclass = SubclassKind::Instruction;
        inst.set_opcode(Opcode::SDiv);

        let a = valref(Value::new(Type::i32()).named("a"));
        let b = valref(Value::new(Type::i32()).named("b"));
        inst.operands.push(Rc::clone(&a));
        inst.operands.push(Rc::clone(&b));
        inst.num_operands = 2;

        let isel = RiscVInstructionSelector::new(true);
        let instrs = isel.lower_sdiv(&inst);
        assert_eq!(instrs.len(), 1);
        assert_eq!(instrs[0].opcode, RiscVOpcode::DIV as u32);
    }

    #[test]
    fn test_lower_udiv() {
        let i32_ty = Type::i32();
        let mut inst = Value::new(i32_ty);
        inst.subclass = SubclassKind::Instruction;
        inst.set_opcode(Opcode::UDiv);

        let a = valref(Value::new(Type::i32()).named("a"));
        let b = valref(Value::new(Type::i32()).named("b"));
        inst.operands.push(Rc::clone(&a));
        inst.operands.push(Rc::clone(&b));
        inst.num_operands = 2;

        let isel = RiscVInstructionSelector::new(true);
        let instrs = isel.lower_udiv(&inst);
        assert_eq!(instrs.len(), 1);
        assert_eq!(instrs[0].opcode, RiscVOpcode::DIVU as u32);
    }

    #[test]
    fn test_lower_and() {
        let i32_ty = Type::i32();
        let mut inst = Value::new(i32_ty);
        inst.subclass = SubclassKind::Instruction;
        inst.set_opcode(Opcode::And);

        let a = valref(Value::new(Type::i32()).named("a"));
        let b = valref(Value::new(Type::i32()).named("b"));
        inst.operands.push(Rc::clone(&a));
        inst.operands.push(Rc::clone(&b));
        inst.num_operands = 2;

        let isel = RiscVInstructionSelector::new(true);
        let mi = isel.lower_and(&inst);
        assert_eq!(mi.opcode, RiscVOpcode::AND as u32);
    }

    #[test]
    fn test_lower_or() {
        let i32_ty = Type::i32();
        let mut inst = Value::new(i32_ty);
        inst.subclass = SubclassKind::Instruction;
        inst.set_opcode(Opcode::Or);

        let a = valref(Value::new(Type::i32()).named("a"));
        let b = valref(Value::new(Type::i32()).named("b"));
        inst.operands.push(Rc::clone(&a));
        inst.operands.push(Rc::clone(&b));
        inst.num_operands = 2;

        let isel = RiscVInstructionSelector::new(true);
        let mi = isel.lower_or(&inst);
        assert_eq!(mi.opcode, RiscVOpcode::OR as u32);
    }

    #[test]
    fn test_lower_xor() {
        let i32_ty = Type::i32();
        let mut inst = Value::new(i32_ty);
        inst.subclass = SubclassKind::Instruction;
        inst.set_opcode(Opcode::Xor);

        let a = valref(Value::new(Type::i32()).named("a"));
        let b = valref(Value::new(Type::i32()).named("b"));
        inst.operands.push(Rc::clone(&a));
        inst.operands.push(Rc::clone(&b));
        inst.num_operands = 2;

        let isel = RiscVInstructionSelector::new(true);
        let mi = isel.lower_xor(&inst);
        assert_eq!(mi.opcode, RiscVOpcode::XOR as u32);
    }

    #[test]
    fn test_lower_shl() {
        let i32_ty = Type::i32();
        let mut inst = Value::new(i32_ty);
        inst.subclass = SubclassKind::Instruction;
        inst.set_opcode(Opcode::Shl);

        let a = valref(Value::new(Type::i32()).named("a"));
        let b = valref(Value::new(Type::i32()).named("b"));
        inst.operands.push(Rc::clone(&a));
        inst.operands.push(Rc::clone(&b));
        inst.num_operands = 2;

        let isel = RiscVInstructionSelector::new(true);
        let mi = isel.lower_shl(&inst);
        assert_eq!(mi.opcode, RiscVOpcode::SLL as u32);
    }

    #[test]
    fn test_lower_lshr() {
        let i32_ty = Type::i32();
        let mut inst = Value::new(i32_ty);
        inst.subclass = SubclassKind::Instruction;
        inst.set_opcode(Opcode::LShr);

        let a = valref(Value::new(Type::i32()).named("a"));
        let b = valref(Value::new(Type::i32()).named("b"));
        inst.operands.push(Rc::clone(&a));
        inst.operands.push(Rc::clone(&b));
        inst.num_operands = 2;

        let isel = RiscVInstructionSelector::new(true);
        let mi = isel.lower_lshr(&inst);
        assert_eq!(mi.opcode, RiscVOpcode::SRL as u32);
    }

    #[test]
    fn test_lower_ashr() {
        let i32_ty = Type::i32();
        let mut inst = Value::new(i32_ty);
        inst.subclass = SubclassKind::Instruction;
        inst.set_opcode(Opcode::AShr);

        let a = valref(Value::new(Type::i32()).named("a"));
        let b = valref(Value::new(Type::i32()).named("b"));
        inst.operands.push(Rc::clone(&a));
        inst.operands.push(Rc::clone(&b));
        inst.num_operands = 2;

        let isel = RiscVInstructionSelector::new(true);
        let mi = isel.lower_ashr(&inst);
        assert_eq!(mi.opcode, RiscVOpcode::SRA as u32);
    }

    #[test]
    fn test_lower_icmp_has_sub_and_sltiu() {
        let i32_ty = Type::i32();
        let mut inst = Value::new(Type::i1());
        inst.subclass = SubclassKind::Instruction;
        inst.set_opcode(Opcode::ICmp);

        let a = valref(Value::new(i32_ty.clone()).named("a"));
        let b = valref(Value::new(i32_ty).named("b"));
        inst.operands.push(Rc::clone(&a));
        inst.operands.push(Rc::clone(&b));
        inst.num_operands = 2;

        let isel = RiscVInstructionSelector::new(true);
        let instrs = isel.lower_icmp(&inst);
        // Should produce SUB + SLTIU
        assert_eq!(instrs.len(), 2);
        assert_eq!(instrs[0].opcode, RiscVOpcode::SUB as u32);
        assert_eq!(instrs[1].opcode, RiscVOpcode::SLTIU as u32);
    }

    #[test]
    fn test_lower_ret_rv64() {
        let mut inst = Value::new(Type::void());
        inst.subclass = SubclassKind::Instruction;
        inst.set_opcode(Opcode::Ret);
        inst.num_operands = 0;

        let isel = RiscVInstructionSelector::new(true);
        let instrs = isel.lower_ret(&inst);
        assert_eq!(instrs.len(), 1);
        assert_eq!(instrs[0].opcode, RiscVOpcode::RET as u32);
    }

    #[test]
    fn test_lower_ret_with_value() {
        let mut inst = Value::new(Type::void());
        inst.subclass = SubclassKind::Instruction;
        inst.set_opcode(Opcode::Ret);
        let val = valref(Value::new(Type::i32()).named("retval"));
        inst.operands.push(Rc::clone(&val));
        inst.num_operands = 1;

        let isel = RiscVInstructionSelector::new(true);
        let instrs = isel.lower_ret(&inst);
        // Should contain MV to a0 + RET
        assert!(instrs.len() >= 1);
        assert_eq!(instrs.last().unwrap().opcode, RiscVOpcode::RET as u32);
    }

    #[test]
    fn test_lower_alloca() {
        let mut inst = Value::new(Type::pointer(0));
        inst.subclass = SubclassKind::Instruction;
        inst.set_opcode(Opcode::Alloca);
        inst.num_operands = 1;

        let isel = RiscVInstructionSelector::new(true);
        let mi = isel.lower_alloca(&inst);
        assert_eq!(mi.opcode, RiscVOpcode::ADDI as u32);
        // Should reference SP
        assert!(matches!(&mi.operands[0], MachineOperand::PhysReg(r) if *r == SP as u32));
    }

    #[test]
    fn test_lower_load_rv64() {
        let mut inst = Value::new(Type::i32());
        inst.subclass = SubclassKind::Instruction;
        inst.set_opcode(Opcode::Load);
        let ptr = valref(Value::new(Type::pointer(0)).named("ptr"));
        inst.operands.push(Rc::clone(&ptr));
        inst.num_operands = 1;

        let isel = RiscVInstructionSelector::new(true);
        let mi = isel.lower_load(&inst);
        assert_eq!(mi.opcode, RiscVOpcode::LD as u32);
    }

    #[test]
    fn test_lower_load_rv32() {
        let mut inst = Value::new(Type::i32());
        inst.subclass = SubclassKind::Instruction;
        inst.set_opcode(Opcode::Load);
        let ptr = valref(Value::new(Type::pointer(0)).named("ptr"));
        inst.operands.push(Rc::clone(&ptr));
        inst.num_operands = 1;

        let isel = RiscVInstructionSelector::new(false);
        let mi = isel.lower_load(&inst);
        assert_eq!(mi.opcode, RiscVOpcode::LW as u32);
    }

    #[test]
    fn test_lower_store_rv64() {
        let mut inst = Value::new(Type::void());
        inst.subclass = SubclassKind::Instruction;
        inst.set_opcode(Opcode::Store);
        let val = valref(Value::new(Type::i32()).named("val"));
        let ptr = valref(Value::new(Type::pointer(0)).named("ptr"));
        inst.operands.push(Rc::clone(&val));
        inst.operands.push(Rc::clone(&ptr));
        inst.num_operands = 2;

        let isel = RiscVInstructionSelector::new(true);
        let mi = isel.lower_store(&inst);
        assert_eq!(mi.opcode, RiscVOpcode::SD as u32);
    }

    #[test]
    fn test_lower_store_rv32() {
        let mut inst = Value::new(Type::void());
        inst.subclass = SubclassKind::Instruction;
        inst.set_opcode(Opcode::Store);
        let val = valref(Value::new(Type::i32()).named("val"));
        let ptr = valref(Value::new(Type::pointer(0)).named("ptr"));
        inst.operands.push(Rc::clone(&val));
        inst.operands.push(Rc::clone(&ptr));
        inst.num_operands = 2;

        let isel = RiscVInstructionSelector::new(false);
        let mi = isel.lower_store(&inst);
        assert_eq!(mi.opcode, RiscVOpcode::SW as u32);
    }

    #[test]
    fn test_lower_zext() {
        let mut inst = Value::new(Type::i64());
        inst.subclass = SubclassKind::Instruction;
        inst.set_opcode(Opcode::ZExt);
        let val = valref(Value::new(Type::i32()).named("val"));
        inst.operands.push(Rc::clone(&val));
        inst.num_operands = 1;

        let isel = RiscVInstructionSelector::new(true);
        let mi = isel.lower_zext(&inst);
        // Should be an ADDI (MV) for simple zero-extend
        assert_eq!(mi.opcode, RiscVOpcode::ADDI as u32);
    }

    #[test]
    fn test_lower_sext() {
        let mut inst = Value::new(Type::i64());
        inst.subclass = SubclassKind::Instruction;
        inst.set_opcode(Opcode::SExt);
        let val = valref(Value::new(Type::i32()).named("val"));
        inst.operands.push(Rc::clone(&val));
        inst.num_operands = 1;

        let isel = RiscVInstructionSelector::new(true);
        let mi = isel.lower_sext(&inst);
        assert_eq!(mi.opcode, RiscVOpcode::ADDIW as u32);
    }

    #[test]
    fn test_lower_trunc() {
        let mut inst = Value::new(Type::i32());
        inst.subclass = SubclassKind::Instruction;
        inst.set_opcode(Opcode::Trunc);
        let val = valref(Value::new(Type::i64()).named("val"));
        inst.operands.push(Rc::clone(&val));
        inst.num_operands = 1;

        let isel = RiscVInstructionSelector::new(true);
        let mi = isel.lower_trunc(&inst);
        assert_eq!(mi.opcode, RiscVOpcode::ADDI as u32);
    }

    #[test]
    fn test_lower_bitcast() {
        let mut inst = Value::new(Type::i64());
        inst.subclass = SubclassKind::Instruction;
        inst.set_opcode(Opcode::BitCast);
        let val = valref(Value::new(Type::i64()).named("val"));
        inst.operands.push(Rc::clone(&val));
        inst.num_operands = 1;

        let isel = RiscVInstructionSelector::new(true);
        let mi = isel.lower_bitcast(&inst);
        assert_eq!(mi.opcode, RiscVOpcode::ADDI as u32);
    }

    #[test]
    fn test_lower_gep() {
        let mut inst = Value::new(Type::pointer(0));
        inst.subclass = SubclassKind::Instruction;
        inst.set_opcode(Opcode::GetElementPtr);
        let base = valref(Value::new(Type::pointer(0)).named("base"));
        inst.operands.push(Rc::clone(&base));
        inst.num_operands = 1;

        let isel = RiscVInstructionSelector::new(true);
        let mi = isel.lower_gep(&inst);
        assert_eq!(mi.opcode, RiscVOpcode::ADDI as u32);
    }

    #[test]
    fn test_fits_in_12bit() {
        assert!(RiscVInstructionSelector::fits_in_12bit(0));
        assert!(RiscVInstructionSelector::fits_in_12bit(2047));
        assert!(RiscVInstructionSelector::fits_in_12bit(-2048));
        assert!(!RiscVInstructionSelector::fits_in_12bit(2048));
        assert!(!RiscVInstructionSelector::fits_in_12bit(-2049));
        assert!(!RiscVInstructionSelector::fits_in_12bit(4096));
    }

    #[test]
    fn test_select_instruction_dispatch() {
        let mut isel = RiscVInstructionSelector::new(true);

        let i32_ty = Type::i32();
        let mut inst = Value::new(i32_ty);
        inst.subclass = SubclassKind::Instruction;
        inst.set_opcode(Opcode::Add);

        let a = valref(Value::new(Type::i32()).named("a"));
        let b = valref(Value::new(Type::i32()).named("b"));
        inst.operands.push(Rc::clone(&a));
        inst.operands.push(Rc::clone(&b));
        inst.num_operands = 2;

        let result = isel.select_instruction(&inst);
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].opcode, RiscVOpcode::ADD as u32);
    }

    #[test]
    fn test_select_instruction_unknown_returns_empty() {
        let mut isel = RiscVInstructionSelector::new(true);

        let mut inst = Value::new(Type::void());
        inst.subclass = SubclassKind::Instruction;
        inst.set_opcode(Opcode::Unreachable); // Unsupported opcode

        let result = isel.select_instruction(&inst);
        assert!(result.is_empty());
    }
}