tl-lang 0.1.0

A differentiable programming language with tensor support for machine learning
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
use super::CodeGenerator;
use crate::compiler::ast::*;
use inkwell::types::BasicType;
use inkwell::values::*;

impl<'ctx> CodeGenerator<'ctx> {
    // Helper to infer free indices from implicit tensor equation (RHS)
    // Returns sorted list of unique variable names used as indices but not bound in scope
    fn infer_free_indices(&self, expr: &Expr) -> Vec<String> {
        let mut indices = std::collections::HashSet::new();
        self.collect_indices(expr, &mut indices);

        // Filter out variables that are defined in current scope (e.g. loops)
        // If a variable is NOT in scope, it is a free index (implicit dimension)
        let mut free_indices: Vec<String> = indices
            .into_iter()
            .filter(|idx| {
                // If variable exists in scope, it's a bound value/loop var, NOT a free dimension
                !self.variable_exists(idx)
            })
            .collect();

        free_indices.sort();
        free_indices
    }

    fn collect_indices(&self, expr: &Expr, indices: &mut std::collections::HashSet<String>) {
        match &expr.inner {
            ExprKind::IndexAccess(_, idxs) => {
                for idx in idxs {
                    if let ExprKind::Variable(name) = &idx.inner {
                        indices.insert(name.clone());
                    }
                    // Recursive check? Indices usually simple vars.
                }
            }
            ExprKind::BinOp(lhs, _, rhs) => {
                self.collect_indices(lhs, indices);
                self.collect_indices(rhs, indices);
            }
            ExprKind::UnOp(_, val) => {
                self.collect_indices(val, indices);
            }
            ExprKind::FnCall(_, args)
            | ExprKind::MethodCall(_, _, args)
            | ExprKind::StaticMethodCall(_, _, args) => {
                for arg in args {
                    self.collect_indices(arg, indices);
                }
            }
            ExprKind::TensorLiteral(elems) => {
                for elem in elems {
                    self.collect_indices(elem, indices);
                }
            }
            ExprKind::IfExpr(cond, _, _) => {
                self.collect_indices(cond, indices);
            }
            _ => {}
        }
    }

    fn variable_exists(&self, name: &str) -> bool {
        for scope in self.variables.iter().rev() {
            if scope.contains_key(name) {
                return true;
            }
        }
        false
    }

    pub(crate) fn emit_recursive_unregister(
        &self,
        val: BasicValueEnum<'ctx>,
        ty: &Type,
    ) -> Result<(), String> {
        let unreg_fn = self
            .module
            .get_function("tl_mem_unregister")
            .ok_or("tl_mem_unregister not found")?;

        match ty {
            Type::UserDefined(name) if name == "String" => {} // Skip String
            Type::Tensor(_, _) | Type::Struct(_) | Type::UserDefined(_) => {
                self.builder
                    .build_call(unreg_fn, &[val.into()], "")
                    .map_err(|e| e.to_string())?;
            }
            _ => {}
        }

        match ty {
            Type::Struct(name) | Type::UserDefined(name) => {
                if name == "String" {
                    return Ok(());
                }
                if let Some(struct_def) = self.struct_defs.get(name) {
                    let ptr = val.into_pointer_value();
                    let st_llvm_ty = *self.struct_types.get(name).unwrap();

                    for (i, (_, field_type)) in struct_def.fields.iter().enumerate() {
                        if matches!(
                            field_type,
                            Type::Tensor(_, _) | Type::Struct(_) | Type::UserDefined(_)
                        ) {
                            // GEP
                            let field_ptr = self
                                .builder
                                .build_struct_gep(
                                    st_llvm_ty,
                                    ptr,
                                    i as u32,
                                    &format!("unreg_field_{}", i),
                                )
                                .map_err(|e| e.to_string())?;

                            // Load
                            let load_type = self.context.ptr_type(inkwell::AddressSpace::default());
                            let field_val = self
                                .builder
                                .build_load(load_type, field_ptr, "field_val")
                                .map_err(|e| e.to_string())?;

                            // Recurse
                            self.emit_recursive_unregister(field_val, field_type)?;
                        }
                    }
                }
            }
            _ => {}
        }
        Ok(())
    }

    /// Copy struct contents from src to dst pointer (used for sret)
    pub(crate) fn emit_struct_copy(
        &self,
        dst: inkwell::values::PointerValue<'ctx>,
        src: inkwell::values::PointerValue<'ctx>,
        ty: &Type,
    ) -> Result<(), String> {
        match ty {
            Type::Struct(name) | Type::UserDefined(name) => {
                let struct_def = self
                    .struct_defs
                    .get(name)
                    .ok_or(format!("Struct {} not found", name))?
                    .clone();
                let st_llvm_ty = *self
                    .struct_types
                    .get(name)
                    .ok_or(format!("LLVM struct type {} not found", name))?;

                for (i, (field_name, field_ty)) in struct_def.fields.iter().enumerate() {
                    let src_field_ptr = self
                        .builder
                        .build_struct_gep(st_llvm_ty, src, i as u32, &format!("src_{}", field_name))
                        .map_err(|e| e.to_string())?;
                    let dst_field_ptr = self
                        .builder
                        .build_struct_gep(st_llvm_ty, dst, i as u32, &format!("dst_{}", field_name))
                        .map_err(|e| e.to_string())?;

                    // Load field value from src
                    let llvm_field_ty: inkwell::types::BasicTypeEnum = match field_ty {
                        Type::F32 => self.context.f32_type().into(),
                        Type::I64 => self.context.i64_type().into(),
                        Type::I32 => self.context.i32_type().into(),
                        Type::Bool => self.context.bool_type().into(),
                        Type::Tensor(_, _) | Type::Struct(_) | Type::UserDefined(_) => self
                            .context
                            .ptr_type(inkwell::AddressSpace::default())
                            .into(),
                        _ => self.context.i64_type().into(),
                    };

                    let field_val = self
                        .builder
                        .build_load(llvm_field_ty, src_field_ptr, "field_val")
                        .map_err(|e| e.to_string())?;

                    // Deep Copy Logic:
                    // If field is Tensor/Struct/UserDefined, use emit_deep_clone (Recursively acquire/copy)
                    // Currently emit_deep_clone mallocs new structs, but here we want to store into dst_field_ptr.
                    // But emit_deep_clone returns a Value (Pointer to new struct or Tensor Ptr).
                    // So we store that Value into dst_field_ptr.
                    // This means dst (SRET buffer) will hold Pointers to the Deep Copied fields.
                    // This matches tl semantics (Structs contain pointers).
                    let store_val = if matches!(
                        field_ty,
                        Type::Tensor(_, _) | Type::Struct(_) | Type::UserDefined(_)
                    ) {
                        self.emit_deep_clone(field_val, field_ty)?
                    } else {
                        field_val
                    };

                    // Store to dst
                    self.builder
                        .build_store(dst_field_ptr, store_val)
                        .map_err(|e| e.to_string())?;
                }
                Ok(())
            }
            _ => Err(format!(
                "emit_struct_copy called on non-struct type: {:?}",
                ty
            )),
        }
    }

    pub(crate) fn emit_recursive_free(
        &self,
        val: BasicValueEnum<'ctx>,
        ty: &Type,
    ) -> Result<(), String> {
        match ty {
            Type::Enum(name) => {
                let enum_def = self
                    .enum_defs
                    .get(name)
                    .ok_or(format!("Enum def {} not found", name))?
                    .clone();
                let enum_ty = *self
                    .enum_types
                    .get(name)
                    .ok_or(format!("Enum type {} not found", name))?;

                let ptr = val.into_pointer_value();

                // Runtime Null Check
                let current_block = self.builder.get_insert_block().unwrap();
                let func = current_block.get_parent().unwrap();
                let free_block = self.context.append_basic_block(func, "free_enum");
                let merge_block = self.context.append_basic_block(func, "after_free_enum");

                let is_null = self
                    .builder
                    .build_is_null(ptr, "is_null")
                    .map_err(|e| e.to_string())?;
                self.builder
                    .build_conditional_branch(is_null, merge_block, free_block)
                    .map_err(|e| e.to_string())?;

                self.builder.position_at_end(free_block);

                // Load Tag (Element 0)
                let tag_ptr = self
                    .builder
                    .build_struct_gep(enum_ty, ptr, 0, "tag_ptr")
                    .map_err(|e| e.to_string())?;
                let tag_val = self
                    .builder
                    .build_load(self.context.i32_type(), tag_ptr, "tag")
                    .map_err(|e| e.to_string())?
                    .into_int_value();

                // Prepare Switch
                let after_switch = self.context.append_basic_block(func, "after_enum_switch");
                let mut cases = vec![];

                for (i, variant) in enum_def.variants.iter().enumerate() {
                    let case_block = self
                        .context
                        .append_basic_block(func, &format!("free_variant_{}", variant.name));
                    cases.push((
                        self.context.i32_type().const_int(i as u64, false),
                        case_block,
                    ));
                }

                // Build Switch
                let cases_refs: Vec<(inkwell::values::IntValue, inkwell::basic_block::BasicBlock)> =
                    cases.iter().map(|(i, b)| (*i, *b)).collect();
                self.builder
                    .build_switch(tag_val, after_switch, &cases_refs)
                    .map_err(|e| e.to_string())?;

                // Populate Cases
                for (i, variant) in enum_def.variants.iter().enumerate() {
                    let case_block = cases[i].1;
                    self.builder.position_at_end(case_block);

                    if !variant.fields.is_empty() {
                        // Cast Payload (Element 1 is [i8 x N])
                        let payload_ptr_raw = self
                            .builder
                            .build_struct_gep(enum_ty, ptr, 1, "payload_ptr_raw")
                            .map_err(|e| e.to_string())?;

                        // Reconstruct Variant Struct Type for GEP
                        let mut field_types: Vec<inkwell::types::BasicTypeEnum> = vec![];
                        for (_, ty) in &variant.fields {
                            let llvm_ty = match ty {
                                Type::F32 => self.context.f32_type().into(),
                                Type::I64 => self.context.i64_type().into(),
                                Type::Bool => self.context.bool_type().into(),
                                Type::Tensor(_, _) => self
                                    .context
                                    .ptr_type(inkwell::AddressSpace::default())
                                    .into(),
                                Type::Struct(_) | Type::Enum(_) | Type::UserDefined(_) => self
                                    .context
                                    .ptr_type(inkwell::AddressSpace::default())
                                    .into(),
                                Type::Vec(_) => self
                                    .context
                                    .ptr_type(inkwell::AddressSpace::default())
                                    .into(),
                                _ => self.context.i64_type().into(),
                            };
                            field_types.push(llvm_ty);
                        }
                        let variant_struct_ty = self.context.struct_type(&field_types, false);

                        // Cast payload ptr to variant struct ptr
                        let payload_ptr = self
                            .builder
                            .build_pointer_cast(
                                payload_ptr_raw,
                                self.context.ptr_type(inkwell::AddressSpace::default()), // Opaque ptr
                                "payload_cast",
                            )
                            .unwrap();

                        for (idx, (_, f_ty)) in variant.fields.iter().enumerate() {
                            if matches!(
                                f_ty,
                                Type::Tensor(_, _)
                                    | Type::Struct(_)
                                    | Type::UserDefined(_)
                                    | Type::Enum(_)
                            ) {
                                let f_ptr = self
                                    .builder
                                    .build_struct_gep(
                                        variant_struct_ty,
                                        payload_ptr,
                                        idx as u32,
                                        "field_ptr",
                                    )
                                    .map_err(|e| e.to_string())?;

                                let f_val = self
                                    .builder
                                    .build_load(
                                        self.context.ptr_type(inkwell::AddressSpace::default()),
                                        f_ptr,
                                        "field_val",
                                    )
                                    .map_err(|e| e.to_string())?;

                                self.emit_recursive_free(f_val, f_ty)?;
                            }
                        }
                    }
                    self.builder
                        .build_unconditional_branch(after_switch)
                        .unwrap();
                }

                self.builder.position_at_end(after_switch);
                self.builder
                    .build_unconditional_branch(merge_block)
                    .unwrap();

                self.builder.position_at_end(merge_block);
            }
            Type::Tensor(_, _) | Type::TensorShaped(_, _) => {
                if !val.is_pointer_value() {
                    panic!("Tensor value is not pointer: {:?}", val);
                }
                let ptr = val.into_pointer_value();

                // Runtime Null Check
                let current_block = self.builder.get_insert_block().unwrap();
                let func = current_block.get_parent().unwrap();
                let free_block = self.context.append_basic_block(func, "free_tensor");
                let merge_block = self.context.append_basic_block(func, "after_free");

                let is_null = self
                    .builder
                    .build_is_null(ptr, "is_null")
                    .map_err(|e| e.to_string())?;
                self.builder
                    .build_conditional_branch(is_null, merge_block, free_block)
                    .map_err(|e| e.to_string())?;

                self.builder.position_at_end(free_block);

                let free_fn = self
                    .module
                    .get_function("tl_tensor_release")
                    .ok_or("tl_tensor_release not found")?;
                self.builder
                    .build_call(free_fn, &[val.into()], "")
                    .map_err(|e| e.to_string())?;

                self.builder
                    .build_unconditional_branch(merge_block)
                    .map_err(|e| e.to_string())?;
                self.builder.position_at_end(merge_block);
            }
            Type::Struct(name) | Type::UserDefined(name) => {
                // Skip String
                if name == "String" {
                    return Ok(());
                }

                let struct_def = self
                    .struct_defs
                    .get(name)
                    .ok_or(format!("Struct def {} not found", name))?
                    .clone();
                let struct_ty = *self
                    .struct_types
                    .get(name)
                    .ok_or(format!("Struct type {} not found", name))?;
                let ptr = val.into_pointer_value();

                // Runtime Null Check
                let current_block = self.builder.get_insert_block().unwrap();
                let func = current_block.get_parent().unwrap();
                let free_block = self.context.append_basic_block(func, "free_struct");
                let merge_block = self.context.append_basic_block(func, "after_free");

                let is_null = self
                    .builder
                    .build_is_null(ptr, "is_null")
                    .map_err(|e| e.to_string())?;
                self.builder
                    .build_conditional_branch(is_null, merge_block, free_block)
                    .map_err(|e| e.to_string())?;

                self.builder.position_at_end(free_block);

                for (i, (_, f_ty)) in struct_def.fields.iter().enumerate() {
                    match f_ty {
                        Type::Tensor(_, _) | Type::Struct(_) | Type::UserDefined(_) => {
                            let f_ptr = self
                                .builder
                                .build_struct_gep(struct_ty, ptr, i as u32, "field_gep")
                                .map_err(|e| e.to_string())?;
                            let f_val = self
                                .builder
                                .build_load(
                                    self.context.ptr_type(inkwell::AddressSpace::default()),
                                    f_ptr,
                                    "field_load",
                                )
                                .map_err(|e| e.to_string())?;
                            // Recursively free
                            self.emit_recursive_free(f_val, f_ty)?;
                        }
                        _ => {}
                    }
                }

                self.builder
                    .build_unconditional_branch(merge_block)
                    .map_err(|e| e.to_string())?;
                self.builder.position_at_end(merge_block);
            }
            Type::Vec(inner_ty) => {
                // Only support Vec<Tensor> or Vec<Struct> (pointer-sized elements) for now
                if matches!(
                    inner_ty.as_ref(),
                    Type::Tensor(_, _) | Type::Struct(_) | Type::UserDefined(_)
                ) {
                    let len_fn = self
                        .module
                        .get_function("tl_vec_void_len")
                        .ok_or("tl_vec_void_len not found")?;
                    let get_fn = self
                        .module
                        .get_function("tl_vec_void_get")
                        .ok_or("tl_vec_void_get not found")?;
                    let free_fn = self
                        .module
                        .get_function("tl_vec_void_free")
                        .ok_or("tl_vec_void_free not found")?;

                    let void_ptr_type = self.context.ptr_type(inkwell::AddressSpace::default());
                    let ptr = val.into_pointer_value();
                    let cast_ptr = self
                        .builder
                        .build_pointer_cast(ptr, void_ptr_type, "vec_ptr")
                        .unwrap();

                    // Get Length
                    let len_call = self
                        .builder
                        .build_call(len_fn, &[cast_ptr.into()], "len")
                        .map_err(|e| e.to_string())?;
                    let len_val = match len_call.try_as_basic_value() {
                        inkwell::values::ValueKind::Basic(v) => {
                            if v.is_int_value() {
                                v.into_int_value()
                            } else {
                                return Err(format!("len returned non-int: {:?}", v));
                            }
                        }
                        _ => return Err("len call returned non-basic value".to_string()),
                    };

                    // Loop Setup
                    let current_bb = self.builder.get_insert_block().unwrap();
                    let func = current_bb.get_parent().unwrap();
                    let loop_bb = self.context.append_basic_block(func, "vec_free_loop");
                    let body_bb = self.context.append_basic_block(func, "vec_free_body");
                    let end_bb = self.context.append_basic_block(func, "vec_free_end");

                    self.builder
                        .build_unconditional_branch(loop_bb)
                        .map_err(|e| e.to_string())?;

                    // Loop Header (Condition)
                    self.builder.position_at_end(loop_bb);
                    let i64_type = self.context.i64_type();
                    let idx_phi = self
                        .builder
                        .build_phi(i64_type, "i")
                        .map_err(|e| e.to_string())?;
                    idx_phi.add_incoming(&[(&i64_type.const_int(0, false), current_bb)]);

                    let idx_val = idx_phi.as_basic_value().into_int_value();
                    let cmp = self
                        .builder
                        .build_int_compare(inkwell::IntPredicate::ULT, idx_val, len_val, "cmp")
                        .map_err(|e| e.to_string())?;
                    self.builder
                        .build_conditional_branch(cmp, body_bb, end_bb)
                        .map_err(|e| e.to_string())?;

                    // Loop Body
                    self.builder.position_at_end(body_bb);
                    let elem_ptr_call = self
                        .builder
                        .build_call(get_fn, &[cast_ptr.into(), idx_val.into()], "elem_ptr")
                        .map_err(|e| e.to_string())?;
                    let elem_ptr_void = match elem_ptr_call.try_as_basic_value() {
                        inkwell::values::ValueKind::Basic(v) => v,
                        _ => return Err("elem_ptr call returned non-basic value".to_string()),
                    };

                    let cast_elem = self
                        .builder
                        .build_pointer_cast(
                            elem_ptr_void.into_pointer_value(),
                            void_ptr_type,
                            "cast_elem",
                        )
                        .unwrap();
                    self.emit_recursive_free(cast_elem.into(), inner_ty)?;

                    // Increment and Jump
                    let next_idx = self
                        .builder
                        .build_int_add(idx_val, i64_type.const_int(1, false), "next_i")
                        .map_err(|e| e.to_string())?;
                    idx_phi.add_incoming(&[(&next_idx, body_bb)]);
                    self.builder
                        .build_unconditional_branch(loop_bb)
                        .map_err(|e| e.to_string())?;

                    // End
                    self.builder.position_at_end(end_bb);
                    self.builder
                        .build_call(free_fn, &[cast_ptr.into()], "")
                        .map_err(|e| e.to_string())?;
                }
            }
            _ => {}
        }
        Ok(())
    }

    pub(crate) fn compile_stmt(&mut self, stmt: &Stmt) -> Result<(), String> {
        match &stmt.inner {
            StmtKind::Use { .. } => Ok(()),
            StmtKind::FieldAssign { obj, field, value } => {
                let (obj_val, obj_ty) = self.compile_expr(obj)?;
                let struct_name = match obj_ty {
                    Type::Struct(name) => name,
                    Type::UserDefined(name) => name,
                    _ => return Err(format!("Field assignment on non-struct type {:?}", obj_ty)),
                };

                let simple_struct_name = if struct_name.contains("::") {
                    struct_name.split("::").last().unwrap()
                } else {
                    &struct_name
                };

                let (field_idx, field_type) = {
                    let struct_def = self
                        .struct_defs
                        .get(simple_struct_name)
                        .ok_or(format!("Struct definition for {} not found", struct_name))?;

                    let idx = struct_def
                        .fields
                        .iter()
                        .position(|(n, _)| n == field)
                        .ok_or(format!(
                            "Field {} not found in struct {}",
                            field, struct_name
                        ))?;
                    (idx, struct_def.fields[idx].1.clone())
                };

                if !obj_val.is_pointer_value() {
                    return Err("Cannot assign field of non-pointer struct".into());
                }
                let ptr = obj_val.into_pointer_value();
                let st_llvm_ty = *self.struct_types.get(simple_struct_name).unwrap();

                let field_ptr = self
                    .builder
                    .build_struct_gep(st_llvm_ty, ptr, field_idx as u32, &format!("ptr_{}", field))
                    .map_err(|e| e.to_string())?;

                let (val, _) = self.compile_expr(value)?;

                // Load old value to free it
                if matches!(
                    field_type,
                    Type::Tensor(_, _) | Type::Struct(_) | Type::UserDefined(_)
                ) {
                    let load_type = self.context.ptr_type(inkwell::AddressSpace::default());
                    let current_val = self
                        .builder
                        .build_load(load_type, field_ptr, "old_field_val")
                        .map_err(|e| e.to_string())?
                        .into_pointer_value(); // Valid even if null? Yes.

                    // Fix: Check for Self-Assignment (val == current_val)
                    // If pointers are equal, DO NOT FREE.
                    let val_ptr = val.into_pointer_value();
                    let are_diff = self
                        .builder
                        .build_int_compare(
                            inkwell::IntPredicate::NE,
                            current_val,
                            val_ptr,
                            "cnt_free_diff",
                        )
                        .map_err(|e| e.to_string())?;

                    let free_block = self.context.append_basic_block(
                        self.builder
                            .get_insert_block()
                            .unwrap()
                            .get_parent()
                            .unwrap(),
                        "free_old_val",
                    );
                    let skip_block = self.context.append_basic_block(
                        self.builder
                            .get_insert_block()
                            .unwrap()
                            .get_parent()
                            .unwrap(),
                        "skip_free",
                    );

                    self.builder
                        .build_conditional_branch(are_diff, free_block, skip_block)
                        .unwrap();

                    self.builder.position_at_end(free_block);
                    self.emit_recursive_free(current_val.into(), &field_type)?;
                    self.builder.build_unconditional_branch(skip_block).unwrap();

                    self.builder.position_at_end(skip_block);
                }

                self.builder
                    .build_store(field_ptr, val)
                    .map_err(|e| e.to_string())?;

                // Fix for Use-After-Free: Unregister the NEW value from current scope
                // because it is now owned by the struct.
                let unreg_fn = self.module.get_function("tl_mem_unregister");
                if let Some(f) = unreg_fn {
                    let should_unregister = match &field_type {
                        Type::Tensor(_, _) => true,
                        Type::Struct(_) | Type::UserDefined(_) => true,
                        _ => false,
                    };

                    if should_unregister {
                        self.builder
                            .build_call(f, &[val.into()], "")
                            .map_err(|e| e.to_string())?;
                    }
                }

                Ok(())
            }
            StmtKind::TensorDecl {
                name,
                type_annotation,
                init,
            } => {
                if let Some(expr) = init {
                    let (val_ir, _inferred_ty) = self.ensure_tensor_v2(expr, 0)?;
                    let val_ty = if matches!(type_annotation, Type::Tensor(_, _)) {
                        type_annotation.clone()
                    } else if matches!(type_annotation, Type::ScalarArray(_, _)) {
                        type_annotation.clone()
                    } else {
                        // tensor name: f32 means Tensor<f32, 0>
                        Type::Tensor(Box::new(type_annotation.clone()), 0)
                    };

                    // NOTE: Removed clone to preserve gradients

                    if self.variables.last().unwrap().contains_key(name) {
                        // Start of double-free fix logic
                        let (_var_val, _, should_free) = &self.variables.last().unwrap()[name];

                        if *should_free {
                            // Free logic removed to prevent double-free with MemoryManager.
                            // Old value remains in scope list and will be freed at scope exit.
                        }

                        let ptr = self.variables.last().unwrap()[name].0.into_pointer_value();
                        self.builder
                            .build_store(ptr, val_ir)
                            .map_err(|e| e.to_string())?;

                        // Update variable map to mark as owned (should_free = true)
                        self.variables
                            .last_mut()
                            .unwrap()
                            .insert(name.clone(), (ptr.into(), val_ty, true));
                    } else {
                        let fn_val = self
                            .builder
                            .get_insert_block()
                            .unwrap()
                            .get_parent()
                            .unwrap();
                        let ptr = self.create_entry_block_alloca(fn_val, name, &val_ty);
                        self.builder
                            .build_store(ptr, val_ir)
                            .map_err(|e| e.to_string())?;

                        self.variables
                            .last_mut()
                            .unwrap()
                            .insert(name.clone(), (ptr.into(), val_ty, true));
                    }
                }
                Ok(())
            }
            StmtKind::Let {
                name,
                type_annotation,
                value,
                mutable: _,
            } => {
                // 1. Analyze value for Free Indices (Implicit Tensor Equation)
                let free_indices = self.infer_free_indices(value);

                if !free_indices.is_empty() {
                    // Found free indices -> It's a tensor equation! e.g. let C = A[i, j] * B[j, k];
                    // free_indices will be ["i", "k"] (sorted)
                    // Delegate to compile_tensor_equation
                    // Helper to convert indices string to generator format
                    // Delegate to compile_tensor_equation
                    // Helper to convert indices string to generator format
                    // Note: Implicit equations don't have explicit ranges here, effectively 0..Limit inferred later.
                    // But our AST expects clauses now.
                    // compile_tensor_equation expects `&[ComprehensionClause]`.
                    // But wait, `compile_tensor_equation` generates loops FROM clauses.
                    // Implicit equations: `let C = A[i]`. LHS=C (no explicit indices). RHS has free `i`.
                    // We treat this as `[ i | A[i] ]`.
                    // So we need to synthesize `indices=["i"]` and `clauses=[Generator("i", IMPLICIT)]`?
                    // No, existing logic for explicit comprehension has explicit ranges.
                    // Implicit reduction/equation relies on bounds inference.

                    // We should invoke `compile_tensor_equation` with:
                    // indices = free_indices
                    // clauses = [] (No explicit generators)
                    // body = value

                    // But `compile_tensor_equation` iterates `clauses` to generate loops!
                    // If clauses is empty, it generates NO LOOPS.
                    // This breaks implicit equations.

                    // Fix: `compile_tensor_equation` accepts `indices` (LHS/Output) AND `clauses`.
                    // If `clauses` is empty, it should try to infer loops from `indices` + `free vars`?
                    // OR: We must synthesize clauses effectively.
                    // We don't know bounds easily here without analysis.
                    // Actually, `compile_tensor_equation` does `self.enter_scope()` and bounds lookup.
                    // But it expects clauses to drive the loops.

                    // REVERT/ADJUSTMENT to `compile_tensor_equation`:
                    // It should take `indices: &[String]` (Output dims) and `clauses: &[Clause]`.
                    // It should ALSO take `implicit_indices: &[String]`?
                    // Or we just synthesize clauses.
                    // But we can't synthesize semantic `Expr` for bounds easily.

                    // Let's modify `compile_tensor_equation` to accept an optional "Force Loops for these indices" argument?
                    // Or better: Use `ExprKind::TensorComprehension` AST node effectively.
                    // Implicit equation `C = A[i]` is semantically `C = [i | A[i]]` where `i` range is inferred.
                    // Our new syntax supports `[i | A[i]]` (Implicit body? No, implicit generator?).
                    // `i` is in LHS. RHS has no generator for `i`.
                    // Logic must handle "LHS index NOT in generators".
                    // Existing logic (old): matched `(idx, range_opt)`. If `range_opt` None, inferred.
                    // New logic: `Clause::Generator` HAS `range: Expr`. Mandatory.

                    // So we need a way to represent "Generator with Implicit Range" in `Clause`.
                    // We can add `ExprKind::ImplicitRange`? Or `Option<Expr>` in `Generator` variant?

                    // Let's update `ComprehensionClause` definition to allow optional range?
                    // `Generator { name: String, range: Option<Expr> }`.
                    // This restores compatibility with implicit generators.

                    // Implicit equation `C = A[i]` is semantically `C = [i | { A[i] }]` (Empty clauses).
                    // `compile_tensor_equation` will detect that `i` is in `indices` but not in `clauses`,
                    // and will infer the range from `body` (value).

                    let clauses: Vec<ComprehensionClause> = Vec::new();

                    return self
                        .compile_tensor_equation(name, &free_indices, &clauses, Some(value))
                        .map_err(|e| e.to_string());
                }

                let (mut val_ir, mut val_ty) = self.compile_expr(value)?;

                // Ownership: Shared. The temporary (value) remains in scope and will be released at scope exit.
                // The variable (name) acquires a NEW reference via deep_clone below.
                // We do NOT unregister the temporary. Ref 1 (Temp) + Ref 1 (Var) = 2.
                // Temp Scope Exit -> -1. Var Scope Exit -> -1. Total 0. Safe.

                // Removed: Move Semantics logic.
                // We default to CLONE for variables (see below), so we should NOT disable cleanup for the source.

                // Convert ScalarArray to Tensor if explicitly requested as Tensor
                if let Some(target_ty) = type_annotation {
                    if matches!(target_ty, Type::Tensor(_, _))
                        && matches!(val_ty, Type::ScalarArray(_, _))
                    {
                        let (v, _t) = self.ensure_tensor_v2(value, 0)?;
                        val_ir = v;
                        val_ty = target_ty.clone();
                    }
                }

                // Variable Assignment: Deep Clone (Struct Copy + Tensor Acquire)
                // Optimization: R-value Move Semantics
                // If the value is a temporary (FnCall, BinOp, etc), we take ownership (Move).
                // If the value is an L-value (Variable, FieldAccess), we must Copy (Acquire/Clone).

                let is_rvalue = matches!(
                    &value.inner,
                    ExprKind::FnCall(_, _)
                        | ExprKind::MethodCall(_, _, _)
                        | ExprKind::StaticMethodCall(_, _, _)
                        | ExprKind::BinOp(_, _, _)
                        | ExprKind::UnOp(_, _)
                        | ExprKind::TensorLiteral(_)
                        | ExprKind::IfExpr(_, _, _) // Treating IfExpr as R-value (Assumes IfExpr logic ensures failure-safety)
                        | ExprKind::Block(_)
                );

                let should_deep_clone = match &val_ty {
                    Type::Tensor(_, _) => !is_rvalue, // Clone only if L-value
                    Type::Struct(_) | Type::UserDefined(_) => {
                        // Structs/UserDefined: Pointer copy vs Deep Clone
                        // If R-value, we own the pointer. Move.
                        !is_rvalue
                    }
                    _ => false,
                };

                if should_deep_clone {
                    val_ir = self.emit_deep_clone(val_ir, &val_ty)?;
                }

                let current_function = self
                    .builder
                    .get_insert_block()
                    .unwrap()
                    .get_parent()
                    .unwrap();

                // Check for shadowing in CURRENT scope
                if let Some(scope) = self.variables.last_mut() {
                    if let Some((_old_ptr, _old_ty, should_free)) = scope.get(name) {
                        // If we are shadowing, and the old value effectively goes away (we overwrite the map entry),
                        // we MUST free it if it's a tensor and we own it.
                        // NOTE: In Rust, shadowing doesn't drop the old var immediately, it lives until end of scope.
                        // BUT in our compiler, we only track variables by name in the map.
                        // If we overwrite the map entry, we lose access to the old variable.
                        // So for our language semantics, we treat shadowing as "replacing".
                        // Use-case: `let x = ...; let x = ...;`
                        if *should_free {
                            // CRITICAL FIX: Release shadowed value.
                            // Shadowing destroys the old variable handle, so we must release its ownership.
                            if let Some(release_fn) = self.module.get_function("tl_tensor_release")
                            {
                                // Load the actual pointer value from the alloca
                                let ptr_type =
                                    self.context.ptr_type(inkwell::AddressSpace::default());
                                let old_value = self
                                    .builder
                                    .build_load(
                                        ptr_type,
                                        _old_ptr.into_pointer_value(),
                                        "old_shadowed",
                                    )
                                    .map_err(|e| e.to_string())?;

                                self.builder
                                    .build_call(release_fn, &[old_value.into()], "")
                                    .map_err(|e| e.to_string())?;
                            }
                        }
                    }
                }

                let alloca = self.create_entry_block_alloca(current_function, name, &val_ty);
                self.builder
                    .build_store(alloca, val_ir)
                    .map_err(|e| e.to_string())?;

                self.variables
                    .last_mut()
                    .unwrap()
                    .insert(name.clone(), (alloca.into(), val_ty.clone(), true)); // Store pointer and type
                                                                                  /*
                                                                                  match &val_ty {
                                                                                      Type::Tensor(_, _) => {
                                                                                          if let Some(register_fn) =
                                                                                              self.module.get_function("tl_mem_register_tensor")
                                                                                          {
                                                                                              // Load the pointer from alloca (val_ir is the value to store, so it's the pointer)
                                                                                              // val_ir is the T* (OpaqueTensor*)
                                                                                              self.builder
                                                                                                  .build_call(register_fn, &[val_ir.into()], "")
                                                                                                  .map_err(|e| e.to_string())?;
                                                                                          }
                                                                                      }
                                                                                      Type::Struct(_) | Type::UserDefined(_) => {
                                                                                          /*
                                                                                          if let Some(register_fn) = self.module.get_function("tl_mem_register_struct") {
                                                                                              self.builder
                                                                                                  .build_call(register_fn, &[val_ir.into()], "")
                                                                                                  .map_err(|e| e.to_string())?;
                                                                                          }
                                                                                          */
                                                                                      }
                                                                                      _ => {}
                                                                                  }
                                                                                  */
                Ok(())
            }
            StmtKind::Return(expr_opt) => {
                if let Some(expr) = expr_opt {
                    // If returning a variable, mark it as moved (should_free = false)
                    if let ExprKind::Variable(name) = &expr.inner {
                        for scope in self.variables.iter_mut().rev() {
                            if let Some(entry) = scope.get_mut(name) {
                                entry.2 = false;
                                break;
                            }
                        }
                    }
                    let (val, ty) = self.compile_expr(expr)?;

                    // Check if this is a struct return (uses sret)
                    let uses_sret = false; /* SRET DISABLED */

                    // IMPORTANT: Do NOT unregister. Instead Acquire/Copy to preserve for caller.
                    // If we unregister, it releases (decrements refcount).
                    // If we exit scope, it releases (decrements refcount).
                    // Result: Double decrement -> Free.
                    // Fix:
                    // 1. For SRET: emit_struct_copy (above) now does Deep Copy + Acquire.
                    // 2. For Tensor Return: We must Acquire.
                    // 3. For Struct Return: We must Unregister to prevent exit_scope from freeing it.
                    if !uses_sret {
                        match &ty {
                            Type::Tensor(_, _) => {
                                if let Some(acquire_fn) =
                                    self.module.get_function("tl_tensor_acquire")
                                {
                                    let ptr = val.into_pointer_value();
                                    let void_ptr_type =
                                        self.context.ptr_type(inkwell::AddressSpace::default());
                                    let cast_ptr = self
                                        .builder
                                        .build_pointer_cast(ptr, void_ptr_type, "cast_aq_ret")
                                        .unwrap();
                                    self.builder
                                        .build_call(acquire_fn, &[cast_ptr.into()], "")
                                        .unwrap();
                                }
                            }
                            Type::Struct(_) | Type::UserDefined(_) => {
                                // CRITICAL FIX: Unregister struct from scope to transfer ownership to caller.
                                // Without this, exit_scope will free the struct before the caller can use it.
                                if let Some(unreg_fn) =
                                    self.module.get_function("tl_mem_unregister")
                                {
                                    let ptr = val.into_pointer_value();
                                    let void_ptr_type =
                                        self.context.ptr_type(inkwell::AddressSpace::default());
                                    let cast_ptr = self
                                        .builder
                                        .build_pointer_cast(ptr, void_ptr_type, "cast_unreg_ret")
                                        .unwrap();
                                    self.builder
                                        .build_call(unreg_fn, &[cast_ptr.into()], "")
                                        .unwrap();
                                }
                            }
                            _ => {}
                        }
                    }

                    if uses_sret {
                        // CRITICAL: Copy to sret BEFORE cleanup to avoid stale pointer access
                        // Get the sret pointer (first parameter)
                        let current_fn = self
                            .builder
                            .get_insert_block()
                            .and_then(|b| b.get_parent())
                            .ok_or("No current function")?;
                        let sret_ptr = current_fn
                            .get_nth_param(0)
                            .ok_or("Sret function missing sret parameter")?
                            .into_pointer_value();

                        // Copy struct contents to sret pointer BEFORE cleanup
                        let src_ptr = val.into_pointer_value();
                        self.emit_struct_copy(sret_ptr, src_ptr, &ty)?;
                        self.emit_all_scopes_cleanup();
                        self.builder.build_return(None).map_err(|e| e.to_string())?;
                    } else {
                        // Normal return: cleanup then return value
                        self.emit_all_scopes_cleanup();
                        self.builder
                            .build_return(Some(&val))
                            .map_err(|e| e.to_string())?;
                    }
                } else {
                    // return; (Void return)
                    self.emit_all_scopes_cleanup();
                    self.builder.build_return(None).map_err(|e| e.to_string())?;
                }
                Ok(())
            }
            StmtKind::Assign {
                name,
                indices,
                op,
                value,
            } => {
                if let Some(idxs) = indices {
                    if !idxs.is_empty() {
                        if *op != AssignOp::Assign {
                            return Err(
                                "Only direct assignment (=) supported for indexed assignment"
                                    .into(),
                            );
                        }

                        // 1. Resolve variable
                        let mut found_var_ptr = None;
                        let mut found_var_type = None;
                        for scope in self.variables.iter().rev() {
                            if let Some((v, t, _)) = scope.get(name) {
                                found_var_ptr = Some(*v);
                                found_var_type = Some(t.clone());
                                break;
                            }
                        }
                        let var_ptr =
                            found_var_ptr.ok_or(format!("Variable {} not found", name))?;
                        let var_type =
                            found_var_type.ok_or(format!("Variable {} not found", name))?;

                        // 2. Compile Value
                        let (val_ir, val_ty) = self.compile_expr(value)?;

                        match var_type {
                            Type::ScalarArray(elem_ty, _len) => {
                                if idxs.len() != 1 {
                                    return Err("ScalarArray only supports 1D indexing".into());
                                }
                                // Load Array Pointer
                                let ptr_type =
                                    self.context.ptr_type(inkwell::AddressSpace::default());
                                let array_ptr = self
                                    .builder
                                    .build_load(ptr_type, var_ptr.into_pointer_value(), "arr_ptr")
                                    .map_err(|e| e.to_string())?
                                    .into_pointer_value();

                                // Compile Index
                                let (idx_val, idx_ty) = self.compile_expr(&idxs[0])?;
                                let idx_int = match idx_ty {
                                    Type::I64 => idx_val.into_int_value(),
                                    Type::I32 => self
                                        .builder
                                        .build_int_z_extend(
                                            idx_val.into_int_value(),
                                            self.context.i64_type(),
                                            "zext",
                                        )
                                        .unwrap(),
                                    _ => return Err("Index must be integer".into()),
                                };

                                // GEP
                                let elem_llvm_ty: inkwell::types::BasicTypeEnum =
                                    match elem_ty.as_ref() {
                                        Type::I64 => self.context.i64_type().into(),
                                        Type::F32 => self.context.f32_type().into(),
                                        _ => self.context.i64_type().into(),
                                    };

                                let elem_ptr = unsafe {
                                    self.builder
                                        .build_in_bounds_gep(
                                            elem_llvm_ty,
                                            array_ptr,
                                            &[idx_int],
                                            "elem_ptr",
                                        )
                                        .map_err(|e| e.to_string())?
                                };

                                // Cast logic
                                // (If needed, e.g. i64 -> f32?)
                                // Assume types match for now or basic int/float check above

                                self.builder
                                    .build_store(elem_ptr, val_ir)
                                    .map_err(|e| e.to_string())?;
                                return Ok(());
                            }
                            Type::Tensor(_, _) => {
                                // Compile Indices to Array
                                let i64_type = self.context.i64_type();
                                let idx_array_type = i64_type.array_type(idxs.len() as u32);

                                let current_block = self.builder.get_insert_block().unwrap();
                                let function = current_block.get_parent().unwrap();
                                let entry_block = function.get_first_basic_block().unwrap();
                                let entry_builder = self.context.create_builder();
                                if let Some(first_instr) = entry_block.get_first_instruction() {
                                    entry_builder.position_before(&first_instr);
                                } else {
                                    entry_builder.position_at_end(entry_block);
                                }
                                let idx_ptr_alloca = entry_builder
                                    .build_alloca(idx_array_type, "indices_arr")
                                    .map_err(|e| e.to_string())?;

                                for (i, idx_expr) in idxs.iter().enumerate() {
                                    let (val, ty) = self.compile_expr(idx_expr)?;
                                    let int_val = match ty {
                                        Type::I64 => val.into_int_value(),
                                        Type::I32 => self
                                            .builder
                                            .build_int_z_extend(
                                                val.into_int_value(),
                                                i64_type,
                                                "ext",
                                            )
                                            .unwrap(),
                                        _ => return Err("Index must be int".into()),
                                    };
                                    let ptr = unsafe {
                                        self.builder
                                            .build_in_bounds_gep(
                                                idx_array_type,
                                                idx_ptr_alloca,
                                                &[
                                                    i64_type.const_int(0, false),
                                                    i64_type.const_int(i as u64, false),
                                                ],
                                                "idx_ptr",
                                            )
                                            .map_err(|e| e.to_string())?
                                    };
                                    self.builder
                                        .build_store(ptr, int_val)
                                        .map_err(|e| e.to_string())?;
                                }

                                // Load current tensor ptr
                                let load_type =
                                    self.context.ptr_type(inkwell::AddressSpace::default());
                                let current_tensor = self
                                    .builder
                                    .build_load(load_type, var_ptr.into_pointer_value(), "curr_t")
                                    .unwrap();

                                // Call set fxn
                                let set_fn = self
                                    .module
                                    .get_function("tl_tensor_set_f32_md")
                                    .ok_or("tl_tensor_set_f32_md not found")?;

                                let idx_ptr_cast = self
                                    .builder
                                    .build_pointer_cast(
                                        idx_ptr_alloca,
                                        self.context.ptr_type(inkwell::AddressSpace::default()),
                                        "idx_cast",
                                    )
                                    .unwrap();

                                // Ensure Val is F32
                                let f32_val = match val_ty {
                                    Type::F32 => val_ir.into_float_value(),
                                    Type::I64 => self
                                        .builder
                                        .build_signed_int_to_float(
                                            val_ir.into_int_value(),
                                            self.context.f32_type(),
                                            "f32_cast",
                                        )
                                        .unwrap(),
                                    _ => {
                                        return Err(
                                            "Assignment value must be convertible to f32".into()
                                        )
                                    }
                                };

                                let call = self
                                    .builder
                                    .build_call(
                                        set_fn,
                                        &[
                                            current_tensor.into(),
                                            idx_ptr_cast.into(),
                                            i64_type.const_int(idxs.len() as u64, false).into(),
                                            f32_val.into(),
                                        ],
                                        "new_t",
                                    )
                                    .unwrap();

                                let new_tensor_ptr = match call.try_as_basic_value() {
                                    inkwell::values::ValueKind::Basic(v) => v,
                                    _ => return Err("tl_tensor_set_f32_md returned void".into()),
                                };

                                // Free Old Tensor
                                let free_fn = self
                                    .module
                                    .get_function("tl_tensor_free")
                                    .ok_or("tl_tensor_free not found")?;
                                self.builder
                                    .build_call(free_fn, &[current_tensor.into()], "")
                                    .map_err(|e| e.to_string())?;

                                // Store New Tensor
                                self.builder
                                    .build_store(var_ptr.into_pointer_value(), new_tensor_ptr)
                                    .map_err(|e| e.to_string())?;

                                // Scope Promotion / Registration
                                if !self.is_outer_scope(name) {
                                    self.emit_register_tensor(new_tensor_ptr, &var_type)?;
                                }

                                return Ok(());
                            }
                            _ => {
                                return Err(
                                    "Indexed assignment only supported for Tensor and ScalarArray"
                                        .into(),
                                )
                            }
                        }
                    }
                }

                // Compile value first
                let (val_base, val_type) = self.compile_expr(value)?;

                // Clone if alias (initializing from variable or field) to prevent sharing pointers
                let val = if matches!(
                    &value.inner,
                    ExprKind::Variable(_) | ExprKind::FieldAccess(_, _)
                ) {
                    if let Type::Tensor(_, _) = val_type {
                        let clone_fn = self
                            .module
                            .get_function("tl_tensor_clone")
                            .ok_or("tl_tensor_clone not found")?;
                        let call = self
                            .builder
                            .build_call(clone_fn, &[val_base.into()], "cloned")
                            .map_err(|e| e.to_string())?;
                        match call.try_as_basic_value() {
                            inkwell::values::ValueKind::Basic(v) => v,
                            _ => return Err("Clone returned void".into()),
                        }
                    } else {
                        val_base
                    }
                } else {
                    val_base
                };

                // Lookup variable
                let mut found_var_ptr = None;
                let mut found_var_type = None;
                let mut found_should_free = false;
                for scope in self.variables.iter().rev() {
                    if let Some((v, t, sf)) = scope.get(name) {
                        found_var_ptr = Some(*v);
                        found_var_type = Some(t.clone());
                        found_should_free = *sf;
                        break;
                    }
                }

                let var_ptr = found_var_ptr.ok_or(format!("Variable {} not found", name))?;
                let var_type = found_var_type.ok_or(format!("Variable {} not found", name))?;

                // Fix: Ownership Transfer (Runtime -> Compiler)
                // Unregister the new value (RHS) to take ownership.
                match val_type {
                    Type::Struct(_) | Type::UserDefined(_) | Type::Tensor(_, _) => {
                        if let Some(unreg_fn) = self.module.get_function("tl_mem_unregister") {
                            let ptr = val.into_pointer_value();
                            let cast_ptr = self
                                .builder
                                .build_pointer_cast(
                                    ptr,
                                    self.context.ptr_type(inkwell::AddressSpace::default()),
                                    "cast_unreg_assign",
                                )
                                .unwrap();
                            self.builder
                                .build_call(unreg_fn, &[cast_ptr.into()], "")
                                .unwrap();
                        }
                    }
                    _ => {}
                }

                if let Some(idxs) = indices {
                    if !idxs.is_empty() {
                        return Err("Indexed assignment not yet supported".into());
                    }
                }

                // Handle assignment operator (e.g., +=, -=, =)
                let final_val = match op {
                    AssignOp::Assign => {
                        // Free old value if it is a Struct OR Tensor
                        if matches!(
                            var_type,
                            Type::Struct(_) | Type::UserDefined(_) | Type::Tensor(_, _)
                        ) {
                            let load_type = self.context.ptr_type(inkwell::AddressSpace::default());
                            let current_val = self
                                .builder
                                .build_load(
                                    load_type,
                                    var_ptr.into_pointer_value(),
                                    "old_val_to_free",
                                )
                                .map_err(|e| e.to_string())?
                                .into_pointer_value();

                            // Only free if not null
                            let null_ptr = load_type.const_null();
                            let is_not_null = self
                                .builder
                                .build_int_compare(
                                    inkwell::IntPredicate::NE,
                                    current_val,
                                    null_ptr,
                                    "is_not_null",
                                )
                                .map_err(|e| e.to_string())?;

                            // AND also check if we own it
                            let should_free_val = self
                                .context
                                .bool_type()
                                .const_int(found_should_free as u64, false);

                            // AND check if pointers differ (prevent self-free on return self)
                            let new_ptr = val.into_pointer_value();
                            let are_diff = self
                                .builder
                                .build_int_compare(
                                    inkwell::IntPredicate::NE,
                                    current_val,
                                    new_ptr,
                                    "are_diff",
                                )
                                .map_err(|e| e.to_string())?;

                            let can_free_1 = self
                                .builder
                                .build_and(is_not_null, should_free_val, "can_free_1")
                                .unwrap();
                            let can_free = self
                                .builder
                                .build_and(can_free_1, are_diff, "can_free")
                                .unwrap();

                            let free_block = self.context.append_basic_block(
                                self.builder
                                    .get_insert_block()
                                    .unwrap()
                                    .get_parent()
                                    .unwrap(),
                                "free_struct",
                            );
                            let continue_block = self.context.append_basic_block(
                                self.builder
                                    .get_insert_block()
                                    .unwrap()
                                    .get_parent()
                                    .unwrap(),
                                "continue_after_free",
                            );

                            self.builder
                                .build_conditional_branch(can_free, free_block, continue_block)
                                .map_err(|e| e.to_string())?;

                            // Free block
                            self.builder.position_at_end(free_block);

                            // Recursive free fields of the OLD struct
                            self.emit_recursive_free(current_val.into(), &var_type)?;

                            // Also unregister the struct shell itself so Runtime doesn't track it
                            if let Some(unreg_fn) = self.module.get_function("tl_mem_unregister") {
                                let cast_ptr = self
                                    .builder
                                    .build_pointer_cast(
                                        current_val,
                                        self.context.ptr_type(inkwell::AddressSpace::default()),
                                        "cast_unreg_struct",
                                    )
                                    .unwrap();
                                let _ = self.builder.build_call(unreg_fn, &[cast_ptr.into()], "");
                            }

                            // Note: We don't free(malloc) the struct shell. It leaks (small).

                            self.builder
                                .build_unconditional_branch(continue_block)
                                .map_err(|e| e.to_string())?;

                            // Continue block
                            self.builder.position_at_end(continue_block);
                        }

                        // Duplicate Tensor free logic removed

                        let new_val_basic = val;

                        // CHECK SCOPE PROMOTION
                        if self.is_outer_scope(name) {
                            // If assigning to outer scope, we must "promote" (unregister) the new value
                            // so it isn't freed when the current inner scope exits.
                            // This effectively leaks it (until program end), but prevents Use-After-Free.

                            let unreg_fn = self.module.get_function("tl_mem_unregister");

                            if let Some(f) = unreg_fn {
                                if let Type::Tensor(_, _) = var_type {
                                    self.builder
                                        .build_call(f, &[new_val_basic.into()], "")
                                        .map_err(|e| e.to_string())?;
                                } else if matches!(var_type, Type::Struct(_) | Type::UserDefined(_))
                                {
                                    // Recursive unregister for struct fields
                                    self.emit_recursive_unregister(new_val_basic, &var_type)?;

                                    // Also unregister the struct pointer itself
                                    self.builder
                                        .build_call(f, &[new_val_basic.into()], "")
                                        .map_err(|e| e.to_string())?;
                                }
                            }
                        }

                        new_val_basic
                    }
                    AssignOp::AddAssign => {
                        // Load current value
                        let load_type: inkwell::types::BasicTypeEnum = match var_type {
                            Type::I64 => self.context.i64_type().into(),
                            Type::F32 => self.context.f32_type().into(),
                            Type::Bool => self.context.bool_type().into(),
                            Type::Tensor(_, _) => self
                                .context
                                .ptr_type(inkwell::AddressSpace::default())
                                .into(),
                            _ => {
                                return Err(format!(
                                    "Unsupported type for assignment operation: {:?}",
                                    var_type
                                ))
                            }
                        };

                        let current_val = self
                            .builder
                            .build_load(
                                load_type,
                                var_ptr.into_pointer_value(),
                                &format!("{}_current", name),
                            )
                            .map_err(|e| e.to_string())?;

                        // For +=, we are computing New = Old + Val.
                        // The `compile_bin_op` creates a NEW tensor result.
                        // We must free the OLD `current_val` after we use it (or rely on `dl_tensor_add` to NOT consume it? Candle ops return new tensors).
                        // Current `tl_tensor_add` returns new tensor.
                        // So `current_val` (pointer to old tensor) is now orphaned unless we free it.
                        // BUT: `compile_bin_op` emits `tl_tensor_add(lhs, rhs)`.
                        // Does `tl_tensor_add` take ownership? No, specific implementation just reads.
                        // So we MUST free `current_val` here before overwriting `var_ptr`.

                        // Free logic removed.

                        let (op_res, _) = self.compile_bin_op(
                            current_val,
                            var_type.clone(),
                            val,
                            val_type,
                            BinOp::Add,
                        )?;
                        op_res
                    }
                    AssignOp::SubAssign => {
                        // SubAssign logic (In-Place for Tensor)
                        if let Type::Tensor(_, _) = var_type {
                            // Load current val
                            let load_type = self.context.ptr_type(inkwell::AddressSpace::default());
                            let current_val = self
                                .builder
                                .build_load(
                                    load_type,
                                    var_ptr.into_pointer_value(),
                                    &format!("{}_current", name),
                                )
                                .map_err(|e| e.to_string())?;

                            // Call sub_assign
                            let sub_assign_fn =
                                self.module.get_function("tl_tensor_sub_assign").unwrap();
                            self.builder
                                .build_call(sub_assign_fn, &[current_val.into(), val.into()], "")
                                .map_err(|e| e.to_string())?;

                            // Return early to avoid store (in-place)
                            return Ok(());
                        } else {
                            return Err("SubAssign -= only supported for Tensors currently via in-place optimization".into());
                        }
                    }
                    _ => return Err(format!("Unsupported assignment op: {:?}", op)),
                };

                self.builder
                    .build_store(var_ptr.into_pointer_value(), final_val)
                    .map_err(|e| e.to_string())?;
                Ok(())
            }
            StmtKind::If {
                cond,
                then_block,
                else_block,
            } => {
                let parent = self
                    .builder
                    .get_insert_block()
                    .unwrap()
                    .get_parent()
                    .unwrap();

                let (cond_val, _) = self.compile_expr(cond)?;
                let cond_int = self
                    .builder
                    .build_int_cast(
                        cond_val.into_int_value(),
                        self.context.bool_type(),
                        "boolcast",
                    )
                    .unwrap();

                let then_bb = self.context.append_basic_block(parent, "then");
                let else_bb = self.context.append_basic_block(parent, "else");
                let merge_bb = self.context.append_basic_block(parent, "merge");

                self.builder
                    .build_conditional_branch(cond_int, then_bb, else_bb)
                    .unwrap();

                // Then
                self.builder.position_at_end(then_bb);
                self.enter_scope();
                for stmt in then_block {
                    self.compile_stmt(stmt)?;
                }
                // Branch to merge if current block has no terminator
                // Use get_insert_block() because nested statements may have changed current block
                // Check current block
                let current_block = self.builder.get_insert_block().unwrap();
                if current_block.get_terminator().is_none() {
                    self.exit_scope();
                    self.builder.build_unconditional_branch(merge_bb).unwrap();
                } else {
                    self.exit_scope();
                }

                // Else
                self.builder.position_at_end(else_bb);
                self.enter_scope();
                if let Some(else_stmts) = else_block {
                    for stmt in else_stmts {
                        self.compile_stmt(stmt)?;
                    }
                }
                // Check current block (not else_bb) since nested if may have changed it
                let current_block = self.builder.get_insert_block().unwrap();
                if current_block.get_terminator().is_none() {
                    self.exit_scope();
                    self.builder.build_unconditional_branch(merge_bb).unwrap();
                } else {
                    self.exit_scope();
                }

                // Merge
                self.builder.position_at_end(merge_bb);
                Ok(())
            }
            StmtKind::For {
                loop_var,
                iterator,
                body,
            } => {
                let parent = self
                    .builder
                    .get_insert_block()
                    .unwrap()
                    .get_parent()
                    .unwrap();

                let i64_type = self.context.i64_type();

                // Check if iterator is a range (BinOp with ".." conceptually - we detect 0..n pattern)
                // Or if it's a tensor/variable
                let (start_val, end_val, is_tensor_iter) = match &iterator.inner {
                    ExprKind::Range(start, end) => {
                        let (s, _) = self.compile_expr(start)?;
                        let (e, _) = self.compile_expr(end)?;
                        (s.into_int_value(), e.into_int_value(), false)
                    }
                    ExprKind::FnCall(name, args) if name == "range" => {
                        // range(start, end)
                        if args.len() != 2 {
                            return Err("range() requires 2 arguments".into());
                        }
                        let (s, _) = self.compile_expr(&args[0])?;
                        let (e, _) = self.compile_expr(&args[1])?;
                        (s.into_int_value(), e.into_int_value(), false)
                    }
                    ExprKind::Variable(_) | ExprKind::FieldAccess(_, _) => {
                        // Assume it's a tensor or array iteration
                        let (tensor_val, tensor_ty) = self.compile_expr(iterator)?;
                        let len = match &tensor_ty {
                            Type::Tensor(_, _) => {
                                // Get tensor length
                                let len_fn = self
                                    .module
                                    .get_function("tl_tensor_len")
                                    .ok_or("tl_tensor_len not found")?;
                                let len_call = self
                                    .builder
                                    .build_call(len_fn, &[tensor_val.into()], "tensor_len")
                                    .map_err(|e| e.to_string())?;
                                match len_call.try_as_basic_value() {
                                    inkwell::values::ValueKind::Basic(v) => v.into_int_value(),
                                    _ => return Err("Invalid tensor_len return".into()),
                                }
                            }
                            Type::ScalarArray(_, len) => i64_type.const_int(*len as u64, false),
                            _ => {
                                return Err(
                                    "For loop iterator must be a tensor, array, or range".into()
                                )
                            }
                        };

                        // Store tensor/array pointer for use in body
                        let tensor_ptr = tensor_val.into_pointer_value();
                        let tensor_alloca = self
                            .builder
                            .build_alloca(
                                self.context.ptr_type(inkwell::AddressSpace::default()),
                                "for_tensor",
                            )
                            .map_err(|e| e.to_string())?;
                        self.builder
                            .build_store(tensor_alloca, tensor_ptr)
                            .map_err(|e| e.to_string())?;

                        // Register tensor alloca for later use
                        self.variables.last_mut().unwrap().insert(
                            "__for_tensor__".to_string(),
                            (tensor_alloca.into(), tensor_ty.clone(), false),
                        );

                        (i64_type.const_int(0, false), len, true)
                    }
                    _ => {
                        // Try to compile as expression and check type
                        let (iter_val, iter_ty) = self.compile_expr(iterator)?;
                        let len = match &iter_ty {
                            Type::Tensor(_, _) => {
                                let len_fn = self
                                    .module
                                    .get_function("tl_tensor_len")
                                    .ok_or("tl_tensor_len not found")?;
                                let len_call = self
                                    .builder
                                    .build_call(len_fn, &[iter_val.into()], "tensor_len")
                                    .map_err(|e| e.to_string())?;
                                match len_call.try_as_basic_value() {
                                    inkwell::values::ValueKind::Basic(v) => v.into_int_value(),
                                    _ => return Err("Invalid tensor_len return".into()),
                                }
                            }
                            Type::ScalarArray(_, len) => i64_type.const_int(*len as u64, false),
                            _ => {
                                return Err(
                                    "For loop iterator must be a tensor, array, or range".into()
                                )
                            }
                        };

                        let tensor_ptr = iter_val.into_pointer_value();
                        let tensor_alloca = self
                            .builder
                            .build_alloca(
                                self.context.ptr_type(inkwell::AddressSpace::default()),
                                "for_tensor",
                            )
                            .map_err(|e| e.to_string())?;
                        self.builder
                            .build_store(tensor_alloca, tensor_ptr)
                            .map_err(|e| e.to_string())?;

                        self.variables.last_mut().unwrap().insert(
                            "__for_tensor__".to_string(),
                            (tensor_alloca.into(), iter_ty.clone(), false),
                        );

                        (i64_type.const_int(0, false), len, true)
                    }
                };

                // Capture preheader block (where we are jumping from)
                let preheader_block = self.builder.get_insert_block().unwrap();

                // Create basic blocks
                let loop_header = self.context.append_basic_block(parent, "for_header");
                let loop_body = self.context.append_basic_block(parent, "for_body");
                let loop_end = self.context.append_basic_block(parent, "for_end");

                // Branch to loop header
                self.builder
                    .build_unconditional_branch(loop_header)
                    .map_err(|e| e.to_string())?;

                // Loop header: PHI for index
                self.builder.position_at_end(loop_header);
                // let current_block = self.builder.get_insert_block().unwrap(); // No longer needed
                let phi = self
                    .builder
                    .build_phi(i64_type, "for_idx")
                    .map_err(|e| e.to_string())?;

                // Add incoming from entry
                // Use preheader_block captured above

                // Check condition: idx < end
                let cond = self
                    .builder
                    .build_int_compare(
                        inkwell::IntPredicate::SLT,
                        phi.as_basic_value().into_int_value(),
                        end_val,
                        "for_cond",
                    )
                    .map_err(|e| e.to_string())?;

                self.builder
                    .build_conditional_branch(cond, loop_body, loop_end)
                    .map_err(|e| e.to_string())?;

                // Get tensor alloca BEFORE entering new scope (it's in current scope)
                let saved_tensor_alloca = if is_tensor_iter {
                    // Search through all scopes to find __for_tensor__
                    let mut found = None;
                    for scope in self.variables.iter().rev() {
                        if let Some((val, _, _)) = scope.get("__for_tensor__") {
                            found = Some(val.into_pointer_value());
                            break;
                        }
                    }
                    found
                } else {
                    None
                };

                // Loop body
                self.builder.position_at_end(loop_body);

                self.enter_scope();

                // Bind loop variable
                let loop_var_val = if is_tensor_iter {
                    // Search through scopes to find the type of __for_tensor__
                    let mut iter_ty = None;
                    for scope in self.variables.iter().rev() {
                        if let Some((_, ty, _)) = scope.get("__for_tensor__") {
                            iter_ty = Some(ty.clone());
                            break;
                        }
                    }
                    let iter_ty = iter_ty.ok_or("Iterator type not found")?;

                    // Get element from tensor/array - use saved alloca since we're in a new scope
                    let tensor_alloca =
                        saved_tensor_alloca.ok_or("Tensor alloca not found for for-loop")?;
                    let load_type = self.context.ptr_type(inkwell::AddressSpace::default());
                    let tensor_ptr = self
                        .builder
                        .build_load(load_type, tensor_alloca, "tensor_ptr")
                        .map_err(|e| e.to_string())?
                        .into_pointer_value();

                    match iter_ty {
                        Type::Tensor(inner_ty, _) => {
                            let get_fn = self
                                .module
                                .get_function("tl_tensor_get")
                                .ok_or("tl_tensor_get not found")?;
                            let get_call = self
                                .builder
                                .build_call(
                                    get_fn,
                                    &[tensor_ptr.into(), phi.as_basic_value().into()],
                                    "elem_val",
                                )
                                .map_err(|e| e.to_string())?;

                            match get_call.try_as_basic_value() {
                                inkwell::values::ValueKind::Basic(v) => {
                                    let f_val = v.into_float_value();
                                    match inner_ty.as_ref() {
                                        Type::I64 => {
                                            let i_val = self
                                                .builder
                                                .build_float_to_signed_int(
                                                    f_val,
                                                    self.context.i64_type(),
                                                    "f2i",
                                                )
                                                .map_err(|e| e.to_string())?;
                                            (i_val.into(), Type::I64)
                                        }
                                        Type::I32 => {
                                            let i_val = self
                                                .builder
                                                .build_float_to_signed_int(
                                                    f_val,
                                                    self.context.i32_type(),
                                                    "f2i",
                                                )
                                                .map_err(|e| e.to_string())?;
                                            (i_val.into(), Type::I32)
                                        }
                                        _ => (v, Type::F32), // Default/Keep as F32
                                    }
                                }
                                _ => return Err("Invalid tensor_get return".into()),
                            }
                        }
                        Type::ScalarArray(elem_ty, len) => {
                            let llvm_elem_type: inkwell::types::BasicTypeEnum =
                                match elem_ty.as_ref() {
                                    Type::I64 => self.context.i64_type().into(),
                                    Type::F32 => self.context.f32_type().into(),
                                    _ => self.context.f32_type().into(),
                                };
                            let array_type = llvm_elem_type.array_type(len as u32);
                            let elem_ptr = unsafe {
                                self.builder
                                    .build_in_bounds_gep(
                                        array_type,
                                        tensor_ptr,
                                        &[
                                            i64_type.const_int(0, false),
                                            phi.as_basic_value().into_int_value(),
                                        ],
                                        "elem_ptr",
                                    )
                                    .map_err(|e| e.to_string())?
                            };
                            let loaded = self
                                .builder
                                .build_load(llvm_elem_type, elem_ptr, "elem_val")
                                .map_err(|e| e.to_string())?;
                            (loaded, *elem_ty.clone())
                        }
                        _ => unreachable!(),
                    }
                } else {
                    // Range iteration: loop var is the index
                    (phi.as_basic_value(), Type::I64)
                };

                // Create alloca for loop var and store
                let var_alloca = self.create_entry_block_alloca(parent, loop_var, &loop_var_val.1);
                self.builder
                    .build_store(var_alloca, loop_var_val.0)
                    .map_err(|e| e.to_string())?;
                self.variables
                    .last_mut()
                    .unwrap()
                    .insert(loop_var.clone(), (var_alloca.into(), loop_var_val.1, false));

                // Compile body
                for stmt in body {
                    self.compile_stmt(stmt)?;
                }

                self.exit_scope();

                // Increment index and Branch back to header
                // ONLY if the body didn't terminate (e.g. return/break)
                let body_end_block = self.builder.get_insert_block().unwrap();

                if body_end_block.get_terminator().is_none() {
                    let next_idx = self
                        .builder
                        .build_int_add(
                            phi.as_basic_value().into_int_value(),
                            i64_type.const_int(1, false),
                            "next_idx",
                        )
                        .map_err(|e| e.to_string())?;

                    self.builder
                        .build_unconditional_branch(loop_header)
                        .map_err(|e| e.to_string())?;

                    // Add PHI incoming edge from loop back
                    phi.add_incoming(&[(&next_idx, body_end_block)]);
                }

                // Add PHI incoming edge from start (always)
                phi.add_incoming(&[(&start_val, preheader_block)]);

                // Continue at loop end
                self.builder.position_at_end(loop_end);

                // Clean up temporary tensor reference
                if is_tensor_iter {
                    for scope in self.variables.iter_mut().rev() {
                        scope.remove("__for_tensor__");
                    }
                }

                Ok(())
            }
            StmtKind::While { cond, body } => {
                let parent = self
                    .builder
                    .get_insert_block()
                    .unwrap()
                    .get_parent()
                    .unwrap();

                let cond_block = self.context.append_basic_block(parent, "while_cond");
                let body_block = self.context.append_basic_block(parent, "while_body");
                let end_block = self.context.append_basic_block(parent, "while_end");

                // Jump to condition from current
                self.builder
                    .build_unconditional_branch(cond_block)
                    .map_err(|e| e.to_string())?;

                // Compile condition
                self.builder.position_at_end(cond_block);
                self.enter_scope(); // Condition Scope
                let (cond_val, _) = self.compile_expr(cond)?;
                let cond_bool = self
                    .builder
                    .build_int_compare(
                        inkwell::IntPredicate::NE,
                        cond_val.into_int_value(),
                        self.context.bool_type().const_zero(),
                        "while_cond_check",
                    )
                    .map_err(|e| e.to_string())?;

                self.exit_scope(); // Free condition temps
                self.builder
                    .build_conditional_branch(cond_bool, body_block, end_block)
                    .map_err(|e| e.to_string())?;

                // Compile body
                self.builder.position_at_end(body_block);
                self.enter_scope();
                for stmt in body {
                    self.compile_stmt(stmt)?;
                }
                self.exit_scope();

                // Loop back to condition
                if self
                    .builder
                    .get_insert_block()
                    .unwrap()
                    .get_terminator()
                    .is_none()
                {
                    self.builder
                        .build_unconditional_branch(cond_block)
                        .map_err(|e| e.to_string())?;
                }

                // Continue at end
                self.builder.position_at_end(end_block);
                Ok(())
            }
            StmtKind::Expr(expr) => {
                let (val, ty) = self.compile_expr(expr)?;

                // FIX: Handle discarded return values properly to prevent use-after-free bugs.
                // When calling `model.step(lr);` without using the result:
                // - The step method may modify `self` and return a new struct
                // - If we don't capture the return value, the original variable becomes invalid
                // - We need to register the return value as a temporary so it gets freed at scope exit

                match &ty {
                    Type::Struct(_) | Type::UserDefined(_) | Type::Tensor(_, _) => {
                        // For struct/tensor return values: Register as a temporary variable
                        // This is equivalent to `let _ = expr;`
                        // The value will be properly freed at scope exit
                        static DISCARD_ID: std::sync::atomic::AtomicUsize =
                            std::sync::atomic::AtomicUsize::new(0);
                        let id = DISCARD_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                        let temp_name = format!("_discard_{}", id);

                        let current_function = self
                            .builder
                            .get_insert_block()
                            .unwrap()
                            .get_parent()
                            .unwrap();

                        let alloca =
                            self.create_entry_block_alloca(current_function, &temp_name, &ty);
                        self.builder
                            .build_store(alloca, val)
                            .map_err(|e| e.to_string())?;

                        // Register in current scope with should_free=true
                        // This ensures the struct gets freed when the scope exits
                        self.variables
                            .last_mut()
                            .unwrap()
                            .insert(temp_name, (alloca.into(), ty.clone(), true));
                    }

                    _ => {
                        // Primitive types: no action needed (no memory to manage)
                    }
                }

                Ok(())
            }
        }
    }

    // Helper for BinOp
    pub(crate) fn compile_bin_op(
        &self,
        lhs: BasicValueEnum<'ctx>,
        lhs_type: Type,
        rhs: BasicValueEnum<'ctx>,
        rhs_type: Type,
        op: BinOp,
    ) -> Result<(BasicValueEnum<'ctx>, Type), String> {
        match (&lhs_type, &rhs_type) {
            (Type::I64, Type::I64) => {
                let l = lhs.into_int_value();
                let r = rhs.into_int_value();
                let res = match op {
                    BinOp::Add => self.builder.build_int_add(l, r, "addtmp"),
                    BinOp::Sub => self.builder.build_int_sub(l, r, "subtmp"),
                    BinOp::Mul => self.builder.build_int_mul(l, r, "multmp"),
                    BinOp::Div => self.builder.build_int_signed_div(l, r, "divtmp"),
                    BinOp::Mod => self.builder.build_int_signed_rem(l, r, "modtmp"),
                    BinOp::Eq => {
                        self.builder
                            .build_int_compare(inkwell::IntPredicate::EQ, l, r, "eqtmp")
                    }
                    BinOp::Neq => {
                        self.builder
                            .build_int_compare(inkwell::IntPredicate::NE, l, r, "neqtmp")
                    }
                    BinOp::Lt => {
                        self.builder
                            .build_int_compare(inkwell::IntPredicate::SLT, l, r, "lttmp")
                    }
                    BinOp::Gt => {
                        self.builder
                            .build_int_compare(inkwell::IntPredicate::SGT, l, r, "gttmp")
                    }
                    BinOp::Le => {
                        self.builder
                            .build_int_compare(inkwell::IntPredicate::SLE, l, r, "letmp")
                    }
                    BinOp::Ge => {
                        self.builder
                            .build_int_compare(inkwell::IntPredicate::SGE, l, r, "getmp")
                    }
                    BinOp::And => self.builder.build_and(l, r, "andtmp"),
                    BinOp::Or => self.builder.build_or(l, r, "ortmp"),
                }
                .map_err(|e| e.to_string())?;

                if res.get_type().get_bit_width() == 1 {
                    Ok((res.into(), Type::Bool))
                } else {
                    Ok((res.into(), Type::I64))
                }
            }
            (Type::F32, Type::F32) => {
                let l = lhs.into_float_value();
                let r = rhs.into_float_value();
                let res: BasicValueEnum = match op {
                    BinOp::Add => self
                        .builder
                        .build_float_add(l, r, "faddtmp")
                        .map(|v| v.into()),
                    BinOp::Sub => self
                        .builder
                        .build_float_sub(l, r, "fsubtmp")
                        .map(|v| v.into()),
                    BinOp::Mul => self
                        .builder
                        .build_float_mul(l, r, "fmultmp")
                        .map(|v| v.into()),
                    BinOp::Div => self
                        .builder
                        .build_float_div(l, r, "fdivtmp")
                        .map(|v| v.into()),
                    BinOp::Eq => self
                        .builder
                        .build_float_compare(inkwell::FloatPredicate::OEQ, l, r, "feqtmp")
                        .map(|v| v.into()),
                    BinOp::Neq => self
                        .builder
                        .build_float_compare(inkwell::FloatPredicate::ONE, l, r, "fneqtmp")
                        .map(|v| v.into()),
                    BinOp::Lt => self
                        .builder
                        .build_float_compare(inkwell::FloatPredicate::OLT, l, r, "flttmp")
                        .map(|v| v.into()),
                    BinOp::Gt => self
                        .builder
                        .build_float_compare(inkwell::FloatPredicate::OGT, l, r, "fgttmp")
                        .map(|v| v.into()),
                    BinOp::Le => self
                        .builder
                        .build_float_compare(inkwell::FloatPredicate::OLE, l, r, "fletmp")
                        .map(|v| v.into()),
                    BinOp::Ge => self
                        .builder
                        .build_float_compare(inkwell::FloatPredicate::OGE, l, r, "fgetmp")
                        .map(|v| v.into()),
                    _ => return Err("Unsupported float op".into()),
                }
                .map_err(|e| e.to_string())?;

                if res.is_int_value() {
                    Ok((res, Type::Bool))
                } else {
                    Ok((res, Type::F32))
                }
            }
            (Type::UserDefined(s1), Type::UserDefined(s2)) if s1 == "String" && s2 == "String" => {
                match op {
                    BinOp::Add => {
                        let concat_fn = self
                            .module
                            .get_function("tl_string_concat")
                            .ok_or("tl_string_concat not found")?;
                        let res = self
                            .builder
                            .build_call(concat_fn, &[lhs.into(), rhs.into()], "strconcat")
                            .map_err(|e| e.to_string())?;
                        let res_val = match res.try_as_basic_value() {
                            ValueKind::Basic(v) => v,
                            _ => return Err("Invalid string concat return".into()),
                        };
                        Ok((res_val, Type::UserDefined("String".to_string())))
                    }
                    BinOp::Eq | BinOp::Neq => {
                        let strcmp_fn = self
                            .module
                            .get_function("strcmp")
                            .ok_or("strcmp not found")?;
                        let cmp = self
                            .builder
                            .build_call(strcmp_fn, &[lhs.into(), rhs.into()], "strcmp_res")
                            .map_err(|e| e.to_string())?;

                        let cmp_val = match cmp.try_as_basic_value() {
                            ValueKind::Basic(v) => v.into_int_value(),
                            _ => return Err("Invalid strcmp return".into()),
                        };
                        let zero = self.context.i32_type().const_zero();
                        let res = match op {
                            BinOp::Eq => self.builder.build_int_compare(
                                inkwell::IntPredicate::EQ,
                                cmp_val,
                                zero,
                                "streq",
                            ),
                            BinOp::Neq => self.builder.build_int_compare(
                                inkwell::IntPredicate::NE,
                                cmp_val,
                                zero,
                                "strneq",
                            ),
                            _ => unreachable!(),
                        }
                        .map_err(|e| e.to_string())?;
                        Ok((res.into(), Type::Bool))
                    }
                    _ => Err("Only ==, !=, and + supported for Strings".into()),
                }
            }

            (Type::Bool, Type::Bool) => {
                let l = lhs.into_int_value();
                let r = rhs.into_int_value();
                let res = match op {
                    BinOp::And => self.builder.build_and(l, r, "andtmp"),
                    BinOp::Or => self.builder.build_or(l, r, "ortmp"),
                    BinOp::Eq => {
                        self.builder
                            .build_int_compare(inkwell::IntPredicate::EQ, l, r, "eqtmp")
                    }
                    BinOp::Neq => {
                        self.builder
                            .build_int_compare(inkwell::IntPredicate::NE, l, r, "neqtmp")
                    }
                    _ => return Err("Unsupported bool op".into()),
                }
                .map_err(|e| e.to_string())?;
                Ok((res.into(), Type::Bool))
            }
            (Type::Tensor(_, _), Type::Tensor(_, _)) => {
                let l = lhs.into_pointer_value();
                let r = rhs.into_pointer_value();

                let fn_name = match op {
                    BinOp::Add => "tl_tensor_add",
                    BinOp::Mul => "tl_tensor_mul",
                    BinOp::Div => "tl_tensor_div",
                    BinOp::Sub => "tl_tensor_sub",
                    _ => return Err("Unsupported tensor op".into()),
                };

                let fn_val = self
                    .module
                    .get_function(fn_name)
                    .ok_or(format!("Runtime function {} not found", fn_name))?;
                let call = self
                    .builder
                    .build_call(fn_val, &[l.into(), r.into()], "binop_res")
                    .map_err(|e| e.to_string())?;

                let res_ptr = match call.try_as_basic_value() {
                    ValueKind::Basic(v) => v.into_pointer_value(),
                    _ => return Err("Invalid return from runtime binop".into()),
                };
                Ok((res_ptr.into(), lhs_type.clone()))
            }
            // Handling mixed types (F32 vs I64) for convenience
            (Type::F32, Type::I64) => {
                let l = lhs.into_float_value();
                let r = rhs.into_int_value();
                let r_f32 = self
                    .builder
                    .build_signed_int_to_float(r, self.context.f32_type(), "cast_r_f32")
                    .map_err(|e| e.to_string())?;

                // Recurse with F32, F32
                self.compile_bin_op(l.into(), Type::F32, r_f32.into(), Type::F32, op)
            }
            (Type::I64, Type::F32) => {
                let l = lhs.into_int_value();
                let r = rhs.into_float_value();
                let l_f32 = self
                    .builder
                    .build_signed_int_to_float(l, self.context.f32_type(), "cast_l_f32")
                    .map_err(|e| e.to_string())?;

                // Recurse with F32, F32
                self.compile_bin_op(l_f32.into(), Type::F32, r.into(), Type::F32, op)
            }
            (Type::Tensor(inner, _), Type::F32) if **inner == Type::F32 => {
                // Broadcasting Tensor op Scalar
                // Create scalar tensor
                // Create scalar tensor
                let val = rhs.into_float_value();
                let _f32_type = self.context.f32_type();
                let i64_type = self.context.i64_type();

                // 1. Alloca in Entry Block
                let current_block = self.builder.get_insert_block().unwrap();
                let parent_fn = current_block.get_parent().unwrap();

                let data_alloca =
                    self.create_entry_block_alloca(parent_fn, "scalar_data_rhs", &Type::F32);
                self.builder
                    .build_store(data_alloca, val)
                    .map_err(|e| e.to_string())?;

                // 2. Shape Alloca (dummy i64)
                let shape_alloca =
                    self.create_entry_block_alloca(parent_fn, "scalar_shape_rhs", &Type::I64);

                // 3. New Tensor
                let new_fn = self.module.get_function("tl_tensor_new").unwrap();
                let rank_val = i64_type.const_int(0, false); // Rank 0
                let call = self
                    .builder
                    .build_call(
                        new_fn,
                        &[data_alloca.into(), rank_val.into(), shape_alloca.into()],
                        "scalar_tensor_rhs",
                    )
                    .map_err(|e| e.to_string())?;
                let scalar_tensor = match call.try_as_basic_value() {
                    ValueKind::Basic(v) => v.into_pointer_value(),
                    _ => return Err("Invalid tensor new return".into()),
                };

                // 4. Call Op
                let fn_name = match op {
                    BinOp::Add => "tl_tensor_add",
                    BinOp::Mul => "tl_tensor_mul",
                    BinOp::Div => "tl_tensor_div",
                    BinOp::Sub => "tl_tensor_sub",
                    _ => return Err("Unsupported tensor op".into()),
                };
                let fn_val = self
                    .module
                    .get_function(fn_name)
                    .ok_or("Runtime fn not found")?;

                let call = self
                    .builder
                    .build_call(
                        fn_val,
                        &[lhs.into_pointer_value().into(), scalar_tensor.into()],
                        "binop_res",
                    )
                    .map_err(|e| e.to_string())?;

                let res_ptr = match call.try_as_basic_value() {
                    ValueKind::Basic(v) => v.into_pointer_value(),
                    _ => return Err("Invalid return from runtime binop".into()),
                };
                Ok((res_ptr.into(), lhs_type.clone()))
            }
            (Type::F32, Type::Tensor(inner, _)) if **inner == Type::F32 => {
                // Scalar op Tensor (Broadcasting)
                // Create scalar tensor
                let val = lhs.into_float_value();
                let _f32_type = self.context.f32_type();
                let i64_type = self.context.i64_type();

                // 1. Alloca in Entry Block
                let current_block = self.builder.get_insert_block().unwrap();
                let parent_fn = current_block.get_parent().unwrap();

                let data_alloca =
                    self.create_entry_block_alloca(parent_fn, "scalar_data_lhs", &Type::F32);
                self.builder
                    .build_store(data_alloca, val)
                    .map_err(|e| e.to_string())?;

                let shape_alloca =
                    self.create_entry_block_alloca(parent_fn, "scalar_shape_lhs", &Type::I64);

                let new_fn = self.module.get_function("tl_tensor_new").unwrap();
                let rank_val = i64_type.const_int(0, false);
                let call = self
                    .builder
                    .build_call(
                        new_fn,
                        &[data_alloca.into(), rank_val.into(), shape_alloca.into()],
                        "scalar_tensor_lhs",
                    )
                    .map_err(|e| e.to_string())?;
                let scalar_tensor = match call.try_as_basic_value() {
                    ValueKind::Basic(v) => v.into_pointer_value(),
                    _ => return Err("Invalid tensor new return".into()),
                };

                let fn_name = match op {
                    BinOp::Add => "tl_tensor_add",
                    BinOp::Mul => "tl_tensor_mul",
                    BinOp::Div => "tl_tensor_div",
                    BinOp::Sub => "tl_tensor_sub",
                    _ => return Err("Unsupported tensor op".into()),
                };
                let fn_val = self
                    .module
                    .get_function(fn_name)
                    .ok_or("Runtime fn not found")?;

                let call = self
                    .builder
                    .build_call(
                        fn_val,
                        &[scalar_tensor.into(), rhs.into_pointer_value().into()],
                        "binop_res",
                    )
                    .map_err(|e| e.to_string())?;

                let res_ptr = match call.try_as_basic_value() {
                    ValueKind::Basic(v) => v.into_pointer_value(),
                    _ => return Err("Invalid return from runtime binop".into()),
                };
                Ok((res_ptr.into(), rhs_type.clone()))
            }
            // ScalarArray operations: convert to Tensor and use tensor ops
            (Type::ScalarArray(_, len1), Type::ScalarArray(_, len2)) if len1 == len2 => {
                // Convert both ScalarArrays to tensors and perform tensor operation
                let _f32_type = self.context.f32_type();
                let i64_type = self.context.i64_type();

                // Helper to create tensor from ScalarArray pointer
                let create_tensor =
                    |builder: &inkwell::builder::Builder<'ctx>,
                     module: &inkwell::module::Module<'ctx>,
                     ptr: inkwell::values::PointerValue<'ctx>,
                     len: usize|
                     -> Result<inkwell::values::PointerValue<'ctx>, String> {
                        let new_fn = module
                            .get_function("tl_tensor_new")
                            .ok_or("tl_tensor_new not found")?;

                        // Shape: [len]
                        let shape_alloca = builder
                            .build_alloca(i64_type, "shape")
                            .map_err(|e| e.to_string())?;
                        builder
                            .build_store(shape_alloca, i64_type.const_int(len as u64, false))
                            .map_err(|e| e.to_string())?;

                        let call = builder
                            .build_call(
                                new_fn,
                                &[
                                    ptr.into(),
                                    i64_type.const_int(1, false).into(),
                                    shape_alloca.into(),
                                ],
                                "tensor_from_scalar_arr",
                            )
                            .map_err(|e| e.to_string())?;

                        match call.try_as_basic_value() {
                            ValueKind::Basic(v) => Ok(v.into_pointer_value()),
                            _ => Err("Invalid tensor new return".into()),
                        }
                    };

                let l_tensor =
                    create_tensor(&self.builder, &self.module, lhs.into_pointer_value(), *len1)?;
                let r_tensor =
                    create_tensor(&self.builder, &self.module, rhs.into_pointer_value(), *len2)?;

                // Now call tensor binary op
                let fn_name = match op {
                    BinOp::Add => "tl_tensor_add",
                    BinOp::Mul => "tl_tensor_mul",
                    BinOp::Div => "tl_tensor_div",
                    BinOp::Sub => "tl_tensor_sub",
                    _ => return Err("Unsupported ScalarArray op".into()),
                };

                let fn_val = self
                    .module
                    .get_function(fn_name)
                    .ok_or(format!("Runtime function {} not found", fn_name))?;
                let call = self
                    .builder
                    .build_call(fn_val, &[l_tensor.into(), r_tensor.into()], "binop_res")
                    .map_err(|e| e.to_string())?;

                let res_ptr = match call.try_as_basic_value() {
                    ValueKind::Basic(v) => v.into_pointer_value(),
                    _ => return Err("Invalid return from runtime binop".into()),
                };

                // Return as Tensor (since we converted)
                Ok((res_ptr.into(), Type::Tensor(Box::new(Type::F32), 1)))
            }
            _ => Err(format!(
                "Type mismatch in BinOp {:?}: {:?} vs {:?}",
                op, lhs_type, rhs_type
            )),
        }
    }
    /// Deep clone a value (Tensor or Struct containing Tensors)
    pub(crate) fn emit_deep_clone(
        &self,
        val: inkwell::values::BasicValueEnum<'ctx>,
        ty: &Type,
    ) -> Result<inkwell::values::BasicValueEnum<'ctx>, String> {
        match ty {
            Type::Tensor(_, _) => {
                // Shared Ownership: Acquire reference, return same pointer
                let acquire_fn = self
                    .module
                    .get_function("tl_tensor_acquire")
                    .ok_or("tl_tensor_acquire not found")?;

                // Cast to void ptr for acquire function
                let ptr = val.into_pointer_value();
                let void_ptr_type = self.context.ptr_type(inkwell::AddressSpace::default());
                let cast_ptr = self
                    .builder
                    .build_pointer_cast(ptr, void_ptr_type, "cast_tensor_ptr")
                    .unwrap();

                self.builder
                    .build_call(acquire_fn, &[cast_ptr.into()], "")
                    .map_err(|e| e.to_string())?;

                // Return the SAME pointer
                Ok(val)
            }
            Type::Enum(name) => {
                let enum_def = self
                    .enum_defs
                    .get(name)
                    .ok_or(format!("Enum {} definition not found", name))?;
                self.emit_enum_deep_clone(val, enum_def)
            }
            Type::Struct(name) | Type::UserDefined(name) => {
                // Check if it is an Enum
                if let Some(enum_def) = self.enum_defs.get(name) {
                    return self.emit_enum_deep_clone(val, enum_def);
                }

                // HACK: Built-in types (String, File) are opaque pointers
                if name == "String" {
                    // Deep clone string -> strdup (via tl_string_concat("", s) or similar)
                    // We can use tl_string_concat(s, "")
                    let concat_fn = self
                        .module
                        .get_function("tl_string_concat")
                        .ok_or("tl_string_concat not found")?;

                    let s_ptr = val.into_pointer_value();
                    let empty = self
                        .builder
                        .build_global_string_ptr("", "empty_str")
                        .unwrap()
                        .as_pointer_value();

                    let call_site = self
                        .builder
                        .build_call(concat_fn, &[s_ptr.into(), empty.into()], "str_clone")
                        .unwrap();

                    let new_str = match call_site.try_as_basic_value() {
                        inkwell::values::ValueKind::Basic(v) => v,
                        _ => return Err("Failed to clone string".to_string()),
                    };
                    return Ok(new_str);
                } else if name == "File" {
                    // File handle cannot be deeply cloned easily. Return shallow copy (pointer).
                    return Ok(val);
                } else if name == "Path" {
                    // Shallow copy for Path
                    return Ok(val);
                } else if name == "Env" || name == "Http" {
                    // Virtual static classes or opaque
                    return Ok(val);
                }

                let simple_name = if name.contains("::") {
                    name.split("::").last().unwrap()
                } else {
                    name
                };

                let struct_def = self
                    .struct_defs
                    .get(simple_name)
                    .ok_or(format!("Struct {} definition not found", name))?;
                let st_llvm_ty = *self
                    .struct_types
                    .get(simple_name)
                    .ok_or("LLVM Struct type not found")?;

                let new_struct_ptr = self
                    .builder
                    .build_malloc(st_llvm_ty, &format!("copy_{}", name))
                    .map_err(|e| e.to_string())?;

                // Register with MemoryManager (important for nested structs which are not Variables)
                // Actually, if it's a field, it's owned by the parent struct.
                // The parent struct's free will recursively free this.
                // But wait, standard malloc isn't tracked by MemoryManager unless registered.
                // If we use recursive_free for the parent, it calls libc::free on fields.
                // So checking registration is not strictly needed for fields if recursive_free handles it.
                // However, for consistency/debug, we could register? No, let's stick to recursive_free logic.

                let src_ptr = val.into_pointer_value();

                for (i, (field_name, field_ty)) in struct_def.fields.iter().enumerate() {
                    let src_field_ptr = self
                        .builder
                        .build_struct_gep(
                            st_llvm_ty,
                            src_ptr,
                            i as u32,
                            &format!("src_{}", field_name),
                        )
                        .map_err(|e| e.to_string())?;
                    let dst_field_ptr = self
                        .builder
                        .build_struct_gep(
                            st_llvm_ty,
                            new_struct_ptr,
                            i as u32,
                            &format!("dst_{}", field_name),
                        )
                        .map_err(|e| e.to_string())?;

                    let val = match field_ty {
                        Type::Tensor(_, _) | Type::Struct(_) | Type::UserDefined(_) => {
                            let loaded = self
                                .builder
                                .build_load(
                                    self.context.ptr_type(inkwell::AddressSpace::default()),
                                    src_field_ptr,
                                    "f_val",
                                )
                                .map_err(|e| e.to_string())?;
                            self.emit_deep_clone(loaded, field_ty)?
                        }
                        _ => {
                            let llvm_ty: inkwell::types::BasicTypeEnum = match field_ty {
                                Type::F32 => self.context.f32_type().into(),
                                Type::I64 => self.context.i64_type().into(),
                                Type::I32 => self.context.i32_type().into(),
                                Type::Bool => self.context.bool_type().into(),
                                _ => {
                                    return Err(format!("Unsupported clone field: {:?}", field_ty))
                                }
                            };
                            self.builder
                                .build_load(llvm_ty, src_field_ptr, "prim_val")
                                .map_err(|e| e.to_string())?
                        }
                    };

                    self.builder
                        .build_store(dst_field_ptr, val)
                        .map_err(|e| e.to_string())?;
                }
                // Return new struct ptr
                Ok(new_struct_ptr.into())
            }
            Type::Tuple(ts) => {
                // 1. Allocate tuple struct
                let mut llvm_types = Vec::new();
                for t in ts {
                    llvm_types.push(self.get_llvm_type(t)?);
                }
                let tuple_struct_type = self.context.struct_type(&llvm_types, false);

                let size = tuple_struct_type
                    .size_of()
                    .ok_or("Cannot get size of tuple")?;
                let malloc_fn = self
                    .module
                    .get_function("malloc")
                    .ok_or("malloc not found")?;
                let call = self
                    .builder
                    .build_call(malloc_fn, &[size.into()], "tuple_malloc")
                    .map_err(|e| e.to_string())?;
                let raw_ptr = match call.try_as_basic_value() {
                    inkwell::values::ValueKind::Basic(v) => v.into_pointer_value(),
                    _ => return Err("malloc returned invalid value".into()),
                };

                let ptr_type = self.context.ptr_type(inkwell::AddressSpace::default());
                let tuple_ptr = self
                    .builder
                    .build_pointer_cast(raw_ptr, ptr_type, "tuple_ptr")
                    .unwrap();

                // 2. Deep clone elements
                let src_ptr = val.into_pointer_value(); // Source tuple pointer
                let src_cast = self
                    .builder
                    .build_pointer_cast(src_ptr, ptr_type, "src_tuple_cast")
                    .unwrap();

                for (i, ty) in ts.iter().enumerate() {
                    // Load field from src
                    let field_gep = self
                        .builder
                        .build_struct_gep(tuple_struct_type, src_cast, i as u32, "src_field_gep")
                        .map_err(|e| e.to_string())?;
                    let field_llvm_ty = self.get_llvm_type(ty)?;
                    let field_val = self
                        .builder
                        .build_load(field_llvm_ty, field_gep, "src_field_val")
                        .map_err(|e| e.to_string())?;

                    // RECURSIVE DEEP CLONE
                    let cloned_val = self.emit_deep_clone(field_val, ty)?;

                    // Store into dst
                    let dst_gep = self
                        .builder
                        .build_struct_gep(tuple_struct_type, tuple_ptr, i as u32, "dst_field_gep")
                        .map_err(|e| e.to_string())?;
                    self.builder
                        .build_store(dst_gep, cloned_val)
                        .map_err(|e| e.to_string())?;
                }

                Ok(tuple_ptr.into())
            }
            _ => Ok(val), // Primitives copy by value
        }
    }

    fn emit_enum_deep_clone(
        &self,
        val: BasicValueEnum<'ctx>,
        enum_def: &EnumDef,
    ) -> Result<BasicValueEnum<'ctx>, String> {
        let name = &enum_def.name;
        let enum_ty = *self
            .enum_types
            .get(name)
            .ok_or(format!("Enum type {} not found", name))?;

        let src_ptr = val.into_pointer_value();

        // 1. Allocate new enum instance
        let new_ptr = self
            .builder
            .build_malloc(enum_ty, &format!("copy_{}", name))
            .map_err(|e| e.to_string())?;

        // 2. Load Tag
        let tag_ptr = self
            .builder
            .build_struct_gep(enum_ty, src_ptr, 0, "tag_ptr")
            .map_err(|e| e.to_string())?;
        let tag_val = self
            .builder
            .build_load(self.context.i32_type(), tag_ptr, "tag")
            .map_err(|e| e.to_string())?
            .into_int_value();

        // 3. Store Tag to new instance
        let dst_tag_ptr = self
            .builder
            .build_struct_gep(enum_ty, new_ptr, 0, "dst_tag_ptr")
            .map_err(|e| e.to_string())?;
        let _ = self.builder.build_store(dst_tag_ptr, tag_val);

        // 4. Switch on tag to copy payload
        let current_block = self.builder.get_insert_block().unwrap();
        let func = current_block.get_parent().unwrap();
        let after_switch = self.context.append_basic_block(func, "after_enum_clone");

        let mut cases = vec![];
        for (i, variant) in enum_def.variants.iter().enumerate() {
            let case_block = self
                .context
                .append_basic_block(func, &format!("clone_variant_{}", variant.name));
            cases.push((
                self.context.i32_type().const_int(i as u64, false),
                case_block,
            ));
        }

        let cases_refs: Vec<(inkwell::values::IntValue, inkwell::basic_block::BasicBlock)> =
            cases.iter().map(|(i, b)| (*i, *b)).collect();
        self.builder
            .build_switch(tag_val, after_switch, &cases_refs)
            .map_err(|e| e.to_string())?;

        // Populate cases
        for (i, variant) in enum_def.variants.iter().enumerate() {
            let case_block = cases[i].1;
            self.builder.position_at_end(case_block);

            if !variant.fields.is_empty() {
                // Reconstruct field types for GEP/Load/Store
                let mut field_types: Vec<inkwell::types::BasicTypeEnum> = vec![];
                for (_, ty) in &variant.fields {
                    let llvm_ty = match ty {
                        Type::F32 => self.context.f32_type().into(),
                        Type::I64 => self.context.i64_type().into(),
                        Type::Bool => self.context.bool_type().into(),
                        Type::Tensor(_, _) => self
                            .context
                            .ptr_type(inkwell::AddressSpace::default())
                            .into(),
                        Type::Struct(_) | Type::Enum(_) | Type::UserDefined(_) => self
                            .context
                            .ptr_type(inkwell::AddressSpace::default())
                            .into(),
                        _ => self.context.i64_type().into(),
                    };
                    field_types.push(llvm_ty);
                }
                let variant_struct_ty = self.context.struct_type(&field_types, false);
                let variant_ptr_ty = self.context.ptr_type(inkwell::AddressSpace::default());

                // Src Payload
                let src_payload_ptr_raw = self
                    .builder
                    .build_struct_gep(enum_ty, src_ptr, 1, "src_payload_raw")
                    .map_err(|e| e.to_string())?;
                let src_variant_ptr = self
                    .builder
                    .build_pointer_cast(src_payload_ptr_raw, variant_ptr_ty, "src_variant_casted")
                    .unwrap();

                // Dst Payload
                let dst_payload_ptr_raw = self
                    .builder
                    .build_struct_gep(enum_ty, new_ptr, 1, "dst_payload_raw")
                    .map_err(|e| e.to_string())?;
                let dst_variant_ptr = self
                    .builder
                    .build_pointer_cast(dst_payload_ptr_raw, variant_ptr_ty, "dst_variant_casted")
                    .unwrap();

                // Copy Fields
                for (idx, (_, f_ty)) in variant.fields.iter().enumerate() {
                    let src_field_ptr = self
                        .builder
                        .build_struct_gep(variant_struct_ty, src_variant_ptr, idx as u32, "src_f")
                        .map_err(|e| e.to_string())?;
                    let val = self
                        .builder
                        .build_load(field_types[idx], src_field_ptr, "val")
                        .map_err(|e| e.to_string())?;

                    // Recursive Deep Clone
                    let cloned_val = self.emit_deep_clone(val, f_ty)?;

                    let dst_field_ptr = self
                        .builder
                        .build_struct_gep(variant_struct_ty, dst_variant_ptr, idx as u32, "dst_f")
                        .map_err(|e| e.to_string())?;
                    let _ = self.builder.build_store(dst_field_ptr, cloned_val);
                }
            }
            let _ = self.builder.build_unconditional_branch(after_switch);
        }

        self.builder.position_at_end(after_switch);
        Ok(new_ptr.into())
    }
}