llvm-native-core 0.1.10

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
//! LLVM Constants — all constant values.
//! Clean-room behavioral reconstruction. Phase 1 → Phase 2 — LLVM.IR.2 Court.

use crate::types::{Type, TypeId, TypeKind};
use crate::value::{valref, SubclassKind, Value, ValueRef};

/// Container for raw constant data (byte arrays, strings, etc.).
#[derive(Debug, Clone)]
pub struct ConstantData {
    pub data: Vec<u8>,
}

/// A constant integer value (like `i32 42` or `i64 -1`).
/// @llvm_behavior: ConstantInt holds an APInt (arbitrary precision integer).
/// For simplicity, we store i64; full APInt would be needed for >64 bit integers.
#[derive(Debug, Clone)]
pub struct ConstantInt {
    pub value: Value,
    /// The bit width
    pub bits: u32,
    /// Signed value for integers up to 64 bits
    pub signed_val: i64,
    /// Unsigned value
    pub unsigned_val: u64,
}

/// Create a constant integer (e.g., `i32 42`).
pub fn const_int(ty: Type, val: i64) -> ValueRef {
    let bits = ty.integer_bit_width();
    let unsigned_val = if val >= 0 {
        val as u64
    } else {
        !((-(val as i128 + 1)) as u64)
    };
    let mut v = Value::new(ty).with_subclass(SubclassKind::Constant);
    v.name = format!("{}", val);
    v.set_subclass_data(val as u32);
    valref(v)
}

/// Create an i32 constant.
pub fn const_i32(val: i32) -> ValueRef {
    const_int(Type::i32(), val as i64)
}

/// Create an i64 constant.
pub fn const_i64(val: i64) -> ValueRef {
    const_int(Type::i64(), val)
}

/// Create an i1 constant (true/false).
pub fn const_bool(val: bool) -> ValueRef {
    const_int(Type::i1(), if val { 1 } else { 0 })
}

/// Create an i8 constant.
pub fn const_i8(val: i8) -> ValueRef {
    const_int(Type::i8(), val as i64)
}

/// A constant floating-point value.
#[derive(Debug, Clone)]
pub struct ConstantFP {
    pub value: Value,
    /// The float value as f64
    pub fp_val: f64,
}

/// Create a constant 32-bit float.  The name stores the IEEE 754 bit
/// pattern as a decimal string so the ISel can use it as a raw i32
/// immediate (zero-extended to i64 in the name).
pub fn const_float(val: f64) -> ValueRef {
    let ty = Type::float();
    let mut v = Value::new(ty).with_subclass(SubclassKind::Constant);
    v.name = format!("{}", (val as f32).to_bits());
    valref(v)
}

/// Create a constant 32-bit float (f32).
pub fn const_f32(val: f32) -> ValueRef {
    const_float(val as f64)
}

/// Create a constant double.
pub fn const_double(val: f64) -> ValueRef {
    let ty = Type::double();
    let mut v = Value::new(ty).with_subclass(SubclassKind::Constant);
    // Store the IEEE 754 bit pattern as the constant's name, so the ISel
    // can use it as a raw i64 immediate.  Previously we stored the float
    // value string ("3"), but the ISel parses the name as i64, which gave
    // the integer 3 instead of the bit pattern 0x4008000000000000 for 3.0.
    v.name = format!("{}", val.to_bits());
    valref(v)
}

/// Create a constant 64-bit float (f64) — alias for const_double.
pub fn const_f64(val: f64) -> ValueRef {
    const_double(val)
}

/// A null pointer constant.
pub fn const_null_ptr(ty: Type) -> ValueRef {
    let mut v = Value::new(ty).with_subclass(SubclassKind::Constant);
    v.name = "null".into();
    valref(v)
}

/// An undef value (any value of the given type, undefined contents).
pub fn undef_value(ty: Type) -> ValueRef {
    let mut v = Value::new(ty).with_subclass(SubclassKind::Constant);
    v.name = "undef".into();
    valref(v)
}

/// A poison value (results in UB if used in certain ways).
pub fn poison_value(ty: Type) -> ValueRef {
    let mut v = Value::new(ty).with_subclass(SubclassKind::Constant);
    v.name = "poison".into();
    valref(v)
}

/// A zero initializer constant.
pub fn const_zero(ty: Type) -> ValueRef {
    match &ty.kind {
        TypeKind::Integer { .. } => const_int(ty.clone(), 0),
        TypeKind::Float | TypeKind::Double => const_float(0.0),
        TypeKind::Pointer { .. } => const_null_ptr(ty.clone()),
        TypeKind::Struct { .. } => {
            let mut v = Value::new(ty).with_subclass(SubclassKind::Constant);
            v.name = "zeroinitializer".into();
            valref(v)
        }
        TypeKind::Array { .. } | TypeKind::FixedVector { .. } => {
            let mut v = Value::new(ty).with_subclass(SubclassKind::Constant);
            v.name = "zeroinitializer".into();
            valref(v)
        }
        _ => undef_value(ty),
    }
}

// === Constant expressions (simplified) ===

/// A constant expression: add two constants.
pub fn const_add(a: ValueRef, b: ValueRef) -> ValueRef {
    let ty = a.borrow().ty.clone();
    let mut v = Value::new(ty).with_subclass(SubclassKind::Constant);
    v.push_operand(a);
    v.push_operand(b);
    valref(v)
}

/// A constant expression: getelementptr.
pub fn const_gep(base: ValueRef, indices: Vec<ValueRef>) -> ValueRef {
    let ty = Type::pointer(0);
    let mut v = Value::new(ty).with_subclass(SubclassKind::Constant);
    v.push_operand(base);
    for idx in indices {
        v.push_operand(idx);
    }
    valref(v)
}

/// A constant expression: bitcast.
pub fn const_bitcast(val: ValueRef, to_type: Type) -> ValueRef {
    let mut v = Value::new(to_type).with_subclass(SubclassKind::Constant);
    v.push_operand(val);
    valref(v)
}

// === Constant Expressions ===

/// Create a constant GEP (inbounds) expression.
pub fn const_gep_inbounds(base: ValueRef, indices: Vec<ValueRef>) -> ValueRef {
    let ty = Type::pointer(0);
    let mut v = Value::new(ty).with_subclass(SubclassKind::Constant);
    v.push_operand(base);
    for idx in indices {
        v.push_operand(idx);
    }
    v.subclass_data = 1; // flag: inbounds
    valref(v)
}

/// Create a constant integer-to-pointer cast.
pub fn const_int_to_ptr(val: ValueRef, to_type: Type) -> ValueRef {
    let mut v = Value::new(to_type).with_subclass(SubclassKind::Constant);
    v.push_operand(val);
    valref(v)
}

/// Create a constant pointer-to-integer cast.
pub fn const_ptr_to_int(val: ValueRef, to_type: Type) -> ValueRef {
    let mut v = Value::new(to_type).with_subclass(SubclassKind::Constant);
    v.push_operand(val);
    valref(v)
}

/// Create a constant truncate expression.
pub fn const_trunc(val: ValueRef, to_type: Type) -> ValueRef {
    let mut v = Value::new(to_type).with_subclass(SubclassKind::Constant);
    v.push_operand(val);
    valref(v)
}

/// Create a constant zero-extend expression.
pub fn const_zext(val: ValueRef, to_type: Type) -> ValueRef {
    let mut v = Value::new(to_type).with_subclass(SubclassKind::Constant);
    v.push_operand(val);
    valref(v)
}

/// Create a constant sign-extend expression.
pub fn const_sext(val: ValueRef, to_type: Type) -> ValueRef {
    let mut v = Value::new(to_type).with_subclass(SubclassKind::Constant);
    v.push_operand(val);
    valref(v)
}

/// Create a constant fptoui expression.
pub fn const_fptoui(val: ValueRef, to_type: Type) -> ValueRef {
    let mut v = Value::new(to_type).with_subclass(SubclassKind::Constant);
    v.push_operand(val);
    valref(v)
}

/// Create a constant fptosi expression.
pub fn const_fptosi(val: ValueRef, to_type: Type) -> ValueRef {
    let mut v = Value::new(to_type).with_subclass(SubclassKind::Constant);
    v.push_operand(val);
    valref(v)
}

/// Create a constant uitofp expression.
pub fn const_uitofp(val: ValueRef, to_type: Type) -> ValueRef {
    let mut v = Value::new(to_type).with_subclass(SubclassKind::Constant);
    v.push_operand(val);
    valref(v)
}

/// Create a constant sitofp expression.
pub fn const_sitofp(val: ValueRef, to_type: Type) -> ValueRef {
    let mut v = Value::new(to_type).with_subclass(SubclassKind::Constant);
    v.push_operand(val);
    valref(v)
}

/// Create a constant select expression.
pub fn const_select(cond: ValueRef, true_val: ValueRef, false_val: ValueRef) -> ValueRef {
    let ty = true_val.borrow().ty.clone();
    let mut v = Value::new(ty).with_subclass(SubclassKind::Constant);
    v.push_operand(cond);
    v.push_operand(true_val);
    v.push_operand(false_val);
    valref(v)
}

/// Create a constant extractvalue expression.
pub fn const_extract_value(agg: ValueRef, indices: &[u32]) -> ValueRef {
    // Determine result type by walking type kinds
    let ty = agg.borrow().ty.clone();
    let mut result_ty = ty;
    for &idx in indices {
        result_ty = match &result_ty.kind {
            TypeKind::Struct {
                element_type_ids, ..
            } => {
                // We return void as a fallback since we can't resolve TypeIds without context
                Type::void()
            }
            TypeKind::Array { .. } => Type::void(),
            _ => Type::void(),
        };
    }
    let mut v = Value::new(result_ty).with_subclass(SubclassKind::Constant);
    v.push_operand(agg);
    v.subclass_data = indices.iter().fold(0u32, |acc, i| acc.wrapping_add(*i));
    valref(v)
}

/// Create a constant insertvalue expression.
pub fn const_insert_value(agg: ValueRef, element: ValueRef, indices: &[u32]) -> ValueRef {
    let ty = agg.borrow().ty.clone();
    let mut v = Value::new(ty).with_subclass(SubclassKind::Constant);
    v.push_operand(agg);
    v.push_operand(element);
    v.subclass_data = indices.iter().fold(0u32, |acc, i| acc.wrapping_add(*i));
    valref(v)
}

// === Constant Aggregates ===

/// Create a constant array.
pub fn const_array(element_ty: Type, elements: &[ValueRef]) -> ValueRef {
    let len = elements.len() as u32;
    let ty = Type::array_with(len as u64, element_ty.id);
    let mut v = Value::new(ty).with_subclass(SubclassKind::Constant);
    for elem in elements {
        v.push_operand(elem.clone());
    }
    valref(v)
}

/// Create a constant struct.
pub fn const_struct(field_types: &[Type], elements: &[ValueRef]) -> ValueRef {
    let type_ids: Vec<TypeId> = field_types.iter().map(|t| t.id).collect();
    let ty = Type::struct_literal_with(false, type_ids);
    let mut v = Value::new(ty).with_subclass(SubclassKind::Constant);
    for elem in elements {
        v.push_operand(elem.clone());
    }
    valref(v)
}

/// Create a constant packed struct.
pub fn const_packed_struct(field_types: &[Type], elements: &[ValueRef]) -> ValueRef {
    let type_ids: Vec<TypeId> = field_types.iter().map(|t| t.id).collect();
    let ty = Type::struct_literal_with(true, type_ids);
    let mut v = Value::new(ty).with_subclass(SubclassKind::Constant);
    for elem in elements {
        v.push_operand(elem.clone());
    }
    valref(v)
}

/// Create a constant vector (fixed-length).
pub fn const_vector(elements: &[ValueRef]) -> ValueRef {
    if elements.is_empty() {
        return undef_value(Type::void());
    }
    let elem_type_id = elements[0].borrow().ty.id;
    let len = elements.len() as u32;
    let ty = Type::fixed_vector_with(len, elem_type_id);
    let mut v = Value::new(ty).with_subclass(SubclassKind::Constant);
    for elem in elements {
        v.push_operand(elem.clone());
    }
    valref(v)
}

/// Create a constant aggregate zero initializer.
pub fn const_aggregate_zero(ty: Type) -> ValueRef {
    let mut v = Value::new(ty).with_subclass(SubclassKind::Constant);
    v.name = "zeroinitializer".into();
    valref(v)
}

/// Create a blockaddress constant.
pub fn const_block_address(func: ValueRef, block: ValueRef) -> ValueRef {
    let ty = Type::pointer(0);
    let mut v = Value::new(ty).with_subclass(SubclassKind::Constant);
    v.push_operand(func);
    v.push_operand(block);
    valref(v)
}

/// Create a token 'none' constant.
pub fn const_token_none() -> ValueRef {
    let ty = Type::token();
    let mut v = Value::new(ty).with_subclass(SubclassKind::Constant);
    v.name = "none".into();
    valref(v)
}

// === Constant Folding Utilities ===

/// Attempt to constant-fold an integer binary operation.
pub fn const_fold_int_binop(
    a_val: i64,
    b_val: i64,
    op: crate::opcode::Opcode,
    bits: u32,
) -> Option<i64> {
    use crate::opcode::Opcode;
    let mask = if bits >= 64 {
        u64::MAX
    } else {
        (1u64 << bits) - 1
    };
    let a = a_val as u64 & mask;
    let b = b_val as u64 & mask;
    let result = match op {
        Opcode::Add => a.wrapping_add(b),
        Opcode::Sub => a.wrapping_sub(b),
        Opcode::Mul => a.wrapping_mul(b),
        Opcode::SDiv | Opcode::UDiv => {
            if b == 0 {
                return None;
            }
            if op == Opcode::SDiv && a_val == i64::MIN && b_val == -1 {
                return None;
            }
            if op == Opcode::SDiv {
                a_val.wrapping_div(b_val) as u64
            } else {
                a / b
            }
        }
        Opcode::SRem | Opcode::URem => {
            if b == 0 {
                return None;
            }
            if op == Opcode::SRem {
                a_val.wrapping_rem(b_val) as u64
            } else {
                a % b
            }
        }
        Opcode::Shl => a.wrapping_shl((b & (bits as u64 - 1)) as u32),
        Opcode::LShr => a.wrapping_shr((b & (bits as u64 - 1)) as u32),
        Opcode::AShr => {
            let shift = (b & (bits as u64 - 1)) as u32;
            ((a_val >> shift) as u64) & mask
        }
        Opcode::And => a & b,
        Opcode::Or => a | b,
        Opcode::Xor => a ^ b,
        _ => return None,
    };
    let sign_bit = 1u64 << (bits - 1);
    let result_masked = result & mask;
    if result_masked & sign_bit != 0 && bits < 64 {
        Some(-(((result_masked ^ mask) + 1) as i64))
    } else {
        Some(result_masked as i64)
    }
}

/// Attempt to constant-fold an ICmp comparison.
pub fn const_fold_icmp(a_val: i64, b_val: i64, pred: crate::instruction::ICmpPred) -> Option<bool> {
    use crate::instruction::ICmpPred;
    Some(match pred {
        ICmpPred::Eq => a_val == b_val,
        ICmpPred::Ne => a_val != b_val,
        ICmpPred::Ugt => (a_val as u64) > (b_val as u64),
        ICmpPred::Uge => (a_val as u64) >= (b_val as u64),
        ICmpPred::Ult => (a_val as u64) < (b_val as u64),
        ICmpPred::Ule => (a_val as u64) <= (b_val as u64),
        ICmpPred::Sgt => a_val > b_val,
        ICmpPred::Sge => a_val >= b_val,
        ICmpPred::Slt => a_val < b_val,
        ICmpPred::Sle => a_val <= b_val,
    })
}
#[derive(Debug, Clone)]
pub struct GlobalVariable {
    pub value: Value,
    pub is_constant: bool,
    pub initializer: Option<ValueRef>,
    pub linkage: crate::function::Linkage,
    pub section: Option<String>,
    pub alignment: u32,
}

/// Create a global variable.
pub fn new_global(
    ty: Type,
    is_constant: bool,
    linkage: crate::function::Linkage,
    initializer: Option<ValueRef>,
    name: &str,
) -> ValueRef {
    let mut v = Value::new(ty)
        .named(name)
        .with_subclass(SubclassKind::GlobalVariable);
    v.initializer = initializer;
    v.is_constant = is_constant;
    let gv = valref(v);
    // Store linkage in subclass_extra[0] (bit 0 = is_constant, bit 1-2 = linkage)
    gv.borrow_mut().subclass_extra =
        vec![if is_constant { 1u64 } else { 0u64 } | ((linkage as u64) << 1)];
    gv
}

// === Metadata ===

/// A metadata node — a tuple of metadata operands.
#[derive(Debug, Clone)]
pub struct MDNode {
    pub operands: Vec<MetadataValue>,
    /// Unique ID for this node
    pub id: u64,
}

/// A value in the metadata hierarchy.
#[derive(Debug, Clone)]
pub enum MetadataValue {
    /// A metadata string
    String(String),
    /// A reference to an MDNode
    Node(u64),
    /// A constant value as metadata
    Constant(ValueRef),
    /// A null metadata reference
    Null,
}

/// Create a metadata node.
pub fn md_node(operands: Vec<MetadataValue>) -> MDNode {
    use std::sync::atomic::{AtomicU64, Ordering};
    static NEXT_MD_ID: AtomicU64 = AtomicU64::new(0);
    MDNode {
        operands,
        id: NEXT_MD_ID.fetch_add(1, Ordering::SeqCst),
    }
}

/// Create a metadata string.
pub fn md_string(s: impl Into<String>) -> MetadataValue {
    MetadataValue::String(s.into())
}

/// Named metadata in a module (e.g., !llvm.module.flags).
#[derive(Debug, Clone)]
pub struct NamedMDNode {
    pub name: String,
    pub operands: Vec<u64>, // MDNode IDs
}

/// Debug location metadata: file, line, column, scope.
#[derive(Debug, Clone)]
pub struct DebugLoc {
    pub line: u32,
    pub column: u32,
    pub scope: Option<u64>, // MDNode ID
    pub inlined_at: Option<u64>,
}

/// A debug info kind for building DI metadata.
#[derive(Debug, Clone)]
pub enum DIKind {
    CompileUnit,
    File,
    Subprogram,
    LexicalBlock,
    SubroutineType,
    BasicType,
    DerivedType,
    CompositeType,
}

/// Builder for debug info metadata (DIBuilder equivalent).
pub struct DIBuilder {
    pub nodes: Vec<MDNode>,
}

impl DIBuilder {
    pub fn new() -> Self {
        Self { nodes: Vec::new() }
    }

    /// Create a compile unit.
    pub fn create_compile_unit(&mut self, file_id: u64, producer: &str) -> u64 {
        let node = md_node(vec![md_string(producer), MetadataValue::Node(file_id)]);
        let id = node.id;
        self.nodes.push(node);
        id
    }

    /// Create a file descriptor.
    pub fn create_file(&mut self, filename: &str, directory: &str) -> u64 {
        let node = md_node(vec![md_string(filename), md_string(directory)]);
        let id = node.id;
        self.nodes.push(node);
        id
    }

    /// Create a subprogram (function debug info).
    pub fn create_function(
        &mut self,
        scope_id: u64,
        name: &str,
        linkage_name: &str,
        file_id: u64,
        line: u32,
        ty_id: u64,
    ) -> u64 {
        let node = md_node(vec![
            MetadataValue::Node(scope_id),
            md_string(name),
            md_string(linkage_name),
            MetadataValue::Node(file_id),
            MetadataValue::Constant(const_i32(line as i32)),
            MetadataValue::Node(ty_id),
        ]);
        let id = node.id;
        self.nodes.push(node);
        id
    }

    /// Finalize and return all nodes.
    pub fn finalize(self) -> Vec<MDNode> {
        self.nodes
    }
}

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

// ============================================================================
// Phase 2 — Constant expression evaluation, folding, and aggregate support
// ============================================================================

use crate::opcode::{FCmpPred, ICmpPred, Opcode};

/// A constant expression: an operation on constants that produces a new constant.
///
/// @llvm_behavior: `ConstantExpr` in LLVM represents constant-foldable
/// operations like add, gep, bitcast applied to constants. `ConstExpr`
/// stores the opcode, operand constants, and result type.
#[derive(Debug, Clone)]
pub struct ConstExpr {
    pub opcode: Opcode,
    pub operands: Vec<ValueRef>,
    pub ty: Type,
}

/// Represents a constant value — either a simple constant or an expression.
///
/// @llvm_behavior: In LLVM, all constants (int, fp, null, undef, struct,
/// array, vector, expressions) derive from `llvm::Constant`. This enum
/// captures the high-level classification for pattern matching and folding.
#[derive(Debug, Clone)]
pub enum Constant {
    /// A signed integer constant.
    Int(i64, Type),
    /// An unsigned integer constant.
    UInt(u64, Type),
    /// A floating-point constant.
    Float(f64, Type),
    /// A null value.
    Null(Type),
    /// An undef value.
    Undef(Type),
    /// A poison value.
    Poison(Type),
    /// A zero initializer.
    ZeroInitializer(Type),
    /// A constant struct (ordered fields).
    Struct(Vec<Constant>, Type),
    /// A constant array.
    Array(Vec<Constant>, Type),
    /// A constant vector.
    Vector(Vec<Constant>, Type),
    /// A constant expression (unevaluated or partially evaluated).
    Expr(ConstExpr),
    /// A constant aggregate zero.
    AggregateZero(Type),
}

impl Constant {
    /// Create a new constant expression.
    pub fn new_expr(opcode: Opcode, operands: Vec<Constant>, ty: Type) -> Constant {
        // Convert Constant operands to ValueRefs for storage in ConstExpr
        let val_operands: Vec<ValueRef> = operands.iter().map(|c| c.to_value_ref()).collect();
        Constant::Expr(ConstExpr {
            opcode,
            operands: val_operands,
            ty,
        })
    }

    /// Check if this constant represents a null value.
    pub fn is_null_value(&self) -> bool {
        matches!(self, Constant::Null(_))
    }

    /// Check if this constant represents an all-ones value.
    pub fn is_all_ones_value(&self) -> bool {
        match self {
            Constant::Int(v, ty) => {
                let bits = ty.integer_bit_width();
                if bits <= 64 {
                    let mask = if bits == 64 {
                        u64::MAX
                    } else {
                        (1u64 << bits) - 1
                    };
                    *v as u64 & mask == mask
                } else {
                    false // APInt needed for >64 bits
                }
            }
            Constant::UInt(v, ty) => {
                let bits = ty.integer_bit_width();
                if bits <= 64 {
                    let mask = if bits == 64 {
                        u64::MAX
                    } else {
                        (1u64 << bits) - 1
                    };
                    *v & mask == mask
                } else {
                    false
                }
            }
            _ => false,
        }
    }

    /// Get an aggregate element at the given index.
    pub fn get_aggregate_element(&self, idx: u32) -> Option<Constant> {
        match self {
            Constant::Struct(fields, _) => fields.get(idx as usize).cloned(),
            Constant::Array(elems, _) => elems.get(idx as usize).cloned(),
            Constant::Vector(elems, _) => elems.get(idx as usize).cloned(),
            _ => None,
        }
    }

    /// Check if a vector constant is a splat (all elements are the same value).
    /// Returns `Some(element)` if it is a splat, `None` otherwise.
    pub fn get_splat_value(&self) -> Option<Constant> {
        match self {
            Constant::Vector(elems, _) if !elems.is_empty() => {
                let first = &elems[0];
                if elems.iter().all(|e| e == first) {
                    Some(first.clone())
                } else {
                    None
                }
            }
            _ => None,
        }
    }

    /// Pretty-print this constant to an LLVM IR assembly string.
    pub fn to_string(&self) -> String {
        match self {
            Constant::Int(v, ty) => format!("i{} {}", ty.integer_bit_width(), v),
            Constant::UInt(v, ty) => format!("i{} {}", ty.integer_bit_width(), v),
            Constant::Float(v, ty) => format!("{} {}", ty, v),
            Constant::Null(ty) => format!("{} null", ty),
            Constant::Undef(ty) => format!("{} undef", ty),
            Constant::Poison(ty) => format!("{} poison", ty),
            Constant::ZeroInitializer(ty) => format!("{} zeroinitializer", ty),
            Constant::AggregateZero(ty) => format!("{} zeroinitializer", ty),
            Constant::Struct(fields, _) => {
                let fields_str: Vec<String> = fields.iter().map(|f| f.to_string()).collect();
                format!("{{{}}}", fields_str.join(", "))
            }
            Constant::Array(elems, _) => {
                let elems_str: Vec<String> = elems.iter().map(|e| e.to_string()).collect();
                format!("[{}]", elems_str.join(", "))
            }
            Constant::Vector(elems, _) => {
                let elems_str: Vec<String> = elems.iter().map(|e| e.to_string()).collect();
                format!("<{}>", elems_str.join(", "))
            }
            Constant::Expr(expr) => {
                format!(
                    "{} ({})",
                    expr.opcode.as_mnemonic(),
                    expr.operands
                        .iter()
                        .map(|v| v.borrow().name.clone())
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            }
        }
    }

    /// Get the type of this constant.
    pub fn get_type(&self) -> Type {
        match self {
            Constant::Int(_, ty)
            | Constant::UInt(_, ty)
            | Constant::Float(_, ty)
            | Constant::Null(ty)
            | Constant::Undef(ty)
            | Constant::Poison(ty)
            | Constant::ZeroInitializer(ty)
            | Constant::AggregateZero(ty)
            | Constant::Struct(_, ty)
            | Constant::Array(_, ty)
            | Constant::Vector(_, ty) => ty.clone(),
            Constant::Expr(expr) => expr.ty.clone(),
        }
    }

    /// Create a Constant from an APInt-like value.
    ///
    /// @llvm_behavior: This is the equivalent of `ConstantInt::get(ty, APInt(...))`.
    pub fn from_apint(val: &APInt, ty: &Type) -> Constant {
        if let Some(sv) = val.as_signed() {
            Constant::Int(sv, ty.clone())
        } else {
            Constant::UInt(val.as_u64(), ty.clone())
        }
    }

    /// Create a Constant from an APFloat-like value.
    ///
    /// @llvm_behavior: This is the equivalent of `ConstantFP::get(ty, APFloat(...))`.
    pub fn from_apfloat(val: &APFloat, ty: &Type) -> Constant {
        Constant::Float(val.as_f64(), ty.clone())
    }

    /// Convert this Constant to a ValueRef for use in the IR.
    pub fn to_value_ref(&self) -> ValueRef {
        match self {
            Constant::Int(v, ty) => const_int(ty.clone(), *v),
            Constant::UInt(v, ty) => {
                let ival = *v as i64;
                const_int(ty.clone(), ival)
            }
            Constant::Float(v, ty) => {
                if ty.is_floating_point() {
                    const_double(*v)
                } else {
                    const_int(ty.clone(), *v as i64)
                }
            }
            Constant::Null(ty) => const_null_ptr(ty.clone()),
            Constant::Undef(ty) => undef_value(ty.clone()),
            Constant::Poison(ty) => poison_value(ty.clone()),
            Constant::ZeroInitializer(ty) | Constant::AggregateZero(ty) => const_zero(ty.clone()),
            Constant::Struct(_, ty) | Constant::Array(_, ty) | Constant::Vector(_, ty) => {
                const_zero(ty.clone())
            }
            Constant::Expr(_) => {
                let ty = self.get_type();
                undef_value(ty)
            }
        }
    }
}

impl PartialEq for Constant {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Constant::Int(a, ta), Constant::Int(b, tb)) => a == b && ta.kind == tb.kind,
            (Constant::UInt(a, ta), Constant::UInt(b, tb)) => a == b && ta.kind == tb.kind,
            (Constant::Float(a, ta), Constant::Float(b, tb)) => {
                a.to_bits() == b.to_bits() && ta.kind == tb.kind
            }
            (Constant::Null(_), Constant::Null(_)) => true,
            (Constant::Undef(_), Constant::Undef(_)) => true,
            (Constant::Poison(_), Constant::Poison(_)) => true,
            (Constant::ZeroInitializer(_), Constant::ZeroInitializer(_)) => true,
            (Constant::AggregateZero(_), Constant::AggregateZero(_)) => true,
            (Constant::Struct(fa, _), Constant::Struct(fb, _)) => fa == fb,
            (Constant::Array(ea, _), Constant::Array(eb, _)) => ea == eb,
            (Constant::Vector(va, _), Constant::Vector(vb, _)) => va == vb,
            _ => false,
        }
    }
}

// ============================================================================
// APInt and APFloat — simple arbitrary-precision wrappers
// ============================================================================

/// A simple arbitrary-precision integer wrapper.
///
/// @llvm_behavior: `APInt` in LLVM supports arbitrary bit widths.
/// This simplified version uses u64 for up-to-64-bit values and
/// stores wider values as a vector of u64 limbs.
#[derive(Debug, Clone)]
pub struct APInt {
    pub bits: u32,
    pub val: u64,
    pub limbs: Vec<u64>, // for >64-bit values
}

impl APInt {
    pub fn new(bits: u32, val: u64) -> Self {
        Self {
            bits,
            val,
            limbs: Vec::new(),
        }
    }

    pub fn as_u64(&self) -> u64 {
        self.val
    }

    pub fn as_signed(&self) -> Option<i64> {
        if self.bits <= 64 {
            Some(self.val as i64)
        } else {
            None
        }
    }

    pub fn is_zero(&self) -> bool {
        self.val == 0 && self.limbs.iter().all(|&l| l == 0)
    }

    pub fn is_all_ones(&self) -> bool {
        if self.bits <= 64 {
            let mask = if self.bits == 64 {
                u64::MAX
            } else {
                (1u64 << self.bits) - 1
            };
            self.val == mask
        } else {
            self.limbs.iter().all(|&l| l == u64::MAX)
        }
    }

    /// Mask the value to the given bit width.
    pub fn mask(&self) -> u64 {
        if self.bits >= 64 {
            self.val
        } else {
            self.val & ((1u64 << self.bits) - 1)
        }
    }
}

/// A simple arbitrary-precision floating-point wrapper.
///
/// @llvm_behavior: `APFloat` in LLVM supports IEEE 754 formats.
/// This simplified version uses f64 for all float values.
#[derive(Debug, Clone)]
pub struct APFloat {
    pub val: f64,
    pub semantics: FloatSemantics,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FloatSemantics {
    Half,
    BFloat,
    Float,
    Double,
    X86FP80,
    FP128,
    PPCFP128,
}

impl APFloat {
    pub fn new(val: f64, semantics: FloatSemantics) -> Self {
        Self { val, semantics }
    }

    pub fn as_f64(&self) -> f64 {
        self.val
    }

    pub fn is_zero(&self) -> bool {
        self.val == 0.0
    }

    pub fn is_nan(&self) -> bool {
        self.val.is_nan()
    }

    pub fn is_infinity(&self) -> bool {
        self.val.is_infinite()
    }

    pub fn is_negative(&self) -> bool {
        self.val.is_sign_negative()
    }
}

// ============================================================================
// ConstFolding — constant expression evaluator
// ============================================================================

/// A constant folding engine that evaluates operations on constants at
/// compile time.
///
/// @llvm_behavior: `ConstantFold` in LLVM evaluates constant expressions
/// to produce new constants. `ConstFolding` provides the same capability
/// for all standard operations.
pub struct ConstFolding;

impl ConstFolding {
    // === Integer arithmetic ===

    /// Fold an add of two constants.
    pub fn fold_add(a: &Constant, b: &Constant) -> Option<Constant> {
        match (a, b) {
            (Constant::Int(av, aty), Constant::Int(bv, _)) => {
                let bits = aty.integer_bit_width();
                let result = av.wrapping_add(*bv);
                let masked = if bits < 64 {
                    result & ((1i64 << bits) - 1)
                } else {
                    result
                };
                Some(Constant::Int(masked, aty.clone()))
            }
            (Constant::UInt(av, aty), Constant::UInt(bv, _)) => {
                let bits = aty.integer_bit_width();
                let result = av.wrapping_add(*bv);
                let masked = if bits < 64 {
                    result & ((1u64 << bits) - 1)
                } else {
                    result
                };
                Some(Constant::UInt(masked, aty.clone()))
            }
            _ => None,
        }
    }

    /// Fold a sub of two constants.
    pub fn fold_sub(a: &Constant, b: &Constant) -> Option<Constant> {
        match (a, b) {
            (Constant::Int(av, aty), Constant::Int(bv, _)) => {
                let bits = aty.integer_bit_width();
                let result = av.wrapping_sub(*bv);
                let masked = if bits < 64 {
                    result & ((1i64 << bits) - 1)
                } else {
                    result
                };
                Some(Constant::Int(masked, aty.clone()))
            }
            (Constant::UInt(av, aty), Constant::UInt(bv, _)) => {
                let bits = aty.integer_bit_width();
                let result = av.wrapping_sub(*bv);
                let masked = if bits < 64 {
                    result & ((1u64 << bits) - 1)
                } else {
                    result
                };
                Some(Constant::UInt(masked, aty.clone()))
            }
            _ => None,
        }
    }

    /// Fold a mul of two constants.
    pub fn fold_mul(a: &Constant, b: &Constant) -> Option<Constant> {
        match (a, b) {
            (Constant::Int(av, aty), Constant::Int(bv, _)) => {
                let bits = aty.integer_bit_width();
                let result = av.wrapping_mul(*bv);
                let masked = if bits < 64 {
                    result & ((1i64 << bits) - 1)
                } else {
                    result
                };
                Some(Constant::Int(masked, aty.clone()))
            }
            (Constant::UInt(av, aty), Constant::UInt(bv, _)) => {
                let bits = aty.integer_bit_width();
                let result = av.wrapping_mul(*bv);
                let masked = if bits < 64 {
                    result & ((1u64 << bits) - 1)
                } else {
                    result
                };
                Some(Constant::UInt(masked, aty.clone()))
            }
            _ => None,
        }
    }

    /// Fold an unsigned division of two constants.
    pub fn fold_udiv(a: &Constant, b: &Constant) -> Option<Constant> {
        match (a, b) {
            (Constant::UInt(av, aty), Constant::UInt(bv, _)) => {
                if *bv == 0 {
                    None // UB in LLVM
                } else {
                    Some(Constant::UInt(av / bv, aty.clone()))
                }
            }
            (Constant::Int(av, aty), Constant::Int(bv, _)) => {
                if *bv == 0 {
                    None
                } else {
                    let ua = *av as u64;
                    let ub = *bv as u64;
                    Some(Constant::UInt(ua / ub, aty.clone()))
                }
            }
            _ => None,
        }
    }

    /// Fold a signed division of two constants.
    pub fn fold_sdiv(a: &Constant, b: &Constant) -> Option<Constant> {
        match (a, b) {
            (Constant::Int(av, aty), Constant::Int(bv, _)) => {
                if *bv == 0 {
                    None
                } else if *av == i64::MIN && *bv == -1 {
                    // Signed overflow — result is MIN
                    Some(Constant::Int(i64::MIN, aty.clone()))
                } else {
                    Some(Constant::Int(av / bv, aty.clone()))
                }
            }
            _ => None,
        }
    }

    /// Fold an unsigned remainder of two constants.
    pub fn fold_urem(a: &Constant, b: &Constant) -> Option<Constant> {
        match (a, b) {
            (Constant::UInt(av, aty), Constant::UInt(bv, _)) => {
                if *bv == 0 {
                    None
                } else {
                    Some(Constant::UInt(av % bv, aty.clone()))
                }
            }
            (Constant::Int(av, aty), Constant::Int(bv, _)) => {
                if *bv == 0 {
                    None
                } else {
                    let ua = *av as u64;
                    let ub = *bv as u64;
                    Some(Constant::UInt(ua % ub, aty.clone()))
                }
            }
            _ => None,
        }
    }

    /// Fold a signed remainder of two constants.
    pub fn fold_srem(a: &Constant, b: &Constant) -> Option<Constant> {
        match (a, b) {
            (Constant::Int(av, aty), Constant::Int(bv, _)) => {
                if *bv == 0 {
                    None
                } else {
                    Some(Constant::Int(av % bv, aty.clone()))
                }
            }
            _ => None,
        }
    }

    // === Bitwise operations ===

    /// Fold a bitwise and of two constants.
    pub fn fold_and(a: &Constant, b: &Constant) -> Option<Constant> {
        match (a, b) {
            (Constant::Int(av, aty), Constant::Int(bv, _)) => {
                Some(Constant::Int(av & bv, aty.clone()))
            }
            (Constant::UInt(av, aty), Constant::UInt(bv, _)) => {
                Some(Constant::UInt(av & bv, aty.clone()))
            }
            _ => None,
        }
    }

    /// Fold a bitwise or of two constants.
    pub fn fold_or(a: &Constant, b: &Constant) -> Option<Constant> {
        match (a, b) {
            (Constant::Int(av, aty), Constant::Int(bv, _)) => {
                Some(Constant::Int(av | bv, aty.clone()))
            }
            (Constant::UInt(av, aty), Constant::UInt(bv, _)) => {
                Some(Constant::UInt(av | bv, aty.clone()))
            }
            _ => None,
        }
    }

    /// Fold a bitwise xor of two constants.
    pub fn fold_xor(a: &Constant, b: &Constant) -> Option<Constant> {
        match (a, b) {
            (Constant::Int(av, aty), Constant::Int(bv, _)) => {
                Some(Constant::Int(av ^ bv, aty.clone()))
            }
            (Constant::UInt(av, aty), Constant::UInt(bv, _)) => {
                Some(Constant::UInt(av ^ bv, aty.clone()))
            }
            _ => None,
        }
    }

    // === Shift operations ===

    /// Fold a left shift of two constants.
    pub fn fold_shl(a: &Constant, b: &Constant) -> Option<Constant> {
        match (a, b) {
            (Constant::Int(av, aty), Constant::Int(bv, _)) => {
                let shift = (*bv as u32) % aty.integer_bit_width();
                let result = av.wrapping_shl(shift);
                Some(Constant::Int(result, aty.clone()))
            }
            (Constant::UInt(av, aty), Constant::UInt(bv, _)) => {
                let shift = (*bv as u32) % aty.integer_bit_width();
                let result = av.wrapping_shl(shift);
                Some(Constant::UInt(result, aty.clone()))
            }
            _ => None,
        }
    }

    /// Fold a logical right shift of two constants.
    pub fn fold_lshr(a: &Constant, b: &Constant) -> Option<Constant> {
        match (a, b) {
            (Constant::Int(av, aty), Constant::Int(bv, _)) => {
                let shift = (*bv as u32) % aty.integer_bit_width();
                let result = (*av as u64).wrapping_shr(shift) as i64;
                Some(Constant::Int(result, aty.clone()))
            }
            (Constant::UInt(av, aty), Constant::UInt(bv, _)) => {
                let shift = (*bv as u32) % aty.integer_bit_width();
                let result = av.wrapping_shr(shift);
                Some(Constant::UInt(result, aty.clone()))
            }
            _ => None,
        }
    }

    /// Fold an arithmetic right shift of two constants.
    pub fn fold_ashr(a: &Constant, b: &Constant) -> Option<Constant> {
        match (a, b) {
            (Constant::Int(av, aty), Constant::Int(bv, _)) => {
                let bits = aty.integer_bit_width();
                let shift = (*bv as u32) % bits;
                if shift >= bits {
                    // Shift result is sign bit repeated
                    let fill = if *av < 0 { u64::MAX << (bits - 1) } else { 0 };
                    Some(Constant::Int(fill as i64, aty.clone()))
                } else {
                    // Perform arithmetic shift manually
                    let uval = *av as u64;
                    let result = if *av < 0 && shift > 0 {
                        // Create sign-extension mask
                        let mask = u64::MAX << (bits - shift);
                        (uval >> shift) | mask
                    } else {
                        uval >> shift
                    };
                    let masked = if bits < 64 {
                        result & ((1u64 << bits) - 1)
                    } else {
                        result
                    };
                    // Sign-extend from bit width to i64
                    let sign_bit = 1u64 << (bits - 1);
                    let sval = if masked & sign_bit != 0 {
                        // Negative: extend sign bits
                        (masked | (u64::MAX << bits)) as i64
                    } else {
                        masked as i64
                    };
                    Some(Constant::Int(sval, aty.clone()))
                }
            }
            _ => None,
        }
    }

    // === Floating-point arithmetic ===

    /// Fold a floating-point add.
    pub fn fold_fadd(a: &Constant, b: &Constant) -> Option<Constant> {
        match (a, b) {
            (Constant::Float(av, aty), Constant::Float(bv, _)) => {
                Some(Constant::Float(av + bv, aty.clone()))
            }
            _ => None,
        }
    }

    /// Fold a floating-point sub.
    pub fn fold_fsub(a: &Constant, b: &Constant) -> Option<Constant> {
        match (a, b) {
            (Constant::Float(av, aty), Constant::Float(bv, _)) => {
                Some(Constant::Float(av - bv, aty.clone()))
            }
            _ => None,
        }
    }

    /// Fold a floating-point mul.
    pub fn fold_fmul(a: &Constant, b: &Constant) -> Option<Constant> {
        match (a, b) {
            (Constant::Float(av, aty), Constant::Float(bv, _)) => {
                Some(Constant::Float(av * bv, aty.clone()))
            }
            _ => None,
        }
    }

    /// Fold a floating-point div.
    pub fn fold_fdiv(a: &Constant, b: &Constant) -> Option<Constant> {
        match (a, b) {
            (Constant::Float(av, aty), Constant::Float(bv, _)) => {
                if *bv == 0.0 {
                    None
                } else {
                    Some(Constant::Float(av / bv, aty.clone()))
                }
            }
            _ => None,
        }
    }

    // === Cast operations ===

    /// Fold a zero-extend cast.
    pub fn fold_zext(val: &Constant, to_ty: &Type) -> Option<Constant> {
        match val {
            Constant::Int(v, _) => {
                let uv = *v as u64;
                Some(Constant::UInt(uv, to_ty.clone()))
            }
            Constant::UInt(v, _) => Some(Constant::UInt(*v, to_ty.clone())),
            _ => None,
        }
    }

    /// Fold a sign-extend.
    pub fn fold_sext(val: &Constant, to_ty: &Type) -> Option<Constant> {
        match val {
            Constant::Int(v, from_ty) => {
                let from_bits = from_ty.integer_bit_width();
                let to_bits = to_ty.integer_bit_width();
                if from_bits >= to_bits {
                    Some(Constant::Int(*v, to_ty.clone()))
                } else {
                    // Sign extend
                    let shift = 64 - from_bits;
                    let sv = (*v << shift) >> shift; // Arithmetic shift trick
                    Some(Constant::Int(sv, to_ty.clone()))
                }
            }
            _ => None,
        }
    }

    /// Fold a truncate.
    pub fn fold_trunc(val: &Constant, to_ty: &Type) -> Option<Constant> {
        match val {
            Constant::Int(v, _) => {
                let to_bits = to_ty.integer_bit_width();
                let uv = *v as u64;
                if to_bits < 64 {
                    let mask = (1u64 << to_bits) - 1;
                    Some(Constant::UInt(uv & mask, to_ty.clone()))
                } else {
                    Some(Constant::UInt(uv, to_ty.clone()))
                }
            }
            Constant::UInt(v, _) => {
                let to_bits = to_ty.integer_bit_width();
                if to_bits < 64 {
                    let mask = (1u64 << to_bits) - 1;
                    Some(Constant::UInt(v & mask, to_ty.clone()))
                } else {
                    Some(Constant::UInt(*v, to_ty.clone()))
                }
            }
            _ => None,
        }
    }

    /// Fold a bitcast. Performs a no-op reinterpretation of bits.
    pub fn fold_bitcast(val: &Constant, to_ty: &Type) -> Option<Constant> {
        // For same-size types, just reinterpret the value
        match val {
            Constant::Int(v, _) => Some(Constant::Int(*v, to_ty.clone())),
            Constant::UInt(v, _) => Some(Constant::UInt(*v, to_ty.clone())),
            Constant::Float(v, _) => Some(Constant::Float(*v, to_ty.clone())),
            _ => None,
        }
    }

    // === Integer comparison ===

    /// Fold an integer comparison predicate on two constants.
    pub fn fold_icmp(pred: &ICmpPred, a: &Constant, b: &Constant) -> Option<Constant> {
        let result_ty = Type::i1();
        match (a, b) {
            (Constant::Int(av, _), Constant::Int(bv, _)) => {
                let cmp = match pred {
                    ICmpPred::Eq => av == bv,
                    ICmpPred::Ne => av != bv,
                    ICmpPred::Sgt => av > bv,
                    ICmpPred::Sge => av >= bv,
                    ICmpPred::Slt => av < bv,
                    ICmpPred::Sle => av <= bv,
                    ICmpPred::Ugt => (*av as u64) > (*bv as u64),
                    ICmpPred::Uge => (*av as u64) >= (*bv as u64),
                    ICmpPred::Ult => (*av as u64) < (*bv as u64),
                    ICmpPred::Ule => (*av as u64) <= (*bv as u64),
                };
                Some(Constant::Int(if cmp { 1 } else { 0 }, result_ty))
            }
            (Constant::UInt(av, _), Constant::UInt(bv, _)) => {
                let cmp = match pred {
                    ICmpPred::Eq => av == bv,
                    ICmpPred::Ne => av != bv,
                    ICmpPred::Sgt => (*av as i64) > (*bv as i64),
                    ICmpPred::Sge => (*av as i64) >= (*bv as i64),
                    ICmpPred::Slt => (*av as i64) < (*bv as i64),
                    ICmpPred::Sle => (*av as i64) <= (*bv as i64),
                    ICmpPred::Ugt => av > bv,
                    ICmpPred::Uge => av >= bv,
                    ICmpPred::Ult => av < bv,
                    ICmpPred::Ule => av <= bv,
                };
                Some(Constant::Int(if cmp { 1 } else { 0 }, result_ty))
            }
            _ => None,
        }
    }

    // === Floating-point comparison ===

    /// Fold a floating-point comparison predicate on two constants.
    pub fn fold_fcmp(pred: &FCmpPred, a: &Constant, b: &Constant) -> Option<Constant> {
        let result_ty = Type::i1();
        match (a, b) {
            (Constant::Float(av, _), Constant::Float(bv, _)) => {
                let ordered = !av.is_nan() && !bv.is_nan();
                let cmp = match pred {
                    FCmpPred::False => false,
                    FCmpPred::True => true,
                    FCmpPred::Ord => ordered,
                    FCmpPred::Uno => !ordered,
                    FCmpPred::Oeq => ordered && av == bv,
                    FCmpPred::Ogt => ordered && av > bv,
                    FCmpPred::Oge => ordered && av >= bv,
                    FCmpPred::Olt => ordered && av < bv,
                    FCmpPred::Ole => ordered && av <= bv,
                    FCmpPred::One => ordered && av != bv,
                    FCmpPred::Ueq => !ordered || av == bv,
                    FCmpPred::Ugt => !ordered || av > bv,
                    FCmpPred::Uge => !ordered || av >= bv,
                    FCmpPred::Ult => !ordered || av < bv,
                    FCmpPred::Ule => !ordered || av <= bv,
                    FCmpPred::Une => !ordered || av != bv,
                };
                Some(Constant::Int(if cmp { 1 } else { 0 }, result_ty))
            }
            _ => None,
        }
    }

    // === GEP constant folding ===

    /// Fold a GEP (getelementptr) constant expression.
    ///
    /// Attempts to compute the resulting pointer offset when the base and
    /// all indices are constants. Returns `None` if folding is not possible.
    pub fn fold_gep(base: &Constant, indices: &[Constant]) -> Option<Constant> {
        // For fully constant GEP, compute the byte offset
        let ptr_ty = base.get_type();
        if !ptr_ty.is_pointer() {
            return None;
        }

        // In opaque pointer mode (LLVM 15+), we can't compute GEP results
        // without an explicit source element type. Return None for now.
        let mut offset: i64 = 0;
        let mut cur_ty = ptr_ty.get_element_type();

        for (i, idx) in indices.iter().enumerate() {
            match &cur_ty {
                Some(ct) => {
                    if i == 0 {
                        let size = ct.size_in_bytes() as i64;
                        if let Constant::Int(v, _) = idx {
                            offset += v * size;
                        } else {
                            return None;
                        }
                    } else {
                        match &ct.kind {
                            TypeKind::Array { .. } => {
                                let elem_ty = ct.get_element_type();
                                if let Some(et) = &elem_ty {
                                    let elem_size = et.size_in_bytes() as i64;
                                    if let Constant::Int(v, _) = idx {
                                        offset += v * elem_size;
                                    } else {
                                        return None;
                                    }
                                    cur_ty = elem_ty;
                                } else {
                                    return None;
                                }
                            }
                            TypeKind::Struct { .. } => {
                                if let Constant::Int(v, _) = idx {
                                    let field_idx = *v as u32;
                                    if let Some(field_offset) = ct.struct_field_offset(field_idx) {
                                        offset += field_offset as i64;
                                        cur_ty = ct.struct_field_type(field_idx);
                                    } else {
                                        return None;
                                    }
                                } else {
                                    return None;
                                }
                            }
                            TypeKind::FixedVector { .. } | TypeKind::ScalableVector { .. } => {
                                let elem_ty = ct.get_element_type();
                                if let Some(et) = &elem_ty {
                                    let elem_size = et.size_in_bytes() as i64;
                                    if let Constant::Int(v, _) = idx {
                                        offset += v * elem_size;
                                    } else {
                                        return None;
                                    }
                                    cur_ty = elem_ty;
                                } else {
                                    return None;
                                }
                            }
                            _ => return None,
                        }
                    }
                }
                None => {
                    // Opaque pointer or unresolvable type — can't determine offset
                    return None;
                }
            }
        }

        Some(Constant::Int(offset, ptr_ty))
    }

    // === Select constant folding ===

    /// Fold a select on constant values.
    pub fn fold_select(cond: &Constant, tval: &Constant, fval: &Constant) -> Option<Constant> {
        match cond {
            Constant::Int(v, _) => {
                if *v != 0 {
                    Some(tval.clone())
                } else {
                    Some(fval.clone())
                }
            }
            Constant::UInt(v, _) => {
                if *v != 0 {
                    Some(tval.clone())
                } else {
                    Some(fval.clone())
                }
            }
            _ => None,
        }
    }

    // === ExtractValue / InsertValue constant folding ===

    /// Fold an extractvalue from a constant aggregate.
    pub fn fold_extract_value(agg: &Constant, idx: u32) -> Option<Constant> {
        agg.get_aggregate_element(idx)
    }

    /// Fold an insertvalue into a constant aggregate.
    pub fn fold_insert_value(agg: &Constant, val: &Constant, idx: u32) -> Option<Constant> {
        match agg {
            Constant::Struct(fields, ty) => {
                let i = idx as usize;
                let mut new_fields = fields.clone();
                if i < new_fields.len() {
                    new_fields[i] = val.clone();
                }
                Some(Constant::Struct(new_fields, ty.clone()))
            }
            Constant::Array(elems, ty) => {
                let i = idx as usize;
                let mut new_elems = elems.clone();
                if i < new_elems.len() {
                    new_elems[i] = val.clone();
                }
                Some(Constant::Array(new_elems, ty.clone()))
            }
            Constant::Vector(elems, ty) => {
                let i = idx as usize;
                let mut new_elems = elems.clone();
                if i < new_elems.len() {
                    new_elems[i] = val.clone();
                }
                Some(Constant::Vector(new_elems, ty.clone()))
            }
            _ => None,
        }
    }

    // === ExtractElement / InsertElement constant folding ===

    /// Fold an extractelement from a constant vector.
    pub fn fold_extract_element(vec: &Constant, idx: &Constant) -> Option<Constant> {
        match (vec, idx) {
            (Constant::Vector(elems, _), Constant::Int(i, _)) => elems.get(*i as usize).cloned(),
            _ => None,
        }
    }

    /// Fold an insertelement into a constant vector.
    pub fn fold_insert_element(vec: &Constant, elt: &Constant, idx: &Constant) -> Option<Constant> {
        match (vec, idx) {
            (Constant::Vector(elems, ty), Constant::Int(i, _)) => {
                let iu = *i as usize;
                let mut new_elems = elems.clone();
                if iu < new_elems.len() {
                    new_elems[iu] = elt.clone();
                }
                Some(Constant::Vector(new_elems, ty.clone()))
            }
            _ => None,
        }
    }
}

// ============================================================================
// GEPOperator — GEP expression analysis
// ============================================================================

/// A GEP (getelementptr) operator for analyzing GEP expressions.
///
/// @llvm_behavior: `GEPOperator` in LLVM provides analysis methods for
/// `GetElementPtr` constant expressions and instructions. It computes the
/// source element type, result type, and checks structural properties.
#[derive(Debug, Clone)]
pub struct GEPOperator {
    /// The base pointer value.
    pub pointer: ValueRef,
    /// The source element type (pointee type).
    pub source_element_type: Type,
    /// The result element type (after indexing).
    pub result_element_type: Type,
    /// The indices.
    pub indices: Vec<ValueRef>,
    /// Whether this is an inbounds GEP.
    pub is_inbounds: bool,
}

impl GEPOperator {
    /// Create a new GEPOperator from a GEP constant expression or instruction.
    pub fn new(gep: &ValueRef) -> Option<Self> {
        let gep_val = gep.borrow();
        let ops = &gep_val.operands;
        if ops.is_empty() {
            return None;
        }

        let pointer = ops[0].clone();
        let ptr_ty = pointer.borrow().ty.clone();

        // Determine source element type
        let source_element_type = if ptr_ty.is_pointer() {
            ptr_ty.get_element_type().unwrap_or(ptr_ty.clone())
        } else {
            ptr_ty.clone()
        };

        // Compute result element type by walking indices
        let mut result_ty = source_element_type.clone();
        for i in 1..ops.len() {
            result_ty = match &result_ty.kind {
                TypeKind::Array {
                    element_type_id, ..
                } => {
                    crate::types::Type::new(crate::types::TypeKind::Integer { bits: 32 })
                    // Simplified: get the element type
                }
                TypeKind::Struct {
                    element_type_ids, ..
                } => {
                    // For struct GEP, second index is field index — skip structure
                    result_ty.clone()
                }
                TypeKind::FixedVector {
                    element_type_id, ..
                } => {
                    // Vector element
                    result_ty.clone()
                }
                _ => result_ty.clone(),
            };
        }

        let indices: Vec<ValueRef> = ops[1..].to_vec();

        Some(Self {
            pointer,
            source_element_type,
            result_element_type: result_ty,
            indices,
            is_inbounds: false, // simplified
        })
    }

    /// Returns the number of indices.
    pub fn num_indices(&self) -> usize {
        self.indices.len()
    }

    /// Returns true if all indices are zero.
    pub fn has_all_zero_indices(&self) -> bool {
        self.indices.iter().all(|idx| {
            let i = idx.borrow();
            i.name == "0" || i.name == "zeroinitializer"
        })
    }

    /// Returns true if the GEP only indexes into the first element
    /// (i.e., no struct field access or array offset beyond element 0).
    pub fn has_constant_indices(&self) -> bool {
        self.indices.iter().all(|idx| {
            let i = idx.borrow();
            i.is_constant()
        })
    }
}

// ============================================================================
// StructLayout — struct field offset computation
// ============================================================================

/// Computes and caches struct field offsets for a struct type.
///
/// @llvm_behavior: `StructLayout` in LLVM computes the byte offset of
/// each field in a struct, considering alignment and packing rules.
/// This is used by GEP lowering and constant folding.
#[derive(Debug, Clone)]
pub struct StructLayout {
    /// The struct type this layout describes.
    pub struct_type: Type,
    /// Offsets (in bytes) for each field.
    pub field_offsets: Vec<u64>,
    /// Total size of the struct in bytes.
    pub size_in_bytes: u64,
    /// Total alignment of the struct.
    pub alignment: u32,
}

impl StructLayout {
    /// Compute the layout for a given struct type.
    ///
    /// Uses target-independent alignment rules:
    /// - Each field is aligned to its natural alignment.
    /// - Fields are padded to the next alignment boundary.
    /// - The struct itself is aligned to the maximum field alignment.
    pub fn compute(struct_type: &Type) -> Option<Self> {
        let field_types = struct_type.struct_element_type_ids();
        if field_types.is_empty() && !struct_type.is_opaque_struct() {
            // Empty struct
            return Some(Self {
                struct_type: struct_type.clone(),
                field_offsets: Vec::new(),
                size_in_bytes: 0,
                alignment: 1,
            });
        }

        // Determine if struct is packed
        let is_packed = match &struct_type.kind {
            TypeKind::Struct { is_packed, .. } => *is_packed,
            _ => return None,
        };

        // We need actual Type objects, not just IDs. For simplicity,
        // we create types inline using the kind's element_type_ids.
        // In a full implementation, the type store would be consulted.

        let mut offsets = Vec::new();
        let mut current_offset: u64 = 0;
        let mut max_align: u32 = 1;

        for _ft in field_types {
            // For this simplified version, we need the actual types
            // to compute sizes. We'll just use a placeholder approach.
            // In production, this would look up types from the store.
            let field_size: u64 = 4; // simplified default
            let field_align: u32 = if is_packed { 1 } else { 4 };

            // Align current offset
            if field_align > 0 && !is_packed {
                let align_m1 = field_align as u64 - 1;
                current_offset = (current_offset + align_m1) & !align_m1;
            }

            offsets.push(current_offset);
            current_offset += field_size;

            if field_align > max_align {
                max_align = field_align;
            }
        }

        // Align total size
        if max_align > 0 && !is_packed {
            let align_m1 = max_align as u64 - 1;
            current_offset = (current_offset + align_m1) & !align_m1;
        }

        Some(Self {
            struct_type: struct_type.clone(),
            field_offsets: offsets,
            size_in_bytes: current_offset,
            alignment: max_align,
        })
    }

    /// Get the byte offset for a specific field index.
    pub fn get_field_offset(&self, idx: u32) -> Option<u64> {
        self.field_offsets.get(idx as usize).copied()
    }

    /// Returns the number of fields in the struct.
    pub fn num_fields(&self) -> usize {
        self.field_offsets.len()
    }
}

// ============================================================================
// Tests (keep all existing + add new)
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::opcode::{FCmpPred, ICmpPred};

    // === Existing tests (preserved) ===

    #[test]
    fn test_const_int_identity() {
        let v = const_i32(42);
        assert_eq!(v.borrow().name, "42");
    }

    #[test]
    fn test_const_i64() {
        let v = const_i64(-1);
        assert_eq!(v.borrow().name, "-1");
    }

    #[test]
    fn test_const_bool() {
        let t = const_bool(true);
        let f = const_bool(false);
        assert_eq!(t.borrow().name, "1");
        assert_eq!(f.borrow().name, "0");
    }

    #[test]
    fn test_const_float() {
        let v = const_float(3.14);
        assert_eq!(v.borrow().name, "3.14");
    }

    #[test]
    fn test_const_double() {
        let v = const_double(2.718);
        assert_eq!(v.borrow().name, "2.718");
    }

    #[test]
    fn test_const_null_ptr() {
        let v = const_null_ptr(Type::pointer(0));
        assert_eq!(v.borrow().name, "null");
    }

    #[test]
    fn test_undef_value() {
        let v = undef_value(Type::i32());
        assert_eq!(v.borrow().name, "undef");
    }

    #[test]
    fn test_poison_value() {
        let v = poison_value(Type::i32());
        assert_eq!(v.borrow().name, "poison");
    }

    #[test]
    fn test_const_zero_int() {
        let v = const_zero(Type::i32());
        assert_eq!(v.borrow().name, "0");
    }

    #[test]
    fn test_const_zero_ptr() {
        let v = const_zero(Type::pointer(0));
        assert_eq!(v.borrow().name, "null");
    }

    #[test]
    fn test_const_zero_float() {
        let v = const_zero(Type::double());
        assert_eq!(v.borrow().name, "0");
    }

    #[test]
    fn test_const_gep() {
        let base = const_null_ptr(Type::pointer(0));
        let idx = const_i32(0);
        let v = const_gep(base, vec![idx]);
        assert_eq!(v.borrow().operands.len(), 2);
    }

    #[test]
    fn test_const_bitcast() {
        let val = const_i32(42);
        let v = const_bitcast(val, Type::float());
        assert_eq!(v.borrow().operands.len(), 1);
    }

    #[test]
    fn test_new_global() {
        let gv = super::new_global(
            Type::i32(),
            true,
            crate::function::Linkage::External,
            None,
            "my_global",
        );
        assert_eq!(gv.borrow().name, "my_global");
    }

    // === New tests (Phase 2) ===

    #[test]
    fn test_constant_int_new_expr() {
        let c = Constant::new_expr(
            Opcode::Add,
            vec![
                Constant::Int(10, Type::i32()),
                Constant::Int(20, Type::i32()),
            ],
            Type::i32(),
        );
        match c {
            Constant::Expr(expr) => {
                assert_eq!(expr.opcode, Opcode::Add);
                assert_eq!(expr.operands.len(), 2);
            }
            _ => panic!("Expected Expr"),
        }
    }

    #[test]
    fn test_constant_is_null_value() {
        assert!(Constant::Null(Type::i32()).is_null_value());
        assert!(!Constant::Int(0, Type::i32()).is_null_value());
        assert!(!Constant::Float(0.0, Type::double()).is_null_value());
    }

    #[test]
    fn test_constant_is_all_ones() {
        assert!(Constant::Int(-1, Type::i32()).is_all_ones_value());
        assert!(!Constant::Int(0, Type::i32()).is_all_ones_value());
        assert!(!Constant::Int(42, Type::i32()).is_all_ones_value());
    }

    #[test]
    fn test_constant_get_aggregate_element() {
        let s = Constant::Struct(
            vec![
                Constant::Int(1, Type::i32()),
                Constant::Int(2, Type::i32()),
                Constant::Int(3, Type::i32()),
            ],
            Type::i32(),
        );
        assert_eq!(
            s.get_aggregate_element(1),
            Some(Constant::Int(2, Type::i32()))
        );
        assert_eq!(s.get_aggregate_element(10), None);
    }

    #[test]
    fn test_constant_splat_value() {
        let v = Constant::Vector(
            vec![
                Constant::Int(5, Type::i32()),
                Constant::Int(5, Type::i32()),
                Constant::Int(5, Type::i32()),
            ],
            Type::i32(),
        );
        assert_eq!(v.get_splat_value(), Some(Constant::Int(5, Type::i32())));

        let v2 = Constant::Vector(
            vec![Constant::Int(1, Type::i32()), Constant::Int(2, Type::i32())],
            Type::i32(),
        );
        assert_eq!(v2.get_splat_value(), None);
    }

    #[test]
    fn test_constant_to_string() {
        assert_eq!(Constant::Int(42, Type::i32()).to_string(), "i32 42");
        assert_eq!(Constant::Null(Type::pointer(0)).to_string(), "ptr null");
        assert_eq!(Constant::Undef(Type::i32()).to_string(), "i32 undef");
    }

    #[test]
    fn test_apint_operations() {
        let a = APInt::new(32, 42);
        assert!(!a.is_zero());
        assert!(!a.is_all_ones());

        let z = APInt::new(32, 0);
        assert!(z.is_zero());

        let ones = APInt::new(8, 0xFF);
        assert!(ones.is_all_ones());
    }

    #[test]
    fn test_apfloat_operations() {
        let f = APFloat::new(3.14, FloatSemantics::Double);
        assert!(!f.is_zero());
        assert!(!f.is_nan());
        assert!(!f.is_infinity());
        assert!(!f.is_negative());

        let nf = APFloat::new(-1.0, FloatSemantics::Double);
        assert!(nf.is_negative());

        let zf = APFloat::new(0.0, FloatSemantics::Float);
        assert!(zf.is_zero());
    }

    #[test]
    fn test_const_folding_add() {
        let a = Constant::Int(10, Type::i32());
        let b = Constant::Int(20, Type::i32());
        let result = ConstFolding::fold_add(&a, &b);
        assert_eq!(result, Some(Constant::Int(30, Type::i32())));
    }

    #[test]
    fn test_const_folding_sub() {
        let a = Constant::Int(50, Type::i32());
        let b = Constant::Int(20, Type::i32());
        let result = ConstFolding::fold_sub(&a, &b);
        assert_eq!(result, Some(Constant::Int(30, Type::i32())));
    }

    #[test]
    fn test_const_folding_mul() {
        let a = Constant::Int(6, Type::i32());
        let b = Constant::Int(7, Type::i32());
        let result = ConstFolding::fold_mul(&a, &b);
        assert_eq!(result, Some(Constant::Int(42, Type::i32())));
    }

    #[test]
    fn test_const_folding_sdiv() {
        let a = Constant::Int(100, Type::i32());
        let b = Constant::Int(3, Type::i32());
        let result = ConstFolding::fold_sdiv(&a, &b);
        assert_eq!(result, Some(Constant::Int(33, Type::i32())));
    }

    #[test]
    fn test_const_folding_udiv() {
        let a = Constant::UInt(100, Type::i32());
        let b = Constant::UInt(3, Type::i32());
        let result = ConstFolding::fold_udiv(&a, &b);
        assert_eq!(result, Some(Constant::UInt(33, Type::i32())));
    }

    #[test]
    fn test_const_folding_urem() {
        let a = Constant::UInt(100, Type::i32());
        let b = Constant::UInt(7, Type::i32());
        let result = ConstFolding::fold_urem(&a, &b);
        assert_eq!(result, Some(Constant::UInt(2, Type::i32())));
    }

    #[test]
    fn test_const_folding_and() {
        let a = Constant::Int(0xFF, Type::i32());
        let b = Constant::Int(0x0F, Type::i32());
        let result = ConstFolding::fold_and(&a, &b);
        assert_eq!(result, Some(Constant::Int(0x0F, Type::i32())));
    }

    #[test]
    fn test_const_folding_or() {
        let a = Constant::Int(0xF0, Type::i32());
        let b = Constant::Int(0x0F, Type::i32());
        let result = ConstFolding::fold_or(&a, &b);
        assert_eq!(result, Some(Constant::Int(0xFF, Type::i32())));
    }

    #[test]
    fn test_const_folding_xor() {
        let a = Constant::Int(0xFF, Type::i32());
        let b = Constant::Int(0x0F, Type::i32());
        let result = ConstFolding::fold_xor(&a, &b);
        assert_eq!(result, Some(Constant::Int(0xF0, Type::i32())));
    }

    #[test]
    fn test_const_folding_shl() {
        let a = Constant::Int(1, Type::i32());
        let b = Constant::Int(3, Type::i32());
        let result = ConstFolding::fold_shl(&a, &b);
        assert_eq!(result, Some(Constant::Int(8, Type::i32())));
    }

    #[test]
    fn test_const_folding_lshr() {
        let a = Constant::UInt(16, Type::i32());
        let b = Constant::UInt(2, Type::i32());
        let result = ConstFolding::fold_lshr(&a, &b);
        assert_eq!(result, Some(Constant::UInt(4, Type::i32())));
    }

    #[test]
    fn test_const_folding_ashr() {
        let a = Constant::Int(-16, Type::i32());
        let b = Constant::Int(2, Type::i32());
        let result = ConstFolding::fold_ashr(&a, &b);
        assert_eq!(result, Some(Constant::Int(-4, Type::i32())));
    }

    #[test]
    fn test_const_folding_icmp() {
        let a = Constant::Int(10, Type::i32());
        let b = Constant::Int(20, Type::i32());
        let result = ConstFolding::fold_icmp(&ICmpPred::Slt, &a, &b);
        assert_eq!(result, Some(Constant::Int(1, Type::i1())));
    }

    #[test]
    fn test_const_folding_select() {
        let cond = Constant::Int(1, Type::i1());
        let tval = Constant::Int(42, Type::i32());
        let fval = Constant::Int(0, Type::i32());
        let result = ConstFolding::fold_select(&cond, &tval, &fval);
        assert_eq!(result, Some(Constant::Int(42, Type::i32())));
    }

    #[test]
    fn test_const_folding_fadd() {
        let a = Constant::Float(1.5, Type::double());
        let b = Constant::Float(2.5, Type::double());
        let result = ConstFolding::fold_fadd(&a, &b);
        assert_eq!(result, Some(Constant::Float(4.0, Type::double())));
    }

    #[test]
    fn test_const_folding_zext() {
        let a = Constant::Int(255, Type::i8());
        let result = ConstFolding::fold_zext(&a, &Type::i32());
        assert_eq!(result, Some(Constant::UInt(255, Type::i32())));
    }

    #[test]
    fn test_const_folding_sext() {
        let a = Constant::Int(-1, Type::i8());
        let result = ConstFolding::fold_sext(&a, &Type::i32());
        assert_eq!(result, Some(Constant::Int(-1, Type::i32())));
    }

    #[test]
    fn test_const_folding_trunc() {
        let a = Constant::UInt(0x1234, Type::i32());
        let result = ConstFolding::fold_trunc(&a, &Type::i8());
        assert_eq!(result, Some(Constant::UInt(0x34, Type::i8())));
    }

    #[test]
    fn test_struct_layout_empty() {
        let ty = crate::types::Type::struct_named_with("Empty".to_string(), false, vec![]);
        let layout = StructLayout::compute(&ty);
        assert!(layout.is_some());
        let l = layout.unwrap();
        assert_eq!(l.num_fields(), 0);
        assert_eq!(l.size_in_bytes, 0);
    }

    #[test]
    fn test_gep_operator() {
        let base = const_null_ptr(Type::pointer(0));
        let idx = const_i32(0);
        let gep = const_gep(base, vec![idx]);
        let op = GEPOperator::new(&gep);
        assert!(op.is_some());
        let g = op.unwrap();
        assert_eq!(g.num_indices(), 1);
    }

    #[test]
    fn test_constant_equality() {
        let a = Constant::Int(42, Type::i32());
        let b = Constant::Int(42, Type::i32());
        let c = Constant::Int(100, Type::i32());
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn test_const_folding_fcmp() {
        let a = Constant::Float(1.0, Type::double());
        let b = Constant::Float(2.0, Type::double());
        let result = ConstFolding::fold_fcmp(&FCmpPred::Olt, &a, &b);
        assert_eq!(result, Some(Constant::Int(1, Type::i1())));
    }

    #[test]
    fn test_const_folding_extract_element() {
        let v = Constant::Vector(
            vec![
                Constant::Int(10, Type::i32()),
                Constant::Int(20, Type::i32()),
                Constant::Int(30, Type::i32()),
            ],
            Type::i32(),
        );
        let result = ConstFolding::fold_extract_element(&v, &Constant::Int(1, Type::i32()));
        assert_eq!(result, Some(Constant::Int(20, Type::i32())));
    }
}