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
|
// lower.cpp
#include "lower-to-ir.h"
#include "../../slang.h"
#include "ir.h"
#include "ir-insts.h"
#include "mangle.h"
#include "type-layout.h"
#include "visitor.h"
namespace Slang
{
// This file implements lowering of the Slang AST to a simpler SSA
// intermediate representation.
//
// IR is generated in a context (`IRGenContext`), which tracks the current
// location in the IR where code should be emitted (e.g., what basic
// block to add instructions to). Lowering a statement will emit some
// number of instructions to the context, and possibly change the
// insertion point (because of control flow).
//
// When lowering an expression we have a more interesting challenge, for
// two main reasons:
//
// 1. There might be types that are representible in the AST, but which
// we don't want to support natively in the IR. An example is a `struct`
// type with both ordinary and resource-type members; we might want to
// split values with such a type into distinct values during lowering.
//
// 2. We need to handle the difference between l-value and r-value expressions,
// and in particular the fact that HLSL/Slang supports complicated sorts
// of l-values (e.g., `someVector.zxy` is an l-value, even though it can't
// be represented by a single pointer), and also allows l-values to appear
// in multiple contexts (not just the left-hand side of assignment, but
// also as an argument to match an `out` or `in out` parameter).
//
// Our solution to both of these problems is the same. Rather than having
// the lowering of an expression return a single IR-level value (`IRInst*`),
// we have it return a more complex type (`LoweredValInfo`) which can represent
// a wider range of conceptual "values" which might correspond to multiple IR-level
// values, and/or represent a pointer to an l-value rather than the r-value itself.
// We want to keep the representation of a `LoweringValInfo` relatively light
// - right now it is just a single pointer plus a "tag" to distinguish the cases.
//
// This means that cases that can't fit in a single pointer need a heap allocation
// to store their payload. For simplicity we represent all of these with a class
// hierarchy:
//
struct ExtendedValueInfo : RefObject
{};
// This case is used to indicate a value that is a reference
// to an AST-level subscript declaration.
//
struct SubscriptInfo : ExtendedValueInfo
{
DeclRef<SubscriptDecl> declRef;
};
// This case is used to indicate a reference to an AST-level
// subscript operation bound to particular arguments.
//
// For example in a case like this:
//
// RWStructuredBuffer<Foo> gBuffer;
// ... gBuffer[someIndex] ...
//
// the expression `gBuffer[someIndex]` will be lowered to
// a value that references `RWStructureBuffer<Foo>::operator[]`
// with arguments `(gBuffer, someIndex)`.
//
// Such a value can be an l-value, and depending on the context
// where it is used, can lower into a call to either the getter
// or setter operations of the subscript.
//
struct BoundSubscriptInfo : ExtendedValueInfo
{
DeclRef<SubscriptDecl> declRef;
RefPtr<Type> type;
List<IRValue*> args;
};
// Some cases of `ExtendedValueInfo` need to
// recursively contain `LoweredValInfo`s, and
// so we forward declare them here and fill
// them in later.
//
struct BoundMemberInfo;
struct SwizzledLValueInfo;
// This type is our core representation of lowered values.
// In the simple case, it just wraps an `IRInst*`.
// More complex cases, representing l-values or aggregate
// values are also supported.
struct LoweredValInfo
{
// Which of the cases of value are we looking at?
enum class Flavor
{
// No value (akin to a null pointer)
None,
// A simple IR value
Simple,
// An l-value reprsented as an IR
// pointer to the value
Ptr,
// A member declaration bound to a particular `this` value
BoundMember,
// A reference to an AST-level subscript operation
Subscript,
// An AST-level subscript operation bound to a particular
// object and arguments.
BoundSubscript,
// The result of applying swizzling to an l-value
SwizzledLValue,
};
union
{
IRValue* val;
ExtendedValueInfo* ext;
};
Flavor flavor;
LoweredValInfo()
{
flavor = Flavor::None;
val = nullptr;
}
static LoweredValInfo simple(IRValue* v)
{
LoweredValInfo info;
info.flavor = Flavor::Simple;
info.val = v;
return info;
}
static LoweredValInfo ptr(IRValue* v)
{
LoweredValInfo info;
info.flavor = Flavor::Ptr;
info.val = v;
return info;
}
static LoweredValInfo boundMember(
BoundMemberInfo* boundMemberInfo);
BoundMemberInfo* getBoundMemberInfo()
{
assert(flavor == Flavor::BoundMember);
return (BoundMemberInfo*)ext;
}
static LoweredValInfo subscript(
SubscriptInfo* subscriptInfo);
SubscriptInfo* getSubscriptInfo()
{
assert(flavor == Flavor::Subscript);
return (SubscriptInfo*)ext;
}
static LoweredValInfo boundSubscript(
BoundSubscriptInfo* boundSubscriptInfo);
BoundSubscriptInfo* getBoundSubscriptInfo()
{
assert(flavor == Flavor::BoundSubscript);
return (BoundSubscriptInfo*)ext;
}
static LoweredValInfo swizzledLValue(
SwizzledLValueInfo* extInfo);
SwizzledLValueInfo* getSwizzledLValueInfo()
{
assert(flavor == Flavor::SwizzledLValue);
return (SwizzledLValueInfo*)ext;
}
};
// Represents some declaration bound to a particular
// object. For example, if we had `obj.f` where `f`
// is a member function, we'd use a `BoundMemberInfo`
// to represnet this.
//
// Note: This case is largely avoided by special-casing
// in the handling of calls (like `obj.f(arg)`), but
// it is being left here as an example of what we might
// need/want to do in the long term.
struct BoundMemberInfo : ExtendedValueInfo
{
// The base object
LoweredValInfo base;
// The (AST-level) declaration reference.
DeclRef<Decl> declRef;
};
// Represents the result of a swizzle operation in
// an l-value context. A swizzle without duplicate
// elements is allowed as an l-value, even if the
// element are non-contiguous (`.xz`) or out of
// order (`.zxy`).
//
struct SwizzledLValueInfo : ExtendedValueInfo
{
// The type of the expression.
RefPtr<Type> type;
// The base expression (this should be an l-value)
LoweredValInfo base;
// The number of elements in the swizzle
UInt elementCount;
// THe indices for the elements being swizzled
UInt elementIndices[4];
};
LoweredValInfo LoweredValInfo::boundMember(
BoundMemberInfo* boundMemberInfo)
{
LoweredValInfo info;
info.flavor = Flavor::BoundMember;
info.ext = boundMemberInfo;
return info;
}
LoweredValInfo LoweredValInfo::subscript(
SubscriptInfo* subscriptInfo)
{
LoweredValInfo info;
info.flavor = Flavor::Subscript;
info.ext = subscriptInfo;
return info;
}
LoweredValInfo LoweredValInfo::boundSubscript(
BoundSubscriptInfo* boundSubscriptInfo)
{
LoweredValInfo info;
info.flavor = Flavor::BoundSubscript;
info.ext = boundSubscriptInfo;
return info;
}
LoweredValInfo LoweredValInfo::swizzledLValue(
SwizzledLValueInfo* extInfo)
{
LoweredValInfo info;
info.flavor = Flavor::SwizzledLValue;
info.ext = extInfo;
return info;
}
struct SharedIRGenContext
{
CompileRequest* compileRequest;
Dictionary<Decl*, LoweredValInfo> declValues;
// Arrays we keep around strictly for memory-management purposes:
// Any extended values created during lowering need
// to be cleaned up after the fact. We don't try
// to reference-count these along the way because
// they need to get stored into a `union` inside `LoweredValInfo`
List<RefPtr<ExtendedValueInfo>> extValues;
};
struct IRGenContext
{
SharedIRGenContext* shared;
IRBuilder* irBuilder;
// The value to use for any `this` expressions
// that appear in the current context.
//
// TODO: If we ever allow nesting of (non-static)
// types, then we may need to support references
// to an "outer `this`", and this representation
// might be insufficient.
LoweredValInfo thisVal;
Session* getSession()
{
return shared->compileRequest->mSession;
}
};
// Ensure that a version of the given declaration has been emitted to the IR
LoweredValInfo ensureDecl(
IRGenContext* context,
Decl* decl);
// Emit code as needed to construct a reference to the given declaration with
// any needed specializations in place.
LoweredValInfo emitDeclRef(
IRGenContext* context,
DeclRef<Decl> declRef);
IRValue* getSimpleVal(IRGenContext* context, LoweredValInfo lowered);
IROp getIntrinsicOp(
Decl* decl,
IntrinsicOpModifier* intrinsicOpMod)
{
if (int(intrinsicOpMod->op) != 0)
return intrinsicOpMod->op;
// No specified modifier? Then we need to look it up
// based on the name of the declaration...
auto name = decl->getName();
auto nameText = getText(name);
IROp op = findIROp(nameText.Buffer());
assert(op != kIROp_Invalid);
return op;
}
// Given a `LoweredValInfo` for something callable, along with a
// bunch of arguments, emit an appropriate call to it.
LoweredValInfo emitCallToVal(
IRGenContext* context,
IRType* type,
LoweredValInfo funcVal,
UInt argCount,
IRValue* const* args)
{
auto builder = context->irBuilder;
switch (funcVal.flavor)
{
case LoweredValInfo::Flavor::None:
default:
return LoweredValInfo::simple(
builder->emitCallInst(type, getSimpleVal(context, funcVal), argCount, args));
}
}
LoweredValInfo emitCompoundAssignOp(
IRGenContext* context,
IRType* type,
IROp op,
UInt argCount,
IRValue* const* args)
{
auto builder = context->irBuilder;
assert(argCount == 2);
auto leftPtr = args[0];
auto rightVal = args[1];
auto leftVal = builder->emitLoad(leftPtr);
IRValue* innerArgs[] = { leftVal, rightVal };
auto innerOp = builder->emitIntrinsicInst(type, op, 2, innerArgs);
builder->emitStore(leftPtr, innerOp);
return LoweredValInfo::ptr(leftPtr);
}
IRValue* getOneValOfType(
IRGenContext* context,
IRType* type)
{
if (auto basicType = dynamic_cast<BasicExpressionType*>(type))
{
switch (basicType->baseType)
{
case BaseType::Int:
case BaseType::UInt:
case BaseType::UInt64:
return context->irBuilder->getIntValue(type, 1);
case BaseType::Float:
case BaseType::Double:
return context->irBuilder->getFloatValue(type, 1.0);
default:
break;
}
}
// TODO: should make sure to handle vector and matrix types here
SLANG_UNEXPECTED("inc/dec type");
return nullptr;
}
LoweredValInfo emitPreOp(
IRGenContext* context,
IRType* type,
IROp op,
UInt argCount,
IRValue* const* args)
{
auto builder = context->irBuilder;
assert(argCount == 1);
auto argPtr = args[0];
auto preVal = builder->emitLoad(argPtr);
IRValue* oneVal = getOneValOfType(context, type);
IRValue* innerArgs[] = { preVal, oneVal };
auto innerOp = builder->emitIntrinsicInst(type, op, 2, innerArgs);
builder->emitStore(argPtr, innerOp);
return LoweredValInfo::simple(preVal);
}
LoweredValInfo emitPostOp(
IRGenContext* context,
IRType* type,
IROp op,
UInt argCount,
IRValue* const* args)
{
auto builder = context->irBuilder;
assert(argCount == 1);
auto argPtr = args[0];
auto preVal = builder->emitLoad(argPtr);
IRValue* oneVal = getOneValOfType(context, type);
IRValue* innerArgs[] = { preVal, oneVal };
auto innerOp = builder->emitIntrinsicInst(type, op, 2, innerArgs);
builder->emitStore(argPtr, innerOp);
return LoweredValInfo::ptr(argPtr);
}
// Emit a reference to a function, where we have concluded
// that the original AST referenced `funcDeclRef`. The
// optional expression `funcExpr` can provide additional
// detail that might modify how we go about looking up
// the actual value to call.
LoweredValInfo emitFuncRef(
IRGenContext* context,
DeclRef<Decl> funcDeclRef,
Expr* funcExpr)
{
if( !funcExpr )
{
return emitDeclRef(context, funcDeclRef);
}
// Let's look at the expression to see what additional
// information it gives us.
if(auto funcMemberExpr = dynamic_cast<MemberExpr*>(funcExpr))
{
auto baseExpr = funcMemberExpr->BaseExpression;
if(auto baseMemberExpr = baseExpr.As<MemberExpr>())
{
auto baseMemberDeclRef = baseMemberExpr->declRef;
if(auto baseConstraintDeclRef = baseMemberDeclRef.As<GenericTypeConstraintDecl>())
{
// We are calling a method "through" a generic type
// parameter that was constrained to some type.
// That means `funcDeclRef` is a reference to the method
// on the `interface` type (which doesn't actually have
// a body, so we don't want to emit or call it), and
// we actually want to perform a lookup step to
// find the corresponding member on our chosen type.
RefPtr<Type> type = funcExpr->type;
return LoweredValInfo::simple(context->irBuilder->emitLookupInterfaceMethodInst(
type,
baseMemberDeclRef,
funcDeclRef));
}
}
}
// We didn't trigger a special case, so just emit a reference
// to the function itself.
return emitDeclRef(context, funcDeclRef);
}
// Given a `DeclRef` for something callable, along with a bunch of
// arguments, emit an appropriate call to it.
LoweredValInfo emitCallToDeclRef(
IRGenContext* context,
IRType* type,
DeclRef<Decl> funcDeclRef,
Expr* funcExpr,
UInt argCount,
IRValue* const* args)
{
auto builder = context->irBuilder;
if (auto subscriptDeclRef = funcDeclRef.As<SubscriptDecl>())
{
// A reference to a subscript declaration is potentially a
// special case, if we have more than just a getter.
DeclRef<GetterDecl> getterDeclRef;
bool justAGetter = true;
for (auto accessorDeclRef : getMembersOfType<AccessorDecl>(subscriptDeclRef))
{
if (auto foundGetterDeclRef = accessorDeclRef.As<GetterDecl>())
{
getterDeclRef = foundGetterDeclRef;
}
else
{
justAGetter = false;
break;
}
}
if (!justAGetter)
{
// We can't perform an actual call right now, because
// this expression might appear in an r-value or l-value
// position (or *both* if it is being passed as an argument
// for an `in out` parameter!).
//
// Instead, we will construct a special-case value to
// represent the latent subscript operation (abstractly
// this is a reference to a storage location).
// The abstract storage location will need to include
// all the arguments being passed to the subscript operation.
RefPtr<BoundSubscriptInfo> boundSubscript = new BoundSubscriptInfo();
boundSubscript->declRef = subscriptDeclRef;
boundSubscript->type = type;
boundSubscript->args.AddRange(args, argCount);
context->shared->extValues.Add(boundSubscript);
return LoweredValInfo::boundSubscript(boundSubscript);
}
// Otherwise we are just call the getter, and so that
// is what we need to be emitting a call to...
if (getterDeclRef)
funcDeclRef = getterDeclRef;
}
auto funcDecl = funcDeclRef.getDecl();
if(auto intrinsicOpModifier = funcDecl->FindModifier<IntrinsicOpModifier>())
{
auto op = getIntrinsicOp(funcDecl, intrinsicOpModifier);
if (Int(op) < 0)
{
switch (op)
{
case kIRPseudoOp_Pos:
return LoweredValInfo::simple(args[0]);
#define CASE(COMPOUND, OP) \
case COMPOUND: return emitCompoundAssignOp(context, type, OP, argCount, args)
CASE(kIRPseudoOp_AddAssign, kIROp_Add);
CASE(kIRPseudoOp_SubAssign, kIROp_Sub);
CASE(kIRPseudoOp_MulAssign, kIROp_Mul);
CASE(kIRPseudoOp_DivAssign, kIROp_Div);
CASE(kIRPseudoOp_ModAssign, kIROp_Mod);
CASE(kIRPseudoOp_AndAssign, kIROp_BitAnd);
CASE(kIRPseudoOp_OrAssign, kIROp_BitOr);
CASE(kIRPseudoOp_XorAssign, kIROp_BitXor);
CASE(kIRPseudoOp_LshAssign, kIROp_Lsh);
CASE(kIRPseudoOp_RshAssign, kIROp_Rsh);
#undef CASE
#define CASE(COMPOUND, OP) \
case COMPOUND: return emitPreOp(context, type, OP, argCount, args)
CASE(kIRPseudoOp_PreInc, kIROp_Add);
CASE(kIRPseudoOp_PreDec, kIROp_Sub);
#undef CASE
#define CASE(COMPOUND, OP) \
case COMPOUND: return emitPostOp(context, type, OP, argCount, args)
CASE(kIRPseudoOp_PostInc, kIROp_Add);
CASE(kIRPseudoOp_PostDec, kIROp_Sub);
#undef CASE
default:
SLANG_UNIMPLEMENTED_X("IR pseudo-op");
break;
}
}
return LoweredValInfo::simple(builder->emitIntrinsicInst(
type,
op,
argCount,
args));
}
// TODO: handle target intrinsic modifier too...
if( auto ctorDeclRef = funcDeclRef.As<ConstructorDecl>() )
{
// HACK: we know all constructors are builtins for now,
// so we need to emit them as a call to the corresponding
// builtin operation.
//
// TODO: these should all either be intrinsic operations,
// or calls to library functions.
return LoweredValInfo::simple(builder->emitConstructorInst(type, argCount, args));
}
// Fallback case is to emit an actual call.
LoweredValInfo funcVal = emitFuncRef(context, funcDeclRef, funcExpr);
return emitCallToVal(context, type, funcVal, argCount, args);
}
LoweredValInfo emitCallToDeclRef(
IRGenContext* context,
IRType* type,
DeclRef<Decl> funcDeclRef,
Expr* funcExpr,
List<IRValue*> const& args)
{
return emitCallToDeclRef(context, type, funcDeclRef, funcExpr, args.Count(), args.Buffer());
}
IRValue* getSimpleVal(IRGenContext* context, LoweredValInfo lowered)
{
auto builder = context->irBuilder;
top:
switch(lowered.flavor)
{
case LoweredValInfo::Flavor::None:
return nullptr;
case LoweredValInfo::Flavor::Simple:
return lowered.val;
case LoweredValInfo::Flavor::Ptr:
return builder->emitLoad(lowered.val);
case LoweredValInfo::Flavor::BoundSubscript:
{
auto boundSubscriptInfo = lowered.getBoundSubscriptInfo();
for (auto getter : getMembersOfType<GetterDecl>(boundSubscriptInfo->declRef))
{
lowered = emitCallToDeclRef(
context,
boundSubscriptInfo->type,
getter,
nullptr,
boundSubscriptInfo->args);
goto top;
}
SLANG_UNEXPECTED("subscript had no getter");
return nullptr;
}
break;
case LoweredValInfo::Flavor::SwizzledLValue:
{
auto swizzleInfo = lowered.getSwizzledLValueInfo();
return builder->emitSwizzle(
swizzleInfo->type,
getSimpleVal(context, swizzleInfo->base),
swizzleInfo->elementCount,
swizzleInfo->elementIndices);
}
default:
SLANG_UNEXPECTED("unhandled value flavor");
return nullptr;
}
}
struct LoweredTypeInfo
{
enum class Flavor
{
None,
Simple,
};
RefPtr<IRType> type;
Flavor flavor;
LoweredTypeInfo()
{
flavor = Flavor::None;
}
LoweredTypeInfo(IRType* t)
{
flavor = Flavor::Simple;
type = t;
}
};
RefPtr<Type> getSimpleType(LoweredTypeInfo lowered)
{
switch(lowered.flavor)
{
case LoweredTypeInfo::Flavor::None:
return nullptr;
case LoweredTypeInfo::Flavor::Simple:
return lowered.type;
default:
SLANG_UNEXPECTED("unhandled value flavor");
return nullptr;
}
}
LoweredValInfo lowerVal(
IRGenContext* context,
Val* val);
IRValue* lowerSimpleVal(
IRGenContext* context,
Val* val)
{
auto lowered = lowerVal(context, val);
return getSimpleVal(context, lowered);
}
LoweredTypeInfo lowerType(
IRGenContext* context,
Type* type);
static LoweredTypeInfo lowerType(
IRGenContext* context,
QualType const& type)
{
return lowerType(context, type.type);
}
// Lower a type and expect the result to be simple
RefPtr<Type> lowerSimpleType(
IRGenContext* context,
Type* type)
{
auto lowered = lowerType(context, type);
return getSimpleType(lowered);
}
RefPtr<Type> lowerSimpleType(
IRGenContext* context,
QualType const& type)
{
auto lowered = lowerType(context, type);
return getSimpleType(lowered);
}
LoweredValInfo lowerLValueExpr(
IRGenContext* context,
Expr* expr);
LoweredValInfo lowerRValueExpr(
IRGenContext* context,
Expr* expr);
void assign(
IRGenContext* context,
LoweredValInfo const& left,
LoweredValInfo const& right);
void lowerStmt(
IRGenContext* context,
Stmt* stmt);
LoweredValInfo lowerDecl(
IRGenContext* context,
DeclBase* decl);
IRType* getIntType(
IRGenContext* context)
{
return context->getSession()->getBuiltinType(BaseType::Int);
}
// Get a pointer type to the given element type
RefPtr<PtrType> getPtrType(
IRGenContext* context,
IRType* valueType)
{
return context->getSession()->getPtrType(valueType);
}
RefPtr<IRFuncType> getFuncType(
IRGenContext* context,
UInt paramCount,
RefPtr<IRType> const* paramTypes,
IRType* resultType)
{
RefPtr<FuncType> funcType = new FuncType();
funcType->setSession(context->getSession());
funcType->resultType = resultType;
for (UInt pp = 0; pp < paramCount; ++pp)
{
funcType->paramTypes.Add(paramTypes[pp]);
}
return funcType;
}
//
struct ValLoweringVisitor : ValVisitor<ValLoweringVisitor, LoweredValInfo, LoweredTypeInfo>
{
IRGenContext* context;
IRBuilder* getBuilder() { return context->irBuilder; }
LoweredValInfo visitVal(Val* val)
{
SLANG_UNIMPLEMENTED_X("value lowering");
}
LoweredValInfo visitConstantIntVal(ConstantIntVal* val)
{
// TODO: it is a bit messy here that the `ConstantIntVal` representation
// has no notion of a *type* associated with the value...
auto type = getIntType(context);
return LoweredValInfo::simple(getBuilder()->getIntValue(type, val->value));
}
LoweredTypeInfo visitType(Type* type)
{
// TODO(tfoley): Now that we use the AST types directly in the IR, there
// isn't much to do in the "lowering" step. Still, there might be cases
// where certain kinds of legalization need to take place, so this
// visitor setup might still be needed in the long run.
return LoweredTypeInfo(type);
// SLANG_UNIMPLEMENTED_X("type lowering");
}
LoweredTypeInfo visitFuncType(FuncType* type)
{
return LoweredTypeInfo(type);
}
void addGenericArgs(List<IRValue*>* ioArgs, DeclRefBase declRef)
{
auto subs = declRef.substitutions;
while(subs)
{
for(auto aa : subs->args)
{
(*ioArgs).Add(getSimpleVal(context, lowerVal(context, aa)));
}
subs = subs->outer;
}
}
LoweredTypeInfo visitDeclRefType(DeclRefType* type)
{
// If the type in question comes from the module we are
// trying to lower, then we need to make sure to
// emit everything relevant to its declaration.
// TODO: actually test what module the type is coming from.
lowerDecl(context, type->declRef);
return LoweredTypeInfo(type);
}
LoweredTypeInfo visitBasicExpressionType(BasicExpressionType* type)
{
return LoweredTypeInfo(type);
}
LoweredTypeInfo visitVectorExpressionType(VectorExpressionType* type)
{
return LoweredTypeInfo(type);
}
LoweredTypeInfo visitMatrixExpressionType(MatrixExpressionType* type)
{
return LoweredTypeInfo(type);
}
LoweredTypeInfo visitArrayExpressionType(ArrayExpressionType* type)
{
return LoweredTypeInfo(type);
}
LoweredTypeInfo visitIRBasicBlockType(IRBasicBlockType* type)
{
return LoweredTypeInfo(type);
}
};
LoweredValInfo lowerVal(
IRGenContext* context,
Val* val)
{
ValLoweringVisitor visitor;
visitor.context = context;
return visitor.dispatch(val);
}
LoweredTypeInfo lowerType(
IRGenContext* context,
Type* type)
{
ValLoweringVisitor visitor;
visitor.context = context;
return visitor.dispatchType(type);
}
#if 0
struct LoweringVisitor
: ExprVisitor<LoweringVisitor, LoweredExpr>
, StmtVisitor<LoweringVisitor, void>
, DeclVisitor<LoweringVisitor, LoweredDecl>
, ValVisitor<LoweringVisitor, RefPtr<Val>, RefPtr<Type>>
#endif
LoweredValInfo createVar(
IRGenContext* context,
RefPtr<Type> type,
Decl* decl = nullptr)
{
auto builder = context->irBuilder;
auto irAlloc = builder->emitVar(type);
if (decl)
{
builder->addHighLevelDeclDecoration(irAlloc, decl);
}
return LoweredValInfo::ptr(irAlloc);
}
void addArgs(
IRGenContext* context,
List<IRValue*>* ioArgs,
LoweredValInfo argInfo)
{
auto& args = *ioArgs;
switch( argInfo.flavor )
{
case LoweredValInfo::Flavor::Simple:
case LoweredValInfo::Flavor::Ptr:
case LoweredValInfo::Flavor::SwizzledLValue:
args.Add(getSimpleVal(context, argInfo));
break;
default:
SLANG_UNIMPLEMENTED_X("addArgs case");
break;
}
}
//
template<typename Derived>
struct ExprLoweringVisitorBase : ExprVisitor<Derived, LoweredValInfo>
{
IRGenContext* context;
IRBuilder* getBuilder() { return context->irBuilder; }
// Lower an expression that should have the same l-value-ness
// as the visitor itself.
LoweredValInfo lowerSubExpr(Expr* expr)
{
return this->dispatch(expr);
}
LoweredValInfo visitVarExpr(VarExpr* expr)
{
LoweredValInfo info = emitDeclRef(context, expr->declRef);
return info;
}
LoweredValInfo visitOverloadedExpr(OverloadedExpr* expr)
{
SLANG_UNEXPECTED("overloaded expressions should not occur in checked AST");
}
LoweredValInfo visitIndexExpr(IndexExpr* expr)
{
auto type = lowerType(context, expr->type);
auto baseVal = lowerSubExpr(expr->BaseExpression);
auto indexVal = getSimpleVal(context, lowerRValueExpr(context, expr->IndexExpression));
return subscriptValue(type, baseVal, indexVal);
}
LoweredValInfo visitThisExpr(ThisExpr* expr)
{
return context->thisVal;
}
LoweredValInfo visitMemberExpr(MemberExpr* expr)
{
auto loweredType = lowerType(context, expr->type);
auto loweredBase = lowerRValueExpr(context, expr->BaseExpression);
auto declRef = expr->declRef;
if (auto fieldDeclRef = declRef.As<StructField>())
{
// Okay, easy enough: we have a reference to a field of a struct type...
return extractField(loweredType, loweredBase, fieldDeclRef);
}
else if (auto callableDeclRef = declRef.As<CallableDecl>())
{
RefPtr<BoundMemberInfo> boundMemberInfo = new BoundMemberInfo();
boundMemberInfo->base = loweredBase;
boundMemberInfo->declRef = callableDeclRef;
return LoweredValInfo::boundMember(boundMemberInfo);
}
else if(auto constraintDeclRef = declRef.As<GenericTypeConstraintDecl>())
{
// The code is making use of a "witness" that a value of
// some generic type conforms to an interface.
//
// For now we will just emit the base expression as-is.
// TODO: we may need to insert an explicit instruction
// for a cast here (that could become a no-op later).
return loweredBase;
}
SLANG_UNIMPLEMENTED_X("codegen for subscript expression");
}
// We will always lower a dereference expression (`*ptr`)
// as an l-value, since that is the easiest way to handle it.
LoweredValInfo visitDerefExpr(DerefExpr* expr)
{
auto loweredType = lowerType(context, expr->type);
auto loweredBase = lowerRValueExpr(context, expr->base);
// TODO: handle tupel-type for `base`
// The type of the lowered base must by some kind of pointer,
// in order for a dereference to make senese, so we just
// need to extract the value type from that pointer here.
//
IRValue* loweredBaseVal = getSimpleVal(context, loweredBase);
RefPtr<Type> loweredBaseType = loweredBaseVal->getType();
if (loweredBaseType->As<PointerLikeType>()
|| loweredBaseType->As<PtrType>())
{
// Note that we do *not* perform an actual `load` operation
// here, but rather just use the pointer value to construct
// an appropriate `LoweredValInfo` representing the underlying
// dereference.
//
// This is important so that an expression like `&((*foo).bar)`
// (which is desugared from `&foo->bar`) can be handled; such
// an expression does *not* perform a dereference at runtime,
// and is just a bit of pointer math.
//
return LoweredValInfo::ptr(loweredBaseVal);
}
else
{
SLANG_UNIMPLEMENTED_X("codegen for deref expression");
return LoweredValInfo();
}
}
LoweredValInfo visitParenExpr(ParenExpr* expr)
{
return lowerSubExpr(expr->base);
}
LoweredValInfo visitInitializerListExpr(InitializerListExpr* expr)
{
SLANG_UNIMPLEMENTED_X("codegen for initializer list expression");
}
LoweredValInfo visitConstantExpr(ConstantExpr* expr)
{
auto type = lowerSimpleType(context, expr->type);
switch( expr->ConstType )
{
case ConstantExpr::ConstantType::Bool:
return LoweredValInfo::simple(context->irBuilder->getBoolValue(expr->integerValue != 0));
case ConstantExpr::ConstantType::Int:
return LoweredValInfo::simple(context->irBuilder->getIntValue(type, expr->integerValue));
case ConstantExpr::ConstantType::Float:
return LoweredValInfo::simple(context->irBuilder->getFloatValue(type, expr->floatingPointValue));
case ConstantExpr::ConstantType::String:
break;
}
SLANG_UNEXPECTED("unexpected constant type");
}
LoweredValInfo visitAggTypeCtorExpr(AggTypeCtorExpr* expr)
{
SLANG_UNIMPLEMENTED_X("codegen for aggregate type constructor expression");
}
// Add arguments that appeared directly in an argument list
// to the list of argument values for a call.
void addDirectCallArgs(
InvokeExpr* expr,
List<IRValue*>* ioArgs)
{
auto& irArgs = *ioArgs;
for( auto arg : expr->Arguments )
{
// TODO: Need to handle case of l-value arguments,
// when they are matched to `out` or `in out` parameters.
auto loweredArg = lowerRValueExpr(context, arg);
addArgs(context, ioArgs, loweredArg);
}
}
// After a call to a function with `out` or `in out`
// parameters, we may need to copy data back into
// the l-value locations used for output arguments.
//
// During lowering of the argument list, we build
// up a list of these "fixup" assignments that need
// to be performed.
struct OutArgumentFixup
{
LoweredValInfo dst;
LoweredValInfo src;
};
void addDirectCallArgs(
InvokeExpr* expr,
DeclRef<CallableDecl> funcDeclRef,
List<IRValue*>* ioArgs,
List<OutArgumentFixup>* ioFixups)
{
auto funcDecl = funcDeclRef.getDecl();
auto& args = expr->Arguments;
UInt argCount = expr->Arguments.Count();
UInt argIndex = 0;
for (auto paramDeclRef : getMembersOfType<ParamDecl>(funcDeclRef))
{
if (argIndex >= argCount)
{
// The remaining parameters must be defaulted...
break;
}
auto paramDecl = paramDeclRef.getDecl();
RefPtr<Type> paramType = lowerSimpleType(context, GetType(paramDeclRef));
auto argExpr = expr->Arguments[argIndex++];
if (paramDecl->HasModifier<OutModifier>()
|| paramDecl->HasModifier<InOutModifier>())
{
// This is a `out` or `inout` parameter, and so
// the argument must be lowered as an l-value.
LoweredValInfo loweredArg = lowerLValueExpr(context, argExpr);
// According to our "calling convention" we need to
// pass a pointer into the callee.
//
// A naive approach would be to just take the address
// of `loweredArg` above and pass it in, but that
// has two issues:
//
// 1. The l-value might not be something that has a single
// well-defined "address" (e.g., `foo.xzy`).
//
// 2. The l-value argument might actually alias some other
// storage that the callee will access (e.g., we are
// passing in a global variable, or two `out` parameters
// are being passed the same location in an array).
//
// In each of these cases, the safe option is to create
// a temporary variable to use for argument-passing,
// and then do copy-in/copy-out around the call.
LoweredValInfo tempVar = createVar(context, paramType);
// If the parameter is `in out` or `inout`, then we need
// to ensure that we pass in the original value stored
// in the argument, which we accomplish by assigning
// from the l-value to our temp.
if (paramDecl->HasModifier<InModifier>()
|| paramDecl->HasModifier<InOutModifier>())
{
assign(context, tempVar, loweredArg);
}
// Now we can pass the address of the temporary variable
// to the callee as the actual argument for the `in out`
assert(tempVar.flavor == LoweredValInfo::Flavor::Ptr);
(*ioArgs).Add(tempVar.val);
// Finally, after the call we will need
// to copy in the other direction: from our
// temp back to the original l-value.
OutArgumentFixup fixup;
fixup.src = tempVar;
fixup.dst = loweredArg;
(*ioFixups).Add(fixup);
}
else
{
// This is a pure input parameter, and so we will
// pass it as an r-value.
LoweredValInfo loweredArg = lowerRValueExpr(context, argExpr);
addArgs(context, ioArgs, loweredArg);
}
}
}
// Add arguments that appeared directly in an argument list
// to the list of argument values for a call.
void addDirectCallArgs(
InvokeExpr* expr,
DeclRef<Decl> funcDeclRef,
List<IRValue*>* ioArgs,
List<OutArgumentFixup>* ioFixups)
{
if (auto callableDeclRef = funcDeclRef.As<CallableDecl>())
{
addDirectCallArgs(expr, callableDeclRef, ioArgs, ioFixups);
}
else
{
SLANG_UNEXPECTED("shouldn't relaly happen");
addDirectCallArgs(expr, ioArgs);
}
}
void addFuncBaseArgs(
LoweredValInfo funcVal,
List<IRValue*>* ioArgs)
{
switch (funcVal.flavor)
{
default:
return;
}
}
void applyOutArgumentFixups(List<OutArgumentFixup> const& fixups)
{
for (auto fixup : fixups)
{
assign(context, fixup.dst, fixup.src);
}
}
struct ResolvedCallInfo
{
DeclRef<Decl> funcDeclRef;
Expr* baseExpr = nullptr;
};
// Try to resolve a the function expression for a call
// into a reference to a specific declaration, along
// with some contextual information about the declaration
// we are calling.
bool tryResolveDeclRefForCall(
RefPtr<Expr> funcExpr,
ResolvedCallInfo* outInfo)
{
// TODO: unwrap any "identity" expressions that might
// be wrapping the callee.
// First look to see if the expression references a
// declaration at all.
auto declRefExpr = funcExpr.As<DeclRefExpr>();
if(!declRefExpr)
return false;
// A little bit of future proofing here: if we ever
// allow higher-order functions, then we might be
// calling through a variable/field that has a function
// type, but is not itself a function.
// In such a case we should be careful to not statically
// resolve things.
//
if(auto callableDecl = dynamic_cast<CallableDecl*>(declRefExpr->declRef.getDecl()))
{
// Okay, the declaration is directly callable, so we can continue.
}
else
{
// The callee declaration isn't itself a callable (it must have
// a funciton type, though).
return false;
}
// Now we can look at the specific kinds of declaration references,
// and try to tease them apart.
if (auto memberFuncExpr = funcExpr.As<MemberExpr>())
{
outInfo->funcDeclRef = memberFuncExpr->declRef;
outInfo->baseExpr = memberFuncExpr->BaseExpression;
return true;
}
else if (auto staticMemberFuncExpr = funcExpr.As<StaticMemberExpr>())
{
outInfo->funcDeclRef = staticMemberFuncExpr->declRef;
return true;
}
else if (auto varExpr = funcExpr.As<VarExpr>())
{
outInfo->funcDeclRef = varExpr->declRef;
return true;
}
else
{
// Seems to be a case of declaration-reference we don't know about.
SLANG_UNEXPECTED("unknown declaration reference kind");
return false;
}
}
LoweredValInfo visitInvokeExpr(InvokeExpr* expr)
{
auto type = lowerSimpleType(context, expr->type);
// We are going to look at the syntactic form of
// the "function" expression, so that we can avoid
// a lot of complexity that would come from lowering
// it as a general expression first, and then trying
// to apply it. For example, given `obj.f(a,b)` we
// will try to detect that we are trying to compute
// something like `ObjType::f(obj, a, b)` (in pseudo-code),
// rather than trying to construct a meaningful
// intermediate value for `obj.f` first.
//
// Note that this doe not preclude having support
// for directly generating code from `obj.f` - it
// just may be that such usage is more complicated.
// Along the way, we may end up collecting additional
// arguments that will be part of the call.
List<IRValue*> irArgs;
// We will also collect "fixup" actions that need
// to be performed after teh call, in order to
// copy the final values for `out` parameters
// back to their arguments.
List<OutArgumentFixup> argFixups;
auto funcExpr = expr->FunctionExpr;
ResolvedCallInfo resolvedInfo;
if( tryResolveDeclRefForCall(funcExpr, &resolvedInfo) )
{
// In this case we know exaclty what declaration we
// are going to call, and so we can resolve things
// appropriately.
auto funcDeclRef = resolvedInfo.funcDeclRef;
auto baseExpr = resolvedInfo.baseExpr;
// First comes the `this` argument if we are calling
// a member function:
if( baseExpr )
{
auto loweredBaseVal = lowerRValueExpr(context, baseExpr);
addArgs(context, &irArgs, loweredBaseVal);
}
// Then we have the "direct" arguments to the call.
// These may include `out` and `inout` arguments that
// require "fixup" work on the other side.
//
addDirectCallArgs(expr, funcDeclRef, &irArgs, &argFixups);
auto result = emitCallToDeclRef(
context,
type,
funcDeclRef,
funcExpr,
irArgs);
applyOutArgumentFixups(argFixups);
return result;
}
// The default case is to assume that we just have
// an ordinary expression, and can lower it as such.
LoweredValInfo funcVal = lowerRValueExpr(context, expr->FunctionExpr);
// Now we add any direct arguments from the call expression itself.
addDirectCallArgs(expr, &irArgs);
// Delegate to the logic for invoking a value.
auto result = emitCallToVal(context, type, funcVal, irArgs.Count(), irArgs.Buffer());
// TODO: because of the nature of how the `emitCallToVal` case works
// right now, we don't have information on in/out parameters, and
// so we can't collect info to apply fixups.
//
// Once we have a better representation for function types, though,
// this should be fixable.
return result;
}
LoweredValInfo subscriptValue(
LoweredTypeInfo type,
LoweredValInfo baseVal,
IRValue* indexVal)
{
auto builder = getBuilder();
switch (baseVal.flavor)
{
case LoweredValInfo::Flavor::Simple:
return LoweredValInfo::simple(
builder->emitElementExtract(
getSimpleType(type),
getSimpleVal(context, baseVal),
indexVal));
case LoweredValInfo::Flavor::Ptr:
return LoweredValInfo::ptr(
builder->emitElementAddress(
getPtrType(context, getSimpleType(type)),
baseVal.val,
indexVal));
default:
SLANG_UNIMPLEMENTED_X("subscript expr");
return LoweredValInfo();
}
}
LoweredValInfo extractField(
LoweredTypeInfo fieldType,
LoweredValInfo base,
DeclRef<StructField> field)
{
switch (base.flavor)
{
default:
{
IRValue* irBase = getSimpleVal(context, base);
return LoweredValInfo::simple(
getBuilder()->emitFieldExtract(
getSimpleType(fieldType),
irBase,
getBuilder()->getDeclRefVal(field)));
}
break;
case LoweredValInfo::Flavor::Ptr:
{
// We are "extracting" a field from an lvalue address,
// which means we should just compute an lvalue
// representing the field address.
IRValue* irBasePtr = base.val;
return LoweredValInfo::ptr(
getBuilder()->emitFieldAddress(
getPtrType(context, getSimpleType(fieldType)),
irBasePtr,
getBuilder()->getDeclRefVal(field)));
}
break;
}
}
LoweredValInfo visitStaticMemberExpr(StaticMemberExpr* expr)
{
return emitDeclRef(context, expr->declRef);
}
LoweredValInfo visitSelectExpr(SelectExpr* expr)
{
SLANG_UNIMPLEMENTED_X("codegen for select expression");
}
LoweredValInfo visitGenericAppExpr(GenericAppExpr* expr)
{
SLANG_UNIMPLEMENTED_X("generic application expression during code generation");
}
LoweredValInfo visitSharedTypeExpr(SharedTypeExpr* expr)
{
SLANG_UNIMPLEMENTED_X("shared type expression during code generation");
}
LoweredValInfo visitAssignExpr(AssignExpr* expr)
{
// Because our representation of lowered "values"
// can encompass l-values explicitly, we can
// lower assignment easily. We just lower the left-
// and right-hand sides, and then peform an assignment
// based on the resulting values.
//
auto leftVal = lowerLValueExpr(context, expr->left);
auto rightVal = lowerRValueExpr(context, expr->right);
assign(context, leftVal, rightVal);
// The result value of the assignment expression is
// the value of the left-hand side (and it is expected
// to be an l-value).
return leftVal;
}
};
struct LValueExprLoweringVisitor : ExprLoweringVisitorBase<LValueExprLoweringVisitor>
{
// When visiting a swizzle expression in an l-value context,
// we need to construct a "sizzled l-value."
LoweredValInfo visitSwizzleExpr(SwizzleExpr* expr)
{
auto irType = lowerSimpleType(context, expr->type);
auto loweredBase = lowerRValueExpr(context, expr->base);
RefPtr<SwizzledLValueInfo> swizzledLValue = new SwizzledLValueInfo();
swizzledLValue->type = irType;
swizzledLValue->base = loweredBase;
UInt elementCount = (UInt)expr->elementCount;
swizzledLValue->elementCount = elementCount;
for (UInt ii = 0; ii < elementCount; ++ii)
{
swizzledLValue->elementIndices[ii] = (UInt) expr->elementIndices[ii];
}
context->shared->extValues.Add(swizzledLValue);
return LoweredValInfo::swizzledLValue(swizzledLValue);
}
};
struct RValueExprLoweringVisitor : ExprLoweringVisitorBase<RValueExprLoweringVisitor>
{
// A swizzle in an r-value context can save time by just
// emitting the swizzle instuctions directly.
LoweredValInfo visitSwizzleExpr(SwizzleExpr* expr)
{
auto irType = lowerSimpleType(context, expr->type);
auto irBase = getSimpleVal(context, lowerRValueExpr(context, expr->base));
auto builder = getBuilder();
auto irIntType = getIntType(context);
UInt elementCount = (UInt)expr->elementCount;
IRValue* irElementIndices[4];
for (UInt ii = 0; ii < elementCount; ++ii)
{
irElementIndices[ii] = builder->getIntValue(
irIntType,
(IRIntegerValue)expr->elementIndices[ii]);
}
auto irSwizzle = builder->emitSwizzle(
irType,
irBase,
elementCount,
&irElementIndices[0]);
return LoweredValInfo::simple(irSwizzle);
}
};
LoweredValInfo lowerLValueExpr(
IRGenContext* context,
Expr* expr)
{
LValueExprLoweringVisitor visitor;
visitor.context = context;
return visitor.dispatch(expr);
}
LoweredValInfo lowerRValueExpr(
IRGenContext* context,
Expr* expr)
{
RValueExprLoweringVisitor visitor;
visitor.context = context;
return visitor.dispatch(expr);
}
struct StmtLoweringVisitor : StmtVisitor<StmtLoweringVisitor>
{
IRGenContext* context;
IRBuilder* getBuilder() { return context->irBuilder; }
void visitStmt(Stmt* stmt)
{
SLANG_UNIMPLEMENTED_X("stmt catch-all");
}
// Create a basic block in the current function,
// so that it can be used for a label.
IRBlock* createBlock()
{
return getBuilder()->createBlock();
}
// Insert a block at the current location (ending
// the previous block with an unconditional jump
// if needed).
void insertBlock(IRBlock* block)
{
auto builder = getBuilder();
auto prevBlock = builder->block;
auto parentFunc = prevBlock->parentFunc;
// If the previous block doesn't already have
// a terminator instruction, then be sure to
// emit a branch to the new block.
if (!isTerminatorInst(prevBlock->lastInst))
{
builder->emitBranch(block);
}
parentFunc->addBlock(block);
builder->func = parentFunc;
builder->block = block;
}
// Start a new block at the current location.
// This is just the composition of `createBlock`
// and `insertBlock`.
IRBlock* startBlock()
{
auto block = createBlock();
insertBlock(block);
return block;
}
void visitIfStmt(IfStmt* stmt)
{
auto builder = getBuilder();
auto condExpr = stmt->Predicate;
auto thenStmt = stmt->PositiveStatement;
auto elseStmt = stmt->NegativeStatement;
auto irCond = getSimpleVal(context,
lowerRValueExpr(context, condExpr));
if (elseStmt)
{
auto thenBlock = createBlock();
auto elseBlock = createBlock();
auto afterBlock = createBlock();
builder->emitIfElse(irCond, thenBlock, elseBlock, afterBlock);
insertBlock(thenBlock);
lowerStmt(context, thenStmt);
builder->emitBranch(afterBlock);
insertBlock(elseBlock);
lowerStmt(context, elseStmt);
insertBlock(afterBlock);
}
else
{
auto thenBlock = createBlock();
auto afterBlock = createBlock();
builder->emitIf(irCond, thenBlock, afterBlock);
insertBlock(thenBlock);
lowerStmt(context, thenStmt);
insertBlock(afterBlock);
}
}
void addLoopDecorations(
IRInst* inst,
Stmt* stmt)
{
for(auto attr : stmt->GetModifiersOfType<HLSLUncheckedAttribute>())
{
// TODO: We should actually catch these attributes during
// semantic checking, so that they have a strongly-typed
// representation in the AST.
if(getText(attr->getName()) == "unroll")
{
auto decoration = getBuilder()->addDecoration<IRLoopControlDecoration>(inst);
decoration->mode = kIRLoopControl_Unroll;
}
}
}
void visitForStmt(ForStmt* stmt)
{
auto builder = getBuilder();
// The initializer clause for the statement
// can always safetly be emitted to the current block.
if (auto initStmt = stmt->InitialStatement)
{
lowerStmt(context, initStmt);
}
// We will create blocks for the various places
// we need to jump to inside the control flow,
// including the blocks that will be referenced
// by `continue` or `break` statements.
auto loopHead = createBlock();
auto bodyLabel = createBlock();
auto breakLabel = createBlock();
auto continueLabel = createBlock();
// TODO: register `loopHead` as the target for a
// `continue` statement.
// Emit the branch that will start out loop,
// and then insert the block for the head.
auto loopInst = builder->emitLoop(
loopHead,
breakLabel,
continueLabel);
addLoopDecorations(loopInst, stmt);
insertBlock(loopHead);
// Now that we are within the header block, we
// want to emit the expression for the loop condition:
if (auto condExpr = stmt->PredicateExpression)
{
auto irCondition = getSimpleVal(context,
lowerRValueExpr(context, stmt->PredicateExpression));
// Now we want to `break` if the loop condition is false.
builder->emitLoopTest(
irCondition,
bodyLabel,
breakLabel);
}
// Emit the body of the loop
insertBlock(bodyLabel);
lowerStmt(context, stmt->Statement);
// Insert the `continue` block
insertBlock(continueLabel);
if (auto incrExpr = stmt->SideEffectExpression)
{
lowerRValueExpr(context, incrExpr);
}
// At the end of the body we need to jump back to the top.
builder->emitBranch(loopHead);
// Finally we insert the label that a `break` will jump to
insertBlock(breakLabel);
}
void visitWhileStmt(WhileStmt* stmt)
{
// Generating IR for `while` statement is similar to a
// `for` statement, but without a lot of the complications.
auto builder = getBuilder();
// We will create blocks for the various places
// we need to jump to inside the control flow,
// including the blocks that will be referenced
// by `continue` or `break` statements.
auto loopHead = createBlock();
auto bodyLabel = createBlock();
auto breakLabel = createBlock();
// A `continue` inside a `while` loop always
// jumps to the head of hte loop.
auto continueLabel = loopHead;
// TODO: register appropriate targets for
// break/continue statements.
// Emit the branch that will start out loop,
// and then insert the block for the head.
auto loopInst = builder->emitLoop(
loopHead,
breakLabel,
continueLabel);
addLoopDecorations(loopInst, stmt);
insertBlock(loopHead);
// Now that we are within the header block, we
// want to emit the expression for the loop condition:
if (auto condExpr = stmt->Predicate)
{
auto irCondition = getSimpleVal(context,
lowerRValueExpr(context, condExpr));
// Now we want to `break` if the loop condition is false.
builder->emitLoopTest(
irCondition,
bodyLabel,
breakLabel);
}
// Emit the body of the loop
insertBlock(bodyLabel);
lowerStmt(context, stmt->Statement);
// At the end of the body we need to jump back to the top.
builder->emitBranch(loopHead);
// Finally we insert the label that a `break` will jump to
insertBlock(breakLabel);
}
void visitExpressionStmt(ExpressionStmt* stmt)
{
// The statement evaluates an expression
// (for side effects, one assumes) and then
// discards the result. As such, we simply
// lower the expression, and don't use
// the result.
//
// Note that we lower using the l-value path,
// so that an expression statement that names
// a location (but doesn't load from it)
// will not actually emit a load.
lowerLValueExpr(context, stmt->Expression);
}
void visitDeclStmt(DeclStmt* stmt)
{
// For now, we lower a declaration directly
// into the current context.
//
// TODO: We may want to consider whether
// nested type/function declarations should
// be lowered into the global scope during
// IR generation, or whether they should
// be lifted later (pushing capture analysis
// down to the IR).
//
lowerDecl(context, stmt->decl);
}
void visitSeqStmt(SeqStmt* stmt)
{
// To lower a sequence of statements,
// just lower each in order
for (auto ss : stmt->stmts)
{
lowerStmt(context, ss);
}
}
void visitBlockStmt(BlockStmt* stmt)
{
// To lower a block (scope) statement,
// just lower its body. The IR doesn't
// need to reflect the scoping of the AST.
lowerStmt(context, stmt->body);
}
void visitReturnStmt(ReturnStmt* stmt)
{
// A `return` statement turns into a return
// instruction. If the statement had an argument
// expression, then we need to lower that to
// a value first, and then emit the resulting value.
if( auto expr = stmt->Expression )
{
auto loweredExpr = lowerRValueExpr(context, expr);
getBuilder()->emitReturn(getSimpleVal(context, loweredExpr));
}
else
{
getBuilder()->emitReturn();
}
}
};
void lowerStmt(
IRGenContext* context,
Stmt* stmt)
{
StmtLoweringVisitor visitor;
visitor.context = context;
return visitor.dispatch(stmt);
}
void assign(
IRGenContext* context,
LoweredValInfo const& inLeft,
LoweredValInfo const& inRight)
{
LoweredValInfo left = inLeft;
LoweredValInfo right = inRight;
auto builder = context->irBuilder;
top:
switch (left.flavor)
{
case LoweredValInfo::Flavor::Ptr:
switch (right.flavor)
{
case LoweredValInfo::Flavor::Simple:
case LoweredValInfo::Flavor::Ptr:
case LoweredValInfo::Flavor::SwizzledLValue:
{
builder->emitStore(
left.val,
getSimpleVal(context, right));
}
break;
default:
SLANG_UNIMPLEMENTED_X("assignment");
break;
}
break;
case LoweredValInfo::Flavor::SwizzledLValue:
{
// The `left` value is of the form `<someLValue>.<swizzleElements>`.
//
// We could conceivably define a custom "swizzled store" instruction
// that would handle the common case where the base l-value is
// a simple lvalue (`LowerdValInfo::Flavor::Ptr`):
//
// float4 foo;
// foo.zxy = float3(...);
//
// However, this doesn't handle complex cases like the following:
//
// RWStructureBuffer<float4> foo;
// ...
// foo[index].xzy = float3(...);
//
// In a case like that, we really need to lower through a temp:
//
// float4 tmp = foo[index];
// tmp.xzy = float3(...);
// foo[index] = tmp;
//
// We want to handle the general case, we we might as well
// try to handle everything uniformly.
//
auto swizzleInfo = left.getSwizzledLValueInfo();
auto type = swizzleInfo->type;
auto loweredBase = swizzleInfo->base;
// Load from the base value:
IRValue* irLeftVal = getSimpleVal(context, loweredBase);
IRValue* irRightVal = getSimpleVal(context, right);
// Now apply the swizzle
IRInst* irSwizzled = builder->emitSwizzleSet(
irLeftVal->getType(),
irLeftVal,
irRightVal,
swizzleInfo->elementCount,
swizzleInfo->elementIndices);
// And finally, store the value back where we got it.
//
// Note: this is effectively a recursive call to
// `assign()`, so we do a simple tail-recursive call here.
left = loweredBase;
right = LoweredValInfo::simple(irSwizzled);
goto top;
}
break;
case LoweredValInfo::Flavor::BoundSubscript:
{
// The `left` value refers to a subscript operation on
// a resource type, bound to particular arguments, e.g.:
// `someStructuredBuffer[index]`.
//
// When storing to such a value, we need to emit a call
// to the appropriate builtin "setter" accessor.
auto subscriptInfo = left.getBoundSubscriptInfo();
auto type = subscriptInfo->type;
// Search for an appropriate "setter" declaration
for (auto setterDeclRef : getMembersOfType<SetterDecl>(subscriptInfo->declRef))
{
auto allArgs = subscriptInfo->args;
addArgs(context, &allArgs, right);
emitCallToDeclRef(
context,
context->getSession()->getVoidType(),
setterDeclRef,
nullptr,
allArgs);
return;
}
// No setter found? Then we have an error!
SLANG_UNEXPECTED("no setter found");
break;
}
break;
default:
SLANG_UNIMPLEMENTED_X("assignment");
break;
}
}
struct DeclLoweringVisitor : DeclVisitor<DeclLoweringVisitor, LoweredValInfo>
{
IRGenContext* context;
IRBuilder* getBuilder()
{
return context->irBuilder;
}
LoweredValInfo visitDeclBase(DeclBase* decl)
{
SLANG_UNIMPLEMENTED_X("decl catch-all");
}
LoweredValInfo visitDecl(Decl* decl)
{
SLANG_UNIMPLEMENTED_X("decl catch-all");
}
LoweredValInfo visitGenericTypeParamDecl(GenericTypeParamDecl* decl)
{
return LoweredValInfo();
}
LoweredValInfo visitInheritanceDecl(InheritanceDecl* inheritanceDecl)
{
// Construct a type for the parent declaration.
//
// TODO: if this inheritance declaration is under an extension,
// then we should construct the type that is being extended,
// and not a reference to the extension itself.
auto parentDecl = inheritanceDecl->ParentDecl;
RefPtr<Type> type = DeclRefType::Create(
context->getSession(),
makeDeclRef(parentDecl));
// TODO: if the parent type is generic, then I suppose these
// need to be *generic* witness tables?
// What is the super-type that we have declared we inherit from?
RefPtr<Type> superType = inheritanceDecl->base.type;
// Construct the mangled name for the witness table, which depends
// on the type that is conforming, and the type that it conforms to.
String mangledName = getMangledNameForConformanceWitness(
type,
superType);
// Build an IR level witness table, which will represent the
// conformance of the type to its super-type.
auto witnessTable = context->irBuilder->createWitnessTable();
witnessTable->mangledName = mangledName;
// Register the value now, rather than later, to avoid
// infinite recursion.
context->shared->declValues[inheritanceDecl] = LoweredValInfo::simple(witnessTable);
// Semantic checking will have filled in a dictionary of
// witnesses for requirements in the interface, and we
// will now navigate that dictionary to fill in the witness table.
for (auto entry : inheritanceDecl->requirementWitnesses)
{
auto requiredMemberDeclRef = entry.Key;
auto satisfyingMemberDecl = entry.Value;
auto irRequirement = context->irBuilder->getDeclRefVal(requiredMemberDeclRef);
auto irSatisfyingVal = getSimpleVal(context, ensureDecl(context, satisfyingMemberDecl));
auto witnessTableEntry = context->irBuilder->createWitnessTableEntry(
witnessTable,
irRequirement,
irSatisfyingVal);
}
witnessTable->moveToEnd();
// A direct reference to this inheritance relationship (e.g.,
// as a subtype witness) will take the form of a reference to
// the witness table in the IR.
return LoweredValInfo::simple(witnessTable);
}
LoweredValInfo visitDeclGroup(DeclGroup* declGroup)
{
// To lowere a group of declarations, we just
// lower each one individually.
//
for (auto decl : declGroup->decls)
{
// Note: I am directly invoking `dispatch` here,
// instead of `ensureDecl` just to try and
// make sure that we don't accidentally
// emit things to an outer context.
//
// TODO: make sure that can't happen anyway.
dispatch(decl);
}
return LoweredValInfo();
}
LoweredValInfo visitSubscriptDecl(SubscriptDecl* decl)
{
// A subscript operation may encompass one or more
// accessors, and these are what should actually
// get lowered (they are effectively functions).
for (auto accessor : decl->getMembersOfType<AccessorDecl>())
{
if (accessor->HasModifier<IntrinsicOpModifier>())
continue;
ensureDecl(context, accessor);
}
// The subscript declaration itself won't correspond
// to anything in the lowered program, so we don't
// bother creating a representation here.
//
// Note: We may want to have a specific lowered value
// that can represent the combination of callables
// that make up the subscript operation.
return LoweredValInfo();
}
bool isGlobalVarDecl(VarDeclBase* decl)
{
auto parent = decl->ParentDecl;
if (dynamic_cast<ModuleDecl*>(parent))
{
// Variable declared at global scope? -> Global.
return true;
}
return false;
}
LoweredValInfo lowerGlobalVarDecl(VarDeclBase* decl)
{
RefPtr<Type> varType = lowerSimpleType(context, decl->getType());
if (decl->HasModifier<HLSLGroupSharedModifier>())
{
varType = context->getSession()->getGroupSharedType(varType);
}
// TODO: There might be other cases of storage qualifiers
// that should translate into "rate-qualified" types
// for the variable's storage.
//
// TODO: Also worth asking whether we should have semantic
// checking be responsible for applying qualifiers applied
// to a variable over to its type, when it makes sense.
auto builder = getBuilder();
auto irGlobal = builder->createGlobalVar(varType);
irGlobal->mangledName = getMangledName(decl);
if (decl)
{
builder->addHighLevelDeclDecoration(irGlobal, decl);
}
// A global variable's SSA value is a *pointer* to
// the underlying storage.
auto globalVal = LoweredValInfo::ptr(irGlobal);
context->shared->declValues.Add(
DeclRef<VarDeclBase>(decl, nullptr),
globalVal);
if( auto initExpr = decl->initExpr )
{
// TODO: need to handle global with initializer!
}
return globalVal;
}
LoweredValInfo visitVarDeclBase(VarDeclBase* decl)
{
// Detect global (or effectively global) variables
// and handle them differently.
if (isGlobalVarDecl(decl))
{
return lowerGlobalVarDecl(decl);
}
// A user-defined variable declaration will usually turn into
// an `alloca` operation for the variable's storage,
// plus some code to initialize it and then store to the variable.
//
// TODO: we may want to special-case things when the variable's
// type, qualifiers, or context mark it as something that can't
// be mutable (or even do some limited dataflow pass to check
// which variables ever get assigned) so that we can directly
// emit an SSA value in this common case.
//
RefPtr<Type> varType = lowerSimpleType(context, decl->getType());
// TODO: If the variable is marked `static` then we need to
// deal with it specially: we should move its allocation out
// to the global scope, and then we have to deal with its
// initializer expression a bit carefully (it should only
// be initialized on-demand at its first use).
// Some qualifiers on a variable will change how we allocate it,
// so we need to reflect that somehow. The first example
// we run into is the `groupshared` qualifier, which marks
// a variable in a compute shader as having per-group allocation
// rather than the traditional per-thread (or rather per-thread
// per-activation-record) allocation.
//
// Options include:
//
// - Use a distinct allocation opration, so that the type
// of the variable address/value is unchanged.
//
// - Add a notion of an "address space" to pointer types,
// so that we can allocate things in distinct spaces.
//
// - Add a notion of a "rate" so that we can declare a
// variable with a distinct rate.
//
// For now we might do the expedient thing and handle this
// via a notion of an "address space."
if (decl->HasModifier<HLSLGroupSharedModifier>())
{
// TODO: This logic is duplicated with the global-variable
// case. We should seek to share it.
varType = context->getSession()->getGroupSharedType(varType);
}
LoweredValInfo varVal = createVar(context, varType, decl);
if( auto initExpr = decl->initExpr )
{
auto initVal = lowerRValueExpr(context, initExpr);
assign(context, varVal, initVal);
}
context->shared->declValues.Add(
DeclRef<VarDeclBase>(decl, nullptr),
varVal);
return varVal;
}
LoweredValInfo visitAggTypeDecl(AggTypeDecl* decl)
{
// Given a declaration of a type, we need to make sure
// to output "witness tables" for any interfaces this
// type has declared conformance to.
for( auto inheritanceDecl : decl->getMembersOfType<InheritanceDecl>() )
{
ensureDecl(context, inheritanceDecl);
}
// For now, we don't have an IR-level representation
// for the type itself.
return LoweredValInfo();
}
DeclRef<Decl> createDefaultSpecializedDeclRefImpl(Decl* decl)
{
DeclRef<Decl> declRef;
declRef.decl = decl;
declRef.substitutions = createDefaultSubstitutions(context->getSession(), decl);
return declRef;
}
//
// The client should actually call the templated wrapper, to preserve type information.
template<typename D>
DeclRef<D> createDefaultSpecializedDeclRef(D* decl)
{
DeclRef<Decl> declRef = createDefaultSpecializedDeclRefImpl(decl);
return declRef.As<D>();
}
// When lowering something callable (most commonly a function declaration),
// we need to construct an appropriate parameter list for the IR function
// that folds in any contributions from both the declaration itself *and*
// its parent declaration(s).
//
// For example, given code like:
//
// struct Foo { int bar(float y) { ... } };
//
// we need to generate IR-level code something like:
//
// func Foo_bar(Foo this, float y) -> int;
//
// that is, the `this` parameter has become explicit.
//
// The same applies to generic parameters, and these
// should apply even if the nested declaration is `static`:
//
// struct Foo<T> { static int bar(T y) { ... } };
//
// becomes:
//
// func Foo_bar<T>(T y) -> int;
//
// In order to implement this, we are going to do a recursive
// walk over a declaration and its parents, collecting separate
// lists of ordinary and generic parameters that will need
// to be included in the final declaration's parameter list.
//
// When doing code generation for an ordinary value parameter,
// we mostly care about its type, and then also its "direction"
// (`in`, `out`, `in out`). We sometimes need acess to the
// original declaration so that we can inspect it for meta-data,
// but in some cases there is no such declaration (e.g., a `this`
// parameter doesn't get an explicit declaration in the AST).
// To handle this we break out the relevant data into derived
// structures:
//
enum ParameterDirection
{
kParameterDirection_In,
kParameterDirection_Out,
kParameterDirection_InOut,
};
struct ParameterInfo
{
// This AST-level type of the parameter
Type* type;
// The direction (`in` vs `out` vs `in out`)
ParameterDirection direction;
// The variable/parameter declaration for
// this parameter (if any)
VarDeclBase* decl;
// Is this the representation of a `this` parameter?
bool isThisParam = false;
};
//
// We need a way to compute the appropriate `ParameterDirection` for a
// declared parameter:
//
ParameterDirection getParameterDirection(VarDeclBase* paramDecl)
{
if( paramDecl->HasModifier<InOutModifier>() )
{
// The AST specified `inout`:
return kParameterDirection_InOut;
}
if (paramDecl->HasModifier<OutModifier>())
{
// We saw an `out` modifier, so now we need
// to check if there was a paired `in`.
if(paramDecl->HasModifier<InModifier>())
return kParameterDirection_InOut;
else
return kParameterDirection_Out;
}
else
{
// No direction modifier, or just `in`:
return kParameterDirection_In;
}
}
// We need a way to be able to create a `ParameterInfo` given the declaration
// of a parameter:
//
ParameterInfo getParameterInfo(VarDeclBase* paramDecl)
{
ParameterInfo info;
info.type = paramDecl->getType();
info.decl = paramDecl;
info.direction = getParameterDirection(paramDecl);
info.isThisParam = false;
return info;
}
//
// Here's the declaration for the type to hold the lists:
struct ParameterLists
{
List<ParameterInfo> params;
List<Decl*> genericParams;
};
//
// Because there might be a `static` declaration somewhere
// along the lines, we need to be careful to prohibit adding
// non-generic parameters in some cases.
enum ParameterListCollectMode
{
// Collect everything: ordinary and generic parameters.
kParameterListCollectMode_Default,
// Only collect generic parameters.
kParameterListCollectMode_Static,
};
//
// We also need to be able to detect whether a declaration is
// either explicitly or implicitly treated as `static`:
bool isMemberDeclarationEffectivelyStatic(
Decl* decl,
ContainerDecl* parentDecl)
{
// Anything explicitly marked `static` counts.
//
// There is a subtle detail here with a global-scope `static`
// variable not really meaning `static` in the same way, but
// it doesn't matter because the module shouldn't introduce
// any parameters we care about.
if(decl->HasModifier<HLSLStaticModifier>())
return true;
// Next we need to deal with cases where a declaration is
// effectively `static` even if the language doesn't make
// the user say so. Most languages make the default assumption
// that nested types are `static` even if they don't say
// so (Java is an exception here, perhaps due to some
// includence from the Scandanavian OOP tradition).
if(dynamic_cast<AggTypeDecl*>(decl))
return true;
// Things nested inside functions may have dependencies
// on values from the enclosing scope, but this needs to
// be dealt with via "capture" so they are also effectively
// `static`
if(dynamic_cast<FunctionDeclBase*>(parentDecl))
return true;
return false;
}
// We also need to be able to detect whether a declaration is
// either explicitly or implicitly treated as `static`:
ParameterListCollectMode getModeForCollectingParentParameters(
Decl* decl,
ContainerDecl* parentDecl)
{
// If we have a `static` parameter, then it is obvious
// that we should use the `static` mode
if(isMemberDeclarationEffectivelyStatic(decl, parentDecl))
return kParameterListCollectMode_Static;
// Otherwise, let's default to collecting everything
return kParameterListCollectMode_Default;
}
//
// When dealing with a member function, we need to be able to add the `this`
// parameter for the enclosing type:
//
void addThisParameter(
Type* type,
ParameterLists* ioParameterLists)
{
// For now we make any `this` parameter default to `in`. Eventually
// we should add a way for the user to opt in to mutability of `this`
// in cases where they really want it.
//
// Note: an alternative here might be to have the built-in types like
// `Texture2D` actually use `class` declarations and say that the
// `this` parameter for a class type is always `in`, while `struct`
// types can default to `in out`.
ParameterDirection direction = kParameterDirection_In;
ParameterInfo info;
info.type = type;
info.decl = nullptr;
info.direction = direction;
info.isThisParam = true;
ioParameterLists->params.Add(info);
}
void addThisParameter(
AggTypeDecl* typeDecl,
ParameterLists* ioParameterLists)
{
// We need to construct an appopriate declaration-reference
// for the type declaration we were given. In particular,
// we need to specialize it for any generic parameters
// that are in scope here.
auto declRef = createDefaultSpecializedDeclRef(typeDecl);
auto type = DeclRefType::Create(context->getSession(), declRef);
addThisParameter(
type,
ioParameterLists);
}
//
// And here is our function that will do the recursive walk:
void collectParameterLists(
Decl* decl,
ParameterLists* ioParameterLists,
ParameterListCollectMode mode)
{
// The parameters introduced by any "parent" declarations
// will need to come first, so we'll deal with that
// logic here.
if( auto parentDecl = decl->ParentDecl )
{
// Compute the mode to use when collecting parameters from
// the outer declaration. The most important question here
// is whether parameters of the outer declaration should
// also count as parameters of the inner declaration.
ParameterListCollectMode innerMode = getModeForCollectingParentParameters(decl, parentDecl);
// Don't down-grade our `static`-ness along the chain.
if(innerMode < mode)
innerMode = mode;
// Now collect any parameters from the parent declaration itself
collectParameterLists(parentDecl, ioParameterLists, innerMode);
// We also need to consider whether the inner declaration needs to have a `this`
// parameter corresponding to the outer declaration.
if( innerMode != kParameterListCollectMode_Static )
{
if( auto aggTypeDecl = dynamic_cast<AggTypeDecl*>(parentDecl) )
{
addThisParameter(aggTypeDecl, ioParameterLists);
}
else if( auto extensionDecl = dynamic_cast<ExtensionDecl*>(parentDecl) )
{
addThisParameter(extensionDecl->targetType, ioParameterLists);
}
}
}
// Once we've added any parameters based on parent declarations,
// we can see if this declaration itself introduces parameters.
//
if( auto callableDecl = dynamic_cast<CallableDecl*>(decl) )
{
// Don't collect parameters from the outer scope if
// we are in a `static` context.
if( mode == kParameterListCollectMode_Default )
{
for( auto paramDecl : callableDecl->GetParameters() )
{
ioParameterLists->params.Add(getParameterInfo(paramDecl));
}
}
}
else if( auto genericDecl = dynamic_cast<GenericDecl*>(decl) )
{
for( auto memberDecl : genericDecl->Members )
{
if( auto genericTypeParamDecl = memberDecl.As<GenericTypeParamDecl>() )
{
ioParameterLists->genericParams.Add(genericTypeParamDecl);
}
else if( auto genericValueParamDecl = memberDecl.As<GenericValueParamDecl>() )
{
ioParameterLists->genericParams.Add(genericValueParamDecl);
}
else if( auto genericConstraintDel = memberDecl.As<GenericTypeConstraintDecl>() )
{
// When lowering to the IR we need to reify the constraints on
// a generic parameter as concrete parameters of their own.
// These parameter will usually be satisfied by passing a "witness"
// as the argument to correspond to the parameter.
//
// TODO: it is possible that all witness parameters should come
// after the other generic parameters, and thus should be collected
// in a third list.
//
ioParameterLists->genericParams.Add(genericConstraintDel);
}
}
}
}
void trySetMangledName(
IRFunc* irFunc,
Decl* decl)
{
// We want to generate a mangled name for the given declaration and attach
// it to the instruction.
//
// TODO: we probably want to start be doing an early-exit in cases
// where it doesn't make sense to attach a mangled name (e.g., because
// the declaration in question shouldn't have linkage).
//
String mangledName = getMangledName(decl);
irFunc->mangledName = mangledName;
}
LoweredValInfo lowerFuncDecl(FunctionDeclBase* decl)
{
// Collect the parameter lists we will use for our new function.
ParameterLists parameterLists;
collectParameterLists(decl, ¶meterLists, kParameterListCollectMode_Default);
// TODO: if there are any generic parameters in the collected list, then
// we need to output an IR function with generic parameters (or a generic
// with a nested function... the exact representation is still TBD).
// In most cases the return type for a declaration can be read off the declaration
// itself, but things get a bit more complicated when we have to deal with
// accessors for subscript declarations (and eventually for properties).
//
// We compute a declaration to use for looking up the return type here:
CallableDecl* declForReturnType = decl;
if (auto accessorDecl = dynamic_cast<AccessorDecl*>(decl))
{
// We are some kind of accessor, so the parent declaration should
// know the correct return type to expose.
//
auto parentDecl = accessorDecl->ParentDecl;
if (auto subscriptDecl = dynamic_cast<SubscriptDecl*>(parentDecl))
{
declForReturnType = subscriptDecl;
}
}
IRBuilder subBuilderStorage = *getBuilder();
IRBuilder* subBuilder = &subBuilderStorage;
IRGenContext subContextStorage = *context;
IRGenContext* subContext = &subContextStorage;
subContext->irBuilder = subBuilder;
// need to create an IR function here
IRFunc* irFunc = subBuilder->createFunc();
subBuilder->func = irFunc;
trySetMangledName(irFunc, decl);
List<RefPtr<Type>> paramTypes;
// We first need to walk the generic parameters (if any)
// because these will influence the declared type of
// the function.
for(auto pp = decl->ParentDecl; pp; pp = pp->ParentDecl)
{
if(auto genericAncestor = dynamic_cast<GenericDecl*>(pp))
{
irFunc->genericDecl = genericAncestor;
break;
}
}
for( auto paramInfo : parameterLists.params )
{
RefPtr<Type> irParamType = lowerSimpleType(context, paramInfo.type);
switch( paramInfo.direction )
{
case kParameterDirection_In:
// Simple case of a by-value input parameter.
paramTypes.Add(irParamType);
break;
default:
// The parameter is being used for input/output purposes,
// so it will lower to an actual parameter with a pointer type.
//
// TODO: Is this the best representation we can use?
auto irPtrType = getPtrType(context, irParamType);
paramTypes.Add(irPtrType);
}
}
auto irResultType = lowerSimpleType(context, declForReturnType->ReturnType);
if (auto setterDecl = dynamic_cast<SetterDecl*>(decl))
{
// We are lowering a "setter" accessor inside a subscript
// declaration, which means we don't want to *return* the
// stated return type of the subscript, but instead take
// it as a parameter.
//
IRType* irParamType = irResultType;
paramTypes.Add(irParamType);
IRParam* irParam = subBuilder->emitParam(irParamType);
// TODO: we need some way to wire this up to the `newValue`
// or whatever name we give for that parameter inside
// the setter body.
// Instead, a setter always returns `void`
//
irResultType = context->getSession()->getVoidType();
}
auto irFuncType = getFuncType(
context,
paramTypes.Count(),
paramTypes.Buffer(),
irResultType);
irFunc->type = irFuncType;
if (!decl->Body)
{
// This is a function declaration without a body.
// In Slang we currently try not to support forward declarations
// (although we might have to give in eventually), so the
// only case where this arises is for a function that
// needs to be imported from another module.
// TODO: we may need to attach something to the declaration,
// so that later passes don't get confused by it not having
// a body.
}
else
{
// This is a function definition, so we need to actually
// construct IR for the body...
IRBlock* entryBlock = subBuilder->emitBlock();
subBuilder->block = entryBlock;
UInt paramTypeIndex = 0;
for( auto paramInfo : parameterLists.params )
{
auto irParamType = paramTypes[paramTypeIndex++];
LoweredValInfo paramVal;
switch( paramInfo.direction )
{
default:
{
// The parameter is being used for input/output purposes,
// so it will lower to an actual parameter with a pointer type.
//
// TODO: Is this the best representation we can use?
auto irPtrType = irParamType.As<PtrType>();
IRParam* irParamPtr = subBuilder->emitParam(irPtrType);
if(auto paramDecl = paramInfo.decl)
subBuilder->addHighLevelDeclDecoration(irParamPtr, paramDecl);
paramVal = LoweredValInfo::ptr(irParamPtr);
// TODO: We might want to copy the pointed-to value into
// a temporary at the start of the function, and then copy
// back out at the end, so that we don't have to worry
// about things like aliasing in the function body.
//
// For now we will just use the storage that was passed
// in by the caller, knowing that our current lowering
// at call sites will guarantee a fresh/unique location.
}
break;
case kParameterDirection_In:
{
// Simple case of a by-value input parameter.
// But note that HLSL allows an input parameter
// to be used as a local variable inside of a
// function body, so we need to introduce a temporary
// and then copy over to it...
//
// TODO: we could skip this step if we knew
// the parameter was marked `const` or similar.
paramTypes.Add(irParamType);
IRParam* irParam = subBuilder->emitParam(irParamType);
if(auto paramDecl = paramInfo.decl)
subBuilder->addHighLevelDeclDecoration(irParam, paramDecl);
paramVal = LoweredValInfo::simple(irParam);
auto irLocal = subBuilder->emitVar(irParamType);
auto localVal = LoweredValInfo::ptr(irLocal);
assign(subContext, localVal, paramVal);
paramVal = localVal;
}
break;
}
if( auto paramDecl = paramInfo.decl )
{
DeclRef<VarDeclBase> paramDeclRef = makeDeclRef(paramDecl);
subContext->shared->declValues.Add(paramDeclRef, paramVal);
}
if (paramInfo.isThisParam)
{
subContext->thisVal = paramVal;
}
}
lowerStmt(subContext, decl->Body);
// We need to carefully add a terminator instruction to the end
// of the body, in case the user didn't do so.
if (!isTerminatorInst(subContext->irBuilder->block->lastInst))
{
if (irResultType->Equals(context->getSession()->getVoidType()))
{
// `void`-returning function can get an implicit
// return on exit of the body statement.
subContext->irBuilder->emitReturn();
}
else
{
// Value-returning function is expected to `return`
// on every control-flow path. We need to enforce
// this by putting an `unreachable` terminator here,
// and then emit a dataflow error if this block
// can't be eliminated.
SLANG_UNEXPECTED("Needed a return here");
subContext->irBuilder->emitReturn();
}
}
}
getBuilder()->addHighLevelDeclDecoration(irFunc, decl);
// If this declaration was marked as being an intrinsic for a particular
// target, then we should reflect that here.
for( auto targetMod : decl->GetModifiersOfType<SpecializedForTargetModifier>() )
{
// `targetMod` indicates that this particular declaration represents
// a specialized definition of the particular function for the given
// target, and we need to reflect that at the IR level.
auto decoration = getBuilder()->addDecoration<IRTargetDecoration>(irFunc);
decoration->targetName = targetMod->targetToken.Content;
}
// For convenience, ensure that any additional global
// values that were emitted while outputting the function
// body appear before the function itself in the list
// of global values.
irFunc->moveToEnd();
return LoweredValInfo::simple(irFunc);
}
LoweredValInfo visitFunctionDeclBase(FunctionDeclBase* decl)
{
// A function declaration may have multiple, target-specific
// overloads, and we need to emit an IR version of each of these.
// The front end will form a linked list of declaratiosn with
// the same signature, whenever there is any kind of redeclaration.
// We will look to see if that linked list has been formed.
auto primaryDecl = decl->primaryDecl;
if (!primaryDecl)
{
// If there is no linked list then we are in the ordinary
// case with a single declaration, and no special handling
// is needed.
return lowerFuncDecl(decl);
}
// Otherwise, we need to walk the linked list of declarations
// and make sure to emit IR code for any targets that need it.
// TODO: Need to be careful about how this is approached,
// to avoid emitting a bunch of extra definitions in the IR.
auto primaryFuncDecl = dynamic_cast<FunctionDeclBase*>(primaryDecl);
assert(primaryFuncDecl);
LoweredValInfo result = lowerFuncDecl(primaryFuncDecl);
for (auto dd = primaryDecl->nextDecl; dd; dd = dd->nextDecl)
{
auto funcDecl = dynamic_cast<FunctionDeclBase*>(dd);
assert(funcDecl);
lowerFuncDecl(funcDecl);
}
return result;
}
};
LoweredValInfo lowerDecl(
IRGenContext* context,
DeclBase* decl)
{
DeclLoweringVisitor visitor;
visitor.context = context;
return visitor.dispatch(decl);
}
// Ensure that a version of the given declaration has been emitted to the IR
LoweredValInfo ensureDecl(
IRGenContext* context,
Decl* decl)
{
auto shared = context->shared;
LoweredValInfo result;
if(shared->declValues.TryGetValue(decl, result))
return result;
IRBuilder subIRBuilder;
subIRBuilder.shared = context->irBuilder->shared;
IRGenContext subContext = *context;
subContext.irBuilder = &subIRBuilder;
result = lowerDecl(&subContext, decl);
shared->declValues[decl] = result;
return result;
}
IRWitnessTable* findWitnessTable(
IRGenContext* context,
DeclRef<Decl> declRef)
{
IRValue* irVal = getSimpleVal(context, emitDeclRef(context, declRef));
if (!irVal)
{
SLANG_UNEXPECTED("expected a witness table");
return nullptr;
}
if (irVal->op != kIROp_witness_table)
{
// TODO: We might eventually have cases of `specialize` called
// on a witness table...
SLANG_UNEXPECTED("expected a witness table");
return nullptr;
}
return (IRWitnessTable*)irVal;
}
RefPtr<Val> lowerSubstitutionArg(
IRGenContext* context,
Val* val)
{
if (auto type = dynamic_cast<Type*>(val))
{
return lowerSimpleType(context, type);
}
else if (auto declaredSubtypeWitness = dynamic_cast<DeclaredSubtypeWitness*>(val))
{
// We need to look up the IR-level representation of the witness
// (which is a witness table).
auto irWitnessTable = findWitnessTable(context, declaredSubtypeWitness->declRef);
// We have an IR-level value, but we need to embed it into an AST-level
// type, so we will use a proxy `Val` that wraps up an `IRValue` as
// an AST-level value.
//
// TODO: This proxy value currently doesn't enter into use-def chaining,
// and so Bad Things could happen quite easily. We need to fix that
// up in a reasonably clean fashion.
//
RefPtr<IRProxyVal> proxyVal = new IRProxyVal();
proxyVal->inst = irWitnessTable;
return proxyVal;
}
else
{
// For now, jsut assume that all other values
// lower to themselves.
//
// TODO: we should probably handle the case of
// a `Val` that references an AST-level `constexpr`
// variable, since that would need to be lowered
// to a `Val` that references the IR equivalent.
return val;
}
}
// Given a set of substitutions, make sure that we have
// lowered the arguments being used into a form that
// is suitable for use in the IR.
RefPtr<Substitutions> lowerSubstitutions(
IRGenContext* context,
Substitutions* subst)
{
if(!subst)
return nullptr;
RefPtr<Substitutions> newSubst = new Substitutions();
if (subst->outer)
{
newSubst->outer = lowerSubstitutions(
context,
subst->outer);
}
newSubst->genericDecl = subst->genericDecl;
for (auto arg : subst->args)
{
auto newArg = lowerSubstitutionArg(context, arg);
newSubst->args.Add(newArg);
}
return newSubst;
}
LoweredValInfo emitDeclRef(
IRGenContext* context,
DeclRef<Decl> declRef)
{
// First we need to construct an IR value representing the
// unspecialized declaration.
LoweredValInfo loweredDecl = ensureDecl(context, declRef.getDecl());
// If this declaration reference doesn't involve any specializations,
// then we are done at this point.
if(!declRef.substitutions)
return loweredDecl;
auto val = getSimpleVal(context, loweredDecl);
// We have the "raw" substitutions from the AST, but we may
// need to walk through those and replace things in
// cases where the `Val`s used for substitution should
// lower to something other than their original form.
RefPtr<Substitutions> newSubst = lowerSubstitutions(context, declRef.substitutions);
declRef.substitutions = newSubst;
RefPtr<Type> type;
if(auto declType = val->getType())
{
type = declType->Substitute(declRef.substitutions).As<Type>();
}
// Otherwise, we need to construct a specialization of the
// given declaration.
return LoweredValInfo::simple(context->irBuilder->emitSpecializeInst(
type,
val,
declRef));
}
static void lowerEntryPointToIR(
IRGenContext* context,
EntryPointRequest* entryPointRequest)
{
// First, lower the entry point like an ordinary function
auto entryPointFuncDecl = entryPointRequest->decl;
if (!entryPointFuncDecl)
{
// Something must have gone wrong earlier, if we
// weren't able to associate a declaration with
// the entry point request.
return;
}
auto loweredEntryPointFunc = lowerDecl(context, entryPointFuncDecl);
}
#if 0
IRModule* lowerEntryPointToIR(
EntryPointRequest* entryPoint,
ProgramLayout* programLayout,
CodeGenTarget target)
{
SharedIRGenContext sharedContextStorage;
SharedIRGenContext* sharedContext = &sharedContextStorage;
sharedContext->entryPoint = entryPoint;
sharedContext->programLayout = programLayout;
sharedContext->target = target;
IRGenContext contextStorage;
IRGenContext* context = &contextStorage;
context->shared = sharedContext;
SharedIRBuilder sharedBuilderStorage;
SharedIRBuilder* sharedBuilder = &sharedBuilderStorage;
sharedBuilder->module = nullptr;
sharedBuilder->session = entryPoint->compileRequest->mSession;
IRBuilder builderStorage;
IRBuilder* builder = &builderStorage;
builder->shared = sharedBuilder;
IRModule* module = builder->createModule();
sharedBuilder->module = module;
context->irBuilder = builder;
auto entryPointLayout = findEntryPointLayout(sharedContext, entryPoint);
lowerEntryPointToIR(context, entryPoint, entryPointLayout);
return module;
}
#endif
IRModule* generateIRForTranslationUnit(
TranslationUnitRequest* translationUnit)
{
auto compileRequest = translationUnit->compileRequest;
SharedIRGenContext sharedContextStorage;
SharedIRGenContext* sharedContext = &sharedContextStorage;
sharedContext->compileRequest = compileRequest;
IRGenContext contextStorage;
IRGenContext* context = &contextStorage;
context->shared = sharedContext;
SharedIRBuilder sharedBuilderStorage;
SharedIRBuilder* sharedBuilder = &sharedBuilderStorage;
sharedBuilder->module = nullptr;
sharedBuilder->session = compileRequest->mSession;
IRBuilder builderStorage;
IRBuilder* builder = &builderStorage;
builder->shared = sharedBuilder;
IRModule* module = builder->createModule();
sharedBuilder->module = module;
context->irBuilder = builder;
// We need to emit IR for all public/exported symbols
// in the translation unit.
for (auto entryPoint : translationUnit->entryPoints)
{
lowerEntryPointToIR(context, entryPoint);
}
// If we are being sked to dump IR during compilation,
// then we can dump the initial IR for the module here.
if(compileRequest->shouldDumpIR)
{
dumpIR(module);
}
return module;
}
#if 0
String emitSlangIRAssemblyForEntryPoint(
EntryPointRequest* entryPoint)
{
auto compileRequest = entryPoint->compileRequest;
auto irModule = lowerEntryPointToIR(
entryPoint,
compileRequest->layout.Ptr(),
// TODO: we need to pick the target more carefully here
CodeGenTarget::HLSL);
return getSlangIRAssembly(irModule);
}
#endif
} // namespace Slang
|