aboutsummaryrefslogtreecommitdiff
path: root/src/boot/me/trans.ml
blob: 4f7172197c89e726bf8db5d8ef7ebfbb12f693be (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
(* Translation *)

open Semant;;
open Common;;
open Transutil;;

let log cx = Session.log "trans"
  (should_log cx cx.ctxt_sess.Session.sess_log_trans)
  cx.ctxt_sess.Session.sess_log_out
;;

let arr_max a = (Array.length a) - 1;;

type quad_idx = int
;;

type call =
    {
      call_ctrl: call_ctrl;
      call_callee_ptr: Il.operand;
      call_callee_ty: Ast.ty;
      call_callee_ty_params: Ast.ty array;
      call_output: Il.cell;
      call_args: Ast.atom array;
      call_iterator_args: Il.operand array;
      call_indirect_args: Il.operand array;
    }
;;

let need_ty_fn ty =
  match simplified_ty ty with
      Ast.TY_fn tfn -> tfn
    | _ -> bug () "need fn"
;;

let call_output_slot call =
  (fst (need_ty_fn call.call_callee_ty)).Ast.sig_output_slot
;;


type const =
    CONST_val of int64
  | CONST_frag of Asm.frag
;;

let trans_visitor
    (cx:ctxt)
    (inner:Walk.visitor)
    : Walk.visitor =

  let iflog thunk =
    if (should_log cx cx.ctxt_sess.Session.sess_log_trans)
    then thunk ()
    else ()
  in

  let curr_file = Stack.create () in
  let curr_stmt = Stack.create () in

  let (abi:Abi.abi) = cx.ctxt_abi in
  let (word_sz:int64) = word_sz abi in
  let (word_slot:Ast.slot) = word_slot abi in
  let (word_ty:Ast.ty) = Ast.TY_mach abi.Abi.abi_word_ty in

  let oper_str = Il.string_of_operand abi.Abi.abi_str_of_hardreg in
  let cell_str = Il.string_of_cell abi.Abi.abi_str_of_hardreg in

  let (word_bits:Il.bits) = abi.Abi.abi_word_bits in
  let (word_sty:Il.scalar_ty) = Il.ValTy word_bits in
  let (word_rty:Il.referent_ty) = Il.ScalarTy word_sty in
  let (word_ty_mach:ty_mach) =
    match word_bits with
        Il.Bits8 -> TY_u8
      | Il.Bits16 -> TY_u16
      | Il.Bits32 -> TY_u32
      | Il.Bits64 -> TY_u64
  in
  let (word_ty_signed_mach:ty_mach) =
    match word_bits with
        Il.Bits8 -> TY_i8
      | Il.Bits16 -> TY_i16
      | Il.Bits32 -> TY_i32
      | Il.Bits64 -> TY_i64
  in
  let word_n = word_n abi in
  let imm_of_ty (i:int64) (tm:ty_mach) : Il.operand =
    Il.Imm (Asm.IMM i, tm)
  in

  let imm (i:int64) : Il.operand = imm_of_ty i word_ty_mach in
  let simm (i:int64) : Il.operand = imm_of_ty i word_ty_signed_mach in
  let one = imm 1L in
  let neg_one = simm (-1L) in
  let zero = imm 0L in
  let imm_true = imm_of_ty 1L TY_u8 in
  let imm_false = imm_of_ty 0L TY_u8 in
  let zero_byte = imm_of_ty 0L TY_u8 in
  let nil_ptr = Il.Mem ((Il.Abs (Asm.IMM 0L)), Il.NilTy) in
  let wordptr_ty = Il.AddrTy (Il.ScalarTy word_sty) in

  let crate_rel fix =
    Asm.SUB (Asm.M_POS fix, Asm.M_POS cx.ctxt_crate_fixup)
  in

  let crate_rel_word fix =
    Asm.WORD (word_ty_signed_mach, crate_rel fix)
  in

  let crate_rel_imm (fix:fixup) : Il.operand =
    Il.Imm (crate_rel fix, word_ty_signed_mach)
  in

  let fixup_rel_word (base:fixup) (fix:fixup) =
    Asm.WORD (word_ty_signed_mach,
              Asm.SUB (Asm.M_POS fix, Asm.M_POS base))
  in

  let table_of_fixup_rel_fixups
      (fixup:fixup)
      (fixups:fixup array)
      : Asm.frag =
    Asm.SEQ (Array.map (fixup_rel_word fixup) fixups)
  in

  let table_of_table_rel_fixups (fixups:fixup array) : Asm.frag =
    let table_fix = new_fixup "vtbl" in
      Asm.DEF (table_fix, table_of_fixup_rel_fixups table_fix fixups)
  in

  let nabi_indirect =
      match cx.ctxt_sess.Session.sess_targ with
          Linux_x86_elf -> false
        | _ -> true
  in

  let nabi_rust =
    { nabi_indirect = nabi_indirect;
      nabi_convention = CONV_rust }
  in

  let out_mem_disp = abi.Abi.abi_frame_base_sz in
  let arg0_disp =
    Int64.add abi.Abi.abi_frame_base_sz abi.Abi.abi_implicit_args_sz
  in
  let frame_info_disp =
    Int64.neg (Int64.add
                 abi.Abi.abi_frame_info_sz
                 abi.Abi.abi_callee_saves_sz)
  in
  let frame_fns_disp = Int64.add frame_info_disp (word_n 0) in
  let frame_crate_ptr_disp = Int64.add frame_info_disp (word_n 1) in

  let fn_ty (id:node_id) : Ast.ty =
    Hashtbl.find cx.ctxt_all_item_types id
  in
  let fn_args_rty
      (id:node_id)
      (closure:Il.referent_ty option)
      : Il.referent_ty =
    let n_params =
      if defn_id_is_obj_fn_or_drop cx id
      then 0
      else n_item_ty_params cx id
    in
      call_args_referent_type cx n_params (fn_ty id) closure
  in

  let emitters = Stack.create () in
  let push_new_emitter (vregs_ok:bool) (fnid:node_id option) =
    let e = Il.new_emitter
      abi.Abi.abi_emit_target_specific
      vregs_ok fnid
    in
      Stack.push e emitters;
  in

  let push_new_emitter_with_vregs fnid = push_new_emitter true fnid in
  let push_new_emitter_without_vregs fnid = push_new_emitter false fnid in

  let pop_emitter _ = ignore (Stack.pop emitters) in
  let emitter _ = Stack.top emitters in
  let emitter_size_cache _ = (emitter()).Il.emit_size_cache in
  let flush_emitter_size_cache _ =
    Hashtbl.clear (emitter_size_cache())
  in

  let quad_categories = Hashtbl.create 0 in
  let quad_category_stack = Stack.create () in
  let in_quad_category name thunk =
    if cx.ctxt_sess.Session.sess_report_quads
    then Stack.push name quad_category_stack;
    let x = thunk() in
      if cx.ctxt_sess.Session.sess_report_quads
      then ignore (Stack.pop quad_category_stack);
      x
  in

  let credit name i =
    let c =
      htab_search_or_add quad_categories name
        (fun _ -> ref 0)
    in
      c := (!c) + i
  in

  let in_native_quad_category name thunk =
    if cx.ctxt_sess.Session.sess_report_quads
    then
      let i = (emitter()).Il.emit_pc in
      let x = thunk() in
      let j = (emitter()).Il.emit_pc in
        credit name (j-i);
        x
    else
      thunk()
  in

  let emit q =
    begin
      match q with
        Il.Jmp _ -> flush_emitter_size_cache();
        | _ -> ()
    end;
    Il.emit (emitter()) q;
    if cx.ctxt_sess.Session.sess_report_quads
    then
      begin
        let name =
          if Stack.is_empty quad_category_stack
          then "other"
          else Stack.top quad_category_stack
        in
          credit name 1
      end
  in

  let next_vreg _ = Il.next_vreg (emitter()) in
  let next_vreg_cell t = Il.next_vreg_cell (emitter()) t in
  let next_spill_cell t =
    let s = Il.next_spill (emitter()) in
    let spill_mem = Il.Spill s in
    let spill_ta = (spill_mem, Il.ScalarTy t) in
      Il.Mem spill_ta
  in
  let mark _ : quad_idx =
    flush_emitter_size_cache ();
    (emitter()).Il.emit_pc
  in
  let patch_existing (jmp:quad_idx) (targ:quad_idx) : unit =
    Il.patch_jump (emitter()) jmp targ;
    flush_emitter_size_cache ();
  in
  let patch (i:quad_idx) : unit =
    Il.patch_jump (emitter()) i (mark());
    flush_emitter_size_cache ();
    (* Insert a dead quad to ensure there's an otherwise-unused
     * jump-target here.
     *)
    emit Il.Dead
  in

  let current_fn () =
    match (emitter()).Il.emit_node with
        None -> bug () "current_fn without associated node"
      | Some id -> id
  in
  let current_fn_args_rty (closure:Il.referent_ty option) : Il.referent_ty =
    fn_args_rty (current_fn()) closure
  in
  let current_fn_callsz () = get_callsz cx (current_fn()) in

  let annotations _ =
    (emitter()).Il.emit_annotations
  in

  let annotate (str:string) =
    let e = emitter() in
      Hashtbl.add e.Il.emit_annotations e.Il.emit_pc str
  in

  let epilogue_jumps = Stack.create() in
  let simple_break_jumps = Stack.create() in (* not used for for-each *)

  let path_name (_:unit) : string =
    string_of_name (path_to_name cx.ctxt_curr_path)
  in

  let should_inline_structure_helpers _ = false in

  let based (reg:Il.reg) : Il.mem =
    Il.RegIn (reg, None)
  in

  let based_off (reg:Il.reg) (off:Asm.expr64) : Il.mem =
    Il.RegIn (reg, Some off)
  in

  let based_imm (reg:Il.reg) (imm:int64) : Il.mem =
    based_off reg (Asm.IMM imm)
  in

  let fp_imm (imm:int64) : Il.mem =
    based_imm abi.Abi.abi_fp_reg imm
  in

  let sp_imm (imm:int64) : Il.mem =
    based_imm abi.Abi.abi_sp_reg imm
  in

  let word_at (mem:Il.mem) : Il.cell =
    Il.Mem (mem, Il.ScalarTy (Il.ValTy word_bits))
  in

  let imov (dst:Il.cell) (src:Il.operand) : unit =
    emit (Il.imov dst src)
  in

  let mov (dst:Il.cell) (src:Il.operand) : unit =
    emit (Il.umov dst src)
  in

  let umul (dst:Il.cell) (a:Il.operand) (b:Il.operand) : unit =
    emit (Il.binary Il.UMUL dst a b);
  in

  let add (dst:Il.cell) (a:Il.operand) (b:Il.operand) : unit =
    emit (Il.binary Il.ADD dst a b);
  in

  let add_to (dst:Il.cell) (src:Il.operand) : unit =
    add dst (Il.Cell dst) src;
  in

  let sub (dst:Il.cell) (a:Il.operand) (b:Il.operand) : unit =
    emit (Il.binary Il.SUB dst a b);
  in

  let sub_from (dst:Il.cell) (src:Il.operand) : unit =
    sub dst (Il.Cell dst) src;
  in

  let lea (dst:Il.cell) (src:Il.mem) : unit =
    emit (Il.lea dst (Il.Cell (Il.Mem (src, Il.OpaqueTy))))
  in

  let rty_ptr_at (mem:Il.mem) (pointee_rty:Il.referent_ty) : Il.cell =
    Il.Mem (mem, Il.ScalarTy (Il.AddrTy pointee_rty))
  in

  let ptr_at (mem:Il.mem) (pointee_ty:Ast.ty) : Il.cell =
    rty_ptr_at mem (referent_type cx pointee_ty)
  in

  let need_scalar_ty (rty:Il.referent_ty) : Il.scalar_ty =
    match rty with
        Il.ScalarTy s -> s
      | _ -> bug () "expected ScalarTy"
  in

  let need_mem_cell (cell:Il.cell) : Il.typed_mem =
    match cell with
        Il.Mem a -> a
      | Il.Reg _ -> bug ()
          "expected address cell, got non-address register cell"
  in

  let need_cell (operand:Il.operand) : Il.cell =
    match operand with
        Il.Cell c -> c
      | _ -> bug () "expected cell, got operand %s"
          (Il.string_of_operand  abi.Abi.abi_str_of_hardreg operand)
  in

  let get_element_ptr =
    Il.get_element_ptr word_bits abi.Abi.abi_str_of_hardreg
  in

  let get_variant_ptr (mem_cell:Il.cell) (i:int) : Il.cell =
    match mem_cell with
        Il.Mem (mem, Il.UnionTy elts)
          when i >= 0 && i < (Array.length elts) ->
            assert ((Array.length elts) != 0);
            Il.Mem (mem, elts.(i))

      | _ -> bug () "get_variant_ptr %d on cell %s" i
          (cell_str mem_cell)
  in

  let rec ptr_cast = Il.ptr_cast

  and cell_cast = Il.cell_cast

  and curr_crate_ptr _ : Il.cell =
    word_at (fp_imm frame_crate_ptr_disp)

  and crate_rel_to_ptr (rel:Il.operand) (rty:Il.referent_ty) : Il.cell =
    (in_quad_category "crate_rel -> ptr"
       (fun _ ->
          let cell = next_vreg_cell (Il.AddrTy rty) in
          let diff = next_vreg_cell (Il.AddrTy rty) in
            mov cell (Il.Cell (curr_crate_ptr()));
            imov diff rel;
            add_to cell (Il.Cell diff);
            cell))

  (* 
   * Note: alias *requires* its cell to be in memory already, and should
   * only be used on slots you know to be memory-resident. Use 'aliasing' or 
   * 'via_memory' if you have a cell or operand you want in memory for a very
   * short period of time (the time spent by the code generated by the thunk).
   *)

  and alias (cell:Il.cell) : Il.cell =
    let mem, ty = need_mem_cell cell in
    let vreg_cell = next_vreg_cell (Il.AddrTy ty) in
      begin
        match ty with
            Il.NilTy -> ()
          | _ -> lea vreg_cell mem
      end;
      vreg_cell

  and force_to_mem (src:Il.operand) : Il.typed_mem =
    let do_spill op (t:Il.scalar_ty) =
      let spill = next_spill_cell t in
        mov spill op;
        need_mem_cell spill
    in
    match src with
        Il.Cell (Il.Mem ta) -> ta
      | Il.Cell (Il.Reg (_, t)) -> do_spill src t
      | Il.Imm (_,tm) -> do_spill src (Il.ValTy (Il.bits_of_ty_mach tm))
      | Il.ImmPtr (f, rty) ->
          do_spill
            (Il.Cell (crate_rel_to_ptr (crate_rel_imm f) rty))
            (Il.AddrTy rty)

  and force_to_reg (op:Il.operand) : Il.typed_reg =
    let do_mov op st =
      let tmp = next_vreg () in
      let regty = (tmp, st) in
        mov (Il.Reg regty) op;
        regty
    in
      match op with
          Il.Imm  (_, tm) -> do_mov op (Il.ValTy (Il.bits_of_ty_mach tm))
        | Il.ImmPtr (f, rty) ->
            do_mov
              (Il.Cell (crate_rel_to_ptr (crate_rel_imm f) rty))
              (Il.AddrTy rty)
        | Il.Cell (Il.Reg rt) -> rt
        | Il.Cell (Il.Mem (_, Il.ScalarTy st)) -> do_mov op st
        | Il.Cell (Il.Mem (_, rt)) ->
            bug () "forcing non-scalar referent of type %s to register"
              (Il.string_of_referent_ty rt)

  and via_memory (writeback:bool) (c:Il.cell) (thunk:Il.cell -> unit) : unit =
    match c with
        Il.Mem _ -> thunk c
      | Il.Reg _ ->
          let mem_c = Il.Mem (force_to_mem (Il.Cell c)) in
            thunk mem_c;
            if writeback
            then
              mov c (Il.Cell mem_c)

  and aliasing (writeback:bool) (c:Il.cell) (thunk:Il.cell -> unit) : unit =
    via_memory writeback c (fun c -> thunk (alias c))

  and pointee_type (ptr:Il.cell) : Il.referent_ty =
    match ptr with
        Il.Reg (_, (Il.AddrTy rt)) -> rt
      | Il.Mem (_, Il.ScalarTy (Il.AddrTy rt)) -> rt
      | _ ->
          bug () "taking pointee-type of non-address cell %s "
            (cell_str ptr)

  and deref (ptr:Il.cell) : Il.cell =
    let (r, st) = force_to_reg (Il.Cell ptr) in
      match st with
          Il.AddrTy rt -> Il.Mem (based r, rt)
        | _ -> bug () "dereferencing non-address cell of type %s "
            (Il.string_of_scalar_ty st)

  and deref_off (ptr:Il.cell) (off:Asm.expr64) : Il.cell =
    let (r, st) = force_to_reg (Il.Cell ptr) in
      match st with
          Il.AddrTy rt -> Il.Mem (based_off r off, rt)
        | _ -> bug () "offset-dereferencing non-address cell of type %s "
            (Il.string_of_scalar_ty st)

  and deref_imm (ptr:Il.cell) (imm:int64) : Il.cell =
    deref_off ptr (Asm.IMM imm)

  and tp_imm (imm:int64) : Il.cell =
    deref_imm abi.Abi.abi_tp_cell imm
  in


  let make_tydesc_tys n =
    Array.init n (fun _ -> Ast.TY_type)
  in

  let cell_vreg_num (vr:(int option) ref) : int =
    match !vr with
        None ->
          let v = (Il.next_vreg_num (emitter())) in
            vr := Some v;
            v
      | Some v -> v
  in

  let slot_id_referent_type (slot_id:node_id) : Il.referent_ty =
    slot_referent_type cx (get_slot cx slot_id)
  in

  let caller_args_cell (args_rty:Il.referent_ty) : Il.cell =
    Il.Mem (fp_imm out_mem_disp, args_rty)
  in

  let get_obj_box_from_calltup (args_cell:Il.cell) =
    let indirect_args =
      get_element_ptr args_cell Abi.calltup_elt_indirect_args
    in
      deref (cell_cast
               (get_element_ptr indirect_args Abi.indirect_args_elt_closure)
               (Il.ScalarTy (Il.AddrTy (obj_box_rty word_bits))))
  in

  let fp_to_args (fp:Il.cell) (args_rty:Il.referent_ty): Il.cell =
    let (reg, _) = force_to_reg (Il.Cell fp) in
    Il.Mem(based_imm reg out_mem_disp, args_rty)
  in

  let get_ty_param (ty_params:Il.cell) (param_idx:int) : Il.cell =
      get_element_ptr ty_params param_idx
  in

  let get_ty_params_of_frame
      (fnid:node_id)
      (fp:Il.reg)
      (n_ty_params:int)
      : Il.cell =

        let fn_ty = mk_simple_ty_fn [| |] in
        let fn_rty =
          call_args_referent_type cx n_ty_params fn_ty (Some Il.OpaqueTy)
        in
        let args_cell = Il.Mem (based_imm fp out_mem_disp, fn_rty) in

          if defn_id_is_obj_fn_or_drop cx fnid
          then
            (*
             * To get the typarams in an obj fn, we must go to the
             * implicit obj's captured type descriptor.
             *)
            let obj_box =
              get_obj_box_from_calltup args_cell
            in
            let obj = get_element_ptr obj_box Abi.box_rc_field_body in
            let tydesc = get_element_ptr obj Abi.obj_body_elt_tydesc in
            let ty_params_ty = Ast.TY_tup (make_tydesc_tys n_ty_params) in
            let ty_params_rty = referent_type cx ty_params_ty in
            let ty_params =
              get_element_ptr (deref tydesc) Abi.tydesc_field_first_param
            in
            let ty_params =
              cell_cast ty_params (Il.ScalarTy (Il.AddrTy ty_params_rty))
            in
              deref ty_params
          else
            (*
             * Regular function --- typarams are right in the frame calltup.
             *)
            get_element_ptr args_cell Abi.calltup_elt_ty_params
  in

  let get_args_for_current_frame _ =
    let curr_args_rty =
      current_fn_args_rty (Some Il.OpaqueTy)
    in
      caller_args_cell curr_args_rty
  in

  let get_indirect_args_for_current_frame _ =
    get_element_ptr (get_args_for_current_frame ())
      Abi.calltup_elt_indirect_args
  in

  let get_iterator_args_for_current_frame _ =
    get_element_ptr (get_args_for_current_frame ())
      Abi.calltup_elt_iterator_args
  in

  let get_closure_for_current_frame _ =
    let self_indirect_args =
      get_indirect_args_for_current_frame ()
    in
      get_element_ptr self_indirect_args
        Abi.indirect_args_elt_closure
  in

  let get_iter_block_fn_for_current_frame _ =
    let self_iterator_args =
      get_iterator_args_for_current_frame ()
    in
    let blk_fn = get_element_ptr self_iterator_args
      Abi.iterator_args_elt_block_fn
    in
      cell_cast blk_fn
        (Il.ScalarTy (Il.AddrTy Il.CodeTy))
  in

  let get_iter_outer_frame_ptr_for_current_frame _ =
    let self_iterator_args =
      get_iterator_args_for_current_frame ()
    in
      get_element_ptr self_iterator_args
        Abi.iterator_args_elt_outer_frame_ptr
  in

  (*
   * Within a for-each block, calculate the fp of an enclosing for-each block
   * or the enclosing function by chasing static links.
   *)
  let get_nth_outer_frame_ptr (diff:int) : Il.cell =
    (* All for-each block frames have the same args. *)
    let block_args_rty = current_fn_args_rty None in
    let current_fp = Il.Reg (abi.Abi.abi_fp_reg, Il.AddrTy Il.OpaqueTy) in
    let rec out (n:int) (fp:Il.cell) : Il.cell =
      if n == 0
      then fp
      else
        let args = fp_to_args fp block_args_rty in
        let iter_args = get_element_ptr args Abi.calltup_elt_iterator_args in
        let outer_fp =
          get_element_ptr iter_args Abi.iterator_args_elt_outer_frame_ptr
        in
          out (n - 1) outer_fp
    in
      out diff current_fp
  in

  let curr_stmt_depth _ =
    if (Stack.is_empty curr_stmt)
    then None
    else
      Some
        (get_stmt_depth cx (Stack.top curr_stmt))
  in

  let get_ty_params_of_current_frame _ : Il.cell =
    let fnid = current_fn() in
    let n_ty_params = n_item_ty_params cx fnid in
    let local _ =
      get_ty_params_of_frame fnid abi.Abi.abi_fp_reg n_ty_params
    in
      if Hashtbl.mem cx.ctxt_block_is_loop_body fnid
      then
        begin
          let outermost_fnid = get_loop_outermost_fn cx fnid in
            match curr_stmt_depth() with
                None -> local()
              | Some depth ->
                  iflog (fun _ ->
                           annotate "loading outermost frame ty params");
                  let (outermost_fp, _) =
                    force_to_reg (Il.Cell (get_nth_outer_frame_ptr depth))
                  in
                    get_ty_params_of_frame
                      outermost_fnid
                      outermost_fp
                      (n_item_ty_params cx outermost_fnid)
        end
      else
        local()
  in

  let get_ty_param_in_current_frame (param_idx:int) : Il.cell =
    get_ty_param (get_ty_params_of_current_frame()) param_idx
  in

  let linearize_ty_params (ty:Ast.ty) : (Ast.ty * Il.operand array) =
    let htab = Hashtbl.create 0 in
    let q = Queue.create () in
    let base = ty_fold_rebuild (fun t -> t) in
    let ty_fold_param (i, mut) =
      let param = Ast.TY_param (i, mut) in
        match htab_search htab param with
            Some p -> p
          | None ->
              let p = Ast.TY_param (Hashtbl.length htab, mut) in
                htab_put htab param p;
                Queue.add (Il.Cell (get_ty_param_in_current_frame i)) q;
                p
    in
      let fold =
        { base with
            ty_fold_param = ty_fold_param; }
      in
      let ty = fold_ty cx fold ty in
        (ty, queue_to_arr q)
  in

  let has_parametric_types_cache = Hashtbl.create 0 in
  let has_parametric_types (t:Ast.ty) : bool =
    let base = ty_fold_bool_or false in
    let ty_fold_param _ =
      true
    in
    let fold = { base with ty_fold_param = ty_fold_param } in
      htab_search_or_add
        has_parametric_types_cache t
        (fun _ -> fold_ty cx fold t)
  in

  let rec calculate_sz_full (ty_params:Il.cell) (size:size) : Il.operand =
    iflog (fun _ -> annotate
             (Printf.sprintf "calculating size %s"
                (string_of_size size)));
    let sub_sz = calculate_sz_full ty_params in
    match htab_search (emitter_size_cache()) size with
        Some op ->
          iflog (fun _ -> annotate
                   (Printf.sprintf "cached size %s is %s"
                      (string_of_size size)
                      (oper_str op)));
          op

      | _ ->
          let res =
            match size with
                SIZE_fixed i -> imm i
              | SIZE_fixup_mem_pos f -> Il.Imm (Asm.M_POS f, word_ty_mach)
              | SIZE_fixup_mem_sz f -> Il.Imm (Asm.M_SZ f, word_ty_mach)

              | SIZE_param_size i ->
                  let tydesc = deref (get_ty_param ty_params i) in
                    Il.Cell (get_element_ptr tydesc Abi.tydesc_field_size)

              | SIZE_param_align i ->
                  let tydesc = deref (get_ty_param ty_params i) in
                    Il.Cell (get_element_ptr tydesc Abi.tydesc_field_align)

              | SIZE_rt_neg a ->
                  let op_a = sub_sz a in
                  let tmp = next_vreg_cell word_sty in
                    emit (Il.unary Il.NEG tmp op_a);
                    Il.Cell tmp

              | SIZE_rt_add (a, b) ->
                  let op_a = sub_sz a in
                  let op_b = sub_sz b in
                  let tmp = next_vreg_cell word_sty in
                    add tmp op_a op_b;
                    Il.Cell tmp

              | SIZE_rt_mul (a, b) ->
                  let op_a = sub_sz a in
                  let op_b = sub_sz b in
                  let tmp = next_vreg_cell word_sty in
                    emit (Il.binary Il.UMUL tmp op_a op_b);
                    Il.Cell tmp

              | SIZE_rt_max (a, b) ->
                  let op_a = sub_sz a in
                  let op_b = sub_sz b in
                  let tmp = next_vreg_cell word_sty in
                    mov tmp op_a;
                    (* 
                     * FIXME: X86-ism going via a vreg; mem op= mem doesn't
                     * work and IL lacks sufficient brains to cope just now.
                     * Instead, should be
                     * 
                     *     emit (Il.cmp op_a op_b)
                     * 
                     * Luckily this isn't the worst hack since we already
                     * needed a tmp vreg for op_a.
                     *)
                    emit (Il.cmp (Il.Cell tmp) op_b);
                    let jmp = mark () in
                      emit (Il.jmp Il.JAE Il.CodeNone);
                      mov tmp op_b;
                      patch jmp;
                      Il.Cell tmp

              | SIZE_rt_align (align, off) ->
                  (*
                   * calculate off + pad where:
                   *
                   * pad = (align - (off mod align)) mod align
                   * 
                   * In our case it's always a power of two, 
                   * so we can just do:
                   * 
                   * mask = align-1
                   * off += mask
                   * off &= ~mask
                   *
                   *)
                  annotate "fetch alignment";
                  let op_align = sub_sz align in
                    annotate "fetch offset";
                    let op_off = sub_sz off in
                    let mask = next_vreg_cell word_sty in
                    let off = next_vreg_cell word_sty in
                      mov mask op_align;
                      sub_from mask one;
                      mov off op_off;
                      add_to off (Il.Cell mask);
                      emit (Il.unary Il.NOT mask (Il.Cell mask));
                      emit (Il.binary Il.AND
                              off (Il.Cell off) (Il.Cell mask));
                      Il.Cell off
          in
            iflog (fun _ -> annotate
                     (Printf.sprintf "calculated size %s is %s"
                        (string_of_size size)
                        (oper_str res)));
            htab_put (emitter_size_cache()) size res;
            res

  and calculate_sz c s =
    in_quad_category "size calc"
      (fun _ -> calculate_sz_full c s)

  and calculate_sz_in_current_frame (size:size) : Il.operand =
    calculate_sz (get_ty_params_of_current_frame()) size

  and callee_args_cell (tail_area:bool) (args_rty:Il.referent_ty) : Il.cell =
    if tail_area
    then
      Il.Mem (sp_off_sz (current_fn_callsz ()), args_rty)
    else
      Il.Mem (sp_imm 0L, args_rty)

  and based_sz (ty_params:Il.cell) (reg:Il.reg) (size:size) : Il.mem =
    match Il.size_to_expr64 size with
        Some e -> based_off reg e
      | None ->
             let runtime_size = calculate_sz ty_params size in
             let v = next_vreg () in
             let c = (Il.Reg (v, word_sty)) in
               mov c (Il.Cell (Il.Reg (reg, word_sty)));
               add_to c runtime_size;
               based v

  and fp_off_sz (size:size) : Il.mem =
    based_sz (get_ty_params_of_current_frame()) abi.Abi.abi_fp_reg size

  and sp_off_sz (size:size) : Il.mem =
    based_sz (get_ty_params_of_current_frame()) abi.Abi.abi_sp_reg size
  in

  let ty_sz_in_current_frame (ty:Ast.ty) : Il.operand =
    let rty = referent_type cx ty in
    let sz = Il.referent_ty_size word_bits rty in
      calculate_sz_in_current_frame sz
  in

  let ty_sz_with_ty_params
      (ty_params:Il.cell)
      (ty:Ast.ty)
      : Il.operand =
    let rty = referent_type cx ty in
    let sz = Il.referent_ty_size word_bits rty in
      calculate_sz ty_params sz
  in

  let get_element_ptr_dyn
      (ty_params:Il.cell)
      (mem_cell:Il.cell)
      (i:int)
      : Il.cell =
    match mem_cell with
        Il.Mem (mem, Il.StructTy elts)
          when i >= 0 && i < (Array.length elts) ->
            assert ((Array.length elts) != 0);
            begin
              let elt_rty = elts.(i) in
              let elt_off = Il.get_element_offset word_bits elts i in
                match elt_off with
                    SIZE_fixed fixed_off ->
                      Il.Mem (Il.mem_off_imm mem fixed_off, elt_rty)
                  | sz ->
                      let sz = calculate_sz ty_params sz in
                      let v = next_vreg word_sty in
                      let vc = Il.Reg (v, word_sty) in
                        lea vc mem;
                        add_to vc sz;
                        Il.Mem (based v, elt_rty)
            end
      | Il.Mem (_, Il.StructTy elts) ->
          bug ()
            "get_element_ptr dyn %d out of bounds (len %d) on cell %s"
            i (Array.length elts) (cell_str mem_cell)
      | _ ->
          bug () "get_element_ptr_dyn %d on cell %s" i (cell_str mem_cell)
  in

  let get_element_ptr_dyn_in_current_frame
      (mem_cell:Il.cell)
      (i:int)
      : Il.cell =
    get_element_ptr_dyn (get_ty_params_of_current_frame()) mem_cell i
  in

  let deref_off_sz
      (ty_params:Il.cell)
      (ptr:Il.cell)
      (size:size)
      : Il.cell =
    match Il.size_to_expr64 size with
        Some e -> deref_off ptr e
      | None ->
          let (r,_) = force_to_reg (Il.Cell ptr) in
          let mem = based_sz ty_params r size in
            Il.Mem (mem, (pointee_type ptr))
  in


  let cell_of_block_slot
      ?access_depth:(access_depth=curr_stmt_depth())
      (slot_id:node_id)
      : Il.cell =

    let referent_type = slot_id_referent_type slot_id in

    let local_access off =
      Il.Mem (fp_off_sz off, referent_type)
    in

    let outer_access off slot_depth depth =
      let _ = assert (slot_depth < depth) in
        let _ =
          iflog
            begin
              fun _ ->
                let k =
                  Hashtbl.find cx.ctxt_slot_keys slot_id
                in
                  annotate (Printf.sprintf
                              "access outer frame slot #%d = %s"
                              (int_of_node slot_id)
                              (Fmt.fmt_to_str Ast.fmt_slot_key k))
            end
        in
        let diff = depth - slot_depth in
        let _ = annotate "get outer frame pointer" in
        let fp = get_nth_outer_frame_ptr diff in
        let _ = annotate "calculate size" in
        let p =
          based_sz (get_ty_params_of_current_frame())
            (fst (force_to_reg (Il.Cell fp))) off
        in
          Il.Mem (p, referent_type)
    in

      match htab_search cx.ctxt_slot_vregs slot_id with
          Some vr ->
            begin
              match referent_type with
                  Il.ScalarTy st -> Il.Reg (Il.Vreg (cell_vreg_num vr), st)
                | Il.NilTy -> nil_ptr
                | Il.StructTy _ -> bugi cx slot_id
                    "cannot treat structured referent as single operand"
                | Il.UnionTy _ -> bugi cx slot_id
                    "cannot treat union referent as single operand"
                | Il.ParamTy _ -> bugi cx slot_id
                    "cannot treat parametric referent as single operand"
                | Il.OpaqueTy -> bugi cx slot_id
                    "cannot treat opaque referent as single operand"
                | Il.CodeTy ->  bugi cx slot_id
                    "cannot treat code referent as single operand"
            end
        | None ->
            begin
              match htab_search cx.ctxt_slot_offsets slot_id with
                  None -> bugi cx slot_id
                    "slot assigned to neither vreg nor offset"
                | Some off ->
                    if slot_is_obj_state cx slot_id
                    then
                      begin
                        let state_arg = get_closure_for_current_frame () in
                        let (slot_mem, _) =
                          need_mem_cell (deref_off_sz
                                           (get_ty_params_of_current_frame())
                                           state_arg off)
                        in
                          Il.Mem (slot_mem, referent_type)
                      end
                    else
                      match access_depth with
                          None -> local_access off
                        | Some depth ->
                            let slot_depth = get_slot_depth cx slot_id in
                              if slot_depth <> depth
                              then
                                outer_access off slot_depth depth
                              else
                                local_access off
            end
  in

  let binop_to_jmpop (binop:Ast.binop) : Il.jmpop =
    match binop with
        Ast.BINOP_eq -> Il.JE
      | Ast.BINOP_ne -> Il.JNE
      | Ast.BINOP_lt -> Il.JL
      | Ast.BINOP_le -> Il.JLE
      | Ast.BINOP_ge -> Il.JGE
      | Ast.BINOP_gt -> Il.JG
      | _ -> bug () "Unhandled binop in binop_to_jmpop"
  in

  let get_vtbl_entry_idx (table_ptr:Il.cell) (i:int) : Il.cell =
    (* Vtbls are encoded as tables of table-relative displacements. *)
    let (table_mem, _) = need_mem_cell (deref table_ptr) in
    let disp = Il.Cell (word_at (Il.mem_off_imm table_mem (word_n i))) in
    let ptr_cell = next_vreg_cell (Il.AddrTy Il.CodeTy) in
      mov ptr_cell (Il.Cell table_ptr);
      add_to ptr_cell disp;
      ptr_cell
  in

  let get_vtbl_entry
      (obj_cell:Il.cell)
      (obj_ty:Ast.ty_obj)
      (id:Ast.ident)
      : (Il.cell * Ast.ty_fn) =
    let (_, fns) = obj_ty in
    let sorted_idents = sorted_htab_keys fns in
    let i = arr_idx sorted_idents id in
    let fn_ty = Hashtbl.find fns id in
    let table_ptr = get_element_ptr obj_cell Abi.obj_field_vtbl in
      (get_vtbl_entry_idx table_ptr i, fn_ty)
  in

  let rec trans_slot_lval_ext
      (initializing:bool)
      (base_ty:Ast.ty)
      (cell:Il.cell)
      (comp:Ast.lval_component)
      : (Il.cell * Ast.ty) =

    let bounds_checked_access at ty =
      let atop = trans_atom at in
      let unit_sz = ty_sz_in_current_frame ty in
      let idx = next_vreg_cell word_sty in
        mov idx atop;
        emit (Il.binary Il.UMUL idx (Il.Cell idx) unit_sz);
        let elt_mem = trans_bounds_check (deref cell) (Il.Cell idx) in
          (Il.Mem (elt_mem, referent_type cx ty), ty)
    in
      (* 
       * All lval components aside from explicit-deref just auto-deref
       * through all boxes to find their indexable referent.
       *)
    let base_ty = strip_mutable_or_constrained_ty base_ty in
    let (cell, base_ty) =
      if comp = Ast.COMP_deref
      then (cell, base_ty)
      else deref_ty DEREF_all_boxes initializing cell base_ty
    in

    match (base_ty, comp) with
        (Ast.TY_rec entries,
         Ast.COMP_named (Ast.COMP_ident id)) ->
          let i = arr_idx (Array.map fst entries) id in
            (get_element_ptr_dyn_in_current_frame cell i, snd entries.(i))

      | (Ast.TY_tup entries,
         Ast.COMP_named (Ast.COMP_idx i)) ->
          (get_element_ptr_dyn_in_current_frame cell i, entries.(i))

      | (Ast.TY_vec ty,
         Ast.COMP_atom at) ->
          bounds_checked_access at ty

      | (Ast.TY_str,
         Ast.COMP_atom at) ->
          bounds_checked_access at (Ast.TY_mach TY_u8)

      | (Ast.TY_obj obj_ty,
         Ast.COMP_named (Ast.COMP_ident id)) ->
          let (cell, fn_ty) = get_vtbl_entry cell obj_ty id in
            (cell, (Ast.TY_fn fn_ty))

      | (Ast.TY_box _, Ast.COMP_deref) ->
          deref_ty DEREF_one_box initializing cell base_ty

      | _ -> bug () "unhandled form of lval_ext in trans_slot_lval_ext"

  (* 
   * vec: operand holding ptr to vec.
   * mul_idx: index value * unit size.
   * return: ptr to element.
   *)
  and trans_bounds_check (vec:Il.cell) (mul_idx:Il.operand) : Il.mem =
    let (len:Il.cell) = get_element_ptr vec Abi.vec_elt_fill in
    let (data:Il.cell) = get_element_ptr vec Abi.vec_elt_data in
    let (base:Il.cell) = next_vreg_cell Il.voidptr_t in
    let (elt_reg:Il.reg) = next_vreg () in
    let (elt:Il.cell) = Il.Reg (elt_reg, Il.voidptr_t) in
    let (diff:Il.cell) = next_vreg_cell word_sty in
      annotate "bounds check";
      lea base (fst (need_mem_cell data));
      add elt (Il.Cell base) mul_idx;
      emit (Il.binary Il.SUB diff (Il.Cell elt) (Il.Cell base));
      let jmp = trans_compare_simple Il.JB (Il.Cell diff) (Il.Cell len) in
        trans_cond_fail "bounds check" jmp;
        based elt_reg

  and trans_const_atom
      (atom:Ast.atom)
      : (Ast.ty * const) =
    match atom with
        Ast.ATOM_literal lit ->
          begin
            match lit.node with
                Ast.LIT_nil -> (Ast.TY_nil, CONST_val 0L)
              | Ast.LIT_bool false -> (Ast.TY_bool, CONST_val 0L)
              | Ast.LIT_bool true -> (Ast.TY_bool, CONST_val 1L)
              | Ast.LIT_char c -> (Ast.TY_char, CONST_val (Int64.of_int c))
              | Ast.LIT_int i -> (Ast.TY_int, CONST_val i)
              | Ast.LIT_uint i -> (Ast.TY_uint, CONST_val i)
              | Ast.LIT_mach_int (m, i) -> (Ast.TY_mach m, CONST_val i)
          end

      | Ast.ATOM_lval lv ->
          trans_const_lval lv

      | Ast.ATOM_pexp _ ->
          unimpl None "constant-folding pexp atom"

  and trans_const_expr
      (expr:Ast.expr)
      : (Ast.ty * const) =
    match expr with
        Ast.EXPR_atom at -> trans_const_atom at

      | Ast.EXPR_binary (_, a, b) ->
          let _ = trans_const_atom a in
          let _ = trans_const_atom b in
            unimpl None "constant-folding binary expr"

      | Ast.EXPR_unary (_, x) ->
          let _ = trans_const_atom x in
            unimpl None "constant-folding unary expr"

  and trans_const_lval
      (lv:Ast.lval)
      : (Ast.ty * const) =
    assert (lval_base_is_item cx lv);
    let item = lval_item cx lv in
      match item.node.Ast.decl_item with
          Ast.MOD_ITEM_const (_, Some e) -> trans_const_expr e

        | Ast.MOD_ITEM_tag (hdr, _, i) when Array.length hdr = 0 ->
            (lval_ty cx lv,
             CONST_frag (Asm.WORD (word_ty_mach,
                                   Asm.IMM (Int64.of_int i))))

        | _ -> bug ()
            "trans_const_lval called on unsupported item lval '%a'"
              Ast.sprintf_lval lv

  and trans_lval_item
      (lv:Ast.lval)
      : (Il.cell * Ast.ty) =
    assert (lval_base_is_item cx lv);
    match trans_const_lval lv with

        (ty, CONST_val v) ->
          let r tm = Il.Reg (force_to_reg (imm_of_ty v tm)) in
          let f tm = (r tm, ty) in
            begin
              match ty with
                  Ast.TY_mach tm -> f tm
                | Ast.TY_uint -> f word_ty_mach
                | Ast.TY_int -> f word_ty_signed_mach
                | Ast.TY_bool -> f TY_u8
                | Ast.TY_char -> f TY_u32
                | Ast.TY_nil -> (nil_ptr, ty)

                | _ -> bug ()
                    "trans_lval_item on %a: unexpected type %a"
                      Ast.sprintf_lval lv Ast.sprintf_ty ty
            end

      | (ty, CONST_frag f) ->
          let item = lval_item cx lv in
          let ptr =
            crate_rel_to_ptr
              (trans_crate_rel_data_operand
                 (DATA_const item.id)
                 (fun _ -> f))
              (referent_type cx ty)
          in
            (deref ptr, ty)

  and trans_lval_full
      (initializing:bool)
      (lv:Ast.lval)
      : (Il.cell * Ast.ty) =

    let rec trans_slot_lval_full (initializing:bool) (outermost:bool) lv =
      let (cell, ty) =
        match lv with
            Ast.LVAL_ext (base, comp) ->
              let (base_cell, base_ty) =
                trans_slot_lval_full initializing false base
              in
                trans_slot_lval_ext initializing base_ty base_cell comp

          | Ast.LVAL_base _ ->
              let sloti = lval_base_to_slot cx lv in
              let cell = cell_of_block_slot sloti.id in
              let ty = slot_ty sloti.node in
              let cell = deref_slot initializing cell sloti.node in
                (cell, ty)
      in
      let (cell, ty) =
        if outermost
        then
          let id = lval_base_id lv in
          let dctrl =
            (* If this fails, type didn't visit the lval, and we
             * don't know whether to auto-deref the entire lval.
             * Crashing here is best. Compiler bug.
             *)
            match htab_search cx.ctxt_auto_deref_lval id with
                None ->
                  bugi cx id
                    "Lval without auto-deref info; bad typecheck?"
              | Some true -> DEREF_all_boxes
              | Some false -> DEREF_none
          in
            deref_ty dctrl initializing cell ty
        else (cell, ty)
      in
        iflog
          begin
            fun _ ->
              annotate
                (Printf.sprintf "lval %a = %s"
                   Ast.sprintf_lval lv
                   (cell_str cell))
          end;
        (cell, ty)

    in
      if lval_base_is_slot cx lv
      then trans_slot_lval_full initializing true lv
      else
        if initializing
        then err None "init item"
        else trans_lval_item lv

  and trans_lval_maybe_init
      (initializing:bool)
      (lv:Ast.lval)
      : (Il.cell * Ast.ty) =
    in_quad_category "lval"
      (fun _ -> trans_lval_full initializing lv)

  and trans_lval_init (lv:Ast.lval) : (Il.cell * Ast.ty) =
    trans_lval_maybe_init true lv

  and trans_lval (lv:Ast.lval) : (Il.cell * Ast.ty) =
    trans_lval_maybe_init false lv

  and trans_callee
      (flv:Ast.lval)
      : (Il.operand * Ast.ty) =
    (* direct call to item *)
    let fty = Hashtbl.find cx.ctxt_all_lval_types (lval_base_id flv) in
      if lval_base_is_item cx flv then
        let fn_item = lval_item cx flv in
        let fn_ptr = code_fixup_to_ptr_operand (get_fn_fixup cx fn_item.id) in
          (fn_ptr, fty)
      else
        (* indirect call to computed slot *)
        let (cell, _) = trans_lval flv in
          (Il.Cell cell, fty)

  and align x =
    Asm.ALIGN_FILE (16, Asm.ALIGN_MEM(16, x))

  and trans_crate_rel_data_operand
      (d:data)
      (thunk:unit -> Asm.frag)
      : Il.operand =
    let (fix, _) =
      htab_search_or_add cx.ctxt_data d
        begin
          fun _ ->
            let fix = new_fixup "data item" in
            let frag = align (Asm.DEF (fix, thunk())) in
              (fix, frag)
        end
    in
      crate_rel_imm fix

  and trans_crate_rel_data_frag (d:data) (thunk:unit -> Asm.frag) : Asm.frag =
    let (fix, _) =
      htab_search_or_add cx.ctxt_data d
        begin
          fun _ ->
            let fix = new_fixup "data item" in
            let frag = align (Asm.DEF (fix, thunk())) in
              (fix, frag)
        end
    in
      crate_rel_word fix

  and trans_crate_rel_static_string_operand (s:string) : Il.operand =
    trans_crate_rel_data_operand (DATA_str s) (fun _ -> Asm.ZSTRING s)

  and trans_crate_rel_static_string_frag (s:string) : Asm.frag =
    trans_crate_rel_data_frag (DATA_str s) (fun _ -> Asm.ZSTRING s)

  and trans_static_string (s:string) : Il.operand =
    Il.Cell (crate_rel_to_ptr
               (trans_crate_rel_static_string_operand s)
               (referent_type cx Ast.TY_str))

  and get_static_tydesc
      (idopt:node_id option)
      (t:Ast.ty)
      (sz:int64)
      (align:int64)
      (force_stateful:bool)
      : Il.operand =
    trans_crate_rel_data_operand
      (DATA_tydesc t)
      begin
        fun _ ->
          let tydesc_fixup = new_fixup "tydesc" in
          let fix fixup =
            fixup_rel_word tydesc_fixup fixup
          in
          let is_stateful =
            if (force_stateful || type_has_state cx t) then 1L else 0L
          in
            iflog
              (fun _ ->
                 log cx "tydesc for %a has sz=%Ld, align=%Ld, is_stateful=%Ld"
                   Ast.sprintf_ty t sz align is_stateful);
            Asm.DEF
              (tydesc_fixup,
               Asm.SEQ
                 [|
                   Asm.WORD (word_ty_mach, Asm.IMM 0L);
                   Asm.WORD (word_ty_mach, Asm.IMM sz);
                   Asm.WORD (word_ty_mach, Asm.IMM align);
                   fix (get_copy_glue t);
                   fix (get_drop_glue t);
                   begin
                     match ty_mem_ctrl cx t with
                         MEM_interior ->
                           Asm.WORD (word_ty_mach, Asm.IMM 0L);
                       | _ ->
                           fix (get_free_glue t (type_has_state cx t));
                   end;

                   if cx.ctxt_sess.Session.sess_minimal
                   then Asm.WORD (word_ty_mach, Asm.IMM 0L)
                   else fix (get_sever_glue t);

                   if cx.ctxt_sess.Session.sess_minimal
                   then Asm.WORD (word_ty_mach, Asm.IMM 0L)
                   else fix (get_mark_glue t);

                   (* Include any obj-dtor, if this is an obj and has one. *)
                   begin
                     match idopt with
                         None -> Asm.WORD (word_ty_mach, Asm.IMM 0L);
                       | Some oid ->
                           begin
                             let g = GLUE_obj_drop oid in
                               match htab_search cx.ctxt_glue_code g with
                                   Some code -> fix code.code_fixup
                                 | None ->
                                     Asm.WORD (word_ty_mach, Asm.IMM 0L);
                           end
                   end;
                   Asm.WORD (word_ty_mach, Asm.IMM is_stateful);
                 |])
      end

  and get_obj_vtbl (id:node_id) : Il.operand =
    let obj =
      match Hashtbl.find cx.ctxt_all_defns id with
          DEFN_item { Ast.decl_item = Ast.MOD_ITEM_obj obj;
                      Ast.decl_params = _} -> obj
        | _ -> bug () "Trans.get_obj_vtbl on non-obj referent"
    in
      trans_crate_rel_data_operand (DATA_obj_vtbl id)
        begin
          fun _ ->
            iflog (fun _ -> log cx "emitting %d-entry obj vtbl for %s"
                     (Hashtbl.length obj.Ast.obj_fns) (path_name()));
            table_of_table_rel_fixups
              (Array.map
                 begin
                   fun k ->
                     let fn = Hashtbl.find obj.Ast.obj_fns k in
                       get_fn_fixup cx fn.id
                 end
                 (sorted_htab_keys obj.Ast.obj_fns))
        end

  and copy_loop
      (dst:Il.cell)
      (src:Il.cell)
      (sz:Il.operand)
      (elt_sz:Il.operand)
      (elt_copy:Il.cell -> Il.cell -> unit)
      : unit =
    let eltp_sty = Il.AddrTy (Il.ScalarTy (Il.ValTy Il.Bits8)) in
    let dptr = next_vreg_cell eltp_sty in
    let sptr = next_vreg_cell eltp_sty in
    let dlim = next_vreg_cell eltp_sty in
      lea dptr (fst (need_mem_cell dst));
      lea sptr (fst (need_mem_cell src));
      mov dlim (Il.Cell dptr);
      add_to dlim sz;

      let fwd_jmp = mark () in
        emit (Il.jmp Il.JMP Il.CodeNone);
        let back_jmp_targ = mark () in

          elt_copy dptr sptr;

          add_to dptr elt_sz;
          add_to sptr elt_sz;

          patch fwd_jmp;
          let back_jmp =
            trans_compare_simple Il.JB (Il.Cell dptr) (Il.Cell dlim)
          in
            List.iter
              (fun j -> patch_existing j back_jmp_targ) back_jmp;


  and trans_copy_forward_args (args_rty:Il.referent_ty) : unit =
    let caller_args_cell = caller_args_cell args_rty in
    let callee_args_cell = callee_args_cell false args_rty in
    let nbytes = Il.referent_ty_size word_bits args_rty in
    let nbytes = calculate_sz_in_current_frame nbytes in
      copy_loop callee_args_cell caller_args_cell nbytes one
        begin
          fun dptr sptr ->
            mov (deref dptr) (Il.Cell (deref sptr))
        end


  and get_forwarding_obj_fn
      (ident:Ast.ident)
      (caller:Ast.ty_obj)
      (callee:Ast.ty_obj)
      : fixup =
    (* Forwarding "glue" is not glue in the normal sense of being called with
     * only Abi.worst_case_glue_call_args args; the functions are full-fleged
     * obj fns like any other, and they perform a full call to the target
     * obj. We just use the glue facility here to store the forwarding
     * operators somewhere.
     *)
    let g = GLUE_forward (ident, caller, callee) in
    let fix = new_fixup (glue_str cx g) in
    let fty = Hashtbl.find (snd caller) ident in
    let self_args_rty =
      call_args_referent_type cx 0
        (Ast.TY_fn fty) (Some (obj_box_rty word_bits))
    in
    let callsz = Il.referent_ty_size word_bits self_args_rty in
    let spill = new_fixup "forwarding fn spill" in
      trans_glue_frame_entry callsz spill true;
      let all_self_args_cell = caller_args_cell self_args_rty in
      let self_indirect_args_cell =
        get_element_ptr all_self_args_cell Abi.calltup_elt_indirect_args
      in
        (*
         * Note: this is wrong. This assumes our closure is a vtbl,
         * when in fact it is a pointer to a refcounted malloc slab
         * containing an obj.
         *)
      let closure_cell =
        deref (get_element_ptr self_indirect_args_cell
                 Abi.indirect_args_elt_closure)
      in

      let (callee_fn_cell, _) =
        get_vtbl_entry closure_cell callee ident
      in
        iflog (fun _ -> annotate "copy args forward to callee");
        trans_copy_forward_args self_args_rty;

        iflog (fun _ -> annotate "call through to callee");
        (* FIXME (issue #80): use a tail-call here. *)
        call_code (code_of_cell callee_fn_cell);
        trans_glue_frame_exit fix spill g;
        fix


  and get_forwarding_vtbl
      (caller:Ast.ty_obj)
      (callee:Ast.ty_obj)
      : Il.operand =
    trans_crate_rel_data_operand (DATA_forwarding_vtbl (caller,callee))
      begin
        fun _ ->
          let (_,fns) = caller in
          iflog (fun _ -> log cx "emitting %d-entry obj forwarding vtbl"
                   (Hashtbl.length fns));
            table_of_table_rel_fixups
              (Array.map
                 begin
                   fun k ->
                     get_forwarding_obj_fn k caller callee
                 end
                 (sorted_htab_keys fns))
        end

  and drop_existing_if_not_init init cell ty =
    if not init
    then drop_ty_in_current_frame cell ty

  and trans_new_str
      (initializing:bool)
      (dst:Ast.lval)
      (s:string)
      (id:node_id)
      : unit =
    (* Include null byte. *)
    let init_sz = Int64.of_int ((String.length s) + 1) in
    let (dst_cell, dst_ty) = trans_lval_maybe_init initializing dst in
      drop_existing_if_not_init initializing dst_cell dst_ty;
      let ptr =
        crate_rel_to_ptr
          (trans_crate_rel_data_operand
             (DATA_const id)
             (fun _ ->
               Asm.SEQ
                 [|
                   Asm.WORD (word_ty_signed_mach,
                             Asm.IMM Abi.const_refcount);
                   Asm.WORD (word_ty_mach, Asm.IMM init_sz);
                   Asm.WORD (word_ty_mach, Asm.IMM init_sz);
                   Asm.ZSTRING s
                 |]))
          (referent_type cx Ast.TY_str)
      in
        mov dst_cell (Il.Cell ptr);

  and trans_lit (lit:Ast.lit) : Il.operand =
    match lit with
        Ast.LIT_nil -> Il.Cell (nil_ptr)
      | Ast.LIT_bool false -> imm_false
      | Ast.LIT_bool true -> imm_true
      | Ast.LIT_char c -> imm_of_ty (Int64.of_int c) TY_u32
      | Ast.LIT_int i -> simm i
      | Ast.LIT_uint i -> imm i
      | Ast.LIT_mach_int (m, n) -> imm_of_ty n m

  and trans_atom (atom:Ast.atom) : Il.operand =
    iflog
      begin
        fun _ ->
          annotate (Fmt.fmt_to_str Ast.fmt_atom atom)
      end;
    match atom with
        Ast.ATOM_lval lv ->
          let (cell, ty) = trans_lval lv in
            Il.Cell (fst (deref_ty DEREF_none false cell ty))

      | Ast.ATOM_literal lit -> trans_lit lit.node
      | Ast.ATOM_pexp _ -> bug () "Trans.trans_atom on ATOM_pexp"


  and fixup_to_ptr_operand
      (imm_ok:bool)
      (fix:fixup)
      (referent_ty:Il.referent_ty)
      : Il.operand =
    if imm_ok
    then Il.ImmPtr (fix, referent_ty)
    else Il.Cell (crate_rel_to_ptr (crate_rel_imm fix) referent_ty)

  and code_fixup_to_ptr_operand (fix:fixup) : Il.operand =
    fixup_to_ptr_operand abi.Abi.abi_has_pcrel_code fix Il.CodeTy

  (* A pointer-valued op may be of the form ImmPtr, which carries its
   * target fixup, "constant-propagated" through trans so that
   * pc-relative addressing can make use of it whenever
   * appropriate. Reify_ptr exists for cases when you are about to
   * store an ImmPtr into a memory cell or other place beyond which the
   * compiler will cease to know about its identity; at this point you
   * should decay it to a crate-relative displacement and
   * (computationally) add it to the crate base value, before working
   * with it.
   * 
   * This helps you obey the IL type-system prohibition against
   * 'mov'-ing an ImmPtr to a cell. If you forget to call this
   * in the right places, you will get code-generation failures.
   *)
  and reify_ptr (op:Il.operand) : Il.operand =
    match op with
        Il.ImmPtr (fix, rty) ->
          Il.Cell (crate_rel_to_ptr (crate_rel_imm fix) rty)
      | _ -> op

  and annotate_quads (name:string) : unit =
    let e = emitter() in
    let quads = emitted_quads e in
    let annotations = annotations() in
      log cx "emitted quads for %s:" name;
      for i = 0 to arr_max quads
      do
        if Hashtbl.mem annotations i
        then
          List.iter
            (fun a -> log cx "// %s" a)
            (List.rev (Hashtbl.find_all annotations i));
        log cx "[%6d]\t%s" i
          (Il.string_of_quad
             abi.Abi.abi_str_of_hardreg quads.(i));
      done


  and write_frame_info_ptrs (fnid:node_id option) =
    let frame_fns =
      match fnid with
          None -> zero
        | Some _ when cx.ctxt_sess.Session.sess_minimal -> zero
        | Some fnid -> get_frame_glue_fns fnid
    in
    let crate_ptr_reg = next_vreg () in
    let crate_ptr_cell = Il.Reg (crate_ptr_reg, (Il.AddrTy Il.OpaqueTy)) in
      iflog (fun _ -> annotate "write frame-info pointers");
      Abi.load_fixup_addr (emitter())
        crate_ptr_reg cx.ctxt_crate_fixup Il.OpaqueTy;
      mov (word_at (fp_imm frame_crate_ptr_disp)) (Il.Cell (crate_ptr_cell));
      imov (word_at (fp_imm frame_fns_disp)) frame_fns

  and check_interrupt_flag _ =
    if cx.ctxt_sess.Session.sess_minimal
    then ()
    else
      begin
        let dom = next_vreg_cell wordptr_ty in
        let flag = next_vreg_cell word_sty in
          mov dom (Il.Cell (tp_imm (word_n Abi.task_field_dom)));
          mov flag (Il.Cell (deref_imm dom
                               (word_n Abi.dom_field_interrupt_flag)));
          let null_jmp = null_check flag in
            trans_yield ();
            patch null_jmp
      end

  and trans_glue_frame_entry
      (callsz:size)
      (spill:fixup)
      (user_level:bool)
      : unit =
    (*
     * The user_level flag is true to indicate that this is glue that is
     * not called via the push/pop mechanism of trans_call_glue, and thereby
     * may (legitimately) have callsz exceeding Abi.worst_case_glue_call_args.
     *
     * Assert that the callsz is indeed no bigger than our abi's purported
     * worst-case glue args.  Moreover, the callsz should be static for non-
     * user-level glue, so we can rely on (force_sz callsz) as a preliminary
     * assertion as well.
     *)
    if not user_level
    then assert ((Int64.compare
                    (force_sz callsz)
                    (Int64.mul
                       word_sz
                       (Int64.of_int Abi.worst_case_glue_call_args))) <= 0);

    let framesz = SIZE_fixup_mem_sz spill in
      push_new_emitter_with_vregs None;
      iflog (fun _ -> annotate "prologue");
      in_native_quad_category "prologue"
        (fun _ ->
           abi.Abi.abi_emit_fn_prologue (emitter())
             framesz callsz nabi_rust (upcall_fixup "upcall_grow_task")
             false cx.ctxt_sess.Session.sess_minimal);
      (in_quad_category "prologue"
         (fun _ -> write_frame_info_ptrs None));
      (* FIXME: not clear why, but checking interrupt in glue context
       * causes many.rs to crash when run on a sufficiently large number
       * of tasks; possibly a weird interaction with growing? *)
      (* check_interrupt_flag (); *)
      iflog (fun _ -> annotate "finished prologue");

  and emitted_quads e =
    Array.sub e.Il.emit_quads 0 e.Il.emit_pc

  and capture_emitted_glue (fix:fixup) (spill:fixup) (g:glue) : unit =
    let e = emitter() in
      iflog (fun _ -> annotate_quads (glue_str cx g));
      let code = { code_fixup = fix;
                   code_quads = emitted_quads e;
                   code_vregs_and_spill = Some (Il.num_vregs e, spill); }
      in
        htab_put cx.ctxt_glue_code g code

  and trans_glue_frame_exit (fix:fixup) (spill:fixup) (g:glue) : unit =
    iflog (fun _ -> annotate "epilogue");
    abi.Abi.abi_emit_fn_epilogue (emitter());
    capture_emitted_glue fix spill g;
    pop_emitter ()

  and emit_exit_task_glue (fix:fixup) (g:glue) : unit =
    let name = glue_str cx g in
    let spill = new_fixup (name ^ " spill") in
      push_new_emitter_with_vregs None;
      (* 
       * We return-to-here in a synthetic frame we did not build; our job is
       * merely to call upcall_exit.
       *)
      iflog (fun _ -> annotate "assume 'exited' state");
      trans_void_upcall "upcall_exit" [| |];
      capture_emitted_glue fix spill g;
      pop_emitter ()

  and get_exit_task_glue _ : fixup =
    let g = GLUE_exit_task in
      match htab_search cx.ctxt_glue_code g with
          Some code -> code.code_fixup
        | None ->
            let fix = cx.ctxt_exit_task_fixup in
              emit_exit_task_glue fix g;
              fix

  (* FIXME (issue #2): this should eventually use tail calling logic *)

  and emit_fn_thunk_glue
      (n_ty_params:int)
      (arg_slots:Ast.slot array)
      (arg_bound_flags:bool array)
      (fix:fixup)
      (g:glue)
      : unit =

    let extract_slots want_bound =
      arr_filter_some
        (arr_map2
           (fun slot bound ->
              if bound = want_bound then Some slot else None)
           arg_slots
           arg_bound_flags)
    in
    let bound_slots = extract_slots true in
    let unbound_slots = extract_slots false in

    let (self_ty:Ast.ty) = mk_simple_ty_fn unbound_slots in
    let (callee_ty:Ast.ty) = mk_simple_ty_fn arg_slots in

    let self_box_rty = closure_box_rty cx n_ty_params bound_slots in

    let self_args_rty =
      call_args_referent_type cx 0 self_ty (Some self_box_rty)
    in

    let callee_args_rty =
      call_args_referent_type cx n_ty_params callee_ty (Some Il.OpaqueTy)
    in

    let callsz = Il.referent_ty_size word_bits callee_args_rty in
    let spill = new_fixup "bind glue spill" in
      trans_glue_frame_entry callsz spill true;

      let all_self_args_cell = caller_args_cell self_args_rty in

      let self_indirect_args_cell =
        get_element_ptr all_self_args_cell Abi.calltup_elt_indirect_args
      in

      let box_cell =
        deref (get_element_ptr self_indirect_args_cell
                 Abi.indirect_args_elt_closure)
      in

      let closure_cell =
        get_element_ptr box_cell Abi.box_rc_field_body
      in

      let closure_target_cell =
        get_element_ptr closure_cell Abi.closure_body_elt_target
      in

      let closure_target_code_cell =
        get_element_ptr closure_target_cell Abi.fn_field_code
      in

      let self_args_cell =
        get_element_ptr all_self_args_cell Abi.calltup_elt_args
      in

      let self_ty_params_cell =
        get_element_ptr all_self_args_cell Abi.calltup_elt_ty_params
      in

        merge_bound_args
          n_ty_params
          self_args_rty callee_args_rty
          arg_slots arg_bound_flags;
        iflog (fun _ -> annotate "call through to closure target fn");

        call_code (code_of_cell closure_target_code_cell);

        (* Drop the args we were passed. *)
        Array.iteri
          (fun i slot ->
             let cell = get_element_ptr self_args_cell i in
               drop_slot self_ty_params_cell cell slot)
          unbound_slots;

        trans_glue_frame_exit fix spill g


  and get_fn_thunk_glue
      (bind_id:node_id)
      (n_ty_params:int)
      (arg_slots:Ast.slot array)
      (arg_bound_flags:bool array)
      : fixup =
    let g = GLUE_fn_thunk bind_id in
      match htab_search cx.ctxt_glue_code g with
          Some code -> code.code_fixup
        | None ->
            let fix = new_fixup (glue_str cx g) in
              emit_fn_thunk_glue n_ty_params arg_slots arg_bound_flags fix g;
              fix


  (* 
   * Mem-glue functions are either 'mark', 'drop' or 'free', they take
   * one pointer arg and return nothing.
   *)

  and trans_mem_glue_frame_entry (n_outgoing_args:int) (spill:fixup) : unit =
    let callsz = SIZE_fixed (word_n n_outgoing_args) in
      trans_glue_frame_entry callsz spill false

  and get_mem_glue_full (g:glue) (inner:Il.mem -> unit) : fixup =
    match htab_search cx.ctxt_glue_code g with
        Some code -> code.code_fixup
      | None ->
          begin
            let name = glue_str cx g in
            let fix = new_fixup name in
              (* 
               * Put a temporary code entry in the table to handle
               * recursive emit calls during the generation of the glue
               * function.
               *)
            let tmp_code = { code_fixup = fix;
                             code_quads = [| |];
                             code_vregs_and_spill = None; } in
            let spill = new_fixup (name ^ " spill") in
              htab_put cx.ctxt_glue_code g tmp_code;
              log cx "emitting glue: %s" name;
              trans_mem_glue_frame_entry Abi.worst_case_glue_call_args spill;
              let (arg:Il.mem) = fp_imm arg0_disp in
                inner arg;
                Hashtbl.remove cx.ctxt_glue_code g;
                trans_glue_frame_exit fix spill g;
                fix
          end

  and get_mem_glue g i =
    in_quad_category "mem glue" (fun _ -> get_mem_glue_full g i)

  and get_typed_mem_glue
      (g:glue)
      (fty:Ast.ty)
      (inner:Il.cell -> Il.cell -> unit)
      : fixup =
      get_mem_glue g
        begin
          fun _ ->
            let n_ty_params = 0 in
            let calltup_rty =
              call_args_referent_type cx n_ty_params fty None
            in
            let calltup_cell = caller_args_cell calltup_rty in
            let out_cell =
              get_element_ptr calltup_cell Abi.calltup_elt_out_ptr
            in
            let args_cell =
              get_element_ptr calltup_cell Abi.calltup_elt_args
            in
              begin
                match Il.cell_referent_ty args_cell with
                    Il.StructTy az ->
                      assert ((Array.length az)
                              <= Abi.worst_case_glue_call_args);
                  | _ -> bug () "unexpected cell referent ty in glue args"
              end;
              inner out_cell args_cell
        end

  and trace_str b s =
    if b
    then
      begin
        let static = trans_static_string s in
          trans_void_upcall "upcall_trace_str" [| static |]
      end

  and trace_word b w =
    if b
    then
      trans_void_upcall "upcall_trace_word" [| Il.Cell w |]

  and ty_params_covering (t:Ast.ty) : Ast.slot =
    let n_ty_params = n_used_type_params cx t in
    let params = make_tydesc_tys n_ty_params in
      alias_slot (Ast.TY_tup params)

  and get_drop_glue
      (ty:Ast.ty)
      : fixup =
    let ty = get_genericized_ty ty in
    let g = GLUE_drop ty in
    let inner _ (args:Il.cell) =
      let ty_params = deref (get_element_ptr args 0) in
      let cell = get_element_ptr args 1 in
        note_drop_step ty "in drop-glue, dropping";
        trace_word cx.ctxt_sess.Session.sess_trace_drop cell;
        drop_ty_full true ty_params (deref cell) ty;
        note_drop_step ty "drop-glue complete";
    in
    let ty_params_ptr = ty_params_covering ty in
    let fty = mk_simple_ty_fn [| ty_params_ptr; alias_slot ty |] in
      get_typed_mem_glue g fty inner


  and get_free_glue
      (ty:Ast.ty)
      (is_gc:bool)
      : fixup =
    let ty = get_genericized_ty ty in
    let g = GLUE_free ty in
    let inner _ (args:Il.cell) =
      (* Free-glue assumes it's called with a pointer to a box allocation with
       * normal box layout. It's just a way to move drop+free out of leaf
       * code.
       *)
      let ty_params = deref (get_element_ptr args 0) in
      let cell = get_element_ptr args 1 in
        free_ty is_gc ty_params ty cell
    in
    let ty_params_ptr = ty_params_covering ty in
    let fty = mk_simple_ty_fn [| ty_params_ptr; local_slot ty |] in
      get_typed_mem_glue g fty inner


  and get_sever_glue
      (ty:Ast.ty)
      : fixup =
    let ty = get_genericized_ty ty in
    let g = GLUE_sever ty in
    let inner _ (args:Il.cell) =
      let ty_params = deref (get_element_ptr args 0) in
      let cell = get_element_ptr args 1 in
        note_gc_step ty "in sever-glue, severing";
        sever_ty ty_params (deref cell) ty;
        note_gc_step ty "in sever-glue complete";
    in
    let ty_params_ptr = ty_params_covering ty in
    let fty = mk_simple_ty_fn [| ty_params_ptr; alias_slot ty |] in
      get_typed_mem_glue g fty inner


  and get_mark_glue
      (ty:Ast.ty)
      : fixup =
    let ty = get_genericized_ty ty in
    let g = GLUE_mark ty in
    let inner _ (args:Il.cell) =
      let ty_params = deref (get_element_ptr args 0) in
      let cell = get_element_ptr args 1 in
        note_gc_step ty "in mark-glue, marking";
        mark_ty ty_params (deref cell) ty;
        note_gc_step ty "mark-glue complete";
    in
    let ty_params_ptr = ty_params_covering ty in
    let fty = mk_simple_ty_fn [| ty_params_ptr; alias_slot ty |] in
      get_typed_mem_glue g fty inner


  and get_clone_glue
      (ty:Ast.ty)
      : fixup =
    let ty = get_genericized_ty ty in
    let g = GLUE_clone ty in
    let inner (out_ptr:Il.cell) (args:Il.cell) =
      let dst = deref out_ptr in
      let ty_params = deref (get_element_ptr args 0) in
      let src = deref (get_element_ptr args 1) in
      let clone_task = get_element_ptr args 2 in
        clone_ty ty_params clone_task dst src ty
    in
    let ty_params_ptr = ty_params_covering ty in
    let fty =
      mk_ty_fn
        (local_slot ty)        (* dst *)
        [|
          ty_params_ptr;
          alias_slot ty;       (* src *)
          word_slot            (* clone-task *)
        |]
    in
      get_typed_mem_glue g fty inner


  and get_copy_glue
      (ty:Ast.ty)
      : fixup =
    let ty = get_genericized_ty ty in
    let arg_ty_params_alias = 0 in
    let arg_src_alias = 1 in
    let arg_initflag = 2 in

    let g = GLUE_copy ty in
    let inner (out_ptr:Il.cell) (args:Il.cell) =
      let dst = deref out_ptr in
      let ty_params = deref (get_element_ptr args arg_ty_params_alias) in
      let src = deref (get_element_ptr args arg_src_alias) in

      (* Translate copy code for the dst-initializing and
       * dst-non-initializing cases and branch accordingly. *)
      let initflag = get_element_ptr args arg_initflag in
      let jmps = trans_compare_simple Il.JNE (Il.Cell initflag) one in

        trans_copy_ty_full true ty_params true dst ty src ty;

        let skip_noninit_jmp = mark() in
          emit (Il.jmp Il.JMP Il.CodeNone);
          List.iter patch jmps;

          trans_copy_ty_full true ty_params false dst ty src ty;

          patch skip_noninit_jmp;
    in
    let ty_params_ptr = ty_params_covering ty in
    let fty =
      mk_ty_fn
        (local_slot ty)
        [| ty_params_ptr; alias_slot ty; word_slot |]
    in
      get_typed_mem_glue g fty inner

  and get_cmp_glue ty =
    let ty = get_genericized_ty ty in
    let arg_ty_params_alias = 0 in
    let arg_lhs_alias = 1 in
    let arg_rhs_alias = 2 in
    let g = GLUE_cmp ty in
    let inner (out_ptr:Il.cell) (args:Il.cell) =
      let dst = deref out_ptr in
      let ty_params = deref (get_element_ptr args arg_ty_params_alias) in
      let lhs = deref (get_element_ptr args arg_lhs_alias) in
      let rhs = deref (get_element_ptr args arg_rhs_alias) in
      let early_finish_jmps = Queue.create () in
      let cmp_part lhs rhs ty =
        let tmp = trans_cmp ~ty_params ~ty (Il.Cell lhs) (Il.Cell rhs) in
        let keep_going_jmps =
          trans_compare_simple Il.JE tmp zero
        in
          mov dst tmp;
          Queue.add (mark()) early_finish_jmps;
          emit (Il.jmp Il.JMP Il.CodeNone);
          List.iter patch keep_going_jmps
      in
        mov dst zero;
        iter_ty_parts_full ty_params lhs rhs ty cmp_part;
        Queue.iter patch early_finish_jmps;
    in
    let ty_params_ptr = ty_params_covering ty in
    let fty =
      mk_ty_fn
        (local_slot Ast.TY_int)
        [| ty_params_ptr; alias_slot ty; alias_slot ty |]
    in
      get_typed_mem_glue g fty inner

  (*
   * Vector-growth glue takes the following arguments:
   *
   *   0. (Implicit) task ptr
   *   1. Pointer to the typarams of the caller's frame (possibly required to
   *      be passed to element's copy glue).
   *   2. Pointer to the tydesc of the vec, so that we can tell if it's gc
   *      mem, and have a tydesc to pass to malloc if we're allocating anew.
   *   3. Pointer to tydesc of the vec's stored element type, so that elements
   *      can be copied to a newly alloc'ed vec if one must be created.
   *   4. Alias to vec that needs to grow (i.e. ptr to ptr to rust_vec).
   *   5. Number of bytes of growth requested
   *)
  and emit_vec_grow_glue
      (fix:fixup)
      (g:glue)
      : unit =
    let arg_typarams_ptr = 0 in
    let arg_vec_tydesc_ptr = 1 in
    let arg_elt_tydesc_ptr = 2 in
    let arg_vec_alias = 3 in
    let arg_nbytes = 4 in

    let name = glue_str cx g in
      log cx "emitting glue: %s" name;

      let fn_ty =
        mk_simple_ty_fn
          [| ty_params_covering Ast.TY_int;      (* an OK lie *)
             local_slot Ast.TY_type;
             local_slot Ast.TY_type;
             alias_slot (Ast.TY_vec Ast.TY_int); (* an OK lie *)
             local_slot Ast.TY_uint |]
      in

      let args_rty = call_args_referent_type cx 0 fn_ty None in

      let callsz = Il.referent_ty_size word_bits args_rty in
      let spill = new_fixup (name ^ " spill") in
        trans_glue_frame_entry callsz spill false;

        let args_cell =
          get_element_ptr (caller_args_cell args_rty) Abi.calltup_elt_args
        in

        let vec_alias_cell = get_element_ptr args_cell arg_vec_alias in
        let vec_cell = deref vec_alias_cell in
        let nbytes_cell = get_element_ptr args_cell arg_nbytes in
        let vec_td_ptr_cell = get_element_ptr args_cell arg_vec_tydesc_ptr in
        let elt_td_ptr_cell = get_element_ptr args_cell arg_elt_tydesc_ptr in
        let ty_params_cell =
          deref (get_element_ptr args_cell arg_typarams_ptr)
        in

        let need_copy_cell = next_vreg_cell word_sty in
        let new_vec_cell = next_vreg_cell (vec_sty word_bits) in

          aliasing true need_copy_cell
            begin
              fun need_copy_alias_cell ->
                trans_upcall "upcall_vec_grow"
                  new_vec_cell
                  [| Il.Cell vec_cell;
                     Il.Cell nbytes_cell;
                     Il.Cell need_copy_alias_cell;
                     Il.Cell vec_td_ptr_cell; |]
            end;

          let no_copy_jmps =
            trans_compare_simple Il.JE (Il.Cell need_copy_cell) zero
          in

            let dst_vec = deref new_vec_cell in
            let src_vec = deref vec_cell in

            let fill =
              get_element_ptr_dyn ty_params_cell src_vec Abi.vec_elt_fill
            in
            let elt_sz =
              get_element_ptr (deref elt_td_ptr_cell) Abi.tydesc_field_size
            in

            let dst_buf =
              get_element_ptr_dyn ty_params_cell dst_vec Abi.vec_elt_data
            in
            let src_buf =
              get_element_ptr_dyn ty_params_cell src_vec Abi.vec_elt_data
            in

            let ty_params_ptr =
              get_tydesc_params ty_params_cell elt_td_ptr_cell
            in

            let initflag = Il.Reg (force_to_reg one) in

              copy_loop dst_buf src_buf (Il.Cell fill) (Il.Cell elt_sz)
                begin
                  fun dptr sptr ->
                    trans_call_dynamic_glue
                      elt_td_ptr_cell
                      Abi.tydesc_field_copy_glue
                      (Some (deref dptr))
                      [| ty_params_ptr; sptr; initflag |]
                      None
                end;

              (* Set the new vec's fill to the original vec's fill *)
              let dst_fill = get_element_ptr dst_vec Abi.vec_elt_fill in
              let v = next_vreg_cell word_sty in
                mov v (Il.Cell fill);
                mov dst_fill (Il.Cell v);

                List.iter patch no_copy_jmps;

                mov vec_cell (Il.Cell new_vec_cell);

                trans_glue_frame_exit fix spill g


  and get_vec_grow_glue _
      : fixup =
    let g = GLUE_vec_grow in
    match htab_search cx.ctxt_glue_code g with
        Some code -> code.code_fixup
      | None ->
          begin
            let fix = new_fixup (glue_str cx g) in
              emit_vec_grow_glue fix g;
              fix
          end

  (* Glue functions use mostly the same calling convention as ordinary
   * functions.
   * 
   * Each glue function expects its own particular arguments, which are
   * usually aliases-- ie, caller doesn't transfer ownership to the
   * glue. And nothing is represented in terms of AST nodes. So we
   * don't do lvals-and-atoms here.
   *)

  and trans_call_glue
      (code:Il.code)
      (dst:Il.cell option)
      (args:Il.cell array)
      (clo:Il.cell option)
      : unit =
    let inner dst cloptr =
        for i = ((Array.length args) - 1) downto 0
        do
          emit (Il.Push (Il.Cell args.(i)))
        done;
        emit (Il.Push cloptr);
        emit (Il.Push (Il.Cell abi.Abi.abi_tp_cell));
        emit (Il.Push dst);
        call_code code;
        add_to (Il.Reg (abi.Abi.abi_sp_reg, word_sty))
          (imm (Int64.mul word_sz (Int64.of_int (3 + (Array.length args)))));
    in
    let cloptr =
      match clo with
          None -> zero
        | Some cloptr -> Il.Cell cloptr
    in
      match dst with
          None -> inner zero cloptr
        | Some dst ->
            aliasing true dst (fun dst -> inner (Il.Cell dst) cloptr)

  and trans_call_static_glue
      (callee:Il.operand)
      (dst:Il.cell option)
      (args:Il.cell array)
      (clo:Il.cell option)
      : unit =
    trans_call_glue (code_of_operand callee) dst args clo

  and trans_call_dynamic_glue
      (tydesc:Il.cell)
      (idx:int)
      (dst:Il.cell option)
      (args:Il.cell array)
      (clo:Il.cell option)
      : unit =
    let fptr = get_vtbl_entry_idx tydesc idx in
      trans_call_glue (code_of_operand (Il.Cell fptr)) dst args clo

  and trans_call_simple_static_glue
      (fix:fixup)
      (ty_params:Il.cell)
      (args:Il.cell array)
      (clo:Il.cell option)
      : unit =
    trans_call_static_glue
      (code_fixup_to_ptr_operand fix)
      None
      (Array.append [| alias ty_params |] args)
      clo

  and get_tydesc_params
      (outer_ty_params:Il.cell)
      (td:Il.cell)
      : Il.cell =
    let first_param =
      get_element_ptr (deref td) Abi.tydesc_field_first_param
    in
    let res = next_vreg_cell Il.voidptr_t in
      mov res (Il.Cell (alias outer_ty_params));
      emit (Il.cmp (Il.Cell first_param) zero);
      let no_param_jmp = mark() in
        emit (Il.jmp Il.JE Il.CodeNone);
        mov res (Il.Cell first_param);
        patch no_param_jmp;
        res

  and trans_call_simple_dynamic_glue
      (ty_param:int)
      (vtbl_idx:int)
      (ty_params:Il.cell)
      (args:Il.cell array)
      (clo:Il.cell option)
      : unit =
    iflog (fun _ ->
             annotate (Printf.sprintf "calling tydesc[%d].glue[%d]"
                         ty_param vtbl_idx));
    let td = get_ty_param ty_params ty_param in
    let ty_params_ptr = get_tydesc_params ty_params td in
      trans_call_dynamic_glue
        td
        vtbl_idx
        None
        (Array.append [| ty_params_ptr |] args)
        clo

  (*
   * NB: there are 2 categories of comparisons:
   *
   *   - Those called 'compare' that take a jmpop and return a jump list
   *     that the caller should patch.
   *
   *   - Those called 'cmp' that return a number, -1/0/1, indicating the
   *     relative order of lhs and rhs.
   *
   * While in theory compare could be built out of cmp, on real machines
   * we are forced to build cmp out of compare.
   *)


  (* 
   * [trans_cmp] returns the result-code of a three-value comparison, 
   * which is an operand representing the ordering of lhs and rhs. -1 means
   * less than, 0 means equal, 1 means greater-than.
   *
   * We assume that the LHS and RHS of the comparison have the same type, an
   * invariant that the typechecker enforces.
   *)
  and trans_cmp
      ~ty_params:(ty_params:Il.cell)
      ~ty:(ty:Ast.ty)
      (lhs:Il.operand)
      (rhs:Il.operand)
      : Il.operand =
    let ty = strip_mutable_or_constrained_ty ty in
    let (result:Il.cell) = next_vreg_cell (Il.ValTy Il.Bits32) in
      begin
        match ty with

            Ast.TY_bool
          | Ast.TY_mach _
          | Ast.TY_int
          | Ast.TY_uint
          | Ast.TY_char ->
              let cjmp =
                if type_is_unsigned_2s_complement ty
                then Il.JB
                else Il.JL
              in
                (* Start with assumption lhs < rhs *)
                imov result neg_one;
                let lhs_lt_rhs_jmps =
                  trans_compare ~ty_params ~cjmp ~ty lhs rhs
                in
                  (* ... disproven, so assume lhs > rhs *)
                  mov result one;
                  let rhs_lt_lhs_jmps =
                    trans_compare ~ty_params ~cjmp ~ty rhs lhs
                  in
                    (* ... disproven, must be lhs == rhs *)
                    mov result zero;
                    List.iter patch lhs_lt_rhs_jmps;
                    List.iter patch rhs_lt_lhs_jmps;

          | Ast.TY_obj _ ->
              let lhs = need_cell lhs in
              let rhs = need_cell rhs in
              let lhs_binding = get_element_ptr lhs Abi.obj_field_box in
              let rhs_binding = get_element_ptr rhs Abi.obj_field_box in
              let lhs_box, rhs_box = deref lhs_binding, deref rhs_binding in
              let lhs_obj = get_element_ptr lhs_box Abi.box_rc_field_body in
              let rhs_obj = get_element_ptr rhs_box Abi.box_rc_field_body in
              let td = get_element_ptr lhs_obj Abi.obj_body_elt_tydesc in
              let lhs_body =
                get_element_ptr lhs_obj Abi.obj_body_elt_fields
              in
              let rhs_body =
                get_element_ptr rhs_obj Abi.obj_body_elt_fields
              in
              let ty_params_ptr = get_tydesc_params ty_params td in
                trans_call_dynamic_glue
                  td Abi.tydesc_field_cmp_glue
                  (Some result)
                  [| ty_params_ptr; alias lhs_body; alias rhs_body |]
                  None

          | Ast.TY_param (i, _) ->
              let lhs = need_cell lhs in
              let rhs = need_cell rhs in
              let td = get_ty_param ty_params i in
              let ty_params_ptr = get_tydesc_params ty_params td in
                trans_call_dynamic_glue
                  td Abi.tydesc_field_cmp_glue
                  (Some result)
                  [| ty_params_ptr; alias lhs; alias rhs |]
                  None

          | Ast.TY_vec _
          | Ast.TY_str ->
              (* FIXME: temporary until we get sequence-compares working. *)
              mov result zero;

          | _ ->
              let lhs = need_cell lhs in
              let rhs = need_cell rhs in
                trans_call_static_glue
                  (code_fixup_to_ptr_operand (get_cmp_glue ty))
                  (Some result)
                  [| alias ty_params; alias lhs; alias rhs |]
                  None
      end;
      Il.Cell result


  (*
   * [trans_compare_simple] returns a set of jump addresses, which the
   * caller patches to the destination. Only use this function if you are sure
   * that the LHS and RHS have the same type and that both will fit in a
   * machine register; otherwise, use [trans_compare] instead.
   *)
  and trans_compare_simple
      (cjmp:Il.jmpop)
      (lhs:Il.operand)
      (rhs:Il.operand)
      : quad_idx list =
    emit (Il.cmp (Il.Cell (Il.Reg (force_to_reg lhs))) rhs);
    let jmp = mark() in
      emit (Il.jmp cjmp Il.CodeNone);
      [ jmp ]

  (*
   * [trans_compare] returns a set of jump addresses, which the
   * caller patches to the destination.
   *)
  and trans_compare
      ?ty_params:(ty_params=get_ty_params_of_current_frame())
      ~cjmp:(cjmp:Il.jmpop)
      ~ty:(ty:Ast.ty)
      (lhs:Il.operand)
      (rhs:Il.operand)
      : quad_idx list =
      match ty with
          Ast.TY_bool
        | Ast.TY_mach _
        | Ast.TY_int
        | Ast.TY_uint
        | Ast.TY_char ->
            trans_compare_simple cjmp lhs rhs

        | _ ->
            let result =
              trans_cmp ~ty_params ~ty lhs rhs
            in
              emit (Il.cmp result zero);
              let jmp = mark() in
                emit (Il.jmp cjmp Il.CodeNone);
                [ jmp ]


  and trans_cond (invert:bool) (expr:Ast.expr) : quad_idx list =
    let anno _ =
      iflog
        begin
          fun _ ->
            annotate ((Fmt.fmt_to_str Ast.fmt_expr expr) ^
                        ": cond, finale")
        end
    in
      match expr with
          Ast.EXPR_binary (binop, a, b) ->
            let lhs = trans_atom a in
            let rhs = trans_atom b in
            let cjmp = binop_to_jmpop binop in
            let cjmp =
              if invert then
                match cjmp with
                    Il.JE -> Il.JNE
                  | Il.JNE -> Il.JE
                  | Il.JL -> Il.JGE
                  | Il.JLE -> Il.JG
                  | Il.JGE -> Il.JL
                  | Il.JG -> Il.JLE
                  | _ -> bug () "Unhandled inverse binop in trans_cond"
              else
                cjmp
            in
              anno ();
              let ty = atom_type cx a in
                trans_compare ~cjmp ~ty lhs rhs

      | _ ->
          let bool_operand = trans_expr expr in
            anno ();
            trans_compare_simple Il.JNE bool_operand
              (if invert then imm_true else imm_false)

  and trans_binop (binop:Ast.binop) : Il.binop =
    match binop with
        Ast.BINOP_or -> Il.OR
      | Ast.BINOP_and -> Il.AND
      | Ast.BINOP_xor -> Il.XOR

      | Ast.BINOP_lsl -> Il.LSL
      | Ast.BINOP_lsr -> Il.LSR
      | Ast.BINOP_asr -> Il.ASR

      | Ast.BINOP_add -> Il.ADD
      | Ast.BINOP_sub -> Il.SUB

      (* FIXME (issue #57):
       * switch on type of operands, IMUL/IDIV/IMOD etc.
       *)
      | Ast.BINOP_mul -> Il.UMUL
      | Ast.BINOP_div -> Il.UDIV
      | Ast.BINOP_mod -> Il.UMOD
      | _ -> bug () "bad binop to Trans.trans_binop"

  and trans_binary
      (binop:Ast.binop)
      (lhs:Il.operand)
      (rhs:Il.operand) : Il.operand =
    let arith op =
      let bits = Il.operand_bits word_bits lhs in
      let dst = Il.Reg (Il.next_vreg (emitter()), Il.ValTy bits) in
        emit (Il.binary op dst lhs rhs);
        Il.Cell dst
    in
    match binop with
        Ast.BINOP_or | Ast.BINOP_and | Ast.BINOP_xor
      | Ast.BINOP_lsl | Ast.BINOP_lsr | Ast.BINOP_asr
      | Ast.BINOP_add | Ast.BINOP_sub
      (* FIXME (issue #57):
       * switch on type of operands, IMUL/IDIV/IMOD etc.
       *)
      | Ast.BINOP_mul | Ast.BINOP_div | Ast.BINOP_mod ->
          arith (trans_binop binop)

      | _ -> let dst = Il.Reg (Il.next_vreg (emitter()), Il.ValTy Il.Bits8) in
          mov dst imm_true;
          let jmps = trans_compare_simple (binop_to_jmpop binop) lhs rhs in
            mov dst imm_false;
            List.iter patch jmps;
            Il.Cell dst


  and trans_expr (expr:Ast.expr) : Il.operand =

    let anno _ =
      iflog
        begin
          fun _ ->
            annotate ((Fmt.fmt_to_str Ast.fmt_expr expr) ^
                        ": plain exit, finale")
        end
    in
      match expr with
          Ast.EXPR_binary (binop, a, b) ->
            if not (is_prim_type (simplified_ty (atom_type cx a))) ||
                not (is_prim_type (simplified_ty (atom_type cx b))) then
              unimpl None "application of binary operator %a to operands of \
                type %s and %s"
                Ast.sprintf_binop binop
                (pretty_ty_str cx (Ast.sprintf_ty ()) (atom_type cx a))
                (pretty_ty_str cx (Ast.sprintf_ty ()) (atom_type cx b));
            trans_binary binop (trans_atom a) (trans_atom b)

        | Ast.EXPR_unary (unop, a) ->
            assert (is_prim_type (simplified_ty (atom_type cx a)));
            let src = trans_atom a in
            let bits = Il.operand_bits word_bits src in
            let dst = Il.Reg (Il.next_vreg (emitter()), Il.ValTy bits) in
            let op = match unop with
                Ast.UNOP_not
              | Ast.UNOP_bitnot -> Il.NOT
              | Ast.UNOP_neg -> Il.NEG
              | Ast.UNOP_cast t ->
                  let t = Hashtbl.find cx.ctxt_all_cast_types t.id in
                  let at = atom_type cx a in
                  let (t, at) = (simplified_ty t, simplified_ty at) in
                    if (type_is_2s_complement at) &&
                      (type_is_2s_complement t)
                    then
                      if type_is_unsigned_2s_complement t
                      then Il.UMOV
                      else Il.IMOV
                    else
                      err None "unsupported cast operator"
            in
              anno ();
              emit (Il.unary op dst src);
              (* Insist the bool domain being 0x0 and 0x1 *)
              if unop = Ast.UNOP_not
              then trans_binary Ast.BINOP_and (Il.Cell dst) one
              else Il.Cell dst

        | Ast.EXPR_atom a ->
            trans_atom a

  and drop_slot_by_id (depth:int) (slot_id:node_id) : unit =
    let slot = get_slot cx slot_id in
    let k = Hashtbl.find cx.ctxt_slot_keys slot_id in
      iflog (fun _ ->
               annotate
                 (Printf.sprintf
                    "drop_slot %d = %s "
                    (int_of_node slot_id)
                    (Fmt.fmt_to_str Ast.fmt_slot_key k)));
      drop_slot_in_current_frame
        (cell_of_block_slot
           ~access_depth:(Some depth) slot_id) slot

  and drop_slots_after_block bid : unit =
    let depth = Hashtbl.find cx.ctxt_block_loop_depths bid in
    match htab_search cx.ctxt_post_block_slot_drops bid with
        None -> ()
      | Some slots -> List.iter (drop_slot_by_id depth) slots

  and trans_block (block:Ast.block) : unit =
    flush_emitter_size_cache();
    trace_str cx.ctxt_sess.Session.sess_trace_block
      "entering block";
    emit (Il.Enter (Hashtbl.find cx.ctxt_block_fixups block.id));
    Array.iter trans_stmt block.node;
    drop_slots_after_block block.id;
    trace_str cx.ctxt_sess.Session.sess_trace_block
      "exiting block";
    emit Il.Leave;
    trace_str cx.ctxt_sess.Session.sess_trace_block
      "exited block";

  and upcall_fixup (name:string) : fixup =
    Semant.require_native cx REQUIRED_LIB_rustrt name;

  and trans_upcall
      (name:string)
      (ret:Il.cell)
      (args:Il.operand array)
      : unit =
    in_native_quad_category "upcall"
      (fun _ ->
         abi.Abi.abi_emit_native_call (emitter())
           ret nabi_rust (upcall_fixup name) args)

  and trans_void_upcall
      (name:string)
      (args:Il.operand array)
      : unit =
    in_native_quad_category "upcall"
      (fun _ ->
         abi.Abi.abi_emit_native_void_call (emitter())
           nabi_rust (upcall_fixup name) args);

  and trans_log_int (a:Ast.atom) : unit =
    trans_void_upcall "upcall_log_int" [| (trans_atom a) |]

  and trans_log_str (a:Ast.atom) : unit =
    trans_void_upcall "upcall_log_str" [| (trans_atom a) |]

  and trans_spawn
      ((*initializing*)_:bool)
      (dst:Ast.lval)
      (domain:Ast.domain)
      (name:string)
      (fn_lval:Ast.lval)
      (args:Ast.atom array)
      : unit =
    let (task_cell, _) = trans_lval_init dst in
    let runtime_name = trans_static_string name in
    let (fptr_operand, fn_ty) = trans_callee fn_lval in
    (*let fn_ty_params = [| |] in*)
    let _ =
      (* FIXME (issue #82): handle indirect-spawns (clone closure). *)
      if not (lval_is_direct_fn cx fn_lval)
      then bug () "unhandled indirect-spawn"
    in
    let args_rty = call_args_referent_type cx 0 fn_ty None in
    let fptr_operand = reify_ptr fptr_operand in
    let exit_task_glue_fixup = get_exit_task_glue () in
    let callsz =
      calculate_sz_in_current_frame (Il.referent_ty_size word_bits args_rty)
    in
    let exit_task_glue_fptr =
      code_fixup_to_ptr_operand exit_task_glue_fixup
    in
    let exit_task_glue_fptr = reify_ptr exit_task_glue_fptr in

      iflog (fun _ -> annotate "spawn task: copy args");

      let new_task = next_vreg_cell Il.voidptr_t in
      let call = { call_ctrl = CALL_indirect;
                   call_callee_ptr = fptr_operand;
                   call_callee_ty = fn_ty;
                   call_callee_ty_params = [| |];
                   call_output = task_cell;
                   call_args = args;
                   call_iterator_args = [| |];
                   call_indirect_args = [| |] }
      in
        match domain with
            Ast.DOMAIN_thread ->
              begin
                trans_upcall "upcall_new_thread" new_task [| runtime_name |];
                copy_fn_args false true (CLONE_all new_task) call;
                trans_upcall "upcall_start_thread" task_cell
                  [|
                    Il.Cell new_task;
                    exit_task_glue_fptr;
                    fptr_operand;
                    callsz
                  |];
            end
         | _ ->
             begin
                 trans_upcall "upcall_new_task" new_task [| runtime_name |];
                 copy_fn_args false true (CLONE_chan new_task) call;
                 trans_upcall "upcall_start_task" task_cell
                   [|
                     Il.Cell new_task;
                     exit_task_glue_fptr;
                     fptr_operand;
                     callsz
                   |];
             end;
      ()

  and get_curr_span _ =
      if Stack.is_empty curr_stmt
      then ("<none>", 0, 0)
      else
        let stmt_id = Stack.top curr_stmt in
          match (Session.get_span cx.ctxt_sess stmt_id) with
              None -> ("<none>", 0, 0)
            | Some sp -> sp.lo

  and trans_cond_fail (str:string) (fwd_jmps:quad_idx list) : unit =
    let (filename, line, _) = get_curr_span () in
      iflog (fun _ -> annotate ("condition-fail: " ^ str));
      trans_void_upcall "upcall_fail"
        [|
          trans_static_string str;
          trans_static_string filename;
          imm (Int64.of_int line)
        |];
      List.iter patch fwd_jmps

  and trans_check_expr (id:node_id) (e:Ast.expr) : unit =
    match simplified_ty (expr_type cx e) with
        Ast.TY_bool ->
          let fwd_jmps = trans_cond false e in
            trans_cond_fail (Fmt.fmt_to_str Ast.fmt_expr e) fwd_jmps
      | _ -> bugi cx id "check expr on non-bool"

  and trans_malloc
      (dst:Il.cell)
      (nbytes:Il.operand)
      (gc_ctrl_word:Il.operand)
      : unit =
    trans_upcall "upcall_malloc" dst [| nbytes; gc_ctrl_word |]

  and trans_free (src:Il.cell) (is_gc:bool) : unit =
    let is_gc = if is_gc then 1L else 0L in
      trans_void_upcall "upcall_free" [| Il.Cell src; imm is_gc |]

  and trans_yield () : unit =
    trans_void_upcall "upcall_yield" [| |];

  and trans_fail () : unit =
    let (filename, line, _) = get_curr_span () in
      trans_void_upcall "upcall_fail"
        [|
          trans_static_string "explicit failure";
          trans_static_string filename;
          imm (Int64.of_int line)
        |];

  and trans_join (task:Ast.lval) : unit =
    trans_void_upcall "upcall_join" [| trans_atom (Ast.ATOM_lval task) |]

  and trans_send (chan:Ast.lval) (src:Ast.lval) : unit =
    let (src_cell, src_ty) = trans_lval src in
      begin
        match (ty_mem_ctrl cx src_ty) with
          | MEM_rc_opaque
          | MEM_rc_struct
          | MEM_gc ->
              iflog (fun _ -> annotate "incr_refcount of src obj");
              incr_refcount src_cell;
          | _ -> ()
      end;
      aliasing false src_cell
        begin
          fun src_alias ->
            trans_void_upcall "upcall_send"
              [| trans_atom (Ast.ATOM_lval chan);
                 Il.Cell src_alias |];
        end

  and trans_recv (initializing:bool) (dst:Ast.lval) (chan:Ast.lval) : unit =
    let (dstcell, _) = trans_lval_maybe_init initializing dst in
      aliasing true dstcell
        begin
          fun dst_alias ->
            trans_void_upcall "upcall_recv"
              [| Il.Cell dst_alias;
                 trans_atom (Ast.ATOM_lval chan) |];
        end

  and trans_new_port (initializing:bool) (dst:Ast.lval) : unit =
    let (dst_cell, dst_ty) = trans_lval_maybe_init initializing dst in
    let unit_ty = match dst_ty with
        Ast.TY_port t -> t
      | _ -> bug () "init dst of port-init has non-port type"
    in
    let unit_sz = ty_sz cx unit_ty in
      drop_existing_if_not_init initializing dst_cell dst_ty;
      trans_upcall "upcall_new_port" dst_cell [| imm unit_sz |]

  and trans_del_port (port:Il.cell) : unit =
    trans_void_upcall "upcall_del_port" [| Il.Cell port |]

  and trans_new_chan
      (initializing:bool)
      (dst:Ast.lval)
      (port:Ast.lval)
      : unit =
    let (dst_cell, dst_ty) = trans_lval_maybe_init initializing dst in
      drop_existing_if_not_init initializing dst_cell dst_ty;
      trans_upcall "upcall_new_chan" dst_cell
        [| trans_atom (Ast.ATOM_lval port) |]

  and trans_del_chan (chan:Il.cell) : unit =
    trans_void_upcall "upcall_del_chan" [| Il.Cell chan |]

  and trans_kill_task (task:Il.cell) : unit =
    trans_void_upcall "upcall_kill" [| Il.Cell task |]

  (*
   * A vec is implicitly boxed: every slot vec[T] is 1 word and
   * points to a refcounted structure. That structure has 3 words with
   * defined meaning at the beginning; data follows the header.
   *
   *   word 0: refcount or gc control word
   *   word 1: allocated size of data
   *   word 2: initialised size of data
   *   word 3...N: data
   * 
   * This 3-word prefix is shared with strings, we factor the common
   * part out for reuse in string code.
   *)

  and trans_new_vec
      (initializing:bool)
      (dst:Ast.lval)
      (atoms:Ast.atom array)
      : unit =
    let (dst_cell, dst_ty) = trans_lval_maybe_init initializing dst in
    let gc_ctrl =
      if (ty_mem_ctrl cx dst_ty) = MEM_gc
      then Il.Cell (get_tydesc None dst_ty)
      else zero
    in
    let unit_ty = match dst_ty with
        Ast.TY_vec t -> t
      | _ -> bug () "init dst of vec-init has non-vec type"
    in
    let fill = next_vreg_cell word_sty in
    let unit_sz = ty_sz_in_current_frame unit_ty in
      drop_existing_if_not_init initializing dst_cell dst_ty;
      umul fill unit_sz (imm (Int64.of_int (Array.length atoms)));
      trans_upcall "upcall_new_vec" dst_cell [| Il.Cell fill; gc_ctrl |];
      let vec = deref dst_cell in
        let body_mem =
          fst (need_mem_cell
                 (get_element_ptr_dyn_in_current_frame
                    vec Abi.vec_elt_data))
        in
        let unit_rty = referent_type cx unit_ty in
        let body_rty = Il.StructTy (Array.map (fun _ -> unit_rty) atoms) in
        let body = Il.Mem (body_mem, body_rty) in
          Array.iteri
            begin
              fun i atom ->
                let cell = get_element_ptr_dyn_in_current_frame body i in
                  trans_init_ty_from_atom cell unit_ty atom
            end
            atoms;
            mov (get_element_ptr vec Abi.vec_elt_fill) (Il.Cell fill);


  and trans_new_box
      (initializing:bool)
      (dst:Ast.lval)
      (src:Ast.atom)
      : unit =
    let src_op = trans_atom src in
    let src_cell = Il.Mem (force_to_mem src_op) in
    let src_ty = simplified_ty (atom_type cx src) in
    let (dst_cell, dst_ty) = trans_lval_maybe_init initializing dst in
    let _ =
      drop_existing_if_not_init initializing dst_cell dst_ty
    in
    let dst_ty = strip_mutable_or_constrained_ty dst_ty in
    let (dst_cell, dst_ty) =
      deref_ty DEREF_one_box true dst_cell dst_ty
    in
    let _ =
      iflog (fun _ -> log cx "init_box: dst ty %a, src ty %a"
               Ast.sprintf_ty dst_ty Ast.sprintf_ty src_ty)
    in
    let _ = assert (dst_ty = src_ty) in
      trans_copy_ty (get_ty_params_of_current_frame()) true
        dst_cell dst_ty src_cell src_ty


  and get_dynamic_tydesc
      (idopt:node_id option)
      (t:Ast.ty)
      (force_stateful:bool)
      : Il.cell =
    let td = next_vreg_cell Il.voidptr_t in
    let root_desc =
      Il.Cell (crate_rel_to_ptr
                 (get_static_tydesc idopt t 0L 0L force_stateful)
                 (tydesc_rty word_bits))
    in
    let (t, param_descs) = linearize_ty_params t in
    let descs = Array.append [| root_desc |] param_descs in
    let n = Array.length descs in
    let rty = referent_type cx t in
    let (size_sz, align_sz) = Il.referent_ty_layout word_bits rty in
    let size = calculate_sz_in_current_frame size_sz in
    let align = calculate_sz_in_current_frame align_sz in
    let descs_ptr = next_vreg_cell Il.voidptr_t in
      if (Array.length descs) > 0
      then
        (* FIXME (issue #83): this relies on knowledge that spills are
         * contiguous.
         *)
        let spills =
          Array.map (fun _ -> next_spill_cell Il.voidptr_t) descs
        in
          Array.iteri (fun i t -> mov spills.(n-(i+1)) t) descs;
          lea descs_ptr (fst (need_mem_cell spills.(n-1)))
      else
        mov descs_ptr zero;
      trans_upcall "upcall_get_type_desc" td
        [| Il.Cell (curr_crate_ptr());
           size; align; imm (Int64.of_int n);
           Il.Cell descs_ptr |];
      td

  and get_tydesc (idopt:node_id option) (ty:Ast.ty) : Il.cell =
    iflog (fun _ -> log cx "getting tydesc for %a" Ast.sprintf_ty ty);
    let (ty', mut) = simplified_ty_innermost_was_mutable ty in
    match ty' with
        Ast.TY_param (idx, _) ->
          (get_ty_param_in_current_frame idx)
      | t when has_parametric_types t ->
          (get_dynamic_tydesc idopt t mut)
      | _ ->
          (crate_rel_to_ptr (get_static_tydesc idopt ty
                               (ty_sz cx ty)
                               (ty_align cx ty)
                               mut)
             (tydesc_rty word_bits))

  and box_rc_cell (cell:Il.cell) : Il.cell =
    get_element_ptr (deref cell) Abi.box_rc_field_refcnt

  and box_allocation_size
      (ty:Ast.ty)
      : Il.operand =
    let header_sz =
      match ty_mem_ctrl cx ty with
          MEM_gc
        | MEM_rc_opaque
        | MEM_rc_struct -> word_n Abi.box_rc_header_size
        | MEM_interior -> bug () "box_allocation_size of MEM_interior"
    in
    let ty = simplified_ty ty in
    let refty_sz =
      Il.referent_ty_size abi.Abi.abi_word_bits (referent_type cx ty)
    in
      match refty_sz with
          SIZE_fixed _ -> imm (Int64.add (ty_sz cx ty) header_sz)
        | _ ->
            let ty_params = get_ty_params_of_current_frame() in
            let refty_sz = calculate_sz ty_params refty_sz in
            let v = next_vreg word_sty in
            let vc = Il.Reg (v, word_sty) in
              mov vc refty_sz;
              add_to vc (imm header_sz);
              Il.Cell vc;

  and iter_tag_parts
      (ty_params:Il.cell)
      (dst_cell:Il.cell)
      (src_cell:Il.cell)
      (ttag:Ast.ty_tag)
      (f:Il.cell -> Il.cell -> Ast.ty -> unit)
      : unit =
    let src_tag = get_element_ptr src_cell Abi.tag_elt_discriminant in
    let dst_tag = get_element_ptr dst_cell Abi.tag_elt_discriminant in
    let src_union =
      get_element_ptr_dyn ty_params src_cell Abi.tag_elt_variant
    in
    let dst_union =
      get_element_ptr_dyn ty_params dst_cell Abi.tag_elt_variant
    in
    let tmp = next_vreg_cell word_sty in
    let n = get_n_tag_tups cx ttag in
      f dst_tag src_tag word_ty;
      mov tmp (Il.Cell src_tag);
      for i = 0 to n-1
      do
        let ttup = get_nth_tag_tup cx ttag i in
          if Array.length ttup <> 0
          then
            begin
              let pc0 = (emitter()).Il.emit_pc in
              (iflog (fun _ ->
                        annotate (Printf.sprintf "tag case #%i" i)));
              let jmps =
                trans_compare_simple Il.JNE
                  (Il.Cell tmp) (imm (Int64.of_int i))
              in
              let ttup = get_nth_tag_tup cx ttag i in
              let pc1 = (emitter()).Il.emit_pc in
                iter_tup_parts
                  (get_element_ptr_dyn ty_params)
                  (get_variant_ptr dst_union i)
                  (get_variant_ptr src_union i)
                  ttup f;

                (* Hack: if this variant is all dead code, blank it out. *)
                if pc1 = (emitter()).Il.emit_pc
                then
                  begin
                    for j = pc0 to (pc1-1)
                    do (emitter()).Il.emit_quads.(j) <- Il.deadq done
                  end;
                List.iter patch jmps;
            end
      done;

  and seq_unit_ty (seq:Ast.ty) : Ast.ty =
    match simplified_ty seq with
        Ast.TY_vec t -> t
      | Ast.TY_str -> Ast.TY_mach TY_u8
      | _ -> bug () "seq_unit_ty of non-vec, non-str type"


  and iter_seq_parts
      (ty_params:Il.cell)
      (dst_cell:Il.cell)
      (src_cell:Il.cell)
      (unit_ty:Ast.ty)
      (trailing_null:bool)
      (f:Il.cell -> Il.cell -> Ast.ty -> unit)
      : unit =

    let unit_sz = ty_sz_with_ty_params ty_params unit_ty in
    let _ = unit_ty in
      (* 
       * Unlike most of the iter_ty_parts helpers; this one allocates a
       * vreg and so has to be aware of when it's iterating over 2
       * sequences of cells or just 1.
       *)
      check_box_rty src_cell;
      check_box_rty dst_cell;
      if dst_cell = src_cell
      then
        begin
          let src_cell = deref src_cell in
          let data =
            get_element_ptr_dyn ty_params src_cell Abi.vec_elt_data
          in
          let len = get_element_ptr src_cell Abi.vec_elt_fill in
          let ptr = next_vreg_cell Il.voidptr_t in
          let lim = next_vreg_cell Il.voidptr_t in
            lea lim (fst (need_mem_cell data));
            mov ptr (Il.Cell lim);
            add_to lim (Il.Cell len);

            if trailing_null
            then sub_from lim (imm 1L);

            let back_jmp_target = mark () in
            let fwd_jmps =
              trans_compare_simple Il.JAE (Il.Cell ptr) (Il.Cell lim)
            in
            let unit_cell =
              deref (ptr_cast ptr (referent_type cx unit_ty))
            in
              f unit_cell unit_cell unit_ty;
              add_to ptr unit_sz;
              check_interrupt_flag ();
              emit (Il.jmp Il.JMP (Il.CodeLabel back_jmp_target));
              List.iter patch fwd_jmps;
        end
      else
        begin
          unimpl None "seq iter with src != dst."
        end


  and iter_ty_parts_full
      (ty_params:Il.cell)
      (dst_cell:Il.cell)
      (src_cell:Il.cell)
      (ty:Ast.ty)
      (f:Il.cell -> Il.cell -> Ast.ty -> unit)
      : unit =
    (* 
     * FIXME: this will require some reworking if we support
     * rec, tag or tup slots that fit in a vreg. It requires 
     * addrs presently.
     *)

    match strip_mutable_or_constrained_ty ty with
        Ast.TY_rec entries ->
          iter_rec_parts
            (get_element_ptr_dyn ty_params) dst_cell src_cell
            entries f

      | Ast.TY_tup tys ->
          iter_tup_parts
            (get_element_ptr_dyn ty_params) dst_cell src_cell
            tys f

      | Ast.TY_tag tag ->
          iter_tag_parts ty_params dst_cell src_cell tag f

      | Ast.TY_fn _
      | Ast.TY_obj _ -> bug () "Attempting to iterate over fn/pred/obj slots"

      | Ast.TY_vec _ ->
          let unit_ty = seq_unit_ty ty in
            iter_seq_parts ty_params dst_cell src_cell unit_ty false f

      | Ast.TY_str ->
          let unit_ty = seq_unit_ty ty in
            iter_seq_parts ty_params dst_cell src_cell unit_ty true f

      | _ -> ()

  (* 
   * This just calls iter_ty_parts_full with your cell as both src and
   * dst, with an adaptor function that discards the dst parts of the
   * parallel traversal and and calls your provided function on the
   * passed-in src parts.
   *)
  and iter_ty_parts
      (ty_params:Il.cell)
      (cell:Il.cell)
      (ty:Ast.ty)
      (f:Il.cell -> Ast.ty -> unit)
      : unit =
    iter_ty_parts_full ty_params cell cell ty
      (fun _ src_cell ty -> f src_cell ty)

  and drop_ty tp c t =
    (in_quad_category "drop" (fun _ -> drop_ty_normal tp c t))

  and drop_ty_normal tp c t =
    drop_ty_full false tp c t

  and drop_ty_full
      (force_inline:bool)
      (ty_params:Il.cell)
      (cell:Il.cell)
      (ty:Ast.ty)
      : unit =

    let mctrl = ty_mem_ctrl cx ty in
    let ty = strip_mutable_or_constrained_ty ty in
    let call_out_of_line _ =
      trans_call_simple_static_glue (get_drop_glue ty)
        ty_params [| alias cell |] None;
    in

      match ty with

          Ast.TY_fn _
        | Ast.TY_obj _ when force_inline ->
            note_drop_step ty "drop_ty: obj/fn path";
            let box_ptr =
              get_element_ptr cell Abi.binding_field_bound_data
            in
            let _ = check_box_rty box_ptr in
            let null_jmp = null_check box_ptr in
            let rc_jmps = drop_refcount_and_cmp box_ptr in
            let box = deref box_ptr in
            let body = get_element_ptr box Abi.box_rc_field_body in
            let tydesc = get_element_ptr body Abi.obj_body_elt_tydesc in
            let fields =
              match ty with
                  Ast.TY_fn _ ->
                    get_element_ptr body Abi.closure_body_elt_bound_args
                | _ ->
                    get_element_ptr body Abi.obj_body_elt_fields
            in
            let ty_params = get_tydesc_params ty_params tydesc in
              begin
                match ty with
                    Ast.TY_obj _ ->
                      let dtor =
                        get_element_ptr (deref tydesc)
                          Abi.tydesc_field_obj_drop_glue
                      in
                      let null_dtor_jmp = null_check dtor in
                        (* Call any dtor, if present. *)
                        note_drop_step ty "drop_ty: calling obj/fn dtor";
                        trans_call_dynamic_glue
                          tydesc
                          Abi.tydesc_field_obj_drop_glue
                          None
                          [| box_ptr |]
                          (Some box_ptr);
                        patch null_dtor_jmp;
                  | _ -> ()
              end;
              (* Drop the fields. *)
              note_drop_step ty "drop_ty: dropping obj/fn fields";
              trans_call_dynamic_glue
                tydesc
                Abi.tydesc_field_drop_glue
                None
                [| ty_params; alias fields |]
                None;
              (* FIXME: this will fail if the user has lied about the
               * state-ness of their obj. We need to store state-ness in the
               * captured tydesc, and use that.  *)
              note_drop_step ty "drop_ty: freeing obj/fn body";
              trans_free box_ptr (type_has_state cx ty);
              mov box_ptr zero;
              List.iter patch rc_jmps;
              patch null_jmp;
              note_drop_step ty "drop_ty: done obj path";

        | Ast.TY_fn _
        | Ast.TY_obj _ ->
            call_out_of_line()

        | Ast.TY_param (i, _) ->
          note_drop_step ty "drop_ty: parametric-ty path";
          aliasing false cell
            begin
              fun cell ->
                trans_call_simple_dynamic_glue
                  i
                  Abi.tydesc_field_drop_glue
                  ty_params
                  [| cell |]
                  None
            end;
          note_drop_step ty "drop_ty: done parametric-ty path";

        | _ ->
            match mctrl with
                MEM_gc
              | MEM_rc_opaque
              | MEM_rc_struct when force_inline ->

                  note_drop_step ty "drop_ty: box-drop path";

                  let _ = check_box_rty cell in
                  let null_jmp = null_check cell in
                  let js = drop_refcount_and_cmp cell in

                    (* FIXME (issue #25): check to see that the box has
                     * further box members; if it doesn't we can elide the
                     * call to the glue function.  *)

                    trans_call_simple_static_glue
                      (get_free_glue ty (mctrl = MEM_gc))
                      ty_params
                      [| cell |]
                      None;

                    (* Null the slot out to prevent double-free if the frame
                     * unwinds.  *)
                    mov cell zero;
                    List.iter patch js;
                    patch null_jmp;
                    note_drop_step ty "drop_ty: done box-drop path";

              | MEM_gc
              | MEM_rc_opaque
              | MEM_rc_struct ->
                  call_out_of_line()

              | MEM_interior
                  when type_points_to_heap cx ty ||
                    (n_used_type_params cx ty > 0) ->
                  begin
                    note_drop_step ty
                      "drop_ty possibly-heap-referencing path";
                    if force_inline || should_inline_structure_helpers ty
                    then iter_ty_parts ty_params cell ty
                      (drop_ty ty_params)
                    else
                      call_out_of_line();

                    note_drop_step ty
                      "drop_ty: done possibly-heap-referencing path";
                  end

              | MEM_interior ->
                  note_drop_step ty "drop_ty: no-op simple-interior path";
                  (* Interior allocation of all-interior value not caught
                   * above: nothing to do.  *)
                  ()

  and sever_ty
      (ty_params:Il.cell)
      (cell:Il.cell)
      (ty:Ast.ty)
      : unit =
    let _ = note_gc_step ty "severing" in
    let sever_box c =
      let _ = check_box_rty c in
      let null_jmp = null_check c in
      let rc = box_rc_cell c in
      let _ = note_gc_step ty "severing GC cell" in
        emit (Il.binary Il.SUB rc (Il.Cell rc) one);
        mov c zero;
        patch null_jmp
    in
    let ty = strip_mutable_or_constrained_ty ty in

      match ty with
          Ast.TY_fn _
        | Ast.TY_obj _ ->
            if type_has_state cx ty
            then
              let binding =
                get_element_ptr cell Abi.binding_field_bound_data
              in
                sever_box binding;

        | _ ->
            match ty_mem_ctrl cx ty with
                MEM_gc ->
                  sever_box cell

              | MEM_interior when type_points_to_heap cx ty ->
                  iter_ty_parts ty_params cell ty (sever_ty ty_params)

              | _ -> ()
                  (* No need to follow links / call glue; severing is
                     shallow. *)

  and clone_ty
      (ty_params:Il.cell)
      (clone_task:Il.cell)
      (dst:Il.cell)
      (src:Il.cell)
      (ty:Ast.ty)
      : unit =
    let ty = strip_mutable_or_constrained_ty ty in

      match ty with
          Ast.TY_chan _ ->
            trans_upcall "upcall_clone_chan" dst
              [| (Il.Cell clone_task); (Il.Cell src) |]
        | Ast.TY_task
        | Ast.TY_port _
        | _ when type_has_state cx ty
            -> bug () "cloning state type"
        | _ when i64_le (ty_sz cx ty) word_sz
            -> mov dst (Il.Cell src)
        | Ast.TY_fn _
        | Ast.TY_obj _ -> ()
        | Ast.TY_box ty ->
            let glue_fix = get_clone_glue ty in
              trans_call_static_glue
                (code_fixup_to_ptr_operand glue_fix)
                (Some dst)
                [| alias ty_params; src; clone_task |] None
        | _ ->
            iter_ty_parts_full ty_params dst src ty
              (clone_ty ty_params clone_task)

  and unfold_opaque_cell (c:Il.cell) (ty:Ast.ty) : Il.cell =
    match Il.cell_referent_ty c with
        Il.ScalarTy (Il.AddrTy _) ->
          begin
            match strip_mutable_or_constrained_ty ty with
                Ast.TY_box boxed ->
                  Il.ptr_cast c
                    (Il.StructTy [| word_rty; referent_type cx boxed |])
              | _ -> c
          end
      | _ -> c

  and free_ty
      (is_gc:bool)
      (ty_params:Il.cell)
      (ty:Ast.ty)
      (cell:Il.cell)
      : unit =
    check_box_rty cell;
    let cell = unfold_opaque_cell cell ty in
    check_box_rty cell;
    note_drop_step ty "in free-ty";
    begin
    match strip_mutable_or_constrained_ty ty with
        Ast.TY_port _ -> trans_del_port cell
      | Ast.TY_chan _ -> trans_del_chan cell
      | Ast.TY_task -> trans_kill_task cell
      | Ast.TY_str -> trans_free cell false
      | Ast.TY_vec s ->
          iter_seq_parts ty_params cell cell s false
             (fun _ src ty -> drop_ty ty_params src ty);
             trans_free cell is_gc

      | Ast.TY_box body_ty ->
          note_drop_step ty "in free-ty, dropping structured body";
          let (body_mem, _) =
            need_mem_cell
              (get_element_ptr_dyn ty_params (deref cell)
                 Abi.box_rc_field_body)
          in
          let vr = next_vreg_cell Il.voidptr_t in
            lea vr body_mem;
            trace_word cx.ctxt_sess.Session.sess_trace_drop vr;
            trans_call_simple_static_glue
              (get_drop_glue body_ty)
              ty_params
              [| vr |]
              None;
            note_drop_step ty "in free-ty, calling free";
            trans_free cell is_gc;

      | t -> bug () "freeing unexpected type: %a" Ast.sprintf_ty t
    end;
    note_drop_step ty "free-ty done";

  and mark_slot
      (ty_params:Il.cell)
      (cell:Il.cell)
      (slot:Ast.slot)
      : unit =
    (* Marking goes straight through aliases. Reachable means reachable. *)
    mark_ty ty_params (deref_slot false cell slot) (slot_ty slot)

  and mark_ty
      (ty_params:Il.cell)
      (cell:Il.cell)
      (ty:Ast.ty)
      : unit =
    let ty = strip_mutable_or_constrained_ty ty in
      match ty_mem_ctrl cx ty with
          MEM_gc ->
            let tmp = next_vreg_cell Il.voidptr_t in
              trans_upcall "upcall_mark" tmp [| Il.Cell cell |];
              let marked_jump =
                trans_compare_simple Il.JE (Il.Cell tmp) zero
              in
                (* Iterate over box parts marking outgoing links. *)
              let (body_mem, _) =
                need_mem_cell
                  (get_element_ptr_dyn ty_params (deref cell)
                     Abi.box_gc_field_body)
              in
                lea tmp body_mem;
                trans_call_simple_static_glue
                  (get_mark_glue ty)
                  ty_params
                  [| tmp |]
                  None;
                List.iter patch marked_jump;

        | MEM_interior when type_is_structured cx ty ->
            (iflog (fun _ ->
                      annotate ("mark interior memory " ^
                                  (Fmt.fmt_to_str Ast.fmt_ty ty))));
            let (mem, _) = need_mem_cell cell in
            let tmp = next_vreg_cell Il.voidptr_t in
              lea tmp mem;
              trans_call_simple_static_glue
                (get_mark_glue ty)
                ty_params
                [| tmp |]
                None

        | _ -> ()

  and check_box_rty cell =
    match cell with
        Il.Reg (_, Il.AddrTy (Il.StructTy fields))
      | Il.Mem (_, Il.ScalarTy (Il.AddrTy (Il.StructTy fields)))
          when (((Array.length fields) > 0) && (fields.(0) = word_rty)) -> ()
      | _ -> bug ()
          "expected plausibly-box cell, got %s"
            (Il.string_of_referent_ty (Il.cell_referent_ty cell))

  and drop_slot_in_current_frame
      (cell:Il.cell)
      (slot:Ast.slot)
      : unit =
      check_and_flush_chan cell slot;
      drop_slot (get_ty_params_of_current_frame()) cell
        { slot with
            Ast.slot_ty = Some (strip_mutable_or_constrained_ty
                                  (slot_ty slot)) }

  and drop_ty_in_current_frame
      (cell:Il.cell)
      (ty:Ast.ty)
      : unit =
    drop_ty (get_ty_params_of_current_frame()) cell
      (strip_mutable_or_constrained_ty ty)

  (* Returns a mark for a jmp that must be patched to the continuation of
   * the null case (i.e. fall-through means not null).
   *)
  and null_check (cell:Il.cell) : quad_idx =
    in_quad_category "null check"
      begin
        fun _ ->
          emit (Il.cmp (Il.Cell cell) zero);
          let j = mark() in
            emit (Il.jmp Il.JE Il.CodeNone);
            j
      end

  (* Returns a mark for a jmp that must be patched to the continuation of
   * the non-zero refcount case (i.e. fall-through means zero refcount).
   *)
  and drop_refcount_and_cmp (boxed:Il.cell) : quad_idx list =
    in_quad_category "refcount"
      begin
        fun _ ->
          iflog (fun _ -> annotate "drop refcount and maybe free");
          let rc = box_rc_cell boxed in
            if cx.ctxt_sess.Session.sess_trace_gc ||
              cx.ctxt_sess.Session.sess_trace_drop
            then
              begin
                trace_str true "refcount--";
                trace_word true boxed;
                trace_word true rc
              end;
            emit (Il.cmp (Il.Cell rc) (simm Abi.const_refcount));
            let j0 = mark() in
              emit (Il.jmp Il.JE Il.CodeNone);
              emit (Il.binary Il.SUB rc (Il.Cell rc) one);
              emit (Il.cmp (Il.Cell rc) zero);
              let j1 = mark () in
                emit (Il.jmp Il.JNE Il.CodeNone);
                [j0; j1]
      end

  and incr_refcount (boxed:Il.cell) : unit =
    in_quad_category "refcount"
      begin
        fun _ ->
          let rc = box_rc_cell boxed in
            if cx.ctxt_sess.Session.sess_trace_gc ||
              cx.ctxt_sess.Session.sess_trace_drop
            then
              begin
                trace_str true "refcount++";
                trace_word true boxed;
                trace_word true rc
              end;
            emit (Il.cmp (Il.Cell rc) (simm Abi.const_refcount));
            let j = mark() in
              emit (Il.jmp Il.JE Il.CodeNone);
              add_to rc one;
              patch j;
      end

  and drop_slot
      (ty_params:Il.cell)
      (cell:Il.cell)
      (slot:Ast.slot)
      : unit =
    match slot.Ast.slot_mode with
        Ast.MODE_alias -> ()
          (* Aliases are always free to drop. *)
      | Ast.MODE_local ->
          drop_ty ty_params cell (slot_ty slot)

  and note_drop_step ty step =
    if (should_log cx (cx.ctxt_sess.Session.sess_trace_drop ||
                         cx.ctxt_sess.Session.sess_log_trans))
    then
      let mctrl_str =
        match ty_mem_ctrl cx ty with
            MEM_gc -> "MEM_gc"
          | MEM_rc_struct -> "MEM_rc_struct"
          | MEM_rc_opaque -> "MEM_rc_opaque"
          | MEM_interior -> "MEM_interior"
      in
      let tystr = Fmt.fmt_to_str Ast.fmt_ty ty in
      let str = step ^ " " ^ mctrl_str ^ " " ^ tystr in
        begin
          annotate str;
          trace_str cx.ctxt_sess.Session.sess_trace_drop str
        end

  and note_gc_step ty step =
    if (should_log cx (cx.ctxt_sess.Session.sess_trace_gc ||
                         cx.ctxt_sess.Session.sess_log_trans))
    then
      let mctrl_str =
        match ty_mem_ctrl cx ty with
            MEM_gc -> "MEM_gc"
          | MEM_rc_struct -> "MEM_rc_struct"
          | MEM_rc_opaque -> "MEM_rc_opaque"
          | MEM_interior -> "MEM_interior"
      in
      let tystr = Fmt.fmt_to_str Ast.fmt_ty ty in
      let str = step ^ " " ^ mctrl_str ^ " " ^ tystr in
        begin
          annotate str;
          trace_str cx.ctxt_sess.Session.sess_trace_gc str
        end

  (* Returns the offset of the slot-body in the initialized allocation. *)
  and init_box (cell:Il.cell) (ty:Ast.ty) : unit =
    let mctrl = ty_mem_ctrl cx ty in
      match mctrl with
          MEM_gc
        | MEM_rc_opaque
        | MEM_rc_struct ->
            let ctrl =
              if mctrl = MEM_gc
              then Il.Cell (get_tydesc None ty)
              else zero
            in
              iflog (fun _ -> annotate "init box: malloc");
              let sz = box_allocation_size ty in
                trans_malloc cell sz ctrl;
                iflog (fun _ -> annotate "init box: load refcount");
                let rc = box_rc_cell cell in
                  mov rc one

      | MEM_interior -> bug () "init_box of MEM_interior"

  and deref_ty
      (dctrl:deref_ctrl)
      (initializing:bool)
      (cell:Il.cell)
      (ty:Ast.ty)
      : (Il.cell * Ast.ty) =
    match (ty, dctrl) with

      | (Ast.TY_mutable ty, _)
      | (Ast.TY_constrained (ty, _), _) ->
          deref_ty dctrl initializing cell ty

      | (Ast.TY_box ty', DEREF_one_box)
      | (Ast.TY_box ty', DEREF_all_boxes) ->
          check_box_rty cell;
          let cell = unfold_opaque_cell cell ty in
          check_box_rty cell;
          if initializing
          then init_box cell ty;
          let cell =
            get_element_ptr_dyn_in_current_frame
              (deref cell)
              (Abi.box_rc_field_body)
          in
          let inner_dctrl =
            if dctrl = DEREF_one_box
            then DEREF_none
            else DEREF_all_boxes
          in
            (* Possibly deref recursively. *)
            deref_ty inner_dctrl initializing cell ty'

      | _ -> (cell, ty)


  and deref_slot
      (initializing:bool)
      (cell:Il.cell)
      (slot:Ast.slot)
      : Il.cell =
    match slot.Ast.slot_mode with
        Ast.MODE_local ->
          cell

      | Ast.MODE_alias  ->
          if initializing
          then cell
          else deref cell

  and trans_copy_tup
      (ty_params:Il.cell)
      (initializing:bool)
      (dst:Il.cell)
      (src:Il.cell)
      (tys:Ast.ty_tup)
      : unit =
    Array.iteri
      begin
        fun i ty ->
          let sub_dst_cell = get_element_ptr_dyn ty_params dst i in
          let sub_src_cell = get_element_ptr_dyn ty_params src i in
            trans_copy_ty
              ty_params
              initializing
              sub_dst_cell ty
              sub_src_cell ty
      end
      tys

  and trans_copy_ty
      (ty_params:Il.cell)
      (initializing:bool)
      (dst:Il.cell) (dst_ty:Ast.ty)
      (src:Il.cell) (src_ty:Ast.ty)
      : unit =
    trans_copy_ty_full
      false ty_params initializing dst dst_ty src src_ty

  and trans_copy_ty_full
      (force_inline:bool)
      (ty_params:Il.cell)
      (initializing:bool)
      (dst:Il.cell) (dst_ty:Ast.ty)
      (src:Il.cell) (src_ty:Ast.ty)
      : unit =
    let anno (weight:string) : unit =
      iflog
        begin
          fun _ ->
            annotate
              (Printf.sprintf "%sweight copy: %a <- %a"
                 weight
                 Ast.sprintf_ty dst_ty
                 Ast.sprintf_ty src_ty)
        end;
    in
      iflog
        begin
          fun _ ->
            log cx "trans_copy_ty";
            log cx "   dst ty %a, src ty %a"
              Ast.sprintf_ty dst_ty Ast.sprintf_ty src_ty;
            log cx "   dst cell %s, src cell %s"
              (cell_str dst) (cell_str src);
        end;
      assert (simplified_ty src_ty = simplified_ty dst_ty);
      in_quad_category "copy"
        begin
          fun _ ->
            match (ty_mem_ctrl cx src_ty, ty_mem_ctrl cx dst_ty) with
                (MEM_rc_opaque, MEM_rc_opaque)
              | (MEM_gc, MEM_gc)
              | (MEM_rc_struct, MEM_rc_struct) ->
                  (* Lightweight copy: twiddle refcounts, move pointer. *)
                  anno "refcounted light";
                  incr_refcount src;
                  if not initializing
                  then
                    drop_ty ty_params dst dst_ty;
                  mov dst (Il.Cell src)

              | _ ->
                  (* Heavyweight copy: duplicate 1 level of the referent. *)
                  anno "heavy";
                  trans_copy_ty_heavy force_inline ty_params initializing
                    dst dst_ty src src_ty
        end

  (* NB: heavyweight copying here does not mean "producing a deep
   * clone of the entire data tree rooted at the src operand". It means
   * "replicating a single level of the tree".
   * 
   * There is no general-recursion entailed in performing a heavy
   * copy. There is only "one level" to each heavy copy call.
   * 
   * In other words, this is a lightweight copy:
   * 
   *    [dstptr]  <-copy-  [srcptr]
   *         \              |
   *          \             |
   *        [some record.rc++]
   *             |
   *           [some other record]
   * 
   * Whereas this is a heavyweight copy:
   * 
   *    [dstptr]  <-copy-  [srcptr]
   *       |                  |
   *       |                  |
   *  [some record]       [some record]
   *             |          |
   *           [some other record]
   * 
   *)

  and trans_copy_ty_heavy
      (force_inline:bool)
      (ty_params:Il.cell)
      (initializing:bool)
      (dst:Il.cell) (dst_ty:Ast.ty)
      (src:Il.cell) (src_ty:Ast.ty)
      : unit =
    let src_ty = strip_mutable_or_constrained_ty src_ty in
    let dst_ty = strip_mutable_or_constrained_ty dst_ty in

      iflog
        begin
          fun _ ->
            log cx "trans_copy_ty_heavy";
            log cx "   dst ty %a, src ty %a"
              Ast.sprintf_ty dst_ty Ast.sprintf_ty src_ty;
            log cx "   dst cell %s, src cell %s"
              (cell_str dst) (cell_str src);
        end;

      assert (src_ty = dst_ty);

      iflog (fun _ ->
               annotate ("heavy copy: slot preparation"));

      let (dst, ty) = deref_ty DEREF_none initializing dst dst_ty in
      let (src, _) = deref_ty DEREF_none false src src_ty in
        assert (ty = dst_ty);
        match ty with
            Ast.TY_nil
          | Ast.TY_bool
          | Ast.TY_mach _
          | Ast.TY_int
          | Ast.TY_uint
          | Ast.TY_native _
          | Ast.TY_type
          | Ast.TY_char ->
              iflog
                (fun _ -> annotate
                   (Printf.sprintf "copy_ty: simple mov (%Ld byte scalar)"
                      (ty_sz cx ty)));
              mov dst (Il.Cell src)

          | Ast.TY_param (i, _) ->
              iflog
                (fun _ -> annotate
                   (Printf.sprintf "copy_ty: parametric copy %#d" i));
              let initflag = Il.Reg (force_to_reg one) in
              aliasing false src
                begin
                  fun src ->
                    let td = get_ty_param ty_params i in
                    let ty_params_ptr = get_tydesc_params ty_params td in
                      trans_call_dynamic_glue
                        td Abi.tydesc_field_copy_glue
                        (Some dst)
                        [| ty_params_ptr; src; initflag |]
                        None
                end

          | Ast.TY_fn _
          | Ast.TY_obj _ ->
              begin
                let src_item =
                  get_element_ptr src Abi.binding_field_dispatch
                in
                let dst_item =
                  get_element_ptr dst Abi.binding_field_dispatch
                in
                let src_binding =
                  get_element_ptr src Abi.binding_field_bound_data
                in
                let dst_binding =
                  get_element_ptr dst Abi.binding_field_bound_data
                in
                  mov dst_item (Il.Cell src_item);
                  mov dst_binding zero;
                  let null_jmp = null_check src_binding in
                    (* Copy if we have a src binding. *)
                    (* FIXME (issue #58): this is completely wrong, call
                     * through to the binding's self-copy fptr. For now
                     * this only works by accident.
                     *)
                    trans_copy_ty ty_params true
                      dst_binding (Ast.TY_box Ast.TY_int)
                      src_binding (Ast.TY_box Ast.TY_int);
                    patch null_jmp
              end

          | _ ->
              if force_inline || should_inline_structure_helpers ty
              then
                iter_ty_parts_full ty_params dst src ty
                  (fun dst src ty ->
                     trans_copy_ty ty_params true
                       dst ty src ty)
              else
                let initflag = Il.Reg (force_to_reg one) in
                  trans_call_static_glue
                    (code_fixup_to_ptr_operand (get_copy_glue ty))
                    (Some dst)
                    [| alias ty_params;
                       alias src;
                       initflag |]
                    None


  and trans_copy
      (initializing:bool)
      (dst:Ast.lval)
      (src:Ast.expr)
      : unit =
    let (dst_cell, dst_ty) = trans_lval_maybe_init initializing dst in
    let dst_ty = strip_mutable_or_constrained_ty dst_ty in
    let rec can_append t =
      match t with
          Ast.TY_vec _
        | Ast.TY_str -> true
        | Ast.TY_box t when can_append t -> true
        | _ -> false
    in
      match (dst_ty, src) with
          (t,
           Ast.EXPR_binary (Ast.BINOP_add,
                            Ast.ATOM_lval a, Ast.ATOM_lval b))
            when can_append t ->
            (*
             * Translate str or vec
             * 
             *   s = a + b
             * 
             * as
             * 
             *   s = a;
             *   s += b;
             *)
            let (a_cell, a_ty) = trans_lval a in
            let (b_cell, b_ty) = trans_lval b in
              trans_copy_ty
                (get_ty_params_of_current_frame())
                initializing dst_cell dst_ty
                a_cell a_ty;
              trans_vec_append dst_cell dst_ty
                (Il.Cell b_cell) b_ty


        | (Ast.TY_obj caller_obj_ty,
           Ast.EXPR_unary (Ast.UNOP_cast t, a)) ->
            let src_ty = atom_type cx a in
            let _ = assert (not (is_prim_type (src_ty))) in
              begin
                let t = Hashtbl.find cx.ctxt_all_cast_types t.id in
                let _ = assert (t = (Ast.TY_obj caller_obj_ty)) in
                let callee_obj_ty =
                  match atom_type cx a with
                      Ast.TY_obj t -> t
                    | _ -> bug () "obj cast from non-obj type"
                in
                let src_cell = need_cell (trans_atom a) in

                (* FIXME (issue #84): this is wrong. It treats the underlying
                 * obj-state as the same as the callee and simply substitutes
                 * the forwarding vtbl, which would be great if it had any way
                 * convey the callee vtbl to the forwarding functions. But it
                 * doesn't. Instead, we have to malloc a fresh 3-word
                 * refcounted obj to hold the callee's vtbl+state pair, copy
                 * that in as the state here.  *)
                let _ =
                  trans_copy_ty (get_ty_params_of_current_frame())
                    initializing
                    dst_cell dst_ty
                    src_cell src_ty
                in
                let caller_vtbl_oper =
                  get_forwarding_vtbl caller_obj_ty callee_obj_ty
                in
                let (caller_obj, _) =
                  deref_ty DEREF_none initializing dst_cell dst_ty
                in
                let caller_vtbl =
                  get_element_ptr caller_obj Abi.obj_field_vtbl
                in
                  mov caller_vtbl caller_vtbl_oper
              end

        | (_, Ast.EXPR_binary _)
        | (_, Ast.EXPR_unary _)
        | (_, Ast.EXPR_atom (Ast.ATOM_literal _)) ->
            (*
             * Translations of these expr types yield vregs,
             * so copy is just MOV into the lval.
             *)
            let src_operand = trans_expr src in
              mov
                (fst (deref_ty DEREF_none false dst_cell dst_ty))
                src_operand

        | (_, Ast.EXPR_atom (Ast.ATOM_lval src_lval)) ->
            if lval_is_direct_fn cx src_lval then
              trans_init_direct_fn dst_cell src_lval
            else
              (* Possibly-large structure copying *)
              let (src_cell, src_ty) = trans_lval src_lval in
                trans_copy_ty
                  (get_ty_params_of_current_frame())
                  initializing
                  dst_cell dst_ty
                  src_cell src_ty

        | (_, Ast.EXPR_atom (Ast.ATOM_pexp _)) ->
            bug () "Trans.trans_copy on ATOM_pexp"


  and trans_init_direct_fn
      (dst_cell:Il.cell)
      (flv:Ast.lval)
      : unit =
    let item = lval_item cx flv in
    let fix = Hashtbl.find cx.ctxt_fn_fixups item.id in

    let dst_pair_code_cell =
      get_element_ptr dst_cell Abi.fn_field_code
    in

    let dst_pair_box_cell =
      get_element_ptr dst_cell Abi.fn_field_box
    in
      mov dst_pair_code_cell (reify_ptr (Il.ImmPtr (fix, Il.CodeTy)));
      mov dst_pair_box_cell zero


  and trans_init_structural_from_atoms
      (dst:Il.cell)
      (dst_tys:Ast.ty array)
      (atoms:Ast.atom array)
      : unit =
    Array.iteri
      begin
        fun i atom ->
          trans_init_ty_from_atom
            (get_element_ptr_dyn_in_current_frame dst i)
            dst_tys.(i) atom
      end
      atoms

  and trans_new_rec_update
      (dst:Il.cell)
      (dst_tys:Ast.ty array)
      (trec:Ast.ty_rec)
      (atab:(Ast.ident * Ast.mutability * Ast.atom) array)
      (base:Ast.lval)
      : unit =
    Array.iteri
      begin
        fun i (fml_ident, _) ->
          let fml_entry _ (act_ident, _, atom) =
            if act_ident = fml_ident then Some atom else None
          in
          let dst_ty = dst_tys.(i) in
            match arr_search atab fml_entry with
                Some atom ->
                  trans_init_ty_from_atom
                    (get_element_ptr_dyn_in_current_frame dst i)
                    dst_ty atom
              | None ->
                  let (src, _) = trans_lval base in
                    trans_copy_ty
                      (get_ty_params_of_current_frame()) true
                      (get_element_ptr_dyn_in_current_frame dst i) dst_ty
                      (get_element_ptr_dyn_in_current_frame src i) dst_ty
      end
      trec

  and trans_init_ty_from_atom
      (dst:Il.cell) (ty:Ast.ty) (atom:Ast.atom)
      : unit =
    let src = Il.Mem (force_to_mem (trans_atom atom)) in
      trans_copy_ty (get_ty_params_of_current_frame())
       true dst ty src ty

  and trans_init_slot_from_cell
      (ty_params:Il.cell)
      (clone:clone_ctrl)
      (dst:Il.cell) (dst_slot:Ast.slot)
      (src:Il.cell) (src_ty:Ast.ty)
      : unit =
    let dst_ty = slot_ty dst_slot in
    let _ =
      iflog (fun _ ->
               log cx "trans_init_slot_from_cell";
               log cx "   dst slot %a, src ty %a"
                 Ast.sprintf_slot dst_slot Ast.sprintf_ty src_ty;
               log cx "   dst cell %s, src cell %s"
                 (cell_str dst) (cell_str src))
    in
      match (dst_slot.Ast.slot_mode, clone) with
          (Ast.MODE_alias, CLONE_none) ->
            mov dst (Il.Cell (alias (Il.Mem (need_mem_cell src))))

        | (Ast.MODE_local, CLONE_none) ->
            trans_copy_ty
              ty_params true
              dst dst_ty src src_ty

        | (Ast.MODE_alias, _) ->
            bug () "attempting to clone into alias slot"

        | (_, CLONE_chan clone_task) ->
            let clone =
              if (type_contains_chan cx src_ty)
              then CLONE_all clone_task
              else CLONE_none
            in
              (* Feed back with massaged args. *)
              trans_init_slot_from_cell ty_params
                clone dst dst_slot src src_ty

        | (_, CLONE_all clone_task) ->
            clone_ty ty_params clone_task dst src src_ty


  and trans_init_slot_from_atom
      (clone:clone_ctrl)
      (dst:Il.cell) (dst_slot:Ast.slot)
      (src_atom:Ast.atom)
      : unit =
    let _ =
      iflog (fun _ ->
               log cx "trans_init_slot_from_atom";
               log cx "   dst slot %a, src ty %a"
                 Ast.sprintf_slot dst_slot
                 Ast.sprintf_ty (atom_type cx src_atom);
               log cx "   dst cell %s"
                 (cell_str dst))
    in
    match (dst_slot.Ast.slot_mode, clone, src_atom) with
        (Ast.MODE_alias, CLONE_none,
         Ast.ATOM_literal _) ->
          (* Aliasing a literal is a bit weird since nobody
           * else will ever see it, but it seems harmless.
           *)
          let src = trans_atom src_atom in
            mov dst (Il.Cell (alias (Il.Mem (force_to_mem src))))

      | (Ast.MODE_alias, CLONE_chan _, _)
      | (Ast.MODE_alias, CLONE_all _, _) ->
          bug () "attempting to clone into alias slot"
      | _ ->
          let src = Il.Mem (force_to_mem (trans_atom src_atom)) in
            begin
              log cx "   forced-to-mem src cell %s" (cell_str src);
              trans_init_slot_from_cell
                (get_ty_params_of_current_frame())
                clone dst dst_slot src (atom_type cx src_atom)
            end


  and trans_be_fn
      (cx:ctxt)
      (dst_cell:Il.cell)
      (flv:Ast.lval)
      (ty_params:Ast.ty array)
      (args:Ast.atom array)
      : unit =
    let (ptr, fn_ty) = trans_callee flv in
    let cc = call_ctrl flv in
    let call = { call_ctrl = cc;
                 call_callee_ptr = ptr;
                 call_callee_ty = fn_ty;
                 call_callee_ty_params = ty_params;
                 call_output = dst_cell;
                 call_args = args;
                 call_iterator_args = call_iterator_args None;
                 call_indirect_args = call_indirect_args flv cc }
    in
      (* FIXME (issue #85): true if caller is object fn *)
    let caller_is_closure = false in
      log cx "trans_be_fn: %s call to lval %a"
        (call_ctrl_string cc) Ast.sprintf_lval flv;
      trans_be (fun () -> Ast.sprintf_lval () flv) caller_is_closure call

  and trans_prepare_fn_call
      (initializing:bool)
      (cx:ctxt)
      (dst_cell:Il.cell)
      (flv:Ast.lval)
      (ty_params:Ast.ty array)
      (fco:for_each_ctrl option)
      (args:Ast.atom array)
      : Il.operand =
    let (ptr, fn_ty) = trans_callee flv in
    let cc = call_ctrl flv in
    let call = { call_ctrl = cc;
                 call_callee_ptr = ptr;
                 call_callee_ty = fn_ty;
                 call_callee_ty_params = ty_params;
                 call_output = dst_cell;
                 call_args = args;
                 call_iterator_args = call_iterator_args fco;
                 call_indirect_args = call_indirect_args flv cc }
    in
      iflog
        begin
          fun _ ->
            log cx "trans_prepare_fn_call: %s call to lval %a"
              (call_ctrl_string cc) Ast.sprintf_lval flv;
            log cx "lval type: %a" Ast.sprintf_ty fn_ty;
            Array.iteri (fun i t -> log cx "ty param %d = %a"
                           i Ast.sprintf_ty t)
              ty_params;
        end;
      trans_prepare_call initializing (fun () -> Ast.sprintf_lval () flv) call

  and trans_call_pred_and_check
      (constr:Ast.constr)
      (flv:Ast.lval)
      (args:Ast.atom array)
      : unit =
    let (ptr, fn_ty) = trans_callee flv in
    let dst_cell = Il.Mem (force_to_mem imm_false) in
    let call = { call_ctrl = call_ctrl flv;
                 call_callee_ptr = ptr;
                 call_callee_ty = fn_ty;
                 call_callee_ty_params = [| |];
                 call_output = dst_cell;
                 call_args = args;
                 call_iterator_args = [| |];
                 call_indirect_args = [| |] }
    in
      iflog (fun _ -> annotate "predicate call");
      let fn_ptr =
        trans_prepare_call true (fun _ -> Ast.sprintf_lval () flv) call
      in
        call_code (code_of_operand fn_ptr);
        iflog (fun _ -> annotate "predicate check/fail");
        let jmp = trans_compare_simple Il.JE (Il.Cell dst_cell) imm_true in
        let errstr = Printf.sprintf "predicate check: %a"
          Ast.sprintf_constr constr
        in
          trans_cond_fail errstr jmp

  and trans_init_closure
      (closure_cell:Il.cell)
      (target_fn_ptr:Il.operand)
      (target_binding_ptr:Il.operand)
      (ty_params:Ast.ty array)
      (bound_arg_slots:Ast.slot array)
      (bound_args:Ast.atom array)
      : unit =

    let rc_cell = get_element_ptr closure_cell Abi.box_rc_field_refcnt in
    let body_cell = get_element_ptr closure_cell Abi.box_rc_field_body in
    let targ_cell = get_element_ptr body_cell Abi.closure_body_elt_target in
    let bound_args_tydesc_cell =
      get_element_ptr body_cell Abi.closure_body_elt_bound_args_tydesc
    in
    let bound_ty_params_cell =
      get_element_ptr body_cell Abi.closure_body_elt_bound_ty_params
    in
    let args_cell =
      get_element_ptr body_cell Abi.closure_body_elt_bound_args
    in

    iflog (fun _ -> annotate "init closure refcount");
    mov rc_cell one;

    iflog (fun _ -> annotate "set closure bound-args tydesc ptr");
    mov bound_args_tydesc_cell
      (Il.Cell (get_tydesc None
                  (Ast.TY_tup (Array.map slot_ty bound_arg_slots))));


    iflog (fun _ -> annotate "set closure target code ptr");
    mov
      (get_element_ptr targ_cell Abi.fn_field_code)
      (reify_ptr target_fn_ptr);

    iflog (fun _ -> annotate "set closure target closure ptr");
    mov
      (get_element_ptr targ_cell Abi.fn_field_box)
      (reify_ptr target_binding_ptr);

    iflog (fun _ -> annotate "set closure bound tydescs");
    Array.iteri
      begin
        fun i ty ->
          mov
            (get_element_ptr bound_ty_params_cell i)
            (Il.Cell (get_tydesc None ty))
      end
      ty_params;

    iflog (fun _ -> annotate "set closure bound args");
    copy_bound_args args_cell bound_arg_slots bound_args

  and trans_bind_fn
      (initializing:bool)
      (cc:call_ctrl)
      (bind_id:node_id)
      (dst:Ast.lval)
      (flv:Ast.lval)
      (fn_sig:Ast.ty_sig)
      (args:Ast.atom option array)
      : unit =
    let (dst_cell, _) = trans_lval_maybe_init initializing dst in
    let (target_ptr, _) = trans_callee flv in
    let ty_params =
      match htab_search cx.ctxt_call_lval_params (lval_base_id flv) with
          Some params -> params
        | None -> [| |]
    in
    let n_ty_params = Array.length ty_params in
    let arg_bound_flags = Array.map bool_of_option args in
    let arg_slots =
      arr_map2
        (fun arg_slot bound_flag ->
           if bound_flag then Some arg_slot else None)
        fn_sig.Ast.sig_input_slots
        arg_bound_flags
    in
    let bound_arg_slots = arr_filter_some arg_slots in
    let bound_args = arr_filter_some args in
    let thunk_fixup =
      get_fn_thunk_glue bind_id n_ty_params
        fn_sig.Ast.sig_input_slots arg_bound_flags
    in
    let target_code_ptr = callee_code_ptr target_ptr cc in
    let target_box_ptr = callee_box_ptr flv cc in
    let closure_box_rty = closure_box_rty cx n_ty_params bound_arg_slots in
    let closure_box_sz =
      calculate_sz_in_current_frame
        (Il.referent_ty_size word_bits closure_box_rty)
    in
    let pair_code_cell = get_element_ptr dst_cell Abi.fn_field_code in
    let pair_box_cell =
      cell_cast
        (get_element_ptr dst_cell Abi.fn_field_box)
        (Il.ScalarTy (Il.AddrTy (closure_box_rty)))
    in
      iflog (fun _ -> annotate "assign thunk-ptr to code field of pair");
      mov pair_code_cell (reify_ptr (Il.ImmPtr (thunk_fixup, Il.CodeTy)));
      iflog (fun _ ->
               annotate "heap-allocate closure to binding slot of pair");
      trans_malloc pair_box_cell closure_box_sz zero;
      trans_init_closure
        (deref pair_box_cell)
        target_code_ptr
        target_box_ptr
        ty_params
        bound_arg_slots
        bound_args


  and trans_arg0 (arg_cell:Il.cell) (initializing:bool) (call:call) : unit =
    (* Emit arg0 of any call: the output slot. *)
    iflog (fun _ -> annotate "fn-call arg 0: output slot");
    if not initializing
    then
      drop_slot
        (get_ty_params_of_current_frame())
        call.call_output
        (call_output_slot call);
    (* We always get to the same state here: the output slot is uninitialized.
     * We then do something that's illegal to do in the language, but legal
     * here: alias the uninitialized memory. We are ok doing this because the
     * call will fill it in before anyone else observes it. That's the
     * point.
     *)
    mov arg_cell (Il.Cell (alias call.call_output));

  and trans_arg1 (arg_cell:Il.cell) : unit =
    (* Emit arg1 of any call: the task pointer. *)
    iflog (fun _ -> annotate "fn-call arg 1: task pointer");
    trans_init_slot_from_cell
      (get_ty_params_of_current_frame())
      CLONE_none
      arg_cell word_slot
      abi.Abi.abi_tp_cell word_ty

  and trans_argN
      (clone:clone_ctrl)
      (arg_cell:Il.cell)
      (arg_slot:Ast.slot)
      (arg:Ast.atom)
      : unit =
    iflog (fun _ -> log cx "trans_argN: arg slot %a, arg atom %a"
             Ast.sprintf_slot arg_slot Ast.sprintf_atom arg);
    trans_init_slot_from_atom clone arg_cell arg_slot arg

  and code_of_cell (cell:Il.cell) : Il.code =
    match cell with
        Il.Mem (_, Il.ScalarTy (Il.AddrTy Il.CodeTy))
      | Il.Reg (_, Il.AddrTy Il.CodeTy) -> Il.CodePtr (Il.Cell cell)
      | _ ->
          bug () "expected code-pointer cell, found %s"
            (cell_str cell)

  and code_of_operand (operand:Il.operand) : Il.code =
    match operand with
        Il.Cell c -> code_of_cell c
      | Il.ImmPtr (_, Il.CodeTy) -> Il.CodePtr operand
      | _ ->
          bug () "expected code-pointer operand, got %s"
            (oper_str operand)

  and ty_arg_slots (ty:Ast.ty) : Ast.slot array =
    match simplified_ty ty with
        Ast.TY_fn (tsig, _) -> tsig.Ast.sig_input_slots
      | _ -> bug () "Trans.ty_arg_slots on non-callable type: %a"
          Ast.sprintf_ty ty

  and copy_fn_args
      (tail_area:bool)
      (initializing_arg0:bool)
      (clone:clone_ctrl)
      (call:call)
      : unit =

    let n_ty_params = Array.length call.call_callee_ty_params in
    let all_callee_args_rty =
      let clo =
        if call.call_ctrl = CALL_direct
        then None
        else (Some Il.OpaqueTy)
      in
        call_args_referent_type cx n_ty_params call.call_callee_ty clo
    in
    let all_callee_args_cell =
      callee_args_cell tail_area all_callee_args_rty
    in

    let _ = iflog (fun _ -> annotate
                     (Printf.sprintf
                        "copying fn args to %d-ty-param call with rty: %s\n"
                        n_ty_params (Il.string_of_referent_ty
                                       all_callee_args_rty)))
    in
    let callee_arg_slots = ty_arg_slots call.call_callee_ty in
    let callee_output_cell =
      get_element_ptr all_callee_args_cell Abi.calltup_elt_out_ptr
    in
    let callee_task_cell =
      get_element_ptr all_callee_args_cell Abi.calltup_elt_task_ptr
    in
    let callee_indirect_args =
      get_element_ptr all_callee_args_cell Abi.calltup_elt_indirect_args
    in
    let callee_ty_params =
      get_element_ptr all_callee_args_cell Abi.calltup_elt_ty_params
    in
    let callee_args =
      get_element_ptr_dyn_in_current_frame
        all_callee_args_cell Abi.calltup_elt_args
    in
    let callee_iterator_args =
      get_element_ptr_dyn_in_current_frame
        all_callee_args_cell Abi.calltup_elt_iterator_args
    in

    let n_args = Array.length call.call_args in
    let n_iterators = Array.length call.call_iterator_args in
    let n_indirects = Array.length call.call_indirect_args in

      Array.iteri
        begin
          fun i arg_atom ->
            iflog (fun _ ->
                     annotate
                       (Printf.sprintf "fn-call arg %d of %d (+ %d indirect)"
                          i n_args n_indirects));
            trans_argN
              clone
              (get_element_ptr_dyn_in_current_frame callee_args i)
              callee_arg_slots.(i)
              arg_atom
        end
        call.call_args;

      Array.iteri
        begin
          fun i iterator_arg_operand ->
            iflog (fun _ ->
                     annotate (Printf.sprintf "fn-call iterator-arg %d of %d"
                                 i n_iterators));
            mov
              (get_element_ptr_dyn_in_current_frame callee_iterator_args i)
              iterator_arg_operand
        end
        call.call_iterator_args;

      Array.iteri
        begin
          fun i indirect_arg_operand ->
            iflog (fun _ ->
                     annotate (Printf.sprintf "fn-call indirect-arg %d of %d"
                                 i n_indirects));
            mov
              (get_element_ptr_dyn_in_current_frame callee_indirect_args i)
              indirect_arg_operand
        end
        call.call_indirect_args;

      Array.iteri
        begin
          fun i ty_param ->
            iflog (fun _ ->
                     annotate
                       (Printf.sprintf "fn-call ty param %d of %d"
                          i n_ty_params));
            trans_init_slot_from_cell
              (get_ty_params_of_current_frame())
              CLONE_none
              (get_element_ptr callee_ty_params i) word_slot
              (get_tydesc None ty_param) word_ty
        end
        call.call_callee_ty_params;

      trans_arg1 callee_task_cell;

      trans_arg0 callee_output_cell initializing_arg0 call



  and call_code (code:Il.code) : unit =
    let vr = next_vreg_cell Il.voidptr_t in
      emit (Il.call vr code);


  and copy_bound_args
      (dst_cell:Il.cell)
      (bound_arg_slots:Ast.slot array)
      (bound_args:Ast.atom array)
      : unit =
    let n_slots = Array.length bound_arg_slots in
      Array.iteri
        begin
          fun i slot ->
            iflog (fun _ ->
                     annotate (Printf.sprintf
                                 "copy bound arg %d of %d" i n_slots));
            trans_argN CLONE_none
              (get_element_ptr dst_cell i)
              slot bound_args.(i)
        end
        bound_arg_slots

  and merge_bound_args
      (n_ty_params:int)
      (all_self_args_rty:Il.referent_ty)
      (all_callee_args_rty:Il.referent_ty)
      (arg_slots:Ast.slot array)
      (arg_bound_flags:bool array)
      : unit =
    begin
      (* 
       * NB: 'all_*_args', both self and callee, are always 5-tuples: 
       * 
       *    [out_ptr, task_ptr, indirect_args, ty_params, [args]]
       * 
       * The first few bindings here just destructure those via GEP.
       * 
       *)
      let all_self_args_cell = caller_args_cell all_self_args_rty in
      let all_callee_args_cell = callee_args_cell false all_callee_args_rty in

      let self_args_cell =
        get_element_ptr all_self_args_cell Abi.calltup_elt_args
      in
      let self_indirect_args_cell =
        get_element_ptr all_self_args_cell Abi.calltup_elt_indirect_args
      in
      let closure_box_cell =
        deref (get_element_ptr self_indirect_args_cell
                 Abi.indirect_args_elt_closure)
      in
      let closure_cell =
        get_element_ptr closure_box_cell Abi.box_rc_field_body
      in
      let closure_args_cell =
        get_element_ptr closure_cell Abi.closure_body_elt_bound_args
      in
      let closure_ty_params_cell =
        get_element_ptr closure_cell Abi.closure_body_elt_bound_ty_params
      in
      let callee_ty_params_cell =
        get_element_ptr all_callee_args_cell Abi.calltup_elt_ty_params
      in
      let callee_args_cell =
        get_element_ptr_dyn closure_ty_params_cell
          all_callee_args_cell Abi.calltup_elt_args
      in

      let n_args = Array.length arg_bound_flags in
      let bound_i = ref 0 in
      let unbound_i = ref 0 in

        iflog (fun _ -> annotate "copy out-ptr");
        mov
          (get_element_ptr all_callee_args_cell Abi.calltup_elt_out_ptr)
          (Il.Cell (get_element_ptr all_self_args_cell
                      Abi.calltup_elt_out_ptr));

        iflog (fun _ -> annotate "copy task-ptr");
        mov
          (get_element_ptr all_callee_args_cell Abi.calltup_elt_task_ptr)
          (Il.Cell (get_element_ptr all_self_args_cell
                      Abi.calltup_elt_task_ptr));

        iflog (fun _ -> annotate "copy ty-params");
        for ty_i = 0 to (n_ty_params - 1) do
          mov
            (get_element_ptr callee_ty_params_cell ty_i)
            (Il.Cell (get_element_ptr closure_ty_params_cell ty_i))
        done;

        iflog (fun _ -> annotate "copy args");
        for arg_i = 0 to (n_args - 1) do
          let dst_cell = get_element_ptr callee_args_cell arg_i in
          let slot = arg_slots.(arg_i) in
          let is_bound = arg_bound_flags.(arg_i) in
          let src_cell =
            if is_bound then
              begin
                iflog (fun _ -> annotate
                         (Printf.sprintf
                            "extract bound arg %d as actual arg %d"
                            !bound_i arg_i));
                get_element_ptr closure_args_cell (!bound_i)
              end
            else
              begin
                iflog (fun _ -> annotate
                         (Printf.sprintf
                            "extract unbound arg %d as actual arg %d"
                            !unbound_i arg_i));
                get_element_ptr self_args_cell (!unbound_i);
              end
          in
            iflog (fun _ -> annotate
                     (Printf.sprintf
                        "copy into actual-arg %d" arg_i));
            trans_init_slot_from_cell
              closure_ty_params_cell CLONE_none
              dst_cell slot
              (deref_slot false src_cell slot) (slot_ty slot);
            incr (if is_bound then bound_i else unbound_i);
        done;
        assert ((!bound_i + !unbound_i) == n_args)
    end


  and callee_code_ptr
      (fptr:Il.operand)
      (cc:call_ctrl)
      : Il.operand =
    match cc with
        CALL_direct
      | CALL_vtbl -> fptr
      | CALL_indirect ->
          (* fptr is a pair [code*, box*] *)
          let pair_cell = need_cell (reify_ptr fptr) in
            Il.Cell (get_element_ptr pair_cell Abi.fn_field_code)

  and callee_box_ptr
      (pair_lval:Ast.lval)
      (cc:call_ctrl)
      : Il.operand =
    if cc = CALL_direct
    then zero
    else
      let (pair_cell, ty) = trans_lval pair_lval in
      let (pair_cell, _) =
        if cc = CALL_vtbl
          (* |pair_lval| here is the obj to whose vtbl we're dispatching.
           * Said obj might have been auto-deref'ed for the method call,
           * so we have to be sure to do the same here.
           *)
        then deref_ty DEREF_all_boxes false pair_cell ty
        else (pair_cell, ty)
      in
        Il.Cell (get_element_ptr pair_cell Abi.binding_field_bound_data)

  and call_ctrl flv : call_ctrl =
    if lval_is_static cx flv
    then CALL_direct
    else
      if lval_is_obj_vtbl cx flv
      then CALL_vtbl
      else CALL_indirect

  and call_ctrl_string cc =
    match cc with
        CALL_direct -> "direct"
      | CALL_indirect -> "indirect"
      | CALL_vtbl -> "vtbl"

  and call_iterator_args
      (fco:for_each_ctrl option)
      : Il.operand array =
    match fco with
        None -> [| |]
      | Some fco ->
          begin
            iflog (fun _ -> annotate "calculate iterator args");
            [| reify_ptr (code_fixup_to_ptr_operand fco.for_each_fixup);
               Il.Cell (Il.Reg (abi.Abi.abi_fp_reg, Il.voidptr_t)); |]
          end

  and call_indirect_args
      (flv:Ast.lval)
      (cc:call_ctrl)
      : Il.operand array =
      begin
        match cc with
            CALL_direct -> [| |]
          | CALL_indirect -> [| callee_box_ptr flv cc |]
          | CALL_vtbl ->
              begin
                match flv with
                    (* FIXME (issue #84): will need to pass both words of obj
                     * if we add a 'self' value for self-dispatch within
                     * objs. Also to support forwarding-functions / 'as'.
                     *)
                    Ast.LVAL_ext (base, _) -> [| callee_box_ptr base cc |]
                  | _ ->
                      bug (lval_base_id flv)
                        "call_indirect_args on obj-fn without base obj"
              end
      end

  and trans_be
      (logname:(unit -> string))
      (caller_is_closure:bool)
      (call:call)
      : unit =
    let callee_fptr = callee_code_ptr call.call_callee_ptr call.call_ctrl in
    let callee_code = code_of_operand callee_fptr in
    let callee_args_rty =
      call_args_referent_type cx 0 call.call_callee_ty
        (if call.call_ctrl = CALL_direct then None else (Some Il.OpaqueTy))
    in
    let callee_argsz =
      force_sz (Il.referent_ty_size word_bits callee_args_rty)
    in
    let closure_rty =
      if caller_is_closure
      then Some Il.OpaqueTy
      else None
    in
    let caller_args_rty = current_fn_args_rty closure_rty in
    let caller_argsz =
      force_sz (Il.referent_ty_size word_bits caller_args_rty)
    in
      iflog (fun _ -> annotate
               (Printf.sprintf "copy args for tail call to %s" (logname ())));
      copy_fn_args true true CLONE_none call;
      drop_slots_at_curr_stmt();
      iflog (fun _ -> annotate "drop args");
      iter_arg_slots cx (current_fn()) callee_drop_slot;
      abi.Abi.abi_emit_fn_tail_call (emitter())
        (force_sz (current_fn_callsz()))
        caller_argsz callee_code callee_argsz;

  and trans_prepare_call
      (initializing:bool)
      (logname:(unit -> string))
      (call:call)
      : Il.operand =

    let callee_fptr = callee_code_ptr call.call_callee_ptr call.call_ctrl in
      iflog (fun _ -> annotate
               (Printf.sprintf "copy args for call to %s" (logname ())));
      copy_fn_args false initializing CLONE_none call;
      iflog (fun _ -> annotate (Printf.sprintf "call %s" (logname ())));
      callee_fptr

  and callee_drop_slot
      (k:Ast.slot_key)
      (slot_id:node_id)
      (slot:Ast.slot)
      : unit =
    iflog (fun _ ->
             annotate (Printf.sprintf "callee_drop_slot %d = %s "
                         (int_of_node slot_id)
                         (Fmt.fmt_to_str Ast.fmt_slot_key k)));
    drop_slot_in_current_frame (cell_of_block_slot slot_id) slot


  and trans_alt_tag (at:Ast.stmt_alt_tag) : unit =

    let trans_arm arm : quad_idx =
      let (pat, block) = arm.node in

      (* Translates the pattern and returns the addresses of the branch
       * instructions that are taken if the match fails.
       *)
      let rec trans_pat
          (pat:Ast.pat)
          (src_cell:Il.cell)
          (src_ty:Ast.ty)
          : quad_idx list =

        match pat with
            Ast.PAT_lit lit ->
              trans_compare_simple Il.JNE (trans_lit lit) (Il.Cell src_cell)

          | Ast.PAT_tag (lval, pats) ->
              let tag_ident =
                match lval with
                    Ast.LVAL_ext (_, (Ast.COMP_named (Ast.COMP_ident id)))
                  | Ast.LVAL_ext (_, (Ast.COMP_named (Ast.COMP_app (id, _))))
                  | Ast.LVAL_base { node = Ast.BASE_ident id; id = _ }
                  | Ast.LVAL_base { node = Ast.BASE_app (id, _); id = _ } ->
                      id
                  | _ -> bug cx "expected lval ending in ident"
              in
              let ttag =
                match strip_mutable_or_constrained_ty src_ty with
                    Ast.TY_tag ttag -> ttag
                  | _ -> bug cx "expected tag type"
              in
              let tinfo = Hashtbl.find cx.ctxt_all_tag_info ttag.Ast.tag_id in
              let (i,_,_) =
                Hashtbl.find tinfo.tag_idents tag_ident
              in
              let ttup = get_nth_tag_tup cx ttag i in

              let tag_cell:Il.cell =
                get_element_ptr src_cell Abi.tag_elt_discriminant
              in
              let union_cell =
                get_element_ptr_dyn_in_current_frame
                  src_cell
                  Abi.tag_elt_variant
              in

              let next_jumps =
                trans_compare_simple Il.JNE
                  (Il.Cell tag_cell) (imm (Int64.of_int i))
              in

              let tup_cell:Il.cell = get_variant_ptr union_cell i in

              let trans_elem_pat i elem_pat : quad_idx list =
                let elem_cell =
                  get_element_ptr_dyn_in_current_frame tup_cell i
                in
                let elem_ty = ttup.(i) in
                  trans_pat elem_pat elem_cell elem_ty
              in

              let elem_jumps =
                List.concat (Array.to_list (Array.mapi trans_elem_pat pats))
              in
                next_jumps @ elem_jumps

          | Ast.PAT_slot (dst, _) ->
              let dst_slot = get_slot cx dst.id in
              let dst_cell = cell_of_block_slot dst.id in
                trans_init_slot_from_cell
                  (get_ty_params_of_current_frame())
                  CLONE_none dst_cell dst_slot
                  src_cell src_ty;
                []                 (* irrefutable *)

          | Ast.PAT_wild -> []     (* irrefutable *)
      in

      let (lval_cell, lval_ty) = trans_lval at.Ast.alt_tag_lval in
      let next_jumps = trans_pat pat lval_cell lval_ty in
        trans_block block;
        let last_jump = mark() in
          emit (Il.jmp Il.JMP Il.CodeNone);
          List.iter patch next_jumps;
          last_jump
    in
    let last_jumps = Array.map trans_arm at.Ast.alt_tag_arms in
      if not (arr_exists
                (fun _ arm -> (fst arm.node) = Ast.PAT_wild)
                at.Ast.alt_tag_arms)
      then
        trans_cond_fail "non-exhaustive match failure"
          (Array.to_list last_jumps)
      else
        Array.iter patch last_jumps

  (* If we're about to drop a channel, synthesize an upcall_flush_chan.
   * TODO: This should rather appear in a chan dtor when chans become
   * objects. *)
  and check_and_flush_chan
    (cell:Il.cell)
    (slot:Ast.slot)
      : unit =
      let ty = strip_mutable_or_constrained_ty (slot_ty slot) in
      match simplified_ty ty with
          Ast.TY_chan _ ->
                annotate "check_and_flush_chan, flush_chan";
                let rc = box_rc_cell cell in
                  emit (Il.cmp (Il.Cell rc) one);
                let jump = mark () in
                  emit (Il.jmp Il.JNE Il.CodeNone);
                  trans_void_upcall "upcall_flush_chan" [| Il.Cell cell |];
                  patch jump;
        | _ -> ()

  and drop_slots_at_curr_stmt _ : unit =
    let stmt = Stack.top curr_stmt in
      match htab_search cx.ctxt_post_stmt_slot_drops stmt with
          None -> ()
        | Some slots ->
            List.iter
              begin
                fun slot_id ->
                  let slot = get_slot cx slot_id in
                  let k = Hashtbl.find cx.ctxt_slot_keys slot_id in
                    iflog (fun _ ->
                             annotate
                               (Printf.sprintf
                                  "post-stmt, drop_slot %d = %s "
                                  (int_of_node slot_id)
                                  (Fmt.fmt_to_str Ast.fmt_slot_key k)));
                    drop_slot_in_current_frame
                      (cell_of_block_slot slot_id) slot
              end
              slots

  and trans_stmt (stmt:Ast.stmt) : unit =
    (* Helper to localize errors by stmt, at minimum. *)
    try
      iflog
        begin
          fun _ ->
            let s = Fmt.fmt_to_str Ast.fmt_stmt_body stmt in
              log cx "translating stmt: %s" s;
              annotate s;
        end;
      Stack.push stmt.id curr_stmt;
      (in_quad_category "stmt"
         (fun _ -> trans_stmt_full stmt));
      begin
        match stmt.node with
            Ast.STMT_be _
          | Ast.STMT_ret _ -> ()
          | _ -> drop_slots_at_curr_stmt();
      end;
      ignore (Stack.pop curr_stmt);
    with
        Semant_err (None, msg) -> raise (Semant_err ((Some stmt.id), msg))


  and maybe_init (id:node_id) (action:string) (dst:Ast.lval) : bool =
    let b = Hashtbl.mem cx.ctxt_stmt_is_init id in
    let act = if b then ("initializing-" ^ action) else action in
      iflog
        (fun _ ->
           annotate (Printf.sprintf "%s on dst lval %a"
                       act Ast.sprintf_lval dst));
      b


  and get_current_output_cell_and_slot _ : (Il.cell * Ast.slot) =
    let curr_fty =
      need_ty_fn (Hashtbl.find cx.ctxt_all_item_types (current_fn()))
    in
    let curr_args = get_args_for_current_frame () in
    let curr_outptr =
      get_element_ptr curr_args Abi.calltup_elt_out_ptr
    in
    let dst_cell = deref curr_outptr in
    let dst_slot = (fst curr_fty).Ast.sig_output_slot in
      (dst_cell, dst_slot)

  and trans_set_outptr (at:Ast.atom) : unit =
    let (dst_cell, dst_slot) = get_current_output_cell_and_slot () in
      trans_init_slot_from_atom
        CLONE_none dst_cell dst_slot at


  and trans_for_loop (fo:Ast.stmt_for) : unit =
    let ty_params = get_ty_params_of_current_frame () in
    let dst_slot_id = (fst (fo.Ast.for_slot)).id in
    let dst_slot = get_slot cx dst_slot_id in
    let dst_cell = cell_of_block_slot dst_slot_id in
    let seq = fo.Ast.for_seq in
    let (seq_cell, seq_ty) = trans_lval seq in
    let unit_ty = seq_unit_ty seq_ty in
      iter_seq_parts ty_params seq_cell seq_cell unit_ty
        (simplified_ty seq_ty = Ast.TY_str)
        begin
          fun _ src_cell unit_ty ->
            trans_init_slot_from_cell
              ty_params CLONE_none
              dst_cell dst_slot
              src_cell unit_ty;
            trans_block fo.Ast.for_body;
        end

  and trans_for_each_loop (stmt_id:node_id) (fe:Ast.stmt_for_each) : unit =
    let id = fe.Ast.for_each_body.id in
    let g = GLUE_loop_body id in
    let name = glue_str cx g in
    let fix = new_fixup name in
    let framesz = get_framesz cx id in
    let callsz = get_callsz cx id in
    let spill = Hashtbl.find cx.ctxt_spill_fixups id in
      push_new_emitter_with_vregs (Some id);
      iflog (fun _ -> annotate "prologue");
      abi.Abi.abi_emit_fn_prologue (emitter())
        framesz callsz nabi_rust (upcall_fixup "upcall_grow_task")
        false cx.ctxt_sess.Session.sess_minimal;
      write_frame_info_ptrs None;
      iflog (fun _ -> annotate "finished prologue");
      trans_block fe.Ast.for_each_body;
      trans_glue_frame_exit fix spill g;

      (* 
       * We've now emitted the body helper-fn. Next, set up a loop that
       * calls the iter and passes the helper-fn in.
       *)
      emit (Il.Enter
              (Hashtbl.find
                 cx.ctxt_block_fixups
                 fe.Ast.for_each_head.id));
      let (dst_slot, _) = fe.Ast.for_each_slot in
      let dst_cell = cell_of_block_slot dst_slot.id in
      let (flv, args) = fe.Ast.for_each_call in
      let ty_params =
        match htab_search cx.ctxt_call_lval_params (lval_base_id flv) with
            Some params -> params
          | None -> [| |]
      in
      let depth = get_stmt_depth cx stmt_id in
      let fc = { for_each_fixup = fix; for_each_depth = depth } in
        iflog (fun _ ->
                 log cx "for-each at depth %d\n" depth);
        let fn_ptr =
          trans_prepare_fn_call true cx dst_cell flv ty_params (Some fc) args
        in
          call_code (code_of_operand fn_ptr);
          emit Il.Leave;

  and trans_put (atom_opt:Ast.atom option) : unit =
    begin
      match atom_opt with
          None -> ()
        | Some at -> trans_set_outptr at
    end;
    let block_fptr = Il.Cell (get_iter_block_fn_for_current_frame ()) in
    let fp = get_iter_outer_frame_ptr_for_current_frame () in
    let vr = next_vreg_cell Il.voidptr_t in
      mov vr zero;
      trans_call_glue
        (code_of_operand block_fptr)
        None
        [| vr; fp |]
        None

  and trans_vec_append
      (dst_cell:Il.cell)
      (dst_ty:Ast.ty)
      (src_oper:Il.operand)
      (src_ty:Ast.ty)
      : unit =
    let elt_ty = seq_unit_ty dst_ty in
    let trailing_null = simplified_ty dst_ty = Ast.TY_str in
      match (simplified_ty dst_ty, simplified_ty src_ty) with
          (Ast.TY_str, Ast.TY_str)
        | (Ast.TY_vec _, Ast.TY_vec _)
            when (simplified_ty dst_ty) = (simplified_ty src_ty) ->

            let src_cell = need_cell src_oper in
            let src_vec = deref src_cell in
            let src_fill = get_element_ptr src_vec Abi.vec_elt_fill in

              aliasing true dst_cell
                begin
                  fun dst_vec_alias ->
                    trans_call_simple_static_glue
                      (get_vec_grow_glue ())
                      (get_ty_params_of_current_frame ())
                      [| get_tydesc None dst_ty;
                         get_tydesc None elt_ty;
                         dst_vec_alias;
                         src_fill; |]
                      None
                end;

              (*
               * By now, dst_cell points to a vec/str with room for us
               * to add to.
               *)

              let dst_vec = deref dst_cell in
              let dst_fill = get_element_ptr dst_vec Abi.vec_elt_fill in

                if trailing_null
                then sub_from dst_fill (imm 1L);

                (* Copy loop: *)
                let eltp_rty = Il.AddrTy (referent_type cx elt_ty) in
                let dptr = next_vreg_cell eltp_rty in
                let sptr = next_vreg_cell eltp_rty in
                let dlim = next_vreg_cell eltp_rty in
                let elt_sz = ty_sz_in_current_frame elt_ty in
                let dst_data =
                  get_element_ptr_dyn_in_current_frame
                    dst_vec Abi.vec_elt_data
                in
                let src_data =
                  get_element_ptr_dyn_in_current_frame
                    src_vec Abi.vec_elt_data
                in
                  lea dptr (fst (need_mem_cell dst_data));
                  lea sptr (fst (need_mem_cell src_data));
                  add_to dptr (Il.Cell dst_fill);
                  mov dlim (Il.Cell dptr);
                  add_to dlim (Il.Cell src_fill);
                  let fwd_jmp = mark () in
                    emit (Il.jmp Il.JMP Il.CodeNone);
                    let back_jmp_targ = mark () in
                      (* copy slot *)
                      trans_copy_ty
                        (get_ty_params_of_current_frame()) true
                        (deref dptr) elt_ty
                        (deref sptr) elt_ty;
                      add_to dptr elt_sz;
                      add_to sptr elt_sz;
                      patch fwd_jmp;
                      check_interrupt_flag ();
                      let back_jmp =
                        trans_compare_simple
                          Il.JB (Il.Cell dptr) (Il.Cell dlim)
                      in
                        List.iter
                          (fun j -> patch_existing j back_jmp_targ) back_jmp;
                        let v = next_vreg_cell word_sty in
                          mov v (Il.Cell src_fill);
                          add_to dst_fill (Il.Cell v);

        | (Ast.TY_str, e)
        | (Ast.TY_vec _, e)
            when e = simplified_ty elt_ty ->

            let elt_sz = ty_sz_in_current_frame elt_ty in
            let elt_sz_cell = Il.Reg (force_to_reg elt_sz) in
            let elt_sz = Il.Cell elt_sz_cell in

              aliasing true dst_cell
                begin
                  fun dst_vec_alias ->
                    trans_call_simple_static_glue
                      (get_vec_grow_glue ())
                      (get_ty_params_of_current_frame ())
                      [| get_tydesc None dst_ty;
                         get_tydesc None elt_ty;
                         dst_vec_alias;
                         elt_sz_cell; |]
                      None
                end;

              (* 
               * By now, dst_cell points to a vec/str with room for us
               * to add to.
               *)

              (* Reload dst vec, fill; might have changed. *)
              let dst_vec = deref dst_cell in
              let dst_fill = get_element_ptr dst_vec Abi.vec_elt_fill in

              let eltp_rty = Il.AddrTy (referent_type cx elt_ty) in
              let dptr = next_vreg_cell eltp_rty in
              let dst_data =
                get_element_ptr_dyn_in_current_frame
                  dst_vec Abi.vec_elt_data
              in
                lea dptr (fst (need_mem_cell dst_data));
                add_to dptr (Il.Cell dst_fill);
                if trailing_null
                then sub_from dptr elt_sz;
                trans_copy_ty
                  (get_ty_params_of_current_frame()) true
                  (deref dptr) elt_ty
                  (Il.Mem (force_to_mem src_oper)) elt_ty;
                add_to dptr elt_sz;
                if trailing_null
                then mov (deref dptr) zero_byte;
                add_to dst_fill elt_sz;

        | _ ->
            begin
              bug () "unsupported vector-append types %a += %a"
                Ast.sprintf_ty dst_ty
                Ast.sprintf_ty src_ty
            end


  and trans_copy_binop dst binop a_src =
    let (dst_cell, dst_ty) = trans_lval dst in
    let src_oper = trans_atom a_src in
      match dst_ty with
          Ast.TY_str
        | Ast.TY_vec _ when binop = Ast.BINOP_add ->
            trans_vec_append dst_cell dst_ty src_oper (atom_type cx a_src)
        | _ ->
            let (dst_cell, _) = deref_ty DEREF_none false dst_cell dst_ty in
            let bits = Il.operand_bits word_bits src_oper in
              (* 
               * FIXME: X86-ism going via a vreg; mem op= mem doesn't work and
               * IL lacks sufficient brains to cope just now.
               *)
            let src = Il.Reg (Il.next_vreg (emitter()), Il.ValTy bits) in
            let op = trans_binop binop in
              mov src src_oper;
              emit (Il.binary op dst_cell (Il.Cell dst_cell) (Il.Cell src));


  and trans_call id dst flv args =
    let init = maybe_init id "call" dst in
    let ty = lval_ty cx flv in
    let ty_params =
      match
        htab_search
          cx.ctxt_call_lval_params (lval_base_id flv)
      with
          Some params -> params
        | None -> [| |]
    in
      match simplified_ty ty with
          Ast.TY_fn _ ->
            let (dst_cell, _) = trans_lval_maybe_init init dst in
            let fn_ptr =
              trans_prepare_fn_call init cx dst_cell flv
                ty_params None args
            in
              call_code (code_of_operand fn_ptr)
        | _ -> bug () "Calling unexpected lval."


  and trans_log id a =
    match simplified_ty (atom_type cx a) with
        (* NB: If you extend this, be sure to update the
         * typechecking code in type.ml as well. *)
        Ast.TY_str -> trans_log_str a
      | Ast.TY_int | Ast.TY_uint | Ast.TY_bool
      | Ast.TY_char | Ast.TY_mach (TY_u8)
      | Ast.TY_mach (TY_u16) | Ast.TY_mach (TY_u32)
      | Ast.TY_mach (TY_i8) | Ast.TY_mach (TY_i16)
      | Ast.TY_mach (TY_i32) ->
          trans_log_int a
      | _ -> unimpl (Some id) "logging type"

  and trans_while (id:node_id) (sw:Ast.stmt_while) : unit =
    let (head_stmts, head_expr) = sw.Ast.while_lval in
    let fwd_jmp = mark () in
      emit (Il.jmp Il.JMP Il.CodeNone);
      let block_begin = mark () in
        Stack.push (Stack.create()) simple_break_jumps;
        trans_block sw.Ast.while_body;
        patch fwd_jmp;
        Array.iter trans_stmt head_stmts;
        check_interrupt_flag ();
        let flag = next_vreg_cell (Il.ValTy Il.Bits8) in
          mov flag imm_true;
          let true_jmps = trans_cond false head_expr in
            mov flag imm_false;
            List.iter patch true_jmps;
            begin
              begin
                match htab_search cx.ctxt_while_header_slots id with
                    None -> ()
                  | Some slots ->
                      let depth = get_stmt_depth cx id in
                        List.iter (drop_slot_by_id depth) slots
              end;
              let back_jmps =
                trans_compare_simple Il.JE (Il.Cell flag) imm_true
              in
                List.iter (fun j -> patch_existing j block_begin) back_jmps;
        end;
        Stack.iter patch (Stack.pop simple_break_jumps);


  and trans_stmt_full (stmt:Ast.stmt) : unit =
    match stmt.node with

        Ast.STMT_log a ->
          trans_log stmt.id a

      | Ast.STMT_check_expr e ->
          trans_check_expr stmt.id e

      | Ast.STMT_yield ->
          trans_yield ()

      | Ast.STMT_fail ->
          trans_fail ()

      | Ast.STMT_join task ->
          trans_join task

      | Ast.STMT_send (chan,src) ->
          trans_send chan src

      | Ast.STMT_spawn (dst, domain, name, plv, args) ->
          trans_spawn (maybe_init stmt.id "spawn" dst) dst
            domain name plv args

      | Ast.STMT_recv (dst, chan) ->
          trans_recv (maybe_init stmt.id "recv" dst) dst chan

      | Ast.STMT_copy (dst, e_src) ->
          trans_copy (maybe_init stmt.id "copy" dst) dst e_src

      | Ast.STMT_copy_binop (dst, binop, a_src) ->
          trans_copy_binop dst binop a_src

      | Ast.STMT_call (dst, flv, args) ->
          trans_call stmt.id dst flv args

      | Ast.STMT_bind (dst, flv, args) ->
          begin
            let init = maybe_init stmt.id "bind" dst in
              match lval_ty cx flv with
                  Ast.TY_fn (tsig, _) ->
                    trans_bind_fn
                      init (call_ctrl flv) stmt.id dst flv tsig args
                | _ -> bug () "Binding unexpected lval."
          end

      | Ast.STMT_new_rec (dst, atab, base) ->
          let init = maybe_init stmt.id "new rec" dst in
          let (dst_cell, dst_ty) = trans_lval_maybe_init init dst in
          let (trec, dst_tys) =
            match dst_ty with
                Ast.TY_rec trec -> (trec, Array.map snd trec)
              | _ ->
                  bugi cx stmt.id
                    "non-rec destination type in stmt_new_rec"
          in
            begin
              drop_existing_if_not_init init dst_cell dst_ty;
              match base with
                  None ->
                    let atoms = Array.map (fun (_, _, atom) -> atom) atab in
                      trans_init_structural_from_atoms
                        dst_cell dst_tys atoms
                | Some base_lval ->
                    trans_new_rec_update
                      dst_cell dst_tys trec atab base_lval
            end

      | Ast.STMT_new_tup (dst, elems) ->
          let init = maybe_init stmt.id "new tup" dst in
          let (dst_cell, dst_ty) = trans_lval_maybe_init init dst in
          let dst_tys =
            match dst_ty with
                Ast.TY_tup ttup -> ttup
              | _ ->
                  bugi cx stmt.id
                    "non-tup destination type in stmt_new_tup"
          in
          let atoms = Array.map snd elems in
            drop_existing_if_not_init init dst_cell dst_ty;
            trans_init_structural_from_atoms dst_cell dst_tys atoms


      | Ast.STMT_new_str (dst, s) ->
          let init = maybe_init stmt.id "new str" dst in
            trans_new_str init dst s stmt.id

      | Ast.STMT_new_vec (dst, _, atoms) ->
          let init = maybe_init stmt.id "new vec" dst in
            trans_new_vec init dst atoms

      | Ast.STMT_new_port dst ->
          let init = maybe_init stmt.id "new port" dst in
            trans_new_port init dst

      | Ast.STMT_new_chan (dst, port) ->
          let init = maybe_init stmt.id "new chan" dst in
          begin
            match port with
                None ->
                  let (dst_cell, _) =
                    trans_lval_maybe_init init dst
                  in
                    mov dst_cell imm_false
              | Some p ->
                  trans_new_chan init dst p
          end

      | Ast.STMT_new_box (dst, _, src) ->
          let init = maybe_init stmt.id "new box" dst in
            trans_new_box init dst src

      | Ast.STMT_block block ->
          trans_block block

      | Ast.STMT_while sw ->
          trans_while stmt.id sw

      | Ast.STMT_if si ->
          let skip_thn_jmps = trans_cond true si.Ast.if_test in
            trans_block si.Ast.if_then;
            begin
              match si.Ast.if_else with
                  None -> List.iter patch skip_thn_jmps
                | Some els ->
                    let skip_els_jmp = mark () in
                      begin
                        emit (Il.jmp Il.JMP Il.CodeNone);
                        List.iter patch skip_thn_jmps;
                        trans_block els;
                        patch skip_els_jmp
                      end
            end

      | Ast.STMT_check (preds, calls) ->
          Array.iteri
            (fun i (fn, args) -> trans_call_pred_and_check preds.(i) fn args)
            calls

      | Ast.STMT_ret atom_opt ->
          if get_stmt_depth cx stmt.id > 0
          then unimpl (Some stmt.id) "ret within iterator-block";
          begin
            match atom_opt with
                None -> ()
              | Some at -> trans_set_outptr at
          end;
          drop_slots_at_curr_stmt();
          Stack.push (mark()) (Stack.top epilogue_jumps);
          emit (Il.jmp Il.JMP Il.CodeNone)

      | Ast.STMT_be (flv, args) ->
          let ty_params =
            match htab_search cx.ctxt_call_lval_params (lval_base_id flv) with
                Some params -> params
              | None -> [| |]
            in
          let (dst_cell, _) = get_current_output_cell_and_slot () in
            trans_be_fn cx dst_cell flv ty_params args

      | Ast.STMT_break ->
          if get_stmt_depth cx stmt.id > 0
          then unimpl (Some stmt.id) "break within iterator-block";
          drop_slots_at_curr_stmt();
          Stack.push (mark()) (Stack.top simple_break_jumps);
          emit (Il.jmp Il.JMP Il.CodeNone);

      | Ast.STMT_put atom_opt ->
          trans_put atom_opt

      | Ast.STMT_alt_tag stmt_alt_tag -> trans_alt_tag stmt_alt_tag

      | Ast.STMT_decl _ -> ()

      | Ast.STMT_for fo ->
          trans_for_loop fo

      | Ast.STMT_for_each fe ->
          trans_for_each_loop stmt.id fe

      | _ -> bugi cx stmt.id "unhandled form of statement in trans_stmt %a"
          Ast.sprintf_stmt stmt

  and capture_emitted_quads (fix:fixup) (node:node_id) : unit =
    let e = emitter() in
    let n_vregs = Il.num_vregs e in
    let quads = emitted_quads e in
    let name = path_name () in
    let f =
      if Stack.is_empty curr_file
      then bugi cx node "missing file scope when capturing quads."
      else Stack.top curr_file
    in
    let item_code = Hashtbl.find cx.ctxt_file_code f in
      begin
        iflog (fun _ ->
                 log cx "capturing quads for item #%d" (int_of_node node);
                 annotate_quads name);
        let vr_s =
          match htab_search cx.ctxt_spill_fixups node with
              None -> (assert (n_vregs = 0); None)
            | Some spill -> Some (n_vregs, spill)
        in
        let code = { code_fixup = fix;
                     code_quads = quads;
                     code_vregs_and_spill = vr_s; }
        in
          htab_put item_code node code;
          htab_put cx.ctxt_all_item_code node code
      end

  and get_frame_glue_fns (fnid:node_id) : Il.operand =
    let n_ty_params = n_item_ty_params cx fnid in
    let get_frame_glue glue inner =
      get_mem_glue glue
        begin
          (* `mem` here is a pointer to the frame we are marking, dropping,
             or relocing, etc. *)
          fun mem ->
            iter_frame_and_arg_slots cx fnid
              begin
                fun key slot_id slot ->
                  match htab_search cx.ctxt_slot_offsets slot_id with
                      Some off when not (slot_is_obj_state cx slot_id) ->
                        let referent_type = slot_id_referent_type slot_id in
                          (*
                           * This might look as though we're always taking the
                           * pointer-to-frame and giving it the type of the
                           * frame/arg of interest, but this is because our
                           * deref_off a few lines later takes the referent
                           * type of the given poiinter (`st`) as the referent
                           * type of the mem-offset-from-the-given-pointer
                           * that it returns.
                           *)
                        let fp_cell = rty_ptr_at mem referent_type in
                        let (fp, st) = force_to_reg (Il.Cell fp_cell) in
                        let ty_params =
                          get_ty_params_of_frame fnid fp n_ty_params
                        in
                        let slot_cell =
                          deref_off_sz ty_params (Il.Reg (fp,st)) off
                        in
                          inner key slot_id ty_params slot slot_cell
                    | _ -> ()
              end
        end
    in
    let frame_has_aliases =
      let r = ref false in
        iter_frame_and_arg_slots cx fnid
          begin
            fun _ _ slot ->
              match slot.Ast.slot_mode with
                  Ast.MODE_alias -> r := true
                | _ -> ()
          end;
        !r
    in
    let frame_points_to_heap =
      let r = ref false in
        iter_frame_and_arg_slots cx fnid
          begin
            fun _ slot_id _ ->
              if type_points_to_heap cx (slot_ty (get_slot cx slot_id))
              then r := true
          end;
        !r
    in
    let null_word = Asm.WORD (word_ty_mach, Asm.IMM 0L) in

    trans_crate_rel_data_operand
      (DATA_frame_glue_fns fnid)
      begin
        fun _ ->
          let mark_frame_word =
            if frame_points_to_heap
            then
              crate_rel_word
                begin
                  get_frame_glue (GLUE_mark_frame fnid)
                    begin
                      fun _ _ ty_params slot slot_cell ->
                        mark_slot ty_params slot_cell slot
                    end
                end
            else
              null_word
          in

          let drop_frame_word =
            if frame_points_to_heap
            then
              crate_rel_word
                begin
                  get_frame_glue (GLUE_drop_frame fnid)
                    begin
                      fun _ _ ty_params slot slot_cell ->
                        drop_slot ty_params slot_cell slot
                    end
                end
            else
              null_word
          in

          let reloc_frame_word =
            if frame_has_aliases
            then
              crate_rel_word
                begin
                  get_frame_glue (GLUE_reloc_frame fnid)
                    begin
                      fun _ _ _ _ _ ->
                        ()
                    end
                end
            else
              null_word
          in
            Asm.SEQ [|
              (* 
               * NB: this must match the struct-offsets given in ABI
               * & rust runtime library.
               *)
              mark_frame_word;
              drop_frame_word;
              reloc_frame_word;
            |]
      end
  in

  let trans_frame_entry
      (fnid:node_id)
      (obj_fn:bool)
      (yield_check:bool)
      : unit =
    let framesz = get_framesz cx fnid in
    let callsz = get_callsz cx fnid in
      Stack.push (Stack.create()) epilogue_jumps;
      push_new_emitter_with_vregs (Some fnid);
      iflog (fun _ -> annotate "prologue");
      iflog (fun _ -> annotate (Printf.sprintf
                                  "framesz %s"
                                  (string_of_size framesz)));
      iflog (fun _ -> annotate (Printf.sprintf
                                  "callsz %s"
                                  (string_of_size callsz)));
      abi.Abi.abi_emit_fn_prologue
        (emitter()) framesz callsz nabi_rust
        (upcall_fixup "upcall_grow_task") obj_fn
        cx.ctxt_sess.Session.sess_minimal;

      write_frame_info_ptrs (Some fnid);
      if yield_check
      then check_interrupt_flag ();
      iflog (fun _ -> annotate "finished prologue");
  in

  let trans_frame_exit (fnid:node_id) (drop_args:bool) : unit =
    Stack.iter patch (Stack.pop epilogue_jumps);
    if drop_args
    then
      begin
        iflog (fun _ -> annotate "drop args");
        iter_arg_slots cx fnid callee_drop_slot;
      end;
    iflog (fun _ -> annotate "epilogue");
    abi.Abi.abi_emit_fn_epilogue (emitter());
    capture_emitted_quads (get_fn_fixup cx fnid) fnid;
    pop_emitter ()
  in

  let trans_fn
      (fnid:node_id)
      (body:Ast.block)
      (obj_fn:bool)
      : unit =
    trans_frame_entry fnid obj_fn true;
    trans_block body;
    trans_frame_exit fnid true;
  in

  let trans_obj_ctor
      (obj_id:node_id)
      (header:Ast.header_slots)
      : unit =
    trans_frame_entry obj_id false false;

    let all_args_rty = current_fn_args_rty None in
    let all_args_cell = caller_args_cell all_args_rty in
    let frame_args =
      get_element_ptr_dyn_in_current_frame
        all_args_cell Abi.calltup_elt_args
    in
    let frame_ty_params =
      get_element_ptr_dyn_in_current_frame
        all_args_cell Abi.calltup_elt_ty_params
    in

    let obj_fields_tup =
      Array.map (fun (sloti,_) -> (slot_ty sloti.node)) header
    in
    let obj_fields_ty = Ast.TY_tup obj_fields_tup in
    let obj_body_ty = Ast.TY_tup [| Ast.TY_type; obj_fields_ty |] in
    let box_ptr_ty = Ast.TY_box obj_body_ty in
    let box_ptr_rty = referent_type cx box_ptr_ty in
    let box_malloc_sz = box_allocation_size box_ptr_ty in

    let ctor_ty = Hashtbl.find cx.ctxt_all_item_types obj_id in
    let obj_ty =
      slot_ty (fst (need_ty_fn ctor_ty)).Ast.sig_output_slot
    in

    let vtbl_ptr = get_obj_vtbl obj_id in
    let _ =
      iflog (fun _ -> annotate "calculate vtbl-ptr from displacement")
    in
    let vtbl_cell = crate_rel_to_ptr vtbl_ptr Il.CodeTy in

    let _ = iflog (fun _ -> annotate "load destination obj pair ptr") in
    let dst_pair_cell = deref (ptr_at (fp_imm out_mem_disp) obj_ty) in
    let dst_pair_item_cell =
      get_element_ptr dst_pair_cell Abi.obj_field_vtbl
    in
    let dst_pair_box_cell =
      get_element_ptr dst_pair_cell Abi.obj_field_box
    in

      (* Load first cell of pair with vtbl ptr.*)
      iflog (fun _ -> annotate "mov vtbl-ptr to obj.item cell");
      mov dst_pair_item_cell (Il.Cell vtbl_cell);

      (* Load second cell of pair with pointer to fresh body tuple.*)
      iflog (fun _ -> annotate "malloc state-tuple to obj.box-ptr cell");
      trans_malloc dst_pair_box_cell box_malloc_sz zero;

      (* Copy rc, tydesc, args into the obj. *)
      let box_ptr = next_vreg_cell (need_scalar_ty box_ptr_rty) in
        iflog (fun _ -> annotate "load obj.box ptr to vreg");
        mov box_ptr (Il.Cell dst_pair_box_cell);
        let box = deref box_ptr in
        let refcnt =
          get_element_ptr_dyn_in_current_frame box
            Abi.box_rc_field_refcnt
        in
        let body =
          get_element_ptr_dyn_in_current_frame box
            Abi.box_rc_field_body
        in
        let obj_tydesc =
          get_element_ptr_dyn_in_current_frame body Abi.obj_body_elt_tydesc
        in
        let obj_fields =
          get_element_ptr_dyn_in_current_frame body Abi.obj_body_elt_fields
        in
          iflog (fun _ -> annotate "write refcnt=1 to obj box");
          mov refcnt one;
          iflog (fun _ -> annotate "write tydesc to obj body");
          mov obj_tydesc
            (Il.Cell (get_tydesc
                        (Some obj_id)
                        (Ast.TY_tup obj_fields_tup)));
          iflog (fun _ -> annotate "copy ctor args to obj body fields");
          trans_copy_tup
            frame_ty_params true
            obj_fields frame_args obj_fields_tup;
          (* We have to do something curious here: we can't drop the
           * arg slots directly as in the normal frame-exit sequence,
           * because the arg slot ids are actually given layout
           * positions inside the object state, and are at different
           * offsets within that state than within the current
           * frame. So we manually drop the argument slots here,
           * without mentioning the slot ids.
           *)
          Array.iteri
            (fun i (sloti, _) ->
               let cell =
                 get_element_ptr_dyn_in_current_frame
                   frame_args i
               in
                 drop_slot frame_ty_params cell sloti.node)
            header;
          trans_frame_exit obj_id false;
  in

  let string_of_name_component (nc:Ast.name_component) : string =
    match nc with
        Ast.COMP_ident i -> i
      | _ -> bug ()
          "Trans.string_of_name_component on non-COMP_ident"
  in


  let trans_static_name_components
      (ncs:Ast.name_component list)
      : Il.operand =
    let f nc =
      trans_crate_rel_static_string_frag (string_of_name_component nc)
    in
      trans_crate_rel_data_operand
        (DATA_name (name_of ncs))
        (fun _ -> Asm.SEQ (Array.append
                             (Array.map f (Array.of_list ncs))
                             [| Asm.WORD (word_ty_mach, Asm.IMM 0L) |]))
  in

  let trans_required_fn (fnid:node_id) (blockid:node_id option) : unit =
    trans_frame_entry fnid false false;
    begin
      match blockid with
          None -> ()
        | Some blockid ->
            emit (Il.Enter (Hashtbl.find cx.ctxt_block_fixups blockid));
    end;
    let (ilib, conv) = Hashtbl.find cx.ctxt_required_items fnid in
    let lib_num =
      htab_search_or_add cx.ctxt_required_lib_num ilib
        (fun _ -> Hashtbl.length cx.ctxt_required_lib_num)
    in
    let f = next_vreg_cell (Il.AddrTy (Il.CodeTy)) in
    let n_ty_params = n_item_ty_params cx fnid in
    let args_rty = direct_call_args_referent_type cx fnid in
    let caller_args_cell = caller_args_cell args_rty in
      begin
        match ilib with
            REQUIRED_LIB_rust ls ->
              begin
                let c_sym_num =
                  htab_search_or_add cx.ctxt_required_c_sym_num
                    (ilib, "rust_crate")
                    (fun _ -> Hashtbl.length cx.ctxt_required_c_sym_num)
                in
                let rust_sym_num =
                  htab_search_or_add cx.ctxt_required_rust_sym_num fnid
                    (fun _ -> Hashtbl.length cx.ctxt_required_rust_sym_num)
                in
                let path_elts = stk_elts_from_bot cx.ctxt_curr_path in
                let _ =
                  assert (ls.required_prefix < (List.length path_elts))
                in
                let relative_path_elts =
                  list_drop ls.required_prefix path_elts
                in
                let libstr = trans_static_string ls.required_libname in
                let relpath =
                  trans_static_name_components relative_path_elts
                in
                  trans_upcall "upcall_require_rust_sym" f
                    [| Il.Cell (curr_crate_ptr());
                       imm (Int64.of_int lib_num);
                       imm (Int64.of_int c_sym_num);
                       imm (Int64.of_int rust_sym_num);
                       libstr;
                       relpath |];

                  trans_copy_forward_args args_rty;

                  call_code (code_of_operand (Il.Cell f));
              end

          | REQUIRED_LIB_c ls ->
              begin
                let c_sym_str =
                  match htab_search cx.ctxt_required_syms fnid with
                      Some s -> s
                    | None ->
                        string_of_name_component
                          (Stack.top cx.ctxt_curr_path)
                in
                let c_sym_num =
                  (* FIXME: permit remapping symbol names to handle
                   * mangled variants.
                   *)
                  htab_search_or_add cx.ctxt_required_c_sym_num
                    (ilib, c_sym_str)
                    (fun _ -> Hashtbl.length cx.ctxt_required_c_sym_num)
                in
                let libstr = trans_static_string ls.required_libname in
                let symstr = trans_static_string c_sym_str in
                let check_rty_sz rty =
                  let sz = force_sz (Il.referent_ty_size word_bits rty) in
                    if sz = 0L || sz = word_sz
                    then ()
                    else bug () "bad arg or ret cell size for native require"
                in
                let out =
                  get_element_ptr caller_args_cell Abi.calltup_elt_out_ptr
                in
                let _ = check_rty_sz (pointee_type out) in
                let args =
                  let ty_params_cell =
                    get_element_ptr caller_args_cell Abi.calltup_elt_ty_params
                  in
                  let args_cell =
                    get_element_ptr caller_args_cell Abi.calltup_elt_args
                  in
                  let n_args =
                    match args_cell with
                        Il.Mem (_, Il.StructTy elts) -> Array.length elts
                      | _ -> bug () "non-StructTy in Trans.trans_required_fn"
                  in
                  let mk_ty_param i =
                    Il.Cell (get_element_ptr ty_params_cell i)
                  in
                  let mk_arg i =
                    let arg = get_element_ptr args_cell i in
                    let _ = check_rty_sz (Il.cell_referent_ty arg) in
                      Il.Cell arg
                  in
                    Array.append
                      (Array.init n_ty_params mk_ty_param)
                      (Array.init n_args mk_arg)
                in
                let nabi = { nabi_convention = conv;
                             nabi_indirect = true }
                in
                  if conv <> CONV_rust
                  then assert (n_ty_params = 0);
                  trans_upcall "upcall_require_c_sym" f
                    [| Il.Cell (curr_crate_ptr());
                       imm (Int64.of_int lib_num);
                       imm (Int64.of_int c_sym_num);
                       libstr;
                       symstr |];

                  abi.Abi.abi_emit_native_call_in_thunk
                    (emitter())
                    (if pointee_type out = Il.NilTy then None else Some out)
                    nabi
                    (Il.Cell f)
                    args;
              end

          | _ -> bug ()
              "Trans.required_rust_fn on unexpected form of require library"
      end;
      if blockid <> None
      then emit Il.Leave;
      match ilib with
          REQUIRED_LIB_rust _ ->
            trans_frame_exit fnid false;
        | REQUIRED_LIB_c _ ->
            trans_frame_exit fnid true;
        | _ -> bug ()
            "Trans.required_rust_fn on unexpected form of require library"
  in

  let trans_tag_fn
      (n:Ast.ident)
      (tagid:node_id)
      (tag:(Ast.header_slots * opaque_id * int))
      : unit =
    trans_frame_entry tagid false false;
    trace_str cx.ctxt_sess.Session.sess_trace_tag
      ("in tag constructor " ^ n);
    let (header_tup, oid, i) = tag in
    let tinfo = Hashtbl.find cx.ctxt_all_tag_info oid in
    let (n, _, _) = Hashtbl.find tinfo.tag_nums i in
    let _ = iflog (fun _ -> log cx "tag variant: %s -> tag value #%d" n i) in
    let (dst_cell, dst_slot) = get_current_output_cell_and_slot() in
    let dst_cell = deref_slot true dst_cell dst_slot in
    let tag_cell = get_element_ptr dst_cell Abi.tag_elt_discriminant in
    let union_cell =
      get_element_ptr_dyn_in_current_frame dst_cell Abi.tag_elt_variant
    in
    let tag_body_cell = get_variant_ptr union_cell i in
    let tag_body_rty = snd (need_mem_cell tag_body_cell) in
    let ty_params = get_ty_params_of_current_frame() in
      (* A clever compiler will inline this. We are not clever. *)
      iflog (fun _ -> annotate (Printf.sprintf "write tag #%d" i));
      mov tag_cell (imm (Int64.of_int i));
      iflog (fun _ -> annotate ("copy tag-content tuple: tag_body_rty=" ^
                                  (Il.string_of_referent_ty tag_body_rty)));
      Array.iteri
        begin
          fun i (sloti, _) ->
            let slot = get_slot cx sloti.id in
            let ty = slot_ty slot in
              trans_copy_ty
                ty_params
                true
                (get_element_ptr_dyn ty_params tag_body_cell i) ty
                (deref_slot false (cell_of_block_slot sloti.id) slot) ty;
        end
        header_tup;
      trace_str cx.ctxt_sess.Session.sess_trace_tag
        ("finished tag constructor " ^ n);
      trans_frame_exit tagid true;
  in

  let trans_tag
      (n:Ast.ident)
      (tagid:node_id)
      (tag:(Ast.header_slots * opaque_id * int))
      : unit =
    let (header_tup, _, _) = tag in
      if Array.length header_tup <> 0
      then trans_tag_fn n tagid tag
  in

  let enter_file_for id =
    if Hashtbl.mem cx.ctxt_item_files id
    then Stack.push id curr_file
  in

  let leave_file_for id =
    if Hashtbl.mem cx.ctxt_item_files id
    then
      if Stack.is_empty curr_file
      then bugi cx id "Missing source file on file-scope exit."
      else ignore (Stack.pop curr_file)
  in

  let visit_defined_mod_item_pre n _ i =
    iflog (fun _ -> log cx "translating defined item #%d = %s"
             (int_of_node i.id) (path_name()));
    match i.node.Ast.decl_item with
        Ast.MOD_ITEM_fn f -> trans_fn i.id f.Ast.fn_body false
      | Ast.MOD_ITEM_tag t -> trans_tag n i.id t
      | Ast.MOD_ITEM_obj ob ->
          trans_obj_ctor i.id
            (Array.map (fun (sloti,ident) ->
                          ({sloti with node = get_slot cx sloti.id},ident))
               ob.Ast.obj_state)
      | _ -> ()
  in

  let visit_required_mod_item_pre _ _ i =
    iflog (fun _ -> log cx "translating required item #%d = %s"
             (int_of_node i.id) (path_name()));
    match i.node.Ast.decl_item with
        Ast.MOD_ITEM_fn f ->
          trans_required_fn i.id (Some f.Ast.fn_body.id)
      | Ast.MOD_ITEM_tag (hslots, _, _) ->
          if Array.length hslots = 0
          then ()
          else trans_required_fn i.id None
      | Ast.MOD_ITEM_mod _ -> ()
      | Ast.MOD_ITEM_type _ -> ()
      | _ -> unimpl (Some i.id)
          "unsupported type of require: %s" (path_name())
  in

  let visit_obj_drop_pre obj b =
    let g = GLUE_obj_drop obj.id in
    let fix =
      match htab_search cx.ctxt_glue_code g with
          Some code -> code.code_fixup
        | None -> bug () "visit_obj_drop_pre without assigned fixup"
    in
    let framesz = get_framesz cx b.id in
    let callsz = get_callsz cx b.id in
    let spill = Hashtbl.find cx.ctxt_spill_fixups b.id in
      push_new_emitter_with_vregs (Some b.id);
      iflog (fun _ -> annotate "prologue");
      abi.Abi.abi_emit_fn_prologue (emitter())
        framesz callsz nabi_rust (upcall_fixup "upcall_grow_task")
        true cx.ctxt_sess.Session.sess_minimal;
      write_frame_info_ptrs None;
      iflog (fun _ -> annotate "finished prologue");
      trans_block b;
      Hashtbl.remove cx.ctxt_glue_code g;
      trans_glue_frame_exit fix spill g;
      inner.Walk.visit_obj_drop_pre obj b
  in

  let visit_defined_obj_fn_pre _ _ fn =
    trans_fn fn.id fn.node.Ast.fn_body true
  in

  let visit_required_obj_fn_pre _ _ _ =
    ()
  in

  let visit_obj_fn_pre obj ident fn =
    enter_file_for fn.id;
    begin
      if Hashtbl.mem cx.ctxt_required_items fn.id
      then
        visit_required_obj_fn_pre obj ident fn
      else
        visit_defined_obj_fn_pre obj ident fn;
    end;
    inner.Walk.visit_obj_fn_pre obj ident fn
  in

  let visit_mod_item_pre n p i =
    enter_file_for i.id;
    begin
      if Hashtbl.mem cx.ctxt_required_items i.id
      then
        visit_required_mod_item_pre n p i
      else
        visit_defined_mod_item_pre n p i
    end;
    inner.Walk.visit_mod_item_pre n p i
  in

  let visit_mod_item_post n p i =
    inner.Walk.visit_mod_item_post n p i;
    leave_file_for i.id
  in

  let visit_obj_fn_post obj ident fn =
    inner.Walk.visit_obj_fn_post obj ident fn;
    leave_file_for fn.id
  in

  let visit_crate_pre crate =
    enter_file_for crate.id;
    inner.Walk.visit_crate_pre crate
  in

  let report_quads _ =
    if cx.ctxt_sess.Session.sess_report_quads
    then
      begin
        let cumulative = ref 0 in
          Printf.fprintf stdout "quads:\n\n";
          Array.iter
            begin
              fun name ->
                let t = Hashtbl.find quad_categories name in
                  Printf.fprintf stdout "%20s: %d\n" name (!t);
                  cumulative := (!cumulative) + (!t)
            end
            (sorted_htab_keys quad_categories);
          Printf.fprintf stdout "\n%20s: %d\n" "cumulative" (!cumulative)
      end
  in

  let visit_crate_post crate =

    inner.Walk.visit_crate_post crate;

    let emit_aux_global_glue cx glue fix fn =
      let glue_name = glue_str cx glue in
        push_new_emitter_without_vregs None;
        let e = emitter() in
          fn e;
          iflog (fun _ -> annotate_quads glue_name);
          if (Il.num_vregs e) != 0
          then bug () "%s uses nonzero vregs" glue_name;
          pop_emitter();
          let code =
            { code_fixup = fix;
              code_quads = emitted_quads e;
              code_vregs_and_spill = None; }
          in
            htab_put cx.ctxt_glue_code glue code
    in

    let tab_sz htab =
      Asm.WORD (word_ty_mach, Asm.IMM (Int64.of_int (Hashtbl.length htab)))
    in

    let crate_data =
      (cx.ctxt_crate_fixup,
       Asm.DEF
         (cx.ctxt_crate_fixup,
          Asm.SEQ [|
            (* 
             * NB: this must match the rust_crate structure
             * in the rust runtime library.
             *)
            crate_rel_word cx.ctxt_image_base_fixup;
            Asm.WORD (word_ty_mach, Asm.M_POS cx.ctxt_crate_fixup);

            crate_rel_word cx.ctxt_debug_abbrev_fixup;
            Asm.WORD (word_ty_mach, Asm.M_SZ cx.ctxt_debug_abbrev_fixup);

            crate_rel_word cx.ctxt_debug_info_fixup;
            Asm.WORD (word_ty_mach, Asm.M_SZ cx.ctxt_debug_info_fixup);

            crate_rel_word cx.ctxt_activate_fixup;
            crate_rel_word cx.ctxt_yield_fixup;
            crate_rel_word cx.ctxt_unwind_fixup;
            crate_rel_word cx.ctxt_gc_fixup;
            crate_rel_word cx.ctxt_exit_task_fixup;

            tab_sz cx.ctxt_required_rust_sym_num;
            tab_sz cx.ctxt_required_c_sym_num;
            tab_sz cx.ctxt_required_lib_num;
          |]))
    in

      (* Emit additional glue we didn't do elsewhere. *)
      emit_aux_global_glue cx GLUE_activate
        cx.ctxt_activate_fixup
        abi.Abi.abi_activate;

      emit_aux_global_glue cx GLUE_yield
        cx.ctxt_yield_fixup
        abi.Abi.abi_yield;

      emit_aux_global_glue cx GLUE_unwind
        cx.ctxt_unwind_fixup
        (fun e -> abi.Abi.abi_unwind
           e nabi_rust (upcall_fixup "upcall_exit"));

      emit_aux_global_glue cx GLUE_gc
        cx.ctxt_gc_fixup
        abi.Abi.abi_gc;

      ignore (get_exit_task_glue ());

      begin
        match abi.Abi.abi_get_next_pc_thunk with
            None -> ()
          | Some (_, fix, fn) ->
              emit_aux_global_glue cx GLUE_get_next_pc fix fn
      end;

      htab_put cx.ctxt_data
        DATA_crate crate_data;

      provide_existing_native cx SEG_data "rust_crate" cx.ctxt_crate_fixup;

      leave_file_for crate.id;

      report_quads()
  in

    { inner with
        Walk.visit_crate_pre = visit_crate_pre;
        Walk.visit_crate_post = visit_crate_post;
        Walk.visit_mod_item_pre = visit_mod_item_pre;
        Walk.visit_mod_item_post = visit_mod_item_post;
        Walk.visit_obj_fn_pre = visit_obj_fn_pre;
        Walk.visit_obj_fn_post = visit_obj_fn_post;
        Walk.visit_obj_drop_pre = visit_obj_drop_pre;
    }
;;


let fixup_assigning_visitor
    (cx:ctxt)
    (inner:Walk.visitor)
    : Walk.visitor =

  let path_name (_:unit) : string =
    Fmt.fmt_to_str Ast.fmt_name (path_to_name cx.ctxt_curr_path)
  in

  let enter_file_for id =
    if Hashtbl.mem cx.ctxt_item_files id
    then
      begin
        let name =
          if Stack.is_empty cx.ctxt_curr_path
          then "crate root"
          else path_name()
        in
        htab_put cx.ctxt_file_fixups id (new_fixup name);
        if not (Hashtbl.mem cx.ctxt_file_code id)
        then htab_put cx.ctxt_file_code id (Hashtbl.create 0);
      end
  in

  let visit_mod_item_pre n p i =
    enter_file_for i.id;
    begin
      match i.node.Ast.decl_item with

          Ast.MOD_ITEM_tag _ ->
            htab_put cx.ctxt_fn_fixups i.id
              (new_fixup (path_name()));

        | Ast.MOD_ITEM_fn _ ->
            begin
              let path = path_to_name cx.ctxt_curr_path in
              let fixup =
                if (not cx.ctxt_sess.Session.sess_library_mode)
                  && (Some path) = cx.ctxt_main_name
                then
                  match cx.ctxt_main_fn_fixup with
                      None -> bug () "missing main fixup in trans"
                    | Some fix -> fix
                else
                  new_fixup (path_name())
              in
                htab_put cx.ctxt_fn_fixups i.id fixup;
            end

        | Ast.MOD_ITEM_obj _ ->
            htab_put cx.ctxt_fn_fixups i.id
              (new_fixup (path_name()));

        | _ -> ()
    end;
    inner.Walk.visit_mod_item_pre n p i
  in

  let visit_obj_fn_pre obj ident fn =
    htab_put cx.ctxt_fn_fixups fn.id
      (new_fixup (path_name()));
    inner.Walk.visit_obj_fn_pre obj ident fn
  in

  let visit_obj_drop_pre obj b =
    let g = GLUE_obj_drop obj.id in
    let fix = new_fixup (path_name()) in
    let tmp_code = { code_fixup = fix;
                     code_quads = [| |];
                     code_vregs_and_spill = None; } in
      htab_put cx.ctxt_glue_code g tmp_code;
      inner.Walk.visit_obj_drop_pre obj b
  in

  let visit_block_pre b =
    htab_put cx.ctxt_block_fixups b.id
      (new_fixup ("lexical block in " ^ (path_name())));
    inner.Walk.visit_block_pre b
  in

  let visit_crate_pre c =
    enter_file_for c.id;
    inner.Walk.visit_crate_pre c;
  in

  { inner with
      Walk.visit_crate_pre = visit_crate_pre;
      Walk.visit_mod_item_pre = visit_mod_item_pre;
      Walk.visit_obj_fn_pre = visit_obj_fn_pre;
      Walk.visit_obj_drop_pre = visit_obj_drop_pre;
      Walk.visit_block_pre = visit_block_pre; }


let process_crate
    (cx:ctxt)
    (crate:Ast.crate)
    : unit =
  let passes =
    [|
      (unreferenced_required_item_ignoring_visitor cx
         (fixup_assigning_visitor cx Walk.empty_visitor));
      (unreferenced_required_item_ignoring_visitor cx
         (trans_visitor cx Walk.empty_visitor))
    |];
  in
    log cx "translating crate";
    begin
      match cx.ctxt_main_name with
          None -> ()
        | Some m ->
            log cx "with main fn %a"
              Ast.sprintf_name m
    end;
    run_passes cx "trans" passes
      cx.ctxt_sess.Session.sess_log_trans log crate;
;;

(*
 * Local Variables:
 * fill-column: 78;
 * indent-tabs-mode: nil
 * buffer-file-coding-system: utf-8-unix
 * compile-command: "make -k -C ../.. 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
 * End:
 *)