summaryrefslogtreecommitdiffstats
path: root/source/slang/slang-emit-c-like.cpp
blob: fbcd0dbbd6b0cf852a5e2508595aaa30713f0001 (plain)
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
// slang-emit-c-like.cpp
#include "slang-emit-c-like.h"

#include "../core/slang-writer.h"
#include "../compiler-core/slang-name.h"

#include "slang-ir-bind-existentials.h"
#include "slang-ir-dce.h"
#include "slang-ir-entry-point-uniforms.h"
#include "slang-ir-glsl-legalize.h"

#include "slang-ir-link.h"
#include "slang-ir-restructure-scoping.h"
#include "slang-ir-specialize.h"
#include "slang-ir-specialize-resources.h"
#include "slang-ir-ssa.h"
#include "slang-ir-union.h"
#include "slang-ir-util.h"
#include "slang-ir-validate.h"
#include "slang-legalize-types.h"
#include "slang-lower-to-ir.h"
#include "slang-mangle.h"

#include "slang-syntax.h"
#include "slang-type-layout.h"
#include "slang-visitor.h"

#include "slang-intrinsic-expand.h"

#include "slang-emit-source-writer.h"
#include "slang-mangled-lexer.h"
#include <assert.h>

namespace Slang {

struct CLikeSourceEmitter::ComputeEmitActionsContext
{
    IRInst*             moduleInst;
    HashSet<IRInst*>    openInsts;
    Dictionary<IRInst*, EmitAction::Level> mapInstToLevel;
    List<EmitAction>*   actions;
};

/* !!!!!!!!!!!!!!!!!!!!!!!!!!!! LocationTracker !!!!!!!!!!!!!!!!!!!!!!!!!! */

/* static */LocationTracker::Kind LocationTracker::getKindFromDecoration(IRDecoration* decoration)
{
    switch (decoration->getOp())
    {
        case kIROp_VulkanRayPayloadDecoration:          return Kind::RayPayload;
        case kIROp_VulkanCallablePayloadDecoration:     return Kind::CallablePayload;
        case kIROp_VulkanHitObjectAttributesDecoration: return Kind::HitObjectAttribute;
        default: break;
    }
    return Kind::Invalid;
}

Index LocationTracker::getValue(IRInst* inst, IRDecoration* decoration)
{
    const Kind kind = getKindFromDecoration(decoration);
    SLANG_RELEASE_ASSERT(kind != Kind::Invalid);
    if (kind == Kind::Invalid)
    {
        return -1;
    }

    return getValue(kind, inst, decoration);
}

Index LocationTracker::getValue(Kind kind, IRInst* inst, IRDecoration* decoration)
{
    if (decoration->getOperandCount() > 0)
    {
        // TODO(JS):
        // There could be a clash with the auto generated location, and the user set value/ 
        // Perhaps the implication in practice is that either all are marked or none.
        const int explicitLocation = int(getIntVal(decoration->getOperand(0)));
        if (explicitLocation >= 0)
            return UInt(explicitLocation);
    }

    auto& nextValue = m_nextValueForKind[Index(kind)];

    const Location defaultLocation{kind, nextValue};
    const Location foundLocation = m_mapIRToLocations.GetOrAddValue(inst, defaultLocation);

    // Increase if it was the default
    nextValue += Index(defaultLocation == foundLocation);

    // Has to match the kind
    return (foundLocation.kind == kind) ? foundLocation.value : -1;
}

/* !!!!!!!!!!!!!!!!!!!!!!!!!!!! CLikeSourceEmitter !!!!!!!!!!!!!!!!!!!!!!!!!! */

/* static */SourceLanguage CLikeSourceEmitter::getSourceLanguage(CodeGenTarget target)
{
    switch (target)
    {
        default:
        case CodeGenTarget::Unknown:
        case CodeGenTarget::None:
        {
            return SourceLanguage::Unknown;
        }
        case CodeGenTarget::GLSL:
        case CodeGenTarget::GLSL_Vulkan:
        case CodeGenTarget::GLSL_Vulkan_OneDesc:
        {
            return SourceLanguage::GLSL;
        }
        case CodeGenTarget::HLSL:
        {
            return SourceLanguage::HLSL;
        }
        case CodeGenTarget::PTX:
        case CodeGenTarget::SPIRV:
        case CodeGenTarget::SPIRVAssembly:
        case CodeGenTarget::DXBytecode:
        case CodeGenTarget::DXBytecodeAssembly:
        case CodeGenTarget::DXIL:
        case CodeGenTarget::DXILAssembly:
        {
            return SourceLanguage::Unknown;
        }
        case CodeGenTarget::CSource:
        {
            return SourceLanguage::C;
        }
        case CodeGenTarget::CPPSource:
        case CodeGenTarget::HostCPPSource:
        {
            return SourceLanguage::CPP;
        }
        case CodeGenTarget::CUDASource:
        {
            return SourceLanguage::CUDA;
        }
    }
}

CLikeSourceEmitter::CLikeSourceEmitter(const Desc& desc)
{
    m_writer = desc.sourceWriter;
    m_sourceLanguage = getSourceLanguage(desc.codeGenContext->getTargetFormat());
    SLANG_ASSERT(m_sourceLanguage != SourceLanguage::Unknown);

    m_target = desc.codeGenContext->getTargetFormat();
    m_codeGenContext = desc.codeGenContext;
    m_entryPointStage = desc.entryPointStage;
    m_effectiveProfile = desc.effectiveProfile;
}

SlangResult CLikeSourceEmitter::init()
{
    return SLANG_OK;
}

void CLikeSourceEmitter::emitFrontMatterImpl(TargetRequest* targetReq)
{
    SLANG_UNUSED(targetReq);
}

//
// Types
//

void CLikeSourceEmitter::emitDeclarator(DeclaratorInfo* declarator)
{
    if (!declarator) return;

    m_writer->emit(" ");

    switch (declarator->flavor)
    {
    case DeclaratorInfo::Flavor::Name:
        {
            auto nameDeclarator = (NameDeclaratorInfo*)declarator;
            m_writer->emitName(*nameDeclarator->nameAndLoc);
        }
        break;

    case DeclaratorInfo::Flavor::SizedArray:
        {
            auto arrayDeclarator = (SizedArrayDeclaratorInfo*)declarator;
            emitDeclarator(arrayDeclarator->next);
            m_writer->emit("[");
            if(auto elementCount = arrayDeclarator->elementCount)
            {
                emitVal(elementCount, getInfo(EmitOp::General));
            }
            m_writer->emit("]");
        }
        break;

    case DeclaratorInfo::Flavor::UnsizedArray:
        {
            auto arrayDeclarator = (UnsizedArrayDeclaratorInfo*)declarator;
            emitDeclarator(arrayDeclarator->next);
            m_writer->emit("[]");
        }
        break;

    case DeclaratorInfo::Flavor::Ptr:
        {
            // TODO: When there are both pointer and array declarators
            // as part of a type, paranetheses may be needed in order
            // to disambiguate between a pointer-to-array and an
            // array-of-poiners.
            //
            auto ptrDeclarator = (PtrDeclaratorInfo*)declarator;
            m_writer->emit("*");
            emitDeclarator(ptrDeclarator->next);
        }
        break;

    case DeclaratorInfo::Flavor::Ref:
        {
            auto refDeclarator = (RefDeclaratorInfo*)declarator;
            m_writer->emit("&");
            emitDeclarator(refDeclarator->next);
        }
        break;

    case DeclaratorInfo::Flavor::LiteralSizedArray:
        {
            auto arrayDeclarator = (LiteralSizedArrayDeclaratorInfo*)declarator;
            emitDeclarator(arrayDeclarator->next);
            m_writer->emit("[");
            m_writer->emit(arrayDeclarator->elementCount);
            m_writer->emit("]");
        }
        break;

    case DeclaratorInfo::Flavor::Attributed:
        {
            auto attributedDeclarator = (AttributedDeclaratorInfo*)declarator;
            auto instWithAttributes = attributedDeclarator->instWithAttributes;
            for(auto attr : instWithAttributes->getAllAttrs())
            {
                _emitPostfixTypeAttr(attr);
            }
            emitDeclarator(attributedDeclarator->next);
        }
        break;
    default:
        SLANG_DIAGNOSE_UNEXPECTED(getSink(), SourceLoc(), "unknown declarator flavor");
        break;
    }
}

void CLikeSourceEmitter::emitSimpleType(IRType* type)
{
    emitSimpleTypeImpl(type);
}

/* static */ UnownedStringSlice CLikeSourceEmitter::getDefaultBuiltinTypeName(IROp op)
{
    switch (op)
    {
        case kIROp_VoidType:    return UnownedStringSlice("void");      
        case kIROp_BoolType:    return UnownedStringSlice("bool");      

        case kIROp_Int8Type:    return UnownedStringSlice("int8_t");    
        case kIROp_Int16Type:   return UnownedStringSlice("int16_t");   
        case kIROp_IntType:     return UnownedStringSlice("int");       
        case kIROp_Int64Type:   return UnownedStringSlice("int64_t");   
        case kIROp_IntPtrType:  return UnownedStringSlice("intptr_t");

        case kIROp_UInt8Type:   return UnownedStringSlice("uint8_t");   
        case kIROp_UInt16Type:  return UnownedStringSlice("uint16_t");  
        case kIROp_UIntType:    return UnownedStringSlice("uint");     
        case kIROp_UInt64Type:  return UnownedStringSlice("uint64_t"); 
        case kIROp_UIntPtrType: return UnownedStringSlice("uintptr_t");

        case kIROp_HalfType:    return UnownedStringSlice("half");     

        case kIROp_FloatType:   return UnownedStringSlice("float");    
        case kIROp_DoubleType:  return UnownedStringSlice("double");

        case kIROp_CharType:    return UnownedStringSlice("uint8_t");
        default:                return UnownedStringSlice();
    }
}


/* static */IRNumThreadsDecoration* CLikeSourceEmitter::getComputeThreadGroupSize(IRFunc* func, Int outNumThreads[kThreadGroupAxisCount])
{
    IRNumThreadsDecoration* decor = func->findDecoration<IRNumThreadsDecoration>();
    for (int i = 0; i < 3; ++i)
    {
        outNumThreads[i] = decor ? Int(getIntVal(decor->getOperand(i))) : 1;
    }
    return decor;
}

List<IRWitnessTableEntry*> CLikeSourceEmitter::getSortedWitnessTableEntries(IRWitnessTable* witnessTable)
{
    List<IRWitnessTableEntry*> sortedWitnessTableEntries;
    auto interfaceType = cast<IRInterfaceType>(witnessTable->getConformanceType());
    auto witnessTableItems = witnessTable->getChildren();
    // Build a dictionary of witness table entries for fast lookup.
    Dictionary<IRInst*, IRWitnessTableEntry*> witnessTableEntryDictionary;
    for (auto item : witnessTableItems)
    {
        if (auto entry = as<IRWitnessTableEntry>(item))
        {
            witnessTableEntryDictionary[entry->getRequirementKey()] = entry;
        }
    }
    // Get a sorted list of entries using RequirementKeys defined in `interfaceType`.
    for (UInt i = 0; i < interfaceType->getOperandCount(); i++)
    {
        auto reqEntry = cast<IRInterfaceRequirementEntry>(interfaceType->getOperand(i));
        IRWitnessTableEntry* entry = nullptr;
        if (witnessTableEntryDictionary.TryGetValue(reqEntry->getRequirementKey(), entry))
        {
            sortedWitnessTableEntries.add(entry);
        }
        else
        {
            SLANG_UNREACHABLE("interface requirement key not found in witness table.");
        }
    }
    return sortedWitnessTableEntries;
}

void CLikeSourceEmitter::_emitPrefixTypeAttr(IRAttr* attr)
{
    SLANG_UNUSED(attr);

    // By defualt we will not emit any attributes.
    //
    // TODO: If `const` ever surfaces as a type attribute in our IR,
    // we may need to handle it here.
}

void CLikeSourceEmitter::_emitPostfixTypeAttr(IRAttr* attr)
{
    SLANG_UNUSED(attr);

    // By defualt we will not emit any attributes.
    //
    // TODO: If `const` ever surfaces as a type attribute in our IR,
    // we may need to handle it here.
}

void CLikeSourceEmitter::_emitType(IRType* type, DeclaratorInfo* declarator)
{
    switch (type->getOp())
    {
    default:
        emitSimpleType(type);
        emitDeclarator(declarator);
        break;

    case kIROp_RateQualifiedType:
        {
            auto rateQualifiedType = cast<IRRateQualifiedType>(type);
            _emitType(rateQualifiedType->getValueType(), declarator);
        }
        break;

    case kIROp_ArrayType:
        {
            auto arrayType = cast<IRArrayType>(type);
            SizedArrayDeclaratorInfo arrayDeclarator(declarator, arrayType->getElementCount());
            _emitType(arrayType->getElementType(), &arrayDeclarator);
        }
        break;

    case kIROp_UnsizedArrayType:
        {
            auto arrayType = cast<IRUnsizedArrayType>(type);
            UnsizedArrayDeclaratorInfo arrayDeclarator(declarator);
            _emitType(arrayType->getElementType(), &arrayDeclarator);
        }
        break;

    case kIROp_AttributedType:
        {
            auto attributedType = cast<IRAttributedType>(type);
            for(auto attr : attributedType->getAllAttrs())
            {
                _emitPrefixTypeAttr(attr);
            }
            AttributedDeclaratorInfo attributedDeclarator(declarator, attributedType);
            _emitType(attributedType->getBaseType(), &attributedDeclarator);
        }
        break;
    }
}

void CLikeSourceEmitter::emitWitnessTable(IRWitnessTable* witnessTable)
{
    SLANG_UNUSED(witnessTable);
}

void CLikeSourceEmitter::emitComWitnessTable(IRWitnessTable* witnessTable)
{
    auto classType = witnessTable->getConcreteType();
    for (auto ent : witnessTable->getEntries())
    {
        auto req = ent->getRequirementKey();
        auto func = as<IRFunc>(ent->getSatisfyingVal());
        if (!func)
            continue;

        auto resultType = func->getResultType();

        auto name = getName(classType) + "::" + getName(req);

        emitFuncDecorations(func);

        emitType(resultType, name);
        m_writer->emit("(");
        // Skip declaration of `this` parameter.
        auto firstParam = func->getFirstParam()->getNextParam();
        for (auto pp = firstParam; pp; pp = pp->getNextParam())
        {
            if (pp != firstParam)
                m_writer->emit(", ");

            emitSimpleFuncParamImpl(pp);
        }
        m_writer->emit(")");
        m_writer->emit("\n{\n");
        m_writer->indent();

        // emit definition for `this` param.
        m_writer->emit("auto ");
        m_writer->emit(getName(func->getFirstParam()));
        m_writer->emit(" = this;\n");

        // Need to emit the operations in the blocks of the function
        emitFunctionBody(func);

        m_writer->dedent();
        m_writer->emit("}\n\n");
    }
}

void CLikeSourceEmitter::emitInterface(IRInterfaceType* interfaceType)
{
    SLANG_UNUSED(interfaceType);
    // By default, don't emit anything for interface types.
    // This behavior is overloaded by concrete emitters.
}

void CLikeSourceEmitter::emitRTTIObject(IRRTTIObject* rttiObject)
{
    SLANG_UNUSED(rttiObject);
    // Ignore rtti object by default.
    // This is only used in targets that support dynamic dispatching.
}


void CLikeSourceEmitter::emitTypeImpl(IRType* type, const StringSliceLoc* nameAndLoc)
{
    if (nameAndLoc)
    {
        // We advance here, such that if there is a #line directive to output it will
        // be done so before the type name appears.
        m_writer->advanceToSourceLocationIfValid(nameAndLoc->loc);

        NameDeclaratorInfo nameDeclarator(nameAndLoc);
        _emitType(type, &nameDeclarator);
    }
    else
    {
        _emitType(type, nullptr);
    }
}

void CLikeSourceEmitter::emitType(IRType* type, Name* name)
{
    SLANG_ASSERT(name);
    StringSliceLoc nameAndLoc(name->text.getUnownedSlice());
    emitType(type, &nameAndLoc);
}

void CLikeSourceEmitter::emitType(IRType* type, const String& name)
{
    StringSliceLoc nameAndLoc(name.getUnownedSlice());
    emitType(type, &nameAndLoc);
}

void CLikeSourceEmitter::emitType(IRType* type)
{
    emitType(type, (StringSliceLoc*)nullptr);
}

void CLikeSourceEmitter::emitType(IRType* type, Name* name, SourceLoc const& nameLoc)
{
    SLANG_ASSERT(name);

    StringSliceLoc nameAndLoc;
    nameAndLoc.loc = nameLoc;
    nameAndLoc.name = name->text.getUnownedSlice();
    
    emitType(type, &nameAndLoc);
}

void CLikeSourceEmitter::emitType(IRType* type, NameLoc const& nameAndLoc)
{
    emitType(type, nameAndLoc.name, nameAndLoc.loc);
}


void CLikeSourceEmitter::emitLivenessImpl(IRInst* inst)
{
    
    auto liveMarker = as<IRLiveRangeMarker>(inst);
    if (!liveMarker)
    {
        return;
    }

    IRInst* referenced = liveMarker->getReferenced();
    SLANG_ASSERT(referenced);

    UnownedStringSlice text;
    switch (inst->getOp())
    {
        case kIROp_LiveRangeStart:
        {
            text = UnownedStringSlice::fromLiteral("SLANG_LIVE_START");
            break;
        }
        case kIROp_LiveRangeEnd:
        {
            text = UnownedStringSlice::fromLiteral("SLANG_LIVE_END");
            break;
        }
        default: break;
    }

    m_writer->emit(text);
    m_writer->emit("(");

    emitOperand(referenced, getInfo(EmitOp::General));

    m_writer->emit(")\n");
}

//
// Expressions
//

bool CLikeSourceEmitter::maybeEmitParens(EmitOpInfo& outerPrec, const EmitOpInfo& prec)
{
    bool needParens = (prec.leftPrecedence <= outerPrec.leftPrecedence)
        || (prec.rightPrecedence <= outerPrec.rightPrecedence);

    if (needParens)
    {
        m_writer->emit("(");

        outerPrec = getInfo(EmitOp::None);
    }
    return needParens;
}

void CLikeSourceEmitter::maybeCloseParens(bool needClose)
{
    if(needClose) m_writer->emit(")");
}

void CLikeSourceEmitter::emitStringLiteral(String const& value)
{
    m_writer->emit("\"");
    for (auto c : value)
    {
        // TODO: This needs a more complete implementation,
        // especially if we want to support Unicode.

        char buffer[] = { c, 0 };
        switch (c)
        {
        default:
            m_writer->emit(buffer);
            break;

        case '\"': m_writer->emit("\\\"");
        case '\'': m_writer->emit("\\\'");
        case '\\': m_writer->emit("\\\\");
        case '\n': m_writer->emit("\\n");
        case '\r': m_writer->emit("\\r");
        case '\t': m_writer->emit("\\t");
        }
    }
    m_writer->emit("\"");
}

void CLikeSourceEmitter::emitVal(IRInst* val, EmitOpInfo const& outerPrec)
{
    if(auto type = as<IRType>(val))
    {
        emitType(type);
    }
    else
    {
        emitInstExpr(val, outerPrec);
    }
}

UInt CLikeSourceEmitter::getBindingOffset(EmitVarChain* chain, LayoutResourceKind kind)
{
    UInt offset = 0;
    for(auto cc = chain; cc; cc = cc->next)
    {
        if(auto resInfo = cc->varLayout->findOffsetAttr(kind))
        {
            offset += resInfo->getOffset();
        }
    }
    return offset;
}

UInt CLikeSourceEmitter::getBindingSpace(EmitVarChain* chain, LayoutResourceKind kind)
{
    UInt space = 0;
    for(auto cc = chain; cc; cc = cc->next)
    {
        auto varLayout = cc->varLayout;
        if(auto resInfo = varLayout->findOffsetAttr(kind))
        {
            space += resInfo->getSpace();
        }
        if(auto resInfo = varLayout->findOffsetAttr(LayoutResourceKind::RegisterSpace))
        {
            space += resInfo->getOffset();
        }
    }
    return space;
}

UInt CLikeSourceEmitter::allocateUniqueID()
{
    return m_uniqueIDCounter++;
}

// IR-level emit logic

UInt CLikeSourceEmitter::getID(IRInst* value)
{
    auto& mapIRValueToID = m_mapIRValueToID;

    UInt id = 0;
    if (mapIRValueToID.TryGetValue(value, id))
        return id;

    id = allocateUniqueID();
    mapIRValueToID.Add(value, id);
    return id;
}

void CLikeSourceEmitter::appendScrubbedName(const UnownedStringSlice& name, StringBuilder& out)
{
    // We will use a plain `U` as a dummy character to insert
    // whenever we need to insert things to make a string into
    // valid name.
    //
    const char dummyChar = 'U';

    // Special case a name that is the empty string, just in case.
    if(name.getLength() == 0)
    {
        out.appendChar(dummyChar);
        return;
    }
     
    // Otherwise, we are going to walk over the name byte by byte
    // and write some legal characters to the output as we go.
    
    if(getSourceLanguage() == SourceLanguage::GLSL)
    {
        // GLSL reserves all names that start with `gl_`,
        // so if we are in danger of collision, then make
        // our name start with a dummy character instead.
        if(name.startsWith("gl_"))
        {
            out.appendChar(dummyChar);
        }
    }

    // We will also detect user-defined names that
    // might overlap with our convention for mangled names,
    // to avoid an possible collision.
    if(name.startsWith("_S"))
    {
        out.appendChar(dummyChar);
    }

    // TODO: This is where we might want to consult
    // a dictionary of reserved words for the chosen target
    //
    //  if(isReservedWord(name)) { sb.Append(dummyChar); }
    //

    // We need to track the previous byte in
    // order to detect consecutive underscores for GLSL.
    int prevChar = -1;

    for(auto c : name)
    {
        // We will treat a dot character or any path separator
        // just like an underscore for the purposes of producing
        // a scrubbed name, so that we translate `SomeType.someMethod`
        // into `SomeType_someMethod`. This increases the readability
        // of output code when the input used lots of nesting of
        // code under types/namespaces/etc.
        //
        // By handling this case at the top of this loop, we
        // ensure that a `.`-turned-`_` is handled just like
        // a `_` in the original name, and will be properly
        // scrubbed for GLSL output.
        //
        switch(c)
        {
        default:
            break;

        case '.':
        case '\\':
        case '/':
            c = '_';
            break;
        }

        if(((c >= 'a') && (c <= 'z'))
            || ((c >= 'A') && (c <= 'Z')))
        {
            // Ordinary ASCII alphabetic characters are assumed
            // to always be okay.
        }
        else if((c >= '0') && (c <= '9'))
        {
            // We don't want to allow a digit as the first
            // byte in a name, since the result wouldn't
            // be a valid identifier in many target languages.
            if(prevChar == -1)
            {
                out.appendChar(dummyChar);
            }
        }
        else if(c == '_')
        {
            // We will collapse any consecutive sequence of `_`
            // characters into a single one (this means that
            // some names that were unique in the original
            // code might not resolve to unique names after
            // scrubbing, but that was true in general).

            if(prevChar == '_')
            {
                // Skip this underscore, so we don't output
                // more than one in a row.
                continue;
            }
        }
        else
        {
            // If we run into a character that wouldn't normally
            // be allowed in an identifier, we need to translate
            // it into something that *is* valid.
            //
            // Our solution for now will be very clumsy: we will
            // emit `x` and then the hexadecimal version of
            // the byte we were given.
            out.appendChar('x');
            out.append(uint32_t((unsigned char) c), 16);

            // We don't want to apply the default handling below,
            // so skip to the top of the loop now.
            prevChar = c;
            continue;
        }

        out.appendChar(c);
        prevChar = c;
    }

    if (getSourceLanguage() == SourceLanguage::GLSL)
    {
        // It looks like the default glslang name limit is 1024, but let's go a little less so there is some wiggle room
        const Index maxTokenLength = 1024 - 8;

        const Index length = out.getLength();

        if (length > maxTokenLength)
        {
            // We are going to output with a prefix and a hash of the full name
            const HashCode64 hash = getStableHashCode64(out.getBuffer(), length);
            // Two hex chars per byte
            const Index hashSize = sizeof(hash) * 2; 

            // Work out a size that is within range taking into account the hash size and extra chars
            Index reducedBaseLength = maxTokenLength - hashSize - 1;
            // If it has a trailing _ remove it.
            // We know because of scrubbing there can only be single _
            reducedBaseLength -= Index(out[reducedBaseLength - 1] == '_');

            // Reduce the length
            out.reduceLength(reducedBaseLength);
            // Let's add a _ to separate from the rest of the name
            out.appendChar('_');
            // Append the hash in hex
            out.append(uint64_t(hash), 16);

            SLANG_ASSERT(out.getLength() <= maxTokenLength);
        }
    }
}

String CLikeSourceEmitter::generateEntryPointNameImpl(IREntryPointDecoration* entryPointDecor)
{
    return entryPointDecor->getName()->getStringSlice();
}

String CLikeSourceEmitter::_generateUniqueName(const UnownedStringSlice& name)
{
    //
    // We need to be careful that the name follows the rules of the target language,
    // so there is a "scrubbing" step that needs to be applied here.
    //
    // We also need to make sure that the name won't collide with other declarations
    // that might have the same name hint applied, so we will still unique
    // them by appending the numeric ID of the instruction.
    //
    // TODO: Find cases where we can drop the suffix safely.
    //
    // TODO: When we start having to handle symbols with external linkage for
    // things like DXIL libraries, we will need to *not* use the friendly
    // names for stuff that should be link-able.
    //
    // The name we output will basically be:
    //
    //      <name>_<uniqueID>
    //
    // Except that we will "scrub" the name first,
    // and we will omit the underscore if the (scrubbed)
    // name hint already ends with one.
    
    StringBuilder sb;

    appendScrubbedName(name, sb);

    // Avoid introducing a double underscore
    if (!sb.endsWith("_"))
    {
        sb.append("_");
    }

    String key = sb.ProduceString();
    
    UInt& countRef = m_uniqueNameCounters.GetOrAddValue(key, 0);
    const UInt count = countRef;
    countRef = count + 1;

    sb.append(Int32(count));
    return sb.ProduceString();
}

String CLikeSourceEmitter::generateName(IRInst* inst)
{
    // If the instruction names something
    // that should be emitted as a target intrinsic,
    // then use that name instead.
    if(auto intrinsicDecoration = findBestTargetIntrinsicDecoration(inst))
    {
        return String(intrinsicDecoration->getDefinition());
    }

    // If the instruction reprsents one of the "magic" declarations
    // that makes the NVAPI library work, then we want to make sure
    // it uses the original name it was declared with, so that our
    // generated code will work correctly with either a Slang-compiled
    // or directly `#include`d version of those declarations during
    // downstream compilation.
    //
    if(auto nvapiDecor = inst->findDecoration<IRNVAPIMagicDecoration>())
    {
        return String(nvapiDecor->getName());
    }

    auto entryPointDecor = inst->findDecoration<IREntryPointDecoration>();
    if (entryPointDecor)
    {
        if (getSourceLanguage() == SourceLanguage::GLSL)
        {
            // GLSL will always need to use `main` as the
            // name for an entry-point function, but other
            // targets should try to use the original name.
            //
            // TODO: always use the original name, and
            // use the appropriate options for glslang to
            // make it support a non-`main` name.
            //
            return "main";
        }

        return generateEntryPointNameImpl(entryPointDecor);
    }

    // If the instruction has a linkage decoration, just use that.
    if (auto externCppDecoration = inst->findDecoration<IRExternCppDecoration>())
    {
        // Just use the linkages mangled name directly.
        return externCppDecoration->getName();
    }

    // If we have a name hint on the instruction, then we will try to use that
    // to provide the basis for the actual name in the output code.
    if(auto nameHintDecoration = inst->findDecoration<IRNameHintDecoration>())
    {
        return _generateUniqueName(nameHintDecoration->getName());
    }

    // If the instruction has a linkage decoration, just use that. 
    if(auto linkageDecoration = inst->findDecoration<IRLinkageDecoration>())
    {
        // Just use the linkages mangled name directly.
        return linkageDecoration->getMangledName();
    }

    // Otherwise fall back to a construct temporary name
    // for the instruction.
    StringBuilder sb;
    sb << "_S";
    sb << Int32(getID(inst));

    return sb.ProduceString();
}

String CLikeSourceEmitter::getName(IRInst* inst)
{
    String name;
    if(!m_mapInstToName.TryGetValue(inst, name))
    {
        name = generateName(inst);
        m_mapInstToName.Add(inst, name);
    }
    return name;
}

void CLikeSourceEmitter::emitSimpleValueImpl(IRInst* inst)
{
    switch(inst->getOp())
    {
    case kIROp_IntLit:
    {
        auto litInst = static_cast<IRConstant*>(inst);

        IRBasicType* type = as<IRBasicType>(inst->getDataType());
        if (type)
        {
            switch (type->getBaseType())
            {
                default:
                
                case BaseType::Int:
                {
                    m_writer->emit("int(");
                    m_writer->emit(int32_t(litInst->value.intVal));
                    m_writer->emit(")");
                    return;
                }
                case BaseType::Int8:
                {
                    m_writer->emit("int8_t(");
                    m_writer->emit(int8_t(litInst->value.intVal));
                    m_writer->emit(")");
                    return;
                }
                case BaseType::Int16:
                {
                    m_writer->emit("int16_t(");
                    m_writer->emit(int16_t(litInst->value.intVal));
                    m_writer->emit(")");
                    return;
                }
                case BaseType::UInt8:
                {
                    m_writer->emit(UInt(uint8_t(litInst->value.intVal)));
                    m_writer->emit("U");
                    break;
                }
                case BaseType::UInt16:
                {
                    m_writer->emit(UInt(uint16_t(litInst->value.intVal)));
                    m_writer->emit("U");
                    break;
                }
                case BaseType::UInt:
                {
                    m_writer->emit(UInt(uint32_t(litInst->value.intVal)));
                    m_writer->emit("U");
                    break;
                }
                case BaseType::Int64:
                {
                    m_writer->emitInt64(int64_t(litInst->value.intVal));
                    m_writer->emit("LL");
                    break;
                }
                case BaseType::UInt64:
                {
                    SLANG_COMPILE_TIME_ASSERT(sizeof(litInst->value.intVal) >= sizeof(uint64_t));
                    m_writer->emitUInt64(uint64_t(litInst->value.intVal));
                    m_writer->emit("ULL");
                    break;
                }
                case BaseType::IntPtr:
                {
#if SLANG_PTR_IS_64
                    m_writer->emit("int64_t(");
                    m_writer->emitInt64(int64_t(litInst->value.intVal));
                    m_writer->emit(")");
#else
                    m_writer->emit("int(");
                    m_writer->emit(int(litInst->value.intVal));
                    m_writer->emit(")");
#endif
                    break;
                }
                case BaseType::UIntPtr:
                {
#if SLANG_PTR_IS_64
                    m_writer->emit("uint64_t(");
                    m_writer->emitUInt64(uint64_t(litInst->value.intVal));
                    m_writer->emit(")");
#else
                    m_writer->emit(UInt(uint32_t(litInst->value.intVal)));
                    m_writer->emit("U");
#endif
                    break;
                }
                
            }
        }
        else
        {
            // If no type... just output what we have
            m_writer->emit(litInst->value.intVal);
        }
        break;
    }

    case kIROp_FloatLit:
        m_writer->emit(((IRConstant*) inst)->value.floatVal);
        break;

    case kIROp_BoolLit:
        {
            bool val = ((IRConstant*)inst)->value.intVal != 0;
            m_writer->emit(val ? "true" : "false");
        }
        break;

    default:
        SLANG_UNIMPLEMENTED_X("val case for emit");
        break;
    }

}

bool CLikeSourceEmitter::shouldFoldInstIntoUseSites(IRInst* inst)
{
    // Certain opcodes should never/always be folded in
    switch( inst->getOp() )
    {
    default:
        break;

    // Never fold these in, because they represent declarations
    //
    case kIROp_Var:
    case kIROp_GlobalVar:
    case kIROp_GlobalConstant:
    case kIROp_GlobalParam:
    case kIROp_Param:
    case kIROp_Func:
    case kIROp_Alloca:
        return false;

    // Never fold these, because their result cannot be computed
    // as a sub-expression (they must be emitted as a declaration
    // or statement).
    case kIROp_DefaultConstruct:
        return false;

    // Always fold these in, because they are trivial
    //
    case kIROp_IntLit:
    case kIROp_FloatLit:
    case kIROp_BoolLit:
    case kIROp_CapabilitySet:
        return true;

    // Always fold these in, because their results
    // cannot be represented in the type system of
    // our current targets.
    //
    // TODO: when we add C/C++ as an optional target,
    // we could consider lowering insts that result
    // in pointers directly.
    //
    case kIROp_FieldAddress:
    case kIROp_GetElementPtr:
    case kIROp_Specialize:
    case kIROp_LookupWitness:
    case kIROp_GetValueFromBoundInterface:
        return true;
    }

    // Layouts and attributes are only present to annotate other
    // instructions, and should not be emitted as anything in
    // source code.
    //
    if(as<IRLayout>(inst))
        return true;
    if(as<IRAttr>(inst))
        return true;

    switch( inst->getOp() )
    {
    default:
        break;

    // HACK: don't fold these in because we currently lower
    // them to initializer lists, which aren't allowed in
    // general expression contexts.
    //
    case kIROp_MakeStruct:
    case kIROp_MakeArray:
    case kIROp_swizzleSet:
        return false;

    }

    // Instructions with specific result *types* will usually
    // want to be folded in, because they aren't allowed as types
    // for temporary variables.
    auto type = inst->getDataType();

    // We treat instructions that yield a type as things we should *always* fold.
    //
    // TODO: In general, at the point where we emit code we do not expect to
    // find types being constructed locally (inside function bodies), but this
    // can end up happening because of interaction between different features.
    // Notably, if a generic function gets force-inlined early in codegen,
    // then any types it constructs will be inlined into the body of the caller
    // by default.
    //
    if(as<IRType>(inst) || as<IRTypeKind>(type))
        return true;

    // Unwrap any layers of array-ness from the type, so that
    // we can look at the underlying data type, in case we
    // should *never* expose a value of that type
    while (auto arrayType = as<IRArrayTypeBase>(type))
    {
        type = arrayType->getElementType();
    }

    // Don't allow temporaries of pointer types to be created,
    // if target langauge doesn't support pointers.
    if(as<IRPtrTypeBase>(type))
    {
        if (!doesTargetSupportPtrTypes())
            return true;
    }

    // First we check for uniform parameter groups,
    // because a `cbuffer` or GLSL `uniform` block
    // does not have a first-class type that we can
    // pass around.
    //
    // TODO: We need to ensure that type legalization
    // cleans up cases where we use a parameter group
    // or parameter block type as a function parameter...
    //
    if(as<IRUniformParameterGroupType>(type))
    {
        // TODO: we need to be careful here, because
        // HLSL shader model 6 allows these as explicit
        // types.
        return true;
    }
    //
    // The stream-output and patch types need to be handled
    // too, because they are not really first class (especially
    // not in GLSL, but they also seem to confuse the HLSL
    // compiler when they get used as temporaries).
    //
    else if (as<IRHLSLStreamOutputType>(type))
    {
        return true;
    }
    else if (as<IRHLSLPatchType>(type))
    {
        return true;
    }

    // GLSL doesn't allow texture/resource types to
    // be used as first-class values, so we need
    // to fold them into their use sites in all cases
    if (getSourceLanguage() == SourceLanguage::GLSL)
    {
        if(as<IRResourceTypeBase>(type))
        {
            return true;
        }
        else if(as<IRHLSLStructuredBufferTypeBase>(type))
        {
            return true;
        }
        else if(as<IRUntypedBufferResourceType>(type))
        {
            return true;
        }
        else if(as<IRSamplerStateTypeBase>(type))
        {
            return true;
        }
        else if(as<IRMeshOutputType>(type))
        {
            return true;
        }
    }



    // If the instruction is at global scope, then it might represent
    // a constant (e.g., the value of an enum case).
    //
    if(as<IRModuleInst>(inst->getParent()))
    {
        if(!inst->mightHaveSideEffects())
            return true;
    }

    // Having dealt with all of the cases where we *must* fold things
    // above, we can now deal with the more general cases where we
    // *should not* fold things.

    // Don't fold something with no users:
    if(!inst->hasUses())
        return false;

    // Don't fold something that has multiple users:
    if(inst->hasMoreThanOneUse())
        return false;

    // Don't fold something that might have side effects:
    if(inst->mightHaveSideEffects())
        return false;

    // Don't fold instructions that are marked `[precise]`.
    // This could in principle be extended to any other
    // decorations that affect the semantics of an instruction
    // in ways that require a temporary to be introduced.
    //
    if(inst->findDecoration<IRPreciseDecoration>())
        return false;

    // In general, undefined value should be emitted as an uninitialized
    // variable, so we shouldn't fold it.
    // However, we cannot emit all undefined values a separate variable
    // definition for certain types on certain targets (e.g. `out TriangleStream<T>`
    // for GLSL), so we check this only after all those special cases are
    // considered.
    if (inst->getOp() == kIROp_undefined)
        return false;

    // Okay, at this point we know our instruction must have a single use.
    auto use = inst->firstUse;
    SLANG_ASSERT(use);
    SLANG_ASSERT(!use->nextUse);

    auto user = use->getUser();

    // Check if the use is a call using a target intrinsic that uses the parameter more than once
    // in the intrinsic definition.
    if (auto callInst = as<IRCall>(user))
    {
        const auto funcValue = callInst->getCallee();

        // Let's see if this instruction is a intrinsic call
        // This is significant, because we can within a target intrinsics definition multiple accesses to the same
        // parameter. This is not indicated into the call, and can lead to output code computes something multiple
        // times as it is folding into the expression of the the target intrinsic, which we don't want.
        if (auto targetIntrinsicDecoration = findBestTargetIntrinsicDecoration(funcValue))
        {         
            // Find the index of the original instruction, to see if it's multiply used.
            IRUse* args = callInst->getArgs();
            const Index paramIndex = Index(use - args);
            SLANG_ASSERT(paramIndex >= 0 && paramIndex < Index(callInst->getArgCount()));

            // Look through the slice to seeing how many times this parameters is used (signified via the $0...$9)
            {
                UnownedStringSlice slice = targetIntrinsicDecoration->getDefinition();
                
                const char* cur = slice.begin();
                const char* end = slice.end();

                // Count the amount of uses
                Index useCount = 0;
                while (cur < end)
                {
                    const char c = *cur;
                    if (c == '$' && cur + 1 < end && cur[1] >= '0' && cur[1] <= '9')
                    {
                        const Index index = Index(cur[1] - '0');
                        useCount += Index(index == paramIndex);
                        cur += 2;
                    }
                    else
                    {
                        cur++;
                    }
                }

                // If there is more than one use can't fold.
                if (useCount > 1)
                {
                    return false;
                }
            }
        }
    }
    
    // We'd like to figure out if it is safe to fold our instruction into `user`

    // First, let's make sure they are in the same block/parent:
    if(inst->getParent() != user->getParent())
        return false;

    // Now let's look at all the instructions between this instruction
    // and the user. If any of them might have side effects, then lets
    // bail out now.
    for(auto ii = inst->getNextInst(); ii != user; ii = ii->getNextInst())
    {
        if(!ii)
        {
            // We somehow reached the end of the block without finding
            // the user, which doesn't make sense if uses dominate
            // defs. Let's just play it safe and bail out.
            return false;
        }

        if(ii->mightHaveSideEffects())
            return false;
    }

    // As a safeguard, we should not allow an instruction that references
    // a block parameter to be folded into a unconcditonal branch
    // (which includes arguments for the parameters of the target block).
    //
    // For simplicity, we will just disallow folding of intructions
    // into an unconditonal branch completely, and leave a more refined
    // version of this check for later.
    //
    if(as<IRUnconditionalBranch>(user))
        return false;

    // Okay, if we reach this point then the user comes later in
    // the same block, and there are no instructions with side
    // effects in between, so it seems safe to fold things in.
    return true;
}

void CLikeSourceEmitter::emitDereferenceOperand(IRInst* inst, EmitOpInfo const& outerPrec)
{
    EmitOpInfo newOuterPrec = outerPrec;

    if (doesTargetSupportPtrTypes())
    {
        switch (inst->getOp())
        {
        case kIROp_Var:
            // If `inst` is a variable, dereferencing it is equivalent to just
            // emit its name. i.e. *&var ==> var.
            // We apply this peep hole optimization here to reduce the clutter of
            // resulting code.
            m_writer->emit(getName(inst));
            return;
        case kIROp_FieldAddress:
        {
            auto innerPrec = getInfo(EmitOp::Postfix);
            bool innerNeedClose = maybeEmitParens(newOuterPrec, innerPrec);
            auto ii = as<IRFieldAddress>(inst);
            auto base = ii->getBase();
            if (isPtrToClassType(base->getDataType()))
                emitDereferenceOperand(base, leftSide(newOuterPrec, innerPrec));
            else
                emitOperand(base, leftSide(newOuterPrec, innerPrec));
            m_writer->emit("->");
            m_writer->emit(getName(ii->getField()));
            maybeCloseParens(innerNeedClose);
            return;
        }
        default:
            break;
        }

        auto dereferencePrec = EmitOpInfo::get(EmitOp::Prefix);
        bool needClose = maybeEmitParens(newOuterPrec, dereferencePrec);
        m_writer->emit("*");
        emitOperand(inst, rightSide(newOuterPrec, dereferencePrec));
        maybeCloseParens(needClose);
    }
    else
    {
        emitOperand(inst, outerPrec);
    }
}

void CLikeSourceEmitter::emitVarExpr(IRInst* inst, EmitOpInfo const& outerPrec)
{
    if (doesTargetSupportPtrTypes())
    {
        auto prec = getInfo(EmitOp::Prefix);
        auto newOuterPrec = outerPrec;
        bool needClose = maybeEmitParens(newOuterPrec, prec);
        m_writer->emit("&");
        m_writer->emit(getName(inst));
        maybeCloseParens(needClose);
    }
    else
    {
        m_writer->emit(getName(inst));
    }
}

void CLikeSourceEmitter::emitOperandImpl(IRInst* inst, EmitOpInfo const&  outerPrec)
{
    if( shouldFoldInstIntoUseSites(inst) )
    {
        emitInstExpr(inst, outerPrec);
        return;
    }

    switch(inst->getOp())
    {
    case kIROp_Var:
    case kIROp_GlobalVar:
        emitVarExpr(inst, outerPrec);
        break;
    default:
        m_writer->emit(getName(inst));
        break;
    }
}

void CLikeSourceEmitter::emitArgs(IRInst* inst)
{
    UInt argCount = inst->getOperandCount();
    IRUse* args = inst->getOperands();

    m_writer->emit("(");
    for(UInt aa = 0; aa < argCount; ++aa)
    {
        if(aa != 0) m_writer->emit(", ");
        emitOperand(args[aa].get(), getInfo(EmitOp::General));
    }
    m_writer->emit(")");
}

void CLikeSourceEmitter::emitRateQualifiers(IRInst* value)
{
    if (IRRate* rate = value->getRate())
    {
        emitRateQualifiersImpl(rate);
    }
}

void CLikeSourceEmitter::emitInstResultDecl(IRInst* inst)
{
    auto type = inst->getDataType();
    if(!type)
        return;

    if (as<IRVoidType>(type))
        return;

    emitTempModifiers(inst);

    emitRateQualifiers(inst);

    if(as<IRModuleInst>(inst->getParent()))
    {
        // "Ordinary" instructions at module scope are constants

        switch (getSourceLanguage())
        {
        case SourceLanguage::CUDA:
        case SourceLanguage::HLSL:
        case SourceLanguage::C:
        case SourceLanguage::CPP:
            m_writer->emit("static ");
            break;

        default:
            break;
        }

        m_writer->emit("const ");
    }

    emitType(type, getName(inst));
    m_writer->emit(" = ");
}

IRTargetSpecificDecoration* CLikeSourceEmitter::findBestTargetDecoration(IRInst* inInst)
{
    return Slang::findBestTargetDecoration(inInst, getTargetCaps());
}

IRTargetIntrinsicDecoration* CLikeSourceEmitter::findBestTargetIntrinsicDecoration(IRInst* inInst)
{
    return as<IRTargetIntrinsicDecoration>(findBestTargetDecoration(inInst));
}

/* static */bool CLikeSourceEmitter::isOrdinaryName(UnownedStringSlice const& name)
{
    char const* cursor = name.begin();
    char const*const end = name.end();

    // Consume an optional `.` at the start, which indicates
    // the ordinary name is for a member function.
    if(cursor < end && *cursor == '.')
        cursor++;

    // Must have at least one char, and first char can't be a digit
    if (cursor >= end || CharUtil::isDigit(cursor[0]))
        return false;

    for(; cursor < end; ++cursor)
    {
        const auto c = *cursor;
        if (CharUtil::isAlphaOrDigit(c) || c == '_')
        {
            continue;
        }

        // We allow :: for scope
        if (c == ':' && cursor + 1 < end && cursor[1] == ':')
        {
            ++cursor;
            continue;
        }

        return false;
    }
    return true;
}


void CLikeSourceEmitter::emitIntrinsicCallExpr(IRCall* inst, IRTargetIntrinsicDecoration* targetIntrinsic, EmitOpInfo const& inOuterPrec)
{
    emitIntrinsicCallExprImpl(inst, targetIntrinsic, inOuterPrec);
}

void CLikeSourceEmitter::emitIntrinsicCallExprImpl(
    IRCall*                         inst,
    IRTargetIntrinsicDecoration*    targetIntrinsic,
    EmitOpInfo const&               inOuterPrec)
{
    auto outerPrec = inOuterPrec;

    IRUse* args = inst->getOperands();
    Index argCount = inst->getOperandCount();

    // First operand was the function to be called
    args++;
    argCount--;

    auto name = targetIntrinsic->getDefinition();

    if(isOrdinaryName(name))
    {
        // Simple case: it is just an ordinary name, so we call it like a builtin.
        auto prec = getInfo(EmitOp::Postfix);
        bool needClose = maybeEmitParens(outerPrec, prec);

        // The definition string may be an ordinary name prefixed with `.`
        // to indicate that the operation should be called as a member
        // function on its first operand.
        //
        if(name[0] == '.')
        {
            emitOperand(args[0].get(), leftSide(outerPrec, prec));
            m_writer->emit(".");

            name = UnownedStringSlice(name.begin() + 1, name.end());
            args++;
            argCount--;
        }

        m_writer->emit(name);
        m_writer->emit("(");
        for (Index aa = 0; aa < argCount; ++aa)
        {
            if (aa != 0) m_writer->emit(", ");
            emitOperand(args[aa].get(), getInfo(EmitOp::General));
        }
        m_writer->emit(")");

        maybeCloseParens(needClose);
        return;
    }
    else if(name == ".operator[]")
    {
        // The user is invoking a built-in subscript operator
        //
        // TODO: We might want to remove this bit of special-casing
        // in favor of making all subscript operations in the standard
        // library explicitly declare how they lower. On the flip
        // side, that would require modifications to a very large
        // number of declarations.

        auto prec = getInfo(EmitOp::Postfix);
        bool needClose = maybeEmitParens(outerPrec, prec);

        Int argIndex = 0;

        emitOperand(args[argIndex++].get(), leftSide(outerPrec, prec));
        m_writer->emit("[");
        emitOperand(args[argIndex++].get(), getInfo(EmitOp::General));
        m_writer->emit("]");

        if(argIndex < argCount)
        {
            m_writer->emit(" = ");
            emitOperand(args[argIndex++].get(), getInfo(EmitOp::General));
        }

        maybeCloseParens(needClose);
        return;
    }
    else
    {
        IntrinsicExpandContext context(this);
        context.emit(inst, args, argCount, name);
    }
}

void CLikeSourceEmitter::_emitCallArgList(IRCall* inst, int startingOperandIndex)
{
    bool isFirstArg = true;
    m_writer->emit("(");
    UInt argCount = inst->getOperandCount();
    for (UInt aa = startingOperandIndex; aa < argCount; ++aa)
    {
        auto operand = inst->getOperand(aa);
        if (as<IRVoidType>(operand->getDataType()))
            continue;

        // TODO: [generate dynamic dispatch code for generics]
        // Pass RTTI object here. Ignore type argument for now.
        if (as<IRType>(operand))
            continue;

        if (!isFirstArg)
            m_writer->emit(", ");
        else
            isFirstArg = false;
        emitOperand(inst->getOperand(aa), getInfo(EmitOp::General));
    }
    m_writer->emit(")");
}

void CLikeSourceEmitter::emitComInterfaceCallExpr(IRCall* inst, EmitOpInfo const& inOuterPrec)
{
    auto funcValue = inst->getOperand(0);
    auto object = funcValue->getOperand(0);
    auto methodKey = funcValue->getOperand(1);
    auto prec = getInfo(EmitOp::Postfix);

    auto outerPrec = inOuterPrec;
    bool needClose = maybeEmitParens(outerPrec, prec);

    emitOperand(object, leftSide(outerPrec, prec));
    m_writer->emit("->");
    m_writer->emit(getName(methodKey));
    _emitCallArgList(inst, 2);
    maybeCloseParens(needClose);
}

void CLikeSourceEmitter::emitCallExpr(IRCall* inst, EmitOpInfo outerPrec)
{
    auto funcValue = inst->getOperand(0);

    // Does this function declare any requirements.
    handleRequiredCapabilities(funcValue);

    // Detect if this is a call into a COM interface method.
    if (funcValue->getOp() == kIROp_LookupWitness)
    {
        auto operand0Type = funcValue->getOperand(0)->getDataType();
        switch (operand0Type->getOp())
        {
        case kIROp_WitnessTableIDType:
        case kIROp_WitnessTableType:
            if (as<IRWitnessTableTypeBase>(operand0Type)
                    ->getConformanceType()
                    ->findDecoration<IRComInterfaceDecoration>())
            {
                emitComInterfaceCallExpr(inst, outerPrec);
                return;
            }
            break;
        case kIROp_ComPtrType:
        case kIROp_PtrType:
        case kIROp_NativePtrType:
            emitComInterfaceCallExpr(inst, outerPrec);
            return;
        }
    }

    // We want to detect any call to an intrinsic operation,
    // that we can emit it directly without mangling, etc.
    if(auto targetIntrinsic = findBestTargetIntrinsicDecoration(funcValue))
    {
        emitIntrinsicCallExpr(inst, targetIntrinsic, outerPrec);
    }
    else
    {
        auto prec = getInfo(EmitOp::Postfix);
        bool needClose = maybeEmitParens(outerPrec, prec);

        emitOperand(funcValue, leftSide(outerPrec, prec));
        _emitCallArgList(inst);
        maybeCloseParens(needClose);
    }
}

void CLikeSourceEmitter::emitInstExpr(IRInst* inst, const EmitOpInfo& inOuterPrec)
{
    // Try target specific impl first
    if (tryEmitInstExprImpl(inst, inOuterPrec))
    {
        return;
    }
    defaultEmitInstExpr(inst, inOuterPrec);
}

void CLikeSourceEmitter::diagnoseUnhandledInst(IRInst* inst)
{
    getSink()->diagnose(inst, Diagnostics::unimplemented, "unexpected IR opcode during code emit");
}

void CLikeSourceEmitter::defaultEmitInstExpr(IRInst* inst, const EmitOpInfo& inOuterPrec)
{
    EmitOpInfo outerPrec = inOuterPrec;
    bool needClose = false;
    switch(inst->getOp())
    {
    case kIROp_GlobalHashedStringLiterals:
        /* Don't need to to output anything for this instruction - it's used for reflecting string literals that
        are hashed with 'getStringHash' */
        break;
    case kIROp_RTTIPointerType:
        break;

    case kIROp_undefined:
    case kIROp_DefaultConstruct:
        m_writer->emit(getName(inst));
        break;

    case kIROp_IntLit:
    case kIROp_FloatLit:
    case kIROp_BoolLit:
        emitSimpleValue(inst);
        break;

    case kIROp_MakeVector:
    case kIROp_MakeMatrix:
    case kIROp_VectorReshape:
    case kIROp_CastFloatToInt:
    case kIROp_CastIntToFloat:
    case kIROp_IntCast:
    case kIROp_FloatCast:
        // Simple constructor call
        emitType(inst->getDataType());
        emitArgs(inst);
        break;
    case kIROp_MakeMatrixFromScalar:
        {
            emitType(inst->getDataType());
            auto matrixType = as<IRMatrixType>(inst->getDataType());
            SLANG_RELEASE_ASSERT(matrixType);
            auto columnCount = as<IRIntLit>(matrixType->getColumnCount());
            SLANG_RELEASE_ASSERT(columnCount);
            auto rowCount = as<IRIntLit>(matrixType->getRowCount());
            SLANG_RELEASE_ASSERT(rowCount);
            m_writer->emit("(");
            for (IRIntegerValue i = 0; i < rowCount->getValue() * columnCount->getValue(); i++)
            {
                if (i != 0)
                    m_writer->emit(", ");
                emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
            }
            m_writer->emit(")");
        }
        break;
    case kIROp_AllocObj:
        m_writer->emit("new ");
        m_writer->emit(getName(inst->getDataType()));
        m_writer->emit("()");
        break;
    case kIROp_MakeUInt64:
        m_writer->emit("((");
        emitType(inst->getDataType());
        m_writer->emit("(");
        emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
        m_writer->emit(") << 32) + ");
        emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
        m_writer->emit(")");
        break;
    case kIROp_MakeVectorFromScalar:
    case kIROp_MatrixReshape:
    case kIROp_CastPtrToInt:
    case kIROp_CastIntToPtr:
    {
        // Simple constructor call
        auto prec = getInfo(EmitOp::Prefix);
        needClose = maybeEmitParens(outerPrec, prec);

        m_writer->emit("(");
        emitType(inst->getDataType());
        m_writer->emit(")");

        emitOperand(inst->getOperand(0), rightSide(outerPrec,prec));
        break;
    }
    case kIROp_FieldExtract:
    {
        // Extract field from aggregate
        IRFieldExtract* fieldExtract = (IRFieldExtract*) inst;

        auto prec = getInfo(EmitOp::Postfix);
        needClose = maybeEmitParens(outerPrec, prec);

        auto base = fieldExtract->getBase();
        emitOperand(base, leftSide(outerPrec, prec));
        if (base->getDataType()->getOp() == kIROp_ClassType)
            m_writer->emit("->");
        else
            m_writer->emit(".");
        if(getSourceLanguage() == SourceLanguage::GLSL
            && as<IRUniformParameterGroupType>(base->getDataType()))
        {
            m_writer->emit("_data.");
        }
        m_writer->emit(getName(fieldExtract->getField()));
        break;
    }
    case kIROp_FieldAddress:
    {
        // Extract field "address" from aggregate

        IRFieldAddress* ii = (IRFieldAddress*) inst;

        if (doesTargetSupportPtrTypes())
        {
            auto prec = getInfo(EmitOp::Prefix);
            needClose = maybeEmitParens(outerPrec, prec);
            m_writer->emit("&");
            outerPrec = rightSide(outerPrec, prec);
            auto innerPrec = getInfo(EmitOp::Postfix);
            bool innerNeedClose = maybeEmitParens(outerPrec, innerPrec);
            auto base = ii->getBase();
            if (isPtrToClassType(base->getDataType()))
                emitDereferenceOperand(base, leftSide(outerPrec, innerPrec));
            else
                emitOperand(base, leftSide(outerPrec, innerPrec));
            m_writer->emit("->");
            m_writer->emit(getName(ii->getField()));
            maybeCloseParens(innerNeedClose);
        }
        else
        {
            auto prec = getInfo(EmitOp::Postfix);
            needClose = maybeEmitParens(outerPrec, prec);

            auto base = ii->getBase();
            emitOperand(base, leftSide(outerPrec, prec));
            m_writer->emit(".");
            if(getSourceLanguage() == SourceLanguage::GLSL
                && as<IRUniformParameterGroupType>(base->getDataType()))
            {
                m_writer->emit("_data.");
            }
            m_writer->emit(getName(ii->getField()));
        }
        break;
    }

    // Comparisons
    case kIROp_Eql:
    case kIROp_Neq:
    case kIROp_Greater:
    case kIROp_Less:
    case kIROp_Geq:
    case kIROp_Leq:
    {
        const auto emitOp = getEmitOpForOp(inst->getOp());

        auto prec = getInfo(emitOp);
        needClose = maybeEmitParens(outerPrec, prec);

        emitOperand(inst->getOperand(0), leftSide(outerPrec, prec));
        m_writer->emit(" ");
        m_writer->emit(prec.op);
        m_writer->emit(" ");
        emitOperand(inst->getOperand(1), rightSide(outerPrec, prec));          
        break;
    }

    // Binary ops
    case kIROp_Add:
    case kIROp_Sub:
    case kIROp_Div:
    case kIROp_IRem:
    case kIROp_FRem:
    case kIROp_Lsh:
    case kIROp_Rsh:
    case kIROp_BitXor:
    case kIROp_BitOr:
    case kIROp_BitAnd:
    case kIROp_And:
    case kIROp_Or:
    case kIROp_Mul:
    {
        const auto emitOp = getEmitOpForOp(inst->getOp());
        const auto info = getInfo(emitOp);

        needClose = maybeEmitParens(outerPrec, info);
        emitOperand(inst->getOperand(0), leftSide(outerPrec, info));    
        m_writer->emit(" ");
        m_writer->emit(info.op);
        m_writer->emit(" ");                                                                  
        emitOperand(inst->getOperand(1), rightSide(outerPrec, info));   
        break;
    }
    // Unary
    case kIROp_Not:
    case kIROp_Neg:
    case kIROp_BitNot:
    {        
        IRInst* operand = inst->getOperand(0);

        const auto emitOp = getEmitOpForOp(inst->getOp());
        const auto prec = getInfo(emitOp);

        needClose = maybeEmitParens(outerPrec, prec);

        switch (inst->getOp())
        {
            case kIROp_BitNot:
            {
                // If it's a BitNot, but the data type is bool special case to !
                m_writer->emit(as<IRBoolType>(inst->getDataType()) ? "!" : prec.op);
                break;
            }
            case kIROp_Not:
            {
                m_writer->emit(prec.op);
                break;
            }
            case kIROp_Neg:
            {
                // Emit a space after the unary -, so if we are followed by a negative literal we don't end up with --
                // which some downstream compilers determine to be decrement.
                m_writer->emit("- ");
                break;
            }
        }

        emitOperand(operand, rightSide(prec, outerPrec));
        break;
    }    
    case kIROp_Load:
        {
            auto base = inst->getOperand(0);
            emitDereferenceOperand(base, outerPrec);
            if(getSourceLanguage() == SourceLanguage::GLSL
                && as<IRUniformParameterGroupType>(base->getDataType()))
            {
                m_writer->emit("._data");
            }
        }
        break;

    case kIROp_Store:
        {
            auto prec = getInfo(EmitOp::Assign);
            needClose = maybeEmitParens(outerPrec, prec);

            emitDereferenceOperand(inst->getOperand(0), leftSide(outerPrec, prec));
            m_writer->emit(" = ");
            emitOperand(inst->getOperand(1), rightSide(prec, outerPrec));
        }
        break;

    case kIROp_Call:
        {
            emitCallExpr((IRCall*)inst, outerPrec);
        }
        break;

    case kIROp_GroupMemoryBarrierWithGroupSync:
        m_writer->emit("GroupMemoryBarrierWithGroupSync()");
        break;

    case kIROp_getNativeStr:
        {
            auto prec = getInfo(EmitOp::Postfix);
            needClose = maybeEmitParens(outerPrec, prec);
            emitOperand(inst->getOperand(0), leftSide(outerPrec, prec));
            m_writer->emit("->getBuffer()");
            break;
        }
    case kIROp_MakeString:
        {
            m_writer->emit("String(");
            emitOperand(inst->getOperand(0), EmitOpInfo());
            m_writer->emit(")");
            break;
        }
    case kIROp_GetNativePtr:
    {
        auto prec = getInfo(EmitOp::Postfix);
        needClose = maybeEmitParens(outerPrec, prec);
        emitOperand(inst->getOperand(0), leftSide(outerPrec, prec));
        m_writer->emit(".get()");
        break;
    }
    case kIROp_GetManagedPtrWriteRef:
    {
        auto prec = getInfo(EmitOp::Postfix);
        needClose = maybeEmitParens(outerPrec, prec);
        emitDereferenceOperand(inst->getOperand(0), leftSide(outerPrec, prec));
        m_writer->emit(".writeRef()");
        break;
    }
    case kIROp_ManagedPtrAttach:
    {
        auto prec = getInfo(EmitOp::Postfix);
        needClose = maybeEmitParens(outerPrec, prec);
        emitDereferenceOperand(inst->getOperand(0), leftSide(outerPrec, prec));
        m_writer->emit(".attach(");
        emitOperand(inst->getOperand(1), EmitOpInfo());
        m_writer->emit(")");
        break;
    }
    case kIROp_ManagedPtrDetach:
    {
        auto prec = getInfo(EmitOp::Postfix);
        needClose = maybeEmitParens(outerPrec, prec);
        emitOperand(inst->getOperand(0), leftSide(outerPrec, prec));
        m_writer->emit(".detach()");
        break;
    }
    case kIROp_GetElement:
    case kIROp_GetElementPtr:
    case kIROp_ImageSubscript:
        // HACK: deal with translation of GLSL geometry shader input arrays.
        if(auto decoration = inst->getOperand(0)->findDecoration<IRGLSLOuterArrayDecoration>())
        {
            auto prec = getInfo(EmitOp::Postfix);
            needClose = maybeEmitParens(outerPrec, prec);

            m_writer->emit(decoration->getOuterArrayName());
            m_writer->emit("[");
            emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
            m_writer->emit("].");
            emitOperand(inst->getOperand(0), rightSide(prec, outerPrec));
            break;
        }
        else
        {
            if (inst->getOp() == kIROp_GetElementPtr && doesTargetSupportPtrTypes())
            {
                const auto info = getInfo(EmitOp::Prefix);
                needClose = maybeEmitParens(outerPrec, info);
                m_writer->emit("&");
                auto rightSidePrec = rightSide(outerPrec, info);
                auto postfixInfo = getInfo(EmitOp::Postfix);
                bool rightSideNeedClose = maybeEmitParens(rightSidePrec, postfixInfo);
                if (isPtrToArrayType(inst->getOperand(0)->getDataType()))
                    emitDereferenceOperand(inst->getOperand(0), leftSide(rightSidePrec, postfixInfo));
                else
                    emitOperand(inst->getOperand(0), leftSide(rightSidePrec, postfixInfo));
                m_writer->emit("[");
                emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
                m_writer->emit("]");
                maybeCloseParens(rightSideNeedClose);
                break;
            }
            else
            {
                auto prec = getInfo(EmitOp::Postfix);
                needClose = maybeEmitParens(outerPrec, prec);

                emitOperand(inst->getOperand(0), leftSide(outerPrec, prec));
                m_writer->emit("[");
                emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
                m_writer->emit("]");
            }
        }
        break;

    case kIROp_swizzle:
        {
            auto prec = getInfo(EmitOp::Postfix);
            needClose = maybeEmitParens(outerPrec, prec);

            auto ii = (IRSwizzle*)inst;
            emitOperand(ii->getBase(), leftSide(outerPrec, prec));
            m_writer->emit(".");
            const Index elementCount = Index(ii->getElementCount());
            for (Index ee = 0; ee < elementCount; ++ee)
            {
                IRInst* irElementIndex = ii->getElementIndex(ee);
                SLANG_RELEASE_ASSERT(irElementIndex->getOp() == kIROp_IntLit);
                IRConstant* irConst = (IRConstant*)irElementIndex;

                UInt elementIndex = (UInt)irConst->value.intVal;
                SLANG_RELEASE_ASSERT(elementIndex < 4);

                char const* kComponents[] = { "x", "y", "z", "w" };
                m_writer->emit(kComponents[elementIndex]);
            }
        }
        break;

    case kIROp_Specialize:
        {
            emitOperand(inst->getOperand(0), outerPrec);
        }
        break;

    case kIROp_WrapExistential:
        {
            // Normally `WrapExistential` shouldn't exist in user code at this point.
            // The only exception is when the user is calling a stdlib generic
            // function that has an existential type argument, for example
            // `StructuredBuffer<ISomething>.Load()`.
            // We can safely ignore the `wrapExistential` operation in this case.
            emitOperand(inst->getOperand(0), outerPrec);
        }
        break;

    case kIROp_Select:
        {
            
            auto prec = getInfo(EmitOp::Conditional);
            needClose = maybeEmitParens(outerPrec, prec);

            emitOperand(inst->getOperand(0), leftSide(outerPrec, prec));
            m_writer->emit(" ? ");
            emitOperand(inst->getOperand(1), prec);
            m_writer->emit(" : ");
            emitOperand(inst->getOperand(2), rightSide(prec, outerPrec));
        }
        break;

    case kIROp_Param:
        m_writer->emit(getName(inst));
        break;

    case kIROp_MakeArray:
    case kIROp_MakeStruct:
        {
            // TODO: initializer-list syntax may not always
            // be appropriate, depending on the context
            // of the expression.

            m_writer->emit("{ ");
            UInt argCount = inst->getOperandCount();
            for (UInt aa = 0; aa < argCount; ++aa)
            {
                if (aa != 0) m_writer->emit(", ");
                emitOperand(inst->getOperand(aa), getInfo(EmitOp::General));
            }
            m_writer->emit(" }");
        }
        break;

    case kIROp_BitCast:
        {
            // Note: we are currently emitting casts as plain old
            // C-style casts, which may not always perform a bitcast.
            //
            // TODO: This operation should map to an intrinsic to be
            // provided in a prelude for C/C++, so that the target
            // can easily emit code for whatever the best possible
            // bitcast is on the platform.
         
            auto prec = getInfo(EmitOp::Prefix);
            needClose = maybeEmitParens(outerPrec, prec);

            m_writer->emit("(");
            emitType(inst->getDataType());
            m_writer->emit(")");
            m_writer->emit("(");
            emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
            m_writer->emit(")");
        }
        break;
    case kIROp_GlobalConstant:
    case kIROp_GetValueFromBoundInterface:
        emitOperand(inst->getOperand(0), outerPrec);
        break;

    case kIROp_ByteAddressBufferLoad:
        m_writer->emit("(");
        emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
        m_writer->emit(").Load<");
        emitType(inst->getDataType());
        m_writer->emit(" >(");
        emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
        m_writer->emit(")");
        break;

    case kIROp_ByteAddressBufferStore:
        {
            auto prec = getInfo(EmitOp::Postfix);
            needClose = maybeEmitParens(outerPrec, prec);

            emitOperand(inst->getOperand(0), leftSide(outerPrec, prec));
            m_writer->emit(".Store(");
            emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
            m_writer->emit(",");
            emitOperand(inst->getOperand(2), getInfo(EmitOp::General));
            m_writer->emit(")");
        }
        break;
    case kIROp_PackAnyValue:
    {
        m_writer->emit("packAnyValue<");
        m_writer->emit(getIntVal(cast<IRAnyValueType>(inst->getDataType())->getSize()));
        m_writer->emit(",");
        emitType(inst->getOperand(0)->getDataType());
        m_writer->emit(">(");
        emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
        m_writer->emit(")");
        break;
    }
    case kIROp_UnpackAnyValue:
    {
        m_writer->emit("unpackAnyValue<");
        m_writer->emit(getIntVal(cast<IRAnyValueType>(inst->getOperand(0)->getDataType())->getSize()));
        m_writer->emit(",");
        emitType(inst->getDataType());
        m_writer->emit(">(");
        emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
        m_writer->emit(")");
        break;
    }
    case kIROp_GpuForeach:
    {
        auto operand = inst->getOperand(2);
        if (as<IRFunc>(operand))
        {
            //emitOperand(operand->findDecoration<IREntryPointDecoration>(), getInfo(EmitOp::General));
            emitOperand(operand, getInfo(EmitOp::General));
        }
        else
        {
            SLANG_UNEXPECTED("Expected 3rd operand to be a function");
        }
        m_writer->emit("_wrapper(");
        emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
        m_writer->emit(", ");
        emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
        UInt argCount = inst->getOperandCount();
        for (UInt aa = 3; aa < argCount; ++aa)
        {
            m_writer->emit(", ");
            emitOperand(inst->getOperand(aa), getInfo(EmitOp::General));
        }
        m_writer->emit(")");
        break;
    }
    case kIROp_GetStringHash:
    {
        auto getStringHashInst = as<IRGetStringHash>(inst);
        auto stringLit = getStringHashInst->getStringLit();

        if (stringLit)
        {
            auto slice = stringLit->getStringSlice();
            m_writer->emit(static_cast<int32_t>(getStableHashCode32(slice.begin(), slice.getLength())));
        }
        else
        {
            // Couldn't handle 
            diagnoseUnhandledInst(inst);
        }
        break;
    }

    default:
        diagnoseUnhandledInst(inst);
        break;
    }
    maybeCloseParens(needClose);
}

void CLikeSourceEmitter::emitInst(IRInst* inst)
{
    try
    {
        _emitInst(inst);
    }
    // Don't emit any context message for an explicit `AbortCompilationException`
    // because it should only happen when an error is already emitted.
    catch(const AbortCompilationException&) { throw; }
    catch(...)
    {
        noteInternalErrorLoc(inst->sourceLoc);
        throw;
    }
}

void CLikeSourceEmitter::_emitInst(IRInst* inst)
{
    if (shouldFoldInstIntoUseSites(inst))
    {
        return;
    }

    // Specially handle params. The issue here is around PHI nodes, and that they do not
    // have source loc information, by default, but we don't want to force outputting a #line.
    if (inst->getOp() == kIROp_Param)
    {
        m_writer->advanceToSourceLocationIfValid(inst->sourceLoc);
    }
    else
    {
         m_writer->advanceToSourceLocation(inst->sourceLoc);
    }

    switch(inst->getOp())
    {
    default:
        emitInstResultDecl(inst);
        emitInstExpr(inst, getInfo(EmitOp::General));
        m_writer->emit(";\n");
        break;

    case kIROp_LiveRangeStart:
    case kIROp_LiveRangeEnd:
        emitLiveness(inst);
        break;
    case kIROp_undefined:
    case kIROp_DefaultConstruct:
        {
            auto type = inst->getDataType();
            emitType(type, getName(inst));
            m_writer->emit(";\n");
        }
        break;

    case kIROp_Var:
        {
            auto var = cast<IRVar>(inst);
            emitVar(var);
        }
        break;

    case kIROp_Param:
        // Don't emit parameters, since they are declared as part of the function.
        break;

    case kIROp_FieldAddress:
        // skip during code emit, since it should be
        // folded into use site(s)
        break;

    case kIROp_Return:
        m_writer->emit("return");
        if (((IRReturn*)inst)->getVal()->getOp() != kIROp_VoidLit)
        {
            m_writer->emit(" ");
            emitOperand(((IRReturn*) inst)->getVal(), getInfo(EmitOp::General));
        }
        m_writer->emit(";\n");
        break;

    case kIROp_discard:
        m_writer->emit("discard;\n");
        break;

    case kIROp_swizzleSet:
        {
            auto ii = (IRSwizzleSet*)inst;
            emitInstResultDecl(inst);
            emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
            m_writer->emit(";\n");

            auto subscriptOuter = getInfo(EmitOp::General);
            auto subscriptPrec = getInfo(EmitOp::Postfix);
            bool needCloseSubscript = maybeEmitParens(subscriptOuter, subscriptPrec);

            emitOperand(inst, leftSide(subscriptOuter, subscriptPrec));
            m_writer->emit(".");
            UInt elementCount = ii->getElementCount();
            for (UInt ee = 0; ee < elementCount; ++ee)
            {
                IRInst* irElementIndex = ii->getElementIndex(ee);
                SLANG_RELEASE_ASSERT(irElementIndex->getOp() == kIROp_IntLit);
                IRConstant* irConst = (IRConstant*)irElementIndex;

                UInt elementIndex = (UInt)irConst->value.intVal;
                SLANG_RELEASE_ASSERT(elementIndex < 4);

                char const* kComponents[] = { "x", "y", "z", "w" };
                m_writer->emit(kComponents[elementIndex]);
            }
            maybeCloseParens(needCloseSubscript);

            m_writer->emit(" = ");
            emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
            m_writer->emit(";\n");
        }
        break;

    case kIROp_SwizzledStore:
        {
            auto subscriptOuter = getInfo(EmitOp::General);
            auto subscriptPrec = getInfo(EmitOp::Postfix);
            bool needCloseSubscript = maybeEmitParens(subscriptOuter, subscriptPrec);


            auto ii = cast<IRSwizzledStore>(inst);
            emitDereferenceOperand(ii->getDest(), leftSide(subscriptOuter, subscriptPrec));
            m_writer->emit(".");
            UInt elementCount = ii->getElementCount();
            for (UInt ee = 0; ee < elementCount; ++ee)
            {
                IRInst* irElementIndex = ii->getElementIndex(ee);
                SLANG_RELEASE_ASSERT(irElementIndex->getOp() == kIROp_IntLit);
                IRConstant* irConst = (IRConstant*)irElementIndex;

                UInt elementIndex = (UInt)irConst->value.intVal;
                SLANG_RELEASE_ASSERT(elementIndex < 4);

                char const* kComponents[] = { "x", "y", "z", "w" };
                m_writer->emit(kComponents[elementIndex]);
            }
            maybeCloseParens(needCloseSubscript);

            m_writer->emit(" = ");
            emitOperand(ii->getSource(), getInfo(EmitOp::General));
            m_writer->emit(";\n");
        }
        break;
    }
}

void CLikeSourceEmitter::emitSemanticsUsingVarLayout(IRVarLayout* varLayout)
{
    if(auto semanticAttr = varLayout->findAttr<IRSemanticAttr>())
    {
        // Note: We force the semantic name stored in the IR to
        // upper-case here because that is what existing Slang
        // tests had assumed and continue to rely upon.
        //
        // The original rationale for switching to uppercase was
        // canonicalization for reflection (users can't accidentally
        // write code that works for `COLOR` but not for `Color`),
        // but it would probably be more ideal for our output code
        // to give the semantic name as close to how it was originally spelled
        // spelled as possible.
        //
        // TODO: Try removing this step and fixing up the test cases
        // to see if we are happier with an approach that doesn't
        // force uppercase.
        //
        String name = semanticAttr->getName();
        name = name.toUpper();

        m_writer->emit(" : ");
        m_writer->emit(name);
        if(auto index = semanticAttr->getIndex())
        {
            m_writer->emit(index);
        }
    }
}

void CLikeSourceEmitter::emitSemantics(IRInst* inst)
{
    emitSemanticsImpl(inst);
}

void CLikeSourceEmitter::emitLayoutSemantics(IRInst* inst, char const* uniformSemanticSpelling)
{
    emitLayoutSemanticsImpl(inst, uniformSemanticSpelling);
}

void CLikeSourceEmitter::emitRegion(Region* inRegion)
{
    // We will use a loop so that we can process sequential (simple)
    // regions iteratively rather than recursively.
    // This is effectively an emulation of tail recursion.
    Region* region = inRegion;
    while(region)
    {
        // What flavor of region are we trying to emit?
        switch(region->getFlavor())
        {
        case Region::Flavor::Simple:
            {
                // A simple region consists of a basic block followed
                // by another region.
                //
                auto simpleRegion = (SimpleRegion*) region;

                // We start by outputting all of the non-terminator
                // instructions in the block.
                //
                auto block = simpleRegion->block;
                auto terminator = block->getTerminator();
                for (auto inst = block->getFirstInst(); inst != terminator; inst = inst->getNextInst())
                {
                    emitInst(inst);
                }

                // Next we have to deal with the terminator instruction
                // itself. In many cases, the terminator will have been
                // turned into a block of its own, but certain cases
                // of terminators are simple enough that we just fold
                // them into the current block.
                //
                m_writer->advanceToSourceLocation(terminator->sourceLoc);
                switch(terminator->getOp())
                {
                default:
                    // Don't do anything with the terminator, and assume
                    // its behavior has been folded into the next region.
                    break;

                case kIROp_Return:
                case kIROp_discard:
                    // For extremely simple terminators, we just handle
                    // them here, so that we don't have to allocate
                    // separate `Region`s for them.
                    emitInst(terminator);
                    break;
                }

                // If the terminator required a full region to represent
                // its behavior in a structured form, then we will move
                // along to that region now.
                //
                // We do this iteratively rather than recursively, by
                // jumping back to the top of our loop with a new
                // value for `region`.
                //
                region = simpleRegion->nextRegion;
                continue;
            }

        // Break and continue regions are trivial to handle, as long as we
        // don't need to consider multi-level break/continue (which we
        // don't for now).
        case Region::Flavor::Break:
            m_writer->emit("break;\n");
            break;
        case Region::Flavor::Continue:
            m_writer->emit("continue;\n");
            break;

        case Region::Flavor::If:
            {
                auto ifRegion = (IfRegion*) region;

                // TODO: consider simplifying the code in
                // the case where `ifRegion == null`
                // so that we output `if(!condition) { elseRegion }`
                // instead of the current `if(condition) {} else { elseRegion }`

                m_writer->emit("if(");
                emitOperand(ifRegion->getCondition(), getInfo(EmitOp::General));
                m_writer->emit(")\n{\n");
                m_writer->indent();
                emitRegion(ifRegion->thenRegion);
                m_writer->dedent();
                m_writer->emit("}\n");

                // Don't emit the `else` region if it would be empty
                //
                if(auto elseRegion = ifRegion->elseRegion)
                {
                    m_writer->emit("else\n{\n");
                    m_writer->indent();
                    emitRegion(elseRegion);
                    m_writer->dedent();
                    m_writer->emit("}\n");
                }

                // Continue with the region after the `if`.
                //
                // TODO: consider just constructing a `SimpleRegion`
                // around an `IfRegion` to handle this sequencing,
                // rather than making `IfRegion` serve as both a
                // conditional and a sequence.
                //
                region = ifRegion->nextRegion;
                continue;
            }
            break;

        case Region::Flavor::Loop:
            {
                auto loopRegion = (LoopRegion*) region;
                auto loopInst = loopRegion->loopInst;

                // If the user applied an explicit decoration to the loop,
                // to control its unrolling behavior, then pass that
                // along in the output code (if the target language
                // supports the semantics of the decoration).
                //
                if (auto loopControlDecoration = loopInst->findDecoration<IRLoopControlDecoration>())
                {
                    emitLoopControlDecorationImpl(loopControlDecoration);
               }

                m_writer->emit("for(;;)\n{\n");
                m_writer->indent();
                emitRegion(loopRegion->body);
                m_writer->dedent();
                m_writer->emit("}\n");

                // Continue with the region after the loop
                region = loopRegion->nextRegion;
                continue;
            }

        case Region::Flavor::Switch:
            {
                auto switchRegion = (SwitchRegion*) region;

                // Emit the start of our statement.
                m_writer->emit("switch(");
                emitOperand(switchRegion->getCondition(), getInfo(EmitOp::General));
                m_writer->emit(")\n{\n");

                auto defaultCase = switchRegion->defaultCase;
                for(auto currentCase : switchRegion->cases)
                {
                    for(auto caseVal : currentCase->values)
                    {
                        m_writer->emit("case ");
                        emitOperand(caseVal, getInfo(EmitOp::General));
                        m_writer->emit(":\n");
                    }
                    if(currentCase.Ptr() == defaultCase)
                    {
                        m_writer->emit("default:\n");
                    }

                    m_writer->indent();
                    m_writer->emit("{\n");
                    m_writer->indent();
                    emitRegion(currentCase->body);
                    m_writer->dedent();
                    m_writer->emit("}\n");
                    m_writer->dedent();
                }

                m_writer->emit("}\n");

                // Continue with the region after the `switch`
                region = switchRegion->nextRegion;
                continue;
            }
            break;
        }
        break;
    }
}

void CLikeSourceEmitter::emitRegionTree(RegionTree* regionTree)
{
    emitRegion(regionTree->rootRegion);
}

bool CLikeSourceEmitter::isDefinition(IRFunc* func)
{
    // For now, we use a simple approach: a function is
    // a definition if it has any blocks, and a declaration otherwise.
    return func->getFirstBlock() != nullptr;
}

void CLikeSourceEmitter::emitEntryPointAttributes(IRFunc* irFunc, IREntryPointDecoration* entryPointDecor)
{
    emitEntryPointAttributesImpl(irFunc, entryPointDecor);
}

void CLikeSourceEmitter::emitFunctionBody(IRGlobalValueWithCode* code)
{
    // Compute a structured region tree that can represent
    // the control flow of our function.
    //
    RefPtr<RegionTree> regionTree = generateRegionTreeForFunc(code, getSink());

    // Now that we've computed the region tree, we have
    // an opportunity to perform some last-minute transformations
    // on the code to make sure it follows our rules.
    //
    // TODO: it would be better to do these transformations earlier,
    // so that we can, e.g., dump the final IR code *before* emission
    // starts, but that gets a bit complicated because we also want
    // to have the region tree available without having to recompute it.
    //
    // For now we are just going to do things the expedient way, but
    // eventually we should allow an IR module to have side-band
    // storage for derived structures like the region tree (and logic
    // for invalidating them when a transformation would break them).
    //
    fixValueScoping(regionTree);

    // Now emit high-level code from that structured region tree.
    //
    emitRegionTree(regionTree);
}

void CLikeSourceEmitter::emitSimpleFuncParamImpl(IRParam* param)
{
    auto paramName = getName(param);
    auto paramType = param->getDataType();

    if(auto layoutDecoration = param->findDecoration<IRLayoutDecoration>() )
    {
        auto layout = as<IRVarLayout>(layoutDecoration->getLayout());
        SLANG_ASSERT(layout);

        if(layout->usesResourceKind(LayoutResourceKind::VaryingInput)
            || layout->usesResourceKind(LayoutResourceKind::VaryingOutput))
        {
            emitInterpolationModifiers(param, paramType, layout);
            emitMeshOutputModifiers(param);
        }
    }

    emitParamType(paramType, paramName);
    emitSemantics(param);
}

void CLikeSourceEmitter::emitSimpleFuncParamsImpl(IRFunc* func)
{
    m_writer->emit("(");

    auto firstParam = func->getFirstParam();
    for (auto pp = firstParam; pp; pp = pp->getNextParam())
    {
        if (pp != firstParam)
            m_writer->emit(", ");

        emitSimpleFuncParamImpl(pp);
    }

    m_writer->emit(")");
}

void CLikeSourceEmitter::emitSimpleFuncImpl(IRFunc* func)
{
    auto resultType = func->getResultType();

    // Deal with decorations that need
    // to be emitted as attributes
    if ( IREntryPointDecoration* entryPointDecor = func->findDecoration<IREntryPointDecoration>())
    {
        emitEntryPointAttributes(func, entryPointDecor);
    }

    // Deal with required features/capabilities of the function
    //
    handleRequiredCapabilitiesImpl(func);

    emitFunctionPreambleImpl(func);

    auto name = getName(func);

    emitFuncDecorations(func);

    emitType(resultType, name);
    emitSimpleFuncParamsImpl(func);
    emitSemantics(func);

    // TODO: encode declaration vs. definition
    if(isDefinition(func))
    {
        m_writer->emit("\n{\n");
        m_writer->indent();

        // Need to emit the operations in the blocks of the function
        emitFunctionBody(func);

        m_writer->dedent();
        m_writer->emit("}\n\n");
    }
    else
    {
        m_writer->emit(";\n\n");
    }
}

void CLikeSourceEmitter::emitParamTypeImpl(IRType* type, String const& name)
{
    // An `out` or `inout` parameter will have been
    // encoded as a parameter of pointer type, so
    // we need to decode that here.
    //
    if( auto outType = as<IROutType>(type))
    {
        m_writer->emit("out ");
        type = outType->getValueType();
    }
    else if( auto inOutType = as<IRInOutType>(type))
    {
        m_writer->emit("inout ");
        type = inOutType->getValueType();
    }
    else if( auto refType = as<IRRefType>(type))
    {
        // Note: There is no HLSL/GLSL equivalent for by-reference parameters,
        // so we don't actually expect to encounter these in user code.
        m_writer->emit("inout ");
        type = refType->getValueType();
    }

    emitType(type, name);
}

void CLikeSourceEmitter::emitFuncDecl(IRFunc* func)
{
    auto name = getName(func);
    emitFuncDecl(func, name);
}

void CLikeSourceEmitter::emitFuncDecl(IRFunc* func, const String& name)
{
    // We don't want to emit declarations for operations
    // that only appear in the IR as stand-ins for built-in
    // operations on that target.
    if (isTargetIntrinsic(func))
        return;

    // Finally, don't emit a declaration for an entry point,
    // because it might need meta-data attributes attached
    // to it, and the HLSL compiler will get upset if the
    // forward declaration doesn't *also* have those
    // attributes.
    if(asEntryPoint(func))
        return;


    // A function declaration doesn't have any IR basic blocks,
    // and as a result it *also* doesn't have the IR `param` instructions,
    // so we need to emit a declaration entirely from the type.

    auto funcType = func->getDataType();
    auto resultType = func->getResultType();

    emitFuncDecorations(func);
    emitType(resultType, name);

    m_writer->emit("(");
    auto paramCount = funcType->getParamCount();
    for(UInt pp = 0; pp < paramCount; ++pp)
    {
        if(pp != 0)
            m_writer->emit(", ");

        String paramName;
        paramName.append("_");
        paramName.append(Int32(pp));
        auto paramType = funcType->getParamType(pp);

        emitParamType(paramType, paramName);
    }
    m_writer->emit(");\n\n");
}

IREntryPointLayout* CLikeSourceEmitter::getEntryPointLayout(IRFunc* func)
{
    if( auto layoutDecoration = func->findDecoration<IRLayoutDecoration>() )
    {
        return as<IREntryPointLayout>(layoutDecoration->getLayout());
    }
    return nullptr;
}

IREntryPointLayout* CLikeSourceEmitter::asEntryPoint(IRFunc* func)
{
    if (auto layoutDecoration = func->findDecoration<IRLayoutDecoration>())
    {
        if (auto entryPointLayout = as<IREntryPointLayout>(layoutDecoration->getLayout()))
        {
            return entryPointLayout;
        }
    }

    return nullptr;
}

bool CLikeSourceEmitter::isTargetIntrinsic(IRFunc* func)
{
    // A function is a target intrinsic if and only if
    // it has a suitable decoration marking it as a
    // target intrinsic for the current compilation target.
    //
    return findBestTargetIntrinsicDecoration(func) != nullptr;
}

void CLikeSourceEmitter::emitFunc(IRFunc* func)
{
    // Target-intrinsic functions should never be emitted
    // even if they happen to have a body.
    //
    if (isTargetIntrinsic(func))
        return;


    if(!isDefinition(func))
    {
        // This is just a function declaration,
        // and so we want to emit it as such.
        //
        emitFuncDecl(func);
    }
    else
    {
        // The common case is that what we
        // have is just an ordinary function,
        // and we can emit it as such.
        //
        emitSimpleFunc(func);
    }
}

void CLikeSourceEmitter::emitFuncDecorationsImpl(IRFunc* func)
{
    for(auto decoration : func->getDecorations())
    {
        emitFuncDecorationImpl(decoration);
    }
}


void CLikeSourceEmitter::emitStruct(IRStructType* structType)
{
    // If the selected `struct` type is actually an intrinsic
    // on our target, then we don't want to emit anything at all.
    if(auto intrinsicDecoration = findBestTargetIntrinsicDecoration(structType))
    {
        return;
    }

    m_writer->emit("struct ");

    emitPostKeywordTypeAttributes(structType);

    m_writer->emit(getName(structType));

    emitStructDeclarationsBlock(structType);
    m_writer->emit(";\n\n");
}

void CLikeSourceEmitter::emitStructDeclarationsBlock(IRStructType* structType)
{
    m_writer->emit("\n{\n");
    m_writer->indent();

    for(auto ff : structType->getFields())
    {
        auto fieldKey = ff->getKey();
        auto fieldType = ff->getFieldType();

        // Filter out fields with `void` type that might
        // have been introduced by legalization.
        if(as<IRVoidType>(fieldType))
            continue;

        // Note: GLSL doesn't support interpolation modifiers on `struct` fields
        if( getSourceLanguage() != SourceLanguage::GLSL )
        {
            emitInterpolationModifiers(fieldKey, fieldType, nullptr);
        }

        emitType(fieldType, getName(fieldKey));
        emitSemantics(fieldKey);
        m_writer->emit(";\n");
    }

    m_writer->dedent();
    m_writer->emit("}");
}

void CLikeSourceEmitter::emitClass(IRClassType* classType)
{
    // If the selected `class` type is actually an intrinsic
    // on our target, then we don't want to emit anything at all.
    if (auto intrinsicDecoration = findBestTargetIntrinsicDecoration(classType))
    {
        return;
    }
    List<IRWitnessTable*> comWitnessTables;
    for (auto child : classType->getDecorations())
    {
        if (auto decoration = as<IRCOMWitnessDecoration>(child))
        {
            comWitnessTables.add(cast<IRWitnessTable>(decoration->getWitnessTable()));
        }
    }
    m_writer->emit("class ");

    emitPostKeywordTypeAttributes(classType);

    m_writer->emit(getName(classType));
    if (comWitnessTables.getCount() == 0)
    {
        m_writer->emit(" : public RefObject");
    }
    else
    {
        m_writer->emit(" : public ComObject");
        for (auto wt : comWitnessTables)
        {
            m_writer->emit(", public ");
            m_writer->emit(getName(wt->getConformanceType()));
        }
    }
    m_writer->emit("\n{\n");
    m_writer->emit("public:\n");
    m_writer->indent();

    if (comWitnessTables.getCount())
    {
        m_writer->emit("SLANG_COM_OBJECT_IUNKNOWN_ALL\n");
        m_writer->emit("void* getInterface(const Guid & uuid)\n{\n");
        m_writer->indent();
        m_writer->emit("if (uuid == ISlangUnknown::getTypeGuid()) return static_cast<ISlangUnknown*>(this);\n");
        for (auto wt : comWitnessTables)
        {
            auto interfaceName = getName(wt->getConformanceType());
            m_writer->emit("if (uuid == ");
            m_writer->emit(interfaceName);
            m_writer->emit("::getTypeGuid())\n");
            m_writer->indent();
            m_writer->emit("return static_cast<");
            m_writer->emit(interfaceName);
            m_writer->emit("*>(this);\n");
            m_writer->dedent();
        }
        m_writer->emit("return nullptr;\n");
        m_writer->dedent();
        m_writer->emit("}\n");
    }

    for (auto ff : classType->getFields())
    {
        auto fieldKey = ff->getKey();
        auto fieldType = ff->getFieldType();

        // Filter out fields with `void` type that might
        // have been introduced by legalization.
        if (as<IRVoidType>(fieldType))
            continue;

        emitInterpolationModifiers(fieldKey, fieldType, nullptr);

        emitType(fieldType, getName(fieldKey));
        emitSemantics(fieldKey);
        m_writer->emit(";\n");
    }

    // Emit COM method declarations.
    for (auto wt : comWitnessTables)
    {
        for (auto wtEntry : wt->getChildren())
        {
            auto req = as<IRWitnessTableEntry>(wtEntry);
            if (!req) continue;
            auto func = as<IRFunc>(req->getSatisfyingVal());
            if (!func) continue;
            m_writer->emit("virtual SLANG_NO_THROW ");
            emitType(func->getResultType(), "SLANG_MCALL " + getName(req->getRequirementKey()));
            m_writer->emit("(");
            auto param = func->getFirstParam();
            param = param->getNextParam();
            for (; param; param = param->getNextParam())
            {
                emitParamType(param->getFullType(), getName(param));
            }
            m_writer->emit(") override;\n");
        }
    }

    m_writer->dedent();
    m_writer->emit("};\n\n");
}

void CLikeSourceEmitter::emitInterpolationModifiers(IRInst* varInst, IRType* valueType, IRVarLayout* layout)
{
    emitInterpolationModifiersImpl(varInst, valueType, layout);
}

void CLikeSourceEmitter::emitMeshOutputModifiers(IRInst* varInst)
{
    emitMeshOutputModifiersImpl(varInst);
}

    /// Emit modifiers that should apply even for a declaration of an SSA temporary.
void CLikeSourceEmitter::emitTempModifiers(IRInst* temp)
{
    if(temp->findDecoration<IRPreciseDecoration>())
    {
        m_writer->emit("precise ");
    }
}

void CLikeSourceEmitter::emitVarModifiers(IRVarLayout* layout, IRInst* varDecl, IRType* varType)
{
    // TODO(JS): We could push all of this onto the target impls, and then not need so many virtual hooks.
    emitVarDecorationsImpl(varDecl);

    emitTempModifiers(varDecl);

    if (!layout)
        return;

    emitMatrixLayoutModifiersImpl(layout);

    // Target specific modifier output
    emitImageFormatModifierImpl(varDecl, varType);

    if(layout->usesResourceKind(LayoutResourceKind::VaryingInput)
        || layout->usesResourceKind(LayoutResourceKind::VaryingOutput))
    {
        emitInterpolationModifiers(varDecl, varType, layout);
        emitMeshOutputModifiers(varDecl);
    }

    // Output target specific qualifiers
    emitLayoutQualifiersImpl(layout);
}

void CLikeSourceEmitter::emitArrayBrackets(IRType* inType)
{
    // A declaration may require zero, one, or
    // more array brackets. When writing out array
    // brackets from left to right, they represent
    // the structure of the type from the "outside"
    // in (that is, if we have a 5-element array of
    // 3-element arrays we should output `[5][3]`),
    // because of C-style declarator rules.
    //
    // This conveniently means that we can print
    // out all the array brackets with a looping
    // rather than a recursive structure.
    //
    // We will peel the input type like an onion,
    // looking at one layer at a time until we
    // reach a non-array type in the middle.
    //
    IRType* type = inType;
    for(;;)
    {
        if(auto arrayType = as<IRArrayType>(type))
        {
            m_writer->emit("[");
            emitVal(arrayType->getElementCount(), getInfo(EmitOp::General));
            m_writer->emit("]");

            // Continue looping on the next layer in.
            //
            type = arrayType->getElementType();
        }
        else if(auto unsizedArrayType = as<IRUnsizedArrayType>(type))
        {
            m_writer->emit("[]");

            // Continue looping on the next layer in.
            //
            type = unsizedArrayType->getElementType();
        }
        else
        {
            // This layer wasn't an array, so we are done.
            //
            return;
        }
    }
}

void CLikeSourceEmitter::emitParameterGroup(IRGlobalParam* varDecl, IRUniformParameterGroupType* type)
{
    emitParameterGroupImpl(varDecl, type);
}

void CLikeSourceEmitter::emitVar(IRVar* varDecl)
{
    auto allocatedType = varDecl->getDataType();
    auto varType = allocatedType->getValueType();
//        auto addressSpace = allocatedType->getAddressSpace();

#if 0
    switch( varType->op )
    {
    case kIROp_ConstantBufferType:
    case kIROp_TextureBufferType:
        emitIRParameterGroup(ctx, varDecl, (IRUniformBufferType*) varType);
        return;

    default:
        break;
    }
#endif

    // Need to emit appropriate modifiers here.

    auto layout = getVarLayout(varDecl);

    emitVarModifiers(layout, varDecl, varType);

#if 0
    switch (addressSpace)
    {
    default:
        break;

    case kIRAddressSpace_GroupShared:
        emit("groupshared ");
        break;
    }
#endif
    emitRateQualifiers(varDecl);

    emitType(varType, getName(varDecl));

    emitSemantics(varDecl);

    emitLayoutSemantics(varDecl);

    m_writer->emit(";\n");
}

void CLikeSourceEmitter::emitGlobalVar(IRGlobalVar* varDecl)
{
    auto allocatedType = varDecl->getDataType();
    auto varType = allocatedType->getValueType();

    String initFuncName;
    if (varDecl->getFirstBlock())
    {
        emitFunctionPreambleImpl(varDecl);

        // A global variable with code means it has an initializer
        // associated with it. Eventually we'd like to emit that
        // initializer directly as an expression here, but for
        // now we'll emit it as a separate function.

        initFuncName = getName(varDecl);
        initFuncName.append("_init");

        m_writer->emit("\n");
        emitType(varType, initFuncName);
        m_writer->emit("()\n{\n");
        m_writer->indent();
        emitFunctionBody(varDecl);
        m_writer->dedent();
        m_writer->emit("}\n");
    }

    // An ordinary global variable won't have a layout
    // associated with it, since it is not a shader
    // parameter.
    //
    SLANG_ASSERT(!getVarLayout(varDecl));
    IRVarLayout* layout = nullptr;

    // An ordinary global variable (which is not a
    // shader parameter) may need special
    // modifiers to indicate it as such.
    //
    switch (getSourceLanguage())
    {
    case SourceLanguage::HLSL:
        // HLSL requires the `static` modifier on any
        // global variables; otherwise they are assumed
        // to be uniforms.
        m_writer->emit("static ");
        break;

    default:
        break;
    }

    emitVarModifiers(layout, varDecl, varType);

    emitRateQualifiers(varDecl);
    emitType(varType, getName(varDecl));

    // TODO: These shouldn't be needed for ordinary
    // global variables.
    //
    emitSemantics(varDecl);
    emitLayoutSemantics(varDecl);

    if (varDecl->getFirstBlock())
    {
        m_writer->emit(" = ");
        m_writer->emit(initFuncName);
        m_writer->emit("()");
    }

    m_writer->emit(";\n\n");
}

void CLikeSourceEmitter::emitGlobalParam(IRGlobalParam* varDecl)
{
    auto rawType = varDecl->getDataType();

    auto varType = rawType;
    if( auto outType = as<IROutTypeBase>(varType) )
    {
        varType = outType->getValueType();
    }
    if (as<IRVoidType>(varType))
        return;

    // When a global shader parameter represents a "parameter group"
    // (either a constant buffer or a parameter block with non-resource
    // data in it), we will prefer to emit it as an ordinary `cbuffer`
    // declaration or `uniform` block, even when emitting HLSL for
    // D3D profiles that support the explicit `ConstantBuffer<T>` type.
    //
    // Alternatively, we could make this choice based on profile, and
    // prefer `ConstantBuffer<T>` on profiles that support it and/or when
    // the input code used that syntax.
    //
    if (auto paramBlockType = as<IRUniformParameterGroupType>(varType))
    {
        emitParameterGroup(varDecl, paramBlockType);
        return;
    }

    // Try target specific ways to emit.
    if (tryEmitGlobalParamImpl(varDecl, varType))
    {
        return;
    }

    // Need to emit appropriate modifiers here.

    // We expect/require all shader parameters to
    // have some kind of layout information associated with them.
    //
    auto layout = getVarLayout(varDecl);
    SLANG_ASSERT(layout);

    emitVarModifiers(layout, varDecl, varType);

    emitRateQualifiers(varDecl);
    emitType(varType, getName(varDecl));

    emitSemantics(varDecl);

    emitLayoutSemantics(varDecl);

    // A shader parameter cannot have an initializer,
    // so we do need to consider emitting one here.

    m_writer->emit(";\n\n");
}

void CLikeSourceEmitter::emitGlobalInst(IRInst* inst)
{
    emitGlobalInstImpl(inst);
}

static bool _shouldSkipFuncEmit(IRInst* func)
{
    // Skip emitting a func if it is a COM interface wrapper implementation and used
    // only by the witness table. We will emit this func differently than normal funcs
    // and this is handled by `emitComWitnessTable`.

    if (func->hasMoreThanOneUse()) return false;
    if (func->firstUse)
    {
        if (auto entry = as<IRWitnessTableEntry>(func->firstUse->getUser()))
        {
            if (auto table = as<IRWitnessTable>(entry->getParent()))
            {
                if (auto interfaceType = table->getConformanceType())
                {
                    if (interfaceType->findDecoration<IRComInterfaceDecoration>())
                    {
                        return true;
                    }
                }
            }
        }
    }
    return false;
}

void CLikeSourceEmitter::emitGlobalInstImpl(IRInst* inst)
{
    m_writer->advanceToSourceLocation(inst->sourceLoc);

    switch(inst->getOp())
    {
    case kIROp_GlobalHashedStringLiterals:
        /* Don't need to to output anything for this instruction - it's used for reflecting string literals that
        are hashed with 'getStringHash' */
        break;

    case kIROp_InterfaceRequirementEntry:
        // Don't emit anything for interface requirement at global level.
        // They are handled in `emitInterface`.
        break;

    case kIROp_Func:
        if (!_shouldSkipFuncEmit(inst))
        {
            emitFunc((IRFunc*) inst);
        }
        break;

    case kIROp_GlobalVar:
        emitGlobalVar((IRGlobalVar*) inst);
        break;

    case kIROp_GlobalParam:
        emitGlobalParam((IRGlobalParam*) inst);
        break;

    case kIROp_Var:
        emitVar((IRVar*) inst);
        break;

    case kIROp_StructType:
        emitStruct(cast<IRStructType>(inst));
        break;
    case kIROp_ClassType:
        emitClass(cast<IRClassType>(inst));
        break;
    case kIROp_InterfaceType:
        emitInterface(cast<IRInterfaceType>(inst));
        break;

    case kIROp_WitnessTable:
        emitWitnessTable(cast<IRWitnessTable>(inst));
        break;

    case kIROp_RTTIObject:
        emitRTTIObject(cast<IRRTTIObject>(inst));
        break;

    default:
        // We have an "ordinary" instruction at the global
        // scope, and we should therefore emit it using the
        // rules for other ordinary instructions.
        //
        // Such an instruction represents (part of) the value
        // for a global constants.
        //
        emitInst(inst);
        break;
    }
}

void CLikeSourceEmitter::ensureInstOperand(ComputeEmitActionsContext* ctx, IRInst* inst, EmitAction::Level requiredLevel)
{
    if(!inst) return;

    if(inst->getParent() == ctx->moduleInst)
    {
        ensureGlobalInst(ctx, inst, requiredLevel);
    }
}

void CLikeSourceEmitter::ensureInstOperandsRec(ComputeEmitActionsContext* ctx, IRInst* inst)
{
    ensureInstOperand(ctx, inst->getFullType());

    UInt operandCount = inst->operandCount;
    auto requiredLevel = EmitAction::Definition;
    switch (inst->getOp())
    {
    case kIROp_NativePtrType:
        requiredLevel = EmitAction::ForwardDeclaration;
        break;
    case kIROp_LookupWitness:
    case kIROp_FieldExtract:
    case kIROp_FieldAddress:
    {
        auto opType = inst->getOperand(0)->getDataType();
        if (auto nativePtrType = as<IRNativePtrType>(opType))
        {
            ensureInstOperand(ctx, nativePtrType->getValueType(), requiredLevel);
        }
        break;
    }
    default:
        break;
    }

    if (auto comWitnessDecoration = as<IRCOMWitnessDecoration>(inst))
    {
        // A COMWitnessDecoration marks the interface inheritance of a class.
        // We need to make sure the implemented interface is emited before the class.
        // The witness table itself doesn't matter.
        if (auto witnessTable = as<IRWitnessTable>(comWitnessDecoration->getWitnessTable()))
        {
            ensureInstOperand(ctx, witnessTable->getConformanceType(), requiredLevel);
        }
        requiredLevel = EmitAction::ForwardDeclaration;
    }

    for(UInt ii = 0; ii < operandCount; ++ii)
    {
        // TODO: there are some special cases we can add here,
        // to avoid outputting full definitions in cases that
        // can get by with forward declarations.
        //
        // For example, true pointer types should (in principle)
        // only need the type they point to to be forward-declared.
        // Similarly, a `call` instruction only needs the callee
        // to be forward-declared, etc.

        ensureInstOperand(ctx, inst->getOperand(ii), requiredLevel);
    }

    for(auto child : inst->getDecorationsAndChildren())
    {
        ensureInstOperandsRec(ctx, child);
    }
}

void CLikeSourceEmitter::ensureGlobalInst(ComputeEmitActionsContext* ctx, IRInst* inst, EmitAction::Level requiredLevel)
{
    // Skip certain instructions that don't affect output.
    switch(inst->getOp())
    {
    case kIROp_Generic:
        return;
    case kIROp_ThisType:
        return;
    default:
        break;
    }
    if (as<IRBasicType>(inst))
        return;

    // Certain inst ops will always emit as definition.
    switch (inst->getOp())
    {
    case kIROp_NativePtrType:
        // Pointer type will have their value type emited as forward declaration,
        // but the pointer type itself should be considered emitted as definition.
        requiredLevel = EmitAction::Level::Definition;
        break;
    default:
        break;
    }

    // Have we already processed this instruction?
    EmitAction::Level existingLevel;
    if(ctx->mapInstToLevel.TryGetValue(inst, existingLevel))
    {
        // If we've already emitted it suitably,
        // then don't worry about it.
        if(existingLevel >= requiredLevel)
            return;
    }

    EmitAction action;
    action.level = requiredLevel;
    action.inst = inst;

    if(requiredLevel == EmitAction::Level::Definition)
    {
        if(ctx->openInsts.Contains(inst))
        {
            SLANG_UNEXPECTED("circularity during codegen");
            return;
        }

        ctx->openInsts.Add(inst);

        ensureInstOperandsRec(ctx, inst);

        ctx->openInsts.Remove(inst);
    }

    ctx->mapInstToLevel[inst] = requiredLevel;

    // Skip instructions that don't correspond to an independent entity in output.
    switch (inst->getOp())
    {
    case kIROp_InterfaceRequirementEntry:
    {
        return;
    }

    default:
        break;
    }
    ctx->actions->add(action);
}

void CLikeSourceEmitter::computeEmitActions(IRModule* module, List<EmitAction>& ioActions)
{
    ComputeEmitActionsContext ctx;
    ctx.moduleInst = module->getModuleInst();
    ctx.actions = &ioActions;

    for(auto inst : module->getGlobalInsts())
    {
        if( as<IRType>(inst) )
        {
            // Don't emit a type unless it is actually used or is marked public.
            if (!inst->findDecoration<IRPublicDecoration>())
                continue;
        }

        ensureGlobalInst(&ctx, inst, EmitAction::Level::Definition);
    }
}

void CLikeSourceEmitter::emitForwardDeclaration(IRInst* inst)
{
    switch (inst->getOp())
    {
    case kIROp_Func:
        emitFuncDecl(cast<IRFunc>(inst));
        break;
    case kIROp_StructType:
        m_writer->emit("struct ");
        m_writer->emit(getName(inst));
        m_writer->emit(";\n");
        break;
    case kIROp_InterfaceType:
    {
        if (inst->findDecoration<IRComInterfaceDecoration>())
        {
            m_writer->emit("struct ");
            m_writer->emit(getName(inst));
            m_writer->emit(";\n");
        }
        break;
    }
    default:
        SLANG_UNREACHABLE("emit forward declaration");
    }
}

void CLikeSourceEmitter::executeEmitActions(List<EmitAction> const& actions)
{
    for(auto action : actions)
    {
        switch(action.level)
        {
        case EmitAction::Level::ForwardDeclaration:
            emitForwardDeclaration(action.inst);
            break;

        case EmitAction::Level::Definition:
            emitGlobalInst(action.inst);
            break;
        }
    }
}

void CLikeSourceEmitter::emitModuleImpl(IRModule* module, DiagnosticSink* sink)
{
    // The IR will usually come in an order that respects
    // dependencies between global declarations, but this
    // isn't guaranteed, so we need to be careful about
    // the order in which we emit things.

    SLANG_UNUSED(sink);

    List<EmitAction> actions;

    computeEmitActions(module, actions);
    executeEmitActions(actions);
}

} // namespace Slang