shape-jit 0.3.1

Tiered JIT compiler (Cranelift) for the Shape virtual machine
Documentation
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
//! Type mapping for MIR-to-Cranelift IR compilation.
//!
//! Maps MIR LocalTypeInfo and NativeKind to Cranelift types.
//! Includes MIR-level type inference for determining slot kinds
//! when the bytecode compiler doesn't provide them.

use cranelift::prelude::types;
use shape_value::heap_value::HeapKind;
use shape_value::v2::ConcreteType;
use shape_vm::mir::types::*;
use shape_vm::type_tracking::NativeKind;

/// Whether a local slot holds a heap value that needs reference counting.
pub(crate) fn is_heap_type(type_info: &LocalTypeInfo) -> bool {
    matches!(type_info, LocalTypeInfo::NonCopy)
}

/// Whether a local slot is known to be Copy (no refcounting needed).
pub(crate) fn is_copy_type(type_info: &LocalTypeInfo) -> bool {
    matches!(type_info, LocalTypeInfo::Copy)
}

/// Get the NativeKind for a local. Returns `None` when the slot
/// index is out of range OR the inference pass left the slot
/// undetermined.
///
/// Per ADR-006 §2.7.7, the deleted `NativeKind::Unknown` placeholder
/// is forbidden in the runtime parallel-kind track. This compile-time
/// helper is a different layer (compile-time inference metadata, not
/// the runtime track), but it adopts the same single-discriminator
/// discipline by returning `Option<NativeKind>` rather than papering
/// over the missing-kind case.
pub(crate) fn slot_kind_for_local(
    slot_kinds: &[Option<NativeKind>],
    slot_idx: u16,
) -> Option<NativeKind> {
    slot_kinds.get(slot_idx as usize).copied().flatten()
}

/// Whether a NativeKind is i32 (Int32 or UInt32).
pub(crate) fn is_i32_slot(kind: NativeKind) -> bool {
    matches!(kind, NativeKind::Int32 | NativeKind::UInt32)
}

/// Whether a NativeKind represents a native (non-NaN-boxed) Cranelift type.
#[allow(dead_code)]
pub(crate) fn is_native_slot(kind: NativeKind) -> bool {
    matches!(
        kind,
        NativeKind::Float64
            | NativeKind::Int32
            | NativeKind::UInt32
            | NativeKind::Bool
            | NativeKind::Int8
            | NativeKind::UInt8
            | NativeKind::Int16
            | NativeKind::UInt16
    )
}

/// Map a NativeKind to its Cranelift type.
/// Native numeric types get their natural width; everything else is I64.
pub(crate) fn cranelift_type_for_slot(kind: NativeKind) -> cranelift::prelude::Type {
    match kind {
        NativeKind::Float64 => types::F64,
        NativeKind::Int32 | NativeKind::UInt32 => types::I32,
        NativeKind::Int8 | NativeKind::UInt8 | NativeKind::Bool => types::I8,
        NativeKind::Int16 | NativeKind::UInt16 => types::I16,
        // Int64, UInt64, String, Ptr(_), Nullable*, IntSize, UIntSize:
        // 8-byte raw u64 (typed pointer for heap arms, scalar for ints).
        _ => types::I64,
    }
}

/// Whether a NativeKind is a v2 heap pointer type (TypedArray, TypedStruct, StringObj).
/// These use inline refcounting via HeapHeader at offset 0.
pub(crate) fn is_v2_heap_slot(kind: NativeKind) -> bool {
    let _ = kind;
    false
}

/// Map a `ConcreteType` element type to the matching `NativeKind` for the v2
/// typed-array codegen helpers (`v2_array_get`/`v2_array_set`).
///
/// ckpt-6-prime Group X JIT FFI String/Decimal BUILD (2026-05-15):
/// extended with `String → StringV2` / `Decimal → DecimalV2` per ADR-006
/// §2.7.5 + §2.7.24 Q25.A SUPERSEDED + audit deliverable (b) §4.1.B. The
/// `StringV2` / `DecimalV2` element kinds route through the v2-raw
/// `TypedArray<*const StringObj>` / `TypedArray<*const DecimalObj>`
/// allocators added in `v2_array_new_func`; per-element literal-upgrade
/// is handled in `emit_v2_array_aggregate`'s StringV2/DecimalV2 arms
/// mirroring the VM-side `NewStringV2` / `NewDecimalV2` opcodes at
/// `crates/shape-vm/src/executor/v2_handlers/array.rs:803-858`.
pub(crate) fn elem_slot_kind_for_concrete(elem: &ConcreteType) -> Option<NativeKind> {
    match elem {
        ConcreteType::F64 => Some(NativeKind::Float64),
        ConcreteType::I64 => Some(NativeKind::Int64),
        ConcreteType::I32 => Some(NativeKind::Int32),
        ConcreteType::I16 => Some(NativeKind::Int16),
        ConcreteType::I8 => Some(NativeKind::Int8),
        ConcreteType::U64 => Some(NativeKind::UInt64),
        ConcreteType::U32 => Some(NativeKind::UInt32),
        ConcreteType::U16 => Some(NativeKind::UInt16),
        ConcreteType::U8 => Some(NativeKind::UInt8),
        ConcreteType::Bool => Some(NativeKind::Bool),
        // Round 19 S1.5 W12-nativekind-scalar-additions (2026-05-14):
        // ADR-006 §2.7.5 amendment.
        ConcreteType::F32 => Some(NativeKind::Float32),
        ConcreteType::Char => Some(NativeKind::Char),
        // ckpt-6-prime Group X JIT FFI String/Decimal BUILD (2026-05-15):
        // Array<string> / Array<decimal> route through v2-raw
        // `TypedArray<*const StringObj>` / `TypedArray<*const DecimalObj>`
        // carriers per ADR-006 §2.7.5 + §2.7.24 Q25.A SUPERSEDED + audit
        // deliverable (b) §4.1.B.
        ConcreteType::String => Some(NativeKind::StringV2),
        ConcreteType::Decimal => Some(NativeKind::DecimalV2),
        _ => None,
    }
}

/// Inspect a slot's `ConcreteType` and report the v2 typed-array element kind
/// when the slot is known to hold an `Array<T>` whose element type maps to a
/// scalar Cranelift load/store. Returns `None` for unknown / non-array /
/// non-scalar slots — caller falls back to legacy NaN-boxed path.
pub(crate) fn is_v2_typed_array_slot(
    concrete_types: &[ConcreteType],
    slot_idx: u16,
) -> Option<NativeKind> {
    let ct = concrete_types.get(slot_idx as usize)?;
    match ct {
        ConcreteType::Array(elem) => elem_slot_kind_for_concrete(elem),
        _ => None,
    }
}

/// Project a `ConcreteType` to its corresponding `NativeKind` for the
/// §2.7.7 / Q9 parallel-kind track seed.
///
/// ADR-006 §2.7.11/Q12: closure-bearing slots (e.g. function return
/// values that produce a closure value via `jit_finalize_heap_closure`)
/// carry kind `Ptr(HeapKind::Closure)` per the slot-tier convention.
/// `ConcreteType::Closure(_)` is the bytecode-compiler-supplied kind
/// source for such slots; without this projection the closure-callee
/// classification at the indirect-call entry can't be derived from
/// MIR-observable statements alone (`infer_slot_kinds` sees only
/// `Rvalue::Use(Copy(_))` chains, not the producing function-call's
/// declared return type).
///
/// Returns `None` for `ConcreteType::Void` (the unit/no-value type)
/// since there is no carrier-bits-shaped slot for void.
pub(crate) fn native_kind_from_concrete_type(ct: &ConcreteType) -> Option<NativeKind> {
    use shape_value::heap_value::HeapKind;
    Some(match ct {
        ConcreteType::F64 => NativeKind::Float64,
        ConcreteType::I64 => NativeKind::Int64,
        ConcreteType::I32 => NativeKind::Int32,
        ConcreteType::I16 => NativeKind::Int16,
        ConcreteType::I8 => NativeKind::Int8,
        ConcreteType::U64 => NativeKind::UInt64,
        ConcreteType::U32 => NativeKind::UInt32,
        ConcreteType::U16 => NativeKind::UInt16,
        ConcreteType::U8 => NativeKind::UInt8,
        ConcreteType::Bool => NativeKind::Bool,
        ConcreteType::String => NativeKind::String,
        // Closure / Function carry `Arc<HeapValue::ClosureRaw>` per
        // §2.7.11/Q12 — `Ptr(HeapKind::Closure)`.
        ConcreteType::Closure(_) | ConcreteType::Function(_) => {
            NativeKind::Ptr(HeapKind::Closure)
        }
        // Result/Option are typed-Arc heap values with their own
        // HeapKind discriminator per §2.7.17.
        ConcreteType::Result(_, _) => NativeKind::Ptr(HeapKind::Result),
        ConcreteType::Option(_) => NativeKind::Ptr(HeapKind::Option),
        // Array<T> — `Arc<TypedArrayData>` per §2.7.6 / Route A.
        ConcreteType::Array(_) => NativeKind::Ptr(HeapKind::TypedArray),
        // HashMap — `Arc<HashMapData>` per Stage C P1(b).
        ConcreteType::HashMap(_, _) => NativeKind::Ptr(HeapKind::HashMap),
        // Struct → TypedObject per §2.7.6.
        ConcreteType::Struct(_) => NativeKind::Ptr(HeapKind::TypedObject),
        // Enum payloads live in TypedObject too (the W14-variant-codegen
        // single-storage-discriminator convention).
        ConcreteType::Enum(_) => NativeKind::Ptr(HeapKind::TypedObject),
        // Decimal / BigInt / DateTime carry typed-Arc heap values.
        ConcreteType::Decimal => NativeKind::Ptr(HeapKind::Decimal),
        ConcreteType::BigInt => NativeKind::Ptr(HeapKind::BigInt),
        ConcreteType::DateTime => NativeKind::Ptr(HeapKind::Temporal),
        // Pointer is the FFI `*const T` raw pointer — UInt64 carrier.
        ConcreteType::Pointer(_) => NativeKind::UInt64,
        // Tuple slots carry typed-array-style storage per the W14
        // tuple-codegen convention; treat as TypedObject for the
        // kind track.
        ConcreteType::Tuple(_) => NativeKind::Ptr(HeapKind::TypedObject),
        // ── Phase 3 cluster-0 Round 11-trinity 11E (2026-05-13) ─────────
        // Collection / concurrency carriers — taxonomy extended in
        // `shape-value/src/v2/concrete_type.rs` per the Round 10 surfaced
        // item (B). Each ConcreteType arm maps to its dedicated
        // `HeapKind` ordinal (§2.7.15 / §2.7.17 / §2.7.18 / §2.7.20 /
        // §2.7.25) and dispatches through Round 9's `retain_func_for_place`
        // / `release_func_for_place` 8-arm extension. Pre-11E the JIT
        // EnumStore consumer carried out-of-band kind seeding at the
        // `mir_compiler/types.rs` EnumStore arm because ConcreteType
        // didn't have these variants; with 11E landed the in-band
        // `concrete_seed` path is authoritative.
        ConcreteType::HashSet(_) => NativeKind::Ptr(HeapKind::HashSet),
        ConcreteType::Deque(_) => NativeKind::Ptr(HeapKind::Deque),
        ConcreteType::PriorityQueue => NativeKind::Ptr(HeapKind::PriorityQueue),
        ConcreteType::Channel(_) => NativeKind::Ptr(HeapKind::Channel),
        ConcreteType::Mutex(_) => NativeKind::Ptr(HeapKind::Mutex),
        ConcreteType::Atomic => NativeKind::Ptr(HeapKind::Atomic),
        ConcreteType::Lazy(_) => NativeKind::Ptr(HeapKind::Lazy),
        // ── Round 19 S1.5 W12-nativekind-scalar-additions ──────────
        // (2026-05-14) — ADR-006 §2.7.5 amendment.
        ConcreteType::F32 => NativeKind::Float32,
        ConcreteType::Char => NativeKind::Char,
        // Void has no carrier slot.
        ConcreteType::Void => return None,
    })
}

// ── MIR-level type inference ────────────────────────────────────────────

/// Infer SlotKinds from MIR constants and operations.
///
/// Scans all basic blocks forward and tracks what types flow into each slot.
/// When the bytecode compiler doesn't provide slot_kinds (empty vec),
/// this pass fills them in from MIR-observable information.
///
/// Returns a `Vec<Option<NativeKind>>`: `Some(k)` for slots whose kind
/// the inference proved, `None` for slots the inference left
/// undetermined (e.g. opaque field reads, or parameters with no
/// kind-source). Per ADR-006 §2.7.7 we use `None` rather than the
/// deleted `NativeKind::Unknown` placeholder — callers that need a
/// concrete kind for codegen surface-and-stop on `None`.
///
/// Rules:
/// - Assign(slot, Use(Constant(Float(_)))) → Float64
/// - Assign(slot, Use(Constant(Int(_)))) → Int64 (NaN-boxed int uses 48-bit payload)
/// - Assign(slot, Use(Constant(Bool(_)))) → Bool
/// - Assign(slot, BinaryOp(arith, lhs, rhs)) → inherits from operands if both agree
/// - Assign(slot, Use(Move/Copy(other_slot))) → inherits from other_slot
/// - Conflicting assignments → keep existing
pub(crate) fn infer_slot_kinds(
    mir: &MirFunction,
    existing: &[Option<NativeKind>],
) -> Vec<Option<NativeKind>> {
    infer_slot_kinds_with_concrete(mir, existing, &[])
}

/// Same as `infer_slot_kinds` but also accepts the per-slot
/// `ConcreteType` vector. Used by two orthogonal producing-site
/// classifications:
///
/// 1. **Field projection (W12-jit-binop-after-heap-read-kind-tracker /
///    Round 5A)**: pre-computes a `field_kinds_pre` map from
///    `StatementKind::ObjectStore` operands, then projects through
///    `Place::Field` reads so `Assign(slot, Use(Move(Field(_, _))))`
///    infers the FIELD's kind, not the base struct's heap kind.
///
/// 2. **Index projection (W12-jit-print-kind / Round 5C)**: the
///    `ConcreteType` vector is used to project through `Place::Index` to
///    the array's element kind so destination slots of
///    `Assign(slot, Use(Copy(Index(arr, _))))` infer the element kind
///    rather than the array's heap-pointer kind. Mirrors the JIT codegen-
///    side `v2_typed_array_elem_kind` projection used in
///    `place_native_kind` (rvalues.rs).
///
/// 3. **Call-terminator destination stamping (W12-jit-print-kind /
///    Round 5C)**: BEFORE the forward statement pass, the destination
///    slot of every `TerminatorKind::Call` is stamped from
///    `well_known_method_return_kind` /
///    `well_known_function_return_kind` so a downstream `Assign(n_slot,
///    Use(Move(call_temp)))` can propagate the method-call return kind
///    into the user-visible binding slot.
///
/// ADR-006 §2.7.5 producing-site classification: when the source MIR
/// statement reads an element from a typed-array slot
/// (`Assign(dst, Use(Copy/Move(Index(arr, _))))`), the destination's
/// `NativeKind` is the element kind, not the array's pointer kind. The
/// element kind comes from the typed-array seed
/// (`ConcreteType::Array(elem)`) the bytecode compiler stamps via
/// `infer_top_level_concrete_types_from_mir` / `function_local_concrete_types`,
/// and is passed in as `concrete_types`. Without this projection the
/// `xs[0]` slot stays `None` and a downstream `print(xs[0])` falls into
/// the kind-blind decoder.
///
/// `concrete_types` aligned with MIR slot indices (same shape as the
/// `concrete_seed` built in `mir_compiler::mod.rs`). Entries outside
/// `Array(_)` shapes contribute nothing to the Index-projection rule.
pub(crate) fn infer_slot_kinds_with_concrete(
    mir: &MirFunction,
    existing: &[Option<NativeKind>],
    concrete_types: &[ConcreteType],
) -> Vec<Option<NativeKind>> {
    let n = mir.num_locals as usize;
    let mut kinds: Vec<Option<NativeKind>> = vec![None; n];

    // Seed from existing slot_kinds (from bytecode compiler).
    for (i, &k) in existing.iter().enumerate() {
        if i < n && k.is_some() {
            kinds[i] = k;
        }
    }

    // ADR-006 §2.7.5 producing-site classification for `TerminatorKind::Call`
    // destinations (W12-jit-print-kind / Round 5C) — seeded BEFORE the
    // forward statement pass so the call-result kind is available when a
    // downstream `Assign(slot, Use(Move(call_temp)))` walks the forward
    // pass to propagate the method-call return kind into the user-
    // visible binding slot.
    //
    // The `infer_slot_kinds` statement-walk only sees
    // `StatementKind::Assign(place, rvalue)` writes; the destination of a
    // Call terminator (`TerminatorKind::Call { destination, .. }`) is the
    // separate kind-source the statement-walk misses. Without this seed a
    // `let n = s.size(); print(n)` flows the method-call result through a
    // temp slot whose `kinds[temp]` stays `None`, and the downstream
    // `Assign(n_slot, Use(Move(temp)))` forward-pass inherits `None`,
    // sending `print(n)` into the kind-blind decoder
    // (`format_value_word`, a deleted-W-series tag-decode pattern per
    // CLAUDE.md "Forbidden code").
    //
    // The kind is classified from the well-known method name per
    // `well_known_method_return_kind` — a small registry of method names
    // whose return type is invariant across receiver types in the
    // VM's method registry (`crates/shape-vm/src/executor/objects/
    // method_registry.rs`): `size`/`len`/`length`/`count` → Int64;
    // `isEmpty`/`contains`/`has` → Bool. Names outside this set
    // remain `None` — the slot's kind genuinely isn't statically
    // classifiable from the MIR-observable shape alone, per §2.7.7
    // (no fabricated default).
    for block in &mir.blocks {
        if let TerminatorKind::Call {
            func,
            args,
            destination,
            ..
        } = &block.terminator.kind
        {
            if let Place::Local(slot) = destination {
                let idx = slot.0 as usize;
                if idx < n && kinds[idx].is_none() {
                    let ret_kind = match func {
                        Operand::Constant(MirConstant::Method(name)) => {
                            // ADR-006 §2.7.5 producing-site conduit
                            // extension for parametric-return methods
                            // (Phase 3 cluster-0 Round 11-trinity Part b,
                            // 2026-05-13). Method-return kinds split into
                            // two cohorts: invariant-across-receivers
                            // (`size`/`isEmpty`/...) classified via
                            // `well_known_method_return_kind(name)`, and
                            // receiver-parametric (`HashMap.get →
                            // Option<V>`, `Mutex.get → T`, `Atomic.load →
                            // i64`, `Array.sum/mean/min/max → element`)
                            // classified via
                            // `parametric_method_return_kind(name,
                            // receiver_ct)` where `receiver_ct` is
                            // `concrete_types[args[0].root_local()]`.
                            //
                            // Invariant-name classification runs first
                            // (current behavior); when it returns None,
                            // fall through to the receiver-parametric
                            // classifier. This preserves the existing
                            // Round 5C semantics for size/len/etc.
                            // exactly, and extends classification for
                            // methods whose return kind genuinely
                            // depends on the receiver shape.
                            //
                            // The receiver-in-pass-kinds fallback
                            // (`method_return_kind_from_in_pass_kinds`) is
                            // NOT consulted here because at this point in
                            // the pass the EnumStore-driven kind seeds (line
                            // ~582) have not been applied — bare-form
                            // collection ctors like `HashMap()` are still
                            // unclassified. The chain-temp fallback runs in
                            // a SECOND fixpoint-iterated call-stamp pass
                            // BELOW (line ~692, after the forward pass) per
                            // Phase 4b Round 5c-2-α HashMap-has-2-chain
                            // ratify 2026-05-19.
                            well_known_method_return_kind(name).or_else(|| {
                                parametric_method_return_kind_from_receiver(
                                    name,
                                    args,
                                    concrete_types,
                                )
                            })
                        }
                        Operand::Constant(MirConstant::Function(name)) => {
                            well_known_function_return_kind(name)
                        }
                        _ => None,
                    };
                    if let Some(k) = ret_kind {
                        kinds[idx] = Some(k);
                    }
                }
            }
        }
    }

    // W12-jit-binop-after-heap-read-kind-tracker (ADR-006 §2.7.5 /
    // Round 5A): pre-compute the producer-side field-kinds map from
    // `StatementKind::ObjectStore { operands, field_names }`. Each
    // operand's kind is resolved via a forward-only constant-propagation
    // pass over the seeded slot kinds (`kinds` here, freshly seeded with
    // `existing`). The result is then used to project through
    // `Place::Field` in `infer_rvalue_kind_with_projections` /
    // `infer_operand_kind_with_projections` so that `Assign(slot,
    // Use(Move(Field(_, _))))` infers the destination slot's kind from
    // the FIELD's kind, not the base struct's heap kind.
    //
    // Without this, slot kinds inferred from `Use(Move(Field(_, _)))`
    // inherit the base's `Ptr(HeapKind::TypedObject)`, which downstream
    // `refcount_disposition` then dispatches as refcounted — and the
    // field-value `i64=3` passed to `arc_release` segfaults at the
    // initial-zero or post-assignment slot read.
    //
    // Run a quick `Assign(slot, Use(Const))` forward pass first to
    // populate operand-source slot kinds, then walk `ObjectStore` to
    // stamp `field_kinds`. The pre-pass is forward-only (no fixed-point
    // iteration); for cluster-0's load-bearing field-add smoke
    // (`Point{x:3,y:4}` with `int` constants) this is sufficient.
    let field_kinds_pre: std::collections::HashMap<String, NativeKind> = {
        let mut tmp_kinds = kinds.clone();
        for block in &mir.blocks {
            for stmt in &block.statements {
                if let StatementKind::Assign(
                    Place::Local(slot),
                    Rvalue::Use(Operand::Constant(c)),
                ) = &stmt.kind
                {
                    let idx = slot.0 as usize;
                    if idx < n && tmp_kinds[idx].is_none() {
                        tmp_kinds[idx] = infer_constant_kind(c);
                    }
                }
            }
        }
        let mut fk: std::collections::HashMap<String, NativeKind> =
            std::collections::HashMap::new();
        for block in &mir.blocks {
            for stmt in &block.statements {
                if let StatementKind::ObjectStore {
                    operands,
                    field_names,
                    ..
                } = &stmt.kind
                {
                    for (op, name) in operands.iter().zip(field_names.iter()) {
                        if name.is_empty() {
                            continue;
                        }
                        if let Some(kind) =
                            infer_operand_kind_with_fields(op, &tmp_kinds, None, None)
                        {
                            fk.insert(name.clone(), kind);
                        }
                    }
                }
            }
        }
        fk
    };

    // Forward pass: infer from constants and operations.
    for block in &mir.blocks {
        for stmt in &block.statements {
            match &stmt.kind {
                StatementKind::Assign(place, rvalue) => {
                    if let Place::Local(slot) = place {
                        let idx = slot.0 as usize;
                        if idx < n && kinds[idx].is_none() {
                            // Combined Field + Index projection (Round
                            // 5A's `infer_rvalue_kind_with_projections`
                            // already handles both: Field via
                            // `field_kinds_pre`, Index via
                            // `concrete_types`'s `Array<scalar>` shape —
                            // the same kind source as 5C's separate
                            // `infer_index_element_kind` helper, bundled
                            // into the more general projection path).
                            if let Some(inferred) = infer_rvalue_kind_with_projections(
                                rvalue,
                                &kinds,
                                Some(&field_kinds_pre),
                                Some(&mir.field_name_table),
                                Some(concrete_types),
                            ) {
                                kinds[idx] = Some(inferred);
                            }
                        } else if idx < n {
                            // Slot already has a kind — check for conflicts.
                            if let Some(inferred) = infer_rvalue_kind_with_projections(
                                rvalue,
                                &kinds,
                                Some(&field_kinds_pre),
                                Some(&mir.field_name_table),
                                Some(concrete_types),
                            ) {
                                if Some(inferred) != kinds[idx] {
                                    // Conflict: different types on different paths.
                                    // Keep the existing kind (first write wins for
                                    // simple programs; SSA form means each slot is
                                    // typically written once in practice).
                                }
                            }
                        }
                    }
                }
                // ADR-006 §2.7.7 / §2.7.11 / Q12 kind-source: a
                // `ClosureCapture` lowers to either the §2.7.11 raw-Arc
                // closure shape (`jit_finalize_heap_closure` → raw
                // `Arc::into_raw(Arc<HeapValue::ClosureRaw>) as u64` slot
                // bits) or the §2.7.11 stack-closure fast path. Either
                // way the slot's `NativeKind` is
                // `Ptr(HeapKind::Closure)` per the §2.7.11/Q12 callee-
                // classification convention. Without this seed the slot
                // would be `None` and the indirect-call dispatch's
                // parallel-kind track would surface a kind-source gap at
                // the load-bearing closure-callee push site for
                // Smoke 1.5.
                StatementKind::ClosureCapture { closure_slot, .. } => {
                    let idx = closure_slot.0 as usize;
                    if idx < n && kinds[idx].is_none() {
                        kinds[idx] = Some(NativeKind::Ptr(HeapKind::Closure));
                    }
                }
                // W12-jit-call-method-shell-rebuild (Phase 3 cluster-0
                // Round 10 / 8B.2, 2026-05-13): ADR-006 §2.7.5 producer-
                // side classification for primitive-collection ctors.
                //
                // The bytecode compiler doesn't synthesize a
                // `ConcreteType::HashSet` / `Deque` / `PriorityQueue` /
                // `Channel` / `Mutex` / `Atomic` / `Lazy` variant — those
                // types aren't modeled in the §2.7.6 concrete-types
                // taxonomy yet (W17-collection-concrete-types is the
                // tracked follow-up). The MIR-emit-side EnumStore is the
                // load-bearing kind source: when `variant_name` is one of
                // the 8 collection names, the container slot bits are
                // exactly `Arc::into_raw(Arc<XData>) as u64` per Round 9's
                // typed-Arc ctor FFI bodies, and the slot's `NativeKind`
                // is the matching `Ptr(HeapKind::*)` arm.
                //
                // Without this seed the slot kind on the §2.7.7 / Q9
                // parallel-kind track stays `None` → falls back to the
                // §2.7.5 carrier kind `UInt64` at the receiver push site
                // → the `jit_call_method` shell's delegation predicate
                // routes to the legacy JIT-format dispatch path (which
                // doesn't know how to read `Arc<HashSetData>` raw
                // pointers as JIT NaN-box bits) → method dispatch
                // surfaces silently as TAG_NULL. The kind seed here
                // closes that gap.
                //
                // The `HashMap` collection ctor maps to
                // `Ptr(HeapKind::HashMap)`. Note that this overlaps with
                // the `ConcreteType::HashMap(K, V)` →
                // `Ptr(HeapKind::HashMap)` seed for v2 typed HashMaps;
                // both paths converge on the same carrier kind. The MIR
                // EnumStore for `HashMap()` runs only for the bare-form
                // ctor (`is_bare_collection_ctor` accepts it); typed
                // HashMaps from `HashMap<string, int>()` go through the
                // bytecode compiler's typed-HashMap fast path, which
                // populates `concrete_types[slot] = HashMap(_, _)`
                // directly and the `concrete_seed` upstream of this pass
                // already handled it.
                StatementKind::EnumStore {
                    container_slot,
                    variant_name: Some(name),
                    ..
                } => {
                    let collection_kind = match name.as_str() {
                        "Set" | "HashSet" => Some(NativeKind::Ptr(HeapKind::HashSet)),
                        "HashMap" => Some(NativeKind::Ptr(HeapKind::HashMap)),
                        "Deque" => Some(NativeKind::Ptr(HeapKind::Deque)),
                        "PriorityQueue" => {
                            Some(NativeKind::Ptr(HeapKind::PriorityQueue))
                        }
                        "Channel" => Some(NativeKind::Ptr(HeapKind::Channel)),
                        "Mutex" => Some(NativeKind::Ptr(HeapKind::Mutex)),
                        "Atomic" => Some(NativeKind::Ptr(HeapKind::Atomic)),
                        "Lazy" => Some(NativeKind::Ptr(HeapKind::Lazy)),
                        _ => None,
                    };
                    if let Some(k) = collection_kind {
                        let idx = container_slot.0 as usize;
                        if idx < n {
                            // Override the upstream concrete_seed: the
                            // bytecode compiler's type-checker classifies
                            // `Set` / `HashMap` / etc. as `ConcreteType::
                            // Struct(_)` (since the stdlib defines them as
                            // typed structs), which `concrete_seed` maps
                            // to `Ptr(HeapKind::TypedObject)`. That's a
                            // wrong-carrier classification for the typed-
                            // Arc ctors landed in Round 9 — the slot bits
                            // are `Arc::into_raw(Arc<HashSetData>)`, NOT
                            // `Arc::into_raw(Arc<TypedObjectStorage>)`,
                            // and the kind drives downstream
                            // retain/release dispatch through Round 9's
                            // `retain_func_for_place` /
                            // `release_func_for_place` 8-arm extension.
                            // A `TypedObject`-labeled slot would dispatch
                            // through `arc_retain` / `arc_release` on the
                            // legacy `UnifiedValue<T>` HeapHeader at
                            // offset 4, which would scribble on the
                            // `HashSetData` payload (audit §5 carrier-
                            // shape rule). The EnumStore producer-site
                            // classification IS authoritative for these
                            // slots per the §2.7.5 stamp-at-MIR-emit
                            // discipline.
                            //
                            // ADR-006 W17-collection-concrete-types is the
                            // tracked follow-up to extend `ConcreteType`
                            // with `HashSet` / `Deque` / `PriorityQueue`
                            // / `Channel` / `Mutex` / `Atomic` / `Lazy`
                            // arms so the bytecode compiler's seed gets
                            // these right at the source.
                            kinds[idx] = Some(k);
                        }
                    }
                }
                _ => {}
            }
        }
    }

    // W12-jit-call-method-shell-rebuild post-pass (Phase 3 cluster-0 Round
    // 10 / 8B.2, 2026-05-13): propagate collection-ctor kinds through
    // identity-Use chains. The bytecode compiler's `concrete_seed` maps
    // `let s = Set()`'s user-visible slot to `Ptr(HeapKind::TypedObject)`
    // (since the stdlib defines `Set` as a typed struct). The forward
    // pass's "first write wins / no overwrite on conflict" rule preserves
    // that wrong-carrier classification: the EnumStore arm above
    // overrides the EnumStore container slot to `Ptr(HeapKind::HashSet)`,
    // but a downstream `Assign(s_slot, Use(Move(tmp_slot)))` leaves
    // `s_slot` at its pre-seeded `Ptr(TypedObject)` instead of inheriting
    // the corrected `Ptr(HashSet)` from `tmp_slot`.
    //
    // This post-pass walks Assign-Use chains and propagates any of the 8
    // typed-Arc collection kinds from source to destination, overriding
    // the pre-seeded `Ptr(TypedObject)` (or any other carrier kind) —
    // because the typed-Arc carrier-shape rule (audit §5) requires the
    // slot kind to drive retain/release dispatch correctly. A
    // `TypedObject`-labeled slot would route through `arc_retain` /
    // `arc_release` on the `UnifiedValue<T>` HeapHeader at offset 4,
    // scribbling on the `Arc<HashSetData>` payload. Override is correct
    // because the EnumStore producer is authoritative.
    //
    // The pass iterates until fixpoint (bounded: each iteration converts
    // at most one slot, so it terminates in O(num_locals) iterations).
    // For `let s = Set(); let t = s; let u = t; ...` chains this
    // propagates through every binding to the deepest use.
    fn is_collection_kind(k: NativeKind) -> bool {
        matches!(
            k,
            NativeKind::Ptr(HeapKind::HashSet)
                | NativeKind::Ptr(HeapKind::HashMap)
                | NativeKind::Ptr(HeapKind::Deque)
                | NativeKind::Ptr(HeapKind::PriorityQueue)
                | NativeKind::Ptr(HeapKind::Channel)
                | NativeKind::Ptr(HeapKind::Mutex)
                | NativeKind::Ptr(HeapKind::Atomic)
                | NativeKind::Ptr(HeapKind::Lazy)
        )
    }
    // Phase 4b Round 5c-2-α HashMap-has-2-chain VM/JIT divergence fix
    // (v0.3-gating SOUNDNESS BUG ratified 2026-05-19). Unified fixpoint
    // pass covering both (a) the existing collection-alias propagation
    // (`let t = s` re-bindings through `Assign(_, Use(Copy/Move))`) and
    // (b) the NEW chain-temp call-terminator stamping for HashMap
    // mutators (`set` / `delete` / `merge`) returning self.
    //
    // Both stamping rules need to be at the same fixpoint level because
    // chain-temp patterns interleave: `HashMap().set(...).set(...)` has
    // each `.set` call's destination temp aliased into a downstream
    // `let m = ...; m.set(...)` rebind which depends on the alias
    // propagation, AND each `.set` call's destination kind depends on
    // its receiver's in-pass `kinds[]` which is the alias-propagated
    // value from the previous chain link.
    //
    // Empirical pre-fix at HEAD 7eb82205: `HashMap().set("a",1).has("a")`
    // already diverged (VM=true / JIT=false) at the 1-chain length
    // because:
    //   1. The EnumStore arm stamps temp_HashMap_ctor's slot as
    //      `Ptr(HeapKind::HashMap)`.
    //   2. The call `temp_set = temp_HashMap_ctor.set("a", 1)` has no
    //      kind classifier entry for `set`, so temp_set stayed None.
    //   3. The MIR copy `m = temp_set` then needs collection-alias-
    //      propagation to inherit temp_set's kind — but temp_set has
    //      no kind, so `m` also stays None.
    //   4. The next call `temp_has = m.has("a")` pushes `m` as receiver
    //      with kind None → fallback to `UInt64` carrier at the
    //      `operand_slot_kind_or_carrier` site →
    //      `jit_call_method` shell's delegation predicate routes to
    //      legacy JIT-format dispatch which doesn't recognize
    //      `Arc::into_raw(Arc<HashMapKindedRef>)` bits → TAG_NULL.
    //   5. The destination kind for `temp_has` is correctly Bool (from
    //      `well_known_method_return_kind("has")`), so TAG_NULL bits
    //      under a Bool consumer renders `false`.
    //
    // Post-fix: the unified fixpoint propagates `Ptr(HeapKind::HashMap)`
    // through each chain link, routing the final `.has()` call's
    // receiver through `jit_trampoline_call_method` per §2.7.10 / Q11
    // dispatch to the VM's `HASHMAP_METHODS.get("has") => v2_has`
    // handler.
    //
    // Per ADR-006 §2.7.5 producer-side stamp. The HashMap-mutator
    // classifier reads the VM-side handler signatures:
    // `hashmap_methods::v2_set` at line 789 returns
    // `KindedSlot::from_hashmap(...)`; `v2_delete` at 1235 and
    // `v2_merge` at 1469 do likewise. VM producer-stamp and JIT
    // consumer-classify converge on the same `Ptr(HeapKind::HashMap)`
    // kind without any cross-layer translation step.
    let mut changed = true;
    let mut iterations = 0;
    let max_iterations = n + 4; // safety bound
    while changed && iterations < max_iterations {
        changed = false;
        iterations += 1;
        for block in &mir.blocks {
            // (a) Collection-alias propagation through `let t = s` /
            // `let u = t` re-bindings — preserves the existing
            // behavior (was a standalone loop pre-Round-5c-2-α).
            for stmt in &block.statements {
                if let StatementKind::Assign(
                    Place::Local(dst),
                    Rvalue::Use(operand),
                ) = &stmt.kind
                {
                    let src_slot = match operand {
                        Operand::Copy(Place::Local(s))
                        | Operand::Move(Place::Local(s))
                        | Operand::MoveExplicit(Place::Local(s)) => Some(*s),
                        _ => None,
                    };
                    if let Some(src) = src_slot {
                        let dst_idx = dst.0 as usize;
                        let src_idx = src.0 as usize;
                        if dst_idx < n && src_idx < n {
                            if let Some(src_kind) = kinds[src_idx] {
                                if is_collection_kind(src_kind)
                                    && kinds[dst_idx] != Some(src_kind)
                                {
                                    kinds[dst_idx] = Some(src_kind);
                                    changed = true;
                                }
                            }
                        }
                    }
                }
            }
            // (b) Chain-temp call-terminator stamping for HashMap
            // mutators — NEW in Round 5c-2-α. Consults the in-pass
            // `kinds[]` for the receiver's NativeKind via
            // `method_return_kind_from_in_pass_kinds`, which the first
            // call-stamp pass at line ~331 doesn't have access to
            // (`concrete_types` doesn't carry the chain-temp shape).
            if let TerminatorKind::Call {
                func,
                args,
                destination,
                ..
            } = &block.terminator.kind
            {
                if let Place::Local(slot) = destination {
                    let idx = slot.0 as usize;
                    if idx < n && kinds[idx].is_none() {
                        let ret_kind = match func {
                            Operand::Constant(MirConstant::Method(name)) => {
                                method_return_kind_from_in_pass_kinds(
                                    name, args, &kinds,
                                )
                            }
                            _ => None,
                        };
                        if let Some(k) = ret_kind {
                            kinds[idx] = Some(k);
                            changed = true;
                        }
                    }
                }
            }
        }
    }

    // F7.c — build the set of "opaque-source" slots: slots whose Rvalue
    // reads from a heap projection (`Field` / `Index`) or another
    // non-trivial source (calls, borrows, aggregates). The runtime value
    // of such a slot is determined by the projection — its Cranelift
    // width is not guaranteed to match anything derivable from later uses.
    //
    // Example: `for i in 0..arr.length { ... }` lowers the `arr.length`
    // read to `Assign(SlotId(4), Use(Copy(Field(Local(1), FieldIdx(0)))))`.
    // The backward pass below would otherwise see `SlotId(5) < SlotId(4)`
    // with `SlotId(5): Int64`, conclude `SlotId(4)` is also `Int64`, and
    // the `compile_binop_int64` fast path would then unpack the
    // `box_number(f64)` bits as a TAG_INT payload — silently reading 0
    // from an f64 `4.0` and making the loop skip every iteration.
    //
    // By excluding these slots from backward propagation, the comparison
    // falls back to `compile_binop_dynamic_cmp`, which traps on a true
    // mixed-tag operand pair (deopt) — but in the common case where the
    // field happens to carry a number (e.g. `arr.length` returns
    // `box_number(len as f64)`), the `both_num` path fires correctly by
    // inspecting the tag bits at runtime rather than trusting an
    // unsound compile-time inference.
    let mut opaque_slots: std::collections::HashSet<usize> = std::collections::HashSet::new();
    for block in &mir.blocks {
        for stmt in &block.statements {
            if let StatementKind::Assign(Place::Local(slot), rvalue) = &stmt.kind {
                let opaque = match rvalue {
                    Rvalue::Use(operand) => is_opaque_operand(operand),
                    // Binary / unary / clone / borrow / aggregate: their
                    // result type comes from the compiler's inference, not
                    // from the destination slot's later uses. We only care
                    // about bare projections here — `Use(Copy(Field))` is
                    // the canonical case.
                    _ => false,
                };
                if opaque {
                    opaque_slots.insert(slot.0 as usize);
                }
            }
        }
    }

    // Backward pass: propagate types from typed operands to Unknown slots
    // used as the other operand in a binop. This picks up closure-param slots
    // like `x` in `|x| x + 1`, where the forward pass leaves `x` Unknown because
    // closure params are registered without a type annotation, but the typed
    // constant `1` proves `x` is Int64.
    //
    // Iterate to a fixed point — at most `n` rounds — so chained inferences
    // propagate (e.g. `|x, y| x + y + 1` should flow Int64 from `1` through
    // both params).
    let mut changed = true;
    let mut rounds = 0;
    while changed && rounds < n {
        changed = false;
        rounds += 1;
        for block in &mir.blocks {
            for stmt in &block.statements {
                if let StatementKind::Assign(_, Rvalue::BinaryOp(op, lhs, rhs)) = &stmt.kind {
                    // Comparisons don't constrain the operands' kinds beyond
                    // "both must match" — and the producing slot becomes Bool,
                    // not the operand kind. Still useful for propagating
                    // operand kinds between each other.
                    let _ = op;
                    let lk = infer_operand_kind(lhs, &kinds);
                    let rk = infer_operand_kind(rhs, &kinds);
                    match (lk, rk) {
                        (Some(k), None) => {
                            if let Some(slot) = operand_local_slot(rhs) {
                                if !opaque_slots.contains(&slot)
                                    && set_kind_if_unknown(&mut kinds, slot, k)
                                {
                                    changed = true;
                                }
                            }
                        }
                        (None, Some(k)) => {
                            if let Some(slot) = operand_local_slot(lhs) {
                                if !opaque_slots.contains(&slot)
                                    && set_kind_if_unknown(&mut kinds, slot, k)
                                {
                                    changed = true;
                                }
                            }
                        }
                        _ => {}
                    }
                }
            }
        }
    }

    // Parameters keep their existing-from-bytecode kind if any.
    // Otherwise they remain `None` — callers needing a concrete
    // kind for codegen surface-and-stop on the `None` per ADR-006
    // §2.7.7 (no deleted `NativeKind::Unknown` placeholder).
    for &param_slot in &mir.param_slots {
        let idx = param_slot.0 as usize;
        if idx < n {
            if let Some(Some(k)) = existing.get(idx).copied() {
                kinds[idx] = Some(k);
            }
        }
    }

    kinds
}

/// Return the statically-known return `NativeKind` for a well-known
/// method name, per ADR-006 §2.7.5 producing-site classification.
///
/// This is the JIT-side classifier for method-call destinations whose
/// return kind is invariant across receiver types in the VM's method
/// registry. The set mirrors the entries that appear in multiple
/// dispatch tables in `crates/shape-vm/src/executor/objects/
/// method_registry.rs` with the same return shape:
///
/// - `size` / `len` / `length` / `count`: every collection-method
///   implementation in `set_methods::v2_size`, `deque_methods::v2_size`,
///   `hashmap_methods::v2_len`, `typed_array_methods::v2_len`,
///   `array_basic::handle_len_v2`, etc. returns `KindedSlot::from_int(...)`.
/// - `isEmpty`: returns `KindedSlot::from_bool(...)` in every collection-
///   method implementation (e.g. `set_methods::v2_is_empty`).
/// - `has` / `contains`: typically `KindedSlot::from_bool(...)`.
///
/// Names outside this set return `None` — the JIT-compile pass treats
/// `None` as "kind genuinely not classifiable from the MIR-observable
/// shape" per §2.7.7 (no Bool-default fallback). Adding a new name
/// requires verifying the receiver-side method registry returns the
/// declared kind for every receiver type the dispatch reaches.
fn well_known_method_return_kind(name: &str) -> Option<NativeKind> {
    match name {
        // Collection-size methods. Verified against every dispatch table
        // in `method_registry.rs` that registers these names: array,
        // datatable, hashmap, set, deque, priority_queue, iterator,
        // typed_array — all return `KindedSlot::from_int(...)`.
        "size" | "len" | "length" | "count" => Some(NativeKind::Int64),
        // Emptiness / membership predicates — `KindedSlot::from_bool(...)`
        // across every receiver's PHF entry.
        "isEmpty" | "is_empty" | "has" | "contains" => Some(NativeKind::Bool),
        _ => None,
    }
}

/// Return the statically-known return `NativeKind` for a well-known
/// builtin-function name (called via `MirConstant::Function(name)`
/// rather than method dispatch). Currently only `len` is exposed as a
/// global builtin alongside its method form, returning Int64.
fn well_known_function_return_kind(name: &str) -> Option<NativeKind> {
    match name {
        // `len(x)` global builtin — returns int for every supported
        // receiver type (Array, String, HashMap, ...).
        "len" => Some(NativeKind::Int64),
        _ => None,
    }
}

/// ADR-006 §2.7.5 producing-site classification for parametric-return
/// method calls (Phase 3 cluster-0 Round 11-trinity Part b, 2026-05-13).
///
/// Companion of `well_known_method_return_kind`: that classifier covers
/// methods whose return type is INVARIANT across receiver types
/// (`size`/`len`/`length`/`count` → Int64; `isEmpty`/`contains`/`has` →
/// Bool — verified against every dispatch table in
/// `crates/shape-vm/src/executor/objects/method_registry.rs`). This
/// classifier covers methods whose return type DEPENDS on the receiver's
/// `ConcreteType` parametric form:
///
/// - `Array<T>.sum() / .mean() / .min() / .max() / .first() / .last() /
///   .pop() / .get(i)` — return kind flows from `ConcreteType::Array(T)`
///   element type to a scalar `NativeKind` (Int64 for `Array<int>`,
///   Float64 for `Array<number>`, etc.). `.first()/.last()/.pop()`
///   wrap in `Option<T>`, classified as `Ptr(HeapKind::Option)` carrier
///   bits per §2.7.17.
/// - `HashMap<K, V>.get(K) → Option<V>` — receiver
///   `ConcreteType::HashMap(_, V)` returns `Ptr(HeapKind::Option)`
///   (the wrapped V is on the Option's inner kind track, picked up by
///   downstream EnumPayload via `infer_enum_payload_kind`).
/// - `Mutex<T>.get() → T` — receiver `ConcreteType::Mutex(T)` returns
///   `native_kind_from_concrete_type(T)`.
/// - `Atomic.load() / .fetch_add(d) / .fetch_sub(d) /
///   .compare_exchange(...)` — i64-only at landing per §2.7.25; return
///   Int64 unconditionally.
/// - `Lazy<T>.get() → T` — receiver `ConcreteType::Lazy(T)` returns
///   `native_kind_from_concrete_type(T)`.
///
/// Names outside this set return `None` — the slot's kind genuinely
/// isn't statically classifiable from the receiver+method pair alone,
/// per §2.7.7 (no Bool-default fallback).
///
/// The receiver's `ConcreteType` is sourced from `concrete_types[args[0]
/// .root_local()]` per §2.7.5 producing-site discipline. When the
/// receiver isn't a `Place::Local` projection (e.g. constant receiver,
/// no concrete_types entry), the classifier returns `None` — the
/// classifier is one of multiple kind sources at this point in the
/// inference pass, and surfacing-and-stopping isn't appropriate here
/// (other downstream passes still get a chance to stamp the slot).
///
/// # User-defined-trait surface boundary (Phase 3 cluster-0 Round 12 T1)
///
/// `ConcreteType::Struct(_)` receivers (user-defined `type X {}` values)
/// fall into the `_ => None` arm by design. Smoke 3
/// (`trait T { method name() -> string } type X {} impl T for X { method name()
/// { "x" } } let t = X {} print(t.name())`) requires `t.name()` to be
/// classified as `NativeKind::String` from the trait's declared return
/// type. The classifier cannot do this because the receiver kind-source
/// is structurally insufficient:
///
/// 1. The receiver slot's `ConcreteType` is `Struct(StructLayoutId(0))`
///    — the bytecode compiler's `concrete_type_from_annotation`
///    (`crates/shape-vm/src/compiler/v2_map_emission.rs:357`) returns
///    the `StructLayoutId(0)` placeholder for every user struct name
///    because the layout-id registry is not wired (the function's
///    `_ => None` arm at line 378 carries the comment "Phase 1.1 Agent 3
///    will fill this in"). So `concrete_types[receiver_slot]` does NOT
///    distinguish `X` from `Y` from `Point` from any other user struct.
/// 2. The trait registry (`TypeRegistry::traits: HashMap<String,
///    TraitDef>` in `crates/shape-runtime/src/type_system/environment/
///    registry.rs:111`) holds the trait's declared return type
///    (`TraitMemberSignature::Method { return_type: TypeAnnotation, .. }`),
///    but the `BytecodeProgram` (`crates/shape-vm/src/bytecode/
///    core_types.rs`) does NOT persist this — it only carries
///    `trait_method_symbols: HashMap<String, String>` (the resolved
///    function name per `(trait, type, impl, method)` key) and
///    `trait_vtables` (vtables keyed by `Trait::ConcreteType`). Neither
///    carries the declared trait method return type.
/// 3. The `function_return_concrete_types: Vec<ConcreteType>` side-table
///    (the parallel pattern §2.7.5 the JIT consumes for direct calls,
///    `core_types.rs:356`) is keyed on function index and built from
///    `FunctionDef.return_type` annotations
///    (`compiler_impl_reference_model.rs:1473`). For trait impl methods
///    desugared via `desugar_impl_method`
///    (`crates/shape-vm/src/compiler/statements.rs:1646`), the impl's
///    `method.return_type` is whatever the impl source declared — for
///    Smoke 3's `impl T for X { method name() { "x" } }` it is `None`
///    (the impl doesn't repeat the trait's `: string` annotation), so
///    `function_return_concrete_types[X::name] = ConcreteType::Void`.
///    The trait's declared return type does not propagate to the impl's
///    function definition.
///
/// Closing this surface requires extending the bytecode→JIT data
/// conduit — adding a new side-table on `BytecodeProgram` that
/// persists per-trait-method declared return `ConcreteType`s,
/// populated at impl-block compilation time from the type registry's
/// `TraitDef.members[*].Required(Method { return_type, .. })` and
/// `TraitDef.members[*].Default(MethodDef { return_type, .. })`
/// entries. This is a cross-crate extension (mirrors the existing
/// `function_return_concrete_types` pattern from Round-6 W12-jit-call-
/// return-kind close 2026-05-12) and is ADR amendment territory per
/// the agent prompt's surface-and-stop list ("If the trait registry
/// isn't accessible from the JIT MIR builder layer (cross-crate
/// boundary issue) — STOP and surface").
///
/// The pin tests `user_defined_trait_method_on_struct_returns_none`
/// and `user_defined_trait_method_call_terminator_remains_unstamped`
/// assert the surface — they are intentional surface pins, not
/// regressions to be papered over by a Bool-default fallback or a
/// hard-coded `"name"` → `String` arm.
fn parametric_method_return_kind_from_receiver(
    name: &str,
    args: &[Operand],
    concrete_types: &[ConcreteType],
) -> Option<NativeKind> {
    use shape_value::heap_value::HeapKind;
    // args[0] is the receiver per the MIR lowering convention
    // (`mir/lowering/expr.rs::Expr::MethodCall` pushes the receiver as
    // arg index 0). Constant receivers can't carry a ConcreteType slot
    // — no classification possible.
    let receiver = args.first()?;
    let receiver_slot = match receiver {
        Operand::Copy(p) | Operand::Move(p) | Operand::MoveExplicit(p) => p.root_local(),
        Operand::Constant(_) => return None,
    };
    let receiver_ct = concrete_types.get(receiver_slot.0 as usize)?;
    // Skip when the receiver slot's ConcreteType wasn't proven by the
    // upstream concrete-types conduit (the Void placeholder).
    if matches!(receiver_ct, ConcreteType::Void) {
        return None;
    }
    match (name, receiver_ct) {
        // ── Array element-typed accessors ──────────────────────────
        // `Array<T>.sum() / .mean() / .min() / .max()` return the
        // element type's scalar kind. The VM-side `array_basic.rs` /
        // `typed_array_methods.rs` PHF entries return
        // `KindedSlot::from_<elem>(...)` per receiver-element kind.
        // ADR-006 §2.7.5 / Round 8A receiver-recovery soundness:
        // the §2.7.5 carrier shape for the element is preserved
        // verbatim in the return value.
        ("sum" | "mean" | "min" | "max", ConcreteType::Array(elem)) => {
            native_kind_from_concrete_type(elem)
        }
        // `Array.get(i)` — returns element T directly (the VM-side
        // bounds-checked accessor; non-Option return).
        ("get", ConcreteType::Array(elem)) => native_kind_from_concrete_type(elem),
        // `Array.first() / .last() / .pop()` — return the bare element
        // kind directly. Phase 4b Round 4 W15 LANG-9-spin-3-first JIT
        // fix (ADR-006 §2.7.5 producer-side stamp).
        //
        // The VM-side PHF handlers (`executor/objects/typed_int_array_
        // methods::first / last / pop`, `typed_number_array_methods::
        // first / last / pop`) return a `KindedSlot` whose `kind` is the
        // ELEMENT kind for non-empty arrays (`Int64` / `Float64` / etc.)
        // and the `KindedSlot::none()` Bool/0 sentinel for empty arrays.
        // The previous mapping to `Ptr(HeapKind::Option)` here mismatched
        // the producer's stamp — JIT downstream consumers treated the
        // bare element bits (e.g. `Int64=2`) as an `Arc<OptionData>`
        // pointer and rendered "None" on print (pre-fix F3b reproducer
        // `[1,2,3,4,5].map(|x|x*2).first()` JIT=None vs VM=2).
        //
        // Per ADR-006 §2.7.5: the receiver's element type IS the proof
        // of the result kind. The PHF handler (producer) stamps the
        // element kind into its returned `KindedSlot`; the JIT codegen
        // (consumer) must use the same kind expectation. No tag-decode
        // bridge: VM PHF and JIT codegen share the producer-stamped
        // element kind from `ConcreteType::Array(elem)`.
        //
        // The empty-array Bool(0) sentinel case yields slot bits=0 with
        // kind=element; downstream `print` of an Int64=0 renders "0"
        // (NOT "None"). That is the existing PHF contract — the audit's
        // F3 reproducer `[1,2,3,4,5].first()` is non-empty, expected
        // result 1 (Int64); the empty-array Option<T> wrapping is a
        // separate semantic question tracked under a §2.7.17
        // Option-return-shape amendment, NOT the LANG-9-spin-3-first
        // territory.
        ("first" | "last" | "pop", ConcreteType::Array(elem)) => {
            native_kind_from_concrete_type(elem)
        }
        // ── HashMap.get ────────────────────────────────────────────
        // `HashMap<K, V>.get(k) → Option<V>` — the VM-side
        // `hashmap_methods::v2_get` returns
        // `KindedSlot::from_option(Arc<OptionData::some/none>(v))`.
        // Carrier kind is `Ptr(HeapKind::Option)`; the inner V flows
        // through EnumPayload at the destructure site.
        ("get", ConcreteType::HashMap(_, _)) => Some(NativeKind::Ptr(HeapKind::Option)),
        // ── HashMap.set / .delete / .merge ─────────────────────────
        // Phase 4b Round 5c-2-α HashMap-has-2-chain VM/JIT divergence
        // fix (v0.3-gating SOUNDNESS BUG ratified 2026-05-19). Per
        // ADR-006 §2.7.5 producer-side stamp, the VM-side handlers
        // (`hashmap_methods::v2_set` at line 789, `v2_delete` at 1235,
        // `v2_merge` at 1469) all return
        // `KindedSlot::from_hashmap(...)` — carrier kind
        // `Ptr(HeapKind::HashMap)`. Pre-fix the JIT call-terminator
        // stamping loop (`infer_slot_kinds_with_concrete` ~331) had no
        // entry for these mutators, so the chained-set destination
        // slot's kind stayed `None` → fell back to `UInt64` carrier in
        // `operand_slot_kind_or_carrier` at the next call's receiver
        // push → `jit_call_method` shell's delegation predicate (line
        // 665 `NativeKind::UInt64 => false`) routed to legacy JIT-
        // format dispatch → `read_heap_kind` on `Arc::into_raw(Arc<
        // HashMapKindedRef>)` bits returned garbage → dispatch fell
        // into `_ => TAG_NULL` (line 878) → `try_call_user_method`
        // declined → final TAG_NULL bits interpreted as Bool=false by
        // the destination `kinds[idx]=Some(Bool)` (from
        // `well_known_method_return_kind("has")`). Empirical
        // reproducer at HEAD 7eb82205: `HashMap().set("a",1)
        // .set("b",2).has("a")` was VM=true / JIT=false. Post-fix:
        // each mutator stamps the destination slot
        // `Ptr(HeapKind::HashMap)`, so the next `.set` or `.has`
        // receiver kind is the right Ptr arm and `jit_call_method`
        // delegates to VM through the §2.7.10 / Q11 path.
        ("set" | "delete" | "merge", ConcreteType::HashMap(_, _)) => {
            Some(NativeKind::Ptr(HeapKind::HashMap))
        }
        // ── HashSet.add / .delete / .union / .intersection / ───────
        //    .difference ──────────────────────────────────────────
        // Phase 4b Round 5c-2-β-α collection-mutator-chain VM/JIT
        // divergence fix (v0.3-gating SOUNDNESS BUG ratified
        // 2026-05-20; sister-class of the HashMap-has-2-chain fix
        // immediately above). Per ADR-006 §2.7.5 producer-side stamp,
        // the VM-side handlers in `set_methods.rs` —
        // `v2_add` (line 259, `MUT_SELF_HASHSET_METHODS`),
        // `v2_delete`, `v2_union` (312), `v2_intersection` (341),
        // `v2_difference` (374) — all return
        // `KindedSlot::from_hashset(...)`, carrier kind
        // `Ptr(HeapKind::HashSet)`. (`add` / `delete` return the
        // mutated receiver Arc; `union` / `intersection` /
        // `difference` return a fresh result set — both produce the
        // same `Ptr(HeapKind::HashSet)` carrier, mirror of how the
        // HashMap arm covers self-returning `set` / `delete`
        // alongside set-valued `merge`.) Pre-fix the chain-temp
        // slot's kind stayed `None` → `UInt64` carrier fallback →
        // `jit_call_method` legacy-format dispatch → `read_heap_kind`
        // garbage → `_ => TAG_NULL` → the final `.has()` Bool
        // consumer rendered `false`. Empirical reproducer at HEAD
        // db3668c5: `Set().add("a").add("b").has("a")` was VM=true /
        // JIT=false (the 1-chain `Set().add("a").has("a")` also
        // diverged — same root cause as the HashMap 1-chain).
        (
            "add" | "delete" | "union" | "intersection" | "difference",
            ConcreteType::HashSet(_),
        ) => Some(NativeKind::Ptr(HeapKind::HashSet)),
        // ── Deque.pushBack / .pushFront ────────────────────────────
        // Phase 4b Round 5c-2-β-α collection-mutator-chain fix. The
        // VM-side handlers `deque_methods::v2_push_back` (line 308)
        // and `v2_push_front` (327) — both `MUT_SELF_DEQUE_METHODS`
        // members — return `KindedSlot::from_deque(...)`, carrier
        // kind `Ptr(HeapKind::Deque)`. (`popBack` / `popFront` are
        // tuple-return — they return the popped element, not the
        // deque — so they stay off this arm, mirror of the
        // `MUT_SELF_TUPLE_RETURN_DEQUE_METHODS` exclusion.) Empirical
        // reproducer at HEAD db3668c5:
        // `Deque().pushBack(1).pushBack(2).size()` was VM=2 /
        // JIT=garbage `-1407374883553280`.
        ("pushBack" | "pushFront", ConcreteType::Deque(_)) => {
            Some(NativeKind::Ptr(HeapKind::Deque))
        }
        // ── PriorityQueue.push ─────────────────────────────────────
        // Phase 4b Round 5c-2-β-α collection-mutator-chain fix. The
        // VM-side handler `priority_queue_methods::v2_push` (line
        // 235) — the sole `MUT_SELF_PRIORITY_QUEUE_METHODS` member —
        // returns `KindedSlot::from_priority_queue(...)`, carrier
        // kind `Ptr(HeapKind::PriorityQueue)`. (`pop` is tuple-return
        // per `MUT_SELF_TUPLE_RETURN_PRIORITY_QUEUE_METHODS` — stays
        // off this arm.) Empirical reproducer at HEAD db3668c5:
        // `PriorityQueue().push(5).push(3).size()` was VM=2 /
        // JIT=garbage `-1407374883553280`.
        ("push", ConcreteType::PriorityQueue) => {
            Some(NativeKind::Ptr(HeapKind::PriorityQueue))
        }
        // ── Channel.send / .close ──────────────────────────────────
        // Phase 4b Round 5c-2-β-α collection-mutator-chain fix. The
        // VM-side handlers `channel_methods::v2_channel_send` (line
        // 98) and `v2_channel_close` (193) both return
        // `KindedSlot::from_channel(...)`, carrier kind
        // `Ptr(HeapKind::Channel)` (the receiver share). `send` /
        // `close` aren't in a `MUT_SELF_*` writeback set —
        // `ChannelData` carries interior mutability via
        // `Mutex<ChannelInner>` so mutations are observed through any
        // Arc share with no slot writeback needed — but they ARE
        // chainable self-returns. Pre-fix the chain-temp kind stayed
        // `None` → `UInt64` carrier → legacy dispatch →
        // wrong-type `Arc<ChannelData>` retain/release. Empirical
        // reproducer at HEAD db3668c5 (hot-loop JIT-compiled):
        // `Channel().send(7).send(9).try_recv()` SIGSEGV'd under JIT
        // (use-after-free on the mis-dispatched `Arc<ChannelData>`)
        // vs VM correct.
        ("send" | "close", ConcreteType::Channel(_)) => {
            Some(NativeKind::Ptr(HeapKind::Channel))
        }
        // ── Mutex.get ──────────────────────────────────────────────
        // `Mutex<T>.get() → T` per §2.7.25. The VM-side
        // `executor/objects/mutex_methods::v2_get` clones the inner
        // `KindedSlot::value` payload — the §2.7.5 carrier shape for
        // the inner T is preserved verbatim.
        ("get", ConcreteType::Mutex(inner)) => native_kind_from_concrete_type(inner),
        // ── Atomic.load / fetch_add / fetch_sub / compare_exchange ─
        // `Atomic` is i64-only at landing per §2.7.25; every return
        // path produces a raw i64 (the `AtomicI64::load` / `fetch_*`
        // result). Pre-typed-payload-amendment all four method names
        // surface Int64.
        (
            "load" | "fetch_add" | "fetch_sub" | "compare_exchange",
            ConcreteType::Atomic,
        ) => Some(NativeKind::Int64),
        // ── Lazy.get ───────────────────────────────────────────────
        // `Lazy<T>.get() → T` per §2.7.25. The cached value's
        // `KindedSlot::value` payload is cloned from `LazyInner.value`
        // after first-init; same receiver-recovery shape as Mutex.
        ("get", ConcreteType::Lazy(inner)) => native_kind_from_concrete_type(inner),
        _ => None,
    }
}

/// Phase 4b Round 5c-2-α HashMap-has-2-chain VM/JIT divergence fix
/// (v0.3-gating SOUNDNESS BUG ratified 2026-05-19).
///
/// ADR-006 §2.7.5 producer-side stamp companion of
/// `parametric_method_return_kind_from_receiver` for the case where the
/// receiver slot's `ConcreteType` is `Void` (no bytecode-compiler
/// concrete-type seed) but the in-pass `kinds[]` track has already
/// classified the receiver's `NativeKind` from an upstream source.
///
/// Load-bearing for chained collection-mutator patterns like
/// `HashMap().set("a",1).set("b",2).has("a")`: the bare-form `HashMap()`
/// ctor receiver gets `Ptr(HeapKind::HashMap)` from the `EnumStore` arm
/// (`types.rs` ~559), but the next `.set(...)` call's destination slot
/// has no ConcreteType entry (the bytecode compiler's concrete-type
/// inference doesn't propagate through method-call return types). With
/// only the ConcreteType-keyed classifier, the chain temp's kind stays
/// `None` → next `.set` / `.has` receiver kind falls back to `UInt64`
/// carrier → `jit_call_method` shell's delegation predicate routes to
/// legacy JIT-format dispatch which doesn't recognize the
/// `Arc::into_raw(Arc<HashMapKindedRef>)` bits → silent TAG_NULL →
/// downstream Bool-kind consumer renders `false`.
///
/// This helper reads the receiver's NativeKind directly from `kinds[]`
/// and classifies HashMap mutator returns (`set` / `delete` / `merge`)
/// — each VM-side handler returns `KindedSlot::from_hashmap(...)` per
/// `hashmap_methods.rs` (v2_set at 789, v2_delete at 1235, v2_merge at
/// 1469). Per §2.7.5: the receiver's `Ptr(HeapKind::HashMap)` kind IS
/// the proof the result is also `Ptr(HeapKind::HashMap)`.
///
/// The companion call-stamp loop in `infer_slot_kinds_with_concrete`
/// runs iteratively until fixpoint (mirrors the existing collection-
/// alias propagation pattern at line 651-687) so chain temps propagate
/// from the EnumStore-stamped ctor receiver through arbitrary chain
/// depth.
fn method_return_kind_from_in_pass_kinds(
    name: &str,
    args: &[Operand],
    kinds: &[Option<NativeKind>],
) -> Option<NativeKind> {
    use shape_value::heap_value::HeapKind;
    let receiver = args.first()?;
    let receiver_slot = match receiver {
        Operand::Copy(p) | Operand::Move(p) | Operand::MoveExplicit(p) => p.root_local(),
        Operand::Constant(_) => return None,
    };
    let receiver_kind = kinds.get(receiver_slot.0 as usize).and_then(|k| *k)?;
    match (name, receiver_kind) {
        // HashMap mutators returning self for chaining. See
        // `parametric_method_return_kind_from_receiver` "HashMap.set /
        // .delete / .merge" arm for the VM-side handler citations.
        ("set" | "delete" | "merge", NativeKind::Ptr(HeapKind::HashMap)) => {
            Some(NativeKind::Ptr(HeapKind::HashMap))
        }
        // HashSet / Deque / PriorityQueue / Channel mutator-chain
        // links — Phase 4b Round 5c-2-β-α collection-mutator-chain
        // VM/JIT divergence fix (v0.3-gating SOUNDNESS BUG ratified
        // 2026-05-20; sister-class of the HashMap-has-2-chain arm
        // above). Each receiver-kind / method-name pair mirrors the
        // corresponding `parametric_method_return_kind_from_receiver`
        // arm — VM-side handler citations are in that function's
        // comments. `add` / `delete` (HashSet), `pushBack` /
        // `pushFront` (Deque), `push` (PriorityQueue), `send` /
        // `close` (Channel) return the (mutated) receiver Arc;
        // `union` / `intersection` / `difference` (HashSet) return a
        // fresh result set — both shapes carry
        // `Ptr(HeapKind::<CollectionType>)`. This in-pass-kinds
        // classifier is the load-bearing one for bare-form ctors
        // (`Set()` / `Deque()` / `PriorityQueue()` / `Channel()`)
        // whose receiver `ConcreteType` is `Struct(_)`/`Void` (not
        // the typed-Arc collection type) — the EnumStore arm seeds
        // the ctor temp's `kinds[]` slot, and this fixpoint pass
        // propagates `Ptr(HeapKind::*)` through each chain link.
        (
            "add" | "delete" | "union" | "intersection" | "difference",
            NativeKind::Ptr(HeapKind::HashSet),
        ) => Some(NativeKind::Ptr(HeapKind::HashSet)),
        ("pushBack" | "pushFront", NativeKind::Ptr(HeapKind::Deque)) => {
            Some(NativeKind::Ptr(HeapKind::Deque))
        }
        ("push", NativeKind::Ptr(HeapKind::PriorityQueue)) => {
            Some(NativeKind::Ptr(HeapKind::PriorityQueue))
        }
        ("send" | "close", NativeKind::Ptr(HeapKind::Channel)) => {
            Some(NativeKind::Ptr(HeapKind::Channel))
        }
        _ => None,
    }
}

/// ADR-006 §2.7.5 element-kind projection for `Place::Index` reads.
///
/// When the Rvalue is `Use(Copy(Index(arr_slot, _)))` (or `Move` /
/// `MoveExplicit` variants) and the receiver slot's `ConcreteType` is
/// `Array(elem)` with a scalar element kind, project the destination's
/// `NativeKind` from the element. Returns `None` for non-Index sources,
/// non-`Place::Local` receivers, or array slots whose `ConcreteType` is
/// not a scalar `Array` (the kind is genuinely not statically classifiable
/// at the producing-MIR layer in those cases).
///
/// This is the kind-source the legacy opaque-projection rule papered
/// over by leaving the destination slot's kind as `None`, which then
/// fell through to the kind-blind print decoder. With strict typing,
/// `Array<int>[i]` proves the destination's kind at JIT-compile time.
///
/// Currently unused after the Round 5A + 5C merge: the more general
/// `infer_rvalue_kind_with_projections` (5A) covers the same Index
/// projection via `concrete_types`. Retained as documentation of the
/// 5C-side helper shape in case a future caller needs the standalone
/// projection without Field threading.
#[allow(dead_code)]
fn infer_index_element_kind(
    rvalue: &Rvalue,
    concrete_types: &[ConcreteType],
) -> Option<NativeKind> {
    let operand = match rvalue {
        Rvalue::Use(op) => op,
        _ => return None,
    };
    let place = match operand {
        Operand::Copy(p) | Operand::Move(p) | Operand::MoveExplicit(p) => p,
        Operand::Constant(_) => return None,
    };
    let (arr_place, _index) = match place {
        Place::Index(arr, idx) => (arr.as_ref(), idx),
        _ => return None,
    };
    let arr_slot = match arr_place {
        Place::Local(slot) => *slot,
        _ => return None,
    };
    let ct = concrete_types.get(arr_slot.0 as usize)?;
    let ConcreteType::Array(elem) = ct else {
        return None;
    };
    elem_slot_kind_for_concrete(elem)
}

/// F7.c — `true` when `operand` reads through a heap projection
/// (`Place::Field` / `Place::Index` / `Place::Deref`). The runtime type
/// of such a read is opaque to the compiler; backward type propagation
/// must not invent a `NativeKind` for the destination slot from unrelated
/// uses of that slot in later binops.
fn is_opaque_operand(operand: &Operand) -> bool {
    match operand {
        Operand::Copy(place) | Operand::Move(place) | Operand::MoveExplicit(place) => {
            is_opaque_place(place)
        }
        Operand::Constant(_) => false,
    }
}

/// Walk a `Place` — `true` if any projection in the chain is a field
/// read, index read, or deref. Pure `Place::Local` chains stay typed.
fn is_opaque_place(place: &Place) -> bool {
    match place {
        Place::Local(_) => false,
        Place::Field(_, _) | Place::Index(_, _) | Place::Deref(_) => true,
    }
}

/// If `operand` is a direct `Copy`/`Move` of a local, return the slot's index.
/// Only handles the simple `Place::Local` form — projections (field/index) do
/// not participate in the backward type propagation.
fn operand_local_slot(operand: &Operand) -> Option<usize> {
    match operand {
        Operand::Copy(Place::Local(slot))
        | Operand::Move(Place::Local(slot))
        | Operand::MoveExplicit(Place::Local(slot)) => Some(slot.0 as usize),
        _ => None,
    }
}

/// Set `kinds[idx] = Some(kind)` if the slot was previously
/// undetermined (`None`), returning `true` when an update happened.
fn set_kind_if_unknown(kinds: &mut [Option<NativeKind>], idx: usize, kind: NativeKind) -> bool {
    if idx < kinds.len() && kinds[idx].is_none() {
        kinds[idx] = Some(kind);
        true
    } else {
        false
    }
}

/// Infer the NativeKind produced by an Rvalue.
fn infer_rvalue_kind(rvalue: &Rvalue, kinds: &[Option<NativeKind>]) -> Option<NativeKind> {
    infer_rvalue_kind_with_fields(rvalue, kinds, None, None)
}

/// Project-aware version of `infer_rvalue_kind`: see
/// `infer_operand_kind_with_fields` for the rationale. `Use(Move(Field))`
/// / `Use(Copy(Field))` route the destination slot's kind to the FIELD's
/// kind (per `field_kinds`) rather than the base struct's heap kind.
#[allow(dead_code)]
fn infer_rvalue_kind_with_fields(
    rvalue: &Rvalue,
    kinds: &[Option<NativeKind>],
    field_kinds: Option<&std::collections::HashMap<String, NativeKind>>,
    field_name_table: Option<&std::collections::HashMap<FieldIdx, String>>,
) -> Option<NativeKind> {
    infer_rvalue_kind_with_projections(rvalue, kinds, field_kinds, field_name_table, None)
}

/// Full project-aware Rvalue kind inference: Field via `field_kinds` +
/// Index via `concrete_types`'s `Array<scalar>` shape. Used by
/// `infer_slot_kinds_with_concrete` for top-level MIR compilation where
/// the bytecode compiler's `concrete_types` side-table is available.
fn infer_rvalue_kind_with_projections(
    rvalue: &Rvalue,
    kinds: &[Option<NativeKind>],
    field_kinds: Option<&std::collections::HashMap<String, NativeKind>>,
    field_name_table: Option<&std::collections::HashMap<FieldIdx, String>>,
    concrete_types: Option<&[ConcreteType]>,
) -> Option<NativeKind> {
    match rvalue {
        Rvalue::Use(operand) => infer_operand_kind_with_projections(
            operand,
            kinds,
            field_kinds,
            field_name_table,
            concrete_types,
        ),
        Rvalue::BinaryOp(op, lhs, rhs) => {
            let lk = infer_operand_kind_with_projections(
                lhs,
                kinds,
                field_kinds,
                field_name_table,
                concrete_types,
            );
            let rk = infer_operand_kind_with_projections(
                rhs,
                kinds,
                field_kinds,
                field_name_table,
                concrete_types,
            );
            match (lk, rk) {
                (Some(l), Some(r)) if l == r => {
                    // Both operands same type.
                    // Arithmetic on floats → float, on ints → int.
                    // Comparisons always → Bool.
                    if is_comparison_op(op) {
                        Some(NativeKind::Bool)
                    } else {
                        Some(l)
                    }
                }
                _ => {
                    // Mixed or unknown operands. Comparison still → Bool.
                    if is_comparison_op(op) {
                        Some(NativeKind::Bool)
                    } else {
                        None
                    }
                }
            }
        }
        Rvalue::UnaryOp(UnOp::Neg, operand) => infer_operand_kind_with_projections(
            operand,
            kinds,
            field_kinds,
            field_name_table,
            concrete_types,
        ),
        // W14.2-A1 (Phase 4b, 2026-05-18): `BitNot` propagates the operand
        // kind — Int64 in / Int64 out per the VM's `BitNotInt` typed opcode
        // at `arithmetic/mod.rs:229`. Same `infer_operand_kind_with_projections`
        // shape as `UnOp::Neg` above. `None` operand kind surfaces unstamped
        // per §2.7.7 #9 / forbidden #9 (no fabricated default).
        Rvalue::UnaryOp(UnOp::BitNot, operand) => infer_operand_kind_with_projections(
            operand,
            kinds,
            field_kinds,
            field_name_table,
            concrete_types,
        ),
        // W10 jit-call-method-user-trait-fix (2026-05-17): when the
        // operand is a user-struct receiver (`Ptr(HeapKind::TypedObject)`),
        // the `!x` lowering routes through the `Not::not(self) -> Self`
        // trait method, returning the same user-struct kind. The legacy
        // `Bool` arm only fires for the built-in `!bool` form (where
        // the operand's kind is `Bool` already).
        Rvalue::UnaryOp(UnOp::Not, operand) => {
            let op_kind = infer_operand_kind_with_projections(
                operand,
                kinds,
                field_kinds,
                field_name_table,
                concrete_types,
            );
            // User-struct receiver → trait dispatch returns Self (same
            // pointer kind). Any other operand kind → built-in `!bool`
            // (Bool result by construction). `None` operand kind →
            // surface unstamped per §2.7.7 #9 / forbidden #9 (no
            // fabricated default).
            match op_kind {
                Some(shape_value::NativeKind::Ptr(_)) => op_kind,
                Some(_) => Some(NativeKind::Bool),
                None => None,
            }
        }
        Rvalue::Clone(operand) => infer_operand_kind_with_projections(
            operand,
            kinds,
            field_kinds,
            field_name_table,
            concrete_types,
        ),
        Rvalue::Borrow(_, _) => None,     // References are heap pointers
        Rvalue::Aggregate(_) => None,      // Arrays are heap objects
        // EnumTest emits a native Bool — kind is Bool by construction
        // per the JIT consumer's `jit_arc_result_is_ok` / `_is_some`
        // signature (returns I8 / `NativeKind::Bool`).
        Rvalue::EnumTest { .. } => Some(NativeKind::Bool),
        // EnumPayload extracts the inner payload bits from
        // `Arc<ResultData>` / `Arc<OptionData>`. The payload's kind is
        // classified at the OPERAND's source via 6A's call-return-kind
        // conduit — `concrete_types[base_slot]` holds the
        // `ConcreteType::Result(Ok_inner, Err_inner)` /
        // `ConcreteType::Option(Some_inner)` for a slot bound to a
        // function-call result. The variant tag selects which arm's
        // inner type to project.
        //
        // When the projection succeeds, the inner type maps to a
        // `NativeKind` via `concrete_to_native_kind` (existing helper).
        // When the operand's `concrete_types` entry isn't `Result(_,_)`
        // / `Option(_)` (e.g. opaque source), returning `None` lets
        // bidirectional inference pick up the kind from downstream uses
        // — not a Bool-default fallback per §2.7.7 #9.
        //
        // Producer-site classification chains via:
        //   `Ok(a/b)` emit → EnumStore[r, var:Ok, op:a/b] → r is
        //   Arc<ResultData> → caller's `let r = divide(...)` slot has
        //   `concrete_types[r] = Result(I64, String)` via 6A → in
        //   downstream `match r { Ok(v) => ... }`, the binding's
        //   `EnumPayload { operand: Copy(r), variant: Ok }` reads
        //   `concrete_types[r].ok_arm` = I64 → v's slot kind = Int64.
        Rvalue::EnumPayload { operand, variant } => {
            infer_enum_payload_kind(operand, *variant, concrete_types)
        }
        // TypePatternTest emits a native Bool — kind is Bool by
        // construction. The JIT consumer surfaces-and-stops on this
        // Rvalue today (preflight rejects it), but the destination slot's
        // kind is still well-defined per ADR-006 §2.7.5 producer-side
        // classification; downstream MIR passes (kind-flow inference,
        // SwitchBool operand classification) see the same Bool stamp
        // whether or not the JIT reaches codegen for the body. W15.2-LANG-5.
        Rvalue::TypePatternTest { .. } => Some(NativeKind::Bool),
        // EnumDiscriminantTest emits a native Bool — kind is Bool by
        // construction (mirror of the TypePatternTest arm above). The JIT
        // consumer surfaces-and-stops on this Rvalue today (preflight
        // rejects it); the destination slot's kind is still well-defined
        // per ADR-006 §2.7.5 producer-side classification. W15.2-LANG-1.
        Rvalue::EnumDiscriminantTest { .. } => Some(NativeKind::Bool),
    }
}

/// Project an EnumPayload Rvalue to the destination slot's kind.
/// Reads `concrete_types[operand.root_local()]` and dispatches on the
/// `VariantTag` to select the arm's inner `ConcreteType`, then maps to
/// `NativeKind` via the scalar-kind helper.
///
/// Returns `None` when:
/// - The operand isn't a `Place::Local` projection (e.g. constant or
///   complex projection) — no concrete_types entry exists.
/// - The operand slot's `ConcreteType` isn't `Result(_,_)` / `Option(_)`
///   (e.g. opaque receiver, intermediate temp before the 6A conduit's
///   propagation pass).
/// - The arm's inner `ConcreteType` doesn't map to a scalar
///   `NativeKind` (e.g. nested heap container — the EnumPayload returns
///   the raw inner-Arc bits and the destination slot kind would be a
///   Ptr; the §2.7.5 conduit hasn't yet stamped Ptr arms for inner
///   types but the upcoming 6A propagation does).
/// Project an `EnumPayload` Rvalue to the destination slot's `NativeKind`
/// per ADR-006 §2.7.5 producing-site classification + §2.7.17 receiver-
/// recovery soundness.
///
/// `jit_arc_result_payload` / `jit_arc_option_payload` extract the inner
/// `KindedSlot.slot.raw()` from the typed-Arc carrier. The returned bits
/// preserve the inner's §2.7.5 carrier shape verbatim — for an `Int64`
/// inner the bits are raw native i64; for a `String` inner the bits are
/// `Arc::into_raw(Arc<String>) as u64`; for a `Ptr(HeapKind::*)` inner
/// the bits are the corresponding typed-Arc raw pointer.
///
/// This classifier uses `native_kind_from_concrete_type` (the full
/// ConcreteType → NativeKind mapping) rather than the more restrictive
/// `elem_slot_kind_for_concrete` (which only handles scalar arms for the
/// v2 typed-array fast path) because the inner carrier coming out of
/// `jit_arc_*_payload` IS the §2.7.5-shaped raw bits + kind label for
/// every NativeKind variant. Pre-Round-8A this used the scalar-only
/// classifier, which left `Err(String)` / `Some(typed_object)` payload
/// slots without a kind stamp; the consumer-side print dispatch then
/// surfaced as `kind_hint = None` and routed through the kind-blind
/// `jit_print` fallback — the W-series defection pattern this round
/// closes.
///
/// Returns `None` only when:
/// - operand isn't a `Place::Local` projection — no `concrete_types[idx]`
///   to read (e.g. `Operand::Constant(_)`),
/// - the operand slot's ConcreteType isn't `Result(_,_)` / `Option(_)` —
///   producer-side gap upstream of EnumPayload,
/// - the arm's inner ConcreteType is `Void` (None variant of an Option,
///   or unmatched Err arm of an Ok-only Result) — no payload exists.
fn infer_enum_payload_kind(
    operand: &Operand,
    variant: VariantTag,
    concrete_types: Option<&[ConcreteType]>,
) -> Option<NativeKind> {
    let concrete_types = concrete_types?;
    let place = match operand {
        Operand::Copy(p) | Operand::Move(p) | Operand::MoveExplicit(p) => p,
        Operand::Constant(_) => return None,
    };
    let base_slot = place.root_local();
    let ct = concrete_types.get(base_slot.0 as usize)?;
    let inner: &ConcreteType = match (variant, ct) {
        (VariantTag::Ok, ConcreteType::Result(ok, _)) => ok.as_ref(),
        (VariantTag::Err, ConcreteType::Result(_, err)) => err.as_ref(),
        (VariantTag::Some_, ConcreteType::Option(inner)) => inner.as_ref(),
        // None has no payload — kind isn't meaningful.
        _ => return None,
    };
    native_kind_from_concrete_type(inner)
}

/// Infer the NativeKind of an operand.
fn infer_operand_kind(operand: &Operand, kinds: &[Option<NativeKind>]) -> Option<NativeKind> {
    infer_operand_kind_with_fields(operand, kinds, None, None)
}

/// W12-jit-binop-after-heap-read-kind-tracker: project through
/// `Place::Field` / `Place::Index` so `infer_slot_kinds` produces the
/// correct destination kind for `Assign(slot, Use(Move(Field(_, _))))`
/// and `Assign(slot, Use(Copy(Index(_, _))))`.
///
/// Without projection, the destination slot inherits the BASE's kind
/// (typically `Ptr(HeapKind::TypedObject)` for a struct base or
/// `Ptr(HeapKind::TypedArray)` for an array base) — but the value
/// actually moved/copied is the FIELD or ELEMENT, whose kind is
/// orthogonal to the base's. The wrong inference makes the destination
/// slot `Ptr(HeapKind::TypedObject)`, which the bytecode-compiler-
/// authoritative `LocalTypeInfo::NonCopy` path then dispatches as
/// refcounted at `release_old_value_if_heap` — and the initial-zero or
/// later-stored field value (e.g. `i64=3`) gets passed to `arc_release`
/// /  `arc_retain` as a raw pointer, segfaulting.
///
/// Sources:
/// - `field_kinds`: the producer-side map from `infer_field_native_kinds`
///   (populated by walking `StatementKind::ObjectStore { operands,
///   field_names }`). For `Place::Field(_, FieldIdx)`, project via
///   `field_name_table[FieldIdx] → name → field_kinds[name]`.
/// - `field_name_table`: passed from the MIR for the `FieldIdx → name`
///   translation. When `None` (the `infer_field_native_kinds` pre-pass
///   that uses constant-only slot kinds), Field projection is skipped
///   and the function falls back to `root_local()` — the same shape as
///   the pre-W12 path.
/// - `Place::Index(_, _)`: not threaded into MIR-level inference yet.
///   The JIT-side `place_native_kind` (in `rvalues.rs`) projects through
///   `concrete_types`'s `Array<scalar>` shape at JIT codegen time;
///   adding the same projection here would require threading
///   `concrete_types` into `infer_slot_kinds` (cross-tier flow). For
///   cluster-0's load-bearing smokes (Smoke 3 field-add and array-
///   scalar smoke `xs[0] + xs[1]`), the Array case is covered by the
///   JIT-side projection alone — the destination slot of
///   `Use(Copy(Index(_, _)))` doesn't drive a refcount-dispatch bug
///   because v2 typed-array slots route through the
///   `RefcountDisposition::Skip_TypedCellCarrier` arm (per
///   `ownership.rs:99`) before reaching the `slot_kind` discriminator.
///   If a future smoke surfaces a similar refcount-on-element-read bug,
///   thread `concrete_types` here.
fn infer_operand_kind_with_fields(
    operand: &Operand,
    kinds: &[Option<NativeKind>],
    field_kinds: Option<&std::collections::HashMap<String, NativeKind>>,
    field_name_table: Option<&std::collections::HashMap<FieldIdx, String>>,
) -> Option<NativeKind> {
    infer_operand_kind_with_projections(
        operand,
        kinds,
        field_kinds,
        field_name_table,
        None,
    )
}

/// Project-aware kind classification with both Field (via `field_kinds`)
/// and Index (via `concrete_types`'s `Array<scalar>` shape).
///
/// `Place::Index(base, _)`: when `concrete_types[base.root_local()] =
/// Array(elem)` with a scalar `elem`, the element kind is `elem` mapped
/// through `elem_slot_kind_for_concrete`. This mirrors the JIT codegen-
/// side `v2_typed_array_elem_kind` projection that drives the typed
/// array load path — same kind source, both consumer sites.
///
/// Without this projection, the destination slot of `Use(Copy(Index(
/// xs_TypedArray, _)))` inherits `xs`'s `Ptr(HeapKind::TypedArray)` kind,
/// then `print(slot)` falls through `print_i64/f64/bool` to the kind-
/// blind `jit_print` fallback, which decodes the raw int as f64 and
/// prints a denormalized garbage. Threading the element kind to the
/// destination slot makes `print` pick the matching `print_i64` /
/// `print_f64` arm and produce the correct output.
fn infer_operand_kind_with_projections(
    operand: &Operand,
    kinds: &[Option<NativeKind>],
    field_kinds: Option<&std::collections::HashMap<String, NativeKind>>,
    field_name_table: Option<&std::collections::HashMap<FieldIdx, String>>,
    concrete_types: Option<&[ConcreteType]>,
) -> Option<NativeKind> {
    match operand {
        Operand::Constant(c) => infer_constant_kind(c),
        Operand::Copy(place) | Operand::Move(place) | Operand::MoveExplicit(place) => {
            if let (Place::Field(_, field_idx), Some(fk), Some(fnt)) =
                (place, field_kinds, field_name_table)
            {
                if let Some(name) = fnt.get(field_idx) {
                    if let Some(k) = fk.get(name).copied() {
                        return Some(k);
                    }
                }
                // Field projection without a stamped kind: fall through
                // to root-local lookup (the pre-W12 behaviour). Caller
                // surfaces `None` honestly if the root lookup also fails.
            }
            if let (Place::Index(base, _), Some(cts)) = (place, concrete_types) {
                let base_slot = base.root_local();
                if let Some(elem_kind) = is_v2_typed_array_slot(cts, base_slot.0) {
                    return Some(elem_kind);
                }
                // Index without a proven Array<scalar> shape: fall
                // through to root-local lookup. Caller surfaces None
                // honestly if the root lookup also fails.
            }
            let slot = place.root_local();
            let idx = slot.0 as usize;
            kinds.get(idx).copied().flatten()
        }
    }
}

/// Producing-site field-kind classification per ADR-006 §2.7.5
/// stamp-at-compile-time discipline (W12-jit-binop-after-heap-read-kind-
/// tracker close, 2026-05-12).
///
/// Walk the MIR for every `StatementKind::ObjectStore { container_slot,
/// operands, field_names }` and stamp `field_native_kinds[name]` with the
/// operand's MIR-inferred `NativeKind`. This makes `Place::Field(base,
/// field_idx)` reads have a proven kind at JIT compile time, threading
/// the kind from the struct-literal producer into downstream `BinaryOp`
/// lowering without runtime tag-bit decode.
///
/// Each operand's kind is sourced from the already-computed `slot_kinds`
/// (which `infer_slot_kinds` produced from MIR-observable constants and
/// `ConcreteType` seeds). For `Constant` operands, classification comes
/// from `infer_constant_kind`. When an operand's kind is unprovable
/// (`None`), the field is NOT stamped — downstream consumers of
/// `field_native_kinds` get `None` and the JIT honestly surfaces the gap
/// at the BinaryOp call site rather than papering with a Bool-default
/// (§2.7.7 #9 forbidden rationalization).
///
/// The map is keyed by field NAME (not `FieldIdx`) to match the existing
/// `field_byte_offsets` keying — the JIT's `field_name_table` translates
/// `FieldIdx → String` at the field-read site, and we look up by name
/// here. Same fragility as `field_byte_offsets`: if two different struct
/// types share a field name with differing types, last-writer-wins. For
/// the Smoke 3 case (`Point.x: int`, `Point.y: int`) and the load-
/// bearing cluster-0 close criterion, this is sufficient. A schema-aware
/// (StructLayoutId-keyed) registry is the principled long-term shape,
/// but adding one is out-of-scope for this sub-cluster — see also
/// `field_byte_offsets`'s identical structural fragility.
///
/// `ObjectStore` is the structural kind source — the same statement
/// that's responsible for materializing the TypedObject in the v2 fast
/// path. By stamping field kinds here we mirror the producer-side
/// classification the §2.7.5 conduit already does for the destination
/// slot's `ConcreteType` (via the `infer_top_level_concrete_types_from_mir`
/// pass in `crates/shape-vm/src/compiler/helpers.rs`), one layer down
/// in the type structure.
pub(crate) fn infer_field_native_kinds(
    mir: &MirFunction,
    slot_kinds: &[Option<NativeKind>],
) -> std::collections::HashMap<String, NativeKind> {
    let mut field_kinds: std::collections::HashMap<String, NativeKind> =
        std::collections::HashMap::new();
    for block in &mir.blocks {
        for stmt in &block.statements {
            if let StatementKind::ObjectStore {
                operands,
                field_names,
                ..
            } = &stmt.kind
            {
                for (op, name) in operands.iter().zip(field_names.iter()) {
                    if name.is_empty() {
                        // Spreads / unnamed positional operands have no
                        // field name in the JIT's flat name→kind map.
                        // The field_byte_offsets walk skips them too.
                        continue;
                    }
                    if let Some(kind) = infer_operand_kind(op, slot_kinds) {
                        field_kinds.insert(name.clone(), kind);
                    }
                }
            }
        }
    }
    field_kinds
}

/// Infer the NativeKind of a constant.
///
/// ADR-006 §2.7.5 / §2.7.11/Q12 producing-site classification:
/// - `Function(_)`: the JIT-internal `box_function(fn_id)` shape — carrier
///   kind `UInt64` (the function-id-class callee-classification kind also
///   used at the §2.7.5 stable-FFI boundary).
/// - `Method(_)`: heap String carrier (`Arc<String>` raw pointer).
/// - `ClosurePlaceholder`: forward-reference for a closure slot —
///   `Ptr(HeapKind::Closure)` per §2.7.11/Q12.
/// - `None`: the unit/null value — kind genuinely unknown; callers
///   surface-and-stop per §2.7.7 #9.
fn infer_constant_kind(constant: &MirConstant) -> Option<NativeKind> {
    match constant {
        MirConstant::Float(_) => Some(NativeKind::Float64),
        MirConstant::Int(_) => Some(NativeKind::Int64),
        MirConstant::Bool(_) => Some(NativeKind::Bool),
        // Phase 3 cluster-2 Round 4 cw-D-fam12 follow-up (instance 57,
        // 2026-05-16). ADR-006 §2.7.5 amendment Round 19 S1.5: Char is a
        // 4-byte scalar `NativeKind` variant (codepoint inline in low 32
        // bits, no Arc wrapping). Stamp at the producing site so the `print`
        // dispatch in `terminators.rs` matches the `NativeKind::Char` arm at
        // line ~679 (post-amendment scalar label) and routes to
        // `jit_print_char(u32)`.
        MirConstant::Char(_) => Some(NativeKind::Char),
        // WS-8 (2026-05-22): the canonical post-amendment scalar label for
        // a decimal carrier is `NativeKind::DecimalV2` per ADR-006 §2.7.5
        // amendment Wave 2 Agent B W12-StringV2-DecimalV2-NativeKind-
        // additions. Stamping it here surfaces correctly downstream when
        // `compile_constant` returns Err (the `print` dispatch's DecimalV2
        // arm is not wired today, so the W12 fall-through routes to the VM
        // interpreter — VM == JIT, both print correctly).
        MirConstant::Decimal(_) => Some(NativeKind::DecimalV2),
        MirConstant::None => None,
        MirConstant::StringId(_) | MirConstant::Str(_) => Some(NativeKind::String),
        MirConstant::Function(_) => Some(NativeKind::UInt64),
        MirConstant::Method(_) => Some(NativeKind::String),
        MirConstant::ClosurePlaceholder => Some(NativeKind::Ptr(HeapKind::Closure)),
    }
}

fn is_comparison_op(op: &BinOp) -> bool {
    matches!(
        op,
        BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge
    )
}

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

    fn make_mir(stmts: Vec<MirStatement>) -> MirFunction {
        MirFunction {
            name: "test".to_string(),
            blocks: vec![BasicBlock {
                id: BasicBlockId(0),
                statements: stmts,
                terminator: Terminator {
                    kind: TerminatorKind::Return,
                    span: shape_ast::Span::default(),
                },
            }],
            num_locals: 4,
            param_slots: vec![],
            param_reference_kinds: vec![],
            local_types: vec![],
            span: shape_ast::Span::default(),
            field_name_table: Default::default(),
            local_struct_type_names: Default::default(),
            local_typed_array_element_types: Default::default(),
            local_declared_scalar_types: Default::default(),
        }
    }

    fn assign_const(slot: u16, constant: MirConstant) -> MirStatement {
        MirStatement {
            kind: StatementKind::Assign(
                Place::Local(SlotId(slot)),
                Rvalue::Use(Operand::Constant(constant)),
            ),
            span: shape_ast::Span::default(),
            point: Point(0),
        }
    }

    #[test]
    fn infer_float_from_constant() {
        let mir = make_mir(vec![assign_const(1, MirConstant::Float(0))]);
        let kinds = infer_slot_kinds(&mir, &[]);
        assert_eq!(kinds[1], Some(NativeKind::Float64));
    }

    #[test]
    fn infer_int_from_constant() {
        let mir = make_mir(vec![assign_const(1, MirConstant::Int(42))]);
        let kinds = infer_slot_kinds(&mir, &[]);
        assert_eq!(kinds[1], Some(NativeKind::Int64));
    }

    #[test]
    fn infer_bool_from_constant() {
        let mir = make_mir(vec![assign_const(1, MirConstant::Bool(true))]);
        let kinds = infer_slot_kinds(&mir, &[]);
        assert_eq!(kinds[1], Some(NativeKind::Bool));
    }

    #[test]
    fn infer_float_from_binop() {
        let mir = make_mir(vec![
            assign_const(1, MirConstant::Float(0)),
            assign_const(2, MirConstant::Float(0)),
            MirStatement {
                kind: StatementKind::Assign(
                    Place::Local(SlotId(3)),
                    Rvalue::BinaryOp(
                        BinOp::Add,
                        Operand::Copy(Place::Local(SlotId(1))),
                        Operand::Copy(Place::Local(SlotId(2))),
                    ),
                ),
                span: shape_ast::Span::default(),
                point: Point(0),
            },
        ]);
        let kinds = infer_slot_kinds(&mir, &[]);
        assert_eq!(kinds[3], Some(NativeKind::Float64));
    }

    #[test]
    fn infer_bool_from_comparison() {
        let mir = make_mir(vec![
            assign_const(1, MirConstant::Float(0)),
            assign_const(2, MirConstant::Float(0)),
            MirStatement {
                kind: StatementKind::Assign(
                    Place::Local(SlotId(3)),
                    Rvalue::BinaryOp(
                        BinOp::Lt,
                        Operand::Copy(Place::Local(SlotId(1))),
                        Operand::Copy(Place::Local(SlotId(2))),
                    ),
                ),
                span: shape_ast::Span::default(),
                point: Point(0),
            },
        ]);
        let kinds = infer_slot_kinds(&mir, &[]);
        assert_eq!(kinds[3], Some(NativeKind::Bool));
    }

    #[test]
    fn infer_backward_from_typed_sibling_on_binop() {
        // Regression: `|x| x + 1` leaves `x` (a param) Unknown after forward
        // inference because params are seeded from `existing`, not from uses.
        // The backward pass must propagate Int64 from the typed constant `1`
        // into `x`'s slot so the JIT binop picker routes through
        // `compile_binop_int64` instead of the dynamic-op error path.
        //
        // MIR shape:
        //   param(0) = x  (Unknown)
        //   _1 = x + Int(1)
        let mut mir = make_mir(vec![MirStatement {
            kind: StatementKind::Assign(
                Place::Local(SlotId(1)),
                Rvalue::BinaryOp(
                    BinOp::Add,
                    Operand::Copy(Place::Local(SlotId(0))),
                    Operand::Constant(MirConstant::Int(1)),
                ),
            ),
            span: shape_ast::Span::default(),
            point: Point(0),
        }]);
        mir.param_slots = vec![SlotId(0)];
        let kinds = infer_slot_kinds(&mir, &[]);
        assert_eq!(
            kinds[0],
            Some(NativeKind::Int64),
            "backward pass should infer x: Int64 from `x + Int(1)`"
        );
    }

    #[test]
    fn infer_backward_chains_across_params() {
        // `|x, y| x + y + 1` — typed constant `1` reaches both params via
        // two rounds of backward propagation. After round 1: `_1 = x + y`
        // stays Unknown (both sides Unknown); `_2 = _1 + Int(1)` makes `_1`
        // Int64. Round 2: `_1 = x + y` with lhs Unknown, rhs Unknown still
        // doesn't help — we need forward assignment of `_1` to come through
        // first. The forward pass already handles `_1` because both operands
        // are "Unknown" → rvalue kind returns None. So after backward makes
        // `_1` = Int64, the statement `_1 = x + y` would need ANOTHER pass
        // that uses the Assign's LHS kind to constrain RHS operands. That
        // is not implemented here — we only propagate within a single binop.
        //
        // This test pins the current (intentionally limited) behaviour:
        // the simpler case of `|x| x + 1` works; chained-binop backward
        // propagation through an intermediate local does NOT.
        let mut mir = make_mir(vec![
            MirStatement {
                kind: StatementKind::Assign(
                    Place::Local(SlotId(2)),
                    Rvalue::BinaryOp(
                        BinOp::Add,
                        Operand::Copy(Place::Local(SlotId(0))),
                        Operand::Copy(Place::Local(SlotId(1))),
                    ),
                ),
                span: shape_ast::Span::default(),
                point: Point(0),
            },
            MirStatement {
                kind: StatementKind::Assign(
                    Place::Local(SlotId(3)),
                    Rvalue::BinaryOp(
                        BinOp::Add,
                        Operand::Copy(Place::Local(SlotId(2))),
                        Operand::Constant(MirConstant::Int(1)),
                    ),
                ),
                span: shape_ast::Span::default(),
                point: Point(0),
            },
        ]);
        mir.param_slots = vec![SlotId(0), SlotId(1)];
        let kinds = infer_slot_kinds(&mir, &[]);
        // The inner binop picks up the type from `_2 + Int(1)` backwards.
        assert_eq!(kinds[2], Some(NativeKind::Int64));
    }

    #[test]
    fn existing_kinds_preserved() {
        let mir = make_mir(vec![assign_const(1, MirConstant::Float(0))]);
        let existing = vec![None, Some(NativeKind::Int32)];
        let kinds = infer_slot_kinds(&mir, &existing);
        // Existing Int32 is preserved (not overridden by Float64 inference)
        assert_eq!(kinds[1], Some(NativeKind::Int32));
    }

    #[test]
    fn cranelift_type_mapping() {
        assert_eq!(cranelift_type_for_slot(NativeKind::Float64), types::F64);
        assert_eq!(cranelift_type_for_slot(NativeKind::Int32), types::I32);
        assert_eq!(cranelift_type_for_slot(NativeKind::Bool), types::I8);
        assert_eq!(cranelift_type_for_slot(NativeKind::Int64), types::I64);
        assert_eq!(cranelift_type_for_slot(NativeKind::String), types::I64);
    }

    // -----------------------------------------------------------------------
    // R4.2F: borrow StackSlot sizing invariants
    //
    // `Rvalue::Borrow` creates a stack cell with
    //     size = cranelift_type_for_slot(kind).bytes()
    //     align = log2(size)
    // These tests pin the native widths across all slot kinds that flow into
    // borrow cells. Non-native kinds must collapse to 8 bytes / align=3 so the
    // widening is a no-op for the legacy heap/unknown path.
    // -----------------------------------------------------------------------

    #[test]
    fn r4_2f_borrow_cell_sizes() {
        // Native-typed slots get their natural width.
        assert_eq!(cranelift_type_for_slot(NativeKind::Float64).bytes(), 8);
        assert_eq!(cranelift_type_for_slot(NativeKind::Int64).bytes(), 8);
        assert_eq!(cranelift_type_for_slot(NativeKind::Int32).bytes(), 4);
        assert_eq!(cranelift_type_for_slot(NativeKind::UInt32).bytes(), 4);
        assert_eq!(cranelift_type_for_slot(NativeKind::Int16).bytes(), 2);
        assert_eq!(cranelift_type_for_slot(NativeKind::UInt16).bytes(), 2);
        assert_eq!(cranelift_type_for_slot(NativeKind::Int8).bytes(), 1);
        assert_eq!(cranelift_type_for_slot(NativeKind::UInt8).bytes(), 1);
        assert_eq!(cranelift_type_for_slot(NativeKind::Bool).bytes(), 1);
        // Non-native slots collapse to 8 bytes (legacy behaviour).
        assert_eq!(cranelift_type_for_slot(NativeKind::String).bytes(), 8);
    }

    #[test]
    fn r4_2f_borrow_cell_alignment_shifts() {
        // `align_shift = size.trailing_zeros()` — must match log2(size) for
        // every power-of-two native width. If this ever breaks, the
        // `StackSlotData::new` call in `Rvalue::Borrow` will assert.
        for kind in [
            NativeKind::Float64,
            NativeKind::Int64,
            NativeKind::Int32,
            NativeKind::UInt32,
            NativeKind::Int16,
            NativeKind::UInt16,
            NativeKind::Int8,
            NativeKind::UInt8,
            NativeKind::Bool,
            NativeKind::String,
        ] {
            let size = cranelift_type_for_slot(kind).bytes();
            assert!(
                size.is_power_of_two(),
                "slot kind {:?} has non-power-of-two size {}",
                kind,
                size
            );
            let shift = size.trailing_zeros() as u8;
            assert_eq!(
                1u32 << shift,
                size,
                "slot kind {:?}: shift {} does not reconstruct size {}",
                kind,
                shift,
                size
            );
        }
    }

    // ── Phase 3 cluster-0 Round 11-trinity Part b (2026-05-13) ──────────
    // Tests for `parametric_method_return_kind_from_receiver`. Verifies
    // the receiver+method-name pair classification against
    // ConcreteType-bearing receivers.

    use shape_value::heap_value::HeapKind;
    use shape_value::v2::ConcreteType;

    fn copy_local(slot: u16) -> Operand {
        Operand::Copy(Place::Local(SlotId(slot)))
    }

    #[test]
    fn parametric_array_sum_returns_element_kind() {
        // `Array<int>.sum() → Int64`
        let cts = vec![
            ConcreteType::Array(Box::new(ConcreteType::I64)),
        ];
        let kind = parametric_method_return_kind_from_receiver("sum", &[copy_local(0)], &cts);
        assert_eq!(kind, Some(NativeKind::Int64));

        // `Array<number>.sum() → Float64`
        let cts = vec![ConcreteType::Array(Box::new(ConcreteType::F64))];
        let kind = parametric_method_return_kind_from_receiver("sum", &[copy_local(0)], &cts);
        assert_eq!(kind, Some(NativeKind::Float64));
    }

    #[test]
    fn parametric_array_mean_and_min_max_inherit_element() {
        let cts = vec![ConcreteType::Array(Box::new(ConcreteType::F64))];
        assert_eq!(
            parametric_method_return_kind_from_receiver("mean", &[copy_local(0)], &cts),
            Some(NativeKind::Float64)
        );
        assert_eq!(
            parametric_method_return_kind_from_receiver("min", &[copy_local(0)], &cts),
            Some(NativeKind::Float64)
        );
        assert_eq!(
            parametric_method_return_kind_from_receiver("max", &[copy_local(0)], &cts),
            Some(NativeKind::Float64)
        );
    }

    #[test]
    fn parametric_array_first_last_pop_return_element_kind() {
        // Phase 4b Round 4 W15 LANG-9-spin-3-first JIT fix (2026-05-18):
        // `Array<T>.first/last/pop` now return the bare element kind
        // matching the VM-side PHF handler (`typed_int_array_methods::
        // first/last/pop` returns `KindedSlot::from_int(...)` for
        // non-empty arrays). The previous mapping to `Ptr(HeapKind::
        // Option)` mismatched the producer's stamp — JIT downstream
        // consumers treated `Int64=2` bits as an `Arc<OptionData>`
        // pointer and rendered "None" on print. Per ADR-006 §2.7.5: the
        // receiver's element type IS the proof of the result kind.
        let cts = vec![ConcreteType::Array(Box::new(ConcreteType::I64))];
        assert_eq!(
            parametric_method_return_kind_from_receiver("first", &[copy_local(0)], &cts),
            Some(NativeKind::Int64)
        );
        assert_eq!(
            parametric_method_return_kind_from_receiver("last", &[copy_local(0)], &cts),
            Some(NativeKind::Int64)
        );
        assert_eq!(
            parametric_method_return_kind_from_receiver("pop", &[copy_local(0)], &cts),
            Some(NativeKind::Int64)
        );

        // `Array<number>.first/last/pop → Float64`
        let cts = vec![ConcreteType::Array(Box::new(ConcreteType::F64))];
        assert_eq!(
            parametric_method_return_kind_from_receiver("first", &[copy_local(0)], &cts),
            Some(NativeKind::Float64)
        );
    }

    #[test]
    fn parametric_hashmap_get_returns_option_carrier() {
        // HashMap.get(k) → Option<V>; destination slot carries
        // Ptr(HeapKind::Option) per §2.7.17. The wrapped V flows
        // through EnumPayload at the destructure site.
        let cts = vec![ConcreteType::HashMap(
            Box::new(ConcreteType::String),
            Box::new(ConcreteType::I64),
        )];
        let kind =
            parametric_method_return_kind_from_receiver("get", &[copy_local(0)], &cts);
        assert_eq!(kind, Some(NativeKind::Ptr(HeapKind::Option)));
    }

    #[test]
    fn parametric_mutex_get_returns_inner_kind() {
        // Mutex<int>.get() → Int64 per §2.7.25 receiver-recovery.
        let cts = vec![ConcreteType::Mutex(Box::new(ConcreteType::I64))];
        let kind =
            parametric_method_return_kind_from_receiver("get", &[copy_local(0)], &cts);
        assert_eq!(kind, Some(NativeKind::Int64));

        // Mutex<bool>.get() → Bool.
        let cts = vec![ConcreteType::Mutex(Box::new(ConcreteType::Bool))];
        let kind =
            parametric_method_return_kind_from_receiver("get", &[copy_local(0)], &cts);
        assert_eq!(kind, Some(NativeKind::Bool));
    }

    #[test]
    fn parametric_atomic_load_fetch_returns_int64() {
        // Atomic is i64-only at landing per §2.7.25.
        let cts = vec![ConcreteType::Atomic];
        for name in &["load", "fetch_add", "fetch_sub", "compare_exchange"] {
            let kind =
                parametric_method_return_kind_from_receiver(name, &[copy_local(0)], &cts);
            assert_eq!(
                kind,
                Some(NativeKind::Int64),
                "Atomic.{name} should return Int64"
            );
        }
    }

    #[test]
    fn parametric_lazy_get_returns_inner_kind() {
        // Lazy<int>.get() → Int64 per §2.7.25 receiver-recovery.
        let cts = vec![ConcreteType::Lazy(Box::new(ConcreteType::I64))];
        let kind =
            parametric_method_return_kind_from_receiver("get", &[copy_local(0)], &cts);
        assert_eq!(kind, Some(NativeKind::Int64));
    }

    #[test]
    fn parametric_unknown_method_returns_none() {
        // Unknown method names produce None — no Bool-default fallback
        // per §2.7.7 #9.
        let cts = vec![ConcreteType::Array(Box::new(ConcreteType::I64))];
        let kind = parametric_method_return_kind_from_receiver(
            "unknown_method",
            &[copy_local(0)],
            &cts,
        );
        assert_eq!(kind, None);
    }

    #[test]
    fn parametric_constant_receiver_returns_none() {
        // A constant-operand receiver has no slot to source ConcreteType
        // from — classification is impossible, return None.
        let kind = parametric_method_return_kind_from_receiver(
            "sum",
            &[Operand::Constant(MirConstant::Int(42))],
            &[],
        );
        assert_eq!(kind, None);
    }

    #[test]
    fn parametric_void_receiver_returns_none() {
        // When the receiver slot's ConcreteType is Void (the upstream
        // conduit couldn't prove a kind), classification falls through
        // to None — no fabricated default.
        let cts = vec![ConcreteType::Void];
        let kind =
            parametric_method_return_kind_from_receiver("sum", &[copy_local(0)], &cts);
        assert_eq!(kind, None);
    }

    #[test]
    fn parametric_size_is_invariant_not_parametric() {
        // `size` is in `well_known_method_return_kind` (invariant
        // across receivers); the parametric classifier should NOT
        // catch it. This pins the cohort split — invariant names land
        // in the well_known path, parametric names in the parametric
        // path. No overlap.
        let cts = vec![ConcreteType::Array(Box::new(ConcreteType::I64))];
        let kind =
            parametric_method_return_kind_from_receiver("size", &[copy_local(0)], &cts);
        assert_eq!(
            kind, None,
            "size belongs to well_known_method_return_kind, not the parametric cohort"
        );
        // But well_known catches it.
        assert_eq!(
            well_known_method_return_kind("size"),
            Some(NativeKind::Int64)
        );
    }

    #[test]
    fn parametric_method_return_kind_integrates_in_call_terminator_seed() {
        // Integration test: a Call terminator for `arr.sum()` on an
        // Array<int> receiver seeds the destination slot's kind to
        // Int64 via the parametric classifier. Mirrors the
        // Round 5C TerminatorKind::Call destination-stamp path; the
        // parametric extension reaches it via the
        // `well_known.or_else(parametric)` chain at the Call-terminator
        // pass.
        //
        // MIR shape:
        //   local 0 = Array<int> receiver (concrete_types seeded)
        //   call .sum(local 0) → local 1
        let mir = MirFunction {
            name: "test_sum".to_string(),
            blocks: vec![BasicBlock {
                id: BasicBlockId(0),
                statements: vec![],
                terminator: Terminator {
                    kind: TerminatorKind::Call {
                        func: Operand::Constant(MirConstant::Method("sum".to_string())),
                        args: vec![copy_local(0)],
                        destination: Place::Local(SlotId(1)),
                        next: BasicBlockId(0),
                    },
                    span: shape_ast::Span::default(),
                },
            }],
            num_locals: 4,
            param_slots: vec![],
            param_reference_kinds: vec![],
            local_types: vec![],
            span: shape_ast::Span::default(),
            field_name_table: Default::default(),
            local_struct_type_names: Default::default(),
            local_typed_array_element_types: Default::default(),
            local_declared_scalar_types: Default::default(),
        };
        let concrete_types = vec![
            ConcreteType::Array(Box::new(ConcreteType::I64)),
            ConcreteType::Void,
            ConcreteType::Void,
            ConcreteType::Void,
        ];
        let kinds = infer_slot_kinds_with_concrete(&mir, &[], &concrete_types);
        assert_eq!(
            kinds[1],
            Some(NativeKind::Int64),
            ".sum() on Array<int> should stamp Int64 on the destination slot"
        );
    }

    // ── Phase 4b Round 5c-2-α HashMap-has-2-chain regression tests ────
    //
    // v0.3-gating SOUNDNESS BUG ratified 2026-05-19. Empirical pre-fix
    // at HEAD 7eb82205: `HashMap().set("a",1).set("b",2).has("a")`
    // returned VM=true / JIT=false. Root cause:
    // `parametric_method_return_kind_from_receiver` had no entry for
    // HashMap mutators (`set` / `delete` / `merge`) returning self, so
    // chain temps' kinds stayed None → fell back to `UInt64` carrier
    // → `jit_call_method` shell routed to legacy JIT-format dispatch
    // → `read_heap_kind` on `Arc::into_raw(Arc<HashMapKindedRef>)`
    // bits returned garbage → TAG_NULL → Bool-kind consumer rendered
    // `false`.
    //
    // Post-fix: two stamp sites — (a) the existing
    // `parametric_method_return_kind_from_receiver` classifier gains
    // HashMap mutator arms keyed on `ConcreteType::HashMap(_, _)`;
    // (b) the new `method_return_kind_from_in_pass_kinds` classifier
    // reads the receiver's NativeKind from the in-pass `kinds[]` track
    // (load-bearing for the bare-`HashMap()` ctor case where
    // `concrete_types` is Void but the EnumStore arm has stamped
    // `Ptr(HeapKind::HashMap)` in `kinds[]`); the call-stamp loop is
    // unified with the collection-alias-propagation fixpoint so
    // chain-temps converge through arbitrary depth.

    #[test]
    fn parametric_hashmap_set_returns_hashmap_carrier() {
        // HashMap.set(k, v) → HashMap (chainable). The VM-side
        // `hashmap_methods::v2_set` at line 789 returns
        // `KindedSlot::from_hashmap(...)`. Per ADR-006 §2.7.5
        // producer-side stamp: the destination slot's kind is
        // `Ptr(HeapKind::HashMap)`.
        let cts = vec![ConcreteType::HashMap(
            Box::new(ConcreteType::String),
            Box::new(ConcreteType::I64),
        )];
        let kind =
            parametric_method_return_kind_from_receiver("set", &[copy_local(0)], &cts);
        assert_eq!(kind, Some(NativeKind::Ptr(HeapKind::HashMap)));
    }

    #[test]
    fn parametric_hashmap_delete_returns_hashmap_carrier() {
        // HashMap.delete(k) → HashMap (chainable). The VM-side
        // `hashmap_methods::v2_delete` at line 1235 returns
        // `KindedSlot::from_hashmap(...)`.
        let cts = vec![ConcreteType::HashMap(
            Box::new(ConcreteType::String),
            Box::new(ConcreteType::I64),
        )];
        let kind =
            parametric_method_return_kind_from_receiver("delete", &[copy_local(0)], &cts);
        assert_eq!(kind, Some(NativeKind::Ptr(HeapKind::HashMap)));
    }

    #[test]
    fn parametric_hashmap_merge_returns_hashmap_carrier() {
        // HashMap.merge(other) → HashMap. The VM-side
        // `hashmap_methods::v2_merge` at line 1469 returns
        // `KindedSlot::from_hashmap(...)`.
        let cts = vec![ConcreteType::HashMap(
            Box::new(ConcreteType::String),
            Box::new(ConcreteType::I64),
        )];
        let kind =
            parametric_method_return_kind_from_receiver("merge", &[copy_local(0)], &cts);
        assert_eq!(kind, Some(NativeKind::Ptr(HeapKind::HashMap)));
    }

    #[test]
    fn in_pass_kinds_classifier_stamps_hashmap_mutators_from_kinds_track() {
        // The bare-form `HashMap()` ctor case: `concrete_types` carries
        // Void (the bytecode compiler's concrete-type inference doesn't
        // synthesize `ConcreteType::HashMap(_, _)` for the bare ctor —
        // the EnumStore arm in `infer_slot_kinds_with_concrete` stamps
        // `Ptr(HeapKind::HashMap)` into `kinds[]` instead). The new
        // `method_return_kind_from_in_pass_kinds` classifier reads the
        // receiver kind directly from `kinds[]` so chain temps following
        // a bare ctor still classify correctly.
        let kinds = vec![Some(NativeKind::Ptr(HeapKind::HashMap)), None, None];
        let kind = method_return_kind_from_in_pass_kinds(
            "set",
            &[copy_local(0)],
            &kinds,
        );
        assert_eq!(kind, Some(NativeKind::Ptr(HeapKind::HashMap)));

        let kind = method_return_kind_from_in_pass_kinds(
            "delete",
            &[copy_local(0)],
            &kinds,
        );
        assert_eq!(kind, Some(NativeKind::Ptr(HeapKind::HashMap)));

        let kind = method_return_kind_from_in_pass_kinds(
            "merge",
            &[copy_local(0)],
            &kinds,
        );
        assert_eq!(kind, Some(NativeKind::Ptr(HeapKind::HashMap)));
    }

    #[test]
    fn in_pass_kinds_classifier_returns_none_for_non_hashmap_receivers() {
        // Non-HashMap receivers must return None — no fabricated default
        // per §2.7.7 #9. Pins the cohort: only HashMap mutators returning
        // self are classified by this helper. Array.push, Vec.push, etc.
        // are NOT classified here (their carrier shape differs; broader
        // scope per dispatch supervisor disposition).
        let kinds = vec![Some(NativeKind::Ptr(HeapKind::TypedArray)), None];
        let kind =
            method_return_kind_from_in_pass_kinds("set", &[copy_local(0)], &kinds);
        assert_eq!(kind, None, "Non-HashMap receiver must not be classified");

        let kinds = vec![Some(NativeKind::Int64), None];
        let kind =
            method_return_kind_from_in_pass_kinds("set", &[copy_local(0)], &kinds);
        assert_eq!(kind, None, "Scalar receiver must not be classified");

        // Unknown method on HashMap receiver — return None.
        let kinds = vec![Some(NativeKind::Ptr(HeapKind::HashMap)), None];
        let kind = method_return_kind_from_in_pass_kinds(
            "unknown_method",
            &[copy_local(0)],
            &kinds,
        );
        assert_eq!(kind, None, "Unknown method must not be classified");
    }

    #[test]
    fn hashmap_chain_propagates_kind_through_call_stamp_fixpoint() {
        // Integration test for the load-bearing chain pattern:
        //   temp0 = HashMap()       (EnumStore → Ptr(HashMap) in kinds[])
        //   temp1 = temp0.set(...)  (call-stamp fixpoint → Ptr(HashMap))
        //   temp2 = temp1.set(...)  (call-stamp fixpoint → Ptr(HashMap))
        //   temp3 = temp2.has(...)  (well_known → Bool)
        //
        // Pre-fix: temp1/temp2 stayed None (no classifier entry for
        // `set`), causing the `.has` receiver-kind dispatch to surface
        // the divergence. Post-fix: each chain link's destination slot
        // is stamped `Ptr(HeapKind::HashMap)` and the .has dispatch
        // routes through `jit_trampoline_call_method` correctly.
        let mir = MirFunction {
            name: "hashmap_chain".to_string(),
            blocks: vec![
                BasicBlock {
                    id: BasicBlockId(0),
                    statements: vec![
                        // temp0 = HashMap() — EnumStore arm stamps
                        // Ptr(HashMap) in the forward pass.
                        MirStatement {
                            kind: StatementKind::Assign(
                                Place::Local(SlotId(0)),
                                Rvalue::Aggregate(vec![]),
                            ),
                            span: shape_ast::Span::default(),
                            point: Point(0),
                        },
                        MirStatement {
                            kind: StatementKind::EnumStore {
                                container_slot: SlotId(0),
                                operands: vec![],
                                variant_name: Some("HashMap".to_string()),
                            },
                            span: shape_ast::Span::default(),
                            point: Point(1),
                        },
                    ],
                    terminator: Terminator {
                        kind: TerminatorKind::Call {
                            func: Operand::Constant(MirConstant::Method(
                                "set".to_string(),
                            )),
                            args: vec![
                                copy_local(0),
                                Operand::Constant(MirConstant::Str("a".to_string())),
                                Operand::Constant(MirConstant::Int(1)),
                            ],
                            destination: Place::Local(SlotId(1)),
                            next: BasicBlockId(1),
                        },
                        span: shape_ast::Span::default(),
                    },
                },
                BasicBlock {
                    id: BasicBlockId(1),
                    statements: vec![],
                    terminator: Terminator {
                        kind: TerminatorKind::Call {
                            func: Operand::Constant(MirConstant::Method(
                                "set".to_string(),
                            )),
                            args: vec![
                                copy_local(1),
                                Operand::Constant(MirConstant::Str("b".to_string())),
                                Operand::Constant(MirConstant::Int(2)),
                            ],
                            destination: Place::Local(SlotId(2)),
                            next: BasicBlockId(2),
                        },
                        span: shape_ast::Span::default(),
                    },
                },
                BasicBlock {
                    id: BasicBlockId(2),
                    statements: vec![],
                    terminator: Terminator {
                        kind: TerminatorKind::Call {
                            func: Operand::Constant(MirConstant::Method(
                                "has".to_string(),
                            )),
                            args: vec![
                                copy_local(2),
                                Operand::Constant(MirConstant::Str("a".to_string())),
                            ],
                            destination: Place::Local(SlotId(3)),
                            next: BasicBlockId(2),
                        },
                        span: shape_ast::Span::default(),
                    },
                },
            ],
            num_locals: 4,
            param_slots: vec![],
            param_reference_kinds: vec![],
            local_types: vec![],
            span: shape_ast::Span::default(),
            field_name_table: Default::default(),
            local_struct_type_names: Default::default(),
            local_typed_array_element_types: Default::default(),
            local_declared_scalar_types: Default::default(),
        };
        // No ConcreteType seeds — every slot is Void, mirroring the
        // bare-`HashMap()` ctor pattern.
        let concrete_types = vec![
            ConcreteType::Void,
            ConcreteType::Void,
            ConcreteType::Void,
            ConcreteType::Void,
        ];
        let kinds = infer_slot_kinds_with_concrete(&mir, &[], &concrete_types);
        assert_eq!(
            kinds[0],
            Some(NativeKind::Ptr(HeapKind::HashMap)),
            "temp0 (HashMap() ctor) must be classified via EnumStore arm"
        );
        assert_eq!(
            kinds[1],
            Some(NativeKind::Ptr(HeapKind::HashMap)),
            "temp1 (1st .set) must inherit Ptr(HashMap) via in-pass-kinds classifier"
        );
        assert_eq!(
            kinds[2],
            Some(NativeKind::Ptr(HeapKind::HashMap)),
            "temp2 (2nd .set) must inherit Ptr(HashMap) — fixpoint propagates the chain"
        );
        assert_eq!(
            kinds[3],
            Some(NativeKind::Bool),
            "temp3 (.has) must be Bool from well_known_method_return_kind"
        );
    }

    // ── Phase 4b Round 5c-2-β-α collection-mutator-chain regression ───
    //
    // Sister-class of the HashMap-has-2-chain tests above. Each
    // collection type (HashSet / Deque / PriorityQueue / Channel) has a
    // chainable mutator whose VM-side handler returns
    // `KindedSlot::from_<collection>(...)`; pre-fix the JIT classifiers
    // had no entry for these names so the chain-temp slot's kind stayed
    // `None` → `UInt64` carrier fallback → legacy JIT-format dispatch →
    // wrong consumer rendering (HashSet `false`, Deque/PQ garbage int,
    // Channel SIGSEGV). These pin the producer-side stamp arms in both
    // `parametric_method_return_kind_from_receiver` (ConcreteType-keyed)
    // and `method_return_kind_from_in_pass_kinds` (in-pass-kinds-keyed,
    // load-bearing for bare-form ctors).

    #[test]
    fn parametric_hashset_mutators_return_hashset_carrier() {
        // HashSet.add / .delete return the mutated receiver Arc;
        // .union / .intersection / .difference return a fresh result
        // set — all five VM-side handlers in `set_methods.rs` (v2_add
        // line 259, v2_delete, v2_union 312, v2_intersection 341,
        // v2_difference 374) return `KindedSlot::from_hashset(...)`.
        let cts = vec![ConcreteType::HashSet(Box::new(ConcreteType::String))];
        for name in ["add", "delete", "union", "intersection", "difference"] {
            let kind =
                parametric_method_return_kind_from_receiver(name, &[copy_local(0)], &cts);
            assert_eq!(
                kind,
                Some(NativeKind::Ptr(HeapKind::HashSet)),
                "HashSet.{name} must classify to Ptr(HeapKind::HashSet)"
            );
        }
    }

    #[test]
    fn parametric_deque_mutators_return_deque_carrier() {
        // Deque.pushBack / .pushFront return the mutated receiver Arc.
        // VM-side `deque_methods::v2_push_back` (308) / `v2_push_front`
        // (327) return `KindedSlot::from_deque(...)`. `popBack` /
        // `popFront` are tuple-return (pop the element) — NOT on the arm.
        let cts = vec![ConcreteType::Deque(Box::new(ConcreteType::I64))];
        for name in ["pushBack", "pushFront"] {
            let kind =
                parametric_method_return_kind_from_receiver(name, &[copy_local(0)], &cts);
            assert_eq!(
                kind,
                Some(NativeKind::Ptr(HeapKind::Deque)),
                "Deque.{name} must classify to Ptr(HeapKind::Deque)"
            );
        }
        // popBack / popFront stay unclassified by this arm.
        for name in ["popBack", "popFront"] {
            let kind =
                parametric_method_return_kind_from_receiver(name, &[copy_local(0)], &cts);
            assert_eq!(kind, None, "Deque.{name} (tuple-return) must not classify here");
        }
    }

    #[test]
    fn parametric_priority_queue_push_returns_priority_queue_carrier() {
        // PriorityQueue.push returns the mutated receiver Arc. VM-side
        // `priority_queue_methods::v2_push` (235) returns
        // `KindedSlot::from_priority_queue(...)`. `ConcreteType::
        // PriorityQueue` is nullary (i64-only at landing per §2.7.18).
        let cts = vec![ConcreteType::PriorityQueue];
        let kind =
            parametric_method_return_kind_from_receiver("push", &[copy_local(0)], &cts);
        assert_eq!(kind, Some(NativeKind::Ptr(HeapKind::PriorityQueue)));
        // pop is tuple-return — not classified here.
        let kind =
            parametric_method_return_kind_from_receiver("pop", &[copy_local(0)], &cts);
        assert_eq!(kind, None, "PriorityQueue.pop (tuple-return) must not classify here");
    }

    #[test]
    fn parametric_channel_mutators_return_channel_carrier() {
        // Channel.send / .close return the receiver share. VM-side
        // `channel_methods::v2_channel_send` (98) / `v2_channel_close`
        // (193) return `KindedSlot::from_channel(...)`.
        let cts = vec![ConcreteType::Channel(Box::new(ConcreteType::I64))];
        for name in ["send", "close"] {
            let kind =
                parametric_method_return_kind_from_receiver(name, &[copy_local(0)], &cts);
            assert_eq!(
                kind,
                Some(NativeKind::Ptr(HeapKind::Channel)),
                "Channel.{name} must classify to Ptr(HeapKind::Channel)"
            );
        }
    }

    #[test]
    fn in_pass_kinds_classifier_stamps_collection_mutators_from_kinds_track() {
        // The bare-form ctor case (`Set()` / `Deque()` / etc.): the
        // receiver `ConcreteType` is Void, but the EnumStore arm has
        // stamped the collection's `Ptr(HeapKind::*)` into `kinds[]`.
        // `method_return_kind_from_in_pass_kinds` reads that and
        // classifies the chain-temp.
        let hs_kinds = vec![Some(NativeKind::Ptr(HeapKind::HashSet)), None];
        for name in ["add", "delete", "union", "intersection", "difference"] {
            assert_eq!(
                method_return_kind_from_in_pass_kinds(name, &[copy_local(0)], &hs_kinds),
                Some(NativeKind::Ptr(HeapKind::HashSet)),
                "HashSet.{name} in-pass-kinds classification"
            );
        }
        let dq_kinds = vec![Some(NativeKind::Ptr(HeapKind::Deque)), None];
        for name in ["pushBack", "pushFront"] {
            assert_eq!(
                method_return_kind_from_in_pass_kinds(name, &[copy_local(0)], &dq_kinds),
                Some(NativeKind::Ptr(HeapKind::Deque)),
                "Deque.{name} in-pass-kinds classification"
            );
        }
        let pq_kinds = vec![Some(NativeKind::Ptr(HeapKind::PriorityQueue)), None];
        assert_eq!(
            method_return_kind_from_in_pass_kinds("push", &[copy_local(0)], &pq_kinds),
            Some(NativeKind::Ptr(HeapKind::PriorityQueue)),
        );
        let ch_kinds = vec![Some(NativeKind::Ptr(HeapKind::Channel)), None];
        for name in ["send", "close"] {
            assert_eq!(
                method_return_kind_from_in_pass_kinds(name, &[copy_local(0)], &ch_kinds),
                Some(NativeKind::Ptr(HeapKind::Channel)),
                "Channel.{name} in-pass-kinds classification"
            );
        }
    }

    #[test]
    fn in_pass_kinds_classifier_rejects_cross_collection_method_names() {
        // Cohort discipline: a method name is classified ONLY when the
        // receiver kind is the matching collection. `add` on a Deque
        // receiver, `pushBack` on a HashSet receiver, etc. must return
        // None — no fabricated default per §2.7.7 #9.
        let dq_kinds = vec![Some(NativeKind::Ptr(HeapKind::Deque)), None];
        assert_eq!(
            method_return_kind_from_in_pass_kinds("add", &[copy_local(0)], &dq_kinds),
            None,
            "HashSet method `add` on a Deque receiver must not classify"
        );
        let hs_kinds = vec![Some(NativeKind::Ptr(HeapKind::HashSet)), None];
        assert_eq!(
            method_return_kind_from_in_pass_kinds("pushBack", &[copy_local(0)], &hs_kinds),
            None,
            "Deque method `pushBack` on a HashSet receiver must not classify"
        );
        assert_eq!(
            method_return_kind_from_in_pass_kinds("send", &[copy_local(0)], &hs_kinds),
            None,
            "Channel method `send` on a HashSet receiver must not classify"
        );
        // Scalar receiver — never classified.
        let scalar_kinds = vec![Some(NativeKind::Int64), None];
        assert_eq!(
            method_return_kind_from_in_pass_kinds("add", &[copy_local(0)], &scalar_kinds),
            None,
        );
    }

    #[test]
    fn hashset_chain_propagates_kind_through_call_stamp_fixpoint() {
        // End-to-end: `Set().add("a").add("b").has("a")`.
        //   temp0 = Set()          (EnumStore → Ptr(HashSet) in kinds[])
        //   temp1 = temp0.add(...) (in-pass-kinds fixpoint → Ptr(HashSet))
        //   temp2 = temp1.add(...) (in-pass-kinds fixpoint → Ptr(HashSet))
        //   temp3 = temp2.has(...) (well_known → Bool)
        let mir = collection_chain_mir(
            "Set",
            "add",
            &[Operand::Constant(MirConstant::Str("a".to_string()))],
            "has",
            &[Operand::Constant(MirConstant::Str("a".to_string()))],
        );
        let concrete_types = vec![ConcreteType::Void; 4];
        let kinds = infer_slot_kinds_with_concrete(&mir, &[], &concrete_types);
        assert_eq!(kinds[0], Some(NativeKind::Ptr(HeapKind::HashSet)));
        assert_eq!(
            kinds[1],
            Some(NativeKind::Ptr(HeapKind::HashSet)),
            "1st .add chain temp must inherit Ptr(HashSet)"
        );
        assert_eq!(
            kinds[2],
            Some(NativeKind::Ptr(HeapKind::HashSet)),
            "2nd .add chain temp must inherit Ptr(HashSet) — fixpoint propagates"
        );
        assert_eq!(
            kinds[3],
            Some(NativeKind::Bool),
            ".has destination must be Bool from well_known_method_return_kind"
        );
    }

    #[test]
    fn deque_chain_propagates_kind_through_call_stamp_fixpoint() {
        // End-to-end: `Deque().pushBack(1).pushBack(2).size()`.
        let mir = collection_chain_mir(
            "Deque",
            "pushBack",
            &[Operand::Constant(MirConstant::Int(1))],
            "size",
            &[],
        );
        let concrete_types = vec![ConcreteType::Void; 4];
        let kinds = infer_slot_kinds_with_concrete(&mir, &[], &concrete_types);
        assert_eq!(kinds[0], Some(NativeKind::Ptr(HeapKind::Deque)));
        assert_eq!(kinds[1], Some(NativeKind::Ptr(HeapKind::Deque)));
        assert_eq!(kinds[2], Some(NativeKind::Ptr(HeapKind::Deque)));
        assert_eq!(
            kinds[3],
            Some(NativeKind::Int64),
            ".size destination must be Int64 from well_known_method_return_kind"
        );
    }

    #[test]
    fn priority_queue_and_channel_chains_propagate_kind_through_fixpoint() {
        // PriorityQueue: `PriorityQueue().push(5).push(3).size()`.
        let pq_mir = collection_chain_mir(
            "PriorityQueue",
            "push",
            &[Operand::Constant(MirConstant::Int(5))],
            "size",
            &[],
        );
        let pq_kinds =
            infer_slot_kinds_with_concrete(&pq_mir, &[], &vec![ConcreteType::Void; 4]);
        assert_eq!(pq_kinds[0], Some(NativeKind::Ptr(HeapKind::PriorityQueue)));
        assert_eq!(pq_kinds[1], Some(NativeKind::Ptr(HeapKind::PriorityQueue)));
        assert_eq!(pq_kinds[2], Some(NativeKind::Ptr(HeapKind::PriorityQueue)));
        assert_eq!(pq_kinds[3], Some(NativeKind::Int64));

        // Channel: `Channel().send(7).send(9).is_closed()`.
        let ch_mir = collection_chain_mir(
            "Channel",
            "send",
            &[Operand::Constant(MirConstant::Int(7))],
            "is_closed",
            &[],
        );
        let ch_kinds =
            infer_slot_kinds_with_concrete(&ch_mir, &[], &vec![ConcreteType::Void; 4]);
        assert_eq!(ch_kinds[0], Some(NativeKind::Ptr(HeapKind::Channel)));
        assert_eq!(ch_kinds[1], Some(NativeKind::Ptr(HeapKind::Channel)));
        assert_eq!(ch_kinds[2], Some(NativeKind::Ptr(HeapKind::Channel)));
    }

    /// Build a 4-slot collection-mutator-chain MIR mirroring the shape of
    /// `hashmap_chain_propagates_kind_through_call_stamp_fixpoint`:
    ///   temp0 = <ctor>()       (Aggregate + EnumStore)
    ///   temp1 = temp0.<mut>(.) (Call terminator)
    ///   temp2 = temp1.<mut>(.) (Call terminator)
    ///   temp3 = temp2.<query>(.) (Call terminator)
    fn collection_chain_mir(
        ctor: &str,
        mutator: &str,
        mut_arg: &[Operand],
        query: &str,
        query_args: &[Operand],
    ) -> MirFunction {
        let mut mut_args_1 = vec![copy_local(0)];
        mut_args_1.extend_from_slice(mut_arg);
        let mut mut_args_2 = vec![copy_local(1)];
        mut_args_2.extend_from_slice(mut_arg);
        let mut query_full = vec![copy_local(2)];
        query_full.extend_from_slice(query_args);
        MirFunction {
            name: "collection_chain".to_string(),
            blocks: vec![
                BasicBlock {
                    id: BasicBlockId(0),
                    statements: vec![
                        MirStatement {
                            kind: StatementKind::Assign(
                                Place::Local(SlotId(0)),
                                Rvalue::Aggregate(vec![]),
                            ),
                            span: shape_ast::Span::default(),
                            point: Point(0),
                        },
                        MirStatement {
                            kind: StatementKind::EnumStore {
                                container_slot: SlotId(0),
                                operands: vec![],
                                variant_name: Some(ctor.to_string()),
                            },
                            span: shape_ast::Span::default(),
                            point: Point(1),
                        },
                    ],
                    terminator: Terminator {
                        kind: TerminatorKind::Call {
                            func: Operand::Constant(MirConstant::Method(
                                mutator.to_string(),
                            )),
                            args: mut_args_1,
                            destination: Place::Local(SlotId(1)),
                            next: BasicBlockId(1),
                        },
                        span: shape_ast::Span::default(),
                    },
                },
                BasicBlock {
                    id: BasicBlockId(1),
                    statements: vec![],
                    terminator: Terminator {
                        kind: TerminatorKind::Call {
                            func: Operand::Constant(MirConstant::Method(
                                mutator.to_string(),
                            )),
                            args: mut_args_2,
                            destination: Place::Local(SlotId(2)),
                            next: BasicBlockId(2),
                        },
                        span: shape_ast::Span::default(),
                    },
                },
                BasicBlock {
                    id: BasicBlockId(2),
                    statements: vec![],
                    terminator: Terminator {
                        kind: TerminatorKind::Call {
                            func: Operand::Constant(MirConstant::Method(
                                query.to_string(),
                            )),
                            args: query_full,
                            destination: Place::Local(SlotId(3)),
                            next: BasicBlockId(2),
                        },
                        span: shape_ast::Span::default(),
                    },
                },
            ],
            num_locals: 4,
            param_slots: vec![],
            param_reference_kinds: vec![],
            local_types: vec![],
            span: shape_ast::Span::default(),
            field_name_table: Default::default(),
            local_struct_type_names: Default::default(),
            local_typed_array_element_types: Default::default(),
            local_declared_scalar_types: Default::default(),
        }
    }

    // ── Phase 3 cluster-0 Round 12 T1 surface pin tests ────────────────
    //
    // Surface pins for the user-defined-trait method dispatch boundary
    // documented at `parametric_method_return_kind_from_receiver`'s
    // "User-defined-trait surface boundary" doc block. These tests
    // assert the JIT-internal classifier's posture — they are
    // intentional pins, not regressions to be papered over by a
    // Bool-default fallback or a hard-coded method-name arm.
    //
    // ── Round 13 T1' status (2026-05-13) ────────────────────────────
    //
    // The user-defined-trait method dispatch boundary closes at the
    // **VM-side conduit producer**, not at the JIT-internal
    // parametric classifier. The producer
    // (`crates/shape-vm/src/compiler/helpers.rs::infer_top_level_concrete_types_from_mir_with_resolvers`)
    // stamps the Call-terminator destination slot's ConcreteType from
    // the trait's declared return type via the new method-returns
    // resolver chain:
    //
    //   `mir.local_struct_type_names[receiver_slot]` (gap 1 closure)
    //   → `find_default_trait_impl_for_type_method(type_name, method)`
    //   → `function_return_concrete_types[fn_idx]` (post gap 3 backfill)
    //
    // So Smoke 3 (`trait T { method name() -> string } type X {} impl T for X {
    // method name() { "x" } } let t = X {} print(t.name())` → `x`)
    // closes via the upstream `concrete_types[t_name_slot]
    // = ConcreteType::String` stamp; the JIT consumer at
    // `infer_slot_kinds_with_concrete` projects this through
    // `concrete_seed` (`crates/shape-jit/src/mir_compiler/mod.rs:564`)
    // to `NativeKind::String` automatically — no change to the
    // JIT-internal `parametric_method_return_kind_from_receiver`
    // classifier needed.
    //
    // The 3 pin tests below remain valid post-T1': they assert that the
    // JIT-internal classifier is NOT the place where user-defined trait
    // method classification happens (it would be a wrong-layer
    // classification per CLAUDE.md "Renames to refuse on sight" / Round
    // 6A precedent). The classification correctly lives at the VM-side
    // conduit producer one tier upstream.
    //
    // The new positive pin
    // (`trait_method_call_destination_seeded_from_concrete_types`)
    // asserts the upstream-landing pathway: when the VM-side conduit
    // has stamped `concrete_types[result_slot] = ConcreteType::String`,
    // the JIT consumer's `concrete_seed` projection picks it up to
    // `NativeKind::String`.

    #[test]
    fn user_defined_trait_method_on_struct_returns_none() {
        // Smoke 3 minimal case at the classifier level: receiver
        // `t: X` carries `ConcreteType::Struct(StructLayoutId(0))`
        // because `concrete_type_from_annotation` returns the
        // `StructLayoutId(0)` placeholder for every user struct name
        // (the layout-id registry is not wired — see the function's
        // `_ => None` arm at `v2_map_emission.rs:378` "Phase 1.1
        // Agent 3 will fill this in"). The classifier has no
        // struct-name information to disambiguate `X` from any other
        // user struct, and the trait registry is not threaded into
        // the JIT MIR builder layer — so the trait method's declared
        // return type (`string` from `trait T { method name() -> string }`) is
        // unreachable from this classifier.
        //
        // The classifier must return `None` (surface-and-stop posture),
        // NOT a fabricated `NativeKind::String` from hard-coding `"name"`
        // — that would be a CLAUDE.md "Forbidden rationalizations"
        // walk-back ("hard-code the kickoff Smoke 3 case for now").
        let cts = vec![ConcreteType::placeholder_struct(shape_value::v2::concrete_type::StructLayoutId(0))];
        let kind =
            parametric_method_return_kind_from_receiver("name", &[copy_local(0)], &cts);
        assert_eq!(
            kind, None,
            "User-defined trait method on Struct receiver must surface \
             (return None); the trait registry's declared return type is \
             not threaded into the JIT MIR builder. See classifier doc \
             block 'User-defined-trait surface boundary'."
        );
    }

    #[test]
    fn user_defined_trait_method_call_terminator_remains_unstamped() {
        // Integration pin: the Call-terminator destination-stamp pass
        // at `infer_slot_kinds_with_concrete` chains
        // `well_known.or_else(parametric)`. Neither classifier catches
        // `name` on a `Struct(_)` receiver:
        //
        // - `well_known_method_return_kind("name")` returns `None` —
        //   `"name"` is not a collection-size / emptiness invariant.
        // - `parametric_method_return_kind_from_receiver("name",
        //   args, [Struct(0)])` returns `None` per the pin above.
        //
        // Result: the destination slot's kind remains `None` at JIT
        // MIR time, the downstream `print(t.name())` Call-terminator
        // surfaces at the print-operand-kind-None Route A
        // surface-and-stop. This is the load-bearing Smoke 3 surface
        // shape Round 12 T1 surfaces for cross-crate conduit
        // extension.
        let mir = MirFunction {
            name: "test_trait_dispatch".to_string(),
            blocks: vec![BasicBlock {
                id: BasicBlockId(0),
                statements: vec![],
                terminator: Terminator {
                    kind: TerminatorKind::Call {
                        func: Operand::Constant(MirConstant::Method(
                            "name".to_string(),
                        )),
                        args: vec![copy_local(0)],
                        destination: Place::Local(SlotId(1)),
                        next: BasicBlockId(0),
                    },
                    span: shape_ast::Span::default(),
                },
            }],
            num_locals: 4,
            param_slots: vec![],
            param_reference_kinds: vec![],
            local_types: vec![],
            span: shape_ast::Span::default(),
            field_name_table: Default::default(),
            local_struct_type_names: Default::default(),
            local_typed_array_element_types: Default::default(),
            local_declared_scalar_types: Default::default(),
        };
        let concrete_types = vec![
            ConcreteType::placeholder_struct(shape_value::v2::concrete_type::StructLayoutId(0)),
            ConcreteType::Void,
            ConcreteType::Void,
            ConcreteType::Void,
        ];
        let kinds = infer_slot_kinds_with_concrete(&mir, &[], &concrete_types);
        assert_eq!(
            kinds[1],
            None,
            "Call-terminator destination for `t.name()` on a Struct(_) \
             receiver must remain unstamped — the trait-dispatch return \
             kind cannot be classified without a cross-crate conduit \
             extension. See classifier doc block 'User-defined-trait \
             surface boundary'."
        );
        // Pin the well_known cohort: `"name"` is NOT a well-known
        // invariant method name; without the parametric arm catching
        // it (which it cannot, per the pin above), there is no
        // classification path.
        assert_eq!(
            well_known_method_return_kind("name"),
            None,
            "`name` must not be a well-known method name — that would \
             be a soundness violation (different traits could declare \
             `name` with different return types, e.g. `trait T \
             {{ method name() -> string }}` vs `trait U {{ method name() -> int }}`)."
        );
    }

    #[test]
    fn parametric_classifier_remains_silent_for_struct_receiver_with_known_method_names() {
        // Cohort pin: the parametric arms for `get` / `sum` / `mean` /
        // `min` / `max` / `first` / `last` / `pop` / `load` / `fetch_*`
        // / `compare_exchange` are all keyed on receiver `ConcreteType`
        // matching `Array(_)` / `HashMap(_,_)` / `Mutex(_)` / `Atomic`
        // / `Lazy(_)`. A `Struct(_)` receiver must NOT accidentally
        // fall through to any of these arms — that would be a wrong-
        // carrier classification (a user struct with a `.sum()` method
        // is not an `Array<T>`).
        let cts = vec![ConcreteType::placeholder_struct(shape_value::v2::concrete_type::StructLayoutId(0))];
        for method_name in [
            "get",
            "sum",
            "mean",
            "min",
            "max",
            "first",
            "last",
            "pop",
            "load",
            "fetch_add",
            "fetch_sub",
            "compare_exchange",
            // Trait-dispatch-shaped names that could exist on user
            // structs but are NOT well-known or parametric arms:
            "name",
            "display",
            "to_string",
            "into",
            "from",
            "try_into",
            "try_from",
        ] {
            let kind = parametric_method_return_kind_from_receiver(
                method_name,
                &[copy_local(0)],
                &cts,
            );
            assert_eq!(
                kind, None,
                "method `{method_name}` on Struct(_) receiver must \
                 not be classified by the parametric cohort"
            );
        }
    }

    // ── Phase 3 cluster-0 Round 13 T1' positive pin (2026-05-13) ────────
    //
    // The companion of the 3 surface pins above. Asserts the
    // upstream-landing pathway works: when the VM-side conduit
    // producer
    // (`crates/shape-vm/src/compiler/helpers.rs::infer_top_level_concrete_types_from_mir_with_resolvers`)
    // has stamped `concrete_types[result_slot] = ConcreteType::String`
    // via the method-returns resolver chain (`mir.local_struct_type_names`
    // → `find_default_trait_impl_for_type_method` →
    // `function_return_concrete_types`), the JIT consumer's
    // `concrete_seed` projection
    // (`crates/shape-jit/src/mir_compiler/mod.rs:564`) picks it up to
    // `NativeKind::String` and `infer_slot_kinds_with_concrete`
    // preserves that kind through its existing-seed pass.

    #[test]
    fn trait_method_call_destination_seeded_from_concrete_types() {
        // Simulates the post-T1' compilation state: the VM-side
        // conduit producer has stamped the Call destination slot's
        // ConcreteType to the trait's declared return type
        // (`ConcreteType::String` for Smoke 3's `t.name()` where
        // `trait T { method name() -> string }`). The caller threads this
        // through `concrete_seed` so `existing[result_slot] =
        // Some(NativeKind::String)` when `infer_slot_kinds_with_concrete`
        // is invoked.
        //
        // Verifies: the existing-seed pass preserves the upstream
        // stamp — the Call-terminator pass at lines ~306-359 only
        // sets `kinds[idx]` if `kinds[idx].is_none()` (the
        // `idx < n && kinds[idx].is_none()` guard at line 316), so
        // the upstream `Some(NativeKind::String)` flows through
        // untouched.
        let mir = MirFunction {
            name: "test_trait_dispatch_post_t1prime".to_string(),
            blocks: vec![BasicBlock {
                id: BasicBlockId(0),
                statements: vec![],
                terminator: Terminator {
                    kind: TerminatorKind::Call {
                        func: Operand::Constant(MirConstant::Method(
                            "name".to_string(),
                        )),
                        args: vec![copy_local(0)],
                        destination: Place::Local(SlotId(1)),
                        next: BasicBlockId(0),
                    },
                    span: shape_ast::Span::default(),
                },
            }],
            num_locals: 4,
            param_slots: vec![],
            param_reference_kinds: vec![],
            local_types: vec![],
            span: shape_ast::Span::default(),
            field_name_table: Default::default(),
            local_struct_type_names: Default::default(),
            local_typed_array_element_types: Default::default(),
            local_declared_scalar_types: Default::default(),
        };
        // Simulate post-T1' upstream state: `concrete_types[1]` is
        // stamped String by the VM-side conduit; the caller has
        // projected it through `native_kind_from_concrete_type` to
        // form `existing[1] = Some(NativeKind::String)`.
        let concrete_types = vec![
            ConcreteType::placeholder_struct(shape_value::v2::concrete_type::StructLayoutId(0)),
            ConcreteType::String,
            ConcreteType::Void,
            ConcreteType::Void,
        ];
        let existing = vec![
            None,
            Some(NativeKind::String),
            None,
            None,
        ];
        let kinds = infer_slot_kinds_with_concrete(&mir, &existing, &concrete_types);
        assert_eq!(
            kinds[1],
            Some(NativeKind::String),
            "Post-T1' upstream-seeded Call-terminator destination slot \
             must preserve the trait-method declared return kind through \
             the JIT consumer's existing-seed pass — no clobber by the \
             classifier fallthrough"
        );
    }
}