1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
// WASM backend code generator
//
// This module generates WebAssembly modules from MIR (Mid-level Intermediate Representation).
// It uses the wasm-encoder crate to emit WASM bytecode and relies on RuntimePrimitives
// for heap, state, and array operations through imported host functions.
//
// Architecture:
// - MIR operations -> WASM instructions
// - Runtime operations (heap, state, arrays) -> imported host functions
// - Closures and higher-order functions -> WASM function references and tables
// - Memory layout: linear memory for stack and runtime primitive data
use crate::interner::{Symbol, TypeNodeId};
use crate::mir::{self, Mir, VPtr};
use crate::runtime::primitives::WordSize;
use crate::types::{PType, Type, TypeSize};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use wasm_encoder::{
CodeSection, DataSection, ElementSection, EntityType, ExportSection, Function, FunctionSection,
GlobalSection, ImportSection, MemArg, MemorySection, MemoryType, Module, NameMap, NameSection,
TableSection, TableType, TypeSection, ValType,
};
/// Upper bound of `$arityN` builtin specializations imported for WASM.
///
/// We predeclare a finite set of imports (`split_head$arityN`, `split_tail$arityN`,
/// `prepend$arityN`, `append$arityN`) to avoid generating unbounded host import symbols while still
/// covering practical aggregate element sizes used by current codegen.
///
/// Keep this value in sync with runtime registration in `runtime/wasm.rs`.
const MAX_SPECIALIZED_BUILTIN_ARITY: usize = 16;
/// Plugin function import indices
#[derive(Debug, Clone, Default)]
struct PluginFunctionIndices {
/// Map: function name -> WASM import index
functions: HashMap<Symbol, u32>,
}
/// Runtime primitive function indices for calling imports
#[derive(Debug, Clone, Default)]
struct RuntimeFunctionIndices {
heap_alloc: u32,
heap_retain: u32,
heap_release: u32,
heap_load: u32,
heap_store: u32,
box_alloc: u32,
box_load: u32,
box_clone: u32,
box_release: u32,
box_store: u32,
usersum_clone: u32,
usersum_release: u32,
closure_make: u32,
closure_close: u32,
closure_call: u32,
closure_state_push: u32,
closure_state_pop: u32,
state_push: u32,
state_pop: u32,
state_get: u32,
state_set: u32,
state_delay: u32,
state_mem: u32,
array_alloc: u32,
array_get_elem: u32,
array_set_elem: u32,
runtime_get_now: u32,
runtime_get_samplerate: u32,
// Math function imports (from "math" module)
math_sin: u32,
math_cos: u32,
math_tan: u32,
math_sinh: u32,
math_cosh: u32,
math_tanh: u32,
math_asin: u32,
math_acos: u32,
math_atan: u32,
math_round: u32,
math_floor: u32,
math_ceil: u32,
math_atan2: u32,
math_pow: u32,
math_log: u32,
math_min: u32,
math_max: u32,
// Builtin function imports (from "builtin" module)
builtin_probeln: u32,
builtin_probe: u32,
builtin_length_array: u32,
builtin_split_head: u32,
builtin_split_tail: u32,
builtin_prepend: u32,
builtin_append: u32,
builtin_split_head_specialized: HashMap<usize, u32>,
builtin_split_tail_specialized: HashMap<usize, u32>,
builtin_prepend_specialized: HashMap<usize, u32>,
builtin_append_specialized: HashMap<usize, u32>,
}
/// Linear memory layout manager
///
/// Manages the layout of WASM linear memory regions:
/// - 0..256: Reserved for future use
/// - 256..512: Global variable storage
/// - 512..1024: State exchange temporary region
/// - 1024..: Dynamic allocation region
#[derive(Debug, Clone)]
struct MemoryLayout {
/// Current offset for dynamic allocations (Alloc instructions)
alloc_offset: u32,
/// Base address for state exchange temporary memory region
state_temp_base: u32,
/// Global variable memory offsets: maps global VPtr to linear memory address
global_offsets: HashMap<VPtr, u32>,
/// Next available offset for global variable allocation
next_global_offset: u32,
}
impl Default for MemoryLayout {
fn default() -> Self {
Self {
alloc_offset: 1024, // Start dynamic allocation after reserved regions
state_temp_base: 512, // Reserve 512..1024 for state exchange
global_offsets: HashMap::new(),
next_global_offset: 256, // Reserve 256..512 for globals
}
}
}
// TODO: Replace this runtime threshold heuristic with an explicit callable
// representation in MIR/WASM lowering.
//
// Today, higher-order values are all carried as raw `i64`, so at a `call_indirect`
// site the WASM backend cannot statically distinguish:
// - a direct function-table index, from
// - a pointer to a closure object in linear memory.
//
// The current workaround relies on the fact that runtime allocations start at
// `alloc_offset = 1024`, so smaller values are treated as direct function refs.
// Directionally, the better design is to represent these as distinct callable
// kinds in MIR/lowering rather than recovering that distinction at runtime.
const DIRECT_FUNCTION_REF_MAX_EXCLUSIVE: i64 = 1024;
impl MemoryLayout {
/// Allocate a linear memory offset for a global variable, or return existing one.
fn get_or_alloc_global_offset(&mut self, global: &VPtr) -> u32 {
if let Some(&offset) = self.global_offsets.get(global) {
offset
} else {
let offset = self.next_global_offset;
self.next_global_offset += 8; // 8 bytes per global slot
self.global_offsets.insert(global.clone(), offset);
offset
}
}
}
/// WASM code generator state
pub struct WasmGenerator {
/// Type table (WASM function types)
type_section: TypeSection,
/// Import section (runtime primitives and external functions)
import_section: ImportSection,
/// Function section (function type indices)
function_section: FunctionSection,
/// Memory section (linear memory)
memory_section: MemorySection,
/// Table section (function table for indirect calls)
table_section: TableSection,
/// Code section (function bodies)
code_section: CodeSection,
/// Export section (exported functions)
export_section: ExportSection,
/// Data section (static data and constants)
data_section: DataSection,
/// Element section (function table for indirect calls)
element_section: ElementSection,
/// Global section (WASM global variables)
global_section: GlobalSection,
/// MIR program
mir: Arc<Mir>,
/// Current function index (accounts for imported functions)
current_fn_idx: u32,
/// Number of imported runtime functions (used as offset for MIR function indices)
num_imports: u32,
/// Local variable register mapping
registers: HashMap<Arc<mir::Value>, u32>,
/// Function name to WASM function index mapping
fn_name_to_idx: HashMap<Symbol, u32>,
/// Register type tracking: maps VReg to its WASM type (I64 or F64)
/// Used to correctly map registers to typed local variables
register_types: HashMap<mir::VReg, wasm_encoder::ValType>,
/// Register constant value tracking: maps VReg to constant value if it holds one
/// Used for function indices stored in registers
register_constants: HashMap<mir::VReg, u64>,
/// Number of arguments for the current function being generated.
/// WASM function parameters occupy the first local variable slots,
/// so register-to-local mappings must be offset by this count.
current_num_args: u32,
/// Argument types for the current function being generated.
/// Used by infer_value_type to determine the WASM type of function arguments.
current_arg_types: Vec<wasm_encoder::ValType>,
/// Maps MIR argument index to (WASM param start index, word count).
/// When tuple args are flattened, a single MIR arg maps to multiple WASM params.
current_arg_map: Vec<(u32, u32)>,
/// Number of i64 local slots for the current function.
/// Used as offset base for f64 locals: f64 reg `r` maps to local `num_args + num_i64_locals + r`.
current_num_i64_locals: u32,
/// Linear memory layout manager
mem_layout: MemoryLayout,
/// Runtime primitive function indices
rt: RuntimeFunctionIndices,
/// Plugin function import indices
plugin_fns: PluginFunctionIndices,
/// Registers produced by Alloc instructions, mapped to their content word size.
alloc_registers: HashMap<mir::VReg, TypeSize>,
/// Whether an alloc register should be captured indirectly in closures.
///
/// `true` means closure slots store alloc-cell pointers and
/// `GetUpValue`/`SetUpValue` perform one extra dereference.
alloc_register_indirect: HashMap<mir::VReg, bool>,
/// Registers produced by GetElement instructions, mapped to the element's ValType.
/// These registers hold pointers to elements but are often used as values in the MIR.
getelement_registers: HashMap<mir::VReg, wasm_encoder::ValType>,
/// Maps MIR function index to its WASM type section index
fn_type_indices: Vec<u32>,
/// Adapter function index per MIR function for indirect calls via table.
/// Table slot i points to this adapter, which normalizes non-Unit returns to i64.
indirect_adapter_fn_indices: Vec<u32>,
/// Local variable index for saving/restoring closure self pointer
closure_save_local: u32,
/// Local variable index for storing base address during runtime allocation (i32)
alloc_base_local: u32,
/// WASM global index for the runtime bump allocator pointer
alloc_ptr_global: u32,
/// Local variable index for saving alloc pointer at entry-function start (i32)
alloc_ptr_save_local: u32,
/// Whether the current function being generated is an entry point (dsp or _mimium_global).
/// Entry functions save/restore the alloc pointer to prevent unbounded memory growth.
is_entry_function: bool,
/// Whether `Alloc` in the current function should use runtime allocation.
/// Enabled for functions that may execute re-entrantly via non-external calls.
use_runtime_alloc_for_current_function: bool,
/// Maps function signatures (params, results) to type section indices for call_indirect
call_type_cache: HashMap<(Vec<wasm_encoder::ValType>, Vec<wasm_encoder::ValType>), u32>,
/// Per-function upvalue indirection info.
/// Maps MIR function index to a boolean vec: `true` at position `i` means upvalue `i`
/// stores an alloc **pointer** (not the dereferenced value), so `GetUpValue`/`SetUpValue`
/// must go through one extra level of indirection.
/// This is necessary because in WASM we combine closure creation and close into one step:
/// all closures are immediately "closed" and upvalues from alloc cells are shared by
/// reference rather than copied by value.
indirect_upvalues: HashMap<usize, Vec<bool>>,
/// MIR function index of the function currently being compiled in `generate_function_bodies`.
current_mir_fn_idx: usize,
}
/// Context for emitting control flow blocks
struct BlockEmitContext<'a> {
blocks: &'a [mir::Block],
processed: HashSet<usize>,
}
impl<'a> BlockEmitContext<'a> {
fn new(blocks: &'a [mir::Block]) -> Self {
Self {
blocks,
processed: HashSet::new(),
}
}
fn mark_processed(&mut self, idx: usize) {
self.processed.insert(idx);
}
fn is_processed(&self, idx: usize) -> bool {
self.processed.contains(&idx)
}
}
/// Context for emitting a Switch instruction
struct SwitchContext<'a> {
scrutinee: &'a VPtr,
cases: &'a [(i64, u64)],
default_block: Option<u64>,
merge_block: u64,
}
/// Specifies which phi instruction to skip in a merge block because its
/// result value is already on the WASM operand stack from the enclosing
/// structured control flow.
#[derive(Clone, Copy, PartialEq, Eq)]
enum SkipPhi {
/// Do not skip any phi instruction.
None,
/// Skip a `Phi(_, _)` instruction (from JmpIf).
Phi,
/// Skip a `PhiSwitch(_)` instruction (from Switch).
PhiSwitch,
}
impl SkipPhi {
fn from_phi_info(phi_info: &Option<((VPtr, VPtr), VPtr)>) -> Self {
if phi_info.is_some() {
Self::Phi
} else {
Self::None
}
}
fn from_phi_switch_info(phi_info: &Option<(Vec<VPtr>, VPtr)>) -> Self {
if phi_info.is_some() {
Self::PhiSwitch
} else {
Self::None
}
}
}
impl WasmGenerator {
fn is_probe_value_intercept_arity1(name: Symbol) -> bool {
name.as_str() == "__probe_value_intercept$arity1"
}
fn ext_function_uses_dest_ptr(name: Symbol) -> bool {
let s = name.as_str();
s == "split_head"
|| s == "split_tail"
|| s.starts_with("split_head$arity")
|| s.starts_with("split_tail$arity")
|| s.starts_with("__probe_intercept$arity")
|| s.starts_with("__probe_value_intercept$arity")
}
fn phi_result_type_from_phi_info(
&self,
phi_info: &Option<((VPtr, VPtr), VPtr)>,
) -> Option<ValType> {
phi_info.as_ref().map(|(inputs, phi_dest)| {
if let mir::Value::Register(reg_idx) = phi_dest.as_ref()
&& let Some(reg_type) = self.register_types.get(reg_idx)
{
*reg_type
} else {
self.infer_value_type(&inputs.0)
}
})
}
fn phi_switch_result_type_from_info(
&self,
phi_switch_info: &Option<(Vec<VPtr>, VPtr)>,
) -> Option<ValType> {
phi_switch_info.as_ref().map(|(inputs, phi_dest)| {
if let mir::Value::Register(reg_idx) = phi_dest.as_ref()
&& let Some(reg_type) = self.register_types.get(reg_idx)
{
*reg_type
} else {
inputs
.first()
.map(|input| self.infer_value_type(input))
.unwrap_or(ValType::I64)
}
})
}
/// Create a new WASM generator for the given MIR.
///
/// `ext_fns` should contain the complete list of external function type
/// information gathered from all plugin sources (system plugins, dynamic
/// plugins, etc.). The generator uses this to set up the WASM import
/// declarations that the runtime will later satisfy with host trampolines.
pub fn new(mir: Arc<Mir>, ext_fns: &[crate::plugin::ExtFunTypeInfo]) -> Self {
let mut generator = Self {
type_section: TypeSection::new(),
import_section: ImportSection::new(),
function_section: FunctionSection::new(),
memory_section: MemorySection::new(),
table_section: TableSection::new(),
code_section: CodeSection::new(),
export_section: ExportSection::new(),
data_section: DataSection::new(),
element_section: ElementSection::new(),
global_section: GlobalSection::new(),
mir,
current_fn_idx: 0,
num_imports: 0,
registers: HashMap::new(),
fn_name_to_idx: HashMap::new(),
register_types: HashMap::new(),
register_constants: HashMap::new(),
current_num_args: 0,
current_arg_types: Vec::new(),
current_arg_map: Vec::new(),
current_num_i64_locals: 0,
mem_layout: MemoryLayout::default(),
// Runtime primitive indices will be set by setup_runtime_imports
rt: RuntimeFunctionIndices::default(),
plugin_fns: PluginFunctionIndices::default(),
alloc_registers: HashMap::new(),
alloc_register_indirect: HashMap::new(),
getelement_registers: HashMap::new(),
fn_type_indices: Vec::new(),
indirect_adapter_fn_indices: Vec::new(),
closure_save_local: 0,
alloc_base_local: 0,
alloc_ptr_global: 0,
alloc_ptr_save_local: 0,
is_entry_function: false,
use_runtime_alloc_for_current_function: false,
call_type_cache: HashMap::new(),
indirect_upvalues: HashMap::new(),
current_mir_fn_idx: 0,
};
// Setup runtime primitive imports and memory/table
generator.setup_runtime_imports();
generator.setup_math_imports();
generator.setup_builtin_imports();
generator.setup_plugin_imports(ext_fns);
generator.setup_memory_and_table();
// Save number of imported functions for use in function index calculations
generator.num_imports = generator.current_fn_idx;
generator
}
/// Create a generator with no plugin imports.
///
/// Shorthand used by tests and callers that do not need plugin support.
pub fn new_without_plugins(mir: Arc<Mir>) -> Self {
Self::new(mir, &[])
}
/// Setup import section for RuntimePrimitives host functions
fn setup_runtime_imports(&mut self) {
// Each runtime primitive becomes an imported function from "runtime" module
// All use i32 for pointers, Word (i64), WordSize (i32), and references
let mut type_idx = 0u32;
// Type 0: (i32) -> i64 for heap_alloc
self.type_section
.ty()
.function(vec![ValType::I32], vec![ValType::I64]);
self.rt.heap_alloc = self.add_import("heap_alloc", type_idx);
type_idx += 1;
// Type 1: (i64) -> () for heap_retain, heap_release, box_clone, box_release, closure_close
self.type_section.ty().function(vec![ValType::I64], vec![]);
self.rt.heap_retain = self.add_import("heap_retain", type_idx);
self.rt.heap_release = self.add_import("heap_release", type_idx);
self.rt.box_clone = self.add_import("box_clone", type_idx);
self.rt.box_release = self.add_import("box_release", type_idx);
self.rt.closure_close = self.add_import("closure_close", type_idx);
type_idx += 1;
// Type 2: (i32, i64, i32) -> () for heap_load, box_load
self.type_section
.ty()
.function(vec![ValType::I32, ValType::I64, ValType::I32], vec![]);
self.rt.heap_load = self.add_import("heap_load", type_idx);
self.rt.box_load = self.add_import("box_load", type_idx);
type_idx += 1;
// Type 3: (i64, i32, i32) -> () for heap_store, box_store
self.type_section
.ty()
.function(vec![ValType::I64, ValType::I32, ValType::I32], vec![]);
self.rt.heap_store = self.add_import("heap_store", type_idx);
self.rt.box_store = self.add_import("box_store", type_idx);
type_idx += 1;
// Type 4: (i32, i32) -> i64 for box_alloc
self.type_section
.ty()
.function(vec![ValType::I32, ValType::I32], vec![ValType::I64]);
self.rt.box_alloc = self.add_import("box_alloc", type_idx);
type_idx += 1;
// Type 5: (i32, i32, i32) -> () for usersum_clone, usersum_release
self.type_section
.ty()
.function(vec![ValType::I32, ValType::I32, ValType::I32], vec![]);
self.rt.usersum_clone = self.add_import("usersum_clone", type_idx);
self.rt.usersum_release = self.add_import("usersum_release", type_idx);
type_idx += 1;
// Type 6: (i64, i32, i32) -> i64 for closure_make
self.type_section.ty().function(
vec![ValType::I64, ValType::I32, ValType::I32],
vec![ValType::I64],
);
self.rt.closure_make = self.add_import("closure_make", type_idx);
type_idx += 1;
// Type 7: (i64, i32, i32, i32, i32) -> () for closure_call
self.type_section.ty().function(
vec![
ValType::I64,
ValType::I32,
ValType::I32,
ValType::I32,
ValType::I32,
],
vec![],
);
self.rt.closure_call = self.add_import("closure_call", type_idx);
type_idx += 1;
// Type 8: (i64, i64) -> () for closure_state_push(closure_addr, state_size)
self.type_section
.ty()
.function(vec![ValType::I64, ValType::I64], vec![]);
self.rt.closure_state_push = self.add_import("closure_state_push", type_idx);
type_idx += 1;
// Type 9: () -> () for closure_state_pop
self.type_section.ty().function(vec![], vec![]);
self.rt.closure_state_pop = self.add_import("closure_state_pop", type_idx);
type_idx += 1;
// Type 10: (i64) -> () for state_push, state_pop
self.type_section.ty().function(vec![ValType::I64], vec![]);
self.rt.state_push = self.add_import("state_push", type_idx);
self.rt.state_pop = self.add_import("state_pop", type_idx);
type_idx += 1;
// Type 11: (i32, i32) -> () for state_get, state_set
self.type_section
.ty()
.function(vec![ValType::I32, ValType::I32], vec![]);
self.rt.state_get = self.add_import("state_get", type_idx);
self.rt.state_set = self.add_import("state_set", type_idx);
type_idx += 1;
// Type 10: (f64, f64, i64) -> f64 for state_delay
self.type_section.ty().function(
vec![ValType::F64, ValType::F64, ValType::I64],
vec![ValType::F64],
);
self.rt.state_delay = self.add_import("state_delay", type_idx);
type_idx += 1;
// Type 11: (f64) -> f64 for state_mem
self.type_section
.ty()
.function(vec![ValType::F64], vec![ValType::F64]);
self.rt.state_mem = self.add_import("state_mem", type_idx);
type_idx += 1;
// Type 12: (i64, i32) -> i64 for array_alloc
self.type_section
.ty()
.function(vec![ValType::I64, ValType::I32], vec![ValType::I64]);
self.rt.array_alloc = self.add_import("array_alloc", type_idx);
type_idx += 1;
// Type 13: (i32, i64, i64, i32) -> () for array_get_elem
self.type_section.ty().function(
vec![ValType::I32, ValType::I64, ValType::I64, ValType::I32],
vec![],
);
self.rt.array_get_elem = self.add_import("array_get_elem", type_idx);
type_idx += 1;
// Type 14: (i64, i64, i32, i32) -> () for array_set_elem
self.type_section.ty().function(
vec![ValType::I64, ValType::I64, ValType::I32, ValType::I32],
vec![],
);
self.rt.array_set_elem = self.add_import("array_set_elem", type_idx);
type_idx += 1;
// Type 15: () -> f64 for runtime_get_now, runtime_get_samplerate
// These return f64 directly since mimium's `number` type is f64
self.type_section.ty().function(vec![], vec![ValType::F64]);
self.rt.runtime_get_now = self.add_import("runtime_get_now", type_idx);
self.rt.runtime_get_samplerate = self.add_import("runtime_get_samplerate", type_idx);
}
/// Helper to add an import and increment function index, returns the function index
fn add_import(&mut self, name: &str, type_idx: u32) -> u32 {
self.add_import_from("runtime", name, type_idx)
}
/// Helper to add an import from a specific module
fn add_import_from(&mut self, module: &str, name: &str, type_idx: u32) -> u32 {
self.import_section
.import(module, name, EntityType::Function(type_idx));
let fn_idx = self.current_fn_idx;
self.current_fn_idx += 1;
fn_idx
}
/// Setup math function imports (sin/cos/tan/sinh/cosh/tanh/asin/acos/atan/round/floor/ceil/atan2/pow/log/min/max)
fn setup_math_imports(&mut self) {
// Type: (f64) -> f64
let type_idx_f64_f64 = self.type_section.len();
self.type_section
.ty()
.function(vec![ValType::F64], vec![ValType::F64]);
self.rt.math_sin = self.add_import_from("math", "sin", type_idx_f64_f64);
self.rt.math_cos = self.add_import_from("math", "cos", type_idx_f64_f64);
self.rt.math_tan = self.add_import_from("math", "tan", type_idx_f64_f64);
self.rt.math_sinh = self.add_import_from("math", "sinh", type_idx_f64_f64);
self.rt.math_cosh = self.add_import_from("math", "cosh", type_idx_f64_f64);
self.rt.math_tanh = self.add_import_from("math", "tanh", type_idx_f64_f64);
self.rt.math_asin = self.add_import_from("math", "asin", type_idx_f64_f64);
self.rt.math_acos = self.add_import_from("math", "acos", type_idx_f64_f64);
self.rt.math_atan = self.add_import_from("math", "atan", type_idx_f64_f64);
self.rt.math_round = self.add_import_from("math", "round", type_idx_f64_f64);
self.rt.math_floor = self.add_import_from("math", "floor", type_idx_f64_f64);
self.rt.math_ceil = self.add_import_from("math", "ceil", type_idx_f64_f64);
self.rt.math_log = self.add_import_from("math", "log", type_idx_f64_f64);
// Type: (f64, f64) -> f64
let type_idx_f64_f64_f64 = self.type_section.len();
self.type_section
.ty()
.function(vec![ValType::F64, ValType::F64], vec![ValType::F64]);
self.rt.math_atan2 = self.add_import_from("math", "atan2", type_idx_f64_f64_f64);
self.rt.math_pow = self.add_import_from("math", "pow", type_idx_f64_f64_f64);
self.rt.math_min = self.add_import_from("math", "min", type_idx_f64_f64_f64);
self.rt.math_max = self.add_import_from("math", "max", type_idx_f64_f64_f64);
}
/// Setup builtin function imports (probeln, probe, len, split_head, split_tail)
fn setup_builtin_imports(&mut self) {
// Type: (f64) -> f64 for probeln, probe
let type_idx_f64_f64 = self.type_section.len();
self.type_section
.ty()
.function(vec![ValType::F64], vec![ValType::F64]);
self.rt.builtin_probeln = self.add_import_from("builtin", "probeln", type_idx_f64_f64);
self.rt.builtin_probe = self.add_import_from("builtin", "probe", type_idx_f64_f64);
// Type: (i64) -> f64 for len (takes array handle, returns count as f64)
let type_idx_i64_f64 = self.type_section.len();
self.type_section
.ty()
.function(vec![ValType::I64], vec![ValType::F64]);
self.rt.builtin_length_array =
self.add_import_from("builtin", "len", type_idx_i64_f64);
// Type: (i64, i32) -> () for split_head / split_tail
// arg1: array handle (i64), arg2: destination pointer (i32)
// Writes result tuple to linear memory at dst_ptr.
let type_idx_split = self.type_section.len();
self.type_section
.ty()
.function(vec![ValType::I64, ValType::I32], vec![]);
self.rt.builtin_split_head = self.add_import_from("builtin", "split_head", type_idx_split);
self.rt.builtin_split_tail = self.add_import_from("builtin", "split_tail", type_idx_split);
for arity in 1..=MAX_SPECIALIZED_BUILTIN_ARITY {
let split_head_name = format!("split_head$arity{arity}");
let split_tail_name = format!("split_tail$arity{arity}");
let split_head_idx = self.add_import_from("builtin", &split_head_name, type_idx_split);
let split_tail_idx = self.add_import_from("builtin", &split_tail_name, type_idx_split);
self.rt
.builtin_split_head_specialized
.insert(arity, split_head_idx);
self.rt
.builtin_split_tail_specialized
.insert(arity, split_tail_idx);
}
// Type: (i64, i64) -> i64 for prepend/prepend$arityN and append/append$arityN
let type_idx_prepend = self.type_section.len();
self.type_section
.ty()
.function(vec![ValType::I64, ValType::I64], vec![ValType::I64]);
self.rt.builtin_prepend = self.add_import_from("builtin", "prepend", type_idx_prepend);
self.rt.builtin_append = self.add_import_from("builtin", "append", type_idx_prepend);
for arity in 1..=MAX_SPECIALIZED_BUILTIN_ARITY {
let prepend_name = format!("prepend$arity{arity}");
let append_name = format!("append$arity{arity}");
let prepend_idx = self.add_import_from("builtin", &prepend_name, type_idx_prepend);
let append_idx = self.add_import_from("builtin", &append_name, type_idx_prepend);
self.rt
.builtin_prepend_specialized
.insert(arity, prepend_idx);
self.rt.builtin_append_specialized.insert(arity, append_idx);
}
}
/// Setup plugin function imports from dynamically loaded plugins
/// Setup plugin function imports.
///
/// Registers a WASM import for every runtime-stage external function
/// described in `ext_fns`. This covers both system plugins (like
/// `GuiToolPlugin`) and dynamically loaded ones.
#[cfg(not(target_arch = "wasm32"))]
fn setup_plugin_imports(&mut self, ext_fns: &[crate::plugin::ExtFunTypeInfo]) {
for type_info in ext_fns {
let name = type_info.name;
let fn_ty = type_info.ty.to_type();
if Self::is_probe_value_intercept_arity1(name) {
let type_idx = self.type_section.len();
self.type_section
.ty()
.function(vec![ValType::F64, ValType::F64], vec![ValType::F64]);
let fn_idx = self.add_import_from("plugin", name.as_str(), type_idx);
self.plugin_fns.functions.insert(name, fn_idx);
continue;
}
let Type::Function { arg, ret } = fn_ty else {
log::warn!(
"Plugin function {} has non-function type: {:?}",
name.as_str(),
fn_ty
);
continue;
};
// Flatten tuple arguments into separate WASM parameters
let mut param_types: Vec<ValType> = match arg.to_type() {
Type::Tuple(elems) => elems
.iter()
.map(|t| Self::type_to_valtype(&t.to_type()))
.collect(),
arg_ty => vec![Self::type_to_valtype(&arg_ty)],
};
let is_void = matches!(ret.to_type(), Type::Primitive(PType::Unit));
let flat_ret_len = Self::flatten_type_to_valtypes(&ret.to_type()).len();
let uses_dest_ptr =
!is_void && flat_ret_len > 1 && Self::ext_function_uses_dest_ptr(name);
let return_types: Vec<ValType> = if uses_dest_ptr {
// Dest-pointer convention: the host writes the multi-word
// result to a caller-provided memory address.
param_types.push(ValType::I32); // dst_ptr
vec![] // void return
} else if is_void {
vec![]
} else {
vec![Self::type_to_valtype(&ret.to_type())]
};
let type_idx = self.type_section.len();
self.type_section
.ty()
.function(param_types.clone(), return_types);
let fn_idx = self.add_import_from("plugin", name.as_str(), type_idx);
self.plugin_fns.functions.insert(name, fn_idx);
log::debug!(
"Added plugin import: {} ({} params{})",
name.as_str(),
param_types.len(),
if uses_dest_ptr { " [dest-ptr]" } else { "" },
);
}
}
#[cfg(target_arch = "wasm32")]
fn setup_plugin_imports(&mut self, _ext_fns: &[crate::plugin::ExtFunTypeInfo]) {
// Browser WASM does not use the native plugin mechanism.
}
/// Setup memory and table sections
fn setup_memory_and_table(&mut self) {
const MAX_MEMORY_PAGES: u64 = 65_536; // 4GiB on wasm32 linear memory
// Linear memory: 1 initial page (64KB), max 1024 pages (64MB)
// This is used for stack, runtime primitives data, and constants
self.memory_section.memory(MemoryType {
minimum: 1,
maximum: Some(MAX_MEMORY_PAGES),
memory64: false,
shared: false,
page_size_log2: None,
});
// Function table for indirect calls (closures).
// The element section later inserts one entry per MIR function
// at offset 0, so the initial table size must be at least that count.
let required_table_size = self.mir.functions.len() as u64;
let table_min = required_table_size.max(128);
let table_max = table_min.max(4096);
self.table_section.table(TableType {
element_type: wasm_encoder::RefType::FUNCREF,
minimum: table_min,
maximum: Some(table_max),
table64: false,
shared: false,
});
}
/// Generate a WASM module from MIR
pub fn generate(&mut self) -> Result<Vec<u8>, String> {
// Phase 1: Process MIR functions and generate WASM function declarations
self.process_mir_functions()?;
// Phase 2: Generate function bodies
self.generate_function_bodies()?;
// Phase 2.25: Generate per-function indirect-call adapters and
// populate the function table with adapter function indices.
self.generate_indirect_adapters()?;
self.setup_function_table();
// Phase 2.5: Generate the closure-execution trampoline exported as
// `_mimium_exec_closure_void`. The host (scheduler, etc.) calls this
// to invoke a `() -> ()` closure stored in linear memory by address.
self.generate_exec_closure_trampoline();
// Phase 3: Export functions
self.export_functions()?;
// Phase 3.5: Setup runtime allocator global
// The alloc_ptr_global starts at the final alloc_offset value,
// which is past all compile-time static allocations.
self.global_section.global(
wasm_encoder::GlobalType {
val_type: wasm_encoder::ValType::I32,
mutable: true,
shared: false,
},
&wasm_encoder::ConstExpr::i32_const(self.mem_layout.alloc_offset as i32),
);
self.alloc_ptr_global = 0; // first (and only) global
// Phase 4: Build and encode the module
let module = self.build_module();
Ok(module.finish())
}
/// Process MIR functions and setup WASM function declarations
fn process_mir_functions(&mut self) -> Result<(), String> {
// Clone the functions vector to avoid borrow checker issues
let functions = self.mir.functions.clone();
// Iterate over MIR functions
for func in &functions {
// Infer argument types from function body usage.
// This resolves Unknown argument types that type inference
// didn't propagate back to the MIR function signature.
let inferred_arg_types = Self::infer_argument_types(func);
// Flatten argument types: tuple/record args expand to individual params.
// This matches the MIR calling convention where tuple args are passed
// as separate words at call sites.
let param_types: Vec<ValType> = func
.args
.iter()
.enumerate()
.flat_map(|(arg_idx, arg)| {
let mut flat = Self::flatten_type_to_valtypes(&arg.1.to_type());
// Override with body-inferred types when the declared type is
// insufficient (e.g., {tup:unknown} that should be 3 F64 params).
if let Some(inferred) = inferred_arg_types.get(&arg_idx) {
if inferred.len() > flat.len() {
// Multi-word inferred type replaces under-specified declaration
flat = inferred.clone();
} else if flat.len() == 1
&& inferred.len() == 1
&& flat[0] != inferred[0]
&& Self::allows_scalar_inference_override(&arg.1.to_type())
{
flat[0] = inferred[0];
}
}
flat
})
.collect();
// Get return type
let return_types: Vec<ValType> = func
.return_type
.get()
.and_then(|ty| {
let type_ref = ty.to_type();
// Unit type should have no return value in WASM
if matches!(type_ref, Type::Primitive(PType::Unit)) {
None
} else {
Some(vec![Self::type_to_valtype(&type_ref)])
}
})
.unwrap_or_default();
// Add function type to type section
let type_idx = self.type_section.len();
self.type_section.ty().function(param_types, return_types);
// Add function to function section (links to type index)
self.function_section.function(type_idx);
// Track type index for call_indirect
self.fn_type_indices.push(type_idx);
// Track function name to index mapping
// Note: current_fn_idx already accounts for imported functions
// Only register the first occurrence of each function name (avoid duplicate mappings from multiple includes)
if !self.fn_name_to_idx.contains_key(&func.label) {
self.fn_name_to_idx.insert(func.label, self.current_fn_idx);
log::debug!(
"Registered function {} at index {}",
func.label.as_str(),
self.current_fn_idx
);
} else {
log::debug!(
"Skipping duplicate mapping for function {} (already mapped to index {})",
func.label.as_str(),
self.fn_name_to_idx[&func.label]
);
}
self.current_fn_idx += 1;
}
Ok(())
}
/// Populate the WASM function table with indirect-call adapters.
/// Table index i maps to adapter function index for MIR function i.
fn setup_function_table(&mut self) {
let num_fns = self.mir.functions.len() as u32;
if num_fns == 0 {
return;
}
if self.indirect_adapter_fn_indices.len() == num_fns as usize {
let func_indices = self.indirect_adapter_fn_indices.clone();
self.element_section.active(
Some(0),
&wasm_encoder::ConstExpr::i32_const(0),
wasm_encoder::Elements::Functions(std::borrow::Cow::Owned(func_indices)),
);
return;
}
// Fallback to direct function indices when adapters are not generated.
let func_indices: Vec<u32> = (0..num_fns).map(|i| i + self.num_imports).collect();
self.element_section.active(
Some(0),
&wasm_encoder::ConstExpr::i32_const(0),
wasm_encoder::Elements::Functions(std::borrow::Cow::Borrowed(&func_indices)),
);
}
/// Generate adapter functions used by `call_indirect` table dispatch.
///
/// Each adapter has the same parameter list as its MIR function, but
/// normalizes non-Unit returns to `i64` so that polymorphic higher-order
/// calls can share a stable table signature.
fn generate_indirect_adapters(&mut self) -> Result<(), String> {
use wasm_encoder::Instruction as W;
let functions = self.mir.functions.clone();
self.indirect_adapter_fn_indices.clear();
for (mir_fn_idx, func) in functions.iter().enumerate() {
let inferred_arg_types = Self::infer_argument_types(func);
let original_param_types: Vec<ValType> = func
.args
.iter()
.enumerate()
.flat_map(|(arg_idx, arg)| {
let mut flat = Self::flatten_type_to_valtypes(&arg.1.to_type());
if let Some(inferred) = inferred_arg_types.get(&arg_idx) {
if inferred.len() > flat.len() {
flat = inferred.clone();
} else if flat.len() == 1
&& inferred.len() == 1
&& flat[0] != inferred[0]
&& Self::allows_scalar_inference_override(&arg.1.to_type())
{
flat[0] = inferred[0];
}
}
flat
})
.collect();
// Indirect-call adapters expose a word-level ABI: every parameter is i64.
let adapter_param_types = vec![ValType::I64; original_param_types.len()];
let original_ret_vtype = func.return_type.get().and_then(|ty| {
let ty = ty.to_type();
if matches!(ty, Type::Primitive(PType::Unit)) {
None
} else {
Some(Self::type_to_valtype(&ty))
}
});
let adapter_results = if original_ret_vtype.is_some() {
vec![ValType::I64]
} else {
vec![]
};
let adapter_type_idx = self.type_section.len();
self.type_section
.ty()
.function(adapter_param_types.clone(), adapter_results);
self.function_section.function(adapter_type_idx);
let adapter_fn_idx = self.current_fn_idx;
self.current_fn_idx += 1;
let mut adapter = Function::new([]);
for (param_idx, original_param_vt) in original_param_types.iter().enumerate() {
adapter.instruction(&W::LocalGet(param_idx as u32));
if *original_param_vt == ValType::F64 {
adapter.instruction(&W::F64ReinterpretI64);
}
}
let original_wasm_fn_idx = self.num_imports + mir_fn_idx as u32;
adapter.instruction(&W::Call(original_wasm_fn_idx));
if let Some(ValType::F64) = original_ret_vtype {
adapter.instruction(&W::I64ReinterpretF64);
}
adapter.instruction(&W::End);
self.code_section.function(&adapter);
self.indirect_adapter_fn_indices.push(adapter_fn_idx);
}
Ok(())
}
/// Get or create a WASM function type index for indirect calls.
/// Caches signatures to avoid duplicating type entries.
fn get_or_create_call_type(
&mut self,
params: Vec<wasm_encoder::ValType>,
results: Vec<wasm_encoder::ValType>,
) -> u32 {
let key = (params.clone(), results.clone());
if let Some(&idx) = self.call_type_cache.get(&key) {
return idx;
}
let type_idx = self.type_section.len();
self.type_section.ty().function(params, results);
self.call_type_cache.insert(key, type_idx);
type_idx
}
/// Generate WASM function bodies from MIR
fn generate_function_bodies(&mut self) -> Result<(), String> {
use wasm_encoder::Instruction as W;
// Clone the functions vector to avoid borrow checker issues
let functions = self.mir.functions.clone();
// For each MIR function, generate WASM function body
for (mir_fn_idx, func) in functions.iter().enumerate() {
self.current_mir_fn_idx = mir_fn_idx;
self.use_runtime_alloc_for_current_function =
Self::function_has_non_external_calls(func);
// Reset register mapping and type tracking for each function
self.registers.clear();
self.register_types.clear();
self.register_constants.clear();
// Infer argument types from body usage (same analysis as in process_mir_functions)
let inferred_arg_types = Self::infer_argument_types(func);
// Build flattened argument mapping.
// MIR args are flattened when tuple/record types are passed:
// each element becomes a separate WASM parameter.
let mut arg_map = Vec::new();
let mut flat_arg_types = Vec::new();
let mut wasm_param_idx: u32 = 0;
for (arg_idx, arg) in func.args.iter().enumerate() {
let mut flat_types = Self::flatten_type_to_valtypes(&arg.1.to_type());
// Override with body-inferred types when the declared type is
// insufficient (e.g., {tup:unknown} that should be 3 F64 params).
if let Some(inferred) = inferred_arg_types.get(&arg_idx) {
if inferred.len() > flat_types.len() {
// Multi-word inferred type replaces under-specified declaration
flat_types = inferred.clone();
} else if flat_types.len() == 1
&& inferred.len() == 1
&& flat_types[0] != inferred[0]
&& Self::allows_scalar_inference_override(&arg.1.to_type())
{
flat_types[0] = inferred[0];
}
}
let word_count = flat_types.len() as u32;
arg_map.push((wasm_param_idx, word_count));
flat_arg_types.extend(flat_types);
wasm_param_idx += word_count;
}
self.current_num_args = wasm_param_idx;
self.current_arg_types = flat_arg_types;
self.current_arg_map = arg_map;
// Scan function body to determine register types and constants
self.analyze_register_types(func);
// Compute required local counts from actual register usage
let (max_i64_reg, max_f64_reg) = self.compute_max_register_indices();
let num_i64_locals = max_i64_reg + 1;
let num_f64_locals = max_f64_reg + 1;
self.current_num_i64_locals = num_i64_locals;
// WASM local layout: [args(0..n)] [i64 regs(n..n+num_i64)] [f64 regs(n+num_i64..)] [closure_save: i64]
let mut locals = Vec::new();
if num_i64_locals > 0 {
locals.push((num_i64_locals, ValType::I64));
}
if num_f64_locals > 0 {
locals.push((num_f64_locals, ValType::F64));
}
// Extra i64 local for saving/restoring closure self pointer during indirect calls
locals.push((1, ValType::I64));
self.closure_save_local = self.current_num_args + num_i64_locals + num_f64_locals;
// Extra i32 local for runtime allocator base address (used by MakeClosure)
locals.push((1, ValType::I32));
self.alloc_base_local = self.closure_save_local + 1;
// Detect entry-point functions that need alloc pointer save/restore.
// `dsp` is called per sample/frame; rewinding its temporary linear-memory
// allocations at function boundaries prevents unbounded growth.
// `_mimium_global` runs once and must keep its allocations alive.
let is_entry = func.label.as_str() == "dsp";
self.is_entry_function = is_entry;
// Extra i32 local for saving alloc pointer at entry function start
locals.push((1, ValType::I32));
self.alloc_ptr_save_local = self.alloc_base_local + 1;
// Create a new WASM function
let mut wasm_func = Function::new(locals);
// Entry functions save the alloc pointer at start and restore before return,
// preventing unbounded memory growth from per-sample Alloc instructions.
if is_entry {
wasm_func.instruction(&W::GlobalGet(self.alloc_ptr_global));
wasm_func.instruction(&W::LocalSet(self.alloc_ptr_save_local));
}
// Translate basic blocks with structured control flow awareness
self.emit_function_body(func, &mut wasm_func)?;
// Safety net for entry functions: ensure alloc pointer is restored
// even when control flow reaches function end without passing
// through an explicit MIR Return/ReturnFeed path.
if is_entry {
wasm_func.instruction(&W::LocalGet(self.alloc_ptr_save_local));
wasm_func.instruction(&W::GlobalSet(self.alloc_ptr_global));
}
// Every WASM function body must end with an End instruction
// (functions are implicit blocks in WASM)
wasm_func.instruction(&W::End);
// Add function to code section
self.code_section.function(&wasm_func);
}
Ok(())
}
/// Emit a function body handling structured control flow (if/else from JmpIf/Phi)
fn emit_function_body(
&mut self,
func: &mir::Function,
wasm_func: &mut Function,
) -> Result<(), String> {
use mir::Instruction as I;
use wasm_encoder::Instruction as W;
let blocks = &func.body;
let mut ctx = BlockEmitContext::new(blocks);
for block_idx in 0..blocks.len() {
if ctx.is_processed(block_idx) {
continue;
}
ctx.mark_processed(block_idx);
let block = &blocks[block_idx];
for (dest, instr) in &block.0 {
match instr {
I::JmpIf(cond, then_bb, else_bb, merge_bb) => {
let then_idx = *then_bb as usize;
let else_idx = *else_bb as usize;
let merge_idx = *merge_bb as usize;
// Find Phi in merge block to determine result type and inputs
let phi_info = Self::find_phi_in_block(&blocks[merge_idx]);
// Load condition and convert to i32 for WASM if instruction.
// The native VM uses JmpIfNeg which jumps to else when cond <= 0.0,
// so the then-branch is taken when cond > 0.0.
self.emit_value_load(cond, wasm_func);
if self.infer_value_type(cond) == ValType::F64 {
// cond > 0.0 means then-branch (matching VM's JmpIfNeg semantics)
wasm_func.instruction(&W::F64Const(0.0));
wasm_func.instruction(&W::F64Gt);
} else {
// For i64: cond > 0 means then-branch
wasm_func.instruction(&W::I64Const(0));
wasm_func.instruction(&W::I64GtS);
}
// Determine if block type from Phi presence
let phi_result_type = self.phi_result_type_from_phi_info(&phi_info);
let block_type = phi_result_type
.map(wasm_encoder::BlockType::Result)
.unwrap_or(wasm_encoder::BlockType::Empty);
wasm_func.instruction(&W::If(block_type));
// Emit then-branch block
ctx.mark_processed(then_idx);
self.emit_branch_block(
&ctx.blocks[then_idx],
&mut ctx,
phi_info.as_ref().map(|(inputs, _)| &inputs.0),
phi_result_type,
wasm_func,
)?;
wasm_func.instruction(&W::Else);
// Emit else-branch block
ctx.mark_processed(else_idx);
self.emit_branch_block(
&ctx.blocks[else_idx],
&mut ctx,
phi_info.as_ref().map(|(inputs, _)| &inputs.1),
phi_result_type,
wasm_func,
)?;
wasm_func.instruction(&W::End);
// Emit merge block (skip Phi, which is on the stack from if/else)
ctx.mark_processed(merge_idx);
self.emit_merge_block(
merge_idx,
SkipPhi::from_phi_info(&phi_info),
&mut ctx,
wasm_func,
)?;
}
I::Switch {
scrutinee,
cases,
default_block,
merge_block,
} => {
self.emit_switch(
SwitchContext {
scrutinee,
cases,
default_block: *default_block,
merge_block: *merge_block,
},
&mut ctx,
wasm_func,
)?;
}
_ => {
self.translate_instruction_with_dest(dest.as_ref(), instr, wasm_func)?;
}
}
}
}
Ok(())
}
/// Emit a Switch instruction as a nested if/else chain.
/// Extracted as a method so it can be called recursively for nested switches.
fn emit_switch(
&mut self,
switch_ctx: SwitchContext,
ctx: &mut BlockEmitContext,
wasm_func: &mut Function,
) -> Result<(), String> {
use wasm_encoder::Instruction as W;
let merge_idx = switch_ctx.merge_block as usize;
// Find PhiSwitch in merge block
let phi_switch_info = Self::find_phi_switch_in_block(&ctx.blocks[merge_idx]);
// Determine result type from PhiSwitch
let phi_result_type = self.phi_switch_result_type_from_info(&phi_switch_info);
let block_type = phi_result_type
.map(wasm_encoder::BlockType::Result)
.unwrap_or(wasm_encoder::BlockType::Empty);
let num_cases = switch_ctx.cases.len();
let phi_inputs = phi_switch_info
.as_ref()
.map(|(inputs, _)| inputs.clone())
.unwrap_or_default();
for (i, (case_val, case_bb)) in switch_ctx.cases.iter().enumerate() {
let case_idx = *case_bb as usize;
// Load scrutinee and compare with case value
self.emit_value_load(switch_ctx.scrutinee, wasm_func);
wasm_func.instruction(&W::I64Const(*case_val));
wasm_func.instruction(&W::I64Eq);
wasm_func.instruction(&W::If(block_type));
// Emit case block with nested control flow support
ctx.mark_processed(case_idx);
self.emit_block_instructions(&ctx.blocks[case_idx], ctx, wasm_func)?;
// Push phi input for this case
if let Some(input) = phi_inputs.get(i) {
if let Some(expected) = phi_result_type {
self.emit_value_load_typed(input, expected, wasm_func);
} else {
self.emit_value_load(input, wasm_func);
}
}
wasm_func.instruction(&W::Else);
}
// Default or last else
if let Some(default_bb) = switch_ctx.default_block {
let default_idx = default_bb as usize;
ctx.mark_processed(default_idx);
self.emit_block_instructions(&ctx.blocks[default_idx], ctx, wasm_func)?;
if let Some(input) = phi_inputs.get(num_cases) {
if let Some(expected) = phi_result_type {
self.emit_value_load_typed(input, expected, wasm_func);
} else {
self.emit_value_load(input, wasm_func);
}
}
} else if !phi_inputs.is_empty()
&& let Some(last) = phi_inputs.last()
{
if let Some(expected) = phi_result_type {
self.emit_value_load_typed(last, expected, wasm_func);
} else {
self.emit_value_load(last, wasm_func);
}
}
// Close all the nested if/else blocks
for _ in 0..num_cases {
wasm_func.instruction(&W::End);
}
// Emit merge block (skip PhiSwitch)
ctx.mark_processed(merge_idx);
self.emit_merge_block(
merge_idx,
SkipPhi::from_phi_switch_info(&phi_switch_info),
ctx,
wasm_func,
)?;
Ok(())
}
/// Find the Phi instruction in a merge block.
/// Returns `Some(((then_input, else_input), dest_vptr))` if found.
fn find_phi_in_block(block: &mir::Block) -> Option<((VPtr, VPtr), VPtr)> {
for (dest, instr) in &block.0 {
if let mir::Instruction::Phi(v1, v2) = instr {
return Some(((v1.clone(), v2.clone()), dest.clone()));
}
}
None
}
/// Find the PhiSwitch instruction in a merge block.
/// Returns `Some((inputs_vec, dest_vptr))` if found.
fn find_phi_switch_in_block(block: &mir::Block) -> Option<(Vec<VPtr>, VPtr)> {
for (dest, instr) in &block.0 {
if let mir::Instruction::PhiSwitch(inputs) = instr {
return Some((inputs.clone(), dest.clone()));
}
}
None
}
/// Emit a branch block's instructions, then load the Phi input onto the stack.
/// Handles nested JmpIf instructions by recursively emitting inner if/else structures.
fn emit_branch_block(
&mut self,
block: &mir::Block,
ctx: &mut BlockEmitContext,
phi_input: Option<&VPtr>,
expected_phi_type: Option<ValType>,
func: &mut Function,
) -> Result<(), String> {
use mir::Instruction as I;
use wasm_encoder::Instruction as W;
for (dest, instr) in &block.0 {
match instr {
I::JmpIf(cond, then_bb, else_bb, merge_bb) => {
let then_idx = *then_bb as usize;
let else_idx = *else_bb as usize;
let merge_idx = *merge_bb as usize;
let phi_info = Self::find_phi_in_block(&ctx.blocks[merge_idx]);
self.emit_value_load(cond, func);
if self.infer_value_type(cond) == ValType::F64 {
func.instruction(&W::F64Const(0.0));
func.instruction(&W::F64Gt);
} else {
func.instruction(&W::I64Const(0));
func.instruction(&W::I64GtS);
}
let inner_phi_type = self.phi_result_type_from_phi_info(&phi_info);
let block_type = inner_phi_type
.map(wasm_encoder::BlockType::Result)
.unwrap_or(wasm_encoder::BlockType::Empty);
func.instruction(&W::If(block_type));
ctx.mark_processed(then_idx);
self.emit_branch_block(
&ctx.blocks[then_idx],
ctx,
phi_info.as_ref().map(|(inputs, _)| &inputs.0),
inner_phi_type,
func,
)?;
func.instruction(&W::Else);
ctx.mark_processed(else_idx);
self.emit_branch_block(
&ctx.blocks[else_idx],
ctx,
phi_info.as_ref().map(|(inputs, _)| &inputs.1),
inner_phi_type,
func,
)?;
func.instruction(&W::End);
ctx.mark_processed(merge_idx);
self.emit_merge_block(merge_idx, SkipPhi::from_phi_info(&phi_info), ctx, func)?;
}
I::Switch {
scrutinee,
cases,
default_block,
merge_block,
} => {
self.emit_switch(
SwitchContext {
scrutinee,
cases,
default_block: *default_block,
merge_block: *merge_block,
},
ctx,
func,
)?;
}
_ => {
self.translate_instruction_with_dest(dest.as_ref(), instr, func)?;
}
}
}
// Push the phi input to stay on the stack as the if/else result
if let Some(input) = phi_input {
if let Some(expected) = expected_phi_type {
self.emit_value_load_typed(input, expected, func);
} else {
self.emit_value_load(input, func);
}
}
Ok(())
}
/// Emit all instructions in a block, handling nested control flow (JmpIf, Switch).
/// This is used by Switch case block emission to allow nesting.
fn emit_block_instructions(
&mut self,
block: &mir::Block,
ctx: &mut BlockEmitContext,
func: &mut Function,
) -> Result<(), String> {
use mir::Instruction as I;
use wasm_encoder::Instruction as W;
for (dest, instr) in &block.0 {
match instr {
I::JmpIf(cond, then_bb, else_bb, merge_bb) => {
let then_idx = *then_bb as usize;
let else_idx = *else_bb as usize;
let merge_idx = *merge_bb as usize;
let phi_info = Self::find_phi_in_block(&ctx.blocks[merge_idx]);
self.emit_value_load(cond, func);
if self.infer_value_type(cond) == ValType::F64 {
func.instruction(&W::F64Const(0.0));
func.instruction(&W::F64Gt);
} else {
func.instruction(&W::I64Const(0));
func.instruction(&W::I64GtS);
}
let inner_phi_type = self.phi_result_type_from_phi_info(&phi_info);
let block_type = inner_phi_type
.map(wasm_encoder::BlockType::Result)
.unwrap_or(wasm_encoder::BlockType::Empty);
func.instruction(&W::If(block_type));
ctx.mark_processed(then_idx);
self.emit_branch_block(
&ctx.blocks[then_idx],
ctx,
phi_info.as_ref().map(|(inputs, _)| &inputs.0),
inner_phi_type,
func,
)?;
func.instruction(&W::Else);
ctx.mark_processed(else_idx);
self.emit_branch_block(
&ctx.blocks[else_idx],
ctx,
phi_info.as_ref().map(|(inputs, _)| &inputs.1),
inner_phi_type,
func,
)?;
func.instruction(&W::End);
ctx.mark_processed(merge_idx);
self.emit_merge_block(merge_idx, SkipPhi::from_phi_info(&phi_info), ctx, func)?;
}
I::Switch {
scrutinee,
cases,
default_block,
merge_block,
} => {
self.emit_switch(
SwitchContext {
scrutinee,
cases,
default_block: *default_block,
merge_block: *merge_block,
},
ctx,
func,
)?;
}
_ => {
self.translate_instruction_with_dest(dest.as_ref(), instr, func)?;
}
}
}
Ok(())
}
/// Emit a merge block, handling the Phi at the top (already on stack from if/else).
/// Also handles nested JmpIf/Switch instructions within the merge block.
/// Takes block_idx instead of a block reference to avoid borrow conflicts with ctx.
/// Emit instructions from a merge block. When `skip_phi` is set, the first
/// Phi (or PhiSwitch) instruction's result is assumed to already be on the
/// WASM stack from the enclosing if/else or nested-if chain, so we just
/// `local.set` it into the destination register. All other instructions,
/// including nested `JmpIf` and `Switch`, are emitted recursively.
fn emit_merge_block(
&mut self,
block_idx: usize,
skip_phi: SkipPhi,
ctx: &mut BlockEmitContext,
func: &mut Function,
) -> Result<(), String> {
use mir::Instruction as I;
use wasm_encoder::Instruction as W;
// Clone instructions to avoid holding a borrow on ctx.blocks.
let instructions: Vec<_> = ctx.blocks[block_idx].0.clone();
for (dest, instr) in &instructions {
let is_skipped_phi = match skip_phi {
SkipPhi::None => false,
SkipPhi::Phi => matches!(instr, I::Phi(_, _)),
SkipPhi::PhiSwitch => matches!(instr, I::PhiSwitch(_)),
};
if is_skipped_phi {
// Phi value is already on the stack from if/else; store to dest.
if let mir::Value::Register(reg_idx) = dest.as_ref() {
let reg_type = self
.register_types
.get(reg_idx)
.copied()
.unwrap_or_else(|| match instr {
I::Phi(v1, _) => self.infer_value_type(v1),
I::PhiSwitch(inputs) => inputs
.first()
.map(|input| self.infer_value_type(input))
.unwrap_or(ValType::I64),
_ => ValType::F64,
});
let local_idx = match reg_type {
ValType::I64 => self.current_num_args + *reg_idx as u32,
ValType::F64 => {
self.current_num_args + self.current_num_i64_locals + *reg_idx as u32
}
_ => self.current_num_args + self.current_num_i64_locals + *reg_idx as u32,
};
func.instruction(&W::LocalSet(local_idx));
}
} else if let I::JmpIf(cond, then_bb, else_bb, merge_bb) = instr {
// Nested JmpIf within merge block.
let then_idx = *then_bb as usize;
let else_idx = *else_bb as usize;
let merge_idx = *merge_bb as usize;
let phi_info = Self::find_phi_in_block(&ctx.blocks[merge_idx]);
self.emit_value_load(cond, func);
if self.infer_value_type(cond) == ValType::F64 {
func.instruction(&W::F64Const(0.0));
func.instruction(&W::F64Gt);
} else {
func.instruction(&W::I64Const(0));
func.instruction(&W::I64GtS);
}
let inner_phi_type = self.phi_result_type_from_phi_info(&phi_info);
let block_type = inner_phi_type
.map(wasm_encoder::BlockType::Result)
.unwrap_or(wasm_encoder::BlockType::Empty);
func.instruction(&W::If(block_type));
ctx.mark_processed(then_idx);
self.emit_branch_block(
&ctx.blocks[then_idx],
ctx,
phi_info.as_ref().map(|(inputs, _)| &inputs.0),
inner_phi_type,
func,
)?;
func.instruction(&W::Else);
ctx.mark_processed(else_idx);
self.emit_branch_block(
&ctx.blocks[else_idx],
ctx,
phi_info.as_ref().map(|(inputs, _)| &inputs.1),
inner_phi_type,
func,
)?;
func.instruction(&W::End);
ctx.mark_processed(merge_idx);
self.emit_merge_block(merge_idx, SkipPhi::from_phi_info(&phi_info), ctx, func)?;
} else if let I::Switch {
scrutinee,
cases,
default_block,
merge_block,
} = instr
{
// Nested Switch within merge block.
self.emit_switch(
SwitchContext {
scrutinee,
cases,
default_block: *default_block,
merge_block: *merge_block,
},
ctx,
func,
)?;
} else {
self.translate_instruction_with_dest(dest.as_ref(), instr, func)?;
}
}
Ok(())
}
/// Infer the WASM ValType for function arguments by scanning how they are
/// used in the function body. This resolves `Unknown` argument types that
/// type inference didn't propagate back to the MIR function signature.
///
/// Returns a map from argument index to inferred ValType.
/// Infer argument types from function body usage.
/// Returns a map from arg index to the flattened WASM types.
/// For multi-word arguments (e.g., tuples loaded via Load), returns multiple ValTypes.
fn infer_argument_types(
func: &mir::Function,
) -> std::collections::HashMap<usize, Vec<ValType>> {
use mir::Instruction as I;
use mir::Value as V;
let mut arg_types: std::collections::HashMap<usize, Vec<ValType>> =
std::collections::HashMap::new();
// Helper: if val is Argument(idx), record it with the given flat types.
// Multi-word entries take priority over single-word ones because they
// provide more precise information about the argument's actual shape.
let mut record_arg = |val: &Arc<V>, flat: Vec<ValType>| {
if let V::Argument(idx) = val.as_ref() {
arg_types
.entry(*idx)
.and_modify(|existing| {
// Prefer the wider (multi-word) inference
if flat.len() > existing.len() {
*existing = flat.clone();
} else if flat.len() == existing.len()
&& flat.len() == 1
&& flat[0] != existing[0]
{
// For scalar conflicts, prefer I64. Pointer-like
// arguments often appear as I64 in address ops
// (GetElement/AddI), while unresolved types may
// otherwise default to F64 and produce invalid
// signatures.
if flat[0] == ValType::I64 || existing[0] == ValType::I64 {
existing[0] = ValType::I64;
}
}
})
.or_insert(flat);
}
};
let mut load_arg_sources: HashMap<mir::VReg, usize> = HashMap::new();
for block in &func.body {
for (dest, instr) in &block.0 {
match instr {
// Float arithmetic: operands must be F64
I::AddF(a, b)
| I::SubF(a, b)
| I::MulF(a, b)
| I::DivF(a, b)
| I::ModF(a, b)
| I::PowF(a, b) => {
record_arg(a, vec![ValType::F64]);
record_arg(b, vec![ValType::F64]);
}
I::NegF(a)
| I::AbsF(a)
| I::SqrtF(a)
| I::SinF(a)
| I::CosF(a)
| I::LogF(a) => {
record_arg(a, vec![ValType::F64]);
}
// Integer arithmetic: operands must be I64
I::AddI(a, b)
| I::SubI(a, b)
| I::MulI(a, b)
| I::DivI(a, b)
| I::ModI(a, b) => {
record_arg(a, vec![ValType::I64]);
record_arg(b, vec![ValType::I64]);
}
I::PowI(a) => {
record_arg(a, vec![ValType::I64]);
}
I::NegI(a) | I::AbsI(a) => {
record_arg(a, vec![ValType::I64]);
}
// Cast ops reveal operand types
I::CastFtoI(a) => {
record_arg(a, vec![ValType::F64]);
}
I::CastItoF(a) | I::CastItoB(a) => {
record_arg(a, vec![ValType::I64]);
}
// Tagged union operations: the union value is I64
I::TaggedUnionGetTag(a) | I::TaggedUnionGetValue(a, _) => {
record_arg(a, vec![ValType::I64]);
}
// GetElement: base is usually a pointer (I64), but for
// single-word tuple/record values it behaves as identity.
I::GetElement {
value,
ty,
tuple_offset,
} => {
let arg_source = match value.as_ref() {
V::Argument(idx) => Some(*idx),
V::Register(reg) => load_arg_sources.get(reg).copied(),
_ => None,
};
if let Some(arg_idx) = arg_source {
let declared_base = func
.args
.get(arg_idx)
.map(|arg| Self::flatten_type_to_valtypes(&arg.1.to_type()))
.and_then(|flat| flat.first().copied())
.unwrap_or(ValType::I64);
let min_words = (*tuple_offset as usize) + 1;
let mut inferred_flat = match ty.to_type() {
Type::Tuple(elems) => elems
.iter()
.map(|e| {
let elem_ty = e.to_type();
if elem_ty.contains_unresolved()
|| Self::allows_scalar_inference_override(&elem_ty)
{
declared_base
} else {
Self::type_to_valtype(&elem_ty)
}
})
.collect::<Vec<_>>(),
Type::Record(fields) => fields
.iter()
.map(|f| {
let elem_ty = f.ty.to_type();
if elem_ty.contains_unresolved()
|| Self::allows_scalar_inference_override(&elem_ty)
{
declared_base
} else {
Self::type_to_valtype(&elem_ty)
}
})
.collect::<Vec<_>>(),
_ => Vec::new(),
};
if inferred_flat.len() < min_words {
inferred_flat.resize(min_words, declared_base);
}
if inferred_flat.len() > 1 {
record_arg(&Arc::new(V::Argument(arg_idx)), inferred_flat);
continue;
}
}
let scalar_aggregate = ty.word_size() <= 1 && *tuple_offset == 0;
if scalar_aggregate {
let elem_vtype = match ty.to_type() {
Type::Tuple(elems) => elems
.get(*tuple_offset as usize)
.map(|e| Self::type_to_valtype(&e.to_type()))
.unwrap_or(ValType::I64),
Type::Record(fields) => fields
.get(*tuple_offset as usize)
.map(|f| Self::type_to_valtype(&f.ty.to_type()))
.unwrap_or(ValType::I64),
_ => ValType::I64,
};
record_arg(value, vec![elem_vtype]);
} else {
record_arg(value, vec![ValType::I64]);
}
}
// Store: address is I64, source type depends on stored type
I::Store(addr, src, ty) => {
record_arg(addr, vec![ValType::I64]);
let expected = Self::type_to_valtype(&ty.to_type());
record_arg(src, vec![expected]);
}
// Load: detect multi-word types to expand argument params
I::Load(val, ty) => {
if let (mir::Value::Register(dest_reg), V::Argument(arg_idx)) =
(dest.as_ref(), val.as_ref())
{
load_arg_sources.insert(*dest_reg, *arg_idx);
}
let word_size = ty.word_size();
if word_size > 1 {
// Multi-word load reveals the actual aggregate shape
let flat = Self::flatten_type_to_valtypes(&ty.to_type());
record_arg(val, flat);
} else {
// Scalar load from an Argument can be either:
// - direct scalar value (single-word argument), or
// - dereference through an aggregate pointer (multi-word argument).
// Use the declared argument shape to distinguish them.
let expected = match val.as_ref() {
V::Argument(idx) => {
let declared_word_size = func
.args
.get(*idx)
.map(|arg| arg.1.word_size())
.unwrap_or(1);
if declared_word_size > 1 {
ValType::I64
} else {
Self::type_to_valtype(&ty.to_type())
}
}
_ => Self::type_to_valtype(&ty.to_type()),
};
record_arg(val, vec![expected]);
}
}
// Call: argument types come from the Call's arg type annotations
I::Call(_, args, _) | I::CallIndirect(_, args, _) | I::CallCls(_, args, _) => {
for (arg_val, arg_ty) in args {
let expected = Self::type_to_valtype(&arg_ty.to_type());
record_arg(arg_val, vec![expected]);
}
}
// Return: the returned value should match the function's return type
I::Return(val, ty) => {
let expected = Self::type_to_valtype(&ty.to_type());
record_arg(val, vec![expected]);
}
_ => {}
}
}
}
arg_types
}
/// Analyze MIR function body to determine register types
/// This scans all instructions and records each register's ValType (I64 or F64)
fn analyze_register_types(&mut self, func: &mir::Function) {
use mir::Instruction as I;
use wasm_encoder::ValType;
for block in &func.body {
for (dest, instr) in &block.0 {
if let mir::Value::Register(reg_idx) = dest.as_ref() {
// Track register type
let reg_type = match instr {
// Integer types -> I64
I::Uinteger(val) => {
// Also track the constant value for function indices
self.register_constants.insert(*reg_idx, *val);
ValType::I64
}
I::Integer(_) => ValType::I64,
// Float type -> F64
I::Float(_) => ValType::F64,
// Arithmetic operations - use operand types
I::AddF(..)
| I::SubF(..)
| I::MulF(..)
| I::DivF(..)
| I::ModF(..)
| I::PowF(..) => ValType::F64,
I::AddI(..)
| I::SubI(..)
| I::MulI(..)
| I::DivI(..)
| I::ModI(..)
| I::PowI(..) => ValType::I64,
// Comparison operations -> f64 (0.0/1.0) in mimium
I::Eq(..) | I::Ne(..) | I::Le(..) | I::Lt(..) | I::Ge(..) | I::Gt(..) => {
ValType::F64
}
// Logical operations -> f64 (0.0/1.0) in mimium
I::And(..) | I::Or(..) | I::Not(..) => ValType::F64,
// Load - depends on type annotation and source shape
I::Load(ptr, ty) => {
// For multi-word arguments (tuple/record flattened at call boundary),
// `Load` must preserve the aggregate pointer. Field extraction is
// performed explicitly by subsequent GetElement/Load operations.
if let mir::Value::Argument(arg_idx) = ptr.as_ref()
&& let Some(&(_, word_count)) = self.current_arg_map.get(*arg_idx)
&& word_count > 1
{
ValType::I64
} else {
// Use type_to_valtype for consistent handling
// (e.g., single-field records unwrap to their field type)
Self::type_to_valtype(&ty.to_type())
}
}
// Function calls and memory operations
I::Call(fn_ptr, _, ret_ty) => {
if let mir::Value::ExtFunction(name, _) = fn_ptr.as_ref()
&& Self::is_probe_value_intercept_arity1(*name)
{
ValType::F64
} else {
let ret = ret_ty.to_type();
if ret.contains_unresolved()
|| Self::allows_scalar_inference_override(&ret)
{
self.resolve_mir_fn_idx(fn_ptr.as_ref())
.and_then(|idx| self.mir.functions.get(idx))
.and_then(|f| f.return_type.get())
.map(|ty| Self::type_to_valtype(&ty.to_type()))
.unwrap_or_else(|| Self::type_to_valtype(&ret))
} else {
Self::type_to_valtype(&ret)
}
}
}
I::CallIndirect(_, _, ret_ty) | I::CallCls(_, _, ret_ty) => {
Self::type_to_valtype(&ret_ty.to_type())
}
// Memory allocation returns pointers (i64)
I::Alloc(type_id) => {
let ws = type_id.word_size();
self.alloc_registers.insert(*reg_idx, ws);
self.alloc_register_indirect.insert(
*reg_idx,
Self::alloc_capture_should_be_indirect(&type_id.to_type()),
);
ValType::I64
}
// GetElement returns pointer (i64), but track it so consumers
// can dereference when using the result as a value.
I::GetElement {
value,
ty,
tuple_offset,
} => {
// Extract the element's own type from the composite type
let composite_ty = ty.to_type();
let element_vtype = match &composite_ty {
Type::Tuple(elems) => {
let idx = *tuple_offset as usize;
if idx < elems.len() {
Self::type_to_valtype(&elems[idx].to_type())
} else {
ValType::I64
}
}
Type::Record(fields) => {
let idx = *tuple_offset as usize;
if idx < fields.len() {
Self::type_to_valtype(&fields[idx].ty.to_type())
} else {
ValType::I64
}
}
_ => ValType::I64,
};
let base_vtype = self.infer_value_type(value);
if base_vtype != ValType::I64 {
// Base is already a scalar value. Preserve scalar semantics
// to avoid reinterpreting floating values as pointers.
element_vtype
} else {
self.getelement_registers.insert(*reg_idx, element_vtype);
ValType::I64
}
}
// Phi inherits type from its first input
I::Phi(v1, _) => self.infer_value_type(v1),
// Type casts
I::CastFtoI(_) | I::CastItoB(_) => ValType::I64,
I::CastItoF(_) => ValType::F64,
// Unary float ops
I::NegF(..)
| I::AbsF(..)
| I::SqrtF(..)
| I::SinF(..)
| I::CosF(..)
| I::LogF(..) => ValType::F64,
I::NegI(..) | I::AbsI(..) => ValType::I64,
// State operations: GetState returns an address (pointer)
I::GetState(_) => ValType::I64,
// Delay and Mem return f64
I::Delay(..) => ValType::F64,
I::Mem(..) => ValType::F64,
// GetGlobal loads the actual value
I::GetGlobal(_, ty) => Self::type_to_valtype(&ty.to_type()),
// GetUpValue loads the actual value
I::GetUpValue(_, ty) => Self::type_to_valtype(&ty.to_type()),
// ReturnFeed is handled separately (is_return)
I::ReturnFeed(_, _) => ValType::F64,
// Tagged union operations
I::TaggedUnionWrap { union_type, .. } => {
Self::type_to_valtype(&union_type.to_type())
}
I::TaggedUnionGetTag(_) => ValType::I64,
I::TaggedUnionGetValue(_, _) => ValType::I64, // produces a pointer (address)
// PhiSwitch inherits type from its first input
I::PhiSwitch(inputs) => inputs
.first()
.map(|first| self.infer_value_type(first))
.unwrap_or(ValType::I64),
// Switch does not produce a value
I::Switch { .. } => ValType::I64,
// Array literal produces a pointer
I::Array(..) => ValType::I64,
// String constant produces a pointer
I::String(_) => ValType::I64,
// Closure produces an i64 handle
I::Closure(_) => ValType::I64,
I::MakeClosure { .. } => ValType::I64,
// BoxAlloc produces an i64 handle
I::BoxAlloc { .. } => ValType::I64,
// BoxLoad type depends on inner type
I::BoxLoad { inner_type, .. } => {
Self::type_to_valtype(&inner_type.to_type())
}
// GetArrayElem type depends on elem type
I::GetArrayElem(_, _, elem_ty) => Self::type_to_valtype(&elem_ty.to_type()),
// Default to I64 for unknown/unhandled instructions.
// I64 is the safer default since it's the universal word type.
_ => ValType::I64,
};
self.register_types.insert(*reg_idx, reg_type);
}
}
}
}
/// Compute the maximum register index for i64 and f64 types.
/// Returns (max_i64_index + 1, max_f64_index + 1), i.e. the count of locals needed.
fn compute_max_register_indices(&self) -> (u32, u32) {
let mut max_i64: u32 = 0;
let mut max_f64: u32 = 0;
for (®_idx, &val_type) in &self.register_types {
let idx = reg_idx as u32 + 1; // +1 to convert index to count
match val_type {
ValType::I64 => max_i64 = max_i64.max(idx),
ValType::F64 => max_f64 = max_f64.max(idx),
_ => max_f64 = max_f64.max(idx),
}
}
(max_i64, max_f64)
}
/// Translate a single MIR instruction with destination to WASM
fn translate_instruction_with_dest(
&mut self,
dest: &mir::Value,
instr: &mir::Instruction,
func: &mut Function,
) -> Result<(), String> {
use mir::Instruction as I;
use wasm_encoder::Instruction as W;
// Return instructions (both Return and ReturnFeed) are special - they leave the value on the stack
// for the function to return. We should not store the value to a destination register or drop it.
let is_return = matches!(instr, I::Return(_, _) | I::ReturnFeed(_, _));
// Generate the instruction (pushes result to stack)
self.translate_instruction(instr, func)?;
// Calls to Unit-returning functions produce no value on the WASM stack
// (both MIR functions and plugin imports strip Unit return types).
let is_void_call = matches!(
instr,
I::Call(_, _, ret_ty) | I::CallIndirect(_, _, ret_ty) | I::CallCls(_, _, ret_ty)
if matches!(ret_ty.to_type(), Type::Primitive(PType::Unit))
);
// Only handle destination for non-return instructions that produce a value
if !is_return && !is_void_call && Self::instruction_produces_value(instr) {
// Store result to destination register if specified
match dest {
mir::Value::Register(reg_idx) => {
// Map register to correct local variable based on type
// WASM local layout: [args(0..n)] [i64 regs(n..n+32)] [f64 regs(n+32..n+64)]
let reg_type = self
.register_types
.get(reg_idx)
.copied()
.unwrap_or(ValType::I64);
let local_idx = match reg_type {
ValType::I64 => self.current_num_args + *reg_idx as u32,
ValType::F64 => {
self.current_num_args + self.current_num_i64_locals + *reg_idx as u32
}
_ => self.current_num_args + self.current_num_i64_locals + *reg_idx as u32,
};
func.instruction(&W::LocalSet(local_idx));
}
mir::Value::None => {
// No destination, result is discarded (pop it from stack)
func.instruction(&W::Drop);
}
_ => {
// Other destination types not yet handled
// TODO: Handle Global, State, etc.
}
}
}
Ok(())
}
/// Returns true if the instruction produces a value on the WASM stack.
/// Non-producing instructions (stores, state ops, releases) do not leave
/// a value on the stack, so the caller should not attempt to LocalSet or Drop.
fn instruction_produces_value(instr: &mir::Instruction) -> bool {
use mir::Instruction as I;
!matches!(
instr,
I::Store(..)
| I::PushStateOffset(..)
| I::PopStateOffset(..)
| I::BoxRelease { .. }
| I::BoxClone { .. }
| I::BoxStore { .. }
| I::CloseHeapClosure(..)
| I::CloneHeap(..)
| I::CloneUserSum { .. }
| I::ReleaseUserSum { .. }
| I::CloseUpValues(..)
| I::SetUpValue(..)
| I::SetGlobal(..)
| I::SetArrayElem(..)
| I::Return(..)
| I::ReturnFeed(..)
| I::JmpIf(..)
| I::Jmp(..)
| I::Phi(..)
| I::PhiSwitch(..)
| I::Switch { .. }
)
}
fn function_has_non_external_calls(func: &mir::Function) -> bool {
use mir::Instruction as I;
func.body
.iter()
.flat_map(|bb| bb.0.iter())
.any(|(_, instr)| match instr {
I::Call(fn_ptr, _, _) => !matches!(fn_ptr.as_ref(), mir::Value::ExtFunction(_, _)),
I::CallIndirect(_, _, _) | I::CallCls(_, _, _) => true,
_ => false,
})
}
/// Export all functions and memory
fn export_functions(&mut self) -> Result<(), String> {
// Clone the functions vector to avoid borrow checker issues
let functions = self.mir.functions.clone();
// Track the dsp function index if it exists
let mut dsp_idx = None;
let mut global_init_idx = None;
// Track already exported function indices to avoid duplicates
let mut exported_indices = std::collections::HashSet::new();
// Export all public functions
for func in &functions {
let fn_idx = *self
.fn_name_to_idx
.get(&func.label)
.ok_or_else(|| format!("Function {:?} not found in mapping", func.label))?;
// Check if this is the dsp function
if func.label.as_str() == "dsp" {
dsp_idx = Some(fn_idx);
}
// Check if this is the global initializer
if func.label.as_str() == "_mimium_global" {
global_init_idx = Some(fn_idx);
}
// Only export if not already exported
if exported_indices.insert(fn_idx) {
// Use the function name from the symbol interner
let fn_name = format!("fn_{fn_idx}");
self.export_section
.export(&fn_name, wasm_encoder::ExportKind::Func, fn_idx);
}
}
// Export the dsp function with its canonical name if it exists
if let Some(idx) = dsp_idx {
self.export_section
.export("dsp", wasm_encoder::ExportKind::Func, idx);
}
// Export the global initializer as "main" for the runtime to call
if let Some(idx) = global_init_idx {
self.export_section
.export("main", wasm_encoder::ExportKind::Func, idx);
}
// Export memory so the host can access it
self.export_section
.export("memory", wasm_encoder::ExportKind::Memory, 0);
// Export runtime allocator pointer for host-side safety recovery.
self.export_section.export(
"__alloc_ptr",
wasm_encoder::ExportKind::Global,
self.alloc_ptr_global,
);
Ok(())
}
/// Translate a single MIR instruction to WASM instructions
fn translate_instruction(
&mut self,
instr: &mir::Instruction,
func: &mut Function,
) -> Result<(), String> {
use mir::Instruction as I;
use wasm_encoder::Instruction as W;
match instr {
// Constants
I::Float(f) => {
func.instruction(&W::F64Const(*f));
}
I::Integer(i) => {
func.instruction(&W::I64Const(*i));
}
I::Uinteger(u) => {
func.instruction(&W::I64Const(*u as i64));
}
// Arithmetic operations (f64)
I::AddF(a, b) => {
self.emit_value_load_typed(a, ValType::F64, func);
self.emit_value_load_typed(b, ValType::F64, func);
func.instruction(&W::F64Add);
}
I::SubF(a, b) => {
self.emit_value_load_typed(a, ValType::F64, func);
self.emit_value_load_typed(b, ValType::F64, func);
func.instruction(&W::F64Sub);
}
I::MulF(a, b) => {
self.emit_value_load_typed(a, ValType::F64, func);
self.emit_value_load_typed(b, ValType::F64, func);
func.instruction(&W::F64Mul);
}
I::DivF(a, b) => {
self.emit_value_load_typed(a, ValType::F64, func);
self.emit_value_load_typed(b, ValType::F64, func);
func.instruction(&W::F64Div);
}
I::NegF(a) => {
self.emit_value_load_typed(a, ValType::F64, func);
func.instruction(&W::F64Neg);
}
I::AbsF(a) => {
self.emit_value_load_typed(a, ValType::F64, func);
func.instruction(&W::F64Abs);
}
I::SqrtF(a) => {
self.emit_value_load_typed(a, ValType::F64, func);
func.instruction(&W::F64Sqrt);
}
I::SinF(a) => {
self.emit_value_load_typed(a, ValType::F64, func);
func.instruction(&W::Call(self.rt.math_sin));
}
I::CosF(a) => {
self.emit_value_load_typed(a, ValType::F64, func);
func.instruction(&W::Call(self.rt.math_cos));
}
I::LogF(a) => {
self.emit_value_load_typed(a, ValType::F64, func);
func.instruction(&W::Call(self.rt.math_log));
}
I::PowF(a, b) => {
self.emit_value_load_typed(a, ValType::F64, func);
self.emit_value_load_typed(b, ValType::F64, func);
func.instruction(&W::Call(self.rt.math_pow));
}
I::ModF(a, b) => {
// WASM has no native f64 remainder; compute a - trunc(a/b) * b
self.emit_value_load_typed(a, ValType::F64, func);
self.emit_value_load_typed(a, ValType::F64, func);
self.emit_value_load_typed(b, ValType::F64, func);
func.instruction(&W::F64Div);
func.instruction(&W::F64Trunc);
self.emit_value_load_typed(b, ValType::F64, func);
func.instruction(&W::F64Mul);
func.instruction(&W::F64Sub);
}
// Integer arithmetic operations
I::AddI(a, b) => {
self.emit_value_load_typed(a, ValType::I64, func);
self.emit_value_load_typed(b, ValType::I64, func);
func.instruction(&W::I64Add);
}
I::SubI(a, b) => {
self.emit_value_load_typed(a, ValType::I64, func);
self.emit_value_load_typed(b, ValType::I64, func);
func.instruction(&W::I64Sub);
}
I::MulI(a, b) => {
self.emit_value_load_typed(a, ValType::I64, func);
self.emit_value_load_typed(b, ValType::I64, func);
func.instruction(&W::I64Mul);
}
I::DivI(a, b) => {
self.emit_value_load_typed(a, ValType::I64, func);
self.emit_value_load_typed(b, ValType::I64, func);
func.instruction(&W::I64DivS);
}
I::ModI(a, b) => {
self.emit_value_load_typed(a, ValType::I64, func);
self.emit_value_load_typed(b, ValType::I64, func);
func.instruction(&W::I64RemS);
}
I::NegI(a) => {
// -x = 0 - x
func.instruction(&W::I64Const(0));
self.emit_value_load_typed(a, ValType::I64, func);
func.instruction(&W::I64Sub);
}
I::AbsI(a) => {
// abs(x) = if x < 0 then -x else x
// Use: (x ^ (x >> 63)) - (x >> 63)
self.emit_value_load_typed(a, ValType::I64, func);
self.emit_value_load_typed(a, ValType::I64, func);
func.instruction(&W::I64Const(63));
func.instruction(&W::I64ShrS);
func.instruction(&W::I64Xor);
self.emit_value_load_typed(a, ValType::I64, func);
func.instruction(&W::I64Const(63));
func.instruction(&W::I64ShrS);
func.instruction(&W::I64Sub);
}
// Logical operations (produce f64 0.0/1.0)
I::And(a, b) => {
// Convert both operands to boolean, AND them, convert to f64
self.emit_value_load_typed(a, ValType::F64, func);
func.instruction(&W::F64Const(0.0));
func.instruction(&W::F64Ne);
self.emit_value_load_typed(b, ValType::F64, func);
func.instruction(&W::F64Const(0.0));
func.instruction(&W::F64Ne);
func.instruction(&W::I32And);
func.instruction(&W::F64ConvertI32U);
}
I::Or(a, b) => {
self.emit_value_load_typed(a, ValType::F64, func);
func.instruction(&W::F64Const(0.0));
func.instruction(&W::F64Ne);
self.emit_value_load_typed(b, ValType::F64, func);
func.instruction(&W::F64Const(0.0));
func.instruction(&W::F64Ne);
func.instruction(&W::I32Or);
func.instruction(&W::F64ConvertI32U);
}
I::Not(a) => {
self.emit_value_load_typed(a, ValType::F64, func);
func.instruction(&W::F64Const(0.0));
func.instruction(&W::F64Eq);
func.instruction(&W::F64ConvertI32U);
}
// Type cast operations
I::CastFtoI(a) => {
self.emit_value_load_typed(a, ValType::F64, func);
func.instruction(&W::I64TruncSatF64S);
}
I::CastItoF(a) => {
self.emit_value_load_typed(a, ValType::I64, func);
func.instruction(&W::F64ConvertI64S);
}
I::CastItoB(a) => {
// i64 -> bool (i64): non-zero = 1, zero = 0
self.emit_value_load_typed(a, ValType::I64, func);
func.instruction(&W::I64Const(0));
func.instruction(&W::I64Ne);
func.instruction(&W::I64ExtendI32U);
}
// Boolean operations (results are i32 in WASM, extended to i64 for register storage)
// Operands can be f64 or i64; we check operand type to emit correct comparison.
I::Eq(a, b) => {
let op_type = self.infer_value_type(a);
self.emit_value_load_typed(a, op_type, func);
self.emit_value_load_typed(b, op_type, func);
if op_type == ValType::F64 {
func.instruction(&W::F64Eq);
} else {
func.instruction(&W::I64Eq);
}
func.instruction(&W::F64ConvertI32U);
}
I::Ne(a, b) => {
let op_type = self.infer_value_type(a);
self.emit_value_load_typed(a, op_type, func);
self.emit_value_load_typed(b, op_type, func);
if op_type == ValType::F64 {
func.instruction(&W::F64Ne);
} else {
func.instruction(&W::I64Ne);
}
func.instruction(&W::F64ConvertI32U);
}
I::Lt(a, b) => {
let op_type = self.infer_value_type(a);
self.emit_value_load_typed(a, op_type, func);
self.emit_value_load_typed(b, op_type, func);
if op_type == ValType::F64 {
func.instruction(&W::F64Lt);
} else {
func.instruction(&W::I64LtS);
}
func.instruction(&W::F64ConvertI32U);
}
I::Le(a, b) => {
let op_type = self.infer_value_type(a);
self.emit_value_load_typed(a, op_type, func);
self.emit_value_load_typed(b, op_type, func);
if op_type == ValType::F64 {
func.instruction(&W::F64Le);
} else {
func.instruction(&W::I64LeS);
}
func.instruction(&W::F64ConvertI32U);
}
I::Gt(a, b) => {
let op_type = self.infer_value_type(a);
self.emit_value_load_typed(a, op_type, func);
self.emit_value_load_typed(b, op_type, func);
if op_type == ValType::F64 {
func.instruction(&W::F64Gt);
} else {
func.instruction(&W::I64GtS);
}
func.instruction(&W::F64ConvertI32U);
}
I::Ge(a, b) => {
let op_type = self.infer_value_type(a);
self.emit_value_load_typed(a, op_type, func);
self.emit_value_load_typed(b, op_type, func);
if op_type == ValType::F64 {
func.instruction(&W::F64Ge);
} else {
func.instruction(&W::I64GeS);
}
func.instruction(&W::F64ConvertI32U);
}
// Heap operations - Box operations
I::BoxAlloc { value, inner_type } => {
// box_alloc(src_ptr: i32, size_words: i32) -> i64
// Write value to temp memory, then pass its address
let size = inner_type.word_size() as u32;
let size_words = size.max(1);
let temp_addr = self.mem_layout.alloc_offset;
self.mem_layout.alloc_offset += size_words * 8;
// Write value to temp memory
let val_type = self.infer_value_type(value);
if size_words > 1 && val_type == ValType::I64 {
// Multi-word: copy word-by-word from value pointer
for w in 0..size_words {
func.instruction(&W::I32Const((temp_addr + w * 8) as i32));
self.emit_value_load(value, func);
func.instruction(&W::I32WrapI64);
func.instruction(&W::I64Load(MemArg {
offset: (w * 8) as u64,
align: 3,
memory_index: 0,
}));
func.instruction(&W::I64Store(MemArg {
offset: 0,
align: 3,
memory_index: 0,
}));
}
} else {
// Single-word: store directly
let inner_vtype = Self::type_to_valtype(&inner_type.to_type());
func.instruction(&W::I32Const(temp_addr as i32));
self.emit_value_load_deref(value, inner_vtype, func);
match inner_vtype {
ValType::F64 => {
func.instruction(&W::I64ReinterpretF64);
func.instruction(&W::I64Store(MemArg {
offset: 0,
align: 3,
memory_index: 0,
}));
}
_ => {
func.instruction(&W::I64Store(MemArg {
offset: 0,
align: 3,
memory_index: 0,
}));
}
};
}
func.instruction(&W::I32Const(temp_addr as i32)); // src_ptr
func.instruction(&W::I32Const(size_words as i32));
func.instruction(&W::Call(self.rt.box_alloc));
}
I::BoxLoad { ptr, inner_type } => {
// box_load(dst_ptr: i32, obj: i64, size_words: i32)
// This writes to dst_ptr but returns void.
// We allocate temp memory and read from it after the call.
let size = inner_type.word_size() as i32;
let size_bytes = (size as u32).max(1) * 8;
let temp_addr = self.mem_layout.alloc_offset;
self.mem_layout.alloc_offset += size_bytes;
func.instruction(&W::I32Const(temp_addr as i32)); // dst_ptr
self.emit_value_load_deref(ptr, ValType::I64, func); // obj: HeapIdx
func.instruction(&W::I32Const(size));
func.instruction(&W::Call(self.rt.box_load));
if inner_type.word_size() > 1 {
// Multi-word: return pointer to temp data
func.instruction(&W::I64Const(temp_addr as i64));
} else {
// Single-word: read the loaded value from temp memory
func.instruction(&W::I32Const(temp_addr as i32));
let memarg = MemArg {
offset: 0,
align: 3,
memory_index: 0,
};
match Self::type_to_valtype(&inner_type.to_type()) {
ValType::F64 => func.instruction(&W::F64Load(memarg)),
_ => func.instruction(&W::I64Load(memarg)),
};
}
}
I::BoxClone { ptr } => {
// box_clone(obj: i64)
self.emit_value_load_deref(ptr, ValType::I64, func);
func.instruction(&W::Call(self.rt.box_clone));
}
I::BoxRelease { ptr, inner_type: _ } => {
// box_release(obj: i64)
self.emit_value_load_deref(ptr, ValType::I64, func);
func.instruction(&W::Call(self.rt.box_release));
}
I::BoxStore {
ptr,
value,
inner_type,
} => {
// box_store(obj: i64, src_ptr: i32, size_words: i32)
let size = inner_type.word_size() as u32;
let size_words = size.max(1);
let temp_addr = self.mem_layout.alloc_offset;
self.mem_layout.alloc_offset += size_words * 8;
// Write new value to temp memory
let val_type = self.infer_value_type(value);
if size_words > 1 && val_type == ValType::I64 {
// Multi-word: copy word-by-word from value pointer
for w in 0..size_words {
func.instruction(&W::I32Const((temp_addr + w * 8) as i32));
self.emit_value_load(value, func);
func.instruction(&W::I32WrapI64);
func.instruction(&W::I64Load(MemArg {
offset: (w * 8) as u64,
align: 3,
memory_index: 0,
}));
func.instruction(&W::I64Store(MemArg {
offset: 0,
align: 3,
memory_index: 0,
}));
}
} else {
// Single-word: store directly
func.instruction(&W::I32Const(temp_addr as i32));
self.emit_value_load(value, func);
match val_type {
ValType::F64 => {
func.instruction(&W::I64ReinterpretF64);
func.instruction(&W::I64Store(MemArg {
offset: 0,
align: 3,
memory_index: 0,
}));
}
_ => {
func.instruction(&W::I64Store(MemArg {
offset: 0,
align: 3,
memory_index: 0,
}));
}
};
}
self.emit_value_load_deref(ptr, ValType::I64, func); // obj: HeapIdx
func.instruction(&W::I32Const(temp_addr as i32)); // src_ptr
func.instruction(&W::I32Const(size_words as i32));
func.instruction(&W::Call(self.rt.box_store));
}
// Heap operations - Closure operations
I::MakeClosure { fn_proto, size: _ } => {
// Allocate closure in linear memory: [fn_table_idx: i64] [upval0: i64] ... [upvalN: i64]
// Uses runtime bump allocator so each recursive invocation gets a unique address.
let mir_fn_idx = match fn_proto.as_ref() {
mir::Value::Function(idx) => *idx,
mir::Value::Register(reg_idx) => {
self.register_constants.get(reg_idx).copied().unwrap_or(0) as usize
}
_ => 0,
};
let mir = self.mir.clone();
let upindexes = if mir_fn_idx < mir.functions.len() {
mir.functions[mir_fn_idx].upindexes.clone()
} else {
vec![]
};
let num_upvalues = upindexes.len();
let closure_size_bytes = ((1 + num_upvalues) as u32) * 8;
// Runtime allocation: base address saved in alloc_base_local
self.emit_runtime_alloc(closure_size_bytes, func);
// Store function table index at base (table idx = MIR fn idx)
func.instruction(&W::LocalGet(self.alloc_base_local));
func.instruction(&W::I64Const(mir_fn_idx as i64));
func.instruction(&W::I64Store(MemArg {
offset: 0,
align: 3,
memory_index: 0,
}));
// Capture upvalues into the closure.
//
// In WASM we cannot reference the WASM value stack from
// outside the function, so closures are immediately "closed":
// upvalues originating from single-word `alloc` cells store
// the **alloc pointer** (not the dereferenced value). This
// gives all closures sharing the same alloc cell a live
// reference to the same mutable storage — essential for
// `letrec` self-references and shared mutable state.
//
// Multi-word allocs (tuples, etc.) already store pointers
// (the alloc address IS the data address) and need no extra
// indirection at GetUpValue time.
//
// `GetUpValue` / `SetUpValue` check `indirect_upvalues` to
// decide whether an extra dereference is needed.
let mut is_indirect = vec![false; upindexes.len()];
for (i, upindex) in upindexes.iter().enumerate() {
let upval_byte_offset = ((1 + i) as u32) * 8;
// Push address: base + offset
func.instruction(&W::LocalGet(self.alloc_base_local));
func.instruction(&W::I32Const(upval_byte_offset as i32));
func.instruction(&W::I32Add);
match upindex.as_ref() {
mir::Value::Register(reg_idx)
if self
.alloc_register_indirect
.get(reg_idx)
.copied()
.unwrap_or(false) =>
{
// Single-word alloc: store the alloc pointer so the
// closure shares the mutable cell. GetUpValue will
// dereference through the pointer.
is_indirect[i] = true;
self.emit_value_load(upindex, func);
}
mir::Value::Register(reg_idx)
if self.alloc_registers.get(reg_idx).copied().unwrap_or(0) > 1 =>
{
// Multi-word alloc (tuple etc.): the alloc address
// IS the data address; store as-is, no indirection.
self.emit_value_load(upindex, func);
}
mir::Value::Register(reg_idx)
if self.alloc_registers.contains_key(reg_idx) =>
{
// Single-word direct alloc (e.g. array/function handle,
// single-word record): capture the cell contents, not the
// alloc-cell address.
self.emit_value_load(upindex, func);
func.instruction(&W::I32WrapI64);
func.instruction(&W::I64Load(MemArg {
offset: 0,
align: 3,
memory_index: 0,
}));
}
_ => {
// Direct value (non-alloc register, argument, etc.)
let val_type = self.infer_value_type(upindex);
self.emit_value_load(upindex, func);
if val_type == ValType::F64 {
func.instruction(&W::I64ReinterpretF64);
}
}
}
func.instruction(&W::I64Store(MemArg {
offset: 0,
align: 3,
memory_index: 0,
}));
}
self.indirect_upvalues.insert(mir_fn_idx, is_indirect);
// Push closure address as the result (i64)
func.instruction(&W::LocalGet(self.alloc_base_local));
func.instruction(&W::I64ExtendI32U);
}
I::CloseHeapClosure(_ptr) => {
// No-op in WASM: upvalues are already in linear memory
}
I::CloneHeap(_ptr) => {
// No-op in WASM: linear memory closures don't need refcounting
}
// Heap operations - UserSum operations
I::CloneUserSum { value: _, ty } => {
// usersum_clone(value_ptr: i32, size_words: i32, type_id: i32)
let size = ty.word_size() as i32;
let type_id = 0i32; // TODO: Get actual type_id from type table
func.instruction(&W::I32Const(0)); // value_ptr placeholder
func.instruction(&W::I32Const(size));
func.instruction(&W::I32Const(type_id));
func.instruction(&W::Call(self.rt.usersum_clone));
}
I::ReleaseUserSum { value: _, ty } => {
// usersum_release(value_ptr: i32, size_words: i32, type_id: i32)
let size = ty.word_size() as i32;
let type_id = 0i32; // TODO: Get actual type_id from type table
func.instruction(&W::I32Const(0)); // value_ptr placeholder
func.instruction(&W::I32Const(size));
func.instruction(&W::I32Const(type_id));
func.instruction(&W::Call(self.rt.usersum_release));
}
// State operations
I::PushStateOffset(offset) => {
// state_push(offset: i64)
func.instruction(&W::I64Const(*offset as i64));
func.instruction(&W::Call(self.rt.state_push));
}
I::PopStateOffset(offset) => {
// state_pop(offset: i64)
func.instruction(&W::I64Const(*offset as i64));
func.instruction(&W::Call(self.rt.state_pop));
}
I::GetState(ty) => {
// Allocate a temp region in linear memory for state exchange
let size = ty.word_size() as i32;
let size_bytes = (size as u32).max(1) * 8;
let temp_addr = self.mem_layout.state_temp_base;
self.mem_layout.state_temp_base += size_bytes;
// Call state_get(dst_ptr: i32, size_words: i32) to fill temp memory
func.instruction(&W::I32Const(temp_addr as i32));
func.instruction(&W::I32Const(size));
func.instruction(&W::Call(self.rt.state_get));
// Push the temp address as i64 so subsequent Load can read from it
func.instruction(&W::I64Const(temp_addr as i64));
}
I::ReturnFeed(value, ty) => {
// Persist state value, then return it.
let size = ty.word_size() as i32;
if size <= 1 {
// Single-word value: store to temp memory, then state_set from temp
let size_bytes = 8u32;
let temp_addr = self.mem_layout.state_temp_base;
self.mem_layout.state_temp_base += size_bytes;
let memarg = MemArg {
offset: 0,
align: 3,
memory_index: 0,
};
func.instruction(&W::I32Const(temp_addr as i32));
self.emit_value_load(value, func);
match Self::type_to_valtype(&ty.to_type()) {
ValType::F64 => func.instruction(&W::F64Store(memarg)),
_ => func.instruction(&W::I64Store(memarg)),
};
// Call state_set(src_ptr: i32, size_words: i32) to persist state
func.instruction(&W::I32Const(temp_addr as i32));
func.instruction(&W::I32Const(size));
func.instruction(&W::Call(self.rt.state_set));
} else {
// Multi-word value: value is a pointer to linear memory data.
// Pass the pointer directly to state_set (data is already in memory).
self.emit_value_load(value, func);
func.instruction(&W::I32WrapI64); // convert i64 ptr to i32
func.instruction(&W::I32Const(size));
func.instruction(&W::Call(self.rt.state_set));
}
// Entry functions restore the alloc pointer before returning.
if self.is_entry_function {
func.instruction(&W::LocalGet(self.alloc_ptr_save_local));
func.instruction(&W::GlobalSet(self.alloc_ptr_global));
}
// Push the return value onto the stack (ReturnFeed acts as Return)
self.emit_value_load(value, func);
}
I::Delay(len, input, time) => {
// state_delay(input: f64, time: f64, max_len: i64) -> f64
self.emit_value_load_typed(input, ValType::F64, func);
self.emit_value_load_typed(time, ValType::F64, func);
let max_len_i64 = i64::try_from(*len).unwrap_or(i64::MAX);
func.instruction(&W::I64Const(max_len_i64));
func.instruction(&W::Call(self.rt.state_delay));
}
I::Mem(value) => {
// state_mem(input: f64) -> f64
self.emit_value_load_typed(value, ValType::F64, func);
func.instruction(&W::Call(self.rt.state_mem));
}
// Array operations
I::Array(values, ty) => {
// array_alloc(src_ptr: i64, size_words: i32) -> i64
// Reads `size_words` words from linear memory at `src_ptr` and creates an array.
// MIR stores the array element type here, not the full array type.
let elem_ty = *ty;
let elem_size = elem_ty.word_size() as u32;
let total_words = values.len() as u32 * elem_size.max(1);
let total_bytes = total_words * 8;
// Allocate temp memory region for element data
let temp_addr = self.mem_layout.alloc_offset;
self.mem_layout.alloc_offset += total_bytes;
// Write each element's data to linear memory
for (i, val) in values.iter().enumerate() {
let base_offset = temp_addr + (i as u32) * elem_size.max(1) * 8;
if elem_size > 1 {
// Multi-word element (e.g. tuple): copy data word-by-word
// from the pointer held by the value register.
for w in 0..elem_size {
func.instruction(&W::I32Const((base_offset + w * 8) as i32));
self.emit_value_load(val, func);
func.instruction(&W::I32WrapI64);
func.instruction(&W::I64Load(MemArg {
offset: (w * 8) as u64,
align: 3,
memory_index: 0,
}));
func.instruction(&W::I64Store(MemArg {
offset: 0,
align: 3,
memory_index: 0,
}));
}
} else {
// Single-word element: store directly
func.instruction(&W::I32Const(base_offset as i32));
let elem_valtype = Self::type_to_valtype(&elem_ty.to_type());
self.emit_value_load_typed(val, elem_valtype, func);
match elem_valtype {
ValType::F64 => func.instruction(&W::F64Store(MemArg {
offset: 0,
align: 3,
memory_index: 0,
})),
_ => func.instruction(&W::I64Store(MemArg {
offset: 0,
align: 3,
memory_index: 0,
})),
};
}
}
// Call array_alloc(src_ptr, total_words)
func.instruction(&W::I64Const(temp_addr as i64)); // src_ptr
func.instruction(&W::I32Const(total_words as i32)); // size_words
func.instruction(&W::Call(self.rt.array_alloc));
}
I::GetArrayElem(array, index, elem_ty) => {
// array_get_elem(dst_ptr: i32, arr: i64, index: i64, elem_size_words: i32)
// This writes to dst_ptr but returns void.
// We allocate temp memory and read from it after the call.
let elem_size = elem_ty.word_size() as i32;
let size_bytes = (elem_size as u32).max(1) * 8;
let temp_addr = self.mem_layout.alloc_offset;
self.mem_layout.alloc_offset += size_bytes;
func.instruction(&W::I32Const(temp_addr as i32)); // dst_ptr
self.emit_value_load_typed(array, ValType::I64, func); // array handle
self.emit_value_load_as_numeric_i64(index, func); // index: use numeric truncation, not bit reinterpret
func.instruction(&W::I32Const(elem_size));
func.instruction(&W::Call(self.rt.array_get_elem));
if elem_size > 1 {
// Multi-word element: return pointer to temp memory.
// Subsequent GetElement/Load will offset from this address.
func.instruction(&W::I64Const(temp_addr as i64));
} else {
// Single-word element: load the value from temp memory
func.instruction(&W::I32Const(temp_addr as i32));
let memarg = MemArg {
offset: 0,
align: 3,
memory_index: 0,
};
match Self::type_to_valtype(&elem_ty.to_type()) {
ValType::F64 => func.instruction(&W::F64Load(memarg)),
_ => func.instruction(&W::I64Load(memarg)),
};
}
}
I::SetArrayElem(array, index, _value, elem_ty) => {
// array_set_elem(arr: i64, index: i64, src_ptr: i32, elem_size_words: i32)
let elem_size = elem_ty.word_size() as i32;
self.emit_value_load_typed(array, ValType::I64, func);
self.emit_value_load_as_numeric_i64(index, func);
func.instruction(&W::I32Const(0)); // src_ptr placeholder
func.instruction(&W::I32Const(elem_size));
func.instruction(&W::Call(self.rt.array_set_elem));
}
// Memory operations
I::Alloc(ty) => {
let size_bytes = (ty.word_size() as u32).max(1) * 8;
if self.use_runtime_alloc_for_current_function {
self.emit_runtime_alloc(size_bytes, func);
func.instruction(&W::LocalGet(self.alloc_base_local));
func.instruction(&W::I64ExtendI32U);
} else {
// Allocate at compile-time fixed offset in linear memory.
// This avoids unbounded per-sample growth for transient alloc cells.
let temp_addr = self.mem_layout.alloc_offset;
self.mem_layout.alloc_offset =
self.mem_layout.alloc_offset.saturating_add(size_bytes);
func.instruction(&W::I64Const(temp_addr as i64));
}
}
I::Load(ptr, ty) => {
// Load a value from a pointer
let is_scalar = ty.word_size() <= 1;
match ptr.as_ref() {
mir::Value::Argument(arg_idx) => {
let is_multi_word = self
.current_arg_map
.get(*arg_idx)
.is_some_and(|&(_, wc)| wc > 1);
if is_multi_word {
// Multi-word args are represented as aggregate pointers.
// Preserve the pointer here; element extraction is handled by
// explicit GetElement/Load chains in MIR.
self.emit_value_load_typed(ptr, ValType::I64, func);
} else {
// Single-word arg: the value is direct
let expected_type = Self::type_to_valtype(&ty.to_type());
self.emit_value_load_typed(ptr, expected_type, func);
}
}
_ => {
if is_scalar {
// Scalar: dereference the pointer in linear memory
self.emit_value_load_typed(ptr, ValType::I64, func);
func.instruction(&W::I32WrapI64);
let memarg = MemArg {
offset: 0,
align: 3,
memory_index: 0,
};
let expected_type = Self::type_to_valtype(&ty.to_type());
match expected_type {
ValType::F64 => {
func.instruction(&W::F64Load(memarg));
}
_ => {
func.instruction(&W::I64Load(memarg));
}
}
} else {
// Multi-word type: the address IS the value (pointer to aggregate).
// Don't dereference; GetElement will offset from this address.
self.emit_value_load_typed(ptr, ValType::I64, func);
}
}
}
}
I::Store(dst, src, ty) => {
// Store a value to a memory address
let word_size = ty.word_size() as u32;
if word_size > 1 {
// Multi-word store: copy each word from src address to dst address
// Both src and dst are pointers (I64) to linear memory.
for i in 0..word_size {
let byte_offset = (i * 8) as u64;
// Push destination address (i32) for the store
self.emit_value_load_typed(dst, ValType::I64, func);
func.instruction(&W::I32WrapI64);
// Load source word from src address + offset
self.emit_value_load_typed(src, ValType::I64, func);
func.instruction(&W::I32WrapI64);
let load_memarg = MemArg {
offset: byte_offset,
align: 3,
memory_index: 0,
};
func.instruction(&W::I64Load(load_memarg));
// Store to dst address + offset
let store_memarg = MemArg {
offset: byte_offset,
align: 3,
memory_index: 0,
};
func.instruction(&W::I64Store(store_memarg));
}
} else {
// Single-word store
// Stack order for f64.store/i64.store: [i32_addr, value]
let expected_vtype = Self::type_to_valtype(&ty.to_type());
self.emit_value_load_typed(dst, ValType::I64, func);
func.instruction(&W::I32WrapI64);
self.emit_value_load_deref(src, expected_vtype, func);
if !matches!(src.as_ref(), mir::Value::Register(r) if self.getelement_registers.contains_key(r))
{
let actual_vtype = self.infer_value_type(src);
if actual_vtype == ValType::F64 && expected_vtype == ValType::I64 {
func.instruction(&W::I64ReinterpretF64);
} else if actual_vtype == ValType::I64 && expected_vtype == ValType::F64 {
func.instruction(&W::I32WrapI64);
let memarg = MemArg {
offset: 0,
align: 3,
memory_index: 0,
};
func.instruction(&W::F64Load(memarg));
}
}
let memarg = MemArg {
offset: 0,
align: 3,
memory_index: 0,
};
match expected_vtype {
ValType::F64 => {
func.instruction(&W::F64Store(memarg));
}
_ => {
func.instruction(&W::I64Store(memarg));
}
}
}
}
I::GetElement {
value,
ty,
tuple_offset,
} => {
// Compute address of a field within a composite type.
// The byte offset must account for the actual word sizes of
// all preceding elements. We use word_size() (not
// flatten_type_to_valtypes) because memory layout follows
// word_size: e.g. a UserSum is 2 words (tag + payload) in
// memory even though it flattens to a single I64 pointer
// when passed as a function parameter.
let composite_ty = ty.to_type();
let element_vtype = match &composite_ty {
Type::Tuple(elems) => elems
.get(*tuple_offset as usize)
.map(|e| Self::type_to_valtype(&e.to_type()))
.unwrap_or(ValType::I64),
Type::Record(fields) => fields
.get(*tuple_offset as usize)
.map(|f| Self::type_to_valtype(&f.ty.to_type()))
.unwrap_or(ValType::I64),
_ => ValType::I64,
};
let base_vtype = self.infer_value_type(value);
if base_vtype != ValType::I64 {
// Base is scalar-typed; keep scalar projection semantics for all offsets.
// This avoids treating floating-point bit patterns as memory addresses.
self.emit_value_load_typed(value, element_vtype, func);
return Ok(());
}
self.emit_value_load_typed(value, ValType::I64, func);
if *tuple_offset > 0 {
let offset_bytes = match &composite_ty {
Type::Tuple(elems) => {
let word_offset: u64 = elems[0..(*tuple_offset as usize)]
.iter()
.map(|e| e.word_size() as u64)
.sum();
(word_offset * 8) as i64
}
Type::Record(fields) => {
let word_offset: u64 = fields[0..(*tuple_offset as usize)]
.iter()
.map(|f| f.ty.word_size() as u64)
.sum();
(word_offset * 8) as i64
}
_ => (*tuple_offset * 8) as i64,
};
func.instruction(&W::I64Const(offset_bytes));
func.instruction(&W::I64Add);
}
}
// Function calls
I::Call(fn_ptr, args, ret_ty) => {
// Check if this is an ext function with multi-word return type
// (e.g. split_head/split_tail returning a tuple).
// Such functions use a dest-pointer calling convention:
// the codegen allocates temp space, passes it as an extra arg,
// and the host writes the result there.
if let mir::Value::ExtFunction(name, _fn_ty) = fn_ptr.as_ref() {
let ret_words = ret_ty.word_size() as u32;
let use_dest_ptr = ret_words > 1 && Self::ext_function_uses_dest_ptr(*name);
if use_dest_ptr {
// Multi-word return: dest-pointer convention
let temp_addr = self.mem_layout.alloc_offset;
self.mem_layout.alloc_offset += ret_words * 8;
if let Some(import_idx) = self.resolve_ext_function(name) {
// Load normal args with tuple flattening so that
// aggregate values are expanded to match the
// flattened import signature.
self.emit_call_args_flattened_for_ext(name, args, func);
// Push dest pointer as extra argument
func.instruction(&W::I32Const(temp_addr as i32));
func.instruction(&W::Call(import_idx));
} else {
return Err(format!(
"Unknown external function in Call (multi-word return): {}",
name.as_str()
));
}
// Push temp address as I64 — this is the tuple pointer result
func.instruction(&W::I64Const(temp_addr as i64));
} else {
// Single-word return ExtFunction: standard call
if let Some(import_idx) = self.resolve_ext_function(name) {
self.emit_call_args_flattened_for_ext(name, args, func);
func.instruction(&W::Call(import_idx));
} else {
return Err(format!(
"Unknown external function in Call: {}",
name.as_str()
));
}
}
} else {
// Non-ext function call: load args and call by index.
// Direct calls share the caller's state storage, navigated
// by MIR's PushStateOffset/PopStateOffset instructions.
// Only closure calls (CallCls/CallIndirect) switch state context.
let mut called_mir_fn_idx: Option<usize> = None;
let wasm_fn_idx = match fn_ptr.as_ref() {
mir::Value::Function(fn_idx) => {
called_mir_fn_idx = Some(*fn_idx);
let wasm_idx = *fn_idx as u32 + self.num_imports;
log::debug!("Calling function idx={fn_idx}");
wasm_idx
}
mir::Value::Register(reg_idx) => {
if let Some(const_val) = self.register_constants.get(reg_idx) {
let fn_idx = *const_val as usize;
called_mir_fn_idx = Some(fn_idx);
let wasm_idx = *const_val as u32 + self.num_imports;
log::debug!("Calling function (via register) idx={fn_idx}");
wasm_idx
} else {
eprintln!(
"Warning: Indirect call through register without constant value"
);
self.current_fn_idx
}
}
_ => self.current_fn_idx,
};
// Load arguments using callee-side parameter shapes when available.
// This avoids ABI drift when call-site argument annotations are
// under-specified around aggregates.
if let Some(callee_idx) = called_mir_fn_idx {
let use_callee_abi = self
.mir
.functions
.get(callee_idx)
.is_some_and(|f| f.label.as_str().starts_with("delay$"));
if use_callee_abi {
self.emit_call_args_for_callee(args, callee_idx, func);
} else {
self.emit_call_args_flattened(args, func);
}
} else {
self.emit_call_args_flattened(args, func);
}
func.instruction(&W::Call(wasm_fn_idx));
// Reconcile return stack type when function declaration and
// call-site expectation differ (can happen with unresolved
// MIR types around aggregates/pointers).
let expected_ret_vt = match ret_ty.to_type() {
Type::Primitive(PType::Unit) => None,
other
if other.contains_unresolved()
|| Self::allows_scalar_inference_override(&other) =>
{
None
}
other => Some(Self::type_to_valtype(&other)),
};
let actual_ret_vt = called_mir_fn_idx.and_then(|idx| {
self.mir.functions.get(idx).and_then(|f| {
f.return_type.get().and_then(|ty| {
let ty = ty.to_type();
if matches!(ty, Type::Primitive(PType::Unit)) {
None
} else {
Some(Self::type_to_valtype(&ty))
}
})
})
});
if let (Some(actual), Some(expected)) = (actual_ret_vt, expected_ret_vt)
&& actual != expected
{
match (actual, expected) {
(ValType::F64, ValType::I64) => {
func.instruction(&W::I64ReinterpretF64);
}
(ValType::I64, ValType::F64) => {
func.instruction(&W::F64ReinterpretI64);
}
_ => {}
}
}
}
}
I::CallIndirect(closure_ptr, args, ret_ty) => {
// Check if this is an external function call or a closure call
match closure_ptr.as_ref() {
mir::Value::ExtFunction(name, _fn_ty) => {
// External function call - map to runtime imports.
// Use flattened argument loading so that tuple args are
// expanded into individual WASM values matching the
// import signature produced by setup_plugin_imports.
if let Some(import_idx) = self.resolve_ext_function(name) {
self.emit_call_args_flattened_for_ext(name, args, func);
func.instruction(&W::Call(import_idx));
} else {
return Err(format!(
"Unknown external function in CallIndirect: {}",
name.as_str()
));
}
}
_ => {
let return_types: Vec<ValType> = {
let ty = ret_ty.to_type();
if matches!(ty, Type::Primitive(PType::Unit)) {
vec![]
} else {
vec![ValType::I64]
}
};
let block_type = return_types
.first()
.copied()
.map(wasm_encoder::BlockType::Result)
.unwrap_or(wasm_encoder::BlockType::Empty);
let param_types = Self::indirect_call_param_types(args);
let type_idx = self.get_or_create_call_type(param_types, return_types);
// TODO: This branch is a compatibility workaround for the current
// callable encoding. We should decide direct-function-ref vs closure
// statically during lowering, not by inspecting the runtime value.
self.emit_value_load_typed(closure_ptr, ValType::I64, func);
func.instruction(&W::I64Const(DIRECT_FUNCTION_REF_MAX_EXCLUSIVE));
func.instruction(&W::I64LtU);
func.instruction(&W::If(block_type));
// Raw function values (e.g. functions stored in arrays) are
// represented as direct function-table indices on both MIR and VM.
// They are not heap/linear-memory closures, so call them directly
// without switching closure state.
self.emit_call_args_word(args, func);
self.emit_value_load_typed(closure_ptr, ValType::I64, func);
func.instruction(&W::I32WrapI64);
func.instruction(&W::CallIndirect {
type_index: type_idx,
table_index: 0,
});
func.instruction(&W::Else);
// Closure call via WASM call_indirect through the function table
let memarg = MemArg {
offset: 0,
align: 3,
memory_index: 0,
};
// Compute state size for the callee closure
let state_size = self
.resolve_mir_fn_idx(closure_ptr.as_ref())
.map(|idx| self.get_mir_fn_state_size(idx))
.unwrap_or(64); // conservative default for dynamic calls
// Push closure state onto the state stack
self.emit_closure_state_push(closure_ptr, state_size, func);
// Save current closure_self_ptr to local
func.instruction(&W::I32Const(0)); // CLOSURE_SELF_PTR_ADDR
func.instruction(&W::I64Load(memarg));
func.instruction(&W::LocalSet(self.closure_save_local));
// Set closure_self_ptr to the new closure
func.instruction(&W::I32Const(0)); // CLOSURE_SELF_PTR_ADDR
self.emit_value_load(closure_ptr, func);
func.instruction(&W::I64Store(memarg));
// Push flattened i64 words matching indirect-call adapter ABI.
self.emit_call_args_word(args, func);
// Load function table index from closure[0]
self.emit_value_load(closure_ptr, func);
func.instruction(&W::I32WrapI64);
func.instruction(&W::I64Load(memarg));
func.instruction(&W::I32WrapI64); // table index must be i32
func.instruction(&W::CallIndirect {
type_index: type_idx,
table_index: 0,
});
// Restore the previous closure_self_ptr
func.instruction(&W::I32Const(0)); // CLOSURE_SELF_PTR_ADDR
func.instruction(&W::LocalGet(self.closure_save_local));
func.instruction(&W::I64Store(memarg));
// Pop closure state from the state stack
self.emit_closure_state_pop(func);
func.instruction(&W::End);
// Indirect adapters normalize non-Unit returns to i64.
// Reinterpret back to f64 at numeric call sites.
if !matches!(ret_ty.to_type(), Type::Primitive(PType::Unit))
&& Self::type_to_valtype(&ret_ty.to_type()) == ValType::F64
{
func.instruction(&W::F64ReinterpretI64);
}
}
}
}
// Control flow
I::Return(value, ty) => {
// In WASM, functions implicitly return the value on the stack when they reach 'end'
let is_unit = matches!(ty.to_type(), Type::Primitive(PType::Unit));
// Entry functions restore the alloc pointer before returning.
if self.is_entry_function {
func.instruction(&W::LocalGet(self.alloc_ptr_save_local));
func.instruction(&W::GlobalSet(self.alloc_ptr_global));
}
if !is_unit {
let expected = Self::type_to_valtype(&ty.to_type());
self.emit_value_load_typed(value, expected, func);
}
}
// String constants
I::String(_sym) => {
// String constant - return pointer to string in data section as i64
// TODO: Allocate strings in data section and return address
func.instruction(&W::I64Const(0)); // placeholder pointer
}
// Global variable access
I::GetGlobal(global_ptr, ty) => {
// Load global value from linear memory
let offset = self.get_or_alloc_global_offset(global_ptr);
func.instruction(&W::I32Const(offset as i32));
let memarg = MemArg {
offset: 0,
align: 3,
memory_index: 0,
};
match Self::type_to_valtype(&ty.to_type()) {
ValType::F64 => func.instruction(&W::F64Load(memarg)),
_ => func.instruction(&W::I64Load(memarg)),
};
}
I::SetGlobal(global_ptr, value, ty) => {
// Store value to global's linear memory location
let offset = self.get_or_alloc_global_offset(global_ptr);
let expected_vtype = Self::type_to_valtype(&ty.to_type());
// Check if the value register comes from GetElement (holds a pointer,
// not the value itself). In such cases, dereference the pointer.
let is_getelement = matches!(value.as_ref(), mir::Value::Register(r) if self.getelement_registers.contains_key(r));
func.instruction(&W::I32Const(offset as i32));
if is_getelement {
if ty.word_size() > 1 {
// Multi-word aggregate: GetElement produced a pointer
// to the sub-aggregate in the parent's allocation.
// Store the pointer as-is without dereferencing.
self.emit_value_load(value, func);
} else {
// Scalar element: GetElement produced a pointer to
// where the scalar lives. Dereference to get the value.
self.emit_value_load(value, func);
func.instruction(&W::I32WrapI64);
let deref_memarg = MemArg {
offset: 0,
align: 3,
memory_index: 0,
};
match expected_vtype {
ValType::F64 => func.instruction(&W::F64Load(deref_memarg)),
_ => func.instruction(&W::I64Load(deref_memarg)),
};
}
} else {
let actual_vtype = self.infer_value_type(value);
if actual_vtype == ValType::I64 && expected_vtype == ValType::F64 {
// Value is a pointer (e.g., from alloc), dereference to get f64
self.emit_value_load(value, func);
func.instruction(&W::I32WrapI64);
let deref_memarg = MemArg {
offset: 0,
align: 3,
memory_index: 0,
};
func.instruction(&W::F64Load(deref_memarg));
} else if actual_vtype == ValType::F64 && expected_vtype == ValType::I64 {
// Value is f64 but destination expects i64 - reinterpret bits
self.emit_value_load(value, func);
func.instruction(&W::I64ReinterpretF64);
} else {
self.emit_value_load(value, func);
}
}
let memarg = MemArg {
offset: 0,
align: 3,
memory_index: 0,
};
match expected_vtype {
ValType::F64 => func.instruction(&W::F64Store(memarg)),
_ => func.instruction(&W::I64Store(memarg)),
};
}
// Upvalue access (closure captured variables)
I::GetUpValue(idx, ty) => {
// Load closure_self_ptr from fixed memory location (addr 0)
let memarg = MemArg {
offset: 0,
align: 3,
memory_index: 0,
};
func.instruction(&W::I32Const(0)); // CLOSURE_SELF_PTR_ADDR
func.instruction(&W::I64Load(memarg));
// Add offset: skip fn_index word (8 bytes) + idx * 8
let byte_offset = 8 + (*idx as i64) * 8;
func.instruction(&W::I64Const(byte_offset));
func.instruction(&W::I64Add);
func.instruction(&W::I32WrapI64);
// Load the raw slot value (always i64 in the closure struct)
func.instruction(&W::I64Load(memarg));
// If this upvalue is indirect (alloc pointer), dereference once
// more to reach the actual value stored in the alloc cell.
let is_indirect = self
.indirect_upvalues
.get(&self.current_mir_fn_idx)
.and_then(|v| v.get(*idx as usize))
.copied()
.unwrap_or(false);
if is_indirect {
// The slot holds an alloc cell address; load through it.
func.instruction(&W::I32WrapI64);
func.instruction(&W::I64Load(memarg));
}
// Final type conversion
if Self::type_to_valtype(&ty.to_type()) == ValType::F64 {
func.instruction(&W::F64ReinterpretI64);
}
}
I::SetUpValue(idx, value, ty) => {
// Store to upvalue slot in the current closure.
let memarg = MemArg {
offset: 0,
align: 3,
memory_index: 0,
};
// Check if this upvalue is indirect (alloc pointer).
let is_indirect = self
.indirect_upvalues
.get(&self.current_mir_fn_idx)
.and_then(|v| v.get(*idx as usize))
.copied()
.unwrap_or(false);
// Compute the store target address.
// closure_self_ptr + 8 + idx * 8
func.instruction(&W::I32Const(0)); // CLOSURE_SELF_PTR_ADDR
func.instruction(&W::I64Load(memarg));
let byte_offset = 8 + (*idx as i64) * 8;
func.instruction(&W::I64Const(byte_offset));
func.instruction(&W::I64Add);
func.instruction(&W::I32WrapI64);
if is_indirect {
// The slot holds an alloc cell address; load the pointer,
// then store the value through it.
func.instruction(&W::I64Load(memarg));
func.instruction(&W::I32WrapI64);
}
// Push value (always as i64 for uniform storage)
let expected = Self::type_to_valtype(&ty.to_type());
self.emit_value_load_typed(value, expected, func);
if expected == ValType::F64 {
func.instruction(&W::I64ReinterpretF64);
}
func.instruction(&W::I64Store(memarg));
}
// Closure (old-style, non-heap) - same mechanism as MakeClosure
I::Closure(fn_ptr) => {
// Resolve target MIR function index
let mir_fn_idx = match fn_ptr.as_ref() {
mir::Value::Function(idx) => *idx,
mir::Value::Register(reg_idx) => {
self.register_constants.get(reg_idx).copied().unwrap_or(0) as usize
}
_ => 0,
};
let mir = self.mir.clone();
let upindexes = if mir_fn_idx < mir.functions.len() {
mir.functions[mir_fn_idx].upindexes.clone()
} else {
vec![]
};
let num_upvalues = upindexes.len();
let closure_size_bytes = ((1 + num_upvalues) as u32) * 8;
// Runtime allocation
self.emit_runtime_alloc(closure_size_bytes, func);
// Store function table index
func.instruction(&W::LocalGet(self.alloc_base_local));
func.instruction(&W::I64Const(mir_fn_idx as i64));
func.instruction(&W::I64Store(MemArg {
offset: 0,
align: 3,
memory_index: 0,
}));
// Capture upvalues
for (i, upindex) in upindexes.iter().enumerate() {
let upval_byte_offset = ((1 + i) as u32) * 8;
func.instruction(&W::LocalGet(self.alloc_base_local));
func.instruction(&W::I32Const(upval_byte_offset as i32));
func.instruction(&W::I32Add);
match upindex.as_ref() {
mir::Value::Register(reg_idx)
if self
.alloc_register_indirect
.get(reg_idx)
.copied()
.unwrap_or(false) =>
{
// Single-word alloc: store alloc pointer and dereference on GetUpValue
self.emit_value_load(upindex, func);
}
mir::Value::Register(reg_idx)
if self.alloc_registers.get(reg_idx).copied().unwrap_or(0) > 1 =>
{
// Multi-word alloc (tuple etc.): store pointer as-is
self.emit_value_load(upindex, func);
}
mir::Value::Register(reg_idx)
if self.alloc_registers.contains_key(reg_idx) =>
{
// Single-word direct allocs keep their value in the alloc cell.
// Capture that word rather than the alloc-cell address.
self.emit_value_load(upindex, func);
func.instruction(&W::I32WrapI64);
func.instruction(&W::I64Load(MemArg {
offset: 0,
align: 3,
memory_index: 0,
}));
}
_ => {
let val_type = self.infer_value_type(upindex);
self.emit_value_load(upindex, func);
if val_type == ValType::F64 {
func.instruction(&W::I64ReinterpretF64);
}
}
}
func.instruction(&W::I64Store(MemArg {
offset: 0,
align: 3,
memory_index: 0,
}));
}
// Push closure address as result (i64)
func.instruction(&W::LocalGet(self.alloc_base_local));
func.instruction(&W::I64ExtendI32U);
}
I::CloseUpValues(_src, _ty) => {
// No-op in WASM: upvalues are already in linear memory
}
// CallCls (closure call variant)
I::CallCls(fn_ptr, args, ret_ty) => {
match fn_ptr.as_ref() {
mir::Value::ExtFunction(name, _fn_ty) => {
self.emit_call_args_flattened_for_ext(name, args, func);
if let Some(import_idx) = self.resolve_ext_function(name) {
func.instruction(&W::Call(import_idx));
} else {
return Err(format!(
"Unknown external function in CallCls: {}",
name.as_str()
));
}
}
_ => {
let return_types: Vec<ValType> = {
let ty = ret_ty.to_type();
if matches!(ty, Type::Primitive(PType::Unit)) {
vec![]
} else {
vec![ValType::I64]
}
};
let block_type = return_types
.first()
.copied()
.map(wasm_encoder::BlockType::Result)
.unwrap_or(wasm_encoder::BlockType::Empty);
let param_types = Self::indirect_call_param_types(args);
let type_idx = self.get_or_create_call_type(param_types, return_types);
// TODO: Same as `CallIndirect` above: remove this runtime check once
// direct function refs and closures have distinct lowered forms.
self.emit_value_load_typed(fn_ptr, ValType::I64, func);
func.instruction(&W::I64Const(DIRECT_FUNCTION_REF_MAX_EXCLUSIVE));
func.instruction(&W::I64LtU);
func.instruction(&W::If(block_type));
// Raw function references use the same direct-table representation
// as the VM's indirect-call path. Only heap/linear-memory closures
// need closure-state switching in WASM.
self.emit_call_args_word(args, func);
self.emit_value_load_typed(fn_ptr, ValType::I64, func);
func.instruction(&W::I32WrapI64);
func.instruction(&W::CallIndirect {
type_index: type_idx,
table_index: 0,
});
func.instruction(&W::Else);
// Closure call via WASM call_indirect (same as CallIndirect)
let memarg = MemArg {
offset: 0,
align: 3,
memory_index: 0,
};
// Compute state size for the callee closure
let state_size = self
.resolve_mir_fn_idx(fn_ptr.as_ref())
.map(|idx| self.get_mir_fn_state_size(idx))
.unwrap_or(64); // conservative default
// Push closure state onto the state stack
self.emit_closure_state_push(fn_ptr, state_size, func);
// Save current closure_self_ptr
func.instruction(&W::I32Const(0));
func.instruction(&W::I64Load(memarg));
func.instruction(&W::LocalSet(self.closure_save_local));
// Set closure_self_ptr to the new closure
func.instruction(&W::I32Const(0));
self.emit_value_load(fn_ptr, func);
func.instruction(&W::I64Store(memarg));
// Push flattened i64 words matching indirect-call adapter ABI.
self.emit_call_args_word(args, func);
// Load function table index from closure[0]
self.emit_value_load(fn_ptr, func);
func.instruction(&W::I32WrapI64);
func.instruction(&W::I64Load(memarg));
func.instruction(&W::I32WrapI64);
func.instruction(&W::CallIndirect {
type_index: type_idx,
table_index: 0,
});
// Restore closure_self_ptr
func.instruction(&W::I32Const(0));
func.instruction(&W::LocalGet(self.closure_save_local));
func.instruction(&W::I64Store(memarg));
// Pop closure state from the state stack
self.emit_closure_state_pop(func);
func.instruction(&W::End);
// Indirect adapters normalize non-Unit returns to i64.
// Reinterpret back to f64 at numeric call sites.
if !matches!(ret_ty.to_type(), Type::Primitive(PType::Unit))
&& Self::type_to_valtype(&ret_ty.to_type()) == ValType::F64
{
func.instruction(&W::F64ReinterpretI64);
}
}
}
}
// Placeholder for unimplemented instructions
//
// Tagged union operations
I::TaggedUnionWrap {
tag,
value,
union_type,
} => {
// Store tag and value inline into temp memory, return pointer.
// Layout: [tag: i64] [value_word_0] [value_word_1] ...
let size_bytes = (union_type.word_size() as u32).max(2) * 8;
let temp_addr = self.mem_layout.alloc_offset;
self.mem_layout.alloc_offset += size_bytes;
// Store tag to first word
let memarg = MemArg {
offset: 0,
align: 3,
memory_index: 0,
};
func.instruction(&W::I32Const(temp_addr as i32));
func.instruction(&W::I64Const(*tag as i64));
func.instruction(&W::I64Store(memarg));
// Determine variant payload word size from the union type and tag
let tag_idx = *tag as usize;
let variant_word_size: u32 = match union_type.to_type() {
Type::UserSum { variants, .. } => variants
.get(tag_idx)
.and_then(|(_, payload_ty)| *payload_ty)
.map(|t| t.word_size() as u32)
.unwrap_or(0),
Type::Union(variants) => variants
.get(tag_idx)
.map(|t| t.word_size() as u32)
.unwrap_or(1),
_ => 1,
};
if variant_word_size > 1 {
// Multi-word value: the value register holds a pointer to aggregate data.
// Copy each word inline into the union's value area.
for i in 0..variant_word_size {
func.instruction(&W::I32Const(temp_addr as i32));
self.emit_value_load(value, func);
func.instruction(&W::I32WrapI64);
func.instruction(&W::I64Load(MemArg {
offset: (i * 8) as u64,
align: 3,
memory_index: 0,
}));
func.instruction(&W::I64Store(MemArg {
offset: 8 + (i * 8) as u64,
align: 3,
memory_index: 0,
}));
}
} else {
// Single-word value: store directly
let memarg_val = MemArg {
offset: 8,
align: 3,
memory_index: 0,
};
func.instruction(&W::I32Const(temp_addr as i32));
self.emit_value_load(value, func);
match self.infer_value_type(value) {
ValType::F64 => func.instruction(&W::F64Store(memarg_val)),
_ => func.instruction(&W::I64Store(memarg_val)),
};
}
// Return pointer to the tagged union
func.instruction(&W::I64Const(temp_addr as i64));
}
I::TaggedUnionGetTag(ptr) => {
// Load tag (first word) from tagged union pointer
self.emit_value_load(ptr, func);
func.instruction(&W::I32WrapI64);
let memarg = MemArg {
offset: 0,
align: 3,
memory_index: 0,
};
func.instruction(&W::I64Load(memarg));
}
I::TaggedUnionGetValue(ptr, _ty) => {
// Compute address of value field (ptr + 8), but do NOT load.
// The subsequent I::Load instruction will dereference this address.
self.emit_value_load(ptr, func);
func.instruction(&W::I64Const(8));
func.instruction(&W::I64Add);
}
_ => {
// Unimplemented instructions - no-op
}
}
Ok(())
}
/// Helper: Load a scalar value, dereferencing if the source is a GetElement register.
///
/// GetElement registers hold addresses in linear memory (not the value itself).
/// When a consumer needs the actual value (e.g., BoxLoad needs the HeapIdx),
/// this method dereferences the address to load the value.
fn emit_value_load_deref(
&mut self,
value: &VPtr,
expected: wasm_encoder::ValType,
func: &mut Function,
) {
use wasm_encoder::Instruction as W;
self.emit_value_load(value, func);
if let mir::Value::Register(reg_idx) = value.as_ref() {
if self.getelement_registers.contains_key(reg_idx) {
// GetElement register holds an address; dereference to get the actual value
func.instruction(&W::I32WrapI64);
let memarg = MemArg {
offset: 0,
align: 3,
memory_index: 0,
};
match expected {
wasm_encoder::ValType::F64 => func.instruction(&W::F64Load(memarg)),
_ => func.instruction(&W::I64Load(memarg)),
};
}
}
}
/// Helper: Emit a runtime bump allocation of `size_bytes` bytes.
///
/// Reads the current allocator pointer from the WASM global,
/// saves it to `alloc_base_local`, grows linear memory when needed,
/// bumps the global, and returns the base address in `alloc_base_local`
/// for subsequent use.
///
/// After calling this, use `W::LocalGet(self.alloc_base_local)` to
/// get the i32 base address for memory stores.
fn emit_runtime_alloc(&self, size_bytes: u32, func: &mut Function) {
use wasm_encoder::Instruction as W;
const WASM_PAGE_SHIFT: i32 = 16;
const WASM_PAGE_MASK: i32 = (1 << WASM_PAGE_SHIFT) - 1;
// Save current alloc pointer as allocation base.
func.instruction(&W::GlobalGet(self.alloc_ptr_global));
func.instruction(&W::LocalSet(self.alloc_base_local));
// Compute allocation end pointer and store it in alloc_ptr_save_local
// (used here as a temporary i32 local).
func.instruction(&W::LocalGet(self.alloc_base_local));
func.instruction(&W::I32Const(size_bytes as i32));
func.instruction(&W::I32Add);
func.instruction(&W::LocalSet(self.alloc_ptr_save_local));
// If end > current memory size (bytes), grow memory.
func.instruction(&W::LocalGet(self.alloc_ptr_save_local));
func.instruction(&W::MemorySize(0));
func.instruction(&W::I32Const(WASM_PAGE_SHIFT));
func.instruction(&W::I32Shl);
func.instruction(&W::I32GtU);
func.instruction(&W::If(wasm_encoder::BlockType::Empty));
// pages_needed = ((end - mem_bytes) + (page_size-1)) >> 16
func.instruction(&W::LocalGet(self.alloc_ptr_save_local));
func.instruction(&W::MemorySize(0));
func.instruction(&W::I32Const(WASM_PAGE_SHIFT));
func.instruction(&W::I32Shl);
func.instruction(&W::I32Sub);
func.instruction(&W::I32Const(WASM_PAGE_MASK));
func.instruction(&W::I32Add);
func.instruction(&W::I32Const(WASM_PAGE_SHIFT));
func.instruction(&W::I32ShrU);
func.instruction(&W::MemoryGrow(0));
// memory.grow failure returns -1. Trap explicitly in that case.
func.instruction(&W::I32Const(-1));
func.instruction(&W::I32Eq);
func.instruction(&W::If(wasm_encoder::BlockType::Empty));
func.instruction(&W::Unreachable);
func.instruction(&W::End);
func.instruction(&W::End);
// Commit allocator pointer.
func.instruction(&W::LocalGet(self.alloc_ptr_save_local));
func.instruction(&W::GlobalSet(self.alloc_ptr_global));
}
/// Helper: Emit WASM instructions to load a value onto the stack
fn emit_value_load(&mut self, value: &VPtr, func: &mut Function) {
use mir::Value as V;
use wasm_encoder::Instruction as W;
use wasm_encoder::ValType;
match value.as_ref() {
V::Register(reg_idx) => {
// Map register to correct local variable based on type
// WASM local layout: [args(0..n)] [i64 regs(n..n+32)] [f64 regs(n+32..n+64)]
let reg_type = self
.register_types
.get(reg_idx)
.copied()
.unwrap_or(ValType::I64);
let local_idx = match reg_type {
ValType::I64 => self.current_num_args + *reg_idx as u32,
ValType::F64 => {
self.current_num_args + self.current_num_i64_locals + *reg_idx as u32
}
_ => self.current_num_args + self.current_num_i64_locals + *reg_idx as u32,
};
func.instruction(&W::LocalGet(local_idx));
}
V::Argument(arg_idx) => {
// Use the arg map to find the WASM param index
if let Some(&(param_start, word_count)) =
self.current_arg_map.get(*arg_idx as usize)
{
if word_count <= 1 {
// Single-word arg: just load the param
func.instruction(&W::LocalGet(param_start));
} else {
// Multi-word arg (tuple/record): store all params to temp memory
// and return the pointer so subsequent GetElement/Load can access it
let size_bytes = word_count * 8;
let temp_addr = self.mem_layout.alloc_offset;
self.mem_layout.alloc_offset += size_bytes;
for i in 0..word_count {
let param_idx = param_start + i;
let param_type = self
.current_arg_types
.get(param_idx as usize)
.copied()
.unwrap_or(ValType::I64);
func.instruction(&W::I32Const((temp_addr + i * 8) as i32));
func.instruction(&W::LocalGet(param_idx));
let memarg = MemArg {
offset: 0,
align: 3,
memory_index: 0,
};
match param_type {
ValType::F64 => func.instruction(&W::F64Store(memarg)),
_ => func.instruction(&W::I64Store(memarg)),
};
}
// Push the temp address as the aggregate pointer
func.instruction(&W::I64Const(temp_addr as i64));
}
} else {
// Fallback: assume arg index maps directly
func.instruction(&W::LocalGet(*arg_idx as u32));
}
}
V::Global(_global_val) => {
// Load global variable
// TODO: Implement global variable access
// For now, use I64 placeholder for uniformity
func.instruction(&W::I64Const(0));
}
V::Function(func_idx) => {
// Function index as i64 (matching register type I64)
func.instruction(&W::I64Const(*func_idx as i64));
}
V::ExtFunction(name, _ty) => {
// External function reference - push its import index as i64
if let Some(import_idx) = self.resolve_ext_function(name) {
func.instruction(&W::I64Const(import_idx as i64));
} else {
func.instruction(&W::I64Const(0)); // Unknown ext function
}
}
V::State(_inner) => {
// State reference - placeholder
func.instruction(&W::I64Const(0));
}
V::Constructor(_name, _tag, _ty) => {
// Constructor tag
func.instruction(&W::I64Const(0)); // placeholder
}
V::None => {
// None value - push appropriate zero based on expected type context
// Default to I64 since it's safer (can be reinterpreted as f64 if needed)
func.instruction(&W::I64Const(0));
}
_ => {
// Placeholder for other value types
func.instruction(&W::I64Const(0));
}
}
}
/// Emit WASM instructions to load a value with type coercion.
/// If the value's actual type (I64 pointer from GetElement) differs from the expected
/// type (F64 value), a memory dereference is inserted automatically.
fn emit_value_load_typed(&mut self, value: &VPtr, expected: ValType, func: &mut Function) {
use wasm_encoder::Instruction as W;
let actual = self.infer_value_type(value);
self.emit_value_load(value, func);
if actual == ValType::I64 && expected == ValType::F64 {
// I64 values used where F64 is expected are pointers to memory
// (e.g. GetElement results). Dereference to load the float value.
let memarg = MemArg {
offset: 0,
align: 3,
memory_index: 0,
};
func.instruction(&W::I32WrapI64);
func.instruction(&W::F64Load(memarg));
} else if actual == ValType::F64 && expected == ValType::I64 {
// Value is f64 but an i64 is expected; reinterpret bits
// (preserves float bit pattern for storage in i64 word slots)
func.instruction(&W::I64ReinterpretF64);
}
}
/// Emit call arguments with proper tuple/record flattening.
/// When a MIR argument has a multi-word type (tuple/record), its runtime
/// value is a pointer to linear memory. This method dereferences the pointer
/// and pushes each element onto the WASM operand stack individually,
/// matching the flattened function signature produced by `process_mir_functions`.
fn emit_call_args_flattened(&mut self, args: &[(VPtr, TypeNodeId)], func: &mut Function) {
use wasm_encoder::Instruction as W;
for (arg, ty) in args {
let resolved = ty.to_type();
let flat_types = Self::flatten_type_to_valtypes(&resolved);
if flat_types.len() <= 1 {
// Single-word arg: load with standard type coercion
let expected = flat_types.first().copied().unwrap_or(ValType::I64);
self.emit_value_load_typed(arg, expected, func);
} else {
// Multi-word arg (tuple/record): the runtime value is an i64
// pointer to the data in linear memory. Dereference each
// element individually to match the flattened WASM signature.
for (i, vtype) in flat_types.iter().enumerate() {
self.emit_value_load(arg, func);
func.instruction(&W::I32WrapI64);
let load_memarg = MemArg {
offset: (i * 8) as u64,
align: 3,
memory_index: 0,
};
match vtype {
ValType::F64 => func.instruction(&W::F64Load(load_memarg)),
_ => func.instruction(&W::I64Load(load_memarg)),
};
}
}
}
}
/// Emit direct-call arguments using the callee's inferred parameter ABI.
fn emit_call_args_for_callee(
&mut self,
args: &[(VPtr, TypeNodeId)],
callee_fn_idx: usize,
func: &mut Function,
) {
use wasm_encoder::Instruction as W;
let Some(callee) = self.mir.functions.get(callee_fn_idx) else {
self.emit_call_args_flattened(args, func);
return;
};
let inferred_arg_types = Self::infer_argument_types(callee);
let callee_expected_flats: Vec<Vec<ValType>> = callee
.args
.iter()
.enumerate()
.map(|(arg_idx, callee_arg)| {
let mut flat = Self::flatten_type_to_valtypes(&callee_arg.1.to_type());
if let Some(inferred) = inferred_arg_types.get(&arg_idx) {
if inferred.len() > flat.len() {
flat = inferred.clone();
} else if flat.len() == 1
&& inferred.len() == 1
&& flat[0] != inferred[0]
&& Self::allows_scalar_inference_override(&callee_arg.1.to_type())
{
flat[0] = inferred[0];
}
}
flat
})
.collect();
for (arg_idx, (arg, arg_ty)) in args.iter().enumerate() {
let expected_flat = callee_expected_flats
.get(arg_idx)
.cloned()
.unwrap_or_else(|| Self::flatten_type_to_valtypes(&arg_ty.to_type()));
if expected_flat.len() <= 1 {
let expected = expected_flat.first().copied().unwrap_or(ValType::I64);
self.emit_value_load_typed(arg, expected, func);
} else {
let actual_vtype = self.infer_value_type(arg);
for (i, vtype) in expected_flat.iter().enumerate() {
if actual_vtype == ValType::I64 {
self.emit_value_load(arg, func);
func.instruction(&W::I32WrapI64);
let load_memarg = MemArg {
offset: (i * 8) as u64,
align: 3,
memory_index: 0,
};
match vtype {
ValType::F64 => func.instruction(&W::F64Load(load_memarg)),
_ => func.instruction(&W::I64Load(load_memarg)),
};
} else {
// Scalar actual value used where callee expects a multi-word aggregate.
// Duplicate/coerce the scalar per expected slot to keep ABI consistent.
self.emit_value_load_typed(arg, *vtype, func);
}
}
}
}
}
/// Emit call arguments for external functions with per-function ABI overrides.
fn emit_call_args_flattened_for_ext(
&mut self,
ext_name: &Symbol,
args: &[(VPtr, TypeNodeId)],
func: &mut Function,
) {
use wasm_encoder::Instruction as W;
for (arg_idx, (arg, ty)) in args.iter().enumerate() {
let resolved = ty.to_type();
let flat_types = Self::flatten_type_to_valtypes(&resolved);
if flat_types.len() <= 1 {
let mut expected = flat_types.first().copied().unwrap_or(ValType::I64);
if ((ext_name.as_str() == "prepend"
|| ext_name
.as_str()
.strip_prefix("prepend$arity")
.and_then(|n| n.parse::<usize>().ok())
.is_some())
&& arg_idx == 0)
|| ((ext_name.as_str() == "append"
|| ext_name
.as_str()
.strip_prefix("append$arity")
.and_then(|n| n.parse::<usize>().ok())
.is_some())
&& arg_idx == 1)
{
expected = ValType::I64;
}
// Scheduler ABI: second arg is closure pointer word.
if ext_name.as_str() == "_mimium_schedule_at" && arg_idx == 1 {
expected = ValType::I64;
}
if ext_name.as_str() == "__probe_value_intercept$arity1" {
expected = ValType::F64;
}
self.emit_value_load_typed(arg, expected, func);
} else {
// prepend/prepend$arityN and append/append$arityN take aggregate element
// arguments as packed i64 words (tuple pointer/handle), not flattened fields.
if ((ext_name.as_str() == "prepend"
|| ext_name
.as_str()
.strip_prefix("prepend$arity")
.and_then(|n| n.parse::<usize>().ok())
.is_some())
&& arg_idx == 0)
|| ((ext_name.as_str() == "append"
|| ext_name
.as_str()
.strip_prefix("append$arity")
.and_then(|n| n.parse::<usize>().ok())
.is_some())
&& arg_idx == 1)
{
self.emit_value_load_typed(arg, ValType::I64, func);
continue;
}
for (i, vtype) in flat_types.iter().enumerate() {
self.emit_value_load(arg, func);
func.instruction(&W::I32WrapI64);
let load_memarg = MemArg {
offset: (i * 8) as u64,
align: 3,
memory_index: 0,
};
match vtype {
ValType::F64 => func.instruction(&W::F64Load(load_memarg)),
_ => func.instruction(&W::I64Load(load_memarg)),
};
}
}
}
}
/// Emit call arguments as raw i64 words for indirect-call ABI.
///
/// - Scalar f64 values are reinterpreted to i64 bit patterns.
/// - Scalar i64 values are passed as-is.
/// - Multi-word aggregate args are flattened to per-word i64 loads.
fn emit_call_args_word(&mut self, args: &[(VPtr, TypeNodeId)], func: &mut Function) {
use wasm_encoder::Instruction as W;
for (arg, ty) in args {
let resolved = ty.to_type();
let flat_types = Self::flatten_type_to_valtypes(&resolved);
if flat_types.len() <= 1 {
let expected = flat_types.first().copied().unwrap_or(ValType::I64);
self.emit_value_load_typed(arg, expected, func);
if expected == ValType::F64 {
func.instruction(&W::I64ReinterpretF64);
}
} else {
for i in 0..flat_types.len() {
self.emit_value_load(arg, func);
func.instruction(&W::I32WrapI64);
let load_memarg = MemArg {
offset: (i * 8) as u64,
align: 3,
memory_index: 0,
};
func.instruction(&W::I64Load(load_memarg));
}
}
}
}
/// Build indirect-call parameter ABI from MIR argument types.
///
/// Indirect adapters use an i64-word ABI, so tuple/record arguments
/// contribute one parameter per flattened word.
fn indirect_call_param_types(args: &[(VPtr, TypeNodeId)]) -> Vec<ValType> {
args.iter()
.flat_map(|(_, ty)| {
let word_count = Self::flatten_type_to_valtypes(&ty.to_type()).len().max(1);
std::iter::repeat_n(ValType::I64, word_count)
})
.collect()
}
/// Load a value and convert to i64 using numeric truncation (not bit reinterpretation).
/// Use this for values that represent numeric indices (array indices, etc.)
/// where f64 1.0 should become i64 1, not i64 0x3FF0000000000000.
fn emit_value_load_as_numeric_i64(&mut self, value: &VPtr, func: &mut Function) {
use wasm_encoder::Instruction as W;
let actual = self.infer_value_type(value);
self.emit_value_load(value, func);
if actual == ValType::F64 {
func.instruction(&W::I64TruncSatF64S);
}
}
/// Infer the WASM ValType of a MIR value.
/// Used to select the correct comparison instruction (F64 vs I64).
fn infer_value_type(&self, value: &VPtr) -> ValType {
match value.as_ref() {
mir::Value::Register(reg_idx) => self
.register_types
.get(reg_idx)
.copied()
.unwrap_or(ValType::I64),
mir::Value::Argument(arg_idx) => {
// Look up actual argument type from the current function's arg map.
// For multi-word args (tuples), the materialized value is a pointer (I64).
if let Some(&(param_start, word_count)) = self.current_arg_map.get(*arg_idx) {
if word_count > 1 {
ValType::I64 // Multi-word arg is materialized as a pointer
} else {
self.current_arg_types
.get(param_start as usize)
.copied()
.unwrap_or(ValType::I64)
}
} else {
ValType::I64
}
}
mir::Value::Function(_) | mir::Value::ExtFunction(_, _) => ValType::I64,
// None, State, Global, Constructor all push I64 in emit_value_load,
// so infer_value_type must be consistent and return I64.
mir::Value::None
| mir::Value::State(_)
| mir::Value::Global(_)
| mir::Value::Constructor(_, _, _) => ValType::I64,
}
}
/// Decide whether `Alloc(ty)` should be captured indirectly in closure slots.
///
/// Primitive scalar cells are captured indirectly so closures share mutable
/// storage. Aggregate values are kept as direct pointers even when their
/// word size is one (e.g. single-field records).
fn alloc_capture_should_be_indirect(ty: &Type) -> bool {
match ty {
Type::Primitive(PType::Numeric) | Type::Primitive(PType::Int) => true,
Type::Function { .. } => true,
Type::Intermediate(cell) => {
let tv = cell.read().unwrap();
tv.parent
.as_ref()
.map(|parent| Self::alloc_capture_should_be_indirect(&parent.to_type()))
.unwrap_or(true)
}
_ => false,
}
}
/// Build the final WASM module
fn build_module(&self) -> Module {
const MAX_MEMORY_PAGES: u64 = 65_536; // 4GiB on wasm32 linear memory
let mut module = Module::new();
let initial_memory_pages = self.required_initial_memory_pages();
let mut memory_section = MemorySection::new();
memory_section.memory(MemoryType {
minimum: initial_memory_pages,
maximum: Some(MAX_MEMORY_PAGES),
memory64: false,
shared: false,
page_size_log2: None,
});
// Add all sections in proper order
module.section(&self.type_section);
module.section(&self.import_section);
module.section(&self.function_section);
module.section(&self.table_section);
module.section(&memory_section);
module.section(&self.global_section);
module.section(&self.export_section);
module.section(&self.element_section);
module.section(&self.code_section);
module.section(&self.data_section);
let name_section = self.build_name_section();
module.section(&name_section);
module
}
fn build_name_section(&self) -> NameSection {
let mut name_section = NameSection::new();
let mut function_names = NameMap::new();
let mut pairs = self
.fn_name_to_idx
.iter()
.map(|(name, idx)| (*idx, name.as_str().to_string()))
.collect::<Vec<_>>();
pairs.sort_by_key(|(idx, _)| *idx);
pairs.into_iter().for_each(|(idx, name)| {
function_names.append(idx, &name);
});
name_section.functions(&function_names);
name_section
}
/// Compute the minimum initial number of linear-memory pages needed.
///
/// Includes runtime headroom beyond the compile-time allocation high-water
/// mark so temporary per-sample allocations (e.g. closure/probe paths)
/// do not immediately hit out-of-bounds.
fn required_initial_memory_pages(&self) -> u64 {
const WASM_PAGE_BYTES: u32 = 64 * 1024;
const RUNTIME_ALLOC_HEADROOM_BYTES: u32 = 4 * 1024 * 1024; // 4 MiB
const MIN_INITIAL_PAGES: u32 = 64; // 4 MiB
let bytes_needed = self
.mem_layout
.alloc_offset
.saturating_add(RUNTIME_ALLOC_HEADROOM_BYTES);
let pages = bytes_needed.div_ceil(WASM_PAGE_BYTES);
pages.max(MIN_INITIAL_PAGES) as u64
}
/// Helper: Get or allocate a register for a MIR value
#[allow(dead_code)]
fn get_or_alloc_register(&mut self, value: &Arc<mir::Value>) -> u32 {
if let Some(®) = self.registers.get(value) {
reg
} else {
let reg = self.registers.len() as u32;
self.registers.insert(value.clone(), reg);
reg
}
}
/// Resolve an external function name to a WASM import index.
/// Returns None for unknown external functions.
fn resolve_ext_function(&self, name: &Symbol) -> Option<u32> {
let name_str = name.as_str();
if name_str
.strip_prefix("split_head$arity")
.and_then(|n| n.parse::<usize>().ok())
.and_then(|arity| self.rt.builtin_split_head_specialized.get(&arity).copied())
.is_some()
{
return name_str
.strip_prefix("split_head$arity")
.and_then(|n| n.parse::<usize>().ok())
.and_then(|arity| self.rt.builtin_split_head_specialized.get(&arity).copied());
}
if name_str
.strip_prefix("split_tail$arity")
.and_then(|n| n.parse::<usize>().ok())
.and_then(|arity| self.rt.builtin_split_tail_specialized.get(&arity).copied())
.is_some()
{
return name_str
.strip_prefix("split_tail$arity")
.and_then(|n| n.parse::<usize>().ok())
.and_then(|arity| self.rt.builtin_split_tail_specialized.get(&arity).copied());
}
if name_str
.strip_prefix("prepend$arity")
.and_then(|n| n.parse::<usize>().ok())
.and_then(|arity| self.rt.builtin_prepend_specialized.get(&arity).copied())
.is_some()
{
return name_str
.strip_prefix("prepend$arity")
.and_then(|n| n.parse::<usize>().ok())
.and_then(|arity| self.rt.builtin_prepend_specialized.get(&arity).copied());
}
if name_str
.strip_prefix("append$arity")
.and_then(|n| n.parse::<usize>().ok())
.and_then(|arity| self.rt.builtin_append_specialized.get(&arity).copied())
.is_some()
{
return name_str
.strip_prefix("append$arity")
.and_then(|n| n.parse::<usize>().ok())
.and_then(|arity| self.rt.builtin_append_specialized.get(&arity).copied());
}
match name.as_str() {
"_mimium_getsamplerate" => Some(self.rt.runtime_get_samplerate),
"_mimium_getnow" => Some(self.rt.runtime_get_now),
"probeln" => Some(self.rt.builtin_probeln),
"probe" => Some(self.rt.builtin_probe),
"len" => Some(self.rt.builtin_length_array),
"split_head" => Some(self.rt.builtin_split_head),
"split_tail" => Some(self.rt.builtin_split_tail),
"prepend" => Some(self.rt.builtin_prepend),
"append" => Some(self.rt.builtin_append),
"sin" => Some(self.rt.math_sin),
"cos" => Some(self.rt.math_cos),
"tan" => Some(self.rt.math_tan),
"sinh" => Some(self.rt.math_sinh),
"cosh" => Some(self.rt.math_cosh),
"tanh" => Some(self.rt.math_tanh),
"asin" => Some(self.rt.math_asin),
"acos" => Some(self.rt.math_acos),
"atan" => Some(self.rt.math_atan),
"round" => Some(self.rt.math_round),
"floor" => Some(self.rt.math_floor),
"ceil" => Some(self.rt.math_ceil),
"atan2" => Some(self.rt.math_atan2),
"pow" => Some(self.rt.math_pow),
"log" => Some(self.rt.math_log),
"min" => Some(self.rt.math_min),
"max" => Some(self.rt.math_max),
_ => {
// Check plugin functions
self.plugin_fns.functions.get(name).copied()
}
}
}
/// Compute the state storage size (in words) for a MIR function.
/// This is used to allocate per-closure state storage when emitting closure calls.
fn get_mir_fn_state_size(&self, mir_fn_idx: usize) -> u64 {
if mir_fn_idx < self.mir.functions.len() {
self.mir.functions[mir_fn_idx].state_skeleton.total_size()
} else {
0
}
}
/// Resolve MIR function index from a closure pointer value.
/// Returns the MIR function index if resolvable at compile time, None otherwise.
fn resolve_mir_fn_idx(&self, fn_ptr: &mir::Value) -> Option<usize> {
match fn_ptr {
mir::Value::Function(idx) => Some(*idx),
mir::Value::Register(vreg) => self.register_constants.get(vreg).map(|&v| v as usize),
_ => None,
}
}
/// Emit closure_state_push host function call.
/// Pushes the closure's state onto the state stack before calling it.
fn emit_closure_state_push(
&mut self,
closure_ptr: &VPtr,
state_size: u64,
func: &mut Function,
) {
use wasm_encoder::Instruction as W;
// Push closure address (i64) and state size (i64)
self.emit_value_load(closure_ptr, func);
func.instruction(&W::I64Const(state_size as i64));
func.instruction(&W::Call(self.rt.closure_state_push));
}
/// Emit closure_state_pop host function call.
/// Pops the closure's state from the state stack after the call returns.
fn emit_closure_state_pop(&self, func: &mut Function) {
use wasm_encoder::Instruction as W;
func.instruction(&W::Call(self.rt.closure_state_pop));
}
/// Generate an exported WASM trampoline function `_mimium_exec_closure_void`.
///
/// This function takes a single `i64` argument (the closure address in
/// linear memory) and executes it as a `() -> ()` closure via
/// `call_indirect`. The host scheduler calls this to fire scheduled
/// tasks without needing to replicate the closure-call protocol on the
/// host side.
///
/// Generated WASM (pseudo):
/// ```wasm
/// (func $_mimium_exec_closure_void (param $closure_addr i64)
/// ;; closure_state_push(closure_addr, 64)
/// ;; save old self-ptr, set new self-ptr = closure_addr
/// ;; load fn_table_idx = mem[closure_addr as i32]
/// ;; call_indirect [] -> [] (type () -> ())
/// ;; restore old self-ptr
/// ;; closure_state_pop()
/// )
/// ```
fn generate_exec_closure_trampoline(&mut self) {
use wasm_encoder::Instruction as W;
let memarg = wasm_encoder::MemArg {
offset: 0,
align: 3,
memory_index: 0,
};
// 1. Declare the function type: (i64) -> ()
let type_idx = self.type_section.len();
self.type_section.ty().function(vec![ValType::I64], vec![]);
// 2. Add to function section
self.function_section.function(type_idx);
let fn_idx = self.current_fn_idx;
self.current_fn_idx += 1;
// 3. Build function body
// Locals: local 0 = param (closure_addr: i64)
// local 1 = saved_self_ptr (i64)
// local 2 = saved_alloc_ptr (i32)
let mut func = Function::new([(1, ValType::I64), (1, ValType::I32)]);
let param_closure_addr: u32 = 0;
let local_saved_self_ptr: u32 = 1;
let local_saved_alloc_ptr: u32 = 2;
// Save alloc pointer so that temporary Alloc instructions inside
// the scheduled closure do not cause unbounded memory growth.
func.instruction(&W::GlobalGet(self.alloc_ptr_global));
func.instruction(&W::LocalSet(local_saved_alloc_ptr));
// closure_state_push(closure_addr, 64)
// 64 is a conservative default state size for dynamically dispatched closures
func.instruction(&W::LocalGet(param_closure_addr));
func.instruction(&W::I64Const(64));
func.instruction(&W::Call(self.rt.closure_state_push));
// Save current closure_self_ptr (at memory address 0) to local
func.instruction(&W::I32Const(0));
func.instruction(&W::I64Load(memarg));
func.instruction(&W::LocalSet(local_saved_self_ptr));
// Set closure_self_ptr = closure_addr
func.instruction(&W::I32Const(0));
func.instruction(&W::LocalGet(param_closure_addr));
func.instruction(&W::I64Store(memarg));
// Load fn_table_idx from closure[0]: i64 at closure_addr
func.instruction(&W::LocalGet(param_closure_addr));
func.instruction(&W::I32WrapI64);
func.instruction(&W::I64Load(memarg));
func.instruction(&W::I32WrapI64); // table index is i32
// call_indirect with type () -> ()
// In mimium's WASM codegen, Unit return types produce no WASM results
// (the return is stripped in process_mir_functions), so the scheduled
// `() -> ()` closures truly have WASM type `() -> ()`.
let void_void_type = self.get_or_create_call_type(vec![], vec![]);
func.instruction(&W::CallIndirect {
type_index: void_void_type,
table_index: 0,
});
// Restore the previous closure_self_ptr
func.instruction(&W::I32Const(0));
func.instruction(&W::LocalGet(local_saved_self_ptr));
func.instruction(&W::I64Store(memarg));
// Restore alloc pointer — reclaim temporary allocations made by
// the scheduled closure body.
func.instruction(&W::LocalGet(local_saved_alloc_ptr));
func.instruction(&W::GlobalSet(self.alloc_ptr_global));
// closure_state_pop()
func.instruction(&W::Call(self.rt.closure_state_pop));
func.instruction(&W::End);
self.code_section.function(&func);
// 4. Export with canonical name
self.export_section.export(
"_mimium_exec_closure_void",
wasm_encoder::ExportKind::Func,
fn_idx,
);
}
/// Allocate a linear memory offset for a global variable, or return existing one.
fn get_or_alloc_global_offset(&mut self, global: &VPtr) -> u32 {
self.mem_layout.get_or_alloc_global_offset(global)
}
/// Helper: Map mimium type to WASM ValType
///
/// WASM locals are partitioned into two pools: I64 and F64.
/// All non-float types (pointers, integers, function refs, etc.) map to I64,
/// matching the VM's uniform Word (u64) representation.
#[allow(dead_code)]
fn type_to_valtype(ty: &Type) -> ValType {
match ty {
Type::Primitive(PType::Numeric) => ValType::F64,
Type::Primitive(PType::Int) => ValType::I64,
Type::Primitive(PType::String) => ValType::I64, // pointer to string in linear memory
Type::Primitive(PType::Unit) => ValType::I64, // zero-sized, but use i64 for uniformity
Type::Function { .. } => ValType::I64, // function reference (index as i64)
Type::Record(fields) if fields.len() == 1 => {
// Single-field record: unwrap to field type
Self::type_to_valtype(&fields[0].ty.to_type())
}
Type::Tuple(elems) if elems.len() == 1 => {
// Single-element tuple: unwrap to element type
Self::type_to_valtype(&elems[0].to_type())
}
Type::Tuple(_) | Type::Record(_) => ValType::I64, // pointer to aggregate
Type::Array(_) => ValType::I64, // array reference
Type::Union(_) | Type::UserSum { .. } => ValType::I64, // sum type tag + payload
Type::Ref(_) => ValType::I64, // pointer reference
Type::Boxed(_) => ValType::I64, // heap pointer
Type::Code(_) => ValType::I64, // code reference
// Intermediate type variable: try to resolve through the parent chain
Type::Intermediate(cell) => {
let tv = cell.read().unwrap();
if let Some(parent) = &tv.parent {
Self::type_to_valtype(&parent.to_type())
} else {
// Unresolved type variable defaults to pointer-safe word type.
ValType::I64
}
}
// Unknown/Any/Failure/TypeAlias/TypeScheme: not fully resolved.
// Default to I64 so unresolved values are treated as word/pointer safely.
_ => ValType::I64,
}
}
/// Helper: Calculate size of a type in words
#[allow(dead_code)]
fn type_size(_ty: &Type) -> WordSize {
// TODO: Implement proper type size calculation
1
}
/// Flatten a type into individual WASM ValTypes for function parameter expansion.
/// Tuple and record types are recursively expanded into per-element types,
/// matching the MIR calling convention where tuple args are passed as separate words.
fn flatten_type_to_valtypes(ty: &Type) -> Vec<ValType> {
match ty {
Type::Primitive(PType::Numeric) => vec![ValType::F64],
Type::Primitive(PType::Int) => vec![ValType::I64],
Type::Primitive(PType::Unit) => vec![],
// Resolve Intermediate type variables before flattening
Type::Intermediate(cell) => {
let tv = cell.read().unwrap();
if let Some(parent) = &tv.parent {
Self::flatten_type_to_valtypes(&parent.to_type())
} else {
vec![ValType::I64]
}
}
Type::Tuple(elems) if elems.len() == 1 => {
Self::flatten_type_to_valtypes(&elems[0].to_type())
}
Type::Tuple(elems) => elems
.iter()
.flat_map(|e| Self::flatten_type_to_valtypes(&e.to_type()))
.collect(),
Type::Record(fields) if fields.len() == 1 => {
Self::flatten_type_to_valtypes(&fields[0].ty.to_type())
}
Type::Record(fields) => fields
.iter()
.flat_map(|f| Self::flatten_type_to_valtypes(&f.ty.to_type()))
.collect(),
_ => vec![Self::type_to_valtype(ty)],
}
}
fn allows_scalar_inference_override(ty: &Type) -> bool {
match ty {
Type::Unknown
| Type::Any
| Type::Failure
| Type::TypeAlias(_)
| Type::TypeScheme(_) => true,
Type::Intermediate(_) => true,
Type::Tuple(elems) if elems.len() == 1 => {
Self::allows_scalar_inference_override(&elems[0].to_type())
}
Type::Record(fields) if fields.len() == 1 => {
Self::allows_scalar_inference_override(&fields[0].ty.to_type())
}
_ => false,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::interner::ToSymbol;
use crate::test_utils::{compile_to_mir, repo_test_artifact_path, run_wasm_dsp_f64};
#[test]
fn test_wasmgen_create() {
let mir = Arc::new(Mir::default());
let generator = WasmGenerator::new_without_plugins(mir);
// Verify runtime primitive imports are set up
assert!(generator.current_fn_idx > 20); // At least 25 runtime functions imported
assert!(generator.rt.heap_alloc < generator.current_fn_idx);
assert!(generator.rt.array_alloc < generator.current_fn_idx);
assert!(generator.rt.state_push < generator.current_fn_idx);
}
#[test]
fn test_wasmgen_generate_empty() {
let mir = Arc::new(Mir::default());
let mut generator = WasmGenerator::new_without_plugins(mir);
let result = generator.generate();
assert!(
result.is_ok(),
"Should generate valid WASM module for empty MIR"
);
let wasm_bytes = result.unwrap();
assert!(!wasm_bytes.is_empty(), "WASM module should not be empty");
// Basic WASM module header check
assert_eq!(&wasm_bytes[0..4], &[0x00, 0x61, 0x73, 0x6d]); // "\0asm" magic
assert_eq!(&wasm_bytes[4..8], &[0x01, 0x00, 0x00, 0x00]); // version 1
}
/// Test that Return instructions don't store to destination register
/// This was a bug where MIR generates `reg(dest) := ret value`, causing
/// wasmgen to load the return value onto the stack and then store it to
/// a destination register, leaving the stack empty when the function End
/// instruction expected a return value.
///
/// Fix: Check if instruction is Return or ReturnFeed and skip destination
/// handling in translate_instruction_with_dest().
#[test]
fn test_wasmgen_simple_return() {
let src = "fn dsp() -> float { 0.5 }";
let mir = compile_to_mir(src);
let mut generator = WasmGenerator::new_without_plugins(mir);
let wasm_bytes = generator.generate().expect("WASM generation failed");
// Write to tracked testdata directory for inspection
let wasm_path = repo_test_artifact_path("test_simple_return_from_test.wasm");
std::fs::write(&wasm_path, &wasm_bytes).expect("Failed to write WASM file");
eprintln!(
"Generated WASM file: {:?} ({} bytes)",
wasm_path,
wasm_bytes.len()
);
// Validate with wasmtime - this was failing before the fix
let engine = wasmtime::Engine::default();
let result = wasmtime::Module::new(&engine, &wasm_bytes);
assert!(
result.is_ok(),
"WASM validation should pass for simple return function. Error: {:?}",
result.err()
);
}
#[test]
fn test_wasmgen_unknown_external_function_errors() {
let src = "fn dsp() -> float { probeln(0.0) }";
let mir = compile_to_mir(src);
let mut mir = (*mir).clone();
let unknown_name = "__unknown_ext_for_test".to_symbol();
let patched = mir
.functions
.iter_mut()
.flat_map(|func| func.body.iter_mut())
.flat_map(|block| block.0.iter_mut())
.find_map(|(_, instr)| match instr {
mir::Instruction::Call(fn_ptr, _, _)
| mir::Instruction::CallIndirect(fn_ptr, _, _)
| mir::Instruction::CallCls(fn_ptr, _, _) => {
if let mir::Value::ExtFunction(_, fn_ty) = fn_ptr.as_ref() {
*fn_ptr = Arc::new(mir::Value::ExtFunction(unknown_name, *fn_ty));
Some(())
} else {
None
}
}
_ => None,
})
.is_some();
assert!(
patched,
"Failed to patch MIR with unknown external function"
);
let mut generator = WasmGenerator::new_without_plugins(Arc::new(mir));
let err = generator
.generate()
.expect_err("WASM generation should fail for unknown external function");
assert!(
err.contains("Unknown external function"),
"Error should mention unknown external function, got: {err}"
);
assert!(
err.contains("__unknown_ext_for_test"),
"Error should include unresolved function name, got: {err}"
);
}
#[test]
fn test_wasmgen_function_call() {
let src = r#"
fn helper(x: float) -> float { x * 2.0 }
fn dsp() -> float { helper(21.0) }
"#;
let mir = compile_to_mir(src);
let mut generator = WasmGenerator::new_without_plugins(mir);
let wasm_bytes = generator.generate().expect("WASM generation failed");
// Write to tracked testdata directory for inspection
let wasm_path = repo_test_artifact_path("test_function_call_from_test.wasm");
std::fs::write(&wasm_path, &wasm_bytes).expect("Failed to write WASM file");
eprintln!(
"Generated function call WASM: {:?} ({} bytes)",
wasm_path,
wasm_bytes.len()
);
// Validate with wasmtime
let engine = wasmtime::Engine::default();
let result = wasmtime::Module::new(&engine, &wasm_bytes);
assert!(
result.is_ok(),
"WASM validation should pass for function call. Error: {:?}",
result.err()
);
}
#[test]
fn test_wasmgen_regenerate_test_file() {
let src = r#"
fn dsp() -> float {
42.0
}
"#;
let mir = compile_to_mir(src);
let mut generator = WasmGenerator::new_without_plugins(mir);
let wasm_bytes = generator.generate().expect("WASM generation failed");
// Write to tracked testdata directory for inspection
let wasm_path = repo_test_artifact_path("test_integration.wasm");
std::fs::write(&wasm_path, &wasm_bytes).expect("Failed to write WASM file");
eprintln!(
"Generated WASM file: {:?} ({} bytes)",
wasm_path,
wasm_bytes.len()
);
}
/// Helper: Compile source to WASM and validate with wasmtime
fn compile_and_validate(src: &str, test_name: &str) -> Vec<u8> {
let mir = compile_to_mir(src);
let mut generator = WasmGenerator::new_without_plugins(mir);
let wasm_bytes = generator.generate().expect("WASM generation failed");
// Write to tracked testdata directory for inspection
let wasm_path = repo_test_artifact_path(&format!("{test_name}.wasm"));
std::fs::write(&wasm_path, &wasm_bytes).expect("Failed to write WASM file");
let engine = wasmtime::Engine::default();
let result = wasmtime::Module::new(&engine, &wasm_bytes);
assert!(
result.is_ok(),
"[{test_name}] WASM validation failed: {:?}",
result.err()
);
wasm_bytes
}
/// Test arithmetic chain: multiple operations on floats
#[test]
fn test_wasmgen_arithmetic_chain() {
let src = r#"
fn dsp() -> float {
let x = 3.0;
let y = x + 1.0;
let z = y * 2.0 - x;
z / 2.0
}
"#;
compile_and_validate(src, "test_arithmetic_chain");
}
/// Test nested function calls
#[test]
fn test_wasmgen_nested_calls() {
let src = r#"
fn double(x: float) -> float { x * 2.0 }
fn add_one(x: float) -> float { x + 1.0 }
fn dsp() -> float { add_one(double(10.0)) }
"#;
compile_and_validate(src, "test_nested_calls");
}
/// Test multi-argument function
#[test]
fn test_wasmgen_multi_arg() {
let src = r#"
fn lerp(a: float, b: float, t: float) -> float {
a + (b - a) * t
}
fn dsp() -> float { lerp(0.0, 10.0, 0.5) }
"#;
compile_and_validate(src, "test_multi_arg");
}
/// Test function returning expression with negation
#[test]
fn test_wasmgen_negation() {
let src = r#"
fn neg(x: float) -> float { -x }
fn dsp() -> float { neg(42.0) }
"#;
compile_and_validate(src, "test_negation");
}
/// Test conditional (if/else) expression with JmpIf/Phi
#[test]
fn test_wasmgen_conditional() {
let src = r#"
fn abs_val(x: float) -> float {
if (x < 0.0) {
0.0 - x
} else {
x
}
}
fn dsp() -> float { abs_val(0.0 - 42.0) }
"#;
compile_and_validate(src, "test_conditional");
}
/// Test let bindings with intermediate computations
#[test]
fn test_wasmgen_let_bindings() {
let src = r#"
fn clamp(x: float, lo: float, hi: float) -> float {
let v = if (x < lo) { lo } else { x };
if (v > hi) { hi } else { v }
}
fn dsp() -> float { clamp(1.5, 0.0, 1.0) }
"#;
compile_and_validate(src, "test_let_bindings");
}
/// Test stateful function (counter using `self`)
/// MIR pattern: GetState -> Load -> compute -> ReturnFeed
#[test]
fn test_wasmgen_stateful_counter() {
let src = r#"
fn counter() -> float {
self + 1.0
}
"#;
compile_and_validate(src, "test_stateful_counter");
}
/// Test external function call: samplerate
/// MIR pattern: call_indirect extfun _mimium_getsamplerate
#[test]
fn test_wasmgen_samplerate_call() {
let src = r#"
fn get_sr() -> float {
samplerate
}
"#;
compile_and_validate(src, "test_samplerate_call");
}
/// Test external function call: now
#[test]
fn test_wasmgen_now_call() {
let src = r#"
fn get_time() -> float {
now
}
"#;
compile_and_validate(src, "test_now_call");
}
/// Test stateful phasor function (phase accumulator with samplerate)
#[test]
fn test_wasmgen_phasor() {
let src = r#"
fn phasor(freq: float) -> float {
(self + freq / samplerate) % 1.0
}
"#;
compile_and_validate(src, "test_phasor");
}
/// Test full sinewave DSP pipeline
#[test]
fn test_wasmgen_sinewave() {
let src = r#"
fn phasor(freq: float) -> float {
(self + freq / samplerate) % 1.0
}
fn dsp() -> float {
sin(phasor(440.0) * 3.14159265 * 2.0) * 0.5
}
"#;
compile_and_validate(src, "test_sinewave");
}
#[test]
fn test_wasmgen_hyperbolic_functions() {
let src = r#"
fn dsp() -> float {
sinh(0.5) + cosh(0.25) + tanh(0.75)
}
"#;
compile_and_validate(src, "test_hyperbolic_functions");
}
/// Test global variable (let binding at top level)
#[test]
fn test_wasmgen_global_variable() {
let src = r#"
let PI = 3.14159265
fn dsp() -> float {
sin(440.0 * PI * 2.0)
}
"#;
compile_and_validate(src, "test_global_variable");
}
/// Test global variable used through function call
#[test]
fn test_wasmgen_global_in_function() {
let src = r#"
let GAIN = 0.5
fn apply_gain(x: float) -> float { x * GAIN }
fn dsp() -> float { apply_gain(1.0) }
"#;
compile_and_validate(src, "test_global_in_function");
}
#[test]
fn test_wasmgen_regression_nested_array_split_head_wasm_execution() {
let src = r#"
fn f(arrs){
let (head, rest) = split_head(arrs)
if len(rest) > 0 {
let (head2, rest2) = split_head(rest)
len(head) + len(head2) + len(rest2)
} else {
len(head)
}
}
fn dsp(){
f([[1.0, 2.0], [3.0, 4.0]])
}
"#;
let value = run_wasm_dsp_f64(
src,
Some(repo_test_artifact_path(
"nested_array_split_head_regression.mmm",
)),
);
assert_eq!(value, 4.0);
}
#[test]
fn test_wasmgen_regression_closure_captures_array_handle_wasm_execution() {
let src = r#"
fn dot(left, right){
let (left_head, left_rest) = split_head(left)
let (right_head, right_rest) = split_head(right)
let head_product = left_head * right_head
if len(left_rest) > 0 {
head_product + dot(left_rest, right_rest)
} else {
head_product
}
}
fn map_rows(fun, matrix){
let (head, rest) = split_head(matrix)
if len(rest) > 0 {
prepend(fun(head), map_rows(fun, rest))
} else {
[fun(head)]
}
}
fn dsp(){
let input = [3.0, 4.0]
let out = map_rows(|row| dot(row, input), [[1.0, 2.0], [5.0, 6.0]])
let (head, _) = split_head(out)
head
}
"#;
let value = run_wasm_dsp_f64(
src,
Some(repo_test_artifact_path(
"closure_capture_array_regression.mmm",
)),
);
assert_eq!(value, 11.0);
}
}