bhc-codegen 0.2.4

Code generation backend for BHC (LLVM backend)
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
//! Lowering from Loop IR to LLVM IR.
//!
//! This module implements the translation from BHC's Loop IR to LLVM IR
//! for the Numeric profile. It handles:
//!
//! - Loop constructs: for loops, parallel loops
//! - SIMD operations: vector loads, stores, arithmetic
//! - Memory operations: aligned/unaligned access
//! - Scalar operations: arithmetic, comparisons, casts

use crate::{CodegenError, CodegenResult};
use bhc_index::Idx;
use bhc_intern::Symbol;
use bhc_loop_ir::{
    Alloc, AllocSize, BinOp, Body, CmpOp, IfStmt, Loop, LoopIR, LoopType, MemRef, Op, ReduceOp,
    ScalarType, Stmt, UnOp, Value, ValueId,
};
use bhc_tensor_ir::{AllocRegion, BufferId};
use inkwell::builder::Builder;
use inkwell::context::Context;
use inkwell::intrinsics::Intrinsic;
use inkwell::types::{BasicMetadataTypeEnum, BasicType, BasicTypeEnum, VectorType};
use inkwell::values::{
    BasicValueEnum, FloatValue, FunctionValue, IntValue, PointerValue, VectorValue,
};
use inkwell::AddressSpace;
use inkwell::FloatPredicate;
use inkwell::IntPredicate;
use rustc_hash::FxHashMap;

use super::context::LlvmContext;
use super::module::LlvmModule;

/// State for lowering Loop IR to LLVM IR.
pub struct LoopLowering<'ctx, 'm> {
    /// The underlying LLVM context.
    llvm_ctx: &'ctx Context,
    /// The LLVM module being generated.
    module: &'m LlvmModule<'ctx>,
    /// The IR builder.
    builder: Builder<'ctx>,
    /// Mapping from Loop IR values to LLVM values.
    values: FxHashMap<ValueId, BasicValueEnum<'ctx>>,
    /// Mapping from buffer IDs to LLVM pointers.
    buffers: FxHashMap<BufferId, PointerValue<'ctx>>,
    /// Counter for generating unique names.
    // Kept for the `unique_name` helper used by in-progress Loop IR lowering paths.
    #[allow(dead_code)]
    name_counter: u32,
    /// Current function being generated.
    current_fn: Option<FunctionValue<'ctx>>,
}

impl<'ctx, 'm> LoopLowering<'ctx, 'm> {
    /// Create a new Loop IR lowering context.
    pub fn new(ctx: &'ctx LlvmContext, module: &'m LlvmModule<'ctx>) -> Self {
        Self {
            llvm_ctx: ctx.llvm_context(),
            module,
            builder: ctx.llvm_context().create_builder(),
            values: FxHashMap::default(),
            buffers: FxHashMap::default(),
            name_counter: 0,
            current_fn: None,
        }
    }

    /// Generate a unique name.
    // Utility for naming generated LLVM values; not yet wired into every lowering path.
    #[allow(dead_code)]
    fn unique_name(&mut self, prefix: &str) -> String {
        let name = format!("{}_{}", prefix, self.name_counter);
        self.name_counter += 1;
        name
    }

    /// Lower a complete Loop IR function to LLVM.
    pub fn lower_function(&mut self, ir: &LoopIR) -> CodegenResult<FunctionValue<'ctx>> {
        // Clear state from previous lowering
        self.values.clear();
        self.buffers.clear();

        // Create function signature
        let fn_type = self.create_function_type(ir)?;
        let fn_name = ir.name.as_str();
        let function = self
            .module
            .llvm_module()
            .add_function(fn_name, fn_type, None);
        self.current_fn = Some(function);

        // Create entry block
        let entry = self.llvm_ctx.append_basic_block(function, "entry");
        self.builder.position_at_end(entry);

        // Bind parameters
        for (i, _param) in ir.params.iter().enumerate() {
            let llvm_param = function
                .get_nth_param(i as u32)
                .ok_or_else(|| CodegenError::Internal(format!("Missing parameter {}", i)))?;
            // Store the parameter value
            let param_id = ValueId::new(i);
            self.values.insert(param_id, llvm_param);
        }

        // Allocate buffers
        for alloc in &ir.allocs {
            self.lower_alloc(alloc)?;
        }

        // Lower the body
        self.lower_body(&ir.body)?;

        // Add implicit void return if needed
        if ir.return_ty.is_void()
            && self
                .builder
                .get_insert_block()
                .is_none_or(|b| b.get_terminator().is_none())
        {
            self.builder
                .build_return(None)
                .map_err(|e| CodegenError::LlvmError(e.to_string()))?;
        }

        // Verify the function
        if function.verify(true) {
            Ok(function)
        } else {
            Err(CodegenError::Internal(format!(
                "Generated function {} failed verification",
                fn_name
            )))
        }
    }

    /// Create the LLVM function type for a Loop IR function.
    fn create_function_type(
        &self,
        ir: &LoopIR,
    ) -> CodegenResult<inkwell::types::FunctionType<'ctx>> {
        let param_types: Vec<BasicMetadataTypeEnum> = ir
            .params
            .iter()
            .map(|p| self.loop_type_to_llvm(&p.ty))
            .collect::<CodegenResult<Vec<_>>>()?
            .into_iter()
            .map(|t| t.into())
            .collect();

        let fn_type = if ir.return_ty.is_void() {
            self.llvm_ctx.void_type().fn_type(&param_types, false)
        } else {
            let ret_ty = self.loop_type_to_llvm(&ir.return_ty)?;
            ret_ty.fn_type(&param_types, false)
        };

        Ok(fn_type)
    }

    /// Convert a Loop IR type to an LLVM type.
    fn loop_type_to_llvm(&self, ty: &LoopType) -> CodegenResult<BasicTypeEnum<'ctx>> {
        match ty {
            LoopType::Void => Err(CodegenError::Internal(
                "Cannot convert void to basic type".to_string(),
            )),
            LoopType::Scalar(scalar) => self.scalar_type_to_llvm(*scalar),
            LoopType::Vector(scalar, width) => {
                let elem_ty = self.scalar_type_to_llvm(*scalar)?;
                let vec_ty = match elem_ty {
                    BasicTypeEnum::FloatType(f) => f.vec_type(*width as u32).into(),
                    BasicTypeEnum::IntType(i) => i.vec_type(*width as u32).into(),
                    _ => {
                        return Err(CodegenError::Internal(format!(
                            "Cannot create vector of {:?}",
                            elem_ty
                        )))
                    }
                };
                Ok(vec_ty)
            }
            LoopType::Ptr(_inner) => {
                let ptr_ty = self.llvm_ctx.ptr_type(AddressSpace::default());
                Ok(ptr_ty.into())
            }
        }
    }

    /// Convert a scalar type to an LLVM type.
    fn scalar_type_to_llvm(&self, ty: ScalarType) -> CodegenResult<BasicTypeEnum<'ctx>> {
        let llvm_ty = match ty {
            ScalarType::Bool => self.llvm_ctx.bool_type().into(),
            ScalarType::Int(8) => self.llvm_ctx.i8_type().into(),
            ScalarType::Int(16) => self.llvm_ctx.i16_type().into(),
            ScalarType::Int(32) => self.llvm_ctx.i32_type().into(),
            ScalarType::Int(64) => self.llvm_ctx.i64_type().into(),
            ScalarType::UInt(8) => self.llvm_ctx.i8_type().into(),
            ScalarType::UInt(16) => self.llvm_ctx.i16_type().into(),
            ScalarType::UInt(32) => self.llvm_ctx.i32_type().into(),
            ScalarType::UInt(64) => self.llvm_ctx.i64_type().into(),
            ScalarType::Float(16) => self.llvm_ctx.f16_type().into(),
            ScalarType::Float(32) => self.llvm_ctx.f32_type().into(),
            ScalarType::Float(64) => self.llvm_ctx.f64_type().into(),
            ScalarType::Int(bits) | ScalarType::UInt(bits) => {
                self.llvm_ctx.custom_width_int_type(bits as u32).into()
            }
            ScalarType::Float(bits) => {
                return Err(CodegenError::Unsupported(format!(
                    "Float with {} bits",
                    bits
                )))
            }
        };
        Ok(llvm_ty)
    }

    /// Lower an allocation.
    fn lower_alloc(&mut self, alloc: &Alloc) -> CodegenResult<()> {
        let elem_ty = self.scalar_type_to_llvm(alloc.elem_ty)?;

        // Compute the size
        let _size = match &alloc.size {
            AllocSize::Static(n) => self.llvm_ctx.i64_type().const_int(*n as u64, false),
            AllocSize::Dynamic(vid) => {
                let val = self.get_value(*vid)?;
                match val {
                    BasicValueEnum::IntValue(i) => i,
                    _ => {
                        return Err(CodegenError::TypeError(
                            "Dynamic size must be integer".to_string(),
                        ))
                    }
                }
            }
        };

        // For now, use alloca for stack allocation (Hot Arena)
        // In the future, this would dispatch to arena allocator
        let ptr = match alloc.region {
            AllocRegion::HotArena | AllocRegion::General => {
                // Stack allocate with alignment
                let array_ty = elem_ty.array_type(1024); // Placeholder size
                let alloca = self
                    .builder
                    .build_alloca(array_ty, alloc.name.as_str())
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?;
                alloca
            }
            AllocRegion::Pinned | AllocRegion::DeviceMemory(_) => {
                // These would need malloc/device allocation
                // For now, fall back to stack
                let array_ty = elem_ty.array_type(1024);
                self.builder
                    .build_alloca(array_ty, alloc.name.as_str())
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?
            }
        };

        self.buffers.insert(alloc.buffer, ptr);
        Ok(())
    }

    /// Lower a body (sequence of statements).
    fn lower_body(&mut self, body: &Body) -> CodegenResult<()> {
        for stmt in &body.stmts {
            self.lower_stmt(stmt)?;
        }
        Ok(())
    }

    /// Lower a statement.
    fn lower_stmt(&mut self, stmt: &Stmt) -> CodegenResult<()> {
        match stmt {
            Stmt::Assign(vid, op) => {
                let value = self.lower_op(op)?;
                self.values.insert(*vid, value);
            }
            Stmt::Loop(lp) => {
                self.lower_loop(lp)?;
            }
            Stmt::If(if_stmt) => {
                self.lower_if(if_stmt)?;
            }
            Stmt::Store(mem_ref, value) => {
                self.lower_store(mem_ref, value)?;
            }
            Stmt::Call(result, name, args) => {
                self.lower_call(*result, *name, args)?;
            }
            Stmt::Return(value) => {
                self.lower_return(value.as_ref())?;
            }
            Stmt::Barrier(_kind) => {
                // Insert memory barrier
                self.builder
                    .build_fence(
                        inkwell::AtomicOrdering::SequentiallyConsistent,
                        0, // syncscope ID (0 = system scope)
                        "fence",
                    )
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?;
            }
            Stmt::Comment(_) => {
                // Comments are no-ops in LLVM
            }
        }
        Ok(())
    }

    /// Lower a loop construct.
    fn lower_loop(&mut self, lp: &Loop) -> CodegenResult<()> {
        let function = self
            .current_fn
            .ok_or_else(|| CodegenError::Internal("No current function for loop".to_string()))?;

        // Create basic blocks
        let preheader = self.llvm_ctx.append_basic_block(function, "loop.preheader");
        let header = self.llvm_ctx.append_basic_block(function, "loop.header");
        let body_block = self.llvm_ctx.append_basic_block(function, "loop.body");
        let latch = self.llvm_ctx.append_basic_block(function, "loop.latch");
        let exit = self.llvm_ctx.append_basic_block(function, "loop.exit");

        // Branch to preheader
        self.builder
            .build_unconditional_branch(preheader)
            .map_err(|e| CodegenError::LlvmError(e.to_string()))?;

        // Preheader: initialize loop variable
        self.builder.position_at_end(preheader);
        let lower_val = self.lower_value(&lp.lower)?;
        let lower_int = self.value_to_int(lower_val)?;
        self.builder
            .build_unconditional_branch(header)
            .map_err(|e| CodegenError::LlvmError(e.to_string()))?;

        // Header: phi node and condition check
        self.builder.position_at_end(header);
        let i64_ty = self.llvm_ctx.i64_type();
        let phi = self
            .builder
            .build_phi(i64_ty, "loop.iv")
            .map_err(|e| CodegenError::LlvmError(e.to_string()))?;
        phi.add_incoming(&[(&lower_int, preheader)]);

        let iv_val = phi.as_basic_value().into_int_value();
        self.values.insert(lp.var, BasicValueEnum::IntValue(iv_val));

        let upper_val = self.lower_value(&lp.upper)?;
        let upper_int = self.value_to_int(upper_val)?;

        let cond = self
            .builder
            .build_int_compare(IntPredicate::SLT, iv_val, upper_int, "loop.cond")
            .map_err(|e| CodegenError::LlvmError(e.to_string()))?;

        self.builder
            .build_conditional_branch(cond, body_block, exit)
            .map_err(|e| CodegenError::LlvmError(e.to_string()))?;

        // Body: lower loop body statements
        self.builder.position_at_end(body_block);
        self.lower_body(&lp.body)?;
        self.builder
            .build_unconditional_branch(latch)
            .map_err(|e| CodegenError::LlvmError(e.to_string()))?;

        // Latch: increment and back-edge
        self.builder.position_at_end(latch);
        let step_val = self.lower_value(&lp.step)?;
        let step_int = self.value_to_int(step_val)?;

        // Get the current IV value (may have been updated in the body)
        let current_iv = self
            .values
            .get(&lp.var)
            .copied()
            .ok_or_else(|| CodegenError::Internal("Loop variable not found".to_string()))?;
        let current_iv_int = match current_iv {
            BasicValueEnum::IntValue(i) => i,
            _ => iv_val, // Fall back to phi value
        };

        let next_iv = self
            .builder
            .build_int_add(current_iv_int, step_int, "loop.next")
            .map_err(|e| CodegenError::LlvmError(e.to_string()))?;

        phi.add_incoming(&[(&next_iv, latch)]);

        self.builder
            .build_unconditional_branch(header)
            .map_err(|e| CodegenError::LlvmError(e.to_string()))?;

        // Continue after exit
        self.builder.position_at_end(exit);

        Ok(())
    }

    /// Lower an if statement.
    fn lower_if(&mut self, if_stmt: &IfStmt) -> CodegenResult<()> {
        let function = self
            .current_fn
            .ok_or_else(|| CodegenError::Internal("No current function for if".to_string()))?;

        let cond_val = self.lower_value(&if_stmt.cond)?;
        let cond_bool = match cond_val {
            BasicValueEnum::IntValue(i) => {
                // Convert to i1 if needed
                if i.get_type().get_bit_width() == 1 {
                    i
                } else {
                    self.builder
                        .build_int_compare(
                            IntPredicate::NE,
                            i,
                            i.get_type().const_zero(),
                            "cond.bool",
                        )
                        .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                }
            }
            _ => {
                return Err(CodegenError::TypeError(
                    "If condition must be boolean/integer".to_string(),
                ))
            }
        };

        let then_block = self.llvm_ctx.append_basic_block(function, "if.then");
        let else_block = self.llvm_ctx.append_basic_block(function, "if.else");
        let merge_block = self.llvm_ctx.append_basic_block(function, "if.merge");

        self.builder
            .build_conditional_branch(cond_bool, then_block, else_block)
            .map_err(|e| CodegenError::LlvmError(e.to_string()))?;

        // Then branch
        self.builder.position_at_end(then_block);
        self.lower_body(&if_stmt.then_body)?;
        if self
            .builder
            .get_insert_block()
            .is_none_or(|b| b.get_terminator().is_none())
        {
            self.builder
                .build_unconditional_branch(merge_block)
                .map_err(|e| CodegenError::LlvmError(e.to_string()))?;
        }

        // Else branch
        self.builder.position_at_end(else_block);
        if let Some(else_body) = &if_stmt.else_body {
            self.lower_body(else_body)?;
        }
        if self
            .builder
            .get_insert_block()
            .is_none_or(|b| b.get_terminator().is_none())
        {
            self.builder
                .build_unconditional_branch(merge_block)
                .map_err(|e| CodegenError::LlvmError(e.to_string()))?;
        }

        // Continue at merge
        self.builder.position_at_end(merge_block);

        Ok(())
    }

    /// Lower a store operation.
    fn lower_store(&mut self, mem_ref: &MemRef, value: &Value) -> CodegenResult<()> {
        let ptr = self.compute_address(mem_ref)?;
        let val = self.lower_value(value)?;

        self.builder
            .build_store(ptr, val)
            .map_err(|e| CodegenError::LlvmError(e.to_string()))?;

        Ok(())
    }

    /// Lower a function call.
    fn lower_call(
        &mut self,
        result: Option<ValueId>,
        name: Symbol,
        args: &[Value],
    ) -> CodegenResult<()> {
        // Look up or declare the function
        let fn_name = name.as_str();
        let function = self
            .module
            .llvm_module()
            .get_function(fn_name)
            .ok_or_else(|| CodegenError::Internal(format!("Unknown function: {}", fn_name)))?;

        // Lower arguments
        let arg_vals: Vec<BasicValueEnum> = args
            .iter()
            .map(|a| self.lower_value(a))
            .collect::<CodegenResult<Vec<_>>>()?;

        let arg_meta: Vec<_> = arg_vals.iter().map(|v| (*v).into()).collect();

        let call_result = self
            .builder
            .build_call(function, &arg_meta, "call")
            .map_err(|e| CodegenError::LlvmError(e.to_string()))?;

        if let Some(vid) = result {
            if let Some(ret_val) = call_result.try_as_basic_value().basic() {
                self.values.insert(vid, ret_val);
            }
        }

        Ok(())
    }

    /// Lower a return statement.
    fn lower_return(&mut self, value: Option<&Value>) -> CodegenResult<()> {
        match value {
            Some(v) => {
                let val = self.lower_value(v)?;
                self.builder
                    .build_return(Some(&val))
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?;
            }
            None => {
                self.builder
                    .build_return(None)
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?;
            }
        }
        Ok(())
    }

    /// Lower an operation.
    fn lower_op(&mut self, op: &Op) -> CodegenResult<BasicValueEnum<'ctx>> {
        match op {
            Op::Load(mem_ref) => self.lower_load(mem_ref),
            Op::Binary(bin_op, lhs, rhs) => self.lower_binary(*bin_op, lhs, rhs),
            Op::Unary(un_op, val) => self.lower_unary(*un_op, val),
            Op::Cmp(cmp_op, lhs, rhs) => self.lower_cmp(*cmp_op, lhs, rhs),
            Op::Select(cond, then_val, else_val) => self.lower_select(cond, then_val, else_val),
            Op::Cast(val, target_ty) => self.lower_cast(val, target_ty),
            Op::Broadcast(val, width) => self.lower_broadcast(val, *width),
            Op::Extract(vec, idx) => self.lower_extract(vec, *idx),
            Op::Insert(vec, val, idx) => self.lower_insert(vec, val, *idx),
            Op::Shuffle(v1, v2, mask) => self.lower_shuffle(v1, v2, mask),
            Op::VecReduce(reduce_op, val) => self.lower_vec_reduce(*reduce_op, val),
            Op::Fma(a, b, c) => self.lower_fma(a, b, c),
            Op::PtrAdd(ptr, offset) => self.lower_ptr_add(ptr, offset),
            Op::GetPtr(buffer, index) => self.lower_get_ptr(*buffer, index),
            Op::Phi(_entries) => {
                // Phi nodes are handled specially during loop lowering
                Err(CodegenError::Internal(
                    "Phi nodes should be lowered in loop context".to_string(),
                ))
            }
        }
    }

    /// Lower a load operation.
    fn lower_load(&mut self, mem_ref: &MemRef) -> CodegenResult<BasicValueEnum<'ctx>> {
        let ptr = self.compute_address(mem_ref)?;
        let elem_ty = self.loop_type_to_llvm(&mem_ref.elem_ty)?;

        let load = self
            .builder
            .build_load(elem_ty, ptr, "load")
            .map_err(|e| CodegenError::LlvmError(e.to_string()))?;

        Ok(load)
    }

    /// Compute the address for a memory reference.
    fn compute_address(&mut self, mem_ref: &MemRef) -> CodegenResult<PointerValue<'ctx>> {
        let base_ptr = self.buffers.get(&mem_ref.buffer).copied().ok_or_else(|| {
            CodegenError::Internal(format!("Unknown buffer: {:?}", mem_ref.buffer))
        })?;

        let index_val = self.lower_value(&mem_ref.index)?;
        let index_int = self.value_to_int(index_val)?;

        let elem_ty = self.loop_type_to_llvm(&mem_ref.elem_ty)?;

        // Use GEP to compute the address
        let ptr = unsafe {
            self.builder
                .build_gep(elem_ty, base_ptr, &[index_int], "gep")
                .map_err(|e| CodegenError::LlvmError(e.to_string()))?
        };

        Ok(ptr)
    }

    /// Lower a binary operation.
    fn lower_binary(
        &mut self,
        op: BinOp,
        lhs: &Value,
        rhs: &Value,
    ) -> CodegenResult<BasicValueEnum<'ctx>> {
        let lhs_val = self.lower_value(lhs)?;
        let rhs_val = self.lower_value(rhs)?;

        let result = match (lhs_val, rhs_val) {
            (BasicValueEnum::IntValue(l), BasicValueEnum::IntValue(r)) => {
                self.lower_int_binary(op, l, r)?
            }
            (BasicValueEnum::FloatValue(l), BasicValueEnum::FloatValue(r)) => {
                self.lower_float_binary(op, l, r)?
            }
            (BasicValueEnum::VectorValue(l), BasicValueEnum::VectorValue(r)) => {
                self.lower_vector_binary(op, l, r)?
            }
            _ => {
                return Err(CodegenError::TypeError(format!(
                    "Mismatched types for binary op {:?}",
                    op
                )))
            }
        };

        Ok(result)
    }

    /// Lower an integer binary operation.
    fn lower_int_binary(
        &mut self,
        op: BinOp,
        lhs: IntValue<'ctx>,
        rhs: IntValue<'ctx>,
    ) -> CodegenResult<BasicValueEnum<'ctx>> {
        let result = match op {
            BinOp::Add => self
                .builder
                .build_int_add(lhs, rhs, "add")
                .map_err(|e| CodegenError::LlvmError(e.to_string()))?,
            BinOp::Sub => self
                .builder
                .build_int_sub(lhs, rhs, "sub")
                .map_err(|e| CodegenError::LlvmError(e.to_string()))?,
            BinOp::Mul => self
                .builder
                .build_int_mul(lhs, rhs, "mul")
                .map_err(|e| CodegenError::LlvmError(e.to_string()))?,
            BinOp::SDiv => self
                .builder
                .build_int_signed_div(lhs, rhs, "sdiv")
                .map_err(|e| CodegenError::LlvmError(e.to_string()))?,
            BinOp::UDiv => self
                .builder
                .build_int_unsigned_div(lhs, rhs, "udiv")
                .map_err(|e| CodegenError::LlvmError(e.to_string()))?,
            BinOp::SRem => self
                .builder
                .build_int_signed_rem(lhs, rhs, "srem")
                .map_err(|e| CodegenError::LlvmError(e.to_string()))?,
            BinOp::URem => self
                .builder
                .build_int_unsigned_rem(lhs, rhs, "urem")
                .map_err(|e| CodegenError::LlvmError(e.to_string()))?,
            BinOp::And => self
                .builder
                .build_and(lhs, rhs, "and")
                .map_err(|e| CodegenError::LlvmError(e.to_string()))?,
            BinOp::Or => self
                .builder
                .build_or(lhs, rhs, "or")
                .map_err(|e| CodegenError::LlvmError(e.to_string()))?,
            BinOp::Xor => self
                .builder
                .build_xor(lhs, rhs, "xor")
                .map_err(|e| CodegenError::LlvmError(e.to_string()))?,
            BinOp::Shl => self
                .builder
                .build_left_shift(lhs, rhs, "shl")
                .map_err(|e| CodegenError::LlvmError(e.to_string()))?,
            BinOp::LShr => self
                .builder
                .build_right_shift(lhs, rhs, false, "lshr")
                .map_err(|e| CodegenError::LlvmError(e.to_string()))?,
            BinOp::AShr => self
                .builder
                .build_right_shift(lhs, rhs, true, "ashr")
                .map_err(|e| CodegenError::LlvmError(e.to_string()))?,
            BinOp::SMin | BinOp::UMin | BinOp::SMax | BinOp::UMax => {
                // Use select for min/max
                let cmp = match op {
                    BinOp::SMin => IntPredicate::SLT,
                    BinOp::UMin => IntPredicate::ULT,
                    BinOp::SMax => IntPredicate::SGT,
                    BinOp::UMax => IntPredicate::UGT,
                    _ => unreachable!(),
                };
                let cond = self
                    .builder
                    .build_int_compare(cmp, lhs, rhs, "cmp")
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?;
                self.builder
                    .build_select(cond, lhs, rhs, "minmax")
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                    .into_int_value()
            }
            BinOp::FDiv | BinOp::FRem | BinOp::FMin | BinOp::FMax => {
                return Err(CodegenError::TypeError(
                    "Float operation on integer values".to_string(),
                ))
            }
        };
        Ok(result.into())
    }

    /// Lower a float binary operation.
    fn lower_float_binary(
        &mut self,
        op: BinOp,
        lhs: FloatValue<'ctx>,
        rhs: FloatValue<'ctx>,
    ) -> CodegenResult<BasicValueEnum<'ctx>> {
        let result = match op {
            BinOp::Add => self
                .builder
                .build_float_add(lhs, rhs, "fadd")
                .map_err(|e| CodegenError::LlvmError(e.to_string()))?,
            BinOp::Sub => self
                .builder
                .build_float_sub(lhs, rhs, "fsub")
                .map_err(|e| CodegenError::LlvmError(e.to_string()))?,
            BinOp::Mul => self
                .builder
                .build_float_mul(lhs, rhs, "fmul")
                .map_err(|e| CodegenError::LlvmError(e.to_string()))?,
            BinOp::FDiv => self
                .builder
                .build_float_div(lhs, rhs, "fdiv")
                .map_err(|e| CodegenError::LlvmError(e.to_string()))?,
            BinOp::FRem => self
                .builder
                .build_float_rem(lhs, rhs, "frem")
                .map_err(|e| CodegenError::LlvmError(e.to_string()))?,
            BinOp::FMin => {
                let cond = self
                    .builder
                    .build_float_compare(FloatPredicate::OLT, lhs, rhs, "cmp")
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?;
                self.builder
                    .build_select(cond, lhs, rhs, "fmin")
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                    .into_float_value()
            }
            BinOp::FMax => {
                let cond = self
                    .builder
                    .build_float_compare(FloatPredicate::OGT, lhs, rhs, "cmp")
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?;
                self.builder
                    .build_select(cond, lhs, rhs, "fmax")
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                    .into_float_value()
            }
            _ => {
                return Err(CodegenError::TypeError(
                    "Integer operation on float values".to_string(),
                ))
            }
        };
        Ok(result.into())
    }

    /// Lower a vector binary operation.
    fn lower_vector_binary(
        &mut self,
        op: BinOp,
        lhs: VectorValue<'ctx>,
        rhs: VectorValue<'ctx>,
    ) -> CodegenResult<BasicValueEnum<'ctx>> {
        // Vector operations use the same instructions as scalar
        // LLVM handles vectorization automatically
        let elem_ty = lhs.get_type().get_element_type();

        let result: BasicValueEnum<'ctx> = if elem_ty.is_int_type() {
            match op {
                BinOp::Add => self
                    .builder
                    .build_int_add(lhs, rhs, "vadd")
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                    .into(),
                BinOp::Sub => self
                    .builder
                    .build_int_sub(lhs, rhs, "vsub")
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                    .into(),
                BinOp::Mul => self
                    .builder
                    .build_int_mul(lhs, rhs, "vmul")
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                    .into(),
                _ => {
                    return Err(CodegenError::Unsupported(format!(
                        "Vector int operation {:?}",
                        op
                    )))
                }
            }
        } else {
            match op {
                BinOp::Add => self
                    .builder
                    .build_float_add(lhs, rhs, "vfadd")
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                    .into(),
                BinOp::Sub => self
                    .builder
                    .build_float_sub(lhs, rhs, "vfsub")
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                    .into(),
                BinOp::Mul => self
                    .builder
                    .build_float_mul(lhs, rhs, "vfmul")
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                    .into(),
                BinOp::FDiv => self
                    .builder
                    .build_float_div(lhs, rhs, "vfdiv")
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                    .into(),
                _ => {
                    return Err(CodegenError::Unsupported(format!(
                        "Vector float operation {:?}",
                        op
                    )))
                }
            }
        };

        Ok(result)
    }

    /// Lower a unary operation.
    fn lower_unary(&mut self, op: UnOp, val: &Value) -> CodegenResult<BasicValueEnum<'ctx>> {
        let v = self.lower_value(val)?;

        let result = match v {
            BasicValueEnum::IntValue(i) => self.lower_int_unary(op, i)?,
            BasicValueEnum::FloatValue(f) => self.lower_float_unary(op, f)?,
            BasicValueEnum::VectorValue(vec) => {
                // Handle vector unary ops
                self.lower_vector_unary(op, vec)?
            }
            _ => {
                return Err(CodegenError::TypeError(format!(
                    "Unsupported type for unary op {:?}",
                    op
                )))
            }
        };

        Ok(result)
    }

    /// Lower an integer unary operation.
    fn lower_int_unary(
        &mut self,
        op: UnOp,
        val: IntValue<'ctx>,
    ) -> CodegenResult<BasicValueEnum<'ctx>> {
        let result = match op {
            UnOp::Neg => self
                .builder
                .build_int_neg(val, "neg")
                .map_err(|e| CodegenError::LlvmError(e.to_string()))?,
            UnOp::Not => self
                .builder
                .build_not(val, "not")
                .map_err(|e| CodegenError::LlvmError(e.to_string()))?,
            UnOp::Abs => {
                // abs(x) = x < 0 ? -x : x
                let zero = val.get_type().const_zero();
                let is_neg = self
                    .builder
                    .build_int_compare(IntPredicate::SLT, val, zero, "is_neg")
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?;
                let neg_val = self
                    .builder
                    .build_int_neg(val, "neg")
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?;
                self.builder
                    .build_select(is_neg, neg_val, val, "abs")
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                    .into_int_value()
            }
            _ => {
                return Err(CodegenError::TypeError(format!(
                    "Float unary op {:?} on integer",
                    op
                )))
            }
        };
        Ok(result.into())
    }

    /// Lower a float unary operation.
    fn lower_float_unary(
        &mut self,
        op: UnOp,
        val: FloatValue<'ctx>,
    ) -> CodegenResult<BasicValueEnum<'ctx>> {
        let result = match op {
            UnOp::FNeg | UnOp::Neg => self
                .builder
                .build_float_neg(val, "fneg")
                .map_err(|e| CodegenError::LlvmError(e.to_string()))?,
            UnOp::FAbs | UnOp::Abs => {
                // Use llvm.fabs intrinsic
                let intrinsic = Intrinsic::find("llvm.fabs")
                    .ok_or_else(|| CodegenError::Internal("llvm.fabs not found".to_string()))?;
                let fn_val = intrinsic
                    .get_declaration(self.module.llvm_module(), &[val.get_type().into()])
                    .ok_or_else(|| {
                        CodegenError::Internal("Failed to get fabs declaration".to_string())
                    })?;
                self.builder
                    .build_call(fn_val, &[val.into()], "fabs")
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                    .try_as_basic_value()
                    .basic()
                    .ok_or_else(|| CodegenError::Internal("fabs returned void".to_string()))?
                    .into_float_value()
            }
            UnOp::Sqrt => {
                let intrinsic = Intrinsic::find("llvm.sqrt")
                    .ok_or_else(|| CodegenError::Internal("llvm.sqrt not found".to_string()))?;
                let fn_val = intrinsic
                    .get_declaration(self.module.llvm_module(), &[val.get_type().into()])
                    .ok_or_else(|| {
                        CodegenError::Internal("Failed to get sqrt declaration".to_string())
                    })?;
                self.builder
                    .build_call(fn_val, &[val.into()], "sqrt")
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                    .try_as_basic_value()
                    .basic()
                    .ok_or_else(|| CodegenError::Internal("sqrt returned void".to_string()))?
                    .into_float_value()
            }
            UnOp::Floor => {
                let intrinsic = Intrinsic::find("llvm.floor")
                    .ok_or_else(|| CodegenError::Internal("llvm.floor not found".to_string()))?;
                let fn_val = intrinsic
                    .get_declaration(self.module.llvm_module(), &[val.get_type().into()])
                    .ok_or_else(|| {
                        CodegenError::Internal("Failed to get floor declaration".to_string())
                    })?;
                self.builder
                    .build_call(fn_val, &[val.into()], "floor")
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                    .try_as_basic_value()
                    .basic()
                    .ok_or_else(|| CodegenError::Internal("floor returned void".to_string()))?
                    .into_float_value()
            }
            UnOp::Ceil => {
                let intrinsic = Intrinsic::find("llvm.ceil")
                    .ok_or_else(|| CodegenError::Internal("llvm.ceil not found".to_string()))?;
                let fn_val = intrinsic
                    .get_declaration(self.module.llvm_module(), &[val.get_type().into()])
                    .ok_or_else(|| {
                        CodegenError::Internal("Failed to get ceil declaration".to_string())
                    })?;
                self.builder
                    .build_call(fn_val, &[val.into()], "ceil")
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                    .try_as_basic_value()
                    .basic()
                    .ok_or_else(|| CodegenError::Internal("ceil returned void".to_string()))?
                    .into_float_value()
            }
            UnOp::Round => {
                let intrinsic = Intrinsic::find("llvm.round")
                    .ok_or_else(|| CodegenError::Internal("llvm.round not found".to_string()))?;
                let fn_val = intrinsic
                    .get_declaration(self.module.llvm_module(), &[val.get_type().into()])
                    .ok_or_else(|| {
                        CodegenError::Internal("Failed to get round declaration".to_string())
                    })?;
                self.builder
                    .build_call(fn_val, &[val.into()], "round")
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                    .try_as_basic_value()
                    .basic()
                    .ok_or_else(|| CodegenError::Internal("round returned void".to_string()))?
                    .into_float_value()
            }
            UnOp::Trunc => {
                let intrinsic = Intrinsic::find("llvm.trunc")
                    .ok_or_else(|| CodegenError::Internal("llvm.trunc not found".to_string()))?;
                let fn_val = intrinsic
                    .get_declaration(self.module.llvm_module(), &[val.get_type().into()])
                    .ok_or_else(|| {
                        CodegenError::Internal("Failed to get trunc declaration".to_string())
                    })?;
                self.builder
                    .build_call(fn_val, &[val.into()], "trunc")
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                    .try_as_basic_value()
                    .basic()
                    .ok_or_else(|| CodegenError::Internal("trunc returned void".to_string()))?
                    .into_float_value()
            }
            UnOp::Exp => {
                let intrinsic = Intrinsic::find("llvm.exp")
                    .ok_or_else(|| CodegenError::Internal("llvm.exp not found".to_string()))?;
                let fn_val = intrinsic
                    .get_declaration(self.module.llvm_module(), &[val.get_type().into()])
                    .ok_or_else(|| {
                        CodegenError::Internal("Failed to get exp declaration".to_string())
                    })?;
                self.builder
                    .build_call(fn_val, &[val.into()], "exp")
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                    .try_as_basic_value()
                    .basic()
                    .ok_or_else(|| CodegenError::Internal("exp returned void".to_string()))?
                    .into_float_value()
            }
            UnOp::Log => {
                let intrinsic = Intrinsic::find("llvm.log")
                    .ok_or_else(|| CodegenError::Internal("llvm.log not found".to_string()))?;
                let fn_val = intrinsic
                    .get_declaration(self.module.llvm_module(), &[val.get_type().into()])
                    .ok_or_else(|| {
                        CodegenError::Internal("Failed to get log declaration".to_string())
                    })?;
                self.builder
                    .build_call(fn_val, &[val.into()], "log")
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                    .try_as_basic_value()
                    .basic()
                    .ok_or_else(|| CodegenError::Internal("log returned void".to_string()))?
                    .into_float_value()
            }
            UnOp::Sin => {
                let intrinsic = Intrinsic::find("llvm.sin")
                    .ok_or_else(|| CodegenError::Internal("llvm.sin not found".to_string()))?;
                let fn_val = intrinsic
                    .get_declaration(self.module.llvm_module(), &[val.get_type().into()])
                    .ok_or_else(|| {
                        CodegenError::Internal("Failed to get sin declaration".to_string())
                    })?;
                self.builder
                    .build_call(fn_val, &[val.into()], "sin")
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                    .try_as_basic_value()
                    .basic()
                    .ok_or_else(|| CodegenError::Internal("sin returned void".to_string()))?
                    .into_float_value()
            }
            UnOp::Cos => {
                let intrinsic = Intrinsic::find("llvm.cos")
                    .ok_or_else(|| CodegenError::Internal("llvm.cos not found".to_string()))?;
                let fn_val = intrinsic
                    .get_declaration(self.module.llvm_module(), &[val.get_type().into()])
                    .ok_or_else(|| {
                        CodegenError::Internal("Failed to get cos declaration".to_string())
                    })?;
                self.builder
                    .build_call(fn_val, &[val.into()], "cos")
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                    .try_as_basic_value()
                    .basic()
                    .ok_or_else(|| CodegenError::Internal("cos returned void".to_string()))?
                    .into_float_value()
            }
            UnOp::Rsqrt => {
                // rsqrt(x) = 1 / sqrt(x)
                let sqrt_intrinsic = Intrinsic::find("llvm.sqrt")
                    .ok_or_else(|| CodegenError::Internal("llvm.sqrt not found".to_string()))?;
                let fn_val = sqrt_intrinsic
                    .get_declaration(self.module.llvm_module(), &[val.get_type().into()])
                    .ok_or_else(|| {
                        CodegenError::Internal("Failed to get sqrt declaration".to_string())
                    })?;
                let sqrt_val = self
                    .builder
                    .build_call(fn_val, &[val.into()], "sqrt")
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                    .try_as_basic_value()
                    .basic()
                    .ok_or_else(|| CodegenError::Internal("sqrt returned void".to_string()))?
                    .into_float_value();

                let one = val.get_type().const_float(1.0);
                self.builder
                    .build_float_div(one, sqrt_val, "rsqrt")
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?
            }
            UnOp::Not => return Err(CodegenError::TypeError("Bitwise NOT on float".to_string())),
        };
        Ok(result.into())
    }

    /// Lower a vector unary operation.
    fn lower_vector_unary(
        &mut self,
        op: UnOp,
        vec: VectorValue<'ctx>,
    ) -> CodegenResult<BasicValueEnum<'ctx>> {
        let elem_ty = vec.get_type().get_element_type();
        let result = if elem_ty.is_float_type() {
            match op {
                UnOp::FNeg | UnOp::Neg => self
                    .builder
                    .build_float_neg(vec, "vfneg")
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                    .into(),
                UnOp::FAbs | UnOp::Abs => {
                    let intrinsic = Intrinsic::find("llvm.fabs")
                        .ok_or_else(|| CodegenError::Internal("llvm.fabs not found".to_string()))?;
                    let fn_val = intrinsic
                        .get_declaration(self.module.llvm_module(), &[vec.get_type().into()])
                        .ok_or_else(|| {
                            CodegenError::Internal("Failed to get fabs declaration".to_string())
                        })?;
                    self.builder
                        .build_call(fn_val, &[vec.into()], "vfabs")
                        .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                        .try_as_basic_value()
                        .basic()
                        .ok_or_else(|| CodegenError::Internal("vfabs returned void".to_string()))?
                }
                UnOp::Sqrt => {
                    let intrinsic = Intrinsic::find("llvm.sqrt")
                        .ok_or_else(|| CodegenError::Internal("llvm.sqrt not found".to_string()))?;
                    let fn_val = intrinsic
                        .get_declaration(self.module.llvm_module(), &[vec.get_type().into()])
                        .ok_or_else(|| {
                            CodegenError::Internal("Failed to get sqrt declaration".to_string())
                        })?;
                    self.builder
                        .build_call(fn_val, &[vec.into()], "vsqrt")
                        .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                        .try_as_basic_value()
                        .basic()
                        .ok_or_else(|| CodegenError::Internal("vsqrt returned void".to_string()))?
                }
                _ => {
                    return Err(CodegenError::TypeError(format!(
                        "Unsupported float vector unary op {:?}",
                        op
                    )))
                }
            }
        } else {
            // Integer vector
            match op {
                UnOp::Neg => self
                    .builder
                    .build_int_neg(vec, "vneg")
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                    .into(),
                UnOp::Not => self
                    .builder
                    .build_not(vec, "vnot")
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                    .into(),
                _ => {
                    return Err(CodegenError::TypeError(format!(
                        "Unsupported int vector unary op {:?}",
                        op
                    )))
                }
            }
        };
        Ok(result)
    }

    /// Lower a comparison operation.
    fn lower_cmp(
        &mut self,
        op: CmpOp,
        lhs: &Value,
        rhs: &Value,
    ) -> CodegenResult<BasicValueEnum<'ctx>> {
        let l = self.lower_value(lhs)?;
        let r = self.lower_value(rhs)?;

        let result = match (l, r) {
            (BasicValueEnum::IntValue(li), BasicValueEnum::IntValue(ri)) => {
                let pred = match op {
                    CmpOp::Eq => IntPredicate::EQ,
                    CmpOp::Ne => IntPredicate::NE,
                    CmpOp::SLt => IntPredicate::SLT,
                    CmpOp::SLe => IntPredicate::SLE,
                    CmpOp::SGt => IntPredicate::SGT,
                    CmpOp::SGe => IntPredicate::SGE,
                    CmpOp::ULt => IntPredicate::ULT,
                    CmpOp::ULe => IntPredicate::ULE,
                    CmpOp::UGt => IntPredicate::UGT,
                    CmpOp::UGe => IntPredicate::UGE,
                    _ => {
                        return Err(CodegenError::TypeError(
                            "Float comparison on integers".to_string(),
                        ))
                    }
                };
                self.builder
                    .build_int_compare(pred, li, ri, "icmp")
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                    .into()
            }
            (BasicValueEnum::FloatValue(lf), BasicValueEnum::FloatValue(rf)) => {
                let pred = match op {
                    CmpOp::OEq | CmpOp::Eq => FloatPredicate::OEQ,
                    CmpOp::ONe | CmpOp::Ne => FloatPredicate::ONE,
                    CmpOp::OLt | CmpOp::SLt => FloatPredicate::OLT,
                    CmpOp::OLe | CmpOp::SLe => FloatPredicate::OLE,
                    CmpOp::OGt | CmpOp::SGt => FloatPredicate::OGT,
                    CmpOp::OGe | CmpOp::SGe => FloatPredicate::OGE,
                    _ => FloatPredicate::OEQ,
                };
                self.builder
                    .build_float_compare(pred, lf, rf, "fcmp")
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                    .into()
            }
            _ => {
                return Err(CodegenError::TypeError(
                    "Mismatched types for comparison".to_string(),
                ))
            }
        };

        Ok(result)
    }

    /// Lower a select (ternary) operation.
    fn lower_select(
        &mut self,
        cond: &Value,
        then_val: &Value,
        else_val: &Value,
    ) -> CodegenResult<BasicValueEnum<'ctx>> {
        let c = self.lower_value(cond)?;
        let t = self.lower_value(then_val)?;
        let e = self.lower_value(else_val)?;

        let cond_bool = match c {
            BasicValueEnum::IntValue(i) => {
                if i.get_type().get_bit_width() == 1 {
                    i
                } else {
                    self.builder
                        .build_int_compare(
                            IntPredicate::NE,
                            i,
                            i.get_type().const_zero(),
                            "cond.bool",
                        )
                        .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                }
            }
            _ => {
                return Err(CodegenError::TypeError(
                    "Select condition must be boolean".to_string(),
                ))
            }
        };

        let result = self
            .builder
            .build_select(cond_bool, t, e, "select")
            .map_err(|e| CodegenError::LlvmError(e.to_string()))?;

        Ok(result)
    }

    /// Lower a cast operation.
    fn lower_cast(
        &mut self,
        val: &Value,
        target_ty: &LoopType,
    ) -> CodegenResult<BasicValueEnum<'ctx>> {
        let v = self.lower_value(val)?;
        let target = self.loop_type_to_llvm(target_ty)?;

        let result = match (v, target) {
            (BasicValueEnum::IntValue(i), BasicTypeEnum::IntType(ti)) => {
                let src_bits = i.get_type().get_bit_width();
                let dst_bits = ti.get_bit_width();
                if src_bits < dst_bits {
                    self.builder
                        .build_int_s_extend(i, ti, "sext")
                        .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                        .into()
                } else if src_bits > dst_bits {
                    self.builder
                        .build_int_truncate(i, ti, "trunc")
                        .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                        .into()
                } else {
                    v
                }
            }
            (BasicValueEnum::IntValue(i), BasicTypeEnum::FloatType(tf)) => self
                .builder
                .build_signed_int_to_float(i, tf, "sitofp")
                .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                .into(),
            (BasicValueEnum::FloatValue(f), BasicTypeEnum::IntType(ti)) => self
                .builder
                .build_float_to_signed_int(f, ti, "fptosi")
                .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                .into(),
            (BasicValueEnum::FloatValue(f), BasicTypeEnum::FloatType(tf)) => {
                let src_bits = match f.get_type().print_to_string().to_string().as_str() {
                    "half" => 16,
                    "float" => 32,
                    "double" => 64,
                    _ => 64,
                };
                let dst_bits = match tf.print_to_string().to_string().as_str() {
                    "half" => 16,
                    "float" => 32,
                    "double" => 64,
                    _ => 64,
                };
                if src_bits < dst_bits {
                    self.builder
                        .build_float_ext(f, tf, "fpext")
                        .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                        .into()
                } else if src_bits > dst_bits {
                    self.builder
                        .build_float_trunc(f, tf, "fptrunc")
                        .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                        .into()
                } else {
                    v
                }
            }
            _ => {
                return Err(CodegenError::Unsupported(format!(
                    "Cast from {:?} to {:?}",
                    v.get_type(),
                    target
                )))
            }
        };

        Ok(result)
    }

    /// Lower a broadcast operation (scalar to vector).
    fn lower_broadcast(&mut self, val: &Value, width: u8) -> CodegenResult<BasicValueEnum<'ctx>> {
        let scalar = self.lower_value(val)?;

        let vec_ty = match scalar {
            BasicValueEnum::FloatValue(f) => f.get_type().vec_type(width as u32),
            BasicValueEnum::IntValue(i) => i.get_type().vec_type(width as u32),
            _ => {
                return Err(CodegenError::TypeError(
                    "Cannot broadcast non-scalar".to_string(),
                ))
            }
        };

        // Create vector with all same value
        let mut vec = vec_ty.get_undef();
        for i in 0..width {
            let idx = self.llvm_ctx.i32_type().const_int(i as u64, false);
            vec = self
                .builder
                .build_insert_element(vec, scalar, idx, "broadcast")
                .map_err(|e| CodegenError::LlvmError(e.to_string()))?;
        }

        Ok(vec.into())
    }

    /// Lower an extract operation (vector to scalar).
    fn lower_extract(&mut self, vec: &Value, idx: u8) -> CodegenResult<BasicValueEnum<'ctx>> {
        let v = self.lower_value(vec)?;
        let vector = match v {
            BasicValueEnum::VectorValue(vec) => vec,
            _ => {
                return Err(CodegenError::TypeError(
                    "Extract requires vector".to_string(),
                ))
            }
        };

        let index = self.llvm_ctx.i32_type().const_int(idx as u64, false);
        let result = self
            .builder
            .build_extract_element(vector, index, "extract")
            .map_err(|e| CodegenError::LlvmError(e.to_string()))?;

        Ok(result)
    }

    /// Lower an insert operation.
    fn lower_insert(
        &mut self,
        vec: &Value,
        val: &Value,
        idx: u8,
    ) -> CodegenResult<BasicValueEnum<'ctx>> {
        let v = self.lower_value(vec)?;
        let scalar = self.lower_value(val)?;

        let vector = match v {
            BasicValueEnum::VectorValue(vec) => vec,
            _ => {
                return Err(CodegenError::TypeError(
                    "Insert requires vector".to_string(),
                ))
            }
        };

        let index = self.llvm_ctx.i32_type().const_int(idx as u64, false);
        let result = self
            .builder
            .build_insert_element(vector, scalar, index, "insert")
            .map_err(|e| CodegenError::LlvmError(e.to_string()))?;

        Ok(result.into())
    }

    /// Lower a shuffle operation.
    fn lower_shuffle(
        &mut self,
        v1: &Value,
        v2: &Value,
        mask: &[i32],
    ) -> CodegenResult<BasicValueEnum<'ctx>> {
        let vec1 = match self.lower_value(v1)? {
            BasicValueEnum::VectorValue(v) => v,
            _ => {
                return Err(CodegenError::TypeError(
                    "Shuffle requires vectors".to_string(),
                ))
            }
        };
        let vec2 = match self.lower_value(v2)? {
            BasicValueEnum::VectorValue(v) => v,
            _ => {
                return Err(CodegenError::TypeError(
                    "Shuffle requires vectors".to_string(),
                ))
            }
        };

        // Build mask vector
        let i32_ty = self.llvm_ctx.i32_type();
        let mask_vec: Vec<IntValue> = mask
            .iter()
            .map(|&i| {
                if i < 0 {
                    i32_ty.get_undef()
                } else {
                    i32_ty.const_int(i as u64, false)
                }
            })
            .collect();

        let result = self
            .builder
            .build_shuffle_vector(vec1, vec2, VectorType::const_vector(&mask_vec), "shuffle")
            .map_err(|e| CodegenError::LlvmError(e.to_string()))?;

        Ok(result.into())
    }

    /// Lower a vector reduction operation.
    fn lower_vec_reduce(
        &mut self,
        op: ReduceOp,
        val: &Value,
    ) -> CodegenResult<BasicValueEnum<'ctx>> {
        let vec = match self.lower_value(val)? {
            BasicValueEnum::VectorValue(v) => v,
            _ => {
                return Err(CodegenError::TypeError(
                    "VecReduce requires vector".to_string(),
                ))
            }
        };

        let elem_ty = vec.get_type().get_element_type();

        // Use LLVM reduction intrinsics
        let result = if elem_ty.is_float_type() {
            match op {
                ReduceOp::Add => {
                    let intrinsic =
                        Intrinsic::find("llvm.vector.reduce.fadd").ok_or_else(|| {
                            CodegenError::Internal("reduce.fadd not found".to_string())
                        })?;
                    let fn_val = intrinsic
                        .get_declaration(self.module.llvm_module(), &[vec.get_type().into()])
                        .ok_or_else(|| {
                            CodegenError::Internal("Failed to get reduce.fadd".to_string())
                        })?;
                    let zero = elem_ty.into_float_type().const_float(0.0);
                    self.builder
                        .build_call(fn_val, &[zero.into(), vec.into()], "vreduce.fadd")
                        .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                        .try_as_basic_value()
                        .basic()
                        .ok_or_else(|| CodegenError::Internal("reduce returned void".to_string()))?
                }
                ReduceOp::Mul => {
                    let intrinsic =
                        Intrinsic::find("llvm.vector.reduce.fmul").ok_or_else(|| {
                            CodegenError::Internal("reduce.fmul not found".to_string())
                        })?;
                    let fn_val = intrinsic
                        .get_declaration(self.module.llvm_module(), &[vec.get_type().into()])
                        .ok_or_else(|| {
                            CodegenError::Internal("Failed to get reduce.fmul".to_string())
                        })?;
                    let one = elem_ty.into_float_type().const_float(1.0);
                    self.builder
                        .build_call(fn_val, &[one.into(), vec.into()], "vreduce.fmul")
                        .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                        .try_as_basic_value()
                        .basic()
                        .ok_or_else(|| CodegenError::Internal("reduce returned void".to_string()))?
                }
                ReduceOp::Min => {
                    let intrinsic =
                        Intrinsic::find("llvm.vector.reduce.fmin").ok_or_else(|| {
                            CodegenError::Internal("reduce.fmin not found".to_string())
                        })?;
                    let fn_val = intrinsic
                        .get_declaration(self.module.llvm_module(), &[vec.get_type().into()])
                        .ok_or_else(|| {
                            CodegenError::Internal("Failed to get reduce.fmin".to_string())
                        })?;
                    self.builder
                        .build_call(fn_val, &[vec.into()], "vreduce.fmin")
                        .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                        .try_as_basic_value()
                        .basic()
                        .ok_or_else(|| CodegenError::Internal("reduce returned void".to_string()))?
                }
                ReduceOp::Max => {
                    let intrinsic =
                        Intrinsic::find("llvm.vector.reduce.fmax").ok_or_else(|| {
                            CodegenError::Internal("reduce.fmax not found".to_string())
                        })?;
                    let fn_val = intrinsic
                        .get_declaration(self.module.llvm_module(), &[vec.get_type().into()])
                        .ok_or_else(|| {
                            CodegenError::Internal("Failed to get reduce.fmax".to_string())
                        })?;
                    self.builder
                        .build_call(fn_val, &[vec.into()], "vreduce.fmax")
                        .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                        .try_as_basic_value()
                        .basic()
                        .ok_or_else(|| CodegenError::Internal("reduce returned void".to_string()))?
                }
                _ => {
                    return Err(CodegenError::Unsupported(format!(
                        "Float reduction {:?}",
                        op
                    )))
                }
            }
        } else {
            // Integer reductions
            match op {
                ReduceOp::Add => {
                    let intrinsic = Intrinsic::find("llvm.vector.reduce.add").ok_or_else(|| {
                        CodegenError::Internal("reduce.add not found".to_string())
                    })?;
                    let fn_val = intrinsic
                        .get_declaration(self.module.llvm_module(), &[vec.get_type().into()])
                        .ok_or_else(|| {
                            CodegenError::Internal("Failed to get reduce.add".to_string())
                        })?;
                    self.builder
                        .build_call(fn_val, &[vec.into()], "vreduce.add")
                        .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                        .try_as_basic_value()
                        .basic()
                        .ok_or_else(|| CodegenError::Internal("reduce returned void".to_string()))?
                }
                ReduceOp::Mul => {
                    let intrinsic = Intrinsic::find("llvm.vector.reduce.mul").ok_or_else(|| {
                        CodegenError::Internal("reduce.mul not found".to_string())
                    })?;
                    let fn_val = intrinsic
                        .get_declaration(self.module.llvm_module(), &[vec.get_type().into()])
                        .ok_or_else(|| {
                            CodegenError::Internal("Failed to get reduce.mul".to_string())
                        })?;
                    self.builder
                        .build_call(fn_val, &[vec.into()], "vreduce.mul")
                        .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                        .try_as_basic_value()
                        .basic()
                        .ok_or_else(|| CodegenError::Internal("reduce returned void".to_string()))?
                }
                ReduceOp::And => {
                    let intrinsic = Intrinsic::find("llvm.vector.reduce.and").ok_or_else(|| {
                        CodegenError::Internal("reduce.and not found".to_string())
                    })?;
                    let fn_val = intrinsic
                        .get_declaration(self.module.llvm_module(), &[vec.get_type().into()])
                        .ok_or_else(|| {
                            CodegenError::Internal("Failed to get reduce.and".to_string())
                        })?;
                    self.builder
                        .build_call(fn_val, &[vec.into()], "vreduce.and")
                        .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                        .try_as_basic_value()
                        .basic()
                        .ok_or_else(|| CodegenError::Internal("reduce returned void".to_string()))?
                }
                ReduceOp::Or => {
                    let intrinsic = Intrinsic::find("llvm.vector.reduce.or")
                        .ok_or_else(|| CodegenError::Internal("reduce.or not found".to_string()))?;
                    let fn_val = intrinsic
                        .get_declaration(self.module.llvm_module(), &[vec.get_type().into()])
                        .ok_or_else(|| {
                            CodegenError::Internal("Failed to get reduce.or".to_string())
                        })?;
                    self.builder
                        .build_call(fn_val, &[vec.into()], "vreduce.or")
                        .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                        .try_as_basic_value()
                        .basic()
                        .ok_or_else(|| CodegenError::Internal("reduce returned void".to_string()))?
                }
                ReduceOp::Xor => {
                    let intrinsic = Intrinsic::find("llvm.vector.reduce.xor").ok_or_else(|| {
                        CodegenError::Internal("reduce.xor not found".to_string())
                    })?;
                    let fn_val = intrinsic
                        .get_declaration(self.module.llvm_module(), &[vec.get_type().into()])
                        .ok_or_else(|| {
                            CodegenError::Internal("Failed to get reduce.xor".to_string())
                        })?;
                    self.builder
                        .build_call(fn_val, &[vec.into()], "vreduce.xor")
                        .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                        .try_as_basic_value()
                        .basic()
                        .ok_or_else(|| CodegenError::Internal("reduce returned void".to_string()))?
                }
                _ => {
                    return Err(CodegenError::Unsupported(format!(
                        "Integer reduction {:?}",
                        op
                    )))
                }
            }
        };

        Ok(result)
    }

    /// Lower a fused multiply-add operation.
    fn lower_fma(
        &mut self,
        a: &Value,
        b: &Value,
        c: &Value,
    ) -> CodegenResult<BasicValueEnum<'ctx>> {
        let av = self.lower_value(a)?;
        let bv = self.lower_value(b)?;
        let cv = self.lower_value(c)?;

        match (av, bv, cv) {
            (
                BasicValueEnum::FloatValue(af),
                BasicValueEnum::FloatValue(bf),
                BasicValueEnum::FloatValue(cf),
            ) => {
                let intrinsic = Intrinsic::find("llvm.fma")
                    .ok_or_else(|| CodegenError::Internal("llvm.fma not found".to_string()))?;
                let fn_val = intrinsic
                    .get_declaration(self.module.llvm_module(), &[af.get_type().into()])
                    .ok_or_else(|| {
                        CodegenError::Internal("Failed to get fma declaration".to_string())
                    })?;
                let result = self
                    .builder
                    .build_call(fn_val, &[af.into(), bf.into(), cf.into()], "fma")
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                    .try_as_basic_value()
                    .basic()
                    .ok_or_else(|| CodegenError::Internal("fma returned void".to_string()))?;
                Ok(result)
            }
            (
                BasicValueEnum::VectorValue(av),
                BasicValueEnum::VectorValue(bv),
                BasicValueEnum::VectorValue(cv),
            ) => {
                // Vector FMA
                let intrinsic = Intrinsic::find("llvm.fma")
                    .ok_or_else(|| CodegenError::Internal("llvm.fma not found".to_string()))?;
                let fn_val = intrinsic
                    .get_declaration(self.module.llvm_module(), &[av.get_type().into()])
                    .ok_or_else(|| {
                        CodegenError::Internal("Failed to get vector fma declaration".to_string())
                    })?;
                let result = self
                    .builder
                    .build_call(fn_val, &[av.into(), bv.into(), cv.into()], "vfma")
                    .map_err(|e| CodegenError::LlvmError(e.to_string()))?
                    .try_as_basic_value()
                    .basic()
                    .ok_or_else(|| CodegenError::Internal("vfma returned void".to_string()))?;
                Ok(result)
            }
            _ => {
                // Fall back to mul + add
                let mul = self.lower_binary(BinOp::Mul, a, b)?;
                let _mul_val = match mul {
                    BasicValueEnum::FloatValue(_f) => Value::FloatConst(0.0, ScalarType::F64), // placeholder
                    _ => return Err(CodegenError::TypeError("FMA requires floats".to_string())),
                };
                // This is a simplified fallback; in practice we'd need proper handling
                Err(CodegenError::Unsupported(
                    "FMA on non-float types".to_string(),
                ))
            }
        }
    }

    /// Lower a pointer addition.
    fn lower_ptr_add(
        &mut self,
        ptr: &Value,
        offset: &Value,
    ) -> CodegenResult<BasicValueEnum<'ctx>> {
        let ptr_val = self.lower_value(ptr)?;
        let offset_val = self.lower_value(offset)?;

        let ptr_ptr = match ptr_val {
            BasicValueEnum::PointerValue(p) => p,
            _ => {
                return Err(CodegenError::TypeError(
                    "PtrAdd requires pointer".to_string(),
                ))
            }
        };
        let offset_int = self.value_to_int(offset_val)?;

        let i8_ty = self.llvm_ctx.i8_type();
        let result = unsafe {
            self.builder
                .build_gep(i8_ty, ptr_ptr, &[offset_int], "ptr_add")
                .map_err(|e| CodegenError::LlvmError(e.to_string()))?
        };

        Ok(result.into())
    }

    /// Lower a GetPtr operation (get pointer to buffer element).
    fn lower_get_ptr(
        &mut self,
        buffer: BufferId,
        index: &Value,
    ) -> CodegenResult<BasicValueEnum<'ctx>> {
        let base_ptr = self
            .buffers
            .get(&buffer)
            .copied()
            .ok_or_else(|| CodegenError::Internal(format!("Unknown buffer: {:?}", buffer)))?;

        let idx_val = self.lower_value(index)?;
        let idx_int = self.value_to_int(idx_val)?;

        let i8_ty = self.llvm_ctx.i8_type();
        let result = unsafe {
            self.builder
                .build_gep(i8_ty, base_ptr, &[idx_int], "getptr")
                .map_err(|e| CodegenError::LlvmError(e.to_string()))?
        };

        Ok(result.into())
    }

    /// Lower a Value to an LLVM value.
    fn lower_value(&mut self, val: &Value) -> CodegenResult<BasicValueEnum<'ctx>> {
        match val {
            Value::Var(vid, _ty) => self.get_value(*vid),
            Value::IntConst(n, ty) => {
                let int_ty = match ty {
                    ScalarType::Int(bits) | ScalarType::UInt(bits) => {
                        self.llvm_ctx.custom_width_int_type(*bits as u32)
                    }
                    ScalarType::Bool => self.llvm_ctx.bool_type(),
                    _ => {
                        return Err(CodegenError::TypeError(
                            "IntConst with non-int type".to_string(),
                        ))
                    }
                };
                Ok(int_ty.const_int(*n as u64, true).into())
            }
            Value::FloatConst(f, ty) => {
                let float_ty = match ty {
                    ScalarType::Float(16) => self.llvm_ctx.f16_type(),
                    ScalarType::Float(32) => self.llvm_ctx.f32_type(),
                    ScalarType::Float(64) => self.llvm_ctx.f64_type(),
                    _ => {
                        return Err(CodegenError::TypeError(
                            "FloatConst with non-float type".to_string(),
                        ))
                    }
                };
                Ok(float_ty.const_float(*f).into())
            }
            Value::BoolConst(b) => Ok(self.llvm_ctx.bool_type().const_int(*b as u64, false).into()),
            Value::Undef(ty) => {
                let llvm_ty = self.loop_type_to_llvm(ty)?;
                let undef = match llvm_ty {
                    BasicTypeEnum::IntType(t) => t.get_undef().into(),
                    BasicTypeEnum::FloatType(t) => t.get_undef().into(),
                    BasicTypeEnum::VectorType(t) => t.get_undef().into(),
                    BasicTypeEnum::PointerType(t) => t.get_undef().into(),
                    _ => {
                        return Err(CodegenError::Internal(
                            "Cannot create undef for type".to_string(),
                        ))
                    }
                };
                Ok(undef)
            }
        }
    }

    /// Get an already-lowered value by ID.
    fn get_value(&self, vid: ValueId) -> CodegenResult<BasicValueEnum<'ctx>> {
        self.values
            .get(&vid)
            .copied()
            .ok_or_else(|| CodegenError::Internal(format!("Undefined value: {:?}", vid)))
    }

    /// Convert a basic value to an integer.
    fn value_to_int(&self, val: BasicValueEnum<'ctx>) -> CodegenResult<IntValue<'ctx>> {
        match val {
            BasicValueEnum::IntValue(i) => Ok(i),
            _ => Err(CodegenError::TypeError(
                "Expected integer value".to_string(),
            )),
        }
    }
}

/// Lower a complete Loop IR module to LLVM.
pub fn lower_loop_ir<'a>(
    ctx: &'a LlvmContext,
    module: &'a LlvmModule<'a>,
    ir: &LoopIR,
) -> CodegenResult<FunctionValue<'a>> {
    let mut lowering = LoopLowering::new(ctx, module);
    lowering.lower_function(ir)
}

/// Lower multiple Loop IR functions.
pub fn lower_loop_irs<'a>(
    ctx: &'a LlvmContext,
    module: &'a LlvmModule<'a>,
    irs: &[LoopIR],
) -> CodegenResult<Vec<FunctionValue<'a>>> {
    let mut lowering = LoopLowering::new(ctx, module);
    irs.iter().map(|ir| lowering.lower_function(ir)).collect()
}

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

    #[test]
    fn test_loop_lowering_creation() {
        let backend = crate::LlvmBackend::new();
        let config = crate::CodegenConfig::default();
        let ctx = backend.create_context(config).unwrap();
        let module = ctx.create_module("test").unwrap();

        let lowering = LoopLowering::new(&ctx, &module);
        assert!(lowering.values.is_empty());
        assert!(lowering.buffers.is_empty());
    }

    #[test]
    fn test_scalar_type_mapping() {
        let backend = crate::LlvmBackend::new();
        let config = crate::CodegenConfig::default();
        let ctx = backend.create_context(config).unwrap();
        let module = ctx.create_module("test").unwrap();

        let lowering = LoopLowering::new(&ctx, &module);

        // Test i32
        let i32_ty = lowering.scalar_type_to_llvm(ScalarType::Int(32)).unwrap();
        assert!(matches!(i32_ty, BasicTypeEnum::IntType(_)));

        // Test f64
        let f64_ty = lowering.scalar_type_to_llvm(ScalarType::Float(64)).unwrap();
        assert!(matches!(f64_ty, BasicTypeEnum::FloatType(_)));
    }
}