tl-lang 0.4.8

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
use crate::compiler::ast::*;


use crate::compiler::shape_analysis::ShapeAnalyzer;
use inkwell::builder::Builder;
use inkwell::context::Context;
use inkwell::execution_engine::ExecutionEngine;
use inkwell::module::Module as InkwellModule;
use inkwell::AddressSpace;
use inkwell::types::{BasicMetadataTypeEnum, StructType, BasicType};
use inkwell::values::ValueKind; // Used in relation wrappers
use inkwell::values::{BasicValueEnum, FunctionValue};
use inkwell::OptimizationLevel;
use std::collections::HashMap;

pub const CLEANUP_NONE: u8 = 0;
pub const CLEANUP_FULL: u8 = 1;
pub const CLEANUP_FINALIZE: u8 = 2;
pub const CLEANUP_STACK: u8 = 3;

pub mod builtins;
pub mod expr;
pub mod kb;
pub mod mono;
pub mod specialization;
pub mod stmt;
pub mod tensor;
pub mod type_manager;
pub mod builtin_types;

pub struct CodeGenerator<'ctx> {
    pub(crate) context: &'ctx Context,
    pub(crate) module: InkwellModule<'ctx>,
    pub(crate) builder: Builder<'ctx>,
    pub(crate) execution_engine: ExecutionEngine<'ctx>,
    pub(crate) variables: Vec<HashMap<String, (BasicValueEnum<'ctx>, Type, u8)>>,
    pub(crate) struct_types: HashMap<String, StructType<'ctx>>,
    pub(crate) struct_defs: HashMap<String, StructDef>,
    pub(crate) enum_types: HashMap<String, StructType<'ctx>>,
    pub(crate) enum_defs: HashMap<String, EnumDef>,
    pub(crate) generic_fn_defs: HashMap<String, FunctionDef>,
    pub(crate) generic_impls: HashMap<String, Vec<ImplBlock>>,
    pub(crate) trait_defs: HashMap<String, TraitDef>,
    pub(crate) fn_entry_scope_depth: usize,
    pub(crate) builtin_manager: expr::BuiltinManager,
    pub(crate) instance_methods: HashMap<String, expr::InstanceMethodManager>,
    pub(crate) static_methods: HashMap<String, expr::StaticMethodManager>,
    pub(crate) method_return_types: HashMap<String, Type>, // MangledName -> ReturnType
    pub(crate) fn_params: HashMap<String, Vec<Type>>, // MangledName -> ParamTypes
    pub(crate) loop_stack: Vec<(
        inkwell::basic_block::BasicBlock<'ctx>,
        inkwell::basic_block::BasicBlock<'ctx>,
        usize,
    )>,
    pub(crate) relations: std::collections::HashSet<String>,
    pub(crate) current_span: Option<crate::compiler::error::Span>,
    pub(crate) function_analysis: Option<crate::compiler::liveness::FunctionAnalysis>,
    pub(crate) current_sret_dest: Option<inkwell::values::PointerValue<'ctx>>,
    pub(crate) temporaries: Vec<Vec<(BasicValueEnum<'ctx>, Type, u8)>>,
    pub(crate) variable_liveness: Vec<HashMap<String, usize>>, // Parallel to variables: Last Use Time
    pub(crate) current_time: usize,
    pub(crate) current_fn_return_type: Option<Type>,
    pub(crate) type_manager: type_manager::TypeManager,
    pub(crate) current_method_generics: Option<std::collections::HashMap<String, crate::compiler::ast::Type>>,
    pub(crate) pending_functions: Vec<(crate::compiler::ast::FunctionDef, Option<std::collections::HashMap<String, crate::compiler::ast::Type>>)>,
    pub(crate) specialization_registry: specialization::SpecializationRegistry,
    /// Trait registry: maps type name -> set of implemented trait names.
    /// Used to check trait bounds during monomorphization.
    pub(crate) trait_registry: HashMap<String, std::collections::HashSet<String>>,
    pub(crate) closure_counter: usize,
}

impl<'ctx> CodeGenerator<'ctx> {
    pub fn new(context: &'ctx Context, module_name: &str) -> Self {
        let module = context.create_module(module_name);
        let builder = context.create_builder();
        let execution_engine = module
            .create_jit_execution_engine(OptimizationLevel::None)
            .map_err(|e| e.to_string())
            .unwrap();

        let mut codegen = CodeGenerator {
            context,
            module,
            builder,
            execution_engine,
            variables: vec![HashMap::new()],
            struct_types: HashMap::new(),
            struct_defs: HashMap::new(),
            enum_types: HashMap::new(),
            enum_defs: HashMap::new(),
            generic_fn_defs: HashMap::new(),
            generic_impls: HashMap::new(),
            trait_defs: HashMap::new(),
            fn_entry_scope_depth: 0,
            builtin_manager: expr::BuiltinManager::new(),
            instance_methods: HashMap::new(),
            static_methods: HashMap::new(),
            loop_stack: Vec::new(),
            method_return_types: HashMap::new(),
            fn_params: HashMap::new(),
            relations: std::collections::HashSet::new(),
            current_span: None,
            function_analysis: None,
            current_sret_dest: None,
            temporaries: vec![Vec::new()],
            variable_liveness: vec![HashMap::new()],
            current_time: 0,
            current_fn_return_type: None,
            type_manager: type_manager::TypeManager::new(),
            current_method_generics: None,
            pending_functions: Vec::new(),
            specialization_registry: specialization::SpecializationRegistry::new(),
            trait_registry: {
                let mut reg = HashMap::<String, std::collections::HashSet<String>>::new();
                // PartialEq: types that support == operator
                for ty in &["i64", "i32", "f32", "f64", "bool", "String", "u8", "usize"] {
                    reg.entry(ty.to_string()).or_default().insert("PartialEq".to_string());
                }
                // PartialOrd: types that support < > <= >= operators
                for ty in &["i64", "i32", "f32", "f64", "u8", "usize"] {
                    reg.entry(ty.to_string()).or_default().insert("PartialOrd".to_string());
                }
                reg
            },
            closure_counter: 0,
        };

        // Register all methods (instance and static)
        codegen.register_all_methods();

        // Register builtins (Enums, etc.)
        // Register builtins (Enums, Structs, etc.) - Unified Loader
        builtin_types::load_all_builtins(&mut codegen);
        
        // Compile all enums loaded (including Device, Option, Result)
        let builtin_enums = codegen.enum_defs.values().cloned().collect::<Vec<_>>();
        codegen.compile_enum_defs(&builtin_enums).expect("Failed to compile builtin enums");
        
        // Compile all structs loaded (including Vec, HashMap)
        let builtin_structs = codegen.struct_defs.values().cloned().collect::<Vec<_>>();
        codegen.compile_struct_defs(&builtin_structs).expect("Failed to compile builtin structs");

        // Delegate to runtime module
        builtins::declare_runtime_functions(
            codegen.context,
            &codegen.module,
            &codegen.execution_engine,
            &mut codegen.method_return_types,
        );

        codegen.register_builtin_return_types();
        

        codegen
    }

    fn register_builtin_return_types(&mut self) {
        // ポインタ返却FFI関数の型は declare_runtime_functions 内の add_fn_typed で一元登録済み。
        // ここには add_fn_typed で登録できない特殊なケース(メソッド呼び出し等)のみ残す。

        // Path
        self.method_return_types.insert("tl_path_new".to_string(), Type::Struct("Path".to_string(), vec![]));
        self.method_return_types.insert("tl_path_to_string".to_string(), Type::String("String".to_string()));
        self.method_return_types.insert("tl_path_join".to_string(), Type::Struct("Path".to_string(), vec![]));

        // File
        self.method_return_types.insert("tl_file_open".to_string(), Type::Struct("File".to_string(), vec![]));
        self.method_return_types.insert("tl_file_read_string".to_string(), Type::String("String".to_string()));
        self.method_return_types.insert("tl_file_write_string".to_string(), Type::Void);
        self.method_return_types.insert("tl_args_get".to_string(), Type::String("String".to_string()));
        self.method_return_types.insert("tl_env_get".to_string(), Type::String("String".to_string()));
        self.method_return_types.insert("tl_string_char_at".to_string(), Type::Char("Char".to_string()));

        // Opaque struct pointers
        self.method_return_types.insert("tl_tensor_map_new".to_string(), Type::Struct("Map".to_string(), vec![]));
    }

    pub fn dump_ir(&self) {
        self.module.print_to_stderr();
    }

    pub fn jit_execute(&self, function_name: &str) -> Result<u64, String> {
        unsafe {
            let function = self
                .execution_engine
                .get_function::<unsafe extern "C" fn() -> u64>(function_name)
                .map_err(|e| format!("JIT compile error: {}", e))?;
            self.module.print_to_file("debug.ll").ok();
            let result = function.call();
            Ok(result)
        }
    }

    pub fn emit_object_file(&self, path: &std::path::Path) -> Result<(), String> {
        use inkwell::targets::{
            CodeModel, FileType, InitializationConfig, RelocMode, Target, TargetMachine,
        };

        Target::initialize_native(&InitializationConfig::default()).map_err(|e| e.to_string())?;

        let triple = TargetMachine::get_default_triple();
        let target = Target::from_triple(&triple).map_err(|e| e.to_string())?;

        let target_machine = target
            .create_target_machine(
                &triple,
                "generic",
                "",
                OptimizationLevel::Default,
                RelocMode::Default,
                CodeModel::Default,
            )
            .ok_or("Failed to create target machine")?;

        target_machine
            .write_to_file(&self.module, FileType::Object, path)
            .map_err(|e| e.to_string())
    }

    pub fn emit_assembly_file(&self, path: &std::path::Path) -> Result<(), String> {
        use inkwell::targets::{
            CodeModel, FileType, InitializationConfig, RelocMode, Target, TargetMachine,
        };

    Target::initialize_native(&InitializationConfig::default()).map_err(|e| e.to_string())?;

        let triple = TargetMachine::get_default_triple();
        let target = Target::from_triple(&triple).map_err(|e| e.to_string())?;

        let target_machine = target
            .create_target_machine(
                &triple,
                "generic",
                "",
                OptimizationLevel::Default,
                RelocMode::Default,
                CodeModel::Default,
            )
            .ok_or("Failed to create target machine")?;

        target_machine
            .write_to_file(&self.module, FileType::Assembly, path)
            .map_err(|e| e.to_string())
    }

    pub fn emit_llvm_file(&self, path: &std::path::Path) -> Result<(), String> {
        self.module
            .print_to_file(path)
            .map_err(|e| e.to_string())
    }

    pub(crate) fn push_temp_scope(&mut self) {
        self.temporaries.push(Vec::new());
    }

    #[allow(dead_code)]
    pub(crate) fn pop_temp_scope(&mut self) -> Result<(), String> {
        let temps = self.temporaries.pop().expect("Temporary stack underflow");
        for (val, ty, cleanup) in temps {
            if cleanup != CLEANUP_NONE {
                self.emit_recursive_free(val, &ty, cleanup)?;
            }
        }
        Ok(())
    }

    pub(crate) fn add_temp(&mut self, val: BasicValueEnum<'ctx>, ty: Type) {
        self.add_temp_with_mode(val, ty, CLEANUP_FULL);
    }

    pub(crate) fn add_temp_with_mode(&mut self, val: BasicValueEnum<'ctx>, ty: Type, mode: u8) {
        // Only track types that need freeing
        match &ty {
            Type::Tensor(_, _) | Type::TensorShaped(_, _) | Type::Struct(_, _) | Type::Tuple(_) | Type::Enum(_, _) => {
                 self.temporaries.last_mut().expect("No temporary context").push((val, ty, mode));
            }
            _ => {}
        }
    }

    pub(crate) fn consume_temp(&mut self, val: BasicValueEnum<'ctx>) {
         let ptr = if val.is_pointer_value() {
             val.into_pointer_value()
         } else {
             return; 
         };

         // Search from innermost scope to outermost
         for scope in self.temporaries.iter_mut().rev() {
             if let Some(pos) = scope.iter().position(|(v, _, _)| v.is_pointer_value() && v.into_pointer_value() == ptr) {
                 scope.remove(pos);
                 return;
             }
         }
    }

    /// Like consume_temp but returns true if a temporary was found and removed.
    pub(crate) fn try_consume_temp(&mut self, val: BasicValueEnum<'ctx>) -> bool {
         if !val.is_pointer_value() { return false; }
         let ptr = val.into_pointer_value();

         // Search from innermost scope to outermost
         for scope in self.temporaries.iter_mut().rev() {
             if let Some(pos) = scope.iter().position(|(v, _, _)| v.is_pointer_value() && v.into_pointer_value() == ptr) {
                 scope.remove(pos);
                 return true;
             }
         }
         false
    }

    pub(crate) fn mark_temp_no_cleanup(&mut self, val: BasicValueEnum<'ctx>) {
         let ptr = if val.is_pointer_value() {
             val.into_pointer_value()
         } else {
             return; 
         };

         // Search from innermost scope to outermost
         for scope in self.temporaries.iter_mut().rev() {
             for (v, _, cleanup) in scope.iter_mut() {
                 if v.is_pointer_value() && v.into_pointer_value() == ptr {
                     *cleanup = CLEANUP_NONE;
                 }
             }
         }
    }

    pub(crate) fn check_tensor_result(
        &self,
        call_site_value: inkwell::values::CallSiteValue<'ctx>,
        context_msg: &str,
    ) -> Result<BasicValueEnum<'ctx>, String> {
        let (file, line, col) = if let Some(span) = &self.current_span {
            (span.file.as_deref(), span.line as u32, span.column as u32)
        } else {
            (None, 0, 0)
        };
        self.check_tensor_result_with_loc(call_site_value, context_msg, file, line, col)
    }

    pub(crate) fn check_tensor_result_with_loc(
        &self,
        call_site_value: inkwell::values::CallSiteValue<'ctx>,
        context_msg: &str,
        file: Option<&str>,
        line: u32,
        col: u32,
    ) -> Result<BasicValueEnum<'ctx>, String> {
        let basic_value = match call_site_value.try_as_basic_value() {
            inkwell::values::ValueKind::Basic(v) => v,
            _ => return Err("Call returned void".into()),
        };

        if !basic_value.is_pointer_value() {
            return Ok(basic_value);
        }

        let ptr_val = basic_value.into_pointer_value();

        // LOG ALLOC (Trace all tensor results from runtime)
        let f_name = "tl_log_alloc";
        if let Some(f) = self.module.get_function(f_name) {
             let size_val = self.context.i64_type().const_int(0, false); // Unknown size from return val
             
             // Use file if available, otherwise context_msg (function name)
             let file_str = if let Some(f) = file {
                 f
             } else {
                 context_msg
             };
             
             // Note: build_global_string_ptr might create duplicates, but LLVM merges constants usually.
             if let Ok(file_ptr_val) = self.builder.build_global_string_ptr(file_str, "log_file") {
                 let file_ptr = file_ptr_val.as_pointer_value();
                 let i32_type = self.context.i32_type();
                 let line_val = i32_type.const_int(line as u64, false);
                 
                 let cast_ptr = self.builder.build_pointer_cast(ptr_val, self.context.ptr_type(inkwell::AddressSpace::default()), "cast_log").unwrap();
    
                 self.builder.build_call(f, &[cast_ptr.into(), size_val.into(), file_ptr.into(), line_val.into()], "").ok();
             }
        }

        let current_bb = self.builder.get_insert_block().unwrap();
        let function = current_bb.get_parent().unwrap();

        // Check is_null
        let is_null = self.builder.build_is_null(ptr_val, "is_null").unwrap();

        let error_bb = self.context.append_basic_block(function, "runtime_error");
        let success_bb = self.context.append_basic_block(function, "runtime_success");

        self.builder
            .build_conditional_branch(is_null, error_bb, success_bb)
            .unwrap();

        // Error Handler
        self.builder.position_at_end(error_bb);

        // Prepare location args
        let file_str = file.unwrap_or("unknown");
        let file_ptr = self
            .builder
            .build_global_string_ptr(file_str, "file_str")
            .map_err(|e| e.to_string())?
            .as_pointer_value();

        // Call tl_report_runtime_error_loc(file, line, col)
        let i32_type = self.context.i32_type();
        let amend_fn = self
            .module
            .get_function("tl_report_runtime_error_loc")
            .expect("tl_report_runtime_error_loc missing");

        // tl_amend_error_loc accepts (i8*, i32, i32)
        // file_ptr is i8* (from build_global_string_ptr)

        self.builder
            .build_call(
                amend_fn,
                &[
                    file_ptr.into(),
                    i32_type.const_int(line as u64, false).into(),
                    i32_type.const_int(col as u64, false).into(),
                ],
                "",
            )
            .unwrap();

        // Return zero/null
        let return_type = function.get_type().get_return_type();
        if let Some(rt) = return_type {
            if rt.is_pointer_type() {
                self.builder
                    .build_return(Some(&rt.into_pointer_type().const_null()))
                    .unwrap();
            } else if rt.is_int_type() {
                self.builder
                    .build_return(Some(&rt.into_int_type().const_zero()))
                    .unwrap();
            } else if rt.is_float_type() {
                self.builder
                    .build_return(Some(&rt.into_float_type().const_zero()))
                    .unwrap();
            } else {
                self.builder.build_return(None).unwrap();
            }
        } else {
            self.builder.build_return(None).unwrap();
        }

        // Success Path
        self.builder.position_at_end(success_bb);

        Ok(basic_value) // Return the original pointer (which is valid here)
    }



    // Enter a new scope
    pub(crate) fn next_closure_id(&mut self) -> usize {
        let id = self.closure_counter;
        self.closure_counter += 1;
        id
    }

    fn enter_scope(&mut self) {
        self.variables.push(std::collections::HashMap::new());
        self.variable_liveness.push(std::collections::HashMap::new());
        self.push_temp_scope(); // Track temporaries for this scope
        if let Some(f) = self.module.get_function("tl_mem_enter_scope") {
            self.builder.build_call(f, &[], "").unwrap();
        }
    }

    // Helper to generate free calls for variables in a specific scope index
    fn emit_cleanup_vars_in_scope(&mut self, scope_idx: usize) {
        let vars = if let Some(scope) = self.variables.get(scope_idx) {
            scope.iter().map(|(n, (v, t, m))| (n.clone(), (*v, t.clone(), *m))).collect::<Vec<_>>()
        } else {
            return;
        };

        for (_name, (val_enum, ty, cleanup_mode)) in vars {
            // Closure env_ptr cleanup: free the malloc'd env struct
            if cleanup_mode != CLEANUP_NONE && _name.starts_with("__env_") {
                let ptr = val_enum.into_pointer_value();
                let load_type = self.context.ptr_type(inkwell::AddressSpace::default());
                if let Ok(env_ptr) = self.builder.build_load(load_type, ptr, "env_to_free") {
                    if let Some(free_fn) = self.module.get_function("free") {
                        let _ = self.builder.build_call(free_fn, &[env_ptr.into()], "");
                    }
                }
                continue;
            }
            if cleanup_mode != CLEANUP_NONE {
                    if let Type::Struct(name, _) = &ty {
                    // Opaque Handles check (formerly UserDefined logic)
                    match name.as_str() {
                        "String" => {} // Should be Type::String("String".to_string()) usually
                        "File" | "Path" => {}
                        "Env" | "Http" => {}
                        "Tokenizer" | "KVCache" => {}
                        _ => {
                            // Structs in TL now follow "Reference Semantics" for their members.
                            // However, Struct("Tensor") MUST be freed because it holds a handle.
                            if name == "Tensor" {
                                let ptr = val_enum.into_pointer_value();
                                let load_type = self.context.ptr_type(inkwell::AddressSpace::default());
                                if let Ok(struct_val) =
                                    self.builder.build_load(load_type, ptr, "tensor_to_free")
                                {
                                    // Use Type::Tensor to avoid GEP on opaque pointer
                                    let tensor_ty = Type::Tensor(Box::new(Type::F32), 0);
                                    let _ = self.emit_recursive_free(struct_val, &tensor_ty, cleanup_mode);
                                }
                            } else {
                                // For other structs (including Vec), load handle from alloca
                                let ptr = val_enum.into_pointer_value();
                                let load_type = self.context.ptr_type(inkwell::AddressSpace::default());
                                if let Ok(struct_val) = self.builder.build_load(load_type, ptr, "struct_to_free") {
                                    let _ = self.emit_recursive_free(struct_val, &ty, cleanup_mode);
                                }
                            }
                        }
                    }
                } else if matches!(ty, Type::Tensor(_, _) | Type::TensorShaped(_, _) | Type::Tuple(_)) {
                        // Tuple and Vec also need loading from Alloca
                    let ptr = val_enum.into_pointer_value();
                    let load_type = self.context.ptr_type(inkwell::AddressSpace::default());
                    if let Ok(val) =
                        self.builder.build_load(load_type, ptr, "val_to_free")
                    {
                        let _ = self.emit_recursive_free(val, &ty, cleanup_mode);
                    }
                }
            }
        }

        // Cleanup temporaries in this scope
        let temps = if let Some(temps) = self.temporaries.get(scope_idx) {
            temps.clone()
        } else {
            vec![]
        };

        for (val, ty, cleanup) in temps {
            // Temporaries are always owned (CLEANUP_FULL) unless marked otherwise.
            // They are values (pointers), not allocas.
            if cleanup != CLEANUP_NONE {
                let _ = self.emit_recursive_free(val, &ty, cleanup);
            }
        }
    }

    fn emit_all_scopes_cleanup(&mut self) {
        if let Some(f) = self.module.get_function("tl_mem_exit_scope") {
            // Only clean up scopes pushed WITHIN the current function
            // Iterate in REVERSE order (from inner to outer)
            let start = self.fn_entry_scope_depth;
            let end = self.variables.len();

            for i in (start..end).rev() {
                // 1. Emit cleanup for variables in this scope
                self.emit_cleanup_vars_in_scope(i);

                // 2. Call runtime exit_scope
                self.builder.build_call(f, &[], "").unwrap();
            }
        }
    }

    // Emit cleanup for the current scope (without popping).
    pub(crate) fn emit_top_scope_cleanup(&mut self) {
        if self.variables.is_empty() {
            return;
        }

        // Cleanup current scope
        self.emit_cleanup_vars_in_scope(self.variables.len() - 1);

        if let Some(f) = self.module.get_function("tl_mem_exit_scope") {
            self.builder.build_call(f, &[], "").unwrap();
        }
    }

    // Emit cleanup for all scopes down to (but not including) target_depth.
    // Emit cleanup for all scopes down to (but not including) target_depth.
    pub(crate) fn emit_cleanup_to_depth(&mut self, target_depth: usize) {
        if let Some(f) = self.module.get_function("tl_mem_exit_scope") {
            let mut idx = self.variables.len();
            while idx > target_depth {
                idx -= 1;
                self.emit_cleanup_vars_in_scope(idx);
                self.builder.build_call(f, &[], "").unwrap();
            }
        }
    }

    pub(crate) fn emit_trace_mem(&self, tag: &str) -> Result<(), String> {
        let f = match self.module.get_function("tl_trace_mem") {
            Some(f) => f,
            None => return Ok(()),
        };
        let (file, line, col) = if let Some(span) = &self.current_span {
            (
                span.file.as_deref().unwrap_or("unknown"),
                span.line as u32,
                span.column as u32,
            )
        } else {
            ("unknown", 0, 0)
        };
        let file_ptr = self
            .builder
            .build_global_string_ptr(file, "trace_file")
            .map_err(|e| e.to_string())?
            .as_pointer_value();
        let tag_ptr = self
            .builder
            .build_global_string_ptr(tag, "trace_tag")
            .map_err(|e| e.to_string())?
            .as_pointer_value();
        let i32_type = self.context.i32_type();
        self.builder
            .build_call(
                f,
                &[
                    file_ptr.into(),
                    i32_type.const_int(line as u64, false).into(),
                    i32_type.const_int(col as u64, false).into(),
                    tag_ptr.into(),
                ],
                "",
            )
            .map_err(|e| e.to_string())?;
        Ok(())
    }

    #[allow(dead_code)]
    pub(crate) fn emit_log_alloc(&self, ptr: inkwell::values::BasicValueEnum<'ctx>, size: inkwell::values::IntValue<'ctx>) -> Result<(), String> {
        // tl_log_alloc(ptr, size, file, line)
        let f_name = "tl_log_alloc";
        let f = if let Some(f) = self.module.get_function(f_name) {
             f
        } else {
             let void_ty = self.context.void_type();
             let ptr_ty = self.context.ptr_type(inkwell::AddressSpace::default());
             let i64_ty = self.context.i64_type();
             let i32_ty = self.context.i32_type();
             // ptr, size, file, line
             let ft = void_ty.fn_type(&[ptr_ty.into(), i64_ty.into(), ptr_ty.into(), i32_ty.into()], false);
             self.module.add_function(f_name, ft, None)
        };

        let (file, line, _) = if let Some(span) = &self.current_span {
            (
                span.file.as_deref().unwrap_or("unknown"),
                span.line as u32,
                span.column as u32,
            )
        } else {
            ("unknown", 0, 0)
        };
        
        let file_ptr = self
            .builder
            .build_global_string_ptr(file, "log_file")
            .map_err(|e| e.to_string())?
            .as_pointer_value();
        
        let i32_type = self.context.i32_type();
        let ptr_val = if ptr.is_pointer_value() {
            ptr.into_pointer_value()
        } else {
             // Cast to void*? Or error? Just assume correct usage.
             // If not pointer, maybe cast int to ptr? No, memory alloc always returns ptr.
             return Err("emit_log_alloc expects pointer".into());
        };
        
        let cast_ptr = self.builder.build_pointer_cast(ptr_val, self.context.ptr_type(inkwell::AddressSpace::default()), "cast_log").unwrap();

        self.builder.build_call(
            f,
            &[
                cast_ptr.into(),
                size.into(),
                file_ptr.into(),
                i32_type.const_int(line as u64, false).into(),
            ],
            ""
        ).map_err(|e| e.to_string())?;
        
        Ok(())
    }

/*
    pub(crate) fn emit_log_free(&self, ptr: inkwell::values::BasicValueEnum<'ctx>) -> Result<(), String> {
        // tl_log_free(ptr, file, line)
        let f_name = "tl_log_free";
        let f = if let Some(f) = self.module.get_function(f_name) {
             f
        } else {
             let void_ty = self.context.void_type();
             let ptr_ty = self.context.ptr_type(inkwell::AddressSpace::default());
             let i32_ty = self.context.i32_type();
             // ptr, file, line
             let ft = void_ty.fn_type(&[ptr_ty.into(), ptr_ty.into(), i32_ty.into()], false);
             self.module.add_function(f_name, ft, None)
        };

        let (file, line, _) = if let Some(span) = &self.current_span {
            (
                span.file.as_deref().unwrap_or("unknown"),
                span.line as u32,
                span.column as u32,
            )
        } else {
            ("unknown", 0, 0)
        };
        
        let file_ptr = self
            .builder
            .build_global_string_ptr(file, "log_file")
            .map_err(|e| e.to_string())?
            .as_pointer_value();
        
        let i32_type = self.context.i32_type();
        let ptr_val = if ptr.is_pointer_value() {
            ptr.into_pointer_value()
        } else {
             return Err("emit_log_free expects pointer".into());
        };
        let cast_ptr = self.builder.build_pointer_cast(ptr_val, self.context.ptr_type(inkwell::AddressSpace::default()), "cast_log").unwrap();

        self.builder.build_call(
            f,
            &[
                cast_ptr.into(),
                file_ptr.into(),
                i32_type.const_int(line as u64, false).into(),
            ],
            ""
        ).map_err(|e| e.to_string())?;
        
        Ok(())
    }
*/

    // Exit the current scope
    // Exit the current scope
    fn exit_scope(&mut self) {
        // Only emit cleanup if the current block is NOT terminated.
        // Note: This causes enter/exit imbalance at runtime for return statements.
        // The proper fix is in StmtKind::Return to emit cleanup BEFORE the return.
        let is_terminated = self
            .builder
            .get_insert_block()
            .map(|b| b.get_terminator().is_some())
            .unwrap_or(false);

        if !is_terminated {
            self.emit_top_scope_cleanup();
        }
        self.variables.pop();
        self.variable_liveness.pop();
        // Just pop the temporaries stack (cleanup code was emitted by emit_top_scope_cleanup if needed)
        self.temporaries.pop();
    }

    /// Null out a variable (Move Semantics) so it won't be double-freed
    #[allow(dead_code)]
    pub(crate) fn null_out_variable(&self, name: &str) -> Result<(), String> {
        for scope in self.variables.iter().rev() {
            if let Some((val, ty, _should_free)) = scope.get(name) {
                // Only for types that would be freed recursively
                if matches!(
                    ty,
                    Type::Tensor(_, _) | Type::Struct(_, _)
                ) {
                    let ptr_type = self.context.ptr_type(inkwell::AddressSpace::default());
                    let null_ptr = ptr_type.const_null();

                    self.builder
                        .build_store(val.into_pointer_value(), null_ptr)
                        .map_err(|e| e.to_string())?;
                }
                return Ok(());
            }
        }
        Ok(())
    }

    /// CLEANUP_NONE 変数の cleanup mode を指定値に昇格する。
    /// パラメータ変数に新しい所有値が代入された後に呼び出し、
    /// 次回の代入で旧値を正しく解放するために使用する。
    pub(crate) fn promote_variable_cleanup(&mut self, name: &str, new_mode: u8) {
        for scope in self.variables.iter_mut().rev() {
            if let Some(entry) = scope.get_mut(name) {
                entry.2 = new_mode;
                return;
            }
        }
    }

    fn compile_struct_defs(&mut self, structs: &[StructDef]) -> Result<(), String> {
        // Pass 1: Opaque
        for s in structs {
            if !s.generics.is_empty() {
                // Register generic struct template definition for later monomorphization
                // and for parse_mangled_type_args to recognize the struct arity.
                // (skip LLVM type generation — that happens during monomorphize_struct)
                self.struct_defs.insert(s.name.clone(), s.clone());
                continue;
            }

            // 1. Skip empty specializations generated by TypeChecker/Semantics
            // These usually have names like Vec_i64 but no fields. We rely on generic fallback (Vec) or monomorphization to generate them correctly.


            // 2. Skip overwriting existing valid (non-empty) definitions with empty ones
            if let Some(existing) = self.struct_defs.get(&s.name) {
                if !existing.fields.is_empty() && s.fields.is_empty() {
                    continue;
                }
            }
            
            // 3. Explicit protection removed - Logic 2 covers the corruption case, and we need to allow initialization to proceed.
            // If we block here, CodeGenerator::new fails to register LLVM types because struct_defs is already populated.


            self.struct_types
                .insert(s.name.clone(), self.context.opaque_struct_type(&s.name));
            self.struct_defs.insert(s.name.clone(), s.clone());
        }

        // Pass 2: Body
        for s in structs {
            if !s.generics.is_empty() {
                continue;
            }

            let mut field_types = Vec::new(); // RESET
            for (_field_name, field_type) in &s.fields {
                // println!("DEBUG: compile_struct_defs struct={} field={} type={:?}", s.name, field_name, field_type);
                let llvm_type = match field_type {
                    Type::F32 => self.context.f32_type().into(),
                    Type::F64 => self.context.f64_type().into(),
                    Type::I64 | Type::Entity => self.context.i64_type().into(),
                    Type::Bool => self.context.bool_type().into(),
                    Type::Tensor(_, _) => self
                        .context
                        .ptr_type(inkwell::AddressSpace::default())
                        .into(), // OpaqueTensor*
                    Type::String(_) => self
                        .context
                        .ptr_type(inkwell::AddressSpace::default())
                        .into(),
                    Type::Char(_) | Type::I32 => self.context.i32_type().into(),
                    Type::Ptr(_) | Type::Tuple(_) | Type::Path(_, _) | Type::U8 | Type::Usize => self.context.ptr_type(inkwell::AddressSpace::default()).into(),
                    Type::TraitObject(_) => {
                        let ptr_type = self.context.ptr_type(inkwell::AddressSpace::default());
                        self.context.struct_type(&[ptr_type.into(), ptr_type.into()], false).into()
                    }
                    Type::Struct(name, _) => {
                        // Extract simple name from module path
                        let simple_name = name.as_str();

                        // Check if it is a ZST (Zero Sized Type) by looking up definition
                        let _is_zst = if let Some(def) = self.struct_defs.get(simple_name) {
                            def.fields.is_empty()
                        } else {
                             // If definition not found yet, assume pointer (safe default for forward decls?)
                             // But compiler should have all defs in Pass 1.
                             return Err(format!("Struct definition {} not found during compilation", name));
                        };

                        // ZST Strategy V3.2: Even ZSTs are treated as Pointers (NULL).
                        // This prevents 0-byte field issues and aligns with Void* return from init.
                        self.context
                            .ptr_type(inkwell::AddressSpace::default())
                            .into()
                        
                        /* 
                        if let Some(st) = self.struct_types.get(simple_name) {
                            if is_zst {
                                st.as_basic_type_enum()
                            } else {
                                self.context
                                    .ptr_type(inkwell::AddressSpace::default())
                                    .into()
                            }
                        } else {
                            return Err(format!("Struct type {} not found", name));
                        }
                        */
                    }

                    Type::Enum(_, _) => {
                        // Enum types are always pointers
                        self.context
                            .ptr_type(inkwell::AddressSpace::default())
                            .into()
                    }

                    Type::SpecializedType { mangled_name, .. } => {
                        // SpecializedType (monomorphized generic) - look up by mangled name
                        let _is_zst = if let Some(def) = self.struct_defs.get(mangled_name.as_str()) {
                            def.fields.is_empty()
                        } else {
                            false // May be an enum or forward decl, just use pointer
                        };
                        self.context
                            .ptr_type(inkwell::AddressSpace::default())
                            .into()
                    }

                    _ => {
                        return Err(format!(
                            "Unsupported field type in struct {}: {:?}",
                            s.name, field_type
                        ))
                    }
                };
                field_types.push(llvm_type);
            }
            if let Some(st) = self.struct_types.get(&s.name) {
                st.set_body(&field_types, false);
            }
        }
        Ok(())
    }

    fn compile_enum_defs(&mut self, enums: &[EnumDef]) -> Result<(), String> {
        // Pass 1: Opaque
        for e in enums {
            if !e.generics.is_empty() {
                // Register generic enum template definition for later monomorphization
                // (skip LLVM type generation — that happens during monomorphize_enum)
                self.enum_defs.insert(e.name.clone(), e.clone());
                continue;
            }

            self.enum_types
                .insert(e.name.clone(), self.context.opaque_struct_type(&e.name));
            self.enum_defs.insert(e.name.clone(), e.clone());
        }

        // Pass 2: Body (Tag + Union)
        // We need data layout to calculate variant sizes
        let target_data = self.execution_engine.get_target_data();

        for e in enums {
            if !e.generics.is_empty() {
                continue;
            }

            let mut max_payload_size = 0;

            for v in &e.variants {
                let mut field_types: Vec<inkwell::types::BasicTypeEnum> = Vec::new();
                let array_types_storage: Vec<Type>;
                let fields_iter: Box<dyn Iterator<Item = &Type>> = match &v.kind {
                     VariantKind::Unit => Box::new(std::iter::empty()),
                     VariantKind::Tuple(types) => Box::new(types.iter()),
                     VariantKind::Struct(fields) => Box::new(fields.iter().map(|(_, t)| t)),
                     VariantKind::Array(ty, size) => {
                         array_types_storage = vec![ty.clone(); *size];
                         Box::new(array_types_storage.iter())
                     }
                };

                for ty in fields_iter {
                    let field_llvm_ty = match ty {
                        Type::F32 => self.context.f32_type().into(),
                        Type::F64 => self.context.f64_type().into(),
                        Type::I64 | Type::Entity => self.context.i64_type().into(),
                        Type::Bool => self.context.bool_type().into(),
                        Type::Tensor(_, _) => self
                            .context
                            .ptr_type(inkwell::AddressSpace::default())
                            .into(),
                        Type::TraitObject(_) => {
                            let ptr_type = self.context.ptr_type(inkwell::AddressSpace::default());
                            self.context.struct_type(&[ptr_type.into(), ptr_type.into()], false).into()
                        }
                        Type::Struct(name, _) => {
                             // Extract simple name
                            let simple_name = name.as_str();

                            // Check is_zst
                            let is_zst = if let Some(def) = self.struct_defs.get(simple_name) {
                                def.fields.is_empty()
                            } else {
                                 false // Fallback
                            };

                            if is_zst {
                                 // Inline ZST
                                 if let Some(st) = self.struct_types.get(simple_name) {
                                     st.as_basic_type_enum()
                                 } else {
                                     self.context.ptr_type(inkwell::AddressSpace::default()).into()
                                 }
                            } else {
                                // Objects are pointers
                                self.context
                                    .ptr_type(inkwell::AddressSpace::default())
                                    .into()
                            }
                        }
                        Type::Enum(_, _) => {
                            // Objects are pointers
                            self.context
                                .ptr_type(inkwell::AddressSpace::default())
                                .into()
                        }
                        Type::Tuple(_) => self
                            .context
                            .ptr_type(inkwell::AddressSpace::default())
                            .into(),
                        Type::String(_) => self
                            .context
                            .ptr_type(inkwell::AddressSpace::default())
                            .into(),
                        Type::Char(_) => self.context.i32_type().into(),
                        Type::I32 => self.context.i32_type().into(),
                        Type::U8 => self.context.i8_type().into(),
                        Type::Usize => self.context.i64_type().into(),
                        Type::Path(_, _) => {
                            // Path types are treated as pointers (generic type parameters)
                            self.context
                                .ptr_type(inkwell::AddressSpace::default())
                                .into()
                        }
                        Type::Undefined(_) => {
                            // Undefined types (unresolved generics) are treated as pointers
                            self.context
                                .ptr_type(inkwell::AddressSpace::default())
                                .into()
                        }
                        Type::SpecializedType { .. } => {
                            // UnifiedType (generic struct/enum) are objects, use pointer
                            self.context
                                .ptr_type(inkwell::AddressSpace::default())
                                .into()
                        }
                        _ => {
                            return Err(format!(
                                "Unsupported type in enum variant {}: {:?}",
                                v.name, ty
                            ))
                        }
                    };
                    field_types.push(field_llvm_ty);
                }

                // Create anonymous struct type to measure size
                let variant_struct_ty = self.context.struct_type(&field_types, false);
                let size = target_data.get_store_size(&variant_struct_ty);
                if size > max_payload_size {
                    max_payload_size = size;
                }
            }

            // Enum body: { i32 tag, [i64 x N] payload }
            // Alignment Issue: If we use [i8], alignment is 1. If we store i64, we need alignment 8.
            // By using [i64], we enforce alignment 8 for the payload area.
            let tag_type = self.context.i32_type();

            // Calculate number of i64s needed
            let payload_size = std::cmp::max(max_payload_size, 1); // Bytes needed
            let element_count = (payload_size + 7) / 8; // CEIL(bytes / 8)

            let payload_type = self.context.i64_type().array_type(element_count as u32);

            if let Some(st) = self.enum_types.get(&e.name) {
                st.set_body(&[tag_type.into(), payload_type.into()], false);
            }
        }
        Ok(())
    }

    /// Check if a method should be skipped based on its where clause in a concrete impl block.
    /// Returns true if the method should be skipped (bounds not satisfied).
    fn should_skip_concrete_method(&self, method: &crate::compiler::ast::FunctionDef, imp: &ImplBlock) -> bool {
        let wc = match &method.where_clause {
            Some(wc) => wc,
            None => return false, // No where clause, don't skip
        };

        // Get base name and type args from target type
        let base_name = imp.target_type.get_base_name();
        // Parse base name to extract the non-mangled part (e.g., "Vec" from "Vec[Entry[i64][i64]]")
        let simple_base = base_name.split('[').next().unwrap_or(&base_name).to_string();

        // Look up original generic params for this type
        let original_generics = self.generic_impls.get(&simple_base)
            .and_then(|impls| impls.first())
            .map(|i| i.generics.clone())
            .unwrap_or_default();

        if original_generics.is_empty() {
            return false; // Not a generic type, can't check bounds
        }

        // Extract concrete type args from target_type
        let type_args = match &imp.target_type {
            Type::Struct(_, args) | Type::Enum(_, args) => args.clone(),
            Type::SpecializedType { type_args, .. } => type_args.clone(),
            _ => vec![],
        };

        // Check each predicate
        for pred in &wc.predicates {
            let concrete_type = self.resolve_generic_param(&pred.type_param, &type_args, &original_generics);
            let type_name = self.concrete_type_to_trait_key(&concrete_type);

            for bound in &pred.bounds {
                let mut has_trait = self.trait_registry
                    .get(&type_name)
                    .map_or(false, |traits| traits.contains(&bound.trait_name));
                    
                // Primitive trait bound whitelist fallback
                if !has_trait {
                    has_trait = match type_name.as_str() {
                        "i64" | "f64" | "i32" | "f32" | "u8" | "char" | "bool" | "String" => {
                            match bound.trait_name.as_str() {
                                "PartialEq" | "Clone" => true,
                                "PartialOrd" => type_name != "String" && type_name != "bool",
                                _ => false,
                            }
                        }
                        _ => false,
                    };
                }

                if !has_trait {
                    return true; // Bounds not satisfied, skip this method
                }
            }
        }
        false
    }

    fn compile_impl_blocks(&mut self, impls: &[ImplBlock]) -> Result<(), String> {
        // Pass 1: Declare all methods (Prototypes) and register return types
        for imp in impls {
            // Check if generic impl
            let _target_name = imp.target_type.mangled_name_or_name().unwrap_or("").to_string();
            
            // Skip if formal generics are present
            if !imp.generics.is_empty() {
                let target_name = imp.target_type.get_base_name();
                self.generic_impls.entry(target_name).or_default().push(imp.clone());
                continue;
            }
            
            // Also skip if target type name contains unresolved generic parameter references
            // (e.g., "Vec_Entry_K_V" where K, V are not yet bound to concrete types)
            let has_unresolved_generics = {
                let name = &_target_name;
                // Common generic parameter names that indicate unresolved types
                name.contains("_K_") || name.contains("_V_") || name.contains("_T_") ||
                name.contains("_U_") || name.ends_with("_K") || name.ends_with("_V") ||
                name.ends_with("_T") || name.ends_with("_U")
            };
            if has_unresolved_generics {
                // Store as generic impl for later resolution
                self.generic_impls.entry(_target_name.clone()).or_default().push(imp.clone());
                continue;
            }
            


            for method in &imp.methods {
                // Skip methods whose trait bounds are not satisfied
                if self.should_skip_concrete_method(method, imp) {
                    continue;
                }

                let target_name = imp.target_type.mangled_name_or_name().unwrap_or("").to_string();
                let simple_target = &target_name;
                let mangled_name = if method.is_extern {
                    format!("tl_{}_{}", simple_target.to_lowercase(), method.name)
                } else {
                    format!("tl_{}_{}", simple_target, method.name)
                };
                if mangled_name.contains("Vec_i32") {
                }

                // Register return type for lookups by name (Critical for SRET detection)
                self.method_return_types.insert(mangled_name.clone(), method.return_type.clone());
                self.fn_params.insert(mangled_name.clone(), method.args.iter().map(|a| a.1.clone()).collect());

                // SRET is disabled; keep signatures simple.
                let uses_sret = matches!(method.return_type, Type::Struct(_, _));

                let mut param_types: Vec<BasicMetadataTypeEnum> = Vec::new();

                // If sret, add hidden pointer argument at the beginning
                if uses_sret {
                    param_types.push(
                        self.context
                            .ptr_type(inkwell::AddressSpace::default())
                            .into(),
                    );
                }

                // Add regular arguments
                for (_arg_name, arg_ty) in &method.args {
                    let resolved_ty = if let Type::Struct(name, _) = arg_ty {
                        if name == "Self" {
                            imp.target_type.clone()
                        } else {
                            arg_ty.clone()
                        }
                    } else {
                        arg_ty.clone()
                    }.flatten_specialized();

                    let ty: BasicMetadataTypeEnum = match &resolved_ty {
                        Type::F32 => self.context.f32_type().into(),
                        Type::I64 | Type::Entity | Type::Usize => self.context.i64_type().into(),
                        Type::Bool => self.context.bool_type().into(),
                        Type::U8 => self.context.i8_type().into(),
                        Type::Tensor(_, _) => self
                            .context
                            .ptr_type(inkwell::AddressSpace::default())
                            .into(),
                        Type::TraitObject(_) => {
                            let ptr_type = self.context.ptr_type(inkwell::AddressSpace::default());
                            self.context.struct_type(&[ptr_type.into(), ptr_type.into()], false).into()
                        }
                        Type::Struct(_, _) => self
                            .context
                            .ptr_type(inkwell::AddressSpace::default())
                            .into(),
                        Type::String(_) => self
                            .context
                            .ptr_type(inkwell::AddressSpace::default())
                            .into(),
                        Type::Char(_) | Type::I32 => self.context.i32_type().into(),
                        _ => self
                            .context
                            .ptr_type(inkwell::AddressSpace::default())
                            .into(),
                    };
                    param_types.push(ty);
                }

                // Build function type
                let fn_type = if uses_sret {
                    self.context.void_type().fn_type(&param_types, false)
                } else {
                    match &method.return_type.flatten_specialized() {
                        Type::F32 => self.context.f32_type().fn_type(&param_types, false),
                        Type::I64 | Type::Entity | Type::Usize => {
                            self.context.i64_type().fn_type(&param_types, false)
                        }
                        Type::Bool => self.context.bool_type().fn_type(&param_types, false),
                        Type::U8 => self.context.i8_type().fn_type(&param_types, false),
                        Type::Void => self.context.void_type().fn_type(&param_types, false),
                        Type::Tensor(_, _) => self
                            .context
                            .ptr_type(inkwell::AddressSpace::default())
                            .fn_type(&param_types, false),
                        Type::TraitObject(_) => {
                            let ptr_type = self.context.ptr_type(inkwell::AddressSpace::default());
                            self.context.struct_type(&[ptr_type.into(), ptr_type.into()], false).fn_type(&param_types, false)
                        }
                        Type::Struct(_, _) | Type::Tuple(_) | Type::Enum(_, _) | Type::SpecializedType { .. } => self
                            .context
                            .ptr_type(inkwell::AddressSpace::default())
                            .fn_type(&param_types, false),
                        Type::String(_) => self
                            .context
                            .ptr_type(inkwell::AddressSpace::default())
                            .fn_type(&param_types, false),
                        Type::Char(_) | Type::I32 => self.context.i32_type().fn_type(&param_types, false),
                        _ => self.context.void_type().fn_type(&param_types, false),
                    }
                };

                let _function = self.module.add_function(&mangled_name, fn_type, None);
                
                // Register return type for this method
                let return_type = if let Type::Struct(n, _) = &method.return_type {
                    if n == "Self" {
                        imp.target_type.clone()
                    } else {
                        method.return_type.clone()
                    }
                } else {
                    method.return_type.clone()
                };
                self.method_return_types.insert(mangled_name.clone(), return_type);
            }
        }

        // Pass 2: Compile Bodies
        // Pass 2: Compile Bodies
        for imp in impls {
            if !imp.generics.is_empty() {
                continue;
            }


            for method in &imp.methods {
                // Skip methods whose trait bounds are not satisfied
                if self.should_skip_concrete_method(method, imp) {
                    continue;
                }
                let target_name = imp.target_type.mangled_name_or_name().unwrap_or("").to_string();
                let simple_target = &target_name;
                let mangled_name = if method.is_extern {
                     format!("tl_{}_{}", simple_target.to_lowercase(), method.name)
                } else {
                    format!("tl_{}_{}", simple_target, method.name)
                };

                if method.is_extern {
                    continue;
                }
                let function = self
                    .module
                    .get_function(&mangled_name)
                    .ok_or(format!("Function {} not found", mangled_name))?;

                // Compile Body
                let entry = self.context.append_basic_block(function, "entry");
                self.builder.position_at_end(entry);

                // FIX: Must setup function frame for methods too!
                self.variables.clear();
                self.variables.push(std::collections::HashMap::new());
                self.temporaries.clear();
                self.temporaries.push(Vec::new());
                self.variable_liveness.clear();
                self.variable_liveness.push(std::collections::HashMap::new());
                self.loop_stack.clear();
                self.current_time = method.args.len();

                // Liveness Analysis
                self.function_analysis = Some(crate::compiler::liveness::LivenessAnalyzer::analyze(method));
                let num_slots = self.function_analysis.as_ref().map(|a| a.num_slots).unwrap_or(0);
                
                if let Some(enter_fn) = self.module.get_function("tl_mem_function_enter") {
                     self.builder.build_call(
                         enter_fn,
                         &[self.context.i64_type().const_int(num_slots as u64, false).into()],
                         ""
                     ).unwrap();
                } else {
                    // Declare it if missing
                    let i64_type = self.context.i64_type();
                    let fn_type = self.context.void_type().fn_type(&[i64_type.into()], false);
                    let enter_fn = self.module.add_function("tl_mem_function_enter", fn_type, None);
                    self.builder.build_call(
                         enter_fn,
                         &[self.context.i64_type().const_int(num_slots as u64, false).into()],
                         ""
                     ).unwrap();
                }

                self.fn_entry_scope_depth = self.variables.len();
                self.enter_scope();

                // SRET is disabled; keep signatures simple.
                let uses_sret = matches!(method.return_type, Type::Struct(_, _));
                let param_offset = if uses_sret { 
                     // Register SRET pointer
                     if let Some(sret_param) = function.get_nth_param(0) {
                         if sret_param.is_pointer_value() {
                             sret_param.set_name("sret");
                             self.current_sret_dest = Some(sret_param.into_pointer_value());
                         } else {
                         }
                     } else {
                     }
                     1 
                } else { 
                     self.current_sret_dest = None;
                     0 
                };

                // Get params and store them (skip sret param if present)
                for (i, (arg_name, arg_ty)) in method.args.iter().enumerate() {
                    let resolved_ty = if let Type::Struct(name, _) = arg_ty {
                        if name == "Self" {
                            imp.target_type.clone()
                        } else {
                            arg_ty.clone()
                        }
                    } else {
                        arg_ty.clone()
                    }.flatten_specialized();

                    if let Some(param_val) = function.get_nth_param((i + param_offset) as u32) {
                        param_val.set_name(arg_name);
                        let alloca =
                            self.create_entry_block_alloca(function, arg_name, &resolved_ty)?;
                        self.builder.build_store(alloca, param_val).unwrap();

                        // Register in scope
                        self.variables
                            .last_mut()
                            .unwrap()
                            .insert(arg_name.clone(), (alloca.into(), resolved_ty, CLEANUP_NONE));
                            
                        let arg_time = i + 1; // 1-indexed like visit_function
                        let last_use = if let Some(analysis) = &self.function_analysis {
                            analysis.last_use_times.get(&arg_time).copied().unwrap_or(0)
                        } else { 0 };
                        
                        self.variable_liveness
                            .last_mut()
                            .unwrap()
                            .insert(arg_name.clone(), last_use);
                    }
                }

                for (i, stmt) in method.body.iter().enumerate() {
                    if i == method.body.len() - 1 && method.return_type != Type::Void {
                        // Check if it's an expression that should be returned
                        if let StmtKind::Expr(expr) = &stmt.inner {
                            let (val, ty) = self.compile_expr(expr)?;
                            
                            // FIX: Logic parity with compile_function implicit return
                            // FIX: Logic parity with compile_function implicit return
                            if let ExprKind::Variable(name) = &expr.inner {
                                for scope in self.variables.iter_mut().rev() {
                                    if let Some((_, _, cleanup)) = scope.get_mut(name) {
                                        *cleanup = CLEANUP_NONE;
                                        // Unregister handled in match block below
                                        break;
                                    }
                                }
                            }
                            // Also mark temp no cleanup (for direct expressions)
                            self.mark_temp_no_cleanup(val);

                            let mut final_val = val;
                            match &ty {
                                Type::Tensor(_, _) => {
                                    if let Some(prepare_fn) = self.module.get_function("tl_tensor_prepare_return") {
                                        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_prep_ret").unwrap();
                                        let call = self.builder.build_call(prepare_fn, &[cast_ptr.into()], "ret_ptr").unwrap();
                                        use inkwell::values::ValueKind;
                                        if let ValueKind::Basic(basic_val) = call.try_as_basic_value() {
                                            final_val = basic_val;
                                        }
                                    } else {
                                         self.emit_recursive_unregister(val, &ty)?;
                                    }
                                }
                                Type::Struct(_, _) => {
                                    // SRET Handling for Implicit Returns
                                    if let Some(sret_ptr) = self.current_sret_dest {
                                         let src_ptr = val.into_pointer_value();
                                         self.builder.build_store(sret_ptr, src_ptr).unwrap();

                                         if let Some(unreg_fn) = self.module.get_function("tl_mem_unregister") {
                                             let void_ptr_type = self.context.ptr_type(inkwell::AddressSpace::default());
                                             let cast_ptr = self.builder.build_pointer_cast(src_ptr, void_ptr_type, "cast_unreg_sret").unwrap();
                                             self.builder.build_call(unreg_fn, &[cast_ptr.into()], "").unwrap();
                                         }
                                         
                                         // DISABLED: SRET source free — exit_scope に解放を任せる。
                                         // sub-struct CLEANUP_FULL + promote で field/variable レベルの解放を行い、
                                         // exit_scope の emit_all_scopes_cleanup で SRET source struct を解放する。
                                         // self.emit_recursive_free(src_ptr.into(), &ty, CLEANUP_FULL)?;
                                         
                                         self.emit_all_scopes_cleanup();
                                         // REMOVED: self.variables.pop(); // Handled by exit_scope later
                                         if let Some(exit_fn) = self.module.get_function("tl_mem_function_exit") {
                                                self.builder.build_call(exit_fn, &[], "").unwrap();
                                         }
                                         self.builder.build_return(None).unwrap();
                                         continue;
                                    }

                                    // FIX: Unregister Structs being returned (Shallow Unregister)
                                    // This applies to both Variables (CLEANUP_NONE above) and Temporary Expressions usually.
                                    // Ownership is transferred to caller.
                                    if let Some(unreg_fn) = self.module.get_function("tl_mem_unregister") {
                                         let ptr = val.into_pointer_value();
                                         let ptr_type = self.context.ptr_type(inkwell::AddressSpace::default());
                                         // val is already the Struct* (from compile_expr)
                                         let cast_ptr = self.builder.build_pointer_cast(
                                             ptr,
                                             ptr_type,
                                             "cast_unreg"
                                         ).unwrap(); 
                                         self.builder.build_call(unreg_fn, &[cast_ptr.into()], "").unwrap();
                                    }
                                }
                                _ => {
                                    self.emit_recursive_unregister(val, &ty)?;
                                }
                            }

                            self.emit_all_scopes_cleanup();
                            self.variables.pop();

                            if let Some(exit_fn) = self.module.get_function("tl_mem_function_exit") {
                                 self.builder.build_call(exit_fn, &[], "").unwrap();
                            }

                            self.builder
                                .build_return(Some(&final_val))
                                .map_err(|e| e.to_string())?;
                            continue;
                        }
                    }
                    self.compile_stmt(stmt)?;
                }

                self.exit_scope(); // End method scope

                let is_terminated = self
                    .builder
                    .get_insert_block()
                    .map(|b| b.get_terminator().is_some())
                    .unwrap_or(false);
                if !is_terminated {
                    let ret_ty = self.get_llvm_type(&method.return_type).unwrap_or(self.context.i8_type().into());
                    if let Type::Void = method.return_type {
                        self.builder.build_return(None).unwrap();
                    } else if ret_ty.is_struct_type() {
                        let s = ret_ty.into_struct_type().const_zero();
                        self.builder.build_return(Some(&s)).unwrap();
                    } else if ret_ty.is_pointer_type() {
                        self.builder.build_return(Some(&ret_ty.into_pointer_type().const_null())).unwrap();
                    } else if ret_ty.is_int_type() {
                        self.builder.build_return(Some(&ret_ty.into_int_type().const_zero())).unwrap();
                    } else if ret_ty.is_float_type() {
                        self.builder.build_return(Some(&ret_ty.into_float_type().const_zero())).unwrap();
                    } else {
                        self.builder.build_unreachable().unwrap();
                    }
                }

                self.exit_scope();

                if !function.verify(true) {
                    function.print_to_stderr();
                    return Err(format!("Invalid generated method {}", mangled_name));
                }
            }
        }
        Ok(())
    }

    pub fn compile_module(&mut self, ast_module: &Module, module_name: &str) -> Result<(), String> {


        // Generate Logic KB initialization function
        self.compile_kb_init_function(ast_module, module_name)?;

        // Compile submodules recursively
        for (sub_name, submodule) in &ast_module.submodules {
            self.compile_module(submodule, sub_name)?;
        }

        // Collect Traits mapping
        for tr in &ast_module.traits {
            self.trait_defs.insert(tr.name.clone(), tr.clone());
        }

        // 1. Declare structs (types) and methods
        self.compile_struct_defs(&ast_module.structs)?;
        self.compile_enum_defs(&ast_module.enums)?;
        self.compile_struct_defs(&ast_module.structs)?;
        self.compile_enum_defs(&ast_module.enums)?;
        self.compile_relation_wrappers(&ast_module.relations)?;

        for r in &ast_module.relations {
            self.relations.insert(r.name.clone());
        }

        // Prepare functions list, potentially adding synthetic main
        let mut synthetic_main = None;
        let mut functions_refs = Vec::new();
        let mut main_exists = false;

        for func in &ast_module.functions {
            // If function is generic, skip compilation and store in registry
            if !func.generics.is_empty() {
                self.generic_fn_defs.insert(func.name.clone(), func.clone());
                continue;
            }

            if func.name == "main" {
                main_exists = true;
            }
            functions_refs.push(func);
        }

        if !main_exists && !ast_module.tensor_decls.is_empty() {
            let syn_main = FunctionDef {
                name: "main".to_string(),
                args: vec![],
                return_type: Type::Void,
                body: vec![],
                generics: vec![],
                generic_bounds: vec![],
                where_clause: None,
                is_extern: false,
                is_pub: false,
            };
            synthetic_main = Some(syn_main);
            // We can't push reference to local variable easily here due to lifetimes.
            // But we can iterate separately or handle logic below.
        }

        // 2. Declare functions (prototypes)
        for func in &functions_refs {
            self.compile_fn_proto(func)?;
        }
        if let Some(func) = &synthetic_main {
            self.compile_fn_proto(func)?;
        }

        // 3. Compile Impl Blocks (Declare Method Prototypes + Body)
        // Moved after function proto conversion so methods can call global functions
        self.compile_impl_blocks(&ast_module.impls)?;

        // 3.5. Compile Trait Impl Blocks as regular impl blocks
        // TraitImplBlock methods compile identically to ImplBlock methods
        let trait_impl_blocks: Vec<ImplBlock> = ast_module.trait_impls.iter().map(|ti| {
            ImplBlock {
                target_type: ti.target_type.clone(),
                generics: ti.generics.clone(),
                generic_bounds: ti.generic_bounds.clone(),
                where_clause: ti.where_clause.clone(),
                methods: ti.methods.clone(),
            }
        }).collect();
        self.compile_impl_blocks(&trait_impl_blocks)?;

        // 4. Compile function bodies
        for func in &functions_refs {
            if func.is_extern {
                continue;
            }
            let extra: &[Stmt] = if func.name == "main" {
                &ast_module.tensor_decls
            } else {
                &[]
            };
            self.compile_fn(func, extra)?;
        }
        if let Some(func) = &synthetic_main {
            self.compile_fn(func, &ast_module.tensor_decls)?;
        }

        // 5. Compile deferred functions (monomorphized on-demand)
        // Note: compile_fn might trigger more monomorphizations, so we loop until empty.
        while !self.pending_functions.is_empty() {
            let batch = std::mem::take(&mut self.pending_functions);
            for (func, subst) in batch {
                self.current_method_generics = subst;
                self.compile_fn(&func, &[])?;
                self.current_method_generics = None;
            }
        }

        // 6. Generate methods for specialized types registered in SpecializationRegistry
        // [DELETED in V6.0 AOT Monomorphization]: Monomorphizer now handles this entirely.
        // Loop removed to prevent double-generation and bypass of generic resolution.

        // Apply LLVM optimizations
        if let Err(e) = self.module.verify() {
            self.module.print_to_stderr();
            return Err(format!("Module verification failed: {}", e.to_string()));
        }

        self.apply_optimizations();
        self.module.print_to_file("dump.ll").ok();
        Ok(())
    }

    pub(crate) fn lookup_variable(&self, name: &str) -> Option<(BasicValueEnum<'ctx>, Type)> {
        for scope in self.variables.iter().rev() {
            if let Some((v, t, _)) = scope.get(name) {
                return Some((*v, t.clone()));
            }
        }
        None
    }

    pub(crate) fn lookup_scope_depth(&self, name: &str) -> Option<usize> {
        for (i, scope) in self.variables.iter().enumerate().rev() {
            if scope.contains_key(name) {
                return Some(i);
            }
        }
        None
    }

    pub(crate) fn is_outer_scope(&self, name: &str) -> bool {
        if let Some(depth) = self.lookup_scope_depth(name) {
            // Current depth is self.variables.len() - 1
            if depth < self.variables.len() - 1 {
                return true;
            }
        }
        false
    }

    pub(crate) fn compile_fn_proto(&mut self, func: &FunctionDef) -> Result<FunctionValue<'ctx>, String> {
        if func.name.contains("Vec") && func.name.contains("K") {
            panic!("COMPILE_FN_PROTO_CALLED_FOR_{}!!", func.name);
        }
        // Register return type for lookups by name (Critical for SRET detection)
        self.method_return_types.insert(func.name.clone(), func.return_type.clone());
        self.fn_params.insert(func.name.clone(), func.args.iter().map(|a| a.1.clone()).collect());

        // Check if this function returns a struct or enum (requires sret)
        // Let's assume Structs/Enums need SRET, but Tensors do NOT.
        // String is a pointer, so exclusion is needed.
        let uses_sret = matches!(&func.return_type, Type::Struct(name, _) if name != "Tensor" && name != "String");

        let mut args_types = Vec::new();

        // If sret, add hidden pointer argument at the beginning
        if uses_sret {
            args_types.push(
                self.context
                    .ptr_type(inkwell::AddressSpace::default())
                    .into(),
            );
        }

        // Add regular arguments
        for (_, val) in &func.args {
            let arg_ty_val = self.get_llvm_type(val).map_err(|e| format!("Error compiling arg type {:?}: {}", val, e))?;
            let arg_ty: inkwell::types::BasicMetadataTypeEnum = arg_ty_val.into();
            args_types.push(arg_ty);
        }

        // Build function type
        let fn_type = if uses_sret {
            // Sret functions return void
            self.context.void_type().fn_type(&args_types, false)
        } else {
            let ret_type: Option<inkwell::types::BasicTypeEnum> = if let Type::Void = func.return_type {
                None
            } else {
                Some(self.get_llvm_type(&func.return_type).map_err(|e| format!("Error compiling return type {:?}: {}", func.return_type, e))?)
            };

            match ret_type {
                Some(ty) => ty.fn_type(&args_types, false),
                None => self.context.void_type().fn_type(&args_types, false),
            }
        };

        let val = if let Some(existing) = self.module.get_function(&func.name) {
            existing
        } else {
            self.module.add_function(&func.name, fn_type, None)
        };
        // Add param names for debug
        let param_offset = if uses_sret { 1 } else { 0 };
        if uses_sret {
            if let Some(sret_param) = val.get_nth_param(0) {
                sret_param.set_name("sret");
            }
        }
        for (i, arg) in val.get_param_iter().skip(param_offset).enumerate() {
            arg.set_name(&func.args[i].0);
        }

        // Register return type for this function
        self.method_return_types.insert(func.name.clone(), func.return_type.clone());
        self.fn_params.insert(func.name.clone(), func.args.iter().map(|a| a.1.clone()).collect());

        Ok(val)
    }

    pub(crate) fn compile_fn(&mut self, func: &FunctionDef, extra_stmts: &[Stmt]) -> Result<(), String> {
        let old_ret_type = self.current_fn_return_type.clone();
        self.current_fn_return_type = Some(func.return_type.clone());

        let function = self
            .module
            .get_function(&func.name)
            .ok_or("Function not found")?;

        // Run Liveness Analysis
        self.function_analysis = Some(crate::compiler::liveness::LivenessAnalyzer::analyze(func));

        // RESET STATE for new function to prevent leaking temporaries/variables from previous functions
        self.variables.clear();
        self.variables.push(std::collections::HashMap::new());
        self.temporaries.clear();
        self.temporaries.push(Vec::new());
        self.variable_liveness.clear();
        self.variable_liveness.push(std::collections::HashMap::new());
        self.loop_stack.clear();
        
        // Reset time for liveness synchronization
        self.current_time = func.args.len();

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

        // SETUP FUNCTION FRAME (SLOTS)
        let num_slots = self.function_analysis.as_ref().map(|a| a.num_slots).unwrap_or(0);
        
        if let Some(enter_fn) = self.module.get_function("tl_mem_function_enter") {
             self.builder.build_call(
                 enter_fn,
                 &[self.context.i64_type().const_int(num_slots as u64, false).into()],
                 ""
             ).unwrap();
        } else {
            // Declare it if missing
            let i64_type = self.context.i64_type();
            let fn_type = self.context.void_type().fn_type(&[i64_type.into()], false);
            let enter_fn = self.module.add_function("tl_mem_function_enter", fn_type, None);
            self.builder.build_call(
                 enter_fn,
                 &[self.context.i64_type().const_int(num_slots as u64, false).into()],
                 ""
             ).unwrap();
        }

        // Push a new scope for function arguments
        self.fn_entry_scope_depth = self.variables.len();
        self.enter_scope(); // Function scope


        // Check if this function returns a struct or enum (requires sret)
        let uses_sret = matches!(&func.return_type, Type::Struct(name, _) if name != "Tensor" && name != "String");
        let param_offset = if uses_sret { 1 } else { 0 };

        if uses_sret {
             if let Some(param) = function.get_nth_param(0) {
                 self.current_sret_dest = Some(param.into_pointer_value());
             }
        } else {
             self.current_sret_dest = None;
        }

        // Register arguments (skip sret param if present)
        let mut arg_time = 0;
        for (i, arg) in function.get_param_iter().skip(param_offset).enumerate() {
            arg_time += 1;
            let (arg_name, arg_type) = &func.args[i];
            let alloca = self.create_entry_block_alloca(function, arg_name, arg_type)?;

            // Borrowing Semantics: Just store the pointer/value.
            // Do NOT Acquire/DeepClone. The caller owns the data.
            match arg {
                inkwell::values::BasicValueEnum::PointerValue(p) => {
                    self.builder.build_store(alloca, p).unwrap()
                }
                inkwell::values::BasicValueEnum::FloatValue(f) => {
                    self.builder.build_store(alloca, f).unwrap()
                }
                inkwell::values::BasicValueEnum::IntValue(v) => {
                    self.builder.build_store(alloca, v).unwrap()
                }
                inkwell::values::BasicValueEnum::StructValue(s) => {
                    self.builder.build_store(alloca, s).unwrap()
                }
                inkwell::values::BasicValueEnum::ArrayValue(a) => {
                    self.builder.build_store(alloca, a).unwrap()
                }
                _ => return Err(format!("Unsupported arg type: {:?}", arg)),
            };

            // Insert into current scope with should_free=FALSE
            // Arguments are BORROWED. Function must NOT free them on exit.
            self.variables
                .last_mut()
                .unwrap()
                .insert(arg_name.clone(), (alloca.into(), arg_type.clone(), CLEANUP_NONE));
                
            let last_use = if let Some(analysis) = &self.function_analysis {
                analysis.last_use_times.get(&arg_time).copied().unwrap_or(0)
            } else { 0 };
            
            self.variable_liveness
                .last_mut()
                .unwrap()
                .insert(arg_name.clone(), last_use);
        }

        // Initialize Arena in main if needed
        if func.name == "main" {
            // Logic Engine Init - MUST be before anything else
            if let Some(init_kb) = self.module.get_function("_tl_init_kb") {
                self.builder.build_call(init_kb, &[], "").unwrap();
            }
            // Execute infer to ensure queries work inside main
            if let Some(infer_fn) = self.module.get_function("tl_kb_infer") {
                self.builder.build_call(infer_fn, &[], "").unwrap();
            }

            let mut analyzer = ShapeAnalyzer::new();
            let profile = analyzer.analyze_block(&func.body);
            // Heuristic: If we have static tensors or significant allocations, init arena
            // We assume safe upper bound for OpaqueTensor size (around 32-48 bytes usually, use 64 for safety)
            // Plus the actual static tensor data size.
            let mut total_capacity = profile.total_static_size.unwrap_or(0);
            total_capacity += profile.max_allocations * 512; // Increased per-allocation overhead

            if total_capacity > 0 || profile.max_allocations > 0 {
                // Minimum arena size: 64KB
                total_capacity = total_capacity.max(65536);
                // Align to page size (4096) roughly, or just use what we need.
                // call tl_arena_init(capacity)
                let init_fn = self
                    .module
                    .get_function("tl_arena_init")
                    .or_else(|| {
                        // Declare if missing (should be in builtins but just in case)
                        let i64_type = self.context.i64_type();
                        let fn_type = self.context.void_type().fn_type(&[i64_type.into()], false);
                        let f = self.module.add_function("tl_arena_init", fn_type, None);
                        Some(f)
                    })
                    .unwrap();

                self.builder
                    .build_call(
                        init_fn,
                        &[self
                            .context
                            .i64_type()
                            .const_int(total_capacity as u64, false)
                            .into()],
                        "",
                    )
                    .unwrap();
            }
        }

        // Compile extra statements (e.g. top-level tensor decls)
        for stmt in extra_stmts {
            self.compile_stmt(stmt)?;
        }

        // Compile body
        let body_len = func.body.len();
        for (i, stmt) in func.body.iter().enumerate() {
            if i == body_len - 1 && func.return_type != Type::Void {
                // Check if it's an expression that should be returned
                if let StmtKind::Expr(expr) = &stmt.inner {
                    let (mut val, mut ty) = self.compile_expr(expr)?;

                    // Implicit TraitObject Upcast for implicit Return
                    let current_ret_is_trait = if let Some(Type::TraitObject(trait_name)) = &self.current_fn_return_type {
                        Some(trait_name.clone())
                    } else { None };

                    if let Some(trait_name) = current_ret_is_trait {
                        if let Type::Struct(struct_name, _) = &ty {
                            val = self.emit_trait_object_upcast(val, struct_name, &trait_name)?;
                            ty = Type::TraitObject(trait_name);
                        }
                    }

                    // FIX: Logic parity with StmtKind::Return
                    // Ensure the returned value is NOT cleaned up by emit_all_scopes_cleanup.
                    if let ExprKind::Variable(name) = &expr.inner {
                        for scope in self.variables.iter_mut().rev() {
                            if let Some((_, _, cleanup)) = scope.get_mut(name) {
                                *cleanup = CLEANUP_NONE;
                                break;
                            }
                        }
                    }
                    self.mark_temp_no_cleanup(val);

                    if uses_sret {
                         // SRET Logic
                         if let Some(dest) = self.current_sret_dest {
                             let src_ptr = val.into_pointer_value();
                             self.builder.build_store(dest, src_ptr).unwrap();
                             
                             if let Some(unreg_fn) = self.module.get_function("tl_mem_unregister") {
                                 let void_ptr_type = self.context.ptr_type(inkwell::AddressSpace::default());
                                 let cast_ptr = self.builder.build_pointer_cast(src_ptr, void_ptr_type, "cast_unreg_sret").unwrap();
                                 self.builder.build_call(unreg_fn, &[cast_ptr.into()], "").unwrap();
                             }
                             // FIXME: Now that we just store the pointer, we must NOT free the source struct
                             // because the caller now owns that heap-allocated struct pointer!
                             // self.emit_recursive_free(src_ptr.into(), &ty, CLEANUP_FULL)?;
                         }
                         // FIX: main 関数のクリーンアップ SIGBUS 回避
                         if func.name == "main" {
                             let exit_fn = self.module.get_function("exit")
                                 .unwrap_or_else(|| {
                                     let void_ty = self.context.void_type();
                                     let i32_ty = self.context.i32_type();
                                     let ft = void_ty.fn_type(&[i32_ty.into()], false);
                                     self.module.add_function("exit", ft, None)
                                 });
                             self.builder.build_call(exit_fn, &[self.context.i32_type().const_int(0, false).into()], "").unwrap();
                             self.builder.build_unreachable().unwrap();
                             self.current_fn_return_type = old_ret_type;
                             return Ok(());
                         }
                         self.emit_all_scopes_cleanup();
                         self.variables.pop(); // Compiler scope cleanup
                         
                         // Calls to function exit must happen before return
                         if let Some(exit_fn) = self.module.get_function("tl_mem_function_exit") {
                              self.builder.build_call(exit_fn, &[], "").unwrap();
                         }

                         self.builder.build_return(None).map_err(|e| e.to_string())?;
                    } else {
                        // IMPORTANT: Unregister return value (same as StmtKind::Return)
                        // Use tl_tensor_prepare_return if available


                        let mut final_val = val; 
                        match &ty {
                            Type::Tensor(_, _) => {
                                if let Some(prepare_fn) = self.module.get_function("tl_tensor_prepare_return") {
                                    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_prep_ret").unwrap();
                                    let call = self.builder.build_call(prepare_fn, &[cast_ptr.into()], "ret_ptr").unwrap();
                                    use inkwell::values::ValueKind;
                                    if let ValueKind::Basic(basic_val) = call.try_as_basic_value() {
                                        final_val = basic_val;
                                    }
                                } else {
                                     self.emit_recursive_unregister(val, &ty)?;
                                }
                            }
                            Type::Struct(_, _) => {
                                // Recursive Unregister (Deep)
                                // This ensures fields (Tensors) are removed from Runtime Scope
                                // preventing Double Free when scope exits.
                                self.emit_recursive_unregister(val, &ty)?;
                            }
                            _ => {
                                self.emit_recursive_unregister(val, &ty)?;
                            }
                        }

                        // FIX: main 関数のクリーンアップ SIGBUS 回避
                        if func.name == "main" {
                            let exit_fn = self.module.get_function("exit")
                                .unwrap_or_else(|| {
                                    let void_ty = self.context.void_type();
                                    let i32_ty = self.context.i32_type();
                                    let ft = void_ty.fn_type(&[i32_ty.into()], false);
                                    self.module.add_function("exit", ft, None)
                                });
                            self.builder.build_call(exit_fn, &[self.context.i32_type().const_int(0, false).into()], "").unwrap();
                            self.builder.build_unreachable().unwrap();
                            self.current_fn_return_type = old_ret_type;
                            return Ok(());
                        }
                        self.emit_all_scopes_cleanup();

                        // CRITICAL FIX: Pop the function scope from variables stack
                        self.variables.pop();
                        
                        // Call function exit helper BEFORE return
                        if let Some(exit_fn) = self.module.get_function("tl_mem_function_exit") {
                             self.builder.build_call(exit_fn, &[], "").unwrap();
                        }

                        if ty == Type::Void && func.return_type != Type::Void {
                            self.builder.build_unreachable().unwrap();
                        } else {
                            self.builder
                                .build_return(Some(&final_val))
                                .map_err(|e| e.to_string())?;
                        }
                    }
                                self.current_fn_return_type = old_ret_type;
                    return Ok(()); // RETURN EARLY - Function is done
                }
            }
            self.compile_stmt(stmt)?;
        }

        // FIX: main 関数ではネスト構造体の RC 不整合により exit_scope 内の
        // emit_recursive_free でダングリングポインタアクセス (SIGBUS) が発生する。
        // main 関数終了時はプロセスが終了するため、OS がメモリを回収する — cleanup は不要。
        // exit(0) を呼んでプロセスを安全に終了し、compile_fn から early return して
        // exit_scope の cleanup IR 生成自体をスキップする。
        if func.name == "main" {
            if self.builder.get_insert_block().unwrap().get_terminator().is_none() {
                let exit_fn = self.module.get_function("exit")
                    .unwrap_or_else(|| {
                        let void_ty = self.context.void_type();
                        let i32_ty = self.context.i32_type();
                        let ft = void_ty.fn_type(&[i32_ty.into()], false);
                        self.module.add_function("exit", ft, None)
                    });
                self.builder.build_call(exit_fn, &[self.context.i32_type().const_int(0, false).into()], "").unwrap();
                self.builder.build_unreachable().unwrap();
            }
            self.current_fn_return_type = old_ret_type;
            return Ok(());
        }

        self.exit_scope(); // End function scope

        // CLEANUP FUNCTION FRAME
        // Only if block is NOT terminated (e.g. no return statement at flow end)
        if self.builder.get_insert_block().unwrap().get_terminator().is_none() {
             if let Some(exit_fn) = self.module.get_function("tl_mem_function_exit") {
                  self.builder.build_call(exit_fn, &[], "").unwrap();
             }

             let ret_ty = self.get_llvm_type(&func.return_type).unwrap_or(self.context.i8_type().into());
             if func.return_type == Type::Void {
                 self.builder.build_return(None).map_err(|e| e.to_string())?;
             } else if ret_ty.is_struct_type() {
                 let s = ret_ty.into_struct_type().const_zero();
                 self.builder.build_return(Some(&s)).unwrap();
             } else if ret_ty.is_pointer_type() {
                 self.builder.build_return(Some(&ret_ty.into_pointer_type().const_null())).unwrap();
             } else if ret_ty.is_int_type() {
                 self.builder.build_return(Some(&ret_ty.into_int_type().const_zero())).unwrap();
             } else if ret_ty.is_float_type() {
                 self.builder.build_return(Some(&ret_ty.into_float_type().const_zero())).unwrap();
             } else {
                 self.builder.build_unreachable().unwrap();
             }
        }


        if !function.verify(true) {
            log::error!("=== LLVM VERIFICATION FAILED FOR: {} ===", func.name);
            // function.verify(true) should print the error to stderr
            function.print_to_stderr();
            return Err(format!("Invalid generated function {}", func.name));
        }

        self.current_fn_return_type = old_ret_type;
        Ok(())
    }

    fn apply_optimizations(&self) {
        // OptimizationLevel::Aggressive is already set in execution_engine initialization.
        // Manual pass management requires exact matching of inkwell/LLVM versioned methods.
    }

    fn compile_relation_wrappers(&mut self, relations: &[RelationDecl]) -> Result<(), String> {
        if relations.is_empty() {
            return Ok(());
        }

        // Register return types FIRST so recursive/future calls find it
        for _relation in relations {
        }

        let i64_type = self.context.i64_type();
        let tensor_ptr_type = self.context.ptr_type(inkwell::AddressSpace::default());

        // Runtime function tl_query
        let tl_query_fn = self
            .module
            .get_function("tl_query")
            .ok_or("tl_query must be declared")?;
        // Runtime function tl_tensor_from_i64_array
        let tl_tensor_from_arr_fn = self
            .module
            .get_function("tl_tensor_from_i64_array")
            .ok_or("tl_tensor_from_i64_array must be declared")?;
        // Runtime function tl_tensor_free
        let tl_tensor_free_fn = self
            .module
            .get_function("tl_tensor_free")
            .ok_or("tl_tensor_free must be declared")?;
        // Runtime function tl_ptr_inc_ref
        let _tl_ptr_inc_ref_fn = self
            .module
            .get_function("tl_ptr_inc_ref")
            .or_else(|| {
                let void_ty = self.context.void_type();
                let ptr_ty = self.context.ptr_type(inkwell::AddressSpace::default());
                let ft = void_ty.fn_type(&[ptr_ty.into()], false);
                Some(self.module.add_function("tl_ptr_inc_ref", ft, None))
            })
            .ok_or("tl_ptr_inc_ref decl failed")?;

        for rel in relations {
            let func_name = &rel.name;
            // Args: mask (i64), arg1 (i64), arg2 (i64)...
            let mut arg_types = vec![i64_type.into()]; // mask
            for _ in 0..rel.args.len() {
                arg_types.push(i64_type.into());
            }
            // Tags pointer (as ALLOCATED INT for safe passing)
            arg_types.push(i64_type.into());

            let fn_type = tensor_ptr_type.fn_type(&arg_types, false);
            let function = self.module.add_function(func_name, fn_type, None);

            let basic_block = self.context.append_basic_block(function, "entry");
            self.builder.position_at_end(basic_block);

            // Build name string
            let name_global = self
                .builder
                .build_global_string_ptr(func_name, "rel_name")
                .unwrap();
            let name_ptr = name_global.as_pointer_value();

            // Get mask
            let mask_arg = function.get_nth_param(0).unwrap().into_int_value();

            // Pack other args into array
            let num_args = rel.args.len();
            if num_args > 0 {
                let arr_type = i64_type.array_type(num_args as u32);
                let arr_alloca = self.builder.build_alloca(arr_type, "args_arr").unwrap();

                for i in 0..num_args {
                    let arg_val = function
                        .get_nth_param((i + 1) as u32)
                        .unwrap()
                        .into_int_value();
                    // Store in array
                    // GEP to element i
                    let ptr = unsafe {
                        self.builder
                            .build_gep(
                                arr_type,
                                arr_alloca,
                                &[
                                    i64_type.const_int(0, false),
                                    i64_type.const_int(i as u64, false),
                                ],
                                "",
                            )
                            .unwrap()
                    };
                    self.builder.build_store(ptr, arg_val).unwrap();
                }

                // Create tensor from array
                // tl_tensor_from_i64_array expects pointer to i64 (decayed array) and size
                let decayed_ptr = unsafe {
                    self.builder
                        .build_gep(
                            arr_type,
                            arr_alloca,
                            &[i64_type.const_int(0, false), i64_type.const_int(0, false)],
                            "decayed",
                        )
                        .unwrap()
                };

                let call = self
                    .builder
                    .build_call(
                        tl_tensor_from_arr_fn,
                        &[
                            decayed_ptr.into(),
                            i64_type.const_int(num_args as u64, false).into(),
                        ],
                        "args_tensor",
                    )
                    .unwrap();
                let args_tensor = self.check_tensor_result(call, "args_tensor_error")?;

                // Get tags passed from call-site
                let tags_arg = function.get_nth_param((num_args + 1) as u32).unwrap();

                // Call tl_query
                let result_tensor = match self
                    .builder
                    .build_call(
                        tl_query_fn,
                        &[
                            name_ptr.into(),
                            mask_arg.into(),
                            args_tensor.into(),
                            self.builder.build_int_to_ptr(tags_arg.into_int_value(), self.context.ptr_type(AddressSpace::default()), "tags_ptr").unwrap().into(),
                        ],
                        "res",
                    )
                    .unwrap()
                    .try_as_basic_value()
                {
                    ValueKind::Basic(v) => v,
                    _ => return Err("Expected value from tl_query".to_string()),
                };

                // Free args_tensor (it was created for this call)
                self.builder
                    .build_call(tl_tensor_free_fn, &[args_tensor.into()], "")
                    .unwrap();

                self.builder.build_return(Some(&result_tensor)).unwrap();
            } else {
                // No args case
                // Create empty tensor
                // Or pass null? tl_query check for null args
                let null_ptr = tensor_ptr_type.const_null();
                let tags_arg = function.get_nth_param(1).unwrap(); // tags is at index 1 for no-arg relation
                let result_tensor = match self
                    .builder
                    .build_call(
                        tl_query_fn,
                        &[
                            name_ptr.into(),
                            mask_arg.into(),
                            null_ptr.into(),
                            self.builder.build_int_to_ptr(tags_arg.into_int_value(), self.context.ptr_type(AddressSpace::default()), "tags_ptr").unwrap().into(),
                        ],
                        "res",
                    )
                    .unwrap()
                    .try_as_basic_value()
                {
                    ValueKind::Basic(v) => v,
                    _ => return Err("Expected value from tl_query".to_string()),
                };
                self.builder.build_return(Some(&result_tensor)).unwrap();
            }

            if !function.verify(true) {
                return Err(format!("Invalid generated relation wrapper {}", func_name));
            }
        }
        Ok(())
    }
}