1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
|
// lower.cpp
#include "slang-lower-to-ir.h"
#include "../core/slang-char-util.h"
#include "../core/slang-hash.h"
#include "../core/slang-performance-profiler.h"
#include "../core/slang-random-generator.h"
#include "slang-check.h"
#include "slang-ir-autodiff.h"
#include "slang-ir-bit-field-accessors.h"
#include "slang-ir-check-differentiability.h"
#include "slang-ir-check-recursion.h"
#include "slang-ir-clone.h"
#include "slang-ir-constexpr.h"
#include "slang-ir-dce.h"
#include "slang-ir-diff-call.h"
#include "slang-ir-entry-point-decorations.h"
#include "slang-ir-inline.h"
#include "slang-ir-insert-debug-value-store.h"
#include "slang-ir-insts.h"
#include "slang-ir-link.h"
#include "slang-ir-loop-inversion.h"
#include "slang-ir-lower-defer.h"
#include "slang-ir-lower-error-handling.h"
#include "slang-ir-lower-expand-type.h"
#include "slang-ir-missing-return.h"
#include "slang-ir-obfuscate-loc.h"
#include "slang-ir-operator-shift-overflow.h"
#include "slang-ir-peephole.h"
#include "slang-ir-sccp.h"
#include "slang-ir-simplify-cfg.h"
#include "slang-ir-ssa.h"
#include "slang-ir-string-hash.h"
#include "slang-ir-strip.h"
#include "slang-ir-use-uninitialized-values.h"
#include "slang-ir-util.h"
#include "slang-ir-validate.h"
#include "slang-ir.h"
#include "slang-mangle.h"
#include "slang-type-layout.h"
#include "slang-visitor.h"
#include "slang.h"
// Natural layout
#include "slang-ast-natural-layout.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;
};
// Some cases of `ExtendedValueInfo` need to
// recursively contain `LoweredValInfo`s, and
// so we forward declare them here and fill
// them in later.
//
struct BoundStorageInfo;
struct BoundMemberInfo;
struct SwizzledLValueInfo;
struct SwizzledMatrixLValueInfo;
struct CopiedValInfo;
struct ExtractedExistentialValInfo;
struct ImplicitCastLValueInfo;
// 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
{
typedef LoweredValInfo ThisType;
// 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 represented 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.
BoundStorage,
// The result of applying swizzling to an l-value
SwizzledLValue,
// The result of applying swizzling to an l-value matrix
SwizzledMatrixLValue,
// The value extracted from an opened existential
ExtractedExistential,
// The L-Value that is an implicit cast.
ImplicitCastedLValue,
};
union
{
IRInst* val;
ExtendedValueInfo* ext;
// We can compare any of the pointers above by comparing this pointer. If the union
// ever becomes something other than a union of pointers, this would no longer be
// applicable.
void* aliasPtr;
};
Flavor flavor;
// NOTE! This relies on the union, allowing the comparison of any of the pointer type in the
// union. Assumes equality is the same as val pointer/or ext pointer being equal.
bool operator==(const ThisType& rhs) const
{
return flavor == rhs.flavor && aliasPtr == rhs.aliasPtr;
}
bool operator!=(const ThisType& rhs) const { return !(*this == rhs); }
LoweredValInfo()
{
flavor = Flavor::None;
val = nullptr;
}
LoweredValInfo(IRType* t)
{
flavor = Flavor::Simple;
val = t;
}
static LoweredValInfo simple(IRInst* v)
{
LoweredValInfo info;
info.flavor = Flavor::Simple;
info.val = v;
return info;
}
static LoweredValInfo ptr(IRInst* v)
{
LoweredValInfo info;
info.flavor = Flavor::Ptr;
info.val = v;
return info;
}
static LoweredValInfo boundMember(BoundMemberInfo* boundMemberInfo);
BoundMemberInfo* getBoundMemberInfo()
{
SLANG_ASSERT(flavor == Flavor::BoundMember);
return (BoundMemberInfo*)ext;
}
static LoweredValInfo subscript(SubscriptInfo* subscriptInfo);
SubscriptInfo* getSubscriptInfo()
{
SLANG_ASSERT(flavor == Flavor::Subscript);
return (SubscriptInfo*)ext;
}
static LoweredValInfo boundStorage(BoundStorageInfo* boundStorageInfo);
BoundStorageInfo* getBoundStorageInfo()
{
SLANG_ASSERT(flavor == Flavor::BoundStorage);
return (BoundStorageInfo*)ext;
}
static LoweredValInfo swizzledLValue(SwizzledLValueInfo* extInfo);
static LoweredValInfo swizzledMatrixLValue(SwizzledMatrixLValueInfo* extInfo);
static LoweredValInfo implicitCastedLValue(ImplicitCastLValueInfo* extInfo);
SwizzledLValueInfo* getSwizzledLValueInfo()
{
SLANG_ASSERT(flavor == Flavor::SwizzledLValue);
return (SwizzledLValueInfo*)ext;
}
SwizzledMatrixLValueInfo* getSwizzledMatrixLValueInfo()
{
SLANG_ASSERT(flavor == Flavor::SwizzledMatrixLValue);
return (SwizzledMatrixLValueInfo*)ext;
}
static LoweredValInfo extractedExistential(ExtractedExistentialValInfo* extInfo);
ExtractedExistentialValInfo* getExtractedExistentialValInfo()
{
SLANG_ASSERT(flavor == Flavor::ExtractedExistential);
return (ExtractedExistentialValInfo*)ext;
}
ImplicitCastLValueInfo* getImplicitCastedLValue()
{
SLANG_ASSERT(flavor == Flavor::ImplicitCastedLValue);
return (ImplicitCastLValueInfo*)ext;
}
};
// This case is used to indicate a reference to an AST-level
// operation that accesses abstract storage.
//
// This could be an invocation of a `subscript` declaration,
// with argument representing an index or indices:
//
// RWStructuredBuffer<Foo> gBuffer;
// ... gBuffer[someIndex] ...
//
// the expression `gBuffer[someIndex]` will be lowered to
// a value that references `RWStructureBuffer<Foo>::operator[]`
// with arguments `(gBuffer, someIndex)`.
//
// This could also be an reference to a `property` declaration,
// with no arguments:
//
// struct Sphere { property radius : int { get { ... } } }
// Sphere sphere;
// ... sphere.radius ...
//
// the expression `sphere.radius` will be lowered to a value
// that references `Sphere::radius` with arguments `(sphere)`.
//
// 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 storage.
//
struct BoundStorageInfo : ExtendedValueInfo
{
/// The declaration of the abstract storage (subscript or property)
DeclRef<ContainerDecl> declRef;
/// The IR-level type of the stored value
IRType* type;
/// The base value/object on which storage is being accessed
LoweredValInfo base;
/// Additional arguments required to reify a reference to the storage
List<IRInst*> additionalArgs;
};
// 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;
// The type of this value
IRType* type;
};
// 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.
IRType* type;
// The base expression (this should be an l-value)
LoweredValInfo base;
// The indices for the elements being swizzled
ShortList<uint32_t, 4> elementIndices;
};
// Represents the result of a matrix swizzle operation in an l-value context.
// The same non-contiguous and no-duplicate rules as above apply.
struct SwizzledMatrixLValueInfo : ExtendedValueInfo
{
// The type of the expression.
IRType* type;
// The base expression (this should be an l-value)
LoweredValInfo base;
// The number of elements in the swizzle
UInt elementCount;
// The coords for the elements being swizzled, zero indexed
MatrixCoord elementCoords[4];
};
// Represents the results of extractng a value of
// some (statically unknown) concrete type from
// an existential, in an l-value context.
//
struct ExtractedExistentialValInfo : ExtendedValueInfo
{
// The extracted value
IRInst* extractedVal;
// The original existential value
LoweredValInfo existentialVal;
// The type of `existentialVal`
IRType* existentialType;
// The IR witness table for the conformance of
// the type of `extractedVal` to `existentialType`
//
IRInst* witnessTable;
};
struct ImplicitCastLValueInfo : ExtendedValueInfo
{
// The type of the expression.
IRType* type;
// The base expression (this should be an l-value)
LoweredValInfo base;
// The type of the lvalue (inout, out, ref, etc.)
ParameterDirection lValueType;
};
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::boundStorage(BoundStorageInfo* boundStorageInfo)
{
LoweredValInfo info;
info.flavor = Flavor::BoundStorage;
info.ext = boundStorageInfo;
return info;
}
LoweredValInfo LoweredValInfo::swizzledLValue(SwizzledLValueInfo* extInfo)
{
LoweredValInfo info;
info.flavor = Flavor::SwizzledLValue;
info.ext = extInfo;
return info;
}
LoweredValInfo LoweredValInfo::swizzledMatrixLValue(SwizzledMatrixLValueInfo* extInfo)
{
LoweredValInfo info;
info.flavor = Flavor::SwizzledMatrixLValue;
info.ext = extInfo;
return info;
}
LoweredValInfo LoweredValInfo::implicitCastedLValue(ImplicitCastLValueInfo* extInfo)
{
LoweredValInfo info;
info.flavor = Flavor::ImplicitCastedLValue;
info.ext = extInfo;
return info;
}
LoweredValInfo LoweredValInfo::extractedExistential(ExtractedExistentialValInfo* extInfo)
{
LoweredValInfo info;
info.flavor = Flavor::ExtractedExistential;
info.ext = extInfo;
return info;
}
// An "environment" for mapping AST declarations to IR values.
//
// This is required because in some cases we might lower the
// same AST declaration to the IR multiple times (e.g., when
// a generic transitively contains multiple functions, we
// will emit a distinct IR generic for each function, with
// its own copies of the generic parameters).
//
struct IRGenEnv
{
// Map an AST-level declaration to the IR-level value that represents it.
Dictionary<Decl*, LoweredValInfo> mapDeclToValue;
// The next outer env around this one
IRGenEnv* outer = nullptr;
};
struct SharedIRGenContext
{
// The "global" environment for mapping declarations to their IR values.
IRGenEnv globalEnv;
// Map an AST-level declaration of an interface
// requirement to the IR-level "key" that
// is used to fetch that requirement from a
// witness table.
Dictionary<Decl*, IRStructKey*> interfaceRequirementKeys;
// 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;
// Map from an AST-level statement that can be
// used as the target of a `break` or `continue`
// to the appropriate basic block to jump to.
Dictionary<BreakableStmt::UniqueID, IRBlock*> breakLabels;
Dictionary<BreakableStmt::UniqueID, IRBlock*> continueLabels;
Dictionary<SourceFile*, IRInst*> mapSourceFileToDebugSourceInst;
Dictionary<String, IRInst*> mapSourcePathToDebugSourceInst;
Dictionary<IntVal*, IRInst*> mapSpecConstValToIRInst;
// External (imported) unsafeForceInline functions that need to
// prelink into the current module after lowering.
List<IRInst*> externalSymbolsToPrelink;
void setGlobalValue(Decl* decl, LoweredValInfo value)
{
globalEnv.mapDeclToValue[decl] = value;
}
SharedIRGenContext(
Session* session,
DiagnosticSink* sink,
bool obfuscateCode,
ModuleDecl* mainModuleDecl,
Linkage* linkage)
: m_session(session)
, m_sink(sink)
, m_obfuscateCode(obfuscateCode)
, m_mainModuleDecl(mainModuleDecl)
, m_linkage(linkage)
{
}
Session* m_session = nullptr;
DiagnosticSink* m_sink = nullptr;
bool m_obfuscateCode = false;
ModuleDecl* m_mainModuleDecl = nullptr;
Linkage* m_linkage = nullptr;
// List of all string literals used in user code, regardless
// of how they were used (i.e., whether or not they were hashed).
//
// This does *not* collect:
// * String literals that were only used for attributes/modifiers in
// the user's code (e.g., `"compute"` in `[shader("compute")]`)
// * Any IR string literals constructed for the purpose of decorations,
// reflection, or other meta-data that did not appear as a literal
// in the source code.
//
List<IRInst*> m_stringLiterals;
DebugValueStoreContext debugValueContext;
};
struct IRGenContext;
struct AstOrIRType
{
Type* astType = nullptr;
IRInst* irType = nullptr;
IRInst* getIRType(IRGenContext* context);
AstOrIRType& operator=(Type* t)
{
astType = t;
irType = nullptr;
return *this;
}
AstOrIRType& operator=(IRInst* t)
{
astType = nullptr;
irType = t;
return *this;
}
explicit operator bool() { return astType || irType; }
};
struct CatchHandler
{
// 'nullptr' implies catch-all.
IRType* errorType = nullptr;
// Block of the handler statement. Takes a value of errorType as parameter.
IRBlock* errorHandler = nullptr;
CatchHandler* prev = nullptr;
};
struct IRGenContext
{
ASTBuilder* astBuilder;
// Shared state for the IR generation process
SharedIRGenContext* shared;
// environment for mapping AST decls to IR values
IRGenEnv* env;
// IR builder to use when building code under this context
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;
// The IRType value to lower into for `ThisType`.
AstOrIRType thisType;
// The IR witness value to use for `ThisType`
IRInst* thisTypeWitness = nullptr;
// The return destination parameter to write to at return sites.
// (For use by functions that returns non-copyable types)
LoweredValInfo returnDestination;
// A reference to the Function decl to identify the parent function
// that contains the Inst.
FunctionDeclBase* funcDecl;
bool includeDebugInfo = false;
// The element index if we are inside an `expand` expression.
IRInst* expandIndex = nullptr;
// The current scope end for use with `defer`.
IRBlock* scopeEndBlock = nullptr;
// A chain of nested `catch` handlers for `try` and `throw.
CatchHandler* catchHandler = nullptr;
// Callback function to call when after lowering a type.
std::function<IRType*(IRGenContext* context, Type* type, IRType* irType)> lowerTypeCallback =
nullptr;
explicit IRGenContext(SharedIRGenContext* inShared, ASTBuilder* inAstBuilder)
: shared(inShared), astBuilder(inAstBuilder), env(&inShared->globalEnv), irBuilder(nullptr)
{
}
void registerTypeCallback(
std::function<IRType*(IRGenContext* context, Type* type, IRType* irType)> callback)
{
lowerTypeCallback = callback;
}
void setGlobalValue(Decl* decl, LoweredValInfo value) { shared->setGlobalValue(decl, value); }
void setValue(Decl* decl, LoweredValInfo value) { env->mapDeclToValue[decl] = value; }
Session* getSession() { return shared->m_session; }
DiagnosticSink* getSink() { return shared->m_sink; }
ModuleDecl* getMainModuleDecl() { return shared->m_mainModuleDecl; }
Linkage* getLinkage() { return shared->m_linkage; }
LoweredValInfo* findLoweredDecl(Decl* decl)
{
IRGenEnv* envToFindIn = env;
while (envToFindIn)
{
if (auto rs = envToFindIn->mapDeclToValue.tryGetValue(decl))
return rs;
envToFindIn = envToFindIn->outer;
}
return nullptr;
}
};
ModuleDecl* findModuleDecl(Decl* decl)
{
for (auto dd = decl; dd; dd = dd->parentDecl)
{
if (auto moduleDecl = as<ModuleDecl>(dd))
return moduleDecl;
}
return nullptr;
}
bool isFromCoreModule(Decl* decl)
{
for (auto dd = decl; dd; dd = dd->parentDecl)
{
if (dd->hasModifier<FromCoreModuleModifier>())
return true;
}
return false;
}
bool isDeclInDifferentModule(IRGenContext* context, Decl* decl)
{
return getModuleDecl(decl) != context->getMainModuleDecl();
}
bool isForceInlineEarly(Decl* decl)
{
return decl->hasModifier<UnsafeForceInlineEarlyAttribute>();
}
bool isImportedDecl(IRGenContext* context, Decl* decl, bool& outIsExplicitExtern)
{
// If the declaration has the extern attribute then it must be imported
// from another module.
// Note that `extern` declarations will have a mangled name that does not
// include the module name so the linking step can resolve them correctly.
//
outIsExplicitExtern = false;
if (decl->findModifier<ExternAttribute>() || decl->findModifier<ExternModifier>())
{
outIsExplicitExtern = true;
return true;
}
for (auto parent = decl; parent; parent = parent->parentDecl)
{
if (as<ModuleDecl>(parent) && parent != context->getMainModuleDecl())
return true;
if (parent->findModifier<ExternAttribute>() || parent->findModifier<ExternModifier>())
{
outIsExplicitExtern = true;
return true;
}
}
return false;
}
/// Should the given `decl` nested in `parentDecl` be treated as a static rather than instance
/// declaration?
bool isEffectivelyStatic(Decl* decl, ContainerDecl* parentDecl);
bool isCoreModuleMemberFuncDecl(Decl* decl);
// 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, IRType* type);
bool isFunctionVarDecl(VarDeclBase* decl)
{
// The immediate parent of a function-scope variable
// declaration will be a `ScopeDecl`.
//
// TODO: right now the parent links for scopes are *not*
// set correctly, so we can't just scan up and look
// for a function in the parent chain...
auto parent = decl->parentDecl;
if (as<ScopeDecl>(parent))
{
return true;
}
return false;
}
bool isFunctionStaticVarDecl(VarDeclBase* decl)
{
// Only a variable marked `static` can be static.
if (!decl->findModifier<HLSLStaticModifier>())
return false;
return isFunctionVarDecl(decl);
}
IRInst* getSimpleVal(IRGenContext* context, LoweredValInfo lowered);
int32_t getIntrinsicOp(Decl* decl, IntrinsicOpModifier* intrinsicOpMod)
{
int32_t op = intrinsicOpMod->op;
if (op != 0)
return op;
// No specified modifier? Then we need to look it up
// based on the name of the declaration...
auto name = decl->getName();
auto nameText = getUnownedStringSliceText(name);
IROp irOp = findIROp(nameText);
SLANG_ASSERT(irOp != kIROp_Invalid);
SLANG_ASSERT(int32_t(irOp) >= 0);
return int32_t(irOp);
}
static CatchHandler findErrorHandler(IRGenContext* context, IRType* type)
{
for (auto handler = context->catchHandler; handler != nullptr;
handler = context->catchHandler->prev)
{
if (!handler->errorType || handler->errorType == type)
{
return *handler;
}
}
return CatchHandler();
}
struct TryClauseEnvironment
{
TryClauseType clauseType = TryClauseType::None;
IRBlock* catchBlock = nullptr;
};
// 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,
IRInst* const* args,
const TryClauseEnvironment& tryEnv)
{
auto builder = context->irBuilder;
switch (funcVal.flavor)
{
case LoweredValInfo::Flavor::None:
SLANG_UNEXPECTED("null function");
default:
switch (tryEnv.clauseType)
{
case TryClauseType::None:
{
auto callee = getSimpleVal(context, funcVal);
if (auto dispatchKernel = as<IRDispatchKernel>(callee))
{
// If callee is a dispatch kernel expr, don't emit call(dispatchKernel,
// ...), instead emit a dispatchKernel(high_order_args, actual_args).
auto result = LoweredValInfo::simple(builder->emitDispatchKernelInst(
type,
dispatchKernel->getBaseFn(),
dispatchKernel->getThreadGroupSize(),
dispatchKernel->getDispatchSize(),
argCount,
args));
SLANG_ASSERT(!dispatchKernel->hasUses());
dispatchKernel->removeAndDeallocate();
return result;
}
else
{
return LoweredValInfo::simple(builder->emitCallInst(
type,
getSimpleVal(context, funcVal),
argCount,
args));
}
}
case TryClauseType::Standard:
{
auto callee = getSimpleVal(context, funcVal);
auto funcType = as<IRFuncType>(callee->getDataType());
auto throwAttr = funcType->findAttr<IRFuncThrowTypeAttr>();
assert(throwAttr);
auto handler = findErrorHandler(context, throwAttr->getErrorType());
auto succBlock = builder->createBlock();
auto failBlock =
handler.errorHandler ? handler.errorHandler : builder->createBlock();
auto voidType = builder->getVoidType();
builder->emitTryCallInst(voidType, succBlock, failBlock, callee, argCount, args);
builder->insertBlock(succBlock);
auto value = builder->emitParam(type);
if (!handler.errorHandler)
{
// We have to create a default fail block, which just re-throws.
builder->insertBlock(failBlock);
auto errParam = builder->emitParam(throwAttr->getErrorType());
builder->emitThrow(errParam);
builder->setInsertInto(succBlock);
}
return LoweredValInfo::simple(value);
}
break;
default:
SLANG_UNIMPLEMENTED_X("emitCallToVal(tryClauseType)");
}
}
}
LoweredValInfo lowerRValueExpr(IRGenContext* context, Expr* expr);
void lowerRValueExprWithDestination(IRGenContext* context, LoweredValInfo destination, Expr* expr);
IRType* lowerType(IRGenContext* context, Type* type);
static IRType* lowerType(IRGenContext* context, QualType const& type)
{
return lowerType(context, type.type);
}
IRInst* AstOrIRType::getIRType(IRGenContext* context)
{
if (irType)
return irType;
irType = lowerType(context, astType);
return irType;
}
// 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,
IRType* funcType,
UInt argCount,
IRInst* const* args,
const TryClauseEnvironment& tryEnv)
{
SLANG_ASSERT(funcType);
auto builder = context->irBuilder;
auto funcDecl = funcDeclRef.getDecl();
if (auto intrinsicOpModifier = funcDecl->findModifier<IntrinsicOpModifier>())
{
// The intrinsic op maps to a single IR instruction,
// so we will emit an instruction with the chosen
// opcode, and the arguments to the call as its operands.
//
if (intrinsicOpModifier->op == 0) // Identity, just pass operand 0 through.
{
SLANG_RELEASE_ASSERT(argCount == 1);
return LoweredValInfo::simple(args[0]);
}
auto intrinsicOp = getIntrinsicOp(funcDecl, intrinsicOpModifier);
switch (IROp(intrinsicOp))
{
case kIROp_GetOffsetPtr:
SLANG_ASSERT(argCount == 2);
return LoweredValInfo::simple(builder->emitGetOffsetPtr(args[0], args[1]));
default:
return LoweredValInfo::simple(
builder->emitIntrinsicInst(type, IROp(intrinsicOp), argCount, args));
}
}
// Fallback case is to emit an actual call.
//
LoweredValInfo funcVal = emitDeclRef(context, funcDeclRef, funcType);
return emitCallToVal(context, type, funcVal, argCount, args, tryEnv);
}
LoweredValInfo emitCallToDeclRef(
IRGenContext* context,
IRType* type,
DeclRef<Decl> funcDeclRef,
IRType* funcType,
List<IRInst*> const& args,
const TryClauseEnvironment& tryEnv)
{
return emitCallToDeclRef(
context,
type,
funcDeclRef,
funcType,
args.getCount(),
args.getBuffer(),
tryEnv);
}
/// Emit a call to the given `accessorDeclRef`.
///
/// The `base` value represents the object on which the accessor is being invoked.
/// The `args` represent any additional arguments to the accessor. This could be
/// because we are invoking a subscript accessor (so the args include any index value(s)),
/// and/or because we are invoking a setter (so that the args include the new value
/// to be set).
///
static LoweredValInfo _emitCallToAccessor(
IRGenContext* context,
IRType* type,
DeclRef<AccessorDecl> accessorDeclRef,
LoweredValInfo base,
UInt argCount,
IRInst* const* args);
static LoweredValInfo _emitCallToAccessor(
IRGenContext* context,
IRType* type,
DeclRef<AccessorDecl> accessorDeclRef,
LoweredValInfo base,
List<IRInst*> const& args)
{
return _emitCallToAccessor(
context,
type,
accessorDeclRef,
base,
args.getCount(),
args.getBuffer());
}
/// Lower a reference to abstract storage (a property or subscript).
///
/// The given `storageDeclRef` is being accessed on some `base` value,
/// to yield a value of some expected `type`. The additional `args`
/// are only needed in the case of a subscript declaration (for
/// a property, `argCount` should be zero).
///
/// In the case where there is only a `get` accessor, this function
/// will go ahead and invoke it to produce a value here and now.
/// Otherwise, it will produce an abstract `LoweredValInfo` that
/// encapsulates the reference to the storage so that downstream
/// code can decide which accessor(s) to invoke.
///
[[maybe_unused]] static LoweredValInfo lowerStorageReference(
IRGenContext* context,
IRType* type,
DeclRef<ContainerDecl> storageDeclRef,
LoweredValInfo base,
UInt argCount,
IRInst* const* args)
{
DeclRef<GetterDecl> getterDeclRef;
bool justAGetter = true;
for (auto accessorDeclRef : getMembersOfType<AccessorDecl>(
context->astBuilder,
storageDeclRef,
MemberFilterStyle::Instance))
{
// We want to track whether this storage has any accessors other than
// `get` (assuming that everything except `get` can be used for setting...).
if (auto foundGetterDeclRef = accessorDeclRef.as<GetterDecl>())
{
// We found a getter.
getterDeclRef = foundGetterDeclRef;
}
else
{
// There was something other than a getter, so we can't
// invoke an accessor just now.
justAGetter = false;
}
}
if (!justAGetter || !getterDeclRef)
{
// 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 access operation (abstractly
// this is a reference to a storage location).
// The abstract storage location will need to include
// all the arguments being passed in the case of a subscript operation.
RefPtr<BoundStorageInfo> boundStorage = new BoundStorageInfo();
boundStorage->declRef = storageDeclRef;
boundStorage->type = type;
boundStorage->base = base;
boundStorage->additionalArgs.addRange(args, argCount);
context->shared->extValues.add(boundStorage);
return LoweredValInfo::boundStorage(boundStorage);
}
return _emitCallToAccessor(context, type, getterDeclRef, base, argCount, args);
}
IRInst* getFieldKey(IRGenContext* context, DeclRef<Decl> field)
{
return getSimpleVal(context, emitDeclRef(context, field, context->irBuilder->getKeyType()));
}
LoweredValInfo extractField(
IRGenContext* context,
IRType* fieldType,
LoweredValInfo base,
DeclRef<Decl> field)
{
IRBuilder* builder = context->irBuilder;
switch (base.flavor)
{
default:
{
IRInst* irBase = getSimpleVal(context, base);
return LoweredValInfo::simple(
builder->emitFieldExtract(fieldType, irBase, getFieldKey(context, field)));
}
break;
case LoweredValInfo::Flavor::BoundMember:
case LoweredValInfo::Flavor::BoundStorage:
{
// The base value is one that is trying to defer a get-vs-set
// decision, so we will need to do the same.
RefPtr<BoundMemberInfo> boundMemberInfo = new BoundMemberInfo();
boundMemberInfo->type = fieldType;
boundMemberInfo->base = base;
boundMemberInfo->declRef = field;
context->shared->extValues.add(boundMemberInfo);
return LoweredValInfo::boundMember(boundMemberInfo);
}
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.
IRInst* irBasePtr = base.val;
return LoweredValInfo::ptr(builder->emitFieldAddress(
builder->getPtrType(fieldType),
irBasePtr,
getFieldKey(context, field)));
}
break;
}
}
LoweredValInfo materialize(IRGenContext* context, LoweredValInfo lowered)
{
auto builder = context->irBuilder;
top:
switch (lowered.flavor)
{
case LoweredValInfo::Flavor::None:
case LoweredValInfo::Flavor::Simple:
case LoweredValInfo::Flavor::Ptr:
return lowered;
case LoweredValInfo::Flavor::BoundStorage:
{
auto boundStorageInfo = lowered.getBoundStorageInfo();
// We are being asked to extract a value from a subscript call
// (e.g., `base[index]`). We will first check if the subscript
// declared a getter and use that if possible, and then fall
// back to a `ref` accessor if one is defined.
//
// (Picking the `get` over the `ref` accessor simplifies things
// in case the `get` operation has a natural translation for
// a target, while the general `ref` case does not...)
auto getters = getMembersOfType<GetterDecl>(
context->astBuilder,
boundStorageInfo->declRef,
MemberFilterStyle::Instance);
if (getters.getCount())
{
auto getter = *getters.begin();
lowered = _emitCallToAccessor(
context,
boundStorageInfo->type,
getter,
boundStorageInfo->base,
boundStorageInfo->additionalArgs);
goto top;
}
auto refAccessors = getMembersOfType<RefAccessorDecl>(
context->astBuilder,
boundStorageInfo->declRef,
MemberFilterStyle::Instance);
if (refAccessors.getCount())
{
auto refAccessor = *refAccessors.begin();
// The `ref` accessor will return a pointer to the value, so
// we need to reflect that in the type of our `call` instruction.
IRType* ptrType = context->irBuilder->getPtrType(boundStorageInfo->type);
LoweredValInfo refVal = _emitCallToAccessor(
context,
ptrType,
refAccessor,
boundStorageInfo->base,
boundStorageInfo->additionalArgs);
// The result from the call needs to be implicitly dereferenced,
// so that it can work as an l-value of the desired result type.
lowered = LoweredValInfo::ptr(getSimpleVal(context, refVal));
goto top;
}
// TODO: Ellie, Is this really unreachable? User code input can get here
SLANG_UNEXPECTED("subscript had no getter");
UNREACHABLE_RETURN(LoweredValInfo());
}
break;
case LoweredValInfo::Flavor::BoundMember:
{
auto boundMemberInfo = lowered.getBoundMemberInfo();
auto base = materialize(context, boundMemberInfo->base);
auto declRef = boundMemberInfo->declRef;
if (auto fieldDeclRef = declRef.as<VarDecl>())
{
lowered = extractField(context, boundMemberInfo->type, base, fieldDeclRef);
goto top;
}
else if (auto methodDeclRef = declRef.as<CallableDecl>())
{
auto funcVal = emitDeclRef(context, declRef, boundMemberInfo->type);
SLANG_RELEASE_ASSERT(funcVal.flavor == LoweredValInfo::Flavor::Simple);
lowered = funcVal;
goto top;
}
else
{
SLANG_UNEXPECTED("unexpected member flavor");
UNREACHABLE_RETURN(LoweredValInfo());
}
}
break;
case LoweredValInfo::Flavor::SwizzledLValue:
{
auto swizzleInfo = lowered.getSwizzledLValueInfo();
return LoweredValInfo::simple(builder->emitSwizzle(
swizzleInfo->type,
getSimpleVal(context, swizzleInfo->base),
swizzleInfo->elementIndices.getCount(),
swizzleInfo->elementIndices.getArrayView().getBuffer()));
}
case LoweredValInfo::Flavor::SwizzledMatrixLValue:
{
auto swizzleInfo = lowered.getSwizzledMatrixLValueInfo();
auto base = getSimpleVal(context, swizzleInfo->base);
if (const auto type = as<IRMatrixType>(base->getDataType()))
{
IRInst* components[4];
for (UInt i = 0; i < swizzleInfo->elementCount; ++i)
{
components[i] = builder->emitElementExtract(
builder->emitElementExtract(base, swizzleInfo->elementCoords[i].row),
swizzleInfo->elementCoords[i].col);
}
return swizzleInfo->elementCount == 1
? LoweredValInfo::simple(components[0])
: LoweredValInfo::simple(builder->emitMakeVector(
builder->getVectorType(
type->getElementType(),
swizzleInfo->elementCount),
swizzleInfo->elementCount,
components));
}
else
{
SLANG_UNEXPECTED("Expected a matrix type in matrix swizzle");
}
}
case LoweredValInfo::Flavor::ExtractedExistential:
{
auto info = lowered.getExtractedExistentialValInfo();
return LoweredValInfo::simple(info->extractedVal);
}
case LoweredValInfo::Flavor::ImplicitCastedLValue:
{
auto info = lowered.getImplicitCastedLValue();
auto baseVal = materialize(context, info->base);
auto result = builder->emitCast(info->type, getSimpleVal(context, baseVal));
return LoweredValInfo::simple(result);
}
default:
SLANG_UNEXPECTED("unhandled value flavor");
UNREACHABLE_RETURN(LoweredValInfo());
}
}
IRInst* getSimpleVal(IRGenContext* context, LoweredValInfo lowered)
{
auto builder = context->irBuilder;
// First, try to eliminate any "bound" operations along the chain,
// so that we are dealing with an ordinary value, or an l-value pointer.
lowered = materialize(context, lowered);
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);
default:
SLANG_UNEXPECTED("unhandled value flavor");
UNREACHABLE_RETURN(nullptr);
}
}
LoweredValInfo lowerVal(IRGenContext* context, Val* val);
IRInst* lowerSimpleVal(IRGenContext* context, Val* val)
{
auto lowered = lowerVal(context, val);
return getSimpleVal(context, lowered);
}
LoweredValInfo lowerLValueExpr(IRGenContext* context, Expr* expr);
void assign(IRGenContext* context, LoweredValInfo const& left, LoweredValInfo const& right);
void assignExpr(
IRGenContext* context,
const LoweredValInfo& inLeft,
Expr* rightExpr,
SourceLoc assignmentLoc);
IRInst* getAddress(
IRGenContext* context,
LoweredValInfo const& inVal,
SourceLoc diagnosticLocation);
void lowerStmt(IRGenContext* context, Stmt* stmt);
LoweredValInfo lowerDecl(IRGenContext* context, DeclBase* decl);
IRType* getIntType(IRGenContext* context)
{
return context->irBuilder->getBasicType(BaseType::Int);
}
static IRGeneric* getOuterGeneric(IRInst* gv)
{
auto parentBlock = as<IRBlock>(gv->getParent());
if (!parentBlock)
return nullptr;
auto parentGeneric = as<IRGeneric>(parentBlock->getParent());
return parentGeneric;
}
static void addLinkageDecoration(
IRGenContext* context,
IRInst* inInst,
Decl* decl,
UnownedStringSlice const& mangledName)
{
// If the instruction is nested inside one or more generics,
// then the mangled name should really apply to the outer-most
// generic, and not the declaration nested inside.
auto builder = context->irBuilder;
IRInst* inst = inInst;
while (auto outerGeneric = getOuterGeneric(inst))
{
inst = outerGeneric;
}
bool explicitExtern = false;
if (isImportedDecl(context, decl, explicitExtern))
{
builder->addImportDecoration(inst, mangledName);
if (explicitExtern)
builder->addUserExternDecoration(inst);
}
else
{
builder->addExportDecoration(inst, mangledName);
}
for (auto modifier : decl->modifiers)
{
if (as<PublicModifier>(modifier))
{
builder->addPublicDecoration(inst);
}
else if (as<HLSLExportModifier>(modifier))
{
builder->addHLSLExportDecoration(inst);
builder->addKeepAliveDecoration(inst);
}
else if (as<ExternCppModifier>(modifier))
{
builder->addExternCppDecoration(inst, mangledName);
}
else if (auto dllImportModifier = as<DllImportAttribute>(modifier))
{
auto libraryName = dllImportModifier->modulePath;
auto functionName = dllImportModifier->functionName.getLength()
? dllImportModifier->functionName.getUnownedSlice()
: decl->getName()->text.getUnownedSlice();
builder->addDllImportDecoration(inst, libraryName.getUnownedSlice(), functionName);
}
else if (as<DllExportAttribute>(modifier))
{
builder->addDllExportDecoration(inst, decl->getName()->text.getUnownedSlice());
builder->addHLSLExportDecoration(inst);
builder->addKeepAliveDecoration(inst);
}
else if (as<CudaDeviceExportAttribute>(modifier))
{
builder->addCudaDeviceExportDecoration(inst, decl->getName()->text.getUnownedSlice());
builder->addHLSLExportDecoration(inst);
builder->addExternCppDecoration(inst, decl->getName()->text.getUnownedSlice());
builder->addKeepAliveDecoration(inst);
}
else if (as<CudaHostAttribute>(modifier))
{
builder->addCudaHostDecoration(inst);
builder->addExternCppDecoration(inst, decl->getName()->text.getUnownedSlice());
builder->addKeepAliveDecoration(inst);
}
else if (as<CudaKernelAttribute>(modifier))
{
builder->addCudaKernelDecoration(inst);
builder->addExternCppDecoration(inst, decl->getName()->text.getUnownedSlice());
// Temp decorations to get this function through the linker.
builder->addKeepAliveDecoration(inst);
builder->addHLSLExportDecoration(inst);
}
else if (as<TorchEntryPointAttribute>(modifier))
{
builder->addTorchEntryPointDecoration(inst, decl->getName()->text.getUnownedSlice());
builder->addCudaHostDecoration(inst);
builder->addExternCppDecoration(inst, decl->getName()->text.getUnownedSlice());
// Temp decorations to get this function through the linker.
builder->addKeepAliveDecoration(inst);
builder->addHLSLExportDecoration(inst);
}
else if (as<AutoPyBindCudaAttribute>(modifier))
{
builder->addAutoPyBindCudaDecoration(inst, decl->getName()->text.getUnownedSlice());
builder->addAutoPyBindExportInfoDecoration(inst);
// Temp decorations to get this function through the linker.
builder->addKeepAliveDecoration(inst);
builder->addHLSLExportDecoration(inst);
}
else if (auto pyExportModifier = as<PyExportAttribute>(modifier))
{
builder->addPyExportDecoration(
inst,
pyExportModifier->name.getLength() ? pyExportModifier->name.getUnownedSlice()
: decl->getName()->text.getUnownedSlice());
builder->addHLSLExportDecoration(inst);
}
else if (auto knownBuiltinModifier = as<KnownBuiltinAttribute>(modifier))
{
// We add this to the internal instruction, like other name-like
// decorations, for instance "nameHint". This prevents it becoming
// lost during specialization.
auto constantIntVal = as<ConstantIntVal>(knownBuiltinModifier->name);
if (constantIntVal)
{
auto enumValue = constantIntVal->getValue();
builder->addKnownBuiltinDecoration(inInst, KnownBuiltinDeclName(enumValue));
}
}
}
if (as<InterfaceDecl>(decl->parentDecl) &&
decl->parentDecl->hasModifier<ComInterfaceAttribute>() &&
!inst->findDecoration<IRExternCppDecoration>())
{
builder->addExternCppDecoration(inst, decl->getName()->text.getUnownedSlice());
}
}
static void addLinkageDecoration(IRGenContext* context, IRInst* inst, Decl* decl)
{
const String mangledName = getMangledName(context->astBuilder, decl);
// Obfuscate the mangled names if necessary.
//
// Care is needed around the core module as it is only compiled once and *without* obfuscation,
// so any linkage name to the core module *shouldn't* have obfuscation applied to it.
if (context->shared->m_obfuscateCode && !isFromCoreModule(decl))
{
const auto obfuscatedName = getHashedName(mangledName.getUnownedSlice());
addLinkageDecoration(context, inst, decl, obfuscatedName.getUnownedSlice());
}
else
{
addLinkageDecoration(context, inst, decl, mangledName.getUnownedSlice());
}
}
bool shouldDeclBeTreatedAsInterfaceRequirement(Decl* requirementDecl)
{
if (const auto funcDecl = as<CallableDecl>(requirementDecl))
{
// Subscript decl itself won't have a witness table entry.
// But its accessors will.
if (const auto subscriptDecl = as<SubscriptDecl>(requirementDecl))
return false;
}
else if (const auto assocTypeDecl = as<AssocTypeDecl>(requirementDecl))
{
}
else if (const auto typeConstraint = as<TypeConstraintDecl>(requirementDecl))
{
}
else if (const auto varDecl = as<VarDeclBase>(requirementDecl))
{
}
else if (as<AccessorDecl>(requirementDecl))
{
}
else if (as<InterfaceDefaultImplDecl>(requirementDecl))
{
// A default impl stub function represents a concrete function, not
// a requirement.
return false;
}
else if (const auto genericDecl = as<GenericDecl>(requirementDecl))
{
return shouldDeclBeTreatedAsInterfaceRequirement(genericDecl->inner);
}
else
{
// We will return false for PropertyDecl because the property decl itself
// won't have a witness table entry. Instead there will be witness entries
// for its accessors.
return false;
}
return true;
}
IRStructKey* getInterfaceRequirementKey(IRGenContext* context, Decl* requirementDecl)
{
// Only specific types of decls are treated as requirements, e.g. methods and asssociated types.
// Other types of decls are allowed but not regarded as a requirement.
if (!shouldDeclBeTreatedAsInterfaceRequirement(requirementDecl))
return nullptr;
// TODO: this special case logic can be removed if we also clean up
// `doesGenericSignatureMatchRequirement` Currently `doesGenericSignatureMatchRequirement` will
// use the inner func decl as the key in AST WitnessTable. Therefore we need to match this
// behavior by always using the inner decl as the requirement key.
if (auto genericDecl = as<GenericDecl>(requirementDecl))
return getInterfaceRequirementKey(context, genericDecl->inner);
IRStructKey* requirementKey = nullptr;
if (context->shared->interfaceRequirementKeys.tryGetValue(requirementDecl, requirementKey))
{
return requirementKey;
}
IRBuilder builderStorage = *context->irBuilder;
auto builder = &builderStorage;
builder->setInsertInto(builder->getModule());
// Construct a key to serve as the representation of
// this requirement in the IR, and to allow lookup
// into the declaration.
requirementKey = builder->createStructKey();
addLinkageDecoration(context, requirementKey, requirementDecl);
context->shared->interfaceRequirementKeys.add(requirementDecl, requirementKey);
return requirementKey;
}
void getGenericTypeConformances(
IRGenContext* context,
ShortList<IRType*>& supTypes,
Decl* genericParamDecl)
{
auto parent = genericParamDecl->parentDecl;
if (parent)
{
for (auto typeConstraint : parent->getMembersOfType<GenericTypeConstraintDecl>())
{
if (auto declRefType = as<DeclRefType>(typeConstraint->sub.type))
{
if (declRefType->getDeclRef().getDecl() == genericParamDecl)
{
supTypes.add(lowerType(context, typeConstraint->getSup().type));
}
}
}
}
}
// Check if declRef represents a witness that `ISomeInterface.This : ISomeInterface`.
static bool _isThisTypeSubtypeWitness(DeclRefBase* declRef)
{
auto lookupDeclRef = as<LookupDeclRef>(declRef);
if (!lookupDeclRef)
return false;
if (!as<ThisType>(lookupDeclRef->getLookupSource()))
return false;
auto declaredWitness = as<DeclaredSubtypeWitness>(lookupDeclRef->getWitness());
if (!declaredWitness)
return false;
if (!as<ThisTypeConstraintDecl>(declaredWitness->getDeclRef()))
return false;
return true;
}
// Returns whether `declRef` represents a trivial lookup of an interface requirement
// through `ThisTypeDecl` made from within the same interface Decl.
static bool _isTrivialLookupFromInterfaceThis(IRGenContext* context, DeclRefBase* declRef)
{
if (!_isThisTypeSubtypeWitness(declRef))
return false;
// This is a lookup from an interface's This type.
// If the lookup is made from an interface type itself rather than an extension of it,
// then it is a trivial lookup and we should lower it as a struct key.
return context->thisTypeWitness == nullptr;
}
struct ValLoweringVisitor : ValVisitor<ValLoweringVisitor, LoweredValInfo, LoweredValInfo>
{
IRGenContext* context;
IRBuilder* getBuilder() { return context->irBuilder; }
LoweredValInfo visitVal(Val* /*val*/)
{
SLANG_UNIMPLEMENTED_X("value lowering");
UNREACHABLE_RETURN(LoweredValInfo());
}
LoweredValInfo visitDeclRefIntVal(DeclRefIntVal* val)
{
return emitDeclRef(
context,
val->getDeclRef(),
lowerType(context, getType(context->astBuilder, val->getDeclRef())));
}
LoweredValInfo visitFuncCallIntVal(FuncCallIntVal* val)
{
TryClauseEnvironment tryEnv;
List<IRInst*> args;
IRType* specConstRateType = nullptr;
for (auto arg : val->getArgs())
{
auto loweredArg = lowerVal(context, arg);
args.add(loweredArg.val);
if (!specConstRateType && isSpecConstRateType(loweredArg.val->getFullType()))
specConstRateType = loweredArg.val->getFullType();
}
auto funcType = lowerType(context, val->getFuncType());
auto funcResType = maybeAddRateType(
getBuilder(),
specConstRateType,
as<IRFuncType>(funcType)->getResultType());
auto resVal =
emitCallToDeclRef(context, funcResType, val->getFuncDeclRef(), funcType, args, tryEnv);
return resVal;
}
LoweredValInfo visitTypeCastIntVal(TypeCastIntVal* val)
{
auto baseVal = lowerVal(context, val->getBase());
SLANG_ASSERT(baseVal.flavor == LoweredValInfo::Flavor::Simple);
auto type = lowerType(context, val->getType());
type = maybeAddRateType(getBuilder(), baseVal.val->getFullType(), type);
auto resVal = LoweredValInfo::simple(getBuilder()->emitCast(type, baseVal.val));
return resVal;
}
LoweredValInfo visitWitnessLookupIntVal(WitnessLookupIntVal* val)
{
auto witnessVal = lowerVal(context, val->getWitness());
auto key = getInterfaceRequirementKey(context, val->getKey());
auto type = lowerType(context, val->getType());
return LoweredValInfo::simple(
getBuilder()->emitLookupInterfaceMethodInst(type, witnessVal.val, key));
}
LoweredValInfo visitPolynomialIntVal(PolynomialIntVal* val)
{
auto irBuilder = getBuilder();
auto type = lowerType(context, val->getType());
auto constTerm = irBuilder->getIntValue(type, val->getConstantTerm());
auto resultVal = constTerm;
for (auto term : val->getTerms())
{
auto termVal = irBuilder->getIntValue(type, term->getConstFactor());
for (auto factor : term->getParamFactors())
{
auto factorVal = lowerVal(context, factor->getParam()).val;
for (IntegerLiteralValue i = 0; i < factor->getPower(); i++)
{
termVal = irBuilder->emitMul(factorVal->getFullType(), termVal, factorVal);
}
}
resultVal = irBuilder->emitAdd(termVal->getFullType(), resultVal, termVal);
}
return LoweredValInfo::simple(resultVal);
}
LoweredValInfo visitSizeOfIntVal(SizeOfIntVal* val)
{
auto irBuilder = getBuilder();
auto typeArg = lowerType(context, as<Type>(val->getTypeArg()));
auto count = irBuilder->emitSizeOf(typeArg);
return LoweredValInfo::simple(count);
}
LoweredValInfo visitAlignOfIntVal(AlignOfIntVal* val)
{
auto irBuilder = getBuilder();
auto typeArg = lowerType(context, as<Type>(val->getTypeArg()));
auto count = irBuilder->emitAlignOf(typeArg);
return LoweredValInfo::simple(count);
}
LoweredValInfo visitCountOfIntVal(CountOfIntVal* val)
{
auto irBuilder = getBuilder();
auto type = lowerType(context, val->getType());
auto typeArg = lowerType(context, as<Type>(val->getTypeArg()));
auto count = irBuilder->emitCountOf(type, typeArg);
return LoweredValInfo::simple(count);
}
LoweredValInfo visitConcreteTypePack(ConcreteTypePack* typePack)
{
ShortList<IRType*> types;
for (Index i = 0; i < typePack->getTypeCount(); i++)
{
auto loweredType = lowerType(context, typePack->getElementType(i));
types.add(loweredType);
}
auto irBuilder = getBuilder();
IRType* irTypePack =
irBuilder->getTypePack((UInt)types.getCount(), types.getArrayView().getBuffer());
return LoweredValInfo::simple(irTypePack);
}
LoweredValInfo visitEachType(EachType* eachType)
{
auto type = lowerType(context, eachType->getElementType());
return LoweredValInfo::simple(
getBuilder()->emitEachInst(getBuilder()->getTypeKind(), type));
}
LoweredValInfo visitExpandType(ExpandType* expandType)
{
auto irBuilder = getBuilder();
auto type = lowerType(context, expandType->getPatternType());
ShortList<IRInst*> capturedTypes;
for (Index i = 0; i < expandType->getCapturedTypePackCount(); i++)
{
auto loweredType = lowerType(context, expandType->getCapturedTypePack(i));
capturedTypes.add(loweredType);
}
return LoweredValInfo::simple(irBuilder->getExpandTypeOrVal(
irBuilder->getTypeKind(),
type,
capturedTypes.getArrayView().arrayView));
}
LoweredValInfo visitTypePackSubtypeWitness(TypePackSubtypeWitness* witnessPack)
{
auto irBuilder = getBuilder();
ShortList<IRInst*> witnesses;
ShortList<IRType*> elementTypes;
for (Index i = 0; i < witnessPack->getCount(); i++)
{
auto loweredWitness = lowerVal(context, witnessPack->getWitness(i));
witnesses.add(loweredWitness.val);
elementTypes.add(loweredWitness.val->getFullType());
}
auto irWitnessPack = irBuilder->emitMakeWitnessPack(
irBuilder->getTupleType(
(UInt)elementTypes.getCount(),
elementTypes.getArrayView().getBuffer()),
witnesses.getArrayView().arrayView);
return LoweredValInfo::simple(irWitnessPack);
}
LoweredValInfo visitExpandSubtypeWitness(ExpandSubtypeWitness* witness)
{
auto irBuilder = getBuilder();
auto patternWitnessVal = lowerVal(context, witness->getPatternTypeWitness());
auto subType = lowerType(context, witness->getSub());
auto supType = lowerType(context, witness->getSup());
auto witnessTableType = irBuilder->getWitnessTableType(supType);
ShortList<IRInst*> captures;
if (auto expandType = as<IRExpandTypeOrVal>(subType))
{
for (UInt i = 0; i < expandType->getCaptureCount(); i++)
{
captures.add(expandType->getCaptureType(i));
}
}
return LoweredValInfo::simple(irBuilder->getExpandTypeOrVal(
witnessTableType,
patternWitnessVal.val,
captures.getArrayView().arrayView));
}
LoweredValInfo visitEachSubtypeWitness(EachSubtypeWitness* witness)
{
auto elementWitness = lowerVal(context, witness->getPatternTypeWitness());
auto irBuilder = getBuilder();
auto subType = lowerType(context, witness->getSub());
auto witnessTableType = irBuilder->getWitnessTableType(subType);
return LoweredValInfo::simple(
irBuilder->emitEachInst(witnessTableType, getSimpleVal(context, elementWitness)));
}
LoweredValInfo visitDeclaredSubtypeWitness(DeclaredSubtypeWitness* val)
{
if (as<ThisTypeConstraintDecl>(val->getDeclRef()))
return LoweredValInfo::simple(context->thisTypeWitness);
return emitDeclRef(
context,
val->getDeclRef(),
context->irBuilder->getWitnessTableType(lowerType(context, val->getSup())));
}
LoweredValInfo visitTypeEqualityWitness(TypeEqualityWitness* val)
{
auto subType = lowerType(context, val->getSub());
auto supType = lowerType(context, val->getSup());
auto witnessType =
context->irBuilder->getWitnessTableType(lowerType(context, val->getSup()));
return LoweredValInfo::simple(
context->irBuilder->getTypeEqualityWitness(witnessType, subType, supType));
}
LoweredValInfo visitTypeCoercionWitness(TypeCoercionWitness*)
{
// When we fully support type coercion constraints, we should lower the witness into a
// function that does the conversion.
return LoweredValInfo();
}
LoweredValInfo visitTransitiveSubtypeWitness(TransitiveSubtypeWitness* val)
{
// The base (subToMid) will turn into a value with
// witness-table type.
IRInst* baseWitnessTable = lowerSimpleVal(context, val->getSubToMid());
IRInst* midToSup = nullptr;
// The next step should map to an interface requirement
// that is itself an interface conformance, so the result
// of lowering this value should be a "key" that we can
// use to look up a witness table.
//
// TODO: There are some ugly cases here if `midToSup` is allowed
// to be an arbitrary witness, rather than just a declared one,
// and we probably need to change the logic here so that we
// instead think in terms of applying a subtype witness to
// either a value or a witness table, to perform the appropriate
// casting/lookup logic.
//
// For now we rely on the fact that the front-end doesn't
// produce transitive witnesses in shapes that will cuase us
// problems here.
//
SLANG_RELEASE_ASSERT(baseWitnessTable);
if (auto declaredMidToSup = as<DeclaredSubtypeWitness>(val->getMidToSup()))
{
midToSup =
getInterfaceRequirementKey(context, declaredMidToSup->getDeclRef().getDecl());
}
else
{
midToSup = lowerSimpleVal(context, val->getMidToSup());
}
return LoweredValInfo::simple(getBuilder()->emitLookupInterfaceMethodInst(
getBuilder()->getWitnessTableType(lowerType(context, val->getSup())),
baseWitnessTable,
midToSup));
}
LoweredValInfo visitForwardDifferentiateVal(ForwardDifferentiateVal* val)
{
// TODO: properly fill in type info here.
// We should consider fold all cases of witness table entries to `Val`, and make the
// `DeclRef` case a `DeclRefVal`. So that we can hold the type in `DeclRefVal`.
auto funcVal = emitDeclRef(context, val->getFunc(), context->irBuilder->getTypeKind());
SLANG_RELEASE_ASSERT(funcVal.flavor == LoweredValInfo::Flavor::Simple);
auto diff =
getBuilder()->emitForwardDifferentiateInst(getBuilder()->getTypeKind(), funcVal.val);
return LoweredValInfo::simple(diff);
}
LoweredValInfo visitBackwardDifferentiateVal(BackwardDifferentiateVal* val)
{
auto funcVal = emitDeclRef(context, val->getFunc(), context->irBuilder->getTypeKind());
SLANG_RELEASE_ASSERT(funcVal.flavor == LoweredValInfo::Flavor::Simple);
auto diff =
getBuilder()->emitBackwardDifferentiateInst(getBuilder()->getTypeKind(), funcVal.val);
return LoweredValInfo::simple(diff);
}
LoweredValInfo visitBackwardDifferentiatePropagateVal(BackwardDifferentiatePropagateVal* val)
{
auto funcVal = emitDeclRef(context, val->getFunc(), context->irBuilder->getTypeKind());
SLANG_RELEASE_ASSERT(funcVal.flavor == LoweredValInfo::Flavor::Simple);
auto diff = getBuilder()->emitBackwardDifferentiatePropagateInst(
getBuilder()->getTypeKind(),
funcVal.val);
return LoweredValInfo::simple(diff);
}
LoweredValInfo visitBackwardDifferentiatePrimalVal(BackwardDifferentiatePrimalVal* val)
{
auto funcVal = emitDeclRef(context, val->getFunc(), context->irBuilder->getTypeKind());
SLANG_RELEASE_ASSERT(funcVal.flavor == LoweredValInfo::Flavor::Simple);
auto diff = getBuilder()->emitBackwardDifferentiatePrimalInst(
getBuilder()->getTypeKind(),
funcVal.val);
return LoweredValInfo::simple(diff);
}
LoweredValInfo visitBackwardDifferentiateIntermediateTypeVal(
BackwardDifferentiateIntermediateTypeVal* val)
{
auto funcVal = emitDeclRef(context, val->getFunc(), context->irBuilder->getTypeKind());
SLANG_RELEASE_ASSERT(funcVal.flavor == LoweredValInfo::Flavor::Simple);
auto diff = getBuilder()->getBackwardDiffIntermediateContextType(funcVal.val);
return LoweredValInfo::simple(diff);
}
LoweredValInfo visitDynamicSubtypeWitness(DynamicSubtypeWitness* /*val*/)
{
return LoweredValInfo::simple(nullptr);
}
LoweredValInfo visitConjunctionSubtypeWitness(ConjunctionSubtypeWitness* val)
{
// A witness `W = X & Y & ...` will lower as a tuple of the sub-witnesses
// `X`, `Y`, etc.
//
// The AST representation of a conjunction of witnesses matches this
// tuple-like encoding very closely, so we can simply lower each of
// the component witnesses to produce our result.
//
List<IRInst*> componentWitnesses;
auto componentCount = val->getComponentCount();
for (Index i = 0; i < componentCount; ++i)
{
auto componentWitness = lowerSimpleVal(context, val->getComponentWitness(i));
componentWitnesses.add(componentWitness);
}
return LoweredValInfo::simple(getBuilder()->emitMakeTuple(componentWitnesses));
}
LoweredValInfo visitExtractFromConjunctionSubtypeWitness(
ExtractFromConjunctionSubtypeWitness* val)
{
auto builder = getBuilder();
// We know from `visitConjunctionSubtypeWitness` that a witness for a relationship
// like `T : L & R` will be a tuple `(w_l, w_r)` where `w_l` is a witness
// for `T : L` and `w_r` will be a witness for `T : R`.
//
// An `ExtractFromConjunctionSubtypeWitness` represents the intention to
// extract one of those two sub-witnesses. It directly stores the original
// witness that `T : L & R`, so lower that first and expect it to be
// a value of tuple type.
//
auto conjunctionWitness = lowerSimpleVal(context, val->getConjunctionWitness());
auto conjunctionTupleType = as<IRTupleType>(conjunctionWitness->getDataType());
SLANG_ASSERT(conjunctionTupleType);
// The `ExtractFromConjunctionSubtypeWitness` also stores the index of
// the witness/supertype we want in the conjunction `L & R`.
//
auto indexInConjunction = val->getIndexInConjunction();
// We want to extract the appropriate element from the tuple based on
// the index, but to know the type of the result we need to look up
// the element type that corresponds to that index.
//
// TODO: `IRTupleType` should really have `getElementCount()` and
// `getElementType(index)` accessors.
//
auto elementType = (IRType*)conjunctionTupleType->getOperand(indexInConjunction);
// With the information we've extracted above, we now just need to
// extract the appropriate element from the `(w_l, w_r)` tuple of
// witnesses, and we will have our desired result.
//
return LoweredValInfo::simple(
builder->emitGetTupleElement(elementType, conjunctionWitness, indexInConjunction));
}
LoweredValInfo visitNoneWitness(NoneWitness*)
{
auto builder = getBuilder();
auto voidType = builder->getVoidType();
return LoweredValInfo::simple(builder->createWitnessTable(voidType, voidType));
}
LoweredValInfo visitConstantIntVal(ConstantIntVal* val)
{
auto type = lowerType(context, val->getType());
return LoweredValInfo::simple(getBuilder()->getIntValue(type, val->getValue()));
}
IRType* visitDifferentialPairType(DifferentialPairType* pairType)
{
IRType* primalType = lowerType(context, pairType->getPrimalType());
if (as<IRAssociatedType>(primalType) || as<IRThisType>(primalType))
{
List<IRInst*> operands;
SubstitutionSet(pairType->getDeclRef())
.forEachSubstitutionArg(
[&](Val* arg)
{
auto argVal = lowerVal(context, arg).val;
SLANG_ASSERT(argVal);
operands.add(argVal);
});
auto undefined = getBuilder()->emitUndefined(operands[1]->getFullType());
return getBuilder()->getDifferentialPairUserCodeType(primalType, undefined);
}
else
return lowerSimpleIntrinsicType(pairType);
}
IRFuncType* visitFuncType(FuncType* type)
{
IRType* resultType = lowerType(context, type->getResultType());
Index paramCount = type->getParamCount();
List<IRType*> paramTypes;
for (Index pp = 0; pp < paramCount; ++pp)
{
paramTypes.add(lowerType(context, type->getParamTypeWithDirectionWrapper(pp)));
}
if (type->getErrorType()->equals(context->astBuilder->getBottomType()))
{
return getBuilder()->getFuncType(paramCount, paramTypes.getBuffer(), resultType);
}
else
{
auto errorType = lowerType(context, type->getErrorType());
IRInst* operands[] = {errorType};
auto irThrowFuncTypeAttribute =
getBuilder()->getAttr(kIROp_FuncThrowTypeAttr, 1, operands);
return getBuilder()->getFuncType(
paramCount,
paramTypes.getBuffer(),
resultType,
irThrowFuncTypeAttribute);
}
}
IRType* visitPtrType(PtrType* type)
{
auto astValueType = type->getValueType();
IRType* irValueType = lowerType(context, astValueType);
IRInst* accessQualifier = nullptr;
IRInst* addrSpace = nullptr;
if (auto astAccessQualifier = type->getAccessQualifier())
{
accessQualifier = getSimpleVal(context, lowerVal(context, astAccessQualifier));
}
if (auto astAddrSpace = type->getAddressSpace())
{
addrSpace = getSimpleVal(context, lowerVal(context, astAddrSpace));
}
else
{
addrSpace = getBuilder()->getIntValue(
getBuilder()->getUInt64Type(),
(IRIntegerValue)AddressSpace::Generic);
}
return getBuilder()->getPtrType(kIROp_PtrType, irValueType, accessQualifier, addrSpace);
}
IRType* visitDeclRefType(DeclRefType* type)
{
auto declRef = type->getDeclRef();
auto decl = declRef.getDecl();
// Check for types with teh `__intrinsic_type` modifier.
if (decl->findModifier<IntrinsicTypeModifier>())
{
return lowerSimpleIntrinsicType(type);
}
return (IRType*)getSimpleVal(
context,
emitDeclRef(context, declRef, context->irBuilder->getTypeKind()));
}
IRType* visitTupleType(TupleType* type)
{
List<IRType*> elementTypes;
if (as<ConcreteTypePack>(type->getTypePack()))
{
for (Index i = 0; i < type->getMemberCount(); i++)
{
elementTypes.add(lowerType(context, type->getMember(i)));
}
return context->irBuilder->getTupleType(elementTypes);
}
else
{
return context->irBuilder->getTupleType(lowerType(context, type->getTypePack()));
}
}
IRType* visitNamedExpressionType(NamedExpressionType* type)
{
return (IRType*)getSimpleVal(context, dispatchType(type->getCanonicalType()));
}
IRType* visitBasicExpressionType(BasicExpressionType* type)
{
return getBuilder()->getBasicType(type->getBaseType());
}
IRType* visitVectorExpressionType(VectorExpressionType* type)
{
auto elementType = lowerType(context, type->getElementType());
auto elementCount = lowerSimpleVal(context, type->getElementCount());
return getBuilder()->getVectorType(elementType, elementCount);
}
IRType* visitMatrixExpressionType(MatrixExpressionType* type)
{
auto elementType = lowerType(context, type->getElementType());
auto rowCount = lowerSimpleVal(context, type->getRowCount());
auto columnCount = lowerSimpleVal(context, type->getColumnCount());
auto layout = lowerSimpleVal(context, type->getLayout());
return getBuilder()->getMatrixType(elementType, rowCount, columnCount, layout);
}
IRType* visitArrayExpressionType(ArrayExpressionType* type)
{
auto elementType = lowerType(context, type->getElementType());
if (!type->isUnsized())
{
return getBuilder()->getArrayType(
elementType,
lowerSimpleVal(context, type->getElementCount()));
}
else
{
return getBuilder()->getUnsizedArrayType(elementType);
}
}
// Lower a type where the type declaration being referenced is assumed
// to be an intrinsic type, which can thus be lowered to a simple IR
// type with the appropriate opcode.
IRType* lowerSimpleIntrinsicType(DeclRefType* type)
{
SLANG_ASSERT(getBuilder()->getInsertLoc().getMode() != IRInsertLoc::Mode::None);
auto intrinsicTypeModifier =
type->getDeclRef().getDecl()->findModifier<IntrinsicTypeModifier>();
SLANG_ASSERT(intrinsicTypeModifier);
IROp op = IROp(intrinsicTypeModifier->irOp);
List<IRInst*> operands;
// If there are any substitutions attached to the declRef,
// add them as operands of the IR type.
SubstitutionSet(type->getDeclRef())
.forEachSubstitutionArg(
[&](Val* arg)
{
auto argVal = lowerVal(context, arg).val;
SLANG_ASSERT(argVal);
operands.add(argVal);
});
return getBuilder()->getType(
op,
static_cast<UInt>(operands.getCount()),
operands.getBuffer());
}
IRType* visitResourceType(ResourceType* type) { return lowerSimpleIntrinsicType(type); }
IRType* visitSamplerStateType(SamplerStateType* type) { return lowerSimpleIntrinsicType(type); }
IRType* visitBuiltinGenericType(BuiltinGenericType* type)
{
return lowerSimpleIntrinsicType(type);
}
IRType* visitUntypedBufferResourceType(UntypedBufferResourceType* type)
{
return lowerSimpleIntrinsicType(type);
}
IRType* visitHLSLPatchType(HLSLPatchType* type) { return lowerSimpleIntrinsicType(type); }
IRType* visitMeshOutputType(MeshOutputType* type) { return lowerSimpleIntrinsicType(type); }
IRType* visitExtractExistentialType(ExtractExistentialType* type)
{
auto declRef = type->getDeclRef();
auto existentialType = lowerType(context, getType(context->astBuilder, declRef));
IRInst* existentialVal =
getSimpleVal(context, emitDeclRef(context, declRef, existentialType));
return getBuilder()->emitExtractExistentialType(existentialVal);
}
LoweredValInfo visitExtractExistentialSubtypeWitness(ExtractExistentialSubtypeWitness* witness)
{
auto declRef = witness->getDeclRef();
auto existentialType = lowerType(context, getType(context->astBuilder, declRef));
IRInst* existentialVal =
getSimpleVal(context, emitDeclRef(context, declRef, existentialType));
return LoweredValInfo::simple(
getBuilder()->emitExtractExistentialWitnessTable(existentialVal));
}
LoweredValInfo visitExistentialSpecializedType(ExistentialSpecializedType* type)
{
auto irBaseType = lowerType(context, type->getBaseType());
List<IRInst*> slotArgs;
for (Index i = 0; i < type->getArgCount(); i++)
{
auto arg = type->getArg(i);
auto irArgVal = lowerSimpleVal(context, arg.val);
slotArgs.add(irArgVal);
if (auto witness = arg.witness)
{
auto irArgWitness = lowerSimpleVal(context, witness);
slotArgs.add(irArgWitness);
}
}
auto irType = getBuilder()->getBindExistentialsType(
irBaseType,
slotArgs.getCount(),
slotArgs.getBuffer());
return LoweredValInfo::simple(irType);
}
LoweredValInfo visitThisType(ThisType* type)
{
// A `This` type in an interface decl should lower to `IRThisType`,
// while `This` type in a concrete `struct` should lower to the `struct` type
// itself. A `This` type reference in a concrete type is already translated to that
// type in semantics checking in this setting.
// If we see `This` type here, we are dealing with `This` inside an interface decl.
// Therefore, `context->thisType` should have been set to `IRThisType`
// in `visitInterfaceDecl`, and we can just use that value here.
//
if (context->thisType.irType)
{
return LoweredValInfo::simple(context->thisType.irType);
}
auto interfaceType =
emitDeclRef(context, type->getInterfaceDeclRef(), getBuilder()->getTypeKind());
auto result = LoweredValInfo::simple(
getBuilder()->getThisType((IRType*)getSimpleVal(context, interfaceType)));
if (context->thisType.astType == type)
{
context->thisType = getSimpleVal(context, result);
}
return result;
}
LoweredValInfo visitAndType(AndType* type)
{
auto left = lowerType(context, type->getLeft());
auto right = lowerType(context, type->getRight());
auto irType = getBuilder()->getConjunctionType(left, right);
return LoweredValInfo::simple(irType);
}
LoweredValInfo visitModifiedType(ModifiedType* astType)
{
IRType* irBase = lowerType(context, astType->getBase());
List<IRAttr*> irAttrs;
for (Index i = 0; i < astType->getModifierCount(); i++)
{
auto astModifier = astType->getModifier(i);
IRAttr* irAttr = (IRAttr*)lowerSimpleVal(context, astModifier);
if (irAttr)
irAttrs.add(irAttr);
}
auto irType = getBuilder()->getAttributedType(irBase, irAttrs);
return LoweredValInfo::simple(irType);
}
LoweredValInfo visitUNormModifierVal(UNormModifierVal* astVal)
{
SLANG_UNUSED(astVal);
return LoweredValInfo::simple(getBuilder()->getAttr(kIROp_UNormAttr));
}
LoweredValInfo visitSNormModifierVal(SNormModifierVal* astVal)
{
SLANG_UNUSED(astVal);
return LoweredValInfo::simple(getBuilder()->getAttr(kIROp_SNormAttr));
}
LoweredValInfo visitNoDiffModifierVal(NoDiffModifierVal* astVal)
{
SLANG_UNUSED(astVal);
return LoweredValInfo::simple(getBuilder()->getAttr(kIROp_NoDiffAttr));
}
// We do not expect to encounter the following types in ASTs that have
// passed front-end semantic checking.
#define UNEXPECTED_CASE(NAME) \
IRType* visit##NAME(NAME*) \
{ \
SLANG_UNEXPECTED(#NAME); \
UNREACHABLE_RETURN(nullptr); \
}
UNEXPECTED_CASE(GenericDeclRefType)
UNEXPECTED_CASE(TypeType)
UNEXPECTED_CASE(ErrorType)
UNEXPECTED_CASE(InitializerListType)
UNEXPECTED_CASE(OverloadGroupType)
UNEXPECTED_CASE(NamespaceType)
#undef UNEXPECTED_CASE
};
LoweredValInfo lowerVal(IRGenContext* context, Val* val)
{
ValLoweringVisitor visitor;
visitor.context = context;
auto resolvedVal = val->resolve();
return visitor.dispatch(resolvedVal);
}
IRType* lowerType(IRGenContext* context, Type* type)
{
ValLoweringVisitor visitor;
visitor.context = context;
IRType* loweredType = (IRType*)getSimpleVal(context, visitor.dispatchType(type));
if (context->lowerTypeCallback && loweredType)
context->lowerTypeCallback(context, type, loweredType);
return loweredType;
}
void addVarDecorations(IRGenContext* context, IRInst* inst, Decl* decl)
{
auto builder = context->irBuilder;
for (Modifier* mod : decl->modifiers)
{
if (as<HLSLNoInterpolationModifier>(mod))
{
builder->addInterpolationModeDecoration(inst, IRInterpolationMode::NoInterpolation);
}
else if (as<PerVertexModifier>(mod))
{
builder->addInterpolationModeDecoration(inst, IRInterpolationMode::PerVertex);
}
else if (as<HLSLNoPerspectiveModifier>(mod))
{
builder->addInterpolationModeDecoration(inst, IRInterpolationMode::NoPerspective);
}
else if (as<HLSLLinearModifier>(mod))
{
builder->addInterpolationModeDecoration(inst, IRInterpolationMode::Linear);
}
else if (as<HLSLSampleModifier>(mod))
{
builder->addInterpolationModeDecoration(inst, IRInterpolationMode::Sample);
}
else if (as<HLSLCentroidModifier>(mod))
{
builder->addInterpolationModeDecoration(inst, IRInterpolationMode::Centroid);
}
else if (auto rayPayloadAttr = as<VulkanRayPayloadAttribute>(mod))
{
builder->addVulkanRayPayloadDecoration(inst, rayPayloadAttr->location);
// may not be referenced; adding HLSL export modifier force emits
builder->addHLSLExportDecoration(inst);
}
else if (auto rayPayloadInAttr = as<VulkanRayPayloadInAttribute>(mod))
{
builder->addVulkanRayPayloadInDecoration(inst, rayPayloadInAttr->location);
// may not be referenced; adding HLSL export modifier force emits
builder->addHLSLExportDecoration(inst);
}
else if (auto callablePayloadAttr = as<VulkanCallablePayloadAttribute>(mod))
{
builder->addVulkanCallablePayloadDecoration(inst, callablePayloadAttr->location);
// may not be referenced; adding HLSL export modifier force emits
builder->addHLSLExportDecoration(inst);
}
else if (auto callablePayloadInAttr = as<VulkanCallablePayloadInAttribute>(mod))
{
builder->addVulkanCallablePayloadInDecoration(inst, callablePayloadInAttr->location);
// may not be referenced; adding HLSL export modifier force emits
builder->addHLSLExportDecoration(inst);
}
else if (auto hitObjectAttr = as<VulkanHitObjectAttributesAttribute>(mod))
{
builder->addVulkanHitObjectAttributesDecoration(inst, hitObjectAttr->location);
// may not be referenced; adding HLSL export modifier force emits
builder->addHLSLExportDecoration(inst);
}
else if (as<VulkanHitAttributesAttribute>(mod))
{
builder->addSimpleDecoration<IRVulkanHitAttributesDecoration>(inst);
// may not be referenced; adding HLSL export modifier force emits
builder->addHLSLExportDecoration(inst);
}
else if (as<PreciseModifier>(mod))
{
builder->addSimpleDecoration<IRPreciseDecoration>(inst);
}
else if (auto formatAttr = as<FormatAttribute>(mod))
{
builder->addFormatDecoration(inst, formatAttr->format);
}
else if (as<HLSLPayloadModifier>(mod))
{
builder->addSimpleDecoration<IRHLSLMeshPayloadDecoration>(inst);
}
else if (as<OutModifier>(mod))
{
builder->addSimpleDecoration<IRGlobalOutputDecoration>(inst);
}
else if (as<InModifier>(mod))
{
builder->addSimpleDecoration<IRGlobalInputDecoration>(inst);
}
else if (auto glslLocationMod = as<GLSLLocationAttribute>(mod))
{
builder->addDecoration(
inst,
kIROp_GLSLLocationDecoration,
builder->getIntValue(builder->getIntType(), glslLocationMod->value));
}
else if (auto glslOffsetMod = as<GLSLOffsetLayoutAttribute>(mod))
{
builder->addDecoration(
inst,
kIROp_GLSLOffsetDecoration,
builder->getIntValue(builder->getIntType(), glslOffsetMod->offset));
}
else if (auto glslStructOffsetMod = as<VkStructOffsetAttribute>(mod))
{
builder->addDecoration(
inst,
kIROp_VkStructOffsetDecoration,
builder->getIntValue(builder->getIntType(), glslStructOffsetMod->value));
}
else if (auto hlslSemantic = as<HLSLSimpleSemantic>(mod))
{
builder->addSemanticDecoration(inst, hlslSemantic->name.getContent());
}
else if (as<DynamicUniformModifier>(mod))
{
builder->addDynamicUniformDecoration(inst);
}
else if (auto collection = as<MemoryQualifierSetModifier>(mod))
{
builder->addMemoryQualifierSetDecoration(
inst,
IRIntegerValue(collection->getMemoryQualifierBit()));
}
else if (auto geometryModifier = as<HLSLGeometryShaderInputPrimitiveTypeModifier>(mod))
{
IROp op = kIROp_Invalid;
switch (geometryModifier->astNodeType)
{
case ASTNodeType::HLSLTriangleModifier:
op = kIROp_TriangleInputPrimitiveTypeDecoration;
break;
case ASTNodeType::HLSLPointModifier:
op = kIROp_PointInputPrimitiveTypeDecoration;
break;
case ASTNodeType::HLSLLineModifier:
op = kIROp_LineInputPrimitiveTypeDecoration;
break;
case ASTNodeType::HLSLLineAdjModifier:
op = kIROp_LineAdjInputPrimitiveTypeDecoration;
break;
case ASTNodeType::HLSLTriangleAdjModifier:
op = kIROp_TriangleAdjInputPrimitiveTypeDecoration;
break;
}
if (op != kIROp_Invalid)
builder->addDecoration(inst, op);
}
// TODO: what are other modifiers we need to propagate through?
}
if (auto t =
composeGetters<IRMeshOutputType>(inst->getFullType(), &IROutTypeBase::getValueType))
{
IROp op;
switch (t->getOp())
{
case kIROp_VerticesType:
op = kIROp_VerticesDecoration;
break;
case kIROp_IndicesType:
op = kIROp_IndicesDecoration;
break;
case kIROp_PrimitivesType:
op = kIROp_PrimitivesDecoration;
break;
default:
SLANG_UNREACHABLE("Missing case for IRMeshOutputType");
break;
}
builder->addMeshOutputDecoration(op, inst, t->getMaxElementCount());
}
}
/// If `decl` has a modifier that should turn into a
/// rate qualifier, then apply it to `inst`.
void maybeSetRate(IRGenContext* context, IRInst* inst, Decl* decl)
{
auto builder = context->irBuilder;
if (decl->hasModifier<HLSLGroupSharedModifier>())
{
inst->setFullType(
builder->getRateQualifiedType(builder->getGroupSharedRate(), inst->getFullType()));
}
else if (decl->hasModifier<ActualGlobalModifier>())
{
inst->setFullType(
builder->getRateQualifiedType(builder->getActualGlobalRate(), inst->getFullType()));
}
else if (
decl->hasModifier<SpecializationConstantAttribute>() ||
decl->hasModifier<VkConstantIdAttribute>())
{
inst->setFullType(
builder->getRateQualifiedType(builder->getSpecConstRate(), inst->getFullType()));
}
}
static String getNameForNameHint(IRGenContext* context, Decl* decl)
{
// We will use a bit of an ad hoc convention here for now.
Name* leafName = decl->getName();
// Handle custom name for a global parameter group (e.g., a `cbuffer`)
if (auto reflectionNameModifier = decl->findModifier<ParameterGroupReflectionName>())
{
leafName = reflectionNameModifier->nameAndLoc.name;
}
// There is no point in trying to provide a name hint for something with no name,
// or with an empty name
if (!leafName)
return String();
if (leafName->text.getLength() == 0)
return String();
if (const auto varDecl = as<VarDeclBase>(decl))
{
// For an ordinary local variable, global variable,
// parameter, or field, we will just use the name
// as declared, and now work in anything from
// its parent declaration(s).
//
// TODO: consider whether global/static variables should
// follow different rules.
//
return leafName->text;
}
// For other cases of declaration, we want to consider
// merging its name with the name of its parent declaration.
auto parentDecl = decl->parentDecl;
// Skip past a generic parent, if we are a declaration nested in a generic.
if (auto genericParentDecl = as<GenericDecl>(parentDecl))
parentDecl = genericParentDecl->parentDecl;
// Skip past a FileDecl parent.
if (auto fileParentDecl = as<FileDecl>(parentDecl))
parentDecl = fileParentDecl->parentDecl;
// A `ModuleDecl` can have a name too, but in the common case
// we don't want to generate name hints that include the module
// name, simply because they would lead to every global symbol
// getting a much longer name.
//
// TODO: We should probably include the module name for symbols
// being `import`ed, and not for symbols being compiled directly
// (those coming from a module that had no name given to it).
//
// For now we skip past a `ModuleDecl` parent.
//
if (auto moduleParentDecl = as<ModuleDecl>(parentDecl))
parentDecl = moduleParentDecl->parentDecl;
if (!parentDecl)
{
return leafName->text;
}
auto parentName = getNameForNameHint(context, parentDecl);
if (parentName.getLength() == 0)
{
return leafName->text;
}
// We will now construct a new `Name` to use as the hint,
// combining the name of the parent and the leaf declaration.
StringBuilder sb;
sb.append(parentName);
sb.append(".");
sb.append(leafName->text);
return sb.produceString();
}
/// Try to add an appropriate name hint to the instruction,
/// that can be used for back-end code emission or debug info.
static void addNameHint(IRGenContext* context, IRInst* inst, Decl* decl)
{
String name = getNameForNameHint(context, decl);
if (name.getLength() == 0)
return;
context->irBuilder->addNameHintDecoration(inst, name.getUnownedSlice());
}
/// Add a name hint based on a fixed string.
static void addNameHint(IRGenContext* context, IRInst* inst, char const* text)
{
if (context->shared->m_obfuscateCode)
{
return;
}
context->irBuilder->addNameHintDecoration(inst, UnownedTerminatedStringSlice(text));
}
LoweredValInfo createVar(IRGenContext* context, IRType* type, Decl* decl = nullptr)
{
auto builder = context->irBuilder;
auto irAlloc = builder->emitVar(type);
if (decl)
{
maybeSetRate(context, irAlloc, decl);
addVarDecorations(context, irAlloc, decl);
builder->addHighLevelDeclDecoration(irAlloc, decl);
addNameHint(context, irAlloc, decl);
}
return LoweredValInfo::ptr(irAlloc);
}
// When we try to turn a `LoweredValInfo` into an address of some temporary storage,
// we can either do it "aggressively" or not (what we'll call the "default" behavior,
// although it isn't strictly more common).
//
// The case that this is mostly there to address is when somebody writes an operation
// like:
//
// foo[a] = b;
//
// In that case, we might as well just use the `set` accessor if there is one, rather
// than complicate things. However, in more complex cases like:
//
// foo[a].x = b;
//
// there is no way to satisfy the semantics of the code the user wrote (in terms of
// only writing one vector component, and not a full vector) by using the `set`
// accessor, and we need to be "aggressive" in turning the lvalue `foo[a]` into
// an address.
//
// TODO: realistically IR lowering is too early to be binding to this choice,
// because different accessors might be supported on different targets.
//
enum class TryGetAddressMode
{
Default,
Aggressive,
};
/// Try to coerce `inVal` into a `LoweredValInfo::ptr()` with a simple address.
LoweredValInfo tryGetAddress(
IRGenContext* context,
LoweredValInfo const& inVal,
TryGetAddressMode mode);
/// Add a single `in` argument value to a list of arguments
void addInArg(IRGenContext* context, List<IRInst*>* ioArgs, LoweredValInfo argVal)
{
auto& args = *ioArgs;
switch (argVal.flavor)
{
case LoweredValInfo::Flavor::Simple:
case LoweredValInfo::Flavor::Ptr:
case LoweredValInfo::Flavor::SwizzledLValue:
case LoweredValInfo::Flavor::SwizzledMatrixLValue:
case LoweredValInfo::Flavor::BoundStorage:
case LoweredValInfo::Flavor::BoundMember:
case LoweredValInfo::Flavor::ExtractedExistential:
args.add(getSimpleVal(context, argVal));
break;
default:
SLANG_UNIMPLEMENTED_X("addInArg case");
break;
}
}
// 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;
};
/// Apply any fixups that have been created for `out` and `inout` arguments.
static void applyOutArgumentFixups(IRGenContext* context, List<OutArgumentFixup> const& fixups)
{
for (auto fixup : fixups)
{
assign(context, fixup.dst, fixup.src);
}
}
/// Add one argument value to the argument list for a call being constructed
void addArg(
IRGenContext* context,
List<IRInst*>* ioArgs, //< The argument list being built
List<OutArgumentFixup>* ioFixups, //< "Fixup" logic to apply for `out` or `inout` arguments
LoweredValInfo argVal, //< The lowered value of the argument to add
IRType* paramType, //< The type of the corresponding parameter
ParameterDirection paramDirection, //< The direction of the parameter (`in`, `out`, etc.)
Type* argType, //< The AST-level type of the argument
SourceLoc loc) //< A location to use if we need to report an error
{
switch (paramDirection)
{
case kParameterDirection_Ref:
{
// According to our "calling convention" we need to
// pass a pointer into the callee. Unlike the case for
// `out` and `inout` below, it is never valid to do
// copy-in/copy-out for a `ref` parameter, so we just
// pass in the actual pointer.
//
IRInst* argPtr = getAddress(context, argVal, loc);
if (argPtr)
addInArg(context, ioArgs, LoweredValInfo::simple(argPtr));
else
{
// If arg can't be converted to a pointer, we have already
// reported an error, so just pass a null pointer to allow
// the remaining lowering steps to finish.
addInArg(
context,
ioArgs,
LoweredValInfo::simple(context->irBuilder->getNullVoidPtrValue()));
}
}
break;
case kParameterDirection_Out:
case kParameterDirection_InOut:
case kParameterDirection_ConstRef:
{
// According to our "calling convention" we need to
// pass a pointer into the callee.
//
// Ideally we would like to just pass the address of
// `loweredArg`, and when that it possible we will do so.
// It may happen, though, that `loweredArg` is not an
// addressable l-value (e.g., it is `foo.xyz`, so that
// the bytes of the l-value are not contiguous).
//
LoweredValInfo argPtr = tryGetAddress(context, argVal, TryGetAddressMode::Default);
if (argPtr.flavor == LoweredValInfo::Flavor::Ptr)
{
addInArg(context, ioArgs, LoweredValInfo::simple(argPtr.val));
}
else
{
// If the value is not one that could yield a simple l-value
// then we need to convert it into a temporary
//
if (as<IRThisType>(paramType))
{
// When paramType is ThisType, we need to get the actual argument type
// from the arg.
paramType = lowerType(context, argType);
}
#if 0
if (auto refType = as<IRConstRefType>(paramType))
{
paramType = refType->getValueType();
argVal = LoweredValInfo::simple(
context->irBuilder->emitLoad(getSimpleVal(context, argPtr)));
}
#endif
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 (paramDirection == kParameterDirection_InOut ||
paramDirection == kParameterDirection_ConstRef)
{
assign(context, tempVar, argVal);
}
// Now we can pass the address of the temporary variable
// to the callee as the actual argument for the `in out`
SLANG_ASSERT(tempVar.flavor == LoweredValInfo::Flavor::Ptr);
IRInst* tempPtr = getAddress(context, tempVar, loc);
addInArg(context, ioArgs, LoweredValInfo::simple(tempPtr));
// Finally, after the call we will need
// to copy in the other direction: from our
// temp back to the original l-value.
if (paramDirection != kParameterDirection_ConstRef)
{
OutArgumentFixup fixup;
fixup.src = tempVar;
fixup.dst = argVal;
(*ioFixups).add(fixup);
}
}
}
break;
default:
addInArg(context, ioArgs, argVal);
break;
}
}
/// Add argument(s) corresponding to one parameter to a call
///
/// The `argExpr` is the AST-level expression being passed as an argument to the call.
/// The `paramType` and `paramDirection` represent what is known about the receiving
/// parameter of the callee (e.g., if the parameter `in`, `inout`, etc.).
/// The `ioArgs` array receives the IR-level argument(s) that are added for the given
/// argument expression.
/// The `ioFixups` array receives any "fixup" code that needs to be run *after* the
/// call completes (e.g., to move from a scratch variable used for an `inout` argument back
/// into the original location).
///
void addCallArgsForParam(
IRGenContext* context,
IRType* paramType,
ParameterDirection paramDirection,
Expr* argExpr,
List<IRInst*>* ioArgs,
List<OutArgumentFixup>* ioFixups)
{
switch (paramDirection)
{
case kParameterDirection_Ref:
case kParameterDirection_ConstRef:
case kParameterDirection_Out:
case kParameterDirection_InOut:
{
LoweredValInfo loweredArg = lowerLValueExpr(context, argExpr);
addArg(
context,
ioArgs,
ioFixups,
loweredArg,
paramType,
paramDirection,
argExpr->type,
argExpr->loc);
}
break;
default:
{
LoweredValInfo loweredArg = lowerRValueExpr(context, argExpr);
addInArg(context, ioArgs, loweredArg);
}
break;
}
}
//
/// Compute the direction for a parameter based on its declaration
ParameterDirection getParameterDirection(VarDeclBase* paramDecl)
{
if (paramDecl->hasModifier<RefModifier>())
{
return kParameterDirection_Ref;
}
if (paramDecl->hasModifier<ConstRefModifier>() || paramDecl->hasModifier<HLSLPayloadModifier>())
{
// The payload types are a groupshared variable, and we really don't
// want to copy that into registers in every invocation on platforms
// where this matters, so treat them as by-reference here.
return kParameterDirection_ConstRef;
}
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;
}
}
/// Compute the direction for a `this` parameter based on the declaration of its parent function
///
/// If the given declaration doesn't care about the direction of a `this` parameter, then
/// it will return the provided `defaultDirection` instead.
///
ParameterDirection getThisParamDirection(Decl* parentDecl, ParameterDirection defaultDirection)
{
auto parentParent = getParentAggTypeDecl(parentDecl);
// The `this` parameter for a `class` is always `in`.
if (as<ClassDecl>(parentParent))
{
return kParameterDirection_In;
}
if (parentParent && parentParent->findModifier<NonCopyableTypeAttribute>())
{
if (parentDecl->hasModifier<MutatingAttribute>())
return kParameterDirection_Ref;
else
return kParameterDirection_ConstRef;
}
// Applications can opt in to a mutable `this` parameter,
// by applying the `[mutating]` attribute to their
// declaration.
//
if (parentDecl->hasModifier<MutatingAttribute>())
{
return kParameterDirection_InOut;
}
else if (parentDecl->hasModifier<ConstRefAttribute>())
{
return kParameterDirection_ConstRef;
}
else if (parentDecl->hasModifier<RefAttribute>())
{
return kParameterDirection_Ref;
}
// A `set` accessor on a property or subscript declaration
// defaults to a mutable `this` parameter, but the programmer
// can opt out of this behavior using `[nonmutating]`
//
if (parentDecl->hasModifier<NonmutatingAttribute>())
{
return kParameterDirection_In;
}
else if (as<SetterDecl>(parentDecl))
{
return kParameterDirection_InOut;
}
// Declarations that represent abstract storage (a property
// or subscript) do not want to dictate anything about
// the direction of an outer `this` parameter, since that
// should be determined by their inner accessors.
//
if (as<PropertyDecl>(parentDecl))
{
return defaultDirection;
}
if (as<SubscriptDecl>(parentDecl))
{
return defaultDirection;
}
// A parent generic declaration should not change the
// mutating-ness of the inner declaration.
//
if (as<GenericDecl>(parentDecl))
{
return defaultDirection;
}
// For now we make any `this` parameter default to `in`.
//
return kParameterDirection_In;
}
DeclRef<Decl> createDefaultSpecializedDeclRefImpl(
IRGenContext* context,
SemanticsVisitor* semantics,
Decl* decl)
{
DeclRef<Decl> declRef =
createDefaultSubstitutionsIfNeeded(context->astBuilder, semantics, makeDeclRef(decl));
return declRef;
}
//
// The client should actually call the templated wrapper, to preserve type information.
template<typename D>
DeclRef<D> createDefaultSpecializedDeclRef(
IRGenContext* context,
SemanticsVisitor* semantics,
D* decl)
{
DeclRef<Decl> declRef = createDefaultSpecializedDeclRefImpl(context, semantics, decl);
return declRef.as<D>();
}
static Type* _findReplacementThisParamType(IRGenContext* context, DeclRef<Decl> parentDeclRef)
{
if (auto extensionDeclRef = parentDeclRef.as<ExtensionDecl>())
{
auto targetType = getTargetType(context->astBuilder, extensionDeclRef);
if (auto targetDeclRefType = as<DeclRefType>(targetType))
{
if (auto replacementType =
_findReplacementThisParamType(context, targetDeclRefType->getDeclRef()))
return replacementType;
}
return targetType;
}
if (auto interfaceDeclRef = parentDeclRef.as<InterfaceDecl>())
{
auto thisType = DeclRefType::create(
context->astBuilder,
context->astBuilder->getMemberDeclRef(
interfaceDeclRef,
interfaceDeclRef.getDecl()->getThisTypeDecl()));
return thisType;
}
if (auto defaultImplDeclRef = parentDeclRef.as<InterfaceDefaultImplDecl>())
{
auto thisType = DeclRefType::create(
context->astBuilder,
DeclRef<Decl>(defaultImplDeclRef.getDecl()->thisTypeDecl));
return thisType;
}
return nullptr;
}
/// Get the type of the `this` parameter introduced by `parentDeclRef`, or null.
///
/// E.g., if `parentDeclRef` is a `struct` declaration, then this will
/// return the type of that `struct`.
///
/// If this function is called on a declaration that does not itself directly
/// introduce a notion of `this`, then null will be returned. Note that this
/// includes things like function declarations themselves, which inherit the
/// definition of `this` from their parent/outer declaration.
///
Type* getThisParamTypeForContainer(IRGenContext* context, DeclRef<Decl> parentDeclRef)
{
if (auto replacementType = _findReplacementThisParamType(context, parentDeclRef))
return replacementType;
if (auto aggTypeDeclRef = parentDeclRef.as<AggTypeDecl>())
{
return DeclRefType::create(context->astBuilder, aggTypeDeclRef);
}
return nullptr;
}
Type* getThisParamTypeForCallable(IRGenContext* context, DeclRef<Decl> callableDeclRef)
{
if (auto lookup = as<LookupDeclRef>((callableDeclRef.declRefBase)))
{
return lookup->getLookupSource();
}
auto parentDeclRef = callableDeclRef.getParent();
if (auto subscriptDeclRef = parentDeclRef.as<SubscriptDecl>())
parentDeclRef = subscriptDeclRef.getParent();
if (auto genericDeclRef = parentDeclRef.as<GenericDecl>())
parentDeclRef = genericDeclRef.getParent();
return getThisParamTypeForContainer(context, parentDeclRef);
}
struct StmtLoweringVisitor;
void maybeEmitDebugLine(
IRGenContext* context,
StmtLoweringVisitor* visitor,
Stmt* stmt,
SourceLoc loc = SourceLoc(),
bool allowNullStmt = false);
// 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:
//
struct IRLoweringParameterInfo
{
// This AST-level type of the parameter
Type* type = nullptr;
// The direction (`in` vs `out` vs `in out`)
ParameterDirection direction;
// The direction declared in user code.
ParameterDirection declaredDirection = ParameterDirection::kParameterDirection_In;
// The variable/parameter declaration for
// this parameter (if any)
VarDeclBase* decl = nullptr;
// Is this the representation of a `this` parameter?
bool isThisParam = false;
// Is this the destination of address for non-copyable return val?
bool isReturnDestination = false;
};
//
// We need a way to be able to create a `IRLoweringParameterInfo` given the declaration
// of a parameter:
//
IRLoweringParameterInfo getParameterInfo(
IRGenContext* context,
DeclRef<VarDeclBase> const& paramDecl)
{
IRLoweringParameterInfo info;
info.type = getParamType(context->astBuilder, paramDecl);
info.decl = paramDecl.getDecl();
info.direction = getParameterDirection(paramDecl.getDecl());
info.declaredDirection = info.direction;
info.isThisParam = false;
return info;
}
//
// Here's the declaration for the type to hold the lists:
struct ParameterLists
{
List<IRLoweringParameterInfo> params;
};
//
// 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`:
ParameterListCollectMode getModeForCollectingParentParameters(Decl* decl, ContainerDecl* parentDecl)
{
// If we have a `static` parameter, then it is obvious
// that we should use the `static` mode
if (isEffectivelyStatic(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(ParameterDirection direction, Type* type, ParameterLists* ioParameterLists)
{
IRLoweringParameterInfo info;
info.type = type;
info.decl = nullptr;
info.direction = direction;
info.declaredDirection = direction;
info.isThisParam = true;
ioParameterLists->params.add(info);
}
void maybeAddReturnDestinationParam(ParameterLists* ioParameterLists, Type* resultType)
{
if (isNonCopyableType(resultType))
{
IRLoweringParameterInfo info;
info.type = resultType;
info.decl = nullptr;
info.direction = kParameterDirection_Ref;
info.declaredDirection = info.direction;
info.isReturnDestination = true;
ioParameterLists->params.add(info);
}
}
void makeVaryingInputParamConstRef(IRLoweringParameterInfo& paramInfo)
{
if (paramInfo.direction != kParameterDirection_In)
return;
if (paramInfo.decl->findModifier<HLSLUniformModifier>())
return;
if (as<HLSLPatchType>(paramInfo.type))
return;
paramInfo.direction = kParameterDirection_ConstRef;
}
//
// And here is our function that will do the recursive walk:
void collectParameterLists(
IRGenContext* context,
DeclRef<Decl> const& declRef,
ParameterLists* ioParameterLists,
ParameterListCollectMode mode,
ParameterDirection thisParamDirection)
{
// Don't collect any parameters beyond certain decls.
if (as<InterfaceDefaultImplDecl>(declRef) || as<AggTypeDeclBase>(declRef))
return;
// The parameters introduced by any "parent" declarations
// will need to come first, so we'll deal with that
// logic here.
if (auto parentDeclRef = declRef.getParent())
{
// 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(declRef.getDecl(), parentDeclRef.getDecl());
// Don't down-grade our `static`-ness along the chain.
if (innerMode < mode)
innerMode = mode;
ParameterDirection innerThisParamDirection =
getThisParamDirection(declRef.getDecl(), thisParamDirection);
// Now collect any parameters from the parent declaration itself
collectParameterLists(
context,
parentDeclRef,
ioParameterLists,
innerMode,
innerThisParamDirection);
// We also need to consider whether the inner declaration needs to have a `this`
// parameter corresponding to the outer declaration.
if (innerMode != kParameterListCollectMode_Static)
{
auto thisType = getThisParamTypeForContainer(context, parentDeclRef);
if (thisType)
{
if (declRef.getDecl()->findModifier<NoDiffThisAttribute>())
{
auto noDiffAttr = context->astBuilder->getNoDiffModifierVal();
thisType = context->astBuilder->getModifiedType(thisType, 1, &noDiffAttr);
}
else if (auto fwdDerivDeclRef = declRef.as<ForwardDerivativeRequirementDecl>())
{
thisType = fwdDerivDeclRef.getDecl()->diffThisType;
}
else if (auto bwdDerivDeclRef = declRef.as<BackwardDerivativeRequirementDecl>())
{
thisType = bwdDerivDeclRef.getDecl()->diffThisType;
innerThisParamDirection = kParameterDirection_InOut;
}
addThisParameter(innerThisParamDirection, thisType, ioParameterLists);
}
}
}
// Once we've added any parameters based on parent declarations,
// we can see if this declaration itself introduces parameters.
//
if (auto callableDeclRef = declRef.as<CallableDecl>())
{
// We need a special case here when lowering the varying parameters of an entrypoint
// function. Due to the existence of `EvaluateAttributeAtSample` and friends, we need to
// always lower the varying inputs as `__constref` parameters so we can pass pointers to
// these intrinsics.
// This means that although these parameters are declared as "in" parameters in the source,
// we will actually treat them as __constref parameters when lowering to IR. A complication
// result from this is that if the original source code actually modifies the input
// parameter we still need to create a local var to hold the modified value. In the future
// when we are able to update our language spec to always assume input parameters are
// immutable, then we can remove this adhoc logic of introducing temporary variables. For
// For now we will rely on a follow up pass to remove unnecessary temporary variables if
// we can determine that they are never actually writtten to by the user.
//
bool lowerVaryingInputAsConstRef = declRef.getDecl()->hasModifier<EntryPointAttribute>() ||
declRef.getDecl()->hasModifier<NumThreadsAttribute>();
// Don't collect parameters from the outer scope if
// we are in a `static` context.
if (mode == kParameterListCollectMode_Default)
{
for (auto paramDeclRef : getParameters(context->astBuilder, callableDeclRef))
{
auto paramInfo = getParameterInfo(context, paramDeclRef);
if (lowerVaryingInputAsConstRef)
makeVaryingInputParamConstRef(paramInfo);
ioParameterLists->params.add(paramInfo);
}
maybeAddReturnDestinationParam(
ioParameterLists,
getResultType(context->astBuilder, callableDeclRef));
}
}
}
bool isConstExprVar(Decl* decl)
{
if (decl->hasModifier<ConstExprModifier>())
{
return true;
}
else if (decl->hasModifier<HLSLStaticModifier>() && decl->hasModifier<ConstModifier>())
{
return true;
}
return false;
}
IRType* maybeGetConstExprType(IRBuilder* builder, IRType* type, Decl* decl)
{
if (isConstExprVar(decl))
{
return builder->getRateQualifiedType(builder->getConstExprRate(), type);
}
return type;
}
struct FuncDeclBaseTypeInfo
{
IRType* type;
IRType* resultType;
ParameterLists parameterLists;
List<IRType*> paramTypes;
// If the function returns a non-copyable value, this
// flag is set to indicate that the result should be
// returned via the last ref parameter.
bool returnViaLastRefParam = false;
};
void _lowerFuncDeclBaseTypeInfo(
IRGenContext* context,
DeclRef<FunctionDeclBase> declRef,
FuncDeclBaseTypeInfo& outInfo)
{
auto builder = context->irBuilder;
// Collect the parameter lists we will use for our new function.
auto& parameterLists = outInfo.parameterLists;
collectParameterLists(
context,
declRef,
¶meterLists,
kParameterListCollectMode_Default,
kParameterDirection_In);
auto& paramTypes = outInfo.paramTypes;
for (auto paramInfo : parameterLists.params)
{
IRType* irParamType = lowerType(context, paramInfo.type);
switch (paramInfo.direction)
{
case kParameterDirection_In:
// Simple case of a by-value input parameter.
break;
// If the parameter is declared `out` or `inout`,
// then we will represent it with a pointer type in
// the IR, but we will use a specialized pointer
// type that encodes the parameter direction information.
case kParameterDirection_Out:
irParamType = builder->getOutType(irParamType);
break;
case kParameterDirection_InOut:
irParamType = builder->getInOutType(irParamType);
break;
case kParameterDirection_Ref:
irParamType = builder->getRefType(irParamType, AddressSpace::Generic);
break;
case kParameterDirection_ConstRef:
irParamType = builder->getConstRefType(irParamType, AddressSpace::Generic);
break;
default:
SLANG_UNEXPECTED("unknown parameter direction");
break;
}
// If the parameter was explicitly marked as being a compile-time
// constant (`constexpr`), then attach that information to its
// IR-level type explicitly.
if (paramInfo.decl)
{
irParamType = maybeGetConstExprType(builder, irParamType, paramInfo.decl);
}
if (paramInfo.decl && paramInfo.decl->hasModifier<HLSLGroupSharedModifier>())
{
irParamType = builder->getRateQualifiedType(builder->getGroupSharedRate(), irParamType);
}
// The 'payload' parameter is a read-only groupshared value
if (paramInfo.decl && paramInfo.decl->hasModifier<HLSLPayloadModifier>())
{
irParamType = builder->getRateQualifiedType(builder->getGroupSharedRate(), irParamType);
}
paramTypes.add(irParamType);
}
auto& irResultType = outInfo.resultType;
if (parameterLists.params.getCount() && parameterLists.params.getLast().isReturnDestination)
{
irResultType = context->irBuilder->getVoidType();
outInfo.returnViaLastRefParam = true;
}
else
{
irResultType = lowerType(context, getResultType(context->astBuilder, declRef));
if (auto setterDeclRef = declRef.as<SetterDecl>())
{
// A `set` accessor always returns `void`
//
// TODO: We should handle this by making the result
// type of a `set` accessor be represented accurately
// at the AST level (ditto for the `ref` case below).
//
irResultType = builder->getVoidType();
}
if (auto refAccessorDeclRef = declRef.as<RefAccessorDecl>())
{
// A `ref` accessor needs to return a *pointer* to the value
// being accessed, rather than a simple value.
irResultType = builder->getPtrType(irResultType);
}
}
if (!getErrorCodeType(context->astBuilder, declRef)
->equals(context->astBuilder->getBottomType()))
{
auto irErrorType = lowerType(context, getErrorCodeType(context->astBuilder, declRef));
IRInst* operands[] = {irErrorType};
IRAttr* throwTypeAttr = builder->getAttr(kIROp_FuncThrowTypeAttr, 1, operands);
outInfo.type = builder->getFuncType(
paramTypes.getCount(),
paramTypes.getBuffer(),
irResultType,
throwTypeAttr);
}
else
{
outInfo.type =
builder->getFuncType(paramTypes.getCount(), paramTypes.getBuffer(), irResultType);
}
}
static LoweredValInfo _emitCallToAccessor(
IRGenContext* context,
IRType* type,
DeclRef<AccessorDecl> accessorDeclRef,
LoweredValInfo base,
UInt argCount,
IRInst* const* args)
{
FuncDeclBaseTypeInfo info;
_lowerFuncDeclBaseTypeInfo(context, accessorDeclRef, info);
List<IRInst*> allArgs;
List<OutArgumentFixup> fixups;
if (base.flavor != LoweredValInfo::Flavor::None)
{
SLANG_ASSERT(info.parameterLists.params.getCount() >= 1);
SLANG_ASSERT(info.parameterLists.params[0].isThisParam);
auto thisParam = info.parameterLists.params[0];
auto thisParamType = lowerType(context, thisParam.type);
addArg(
context,
&allArgs,
&fixups,
base,
thisParamType,
thisParam.direction,
thisParam.type,
SourceLoc());
}
allArgs.addRange(args, argCount);
LoweredValInfo result = emitCallToDeclRef(
context,
type,
accessorDeclRef,
info.type,
allArgs.getCount(),
allArgs.getBuffer(),
TryClauseEnvironment());
applyOutArgumentFixups(context, fixups);
return result;
}
template<typename Derived>
struct ExprLoweringContext
{
static bool isLValueContext() { return Derived::_isLValueContext(); }
IRGenContext* context;
IRBuilder* getBuilder() { return context->irBuilder; }
ASTBuilder* getASTBuilder() { return context->astBuilder; }
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(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 = as<DeclRefExpr>(funcExpr);
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 = as<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 function type, though).
return false;
}
// Now we can look at the specific kinds of declaration references,
// and try to tease them apart.
if (auto memberFuncExpr = as<MemberExpr>(funcExpr))
{
outInfo->funcDeclRef = memberFuncExpr->declRef;
outInfo->baseExpr = memberFuncExpr->baseExpression;
return true;
}
else if (auto staticMemberFuncExpr = as<StaticMemberExpr>(funcExpr))
{
outInfo->funcDeclRef = staticMemberFuncExpr->declRef;
return true;
}
else if (auto varExpr = as<VarExpr>(funcExpr))
{
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;
}
}
/// Return `expr` with any outer casts to interface types stripped away
Expr* maybeIgnoreCastToInterface(Expr* expr)
{
auto e = expr;
while (auto castExpr = as<CastToSuperTypeExpr>(e))
{
if (auto declRefType = as<DeclRefType>(e->type))
{
if (declRefType->getDeclRef().as<InterfaceDecl>())
{
e = castExpr->valueArg;
continue;
}
}
else if (auto andType = as<AndType>(e->type))
{
// TODO: We might eventually need to tell the difference
// between conjunctions of interfaces and conjunctions
// that might include non-interface types.
//
// For now we assume that any case to a conjunction
// is effectively a cast to an interface type.
//
e = castExpr->valueArg;
continue;
}
break;
}
return e;
}
// Lower an expression that should have the same l-value-ness
// as the visitor itself.
LoweredValInfo lowerSubExpr(Expr* expr)
{
IRBuilderSourceLocRAII sourceLocInfo(getBuilder(), expr->loc);
if (isLValueContext())
return lowerLValueExpr(context, expr);
return lowerRValueExpr(context, expr);
}
/// Create IR instructions for an argument at a call site, based on
/// AST-level expressions plus function signature information.
///
/// The `funcType` parameter is always required, and specifies the types
/// of all the parameters. The `funcDeclRef` parameter is only required
/// if there are parameter positions for which the matching argument is
/// absent.
///
void addDirectCallArgs(
InvokeExpr* expr,
Index argIndex,
IRType* paramType,
ParameterDirection paramDirection,
DeclRef<ParamDecl> paramDeclRef,
List<IRInst*>* ioArgs,
List<OutArgumentFixup>* ioFixups)
{
Count argCount = expr->arguments.getCount();
if (argIndex < argCount)
{
auto argExpr = expr->arguments[argIndex];
addCallArgsForParam(context, paramType, paramDirection, argExpr, ioArgs, ioFixups);
}
else
{
// We have run out of arguments supplied at the call site,
// but there are still parameters remaining. This must mean
// that these parameters have default argument expressions
// associated with them.
//
// Currently we simply extract the initial-value expression
// from the parameter declaration and then lower it in
// the context of the caller.
//
// Note that the expression could involve subsitutions because
// in the general case it could depend on the generic parameters
// used the specialize the callee. For now we do not handle that
// case, and simply ignore generic arguments.
//
SubstExpr<Expr> argExpr = getInitExpr(getASTBuilder(), paramDeclRef);
SLANG_ASSERT(argExpr);
IRGenEnv subEnvStorage;
IRGenEnv* subEnv = &subEnvStorage;
subEnv->outer = context->env;
IRGenContext subContextStorage = *context;
IRGenContext* subContext = &subContextStorage;
subContext->env = subEnv;
_lowerSubstitutionEnv(
subContext,
argExpr.getSubsts() ? argExpr.getSubsts().declRef : nullptr);
addCallArgsForParam(
subContext,
paramType,
paramDirection,
argExpr.getExpr(),
ioArgs,
ioFixups);
// TODO: The approach we are taking here to default arguments
// is simplistic, and has consequences for the front-end as
// well as binary serialization of modules.
//
// We could consider some more refined approaches where, e.g.,
// functions with default arguments generate multiple IR-level
// functions, that compute and provide the default values.
//
// Alternatively, each parameter with defaults could be generated
// into its own callable function that provides the default value,
// so that calling modules can call into a pre-generated function.
//
// Each of these options involves trade-offs, and we need to
// make a conscious decision at some point.
// Assert that such an expression must have been present.
}
}
void addDirectCallArgs(
InvokeExpr* expr,
FuncType* funcType,
List<IRInst*>* ioArgs,
List<OutArgumentFixup>* ioFixups)
{
Count argCount = expr->arguments.getCount();
SLANG_ASSERT(argCount == funcType->getParamCount());
for (Index i = 0; i < argCount; ++i)
{
auto paramInfo = funcType->getParamInfo(i);
IRType* paramType = lowerType(context, paramInfo.type);
addDirectCallArgs(
expr,
i,
paramType,
paramInfo.direction,
DeclRef<ParamDecl>(),
ioArgs,
ioFixups);
}
}
void addDirectCallArgs(
InvokeExpr* expr,
DeclRef<CallableDecl> funcDeclRef,
List<IRInst*>* ioArgs,
List<OutArgumentFixup>* ioFixups)
{
Count argCounter = 0;
for (auto paramDeclRef : getMembersOfType<ParamDecl>(getASTBuilder(), funcDeclRef))
{
auto paramDecl = paramDeclRef.getDecl();
IRType* paramType = lowerType(context, getType(getASTBuilder(), paramDeclRef));
auto paramDirection = getParameterDirection(paramDecl);
Index argIndex = argCounter++;
addDirectCallArgs(
expr,
argIndex,
paramType,
paramDirection,
paramDeclRef,
ioArgs,
ioFixups);
}
}
// 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<IRInst*>* ioArgs,
List<OutArgumentFixup>* ioFixups)
{
if (auto callableDeclRef = funcDeclRef.as<CallableDecl>())
{
addDirectCallArgs(expr, callableDeclRef, ioArgs, ioFixups);
}
else
{
SLANG_UNEXPECTED("callee was not a callable decl");
}
}
void addFuncBaseArgs(LoweredValInfo funcVal, List<IRInst*>* /*ioArgs*/)
{
switch (funcVal.flavor)
{
default:
return;
}
}
void _lowerSubstitutionArg(
IRGenContext* subContext,
GenericAppDeclRef* subst,
Decl* paramDecl,
Index argIndex)
{
SLANG_ASSERT(argIndex < subst->getArgs().getCount());
auto argVal = lowerVal(subContext, subst->getArgs()[argIndex]);
subContext->setValue(paramDecl, argVal);
}
void _lowerSubstitutionEnv(IRGenContext* subContext, DeclRefBase* subst)
{
if (!subst)
return;
_lowerSubstitutionEnv(subContext, subst->getBase());
if (auto genSubst = as<GenericAppDeclRef>(subst))
{
auto genDecl = genSubst->getGenericDecl();
Index argCounter = 0;
for (auto memberDecl : genDecl->getDirectMemberDecls())
{
if (auto typeParamDecl = as<GenericTypeParamDecl>(memberDecl))
{
_lowerSubstitutionArg(subContext, genSubst, typeParamDecl, argCounter++);
}
else if (auto valParamDecl = as<GenericValueParamDecl>(memberDecl))
{
_lowerSubstitutionArg(subContext, genSubst, valParamDecl, argCounter++);
}
}
for (auto constraintDecl :
genDecl->getDirectMemberDeclsOfType<GenericTypeConstraintDecl>())
{
_lowerSubstitutionArg(subContext, genSubst, constraintDecl, argCounter++);
}
}
// TODO: also need to handle this-type substitution here?
}
void validateInvokeExprArgsWithFunctionModifiers(
InvokeExpr* expr,
FunctionDeclBase* decl,
List<IRInst*>& irArgs)
{
if (auto glslRequireShaderInputParameter =
decl->findModifier<GLSLRequireShaderInputParameterAttribute>())
{
if (!irArgs[glslRequireShaderInputParameter->parameterNumber]
->findDecoration<IRGlobalInputDecoration>())
{
this->context->getSink()->diagnose(
expr,
Diagnostics::requireInputDecoratedVarForParameter,
decl,
glslRequireShaderInputParameter->parameterNumber);
}
return;
}
}
/// Lower an invoke expr, and attempt to fuse a store of the expr's result into destination.
/// If the store is fused, returns LoweredValInfo::None. Otherwise, returns the IR val
/// representing the RValue.
LoweredValInfo visitInvokeExprImpl(
InvokeExpr* expr,
LoweredValInfo destination,
const TryClauseEnvironment& tryEnv)
{
auto type = lowerType(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<IRInst*> irArgs;
// We will also collect "fixup" actions that need
// to be performed after the 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 exactly what declaration we
// are going to call, and so we can resolve things
// appropriately.
auto funcDeclRef = resolvedInfo.funcDeclRef;
auto baseExpr = resolvedInfo.baseExpr;
if (baseExpr)
{
// The base expression might be an "upcast" to a base interface, in
// which case we don't want to emit the result of the cast, but instead
// the source.
//
baseExpr = this->maybeIgnoreCastToInterface(baseExpr);
}
// If the thing being invoked is a subscript operation,
// then we need to handle multiple extra details
// that don't arise for other kinds of calls.
//
// TODO: subscript operations probably deserve to
// be handled on their own path for this reason...
//
if (auto subscriptDeclRef = funcDeclRef.template as<SubscriptDecl>())
{
// A reference to a subscript declaration is a special case,
// because it is not possible to call a subscript directly;
// we must call one of its accessors.
//
auto loweredBase = lowerSubExpr(baseExpr);
addDirectCallArgs(expr, funcDeclRef, &irArgs, &argFixups);
auto result = lowerStorageReference(
context,
type,
subscriptDeclRef,
loweredBase,
irArgs.getCount(),
irArgs.getBuffer());
// TODO: Applying the fixups for arguments to the subscript at this point
// won't technically be correct, since the call to the subscript may
// not have occured at this point.
//
// It seems like we need to either:
//
// * Capture the arguments to the subscript as `LoweredValInfo` instead of `IRInst*`
// so that we can deal with everything related to fixups around the actual call
// site.
//
// OR
//
// * Handle everything to do with "fixups" differently, by treating them as deferred
// actions that gert queued up on the context itself and then flushed at certain
// well-defined points, so that we don't have to be as careful around them.
//
// OR
//
// * Switch to a more "destination-driven" approach to code generation, where we
// can determine on entry to the lowering of a sub-expression whether it will be
// used for read, write, or read/write, and resolve things like the choice of
// accessor at that point instead.
//
applyOutArgumentFixups(context, argFixups);
return result;
}
// First comes the `this` argument if we are calling
// a member function:
if (baseExpr)
{
auto thisType = getThisParamTypeForCallable(context, funcDeclRef);
auto irThisType = lowerType(context, thisType);
addCallArgsForParam(
context,
irThisType,
getThisParamDirection(funcDeclRef.getDecl(), kParameterDirection_In),
baseExpr,
&irArgs,
&argFixups);
}
// Then we have the "direct" arguments to the call.
// These may include `out` and `inout` arguments that
// require "fixup" work on the other side.
//
FuncDeclBaseTypeInfo funcTypeInfo;
_lowerFuncDeclBaseTypeInfo(
context,
funcDeclRef.template as<FunctionDeclBase>(),
funcTypeInfo);
auto funcType = funcTypeInfo.type;
addDirectCallArgs(expr, funcDeclRef, &irArgs, &argFixups);
validateInvokeExprArgsWithFunctionModifiers(
expr,
as<FunctionDeclBase>(funcDeclRef.getDecl()),
irArgs);
LoweredValInfo result;
if (funcTypeInfo.returnViaLastRefParam)
{
// If the function returns a non-copyable type, then we need to
// pass in the destination that receives the result value as an `__ref` parameter.
//
if (destination.flavor != LoweredValInfo::Flavor::None)
{
// If we have a known destination, we can use it directly as argument to the
// call.
irArgs.add(destination.val);
result = LoweredValInfo();
}
else
{
// Otherwise, we need to create a temporary variable to hold the result.
//
auto tempVar = context->irBuilder->emitVar(
tryGetPointedToType(context->irBuilder, funcTypeInfo.paramTypes.getLast()));
irArgs.add(tempVar);
result = LoweredValInfo::ptr(tempVar);
}
}
auto callResult =
emitCallToDeclRef(context, type, funcDeclRef, funcType, irArgs, tryEnv);
applyOutArgumentFixups(context, argFixups);
if (funcTypeInfo.returnViaLastRefParam)
return result;
return callResult;
}
else if (auto funcType = as<FuncType>(expr->functionExpr->type))
{
auto funcVal = lowerRValueExpr(context, expr->functionExpr);
addDirectCallArgs(expr, funcType, &irArgs, &argFixups);
auto result = emitCallToVal(
context,
type,
funcVal,
irArgs.getCount(),
irArgs.getBuffer(),
tryEnv);
applyOutArgumentFixups(context, argFixups);
return result;
}
// TODO: In this case we should be emitting code for the callee as
// an ordinary expression, then emitting the arguments according
// to the type information on the callee (e.g., which parameters
// are `out` or `inout`, and then finally emitting the `call`
// instruction.
//
// We don't currently have the case of emitting arguments according
// to function type info (instead of declaration info), and really
// this case can't occur unless we start adding first-class functions
// to the source language.
//
// For now we just bail out with an error.
//
SLANG_UNEXPECTED("could not resolve target declaration for call");
UNREACHABLE_RETURN(LoweredValInfo());
}
};
template<typename Derived>
struct ExprLoweringVisitorBase : public ExprVisitor<Derived, LoweredValInfo>
{
static bool isLValueContext() { return Derived::_isLValueContext(); }
ExprLoweringContext<Derived> sharedLoweringContext;
IRGenContext*& context;
ExprLoweringVisitorBase()
: context(sharedLoweringContext.context)
{
}
IRBuilder* getBuilder() { return context->irBuilder; }
ASTBuilder* getASTBuilder() { return context->astBuilder; }
LoweredValInfo lowerSubExpr(Expr* expr) { return sharedLoweringContext.lowerSubExpr(expr); }
LoweredValInfo visitAddressOfExpr(AddressOfExpr* expr)
{
auto loweredType = lowerType(context, expr->type);
auto baseVal = lowerLValueExpr(context, expr->arg);
auto ptr = tryGetAddress(context, baseVal, TryGetAddressMode::Aggressive);
switch (ptr.flavor)
{
case LoweredValInfo::Flavor::Ptr:
{
// TODO: This is a hack. We should just be returning `ptr`. We do not do this since
// `ptr` may have the wrong address space. This happens since when lowering-to-ir we
// don't check what addres-space info we should be using for variables we create.
// example: `groupshared int ptr` ==> lower-to-ir lowers as default address-space
// with groupshared-rate.
//
// We need to emit a temporary variable (and cannot emit a cast) since `operator*`
// has its own hacks and is an incorrect implementation of its own. To elaborate,
// `operator*` is defined as `__intrinsic_op(0)`, which means "pass arguments
// through a function `in`, then set as result". This is an issue since this means
// that our function (which should be returning a `ref`) may in fact, not be
// returning a `ref` but instead be loading via the `in` parameter and generating a
// non-pointer result.
auto irVar = context->irBuilder->emitVar(loweredType);
context->irBuilder->emitStore(irVar, ptr.val);
return LoweredValInfo::ptr(irVar);
}
default:
SLANG_UNIMPLEMENTED_X("cannot get address of __getAddress(...) argument");
UNREACHABLE_RETURN(LoweredValInfo());
}
}
LoweredValInfo visitIncompleteExpr(IncompleteExpr*)
{
SLANG_UNEXPECTED("a valid ast should not contain an IncompleteExpr.");
UNREACHABLE_RETURN(LoweredValInfo());
}
LoweredValInfo visitVarExpr(VarExpr* expr)
{
auto lowerTypeOfExpr = lowerType(context, expr->type);
auto declRef = expr->declRef;
if (auto propertyDeclRef = declRef.as<PropertyDecl>())
{
// A reference to a property is a special case, because
// we must translate the reference to the property
// into a reference to one of its accessors.
return lowerStorageReference(
context,
lowerTypeOfExpr,
propertyDeclRef,
LoweredValInfo(),
0,
nullptr);
}
LoweredValInfo info = emitDeclRef(context, declRef, lowerTypeOfExpr);
return info;
}
// Emit IR to denote the forward-mode derivative
// of the inner func-expr. This will be resolved
// to a concrete function during the derivative
// pass.
LoweredValInfo visitForwardDifferentiateExpr(ForwardDifferentiateExpr* expr)
{
auto baseVal = lowerSubExpr(expr->baseFunction);
SLANG_ASSERT(baseVal.flavor == LoweredValInfo::Flavor::Simple);
return LoweredValInfo::simple(getBuilder()->emitForwardDifferentiateInst(
lowerType(context, expr->type),
baseVal.val));
}
LoweredValInfo visitDetachExpr(DetachExpr* expr)
{
auto baseVal = lowerRValueExpr(context, expr->inner);
return LoweredValInfo::simple(getBuilder()->emitDetachDerivative(
lowerType(context, expr->type),
getSimpleVal(context, baseVal)));
}
LoweredValInfo visitPrimalSubstituteExpr(PrimalSubstituteExpr* expr)
{
auto baseVal = lowerSubExpr(expr->baseFunction);
SLANG_ASSERT(baseVal.flavor == LoweredValInfo::Flavor::Simple);
return LoweredValInfo::simple(
getBuilder()->emitPrimalSubstituteInst(lowerType(context, expr->type), baseVal.val));
}
LoweredValInfo visitTreatAsDifferentiableExpr(TreatAsDifferentiableExpr* expr)
{
auto baseVal = lowerSubExpr(expr->innerExpr);
IRInst* innerInst = nullptr;
if (baseVal.flavor != LoweredValInfo::Flavor::Simple)
{
if (!isLValueContext())
{
auto materializedVal = materialize(context, baseVal);
// TODO(Sai): We might be missing the case where a single materialize could create
// multiple calls (multiple index operations?). Not quite sure what the right way
// to handle that case might be.
//
if (as<IRCall>(materializedVal.val))
{
if (expr->flavor == TreatAsDifferentiableExpr::Flavor::NoDiff)
getBuilder()->addDecoration(
materializedVal.val,
kIROp_TreatCallAsDifferentiableDecoration);
else if (expr->flavor == TreatAsDifferentiableExpr::Flavor::Differentiable)
getBuilder()->addDecoration(
materializedVal.val,
kIROp_DifferentiableCallDecoration);
else
SLANG_UNEXPECTED("Unknown TreatAsDifferentiableExpr::Flavor");
}
innerInst = getSimpleVal(context, materializedVal);
// We'll special case handle 'loads' here in order to allow TreatAsDifferentiable to
// be used on array index operations. (This is to avoid a discrepancy between using
// no_diff on local variable indexing vs. resource indexing.)
//
if (as<IRLoad>(innerInst))
innerInst =
getBuilder()->emitDetachDerivative(innerInst->getDataType(), innerInst);
}
else
{
SLANG_UNEXPECTED(
"TreatAsDifferentiableExpr on non-simple l-values not properly defined.");
}
}
else
{
if (auto callInst = as<IRCall>(baseVal.val))
if (expr->flavor == TreatAsDifferentiableExpr::Flavor::NoDiff)
getBuilder()->addDecoration(
callInst,
kIROp_TreatCallAsDifferentiableDecoration);
else if (expr->flavor == TreatAsDifferentiableExpr::Flavor::Differentiable)
getBuilder()->addDecoration(callInst, kIROp_DifferentiableCallDecoration);
else
SLANG_UNEXPECTED("Unknown TreatAsDifferentiableExpr::Flavor");
innerInst = baseVal.val;
}
SLANG_ASSERT(innerInst);
return LoweredValInfo::simple(innerInst);
}
// Emit IR to denote the forward-mode derivative
// of the inner func-expr. This will be resolved
// to a concrete function during the derivative
// pass.
LoweredValInfo visitBackwardDifferentiateExpr(BackwardDifferentiateExpr* expr)
{
auto baseVal = lowerSubExpr(expr->baseFunction);
SLANG_ASSERT(baseVal.flavor == LoweredValInfo::Flavor::Simple);
return LoweredValInfo::simple(getBuilder()->emitBackwardDifferentiateInst(
lowerType(context, expr->type),
baseVal.val));
}
LoweredValInfo visitDispatchKernelExpr(DispatchKernelExpr* expr)
{
auto baseVal = lowerSubExpr(expr->baseFunction);
SLANG_ASSERT(baseVal.flavor == LoweredValInfo::Flavor::Simple);
auto threadSize = lowerRValueExpr(context, expr->threadGroupSize);
auto groupSize = lowerRValueExpr(context, expr->dispatchSize);
// Actual arguments to be filled in when we lower the actual call expr.
// This is handled in `emitCallToVal`.
return LoweredValInfo::simple(getBuilder()->emitDispatchKernelInst(
lowerType(context, expr->type),
baseVal.val,
getSimpleVal(context, threadSize),
getSimpleVal(context, groupSize),
0,
nullptr));
}
LoweredValInfo visitGetArrayLengthExpr(GetArrayLengthExpr* expr)
{
auto type = lowerType(context, expr->arrayExpr->type);
auto arrayType = as<IRArrayType>(type);
SLANG_ASSERT(arrayType);
return LoweredValInfo::simple(arrayType->getElementCount());
}
LoweredValInfo visitSizeOfLikeExpr(SizeOfLikeExpr* sizeOfLikeExpr)
{
// Lets try and lower to a constant
ASTNaturalLayoutContext naturalLayoutContext(getASTBuilder(), nullptr);
const auto size = naturalLayoutContext.calcSize(sizeOfLikeExpr->sizedType);
auto builder = getBuilder();
auto resultType = lowerType(context, sizeOfLikeExpr->type);
if (!size)
{
auto sizedType = lowerType(context, sizeOfLikeExpr->sizedType);
// We can create an inst
IRInst* inst = nullptr;
if (as<AlignOfExpr>(sizeOfLikeExpr))
{
inst = builder->emitAlignOf(sizedType);
}
else if (as<SizeOfExpr>(sizeOfLikeExpr))
{
inst = builder->emitSizeOf(sizedType);
}
else
{
inst = builder->emitCountOf(resultType, sizedType);
}
return LoweredValInfo::simple(inst);
}
const auto value = as<SizeOfExpr>(sizeOfLikeExpr) ? size.size : size.alignment;
return LoweredValInfo::simple(getBuilder()->getIntValue(resultType, value));
}
LoweredValInfo visitOverloadedExpr(OverloadedExpr* /*expr*/)
{
SLANG_UNEXPECTED("overloaded expressions should not occur in checked AST");
UNREACHABLE_RETURN(LoweredValInfo());
}
LoweredValInfo visitOverloadedExpr2(OverloadedExpr2* /*expr*/)
{
SLANG_UNEXPECTED("overloaded expressions should not occur in checked AST");
UNREACHABLE_RETURN(LoweredValInfo());
}
LoweredValInfo visitPartiallyAppliedGenericExpr(PartiallyAppliedGenericExpr* /*expr*/)
{
SLANG_UNEXPECTED("partially applied generics should not occur in checked AST");
UNREACHABLE_RETURN(LoweredValInfo());
}
LoweredValInfo visitLambdaExpr(LambdaExpr*)
{
SLANG_UNEXPECTED("a valid ast should not contain an LambdaExpr.");
UNREACHABLE_RETURN(LoweredValInfo());
}
LoweredValInfo visitSPIRVAsmExpr(SPIRVAsmExpr* expr)
{
// Although the surface syntax can have an empty ASM block, the IR asm
// block must have at least one inst
if (!expr->insts.getCount())
return LoweredValInfo{};
auto builder = context->irBuilder;
const auto type = lowerType(context, expr->type);
const auto spirvAsmInst = builder->emitSPIRVAsm(type);
const auto lowerOperand = [&](const SPIRVAsmOperand& operand) -> IRSPIRVAsmOperand*
{
switch (operand.flavor)
{
case SPIRVAsmOperand::Literal:
{
if (operand.token.type == TokenType::IntegerLiteral)
{
// TODO: we should sign-extend these where appropriate,
// difficult because it requires information on usage...
return builder->emitSPIRVAsmOperandLiteral(
builder->getIntValue(builder->getUIntType(), operand.knownValue));
}
else if (operand.token.type == TokenType::StringLiteral)
{
const auto v = getStringLiteralTokenValue(operand.token);
return builder->emitSPIRVAsmOperandLiteral(
builder->getStringValue(v.getUnownedSlice()));
}
SLANG_UNREACHABLE("Unhandled literal type in visitSPIRVAsmExpr");
}
case SPIRVAsmOperand::Id:
{
const auto id = operand.token.getContent();
return builder->emitSPIRVAsmOperandId(builder->getStringValue(id));
}
case SPIRVAsmOperand::ResultMarker:
{
return builder->emitSPIRVAsmOperandResult();
}
case SPIRVAsmOperand::NamedValue:
{
const auto v = operand.knownValue;
const auto i = builder->getIntValue(builder->getUIntType(), v);
if (operand.wrapInId)
return builder->emitSPIRVAsmOperandEnum(i, builder->getUIntType());
else
return builder->emitSPIRVAsmOperandEnum(i);
}
case SPIRVAsmOperand::BuiltinVar:
{
const auto kind = operand.knownValue;
auto kindInst = builder->getIntValue(builder->getIntType(), kind);
const auto type = lowerType(context, operand.type.type);
return builder->emitSPIRVAsmOperandBuiltinVar(type, kindInst);
}
case SPIRVAsmOperand::GLSL450Set:
{
return builder->emitSPIRVAsmOperandGLSL450Set();
}
case SPIRVAsmOperand::NonSemanticDebugPrintfExtSet:
{
return builder->emitSPIRVAsmOperandDebugPrintfSet();
}
case SPIRVAsmOperand::SlangValue:
{
IRInst* i;
{
IRBuilderInsertLocScope insertScope(builder);
builder->setInsertBefore(spirvAsmInst);
i = getSimpleVal(context, lowerRValueExpr(context, operand.expr));
}
return builder->emitSPIRVAsmOperandInst(i);
}
case SPIRVAsmOperand::SlangImmediateValue:
{
IRInst* i;
{
IRBuilderInsertLocScope insertScope(builder);
builder->setInsertBefore(spirvAsmInst);
i = getSimpleVal(context, lowerRValueExpr(context, operand.expr));
}
return builder->emitSPIRVAsmOperandEnum(i);
}
case SPIRVAsmOperand::SlangValueAddr:
{
IRInst* i;
{
IRBuilderInsertLocScope insertScope(builder);
builder->setInsertBefore(spirvAsmInst);
const auto addr = tryGetAddress(
context,
lowerLValueExpr(context, operand.expr),
TryGetAddressMode::Default);
if (addr.flavor == LoweredValInfo::Flavor::Ptr)
i = addr.val;
else
{
context->getSink()->diagnose(operand.expr, Diagnostics::noSuchAddress);
return nullptr;
}
}
return builder->emitSPIRVAsmOperandInst(i);
}
case SPIRVAsmOperand::SlangType:
{
IRInst* i;
{
IRBuilderInsertLocScope insertScope(builder);
builder->setInsertBefore(spirvAsmInst);
i = lowerType(context, operand.type.type);
}
return builder->emitSPIRVAsmOperandInst(i);
}
case SPIRVAsmOperand::SampledType:
{
IRType* i;
{
IRBuilderInsertLocScope insertScope(builder);
builder->setInsertBefore(spirvAsmInst);
i = lowerType(context, operand.type.type);
}
return builder->emitSPIRVAsmOperandSampledType(i);
}
case SPIRVAsmOperand::ImageType:
{
IRInst* i;
{
IRBuilderInsertLocScope insertScope(builder);
builder->setInsertBefore(spirvAsmInst);
i = getSimpleVal(context, lowerRValueExpr(context, operand.expr));
}
return builder->emitSPIRVAsmOperandImageType(i);
}
case SPIRVAsmOperand::SampledImageType:
{
IRInst* i;
{
IRBuilderInsertLocScope insertScope(builder);
builder->setInsertBefore(spirvAsmInst);
i = getSimpleVal(context, lowerRValueExpr(context, operand.expr));
}
return builder->emitSPIRVAsmOperandSampledImageType(i);
}
case SPIRVAsmOperand::TruncateMarker:
{
return builder->emitSPIRVAsmOperandTruncate();
}
case SPIRVAsmOperand::ConvertTexel:
{
IRInst* i;
{
IRBuilderInsertLocScope insertScope(builder);
builder->setInsertBefore(spirvAsmInst);
i = getSimpleVal(context, lowerRValueExpr(context, operand.expr));
}
return builder->emitSPIRVAsmOperandConvertTexel(i);
}
case SPIRVAsmOperand::EntryPoint:
{
return builder->emitSPIRVAsmOperandEntryPoint();
}
case SPIRVAsmOperand::RayPayloadFromLocation:
{
IRInst* i;
{
IRBuilderInsertLocScope insertScope(builder);
builder->setInsertBefore(spirvAsmInst);
i = getSimpleVal(context, lowerRValueExpr(context, operand.expr));
}
return builder->emitSPIRVAsmOperandRayPayloadFromLocation(i);
}
case SPIRVAsmOperand::RayAttributeFromLocation:
{
IRInst* i;
{
IRBuilderInsertLocScope insertScope(builder);
builder->setInsertBefore(spirvAsmInst);
i = getSimpleVal(context, lowerRValueExpr(context, operand.expr));
}
return builder->emitSPIRVAsmOperandRayAttributeFromLocation(i);
}
case SPIRVAsmOperand::RayCallableFromLocation:
{
IRInst* i;
{
IRBuilderInsertLocScope insertScope(builder);
builder->setInsertBefore(spirvAsmInst);
i = getSimpleVal(context, lowerRValueExpr(context, operand.expr));
}
return builder->emitSPIRVAsmOperandRayCallableFromLocation(i);
}
}
SLANG_UNREACHABLE("Unhandled case in visitSPIRVAsmExpr");
};
IRBuilderInsertLocScope insertScope(builder);
builder->setInsertInto(spirvAsmInst);
for (const auto& inst : expr->insts)
{
const auto opcode = lowerOperand(inst.opcode);
List<IRInst*> operands;
for (const auto& operand : inst.operands)
operands.add(lowerOperand(operand));
builder->emitSPIRVAsmInst(opcode, operands);
}
return LoweredValInfo::simple(spirvAsmInst);
}
LoweredValInfo visitIndexExpr(IndexExpr* expr)
{
auto type = lowerType(context, expr->type);
auto baseVal = lowerSubExpr(expr->baseExpression);
SLANG_RELEASE_ASSERT(expr->indexExprs.getCount() == 1);
auto indexVal = getSimpleVal(context, lowerRValueExpr(context, expr->indexExprs[0]));
return subscriptValue(type, baseVal, indexVal);
}
LoweredValInfo visitThisExpr(ThisExpr* /*expr*/) { return context->thisVal; }
LoweredValInfo visitReturnValExpr(ReturnValExpr*) { return context->returnDestination; }
LoweredValInfo visitMemberExpr(MemberExpr* expr)
{
auto loweredType = lowerType(context, expr->type);
auto baseExpr = expr->baseExpression;
baseExpr = sharedLoweringContext.maybeIgnoreCastToInterface(baseExpr);
auto loweredBase = lowerSubExpr(baseExpr);
auto declRef = expr->declRef;
if (auto fieldDeclRef = declRef.as<VarDecl>())
{
// 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->type =
lowerType(context, getResultType(context->astBuilder, callableDeclRef));
boundMemberInfo->base = loweredBase;
boundMemberInfo->declRef = callableDeclRef;
context->shared->extValues.add(boundMemberInfo);
return LoweredValInfo::boundMember(boundMemberInfo);
}
else if (auto propertyDeclRef = declRef.as<PropertyDecl>())
{
// A reference to a property is a special case, because
// we must translate the reference to the property
// into a reference to one of its accessors.
//
return lowerStorageReference(
context,
loweredType,
propertyDeclRef,
loweredBase,
0,
nullptr);
}
SLANG_UNIMPLEMENTED_X("codegen for member expression");
UNREACHABLE_RETURN(LoweredValInfo());
}
// 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 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.
//
IRInst* loweredBaseVal = getSimpleVal(context, loweredBase);
IRType* loweredBaseType = loweredBaseVal->getDataType();
if (as<IRPointerLikeType>(loweredBaseType) || as<IRPtrTypeBase>(loweredBaseType))
{
// 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");
UNREACHABLE_RETURN(LoweredValInfo());
}
}
LoweredValInfo visitMakeRefExpr(MakeRefExpr* expr)
{
auto loweredBase = lowerLValueExpr(context, expr->base);
if (loweredBase.flavor != LoweredValInfo::Flavor::Ptr)
{
// If the base expression is not one that (trivially)
// lower to a pointer, then we have a bit of a problem,
// because the semantics of forming a reference are
// that we should refer to the memory location of
// the operand itself.
//
// For now, we are hacking this case by supporting
// formation of a *read-only* reference when the base
// expression is an r-value, by first copying the base
// expression into a temporary.
//
// Note that this approach is semantically incorrect,
// and a fix should be made further up the stack to
// rule out whatever is happening here.
//
// TODO(tfoley): Investigate why this case is arising
// at all, and/or eliminate the explicit `Ref` type
// entirely, so we don't have to deal with it.
// We start by asserting that the reference type we
// are being asked to form is read-only.
//
SLANG_ASSERT(as<ExplicitRefType>(expr->type) && !QualType(expr->type).isLeftValue);
// Now we perpetrate our hackery, by forming a simple value
// for the operand in an SSA register and copying it into
// a temporary.
//
// TODO(tfoley): This logic might be better expressed by
// forming a `LoweredValInfo` for the temporary and then
// using the `assign()` operation to write the base into it,
// since that operation might produce simpler code than
// we get by using `getSimpleVal` here.
//
auto baseVal = getSimpleVal(context, loweredBase);
auto tempVar = context->irBuilder->emitVar(baseVal->getFullType());
context->irBuilder->emitStore(tempVar, baseVal);
loweredBase.val = tempVar;
}
// Note that the `flavor` of the lowered value that we return
// is always `Simple`, because at the level of the IR a value
// of type `Ref` is just a pointer.
//
// In the case where the hack above was used to introduce a
// temporary, the pointer value is the address of the temporary
// variable itself.
//
loweredBase.flavor = LoweredValInfo::Flavor::Simple;
return loweredBase;
}
LoweredValInfo visitParenExpr(ParenExpr* expr) { return lowerSubExpr(expr->base); }
LoweredValInfo visitTupleExpr(TupleExpr* expr)
{
List<IRInst*> elements;
for (auto element : expr->elements)
{
auto elementVal = getSimpleVal(context, lowerSubExpr(element));
if (auto makeValPack = as<IRMakeValuePack>(elementVal))
{
// If the element is a value pack, we need to flatten it out
// into the tuple.
for (UInt i = 0; i < makeValPack->getOperandCount(); ++i)
{
elements.add(makeValPack->getOperand(i));
}
continue;
}
elements.add(elementVal);
}
auto irMakeTuple =
getBuilder()->emitMakeTuple((UInt)elements.getCount(), elements.getBuffer());
return LoweredValInfo::simple(irMakeTuple);
}
LoweredValInfo visitPackExpr(PackExpr* expr)
{
List<IRInst*> irArgs;
for (auto arg : expr->args)
{
irArgs.add(getSimpleVal(context, lowerSubExpr(arg)));
}
auto irMakeTuple =
getBuilder()->emitMakeValuePack((UInt)irArgs.getCount(), irArgs.getBuffer());
return LoweredValInfo::simple(irMakeTuple);
}
LoweredValInfo visitEachExpr(EachExpr* expr)
{
auto subVal = lowerSubExpr(expr->baseExpr);
SLANG_ASSERT(context->expandIndex);
auto irEach = getBuilder()->emitGetTupleElement(
lowerType(context, expr->type),
getSimpleVal(context, subVal),
context->expandIndex);
return LoweredValInfo::simple(irEach);
}
LoweredValInfo visitExpandExpr(ExpandExpr* expr)
{
auto irBuilder = getBuilder();
auto irType = lowerType(context, expr->type);
List<IRInst*> irCapturedPacks;
if (auto expandType = as<IRExpandTypeOrVal>(irType))
{
for (UInt i = 0; i < expandType->getCaptureCount(); i++)
{
irCapturedPacks.add(expandType->getCaptureType(i));
}
}
else
{
// If the type of the expression is not an ExpandType, then it must be
// a DeclRefType to a generic type pack parameter.
// In this case, the captured type is just the DeclRefType itself.
irCapturedPacks.add(irType);
}
auto expandInst = irBuilder->emitExpandInst(
irType,
(UInt)irCapturedPacks.getCount(),
irCapturedPacks.getBuffer());
irBuilder->setInsertInto(expandInst);
irBuilder->emitBlock();
auto eachIndex = irBuilder->emitParam(irBuilder->getIntType());
IRInst* oldExpandIndex = context->expandIndex;
context->expandIndex = eachIndex;
SLANG_DEFER(context->expandIndex = oldExpandIndex);
irBuilder->emitYield(getSimpleVal(context, lowerSubExpr(expr->baseExpr)));
irBuilder->setInsertAfter(expandInst);
return LoweredValInfo::simple(expandInst);
}
LoweredValInfo getSimpleDefaultVal(IRType* type)
{
type = (IRType*)unwrapAttributedType(type);
if (auto basicType = as<IRBasicType>(type))
{
switch (basicType->getBaseType())
{
default:
SLANG_UNEXPECTED("missing case for getting IR default value");
UNREACHABLE_RETURN(LoweredValInfo());
break;
case BaseType::Bool:
return LoweredValInfo::simple(getBuilder()->getBoolValue(false));
case BaseType::Int8:
case BaseType::Int16:
case BaseType::Int:
case BaseType::Int64:
case BaseType::UInt8:
case BaseType::UInt16:
case BaseType::UInt:
case BaseType::UInt64:
case BaseType::UIntPtr:
case BaseType::IntPtr:
return LoweredValInfo::simple(getBuilder()->getIntValue(type, 0));
case BaseType::Half:
case BaseType::Float:
case BaseType::Double:
return LoweredValInfo::simple(getBuilder()->getFloatValue(type, 0.0));
}
}
SLANG_UNEXPECTED("missing case for getting IR default value");
UNREACHABLE_RETURN(LoweredValInfo());
}
Type* getOriginalTypeFromModifiedType(Type* type)
{
auto innerType = type;
while (auto modifiedType = as<ModifiedType>(innerType))
innerType = modifiedType->getBase();
return innerType;
}
LoweredValInfo getDefaultVal(Type* type)
{
type = getOriginalTypeFromModifiedType(type);
auto irType = lowerType(context, type);
if (auto basicType = as<BasicExpressionType>(type))
{
return getSimpleDefaultVal(irType);
}
else if (auto vectorType = as<VectorExpressionType>(type))
{
UInt elementCount = (UInt)getIntVal(vectorType->getElementCount());
auto irDefaultValue =
getSimpleVal(context, getDefaultVal(vectorType->getElementType()));
List<IRInst*> args;
for (UInt ee = 0; ee < elementCount; ++ee)
{
args.add(irDefaultValue);
}
return LoweredValInfo::simple(
getBuilder()->emitMakeVector(irType, args.getCount(), args.getBuffer()));
}
else if (auto matrixType = as<MatrixExpressionType>(type))
{
UInt rowCount = (UInt)getIntVal(matrixType->getRowCount());
auto rowType = matrixType->getRowType();
auto irDefaultValue = getSimpleVal(context, getDefaultVal(rowType));
List<IRInst*> args;
for (UInt rr = 0; rr < rowCount; ++rr)
{
args.add(irDefaultValue);
}
return LoweredValInfo::simple(
getBuilder()->emitMakeMatrix(irType, args.getCount(), args.getBuffer()));
}
else if (auto arrayType = as<ArrayExpressionType>(type))
{
auto irDefaultElement =
getSimpleVal(context, getDefaultVal(arrayType->getElementType()));
return LoweredValInfo::simple(
getBuilder()->emitMakeArrayFromElement(irType, irDefaultElement));
}
else if (auto ptrType = as<PtrType>(type))
{
return LoweredValInfo::simple(getBuilder()->getNullPtrValue(irType));
}
else if (auto tupleType = as<TupleType>(type))
{
List<IRInst*> args;
for (Index i = 0; i < tupleType->getMemberCount(); i++)
{
args.add(getSimpleVal(context, getDefaultVal(tupleType->getMember(i))));
}
return LoweredValInfo::simple(
getBuilder()->emitMakeTuple(irType, args.getCount(), args.getBuffer()));
}
else if (auto declRefType = as<DeclRefType>(type))
{
DeclRef<Decl> declRef = declRefType->getDeclRef();
if (auto enumType = declRef.as<EnumDecl>())
{
return LoweredValInfo::simple(getBuilder()->getIntValue(irType, 0));
}
else if (declRef.as<InterfaceDecl>())
{
return LoweredValInfo::simple(getBuilder()->emitDefaultConstruct(irType));
}
else if (auto aggTypeDeclRef = declRef.as<AggTypeDecl>())
{
List<IRInst*> args;
if (auto structTypeDeclRef = aggTypeDeclRef.as<StructDecl>())
{
if (auto baseStructType =
findBaseStructType(getASTBuilder(), structTypeDeclRef))
{
auto irBaseVal = getSimpleVal(context, getDefaultVal(baseStructType));
args.add(irBaseVal);
}
}
for (auto ff : getMembersOfType<VarDecl>(
getASTBuilder(),
aggTypeDeclRef,
MemberFilterStyle::Instance))
{
auto irFieldVal = getSimpleVal(context, getDefaultVal(ff));
args.add(irFieldVal);
}
return LoweredValInfo::simple(
getBuilder()->emitMakeStruct(irType, args.getCount(), args.getBuffer()));
}
}
return LoweredValInfo::simple(getBuilder()->emitDefaultConstruct(irType));
}
LoweredValInfo visitDefaultConstructExpr(DefaultConstructExpr* expr)
{
return LoweredValInfo::simple(
getBuilder()->emitDefaultConstruct(lowerType(context, expr->type)));
}
LoweredValInfo getDefaultVal(DeclRef<VarDeclBase> decl)
{
if (auto initExpr = decl.getDecl()->initExpr)
{
return lowerRValueExpr(context, initExpr);
}
else
{
Type* type = decl.substitute(getASTBuilder(), decl.getDecl()->type);
SLANG_ASSERT(type);
return getDefaultVal(type);
}
}
LoweredValInfo visitMakeArrayFromElementExpr(MakeArrayFromElementExpr* expr)
{
auto irType = lowerType(context, expr->type);
auto irDefaultElement = getSimpleVal(
context,
getDefaultVal(as<ArrayExpressionType>(expr->type)->getElementType()));
return LoweredValInfo::simple(
getBuilder()->emitMakeArrayFromElement(irType, irDefaultElement));
}
LoweredValInfo visitInitializerListExpr(InitializerListExpr* expr)
{
// Allocate a temporary of the given type
auto type = expr->type;
IRType* irType = lowerType(context, type);
List<IRInst*> args;
UInt argCount = expr->args.getCount();
// If the initializer list was empty, then the user was
// asking for default initialization, which should apply
// to (almost) any type.
//
if (argCount == 0)
{
return getDefaultVal(type.type);
}
// Now for each argument in the initializer list,
// fill in the appropriate field of the result
if (auto arrayType = as<ArrayExpressionType>(type))
{
UInt elementCount = (UInt)getIntVal(arrayType->getElementCount());
for (UInt ee = 0; ee < argCount; ++ee)
{
auto argExpr = expr->args[ee];
LoweredValInfo argVal = lowerRValueExpr(context, argExpr);
args.add(getSimpleVal(context, argVal));
}
if (elementCount > argCount)
{
auto irDefaultValue =
getSimpleVal(context, getDefaultVal(arrayType->getElementType()));
for (UInt ee = argCount; ee < elementCount; ++ee)
{
args.add(irDefaultValue);
}
}
return LoweredValInfo::simple(
getBuilder()->emitMakeArray(irType, args.getCount(), args.getBuffer()));
}
else if (auto vectorType = as<VectorExpressionType>(type))
{
UInt elementCount = (UInt)getIntVal(vectorType->getElementCount());
for (UInt ee = 0; ee < argCount; ++ee)
{
auto argExpr = expr->args[ee];
LoweredValInfo argVal = lowerRValueExpr(context, argExpr);
args.add(getSimpleVal(context, argVal));
}
if (elementCount > argCount)
{
auto irDefaultValue =
getSimpleVal(context, getDefaultVal(vectorType->getElementType()));
for (UInt ee = argCount; ee < elementCount; ++ee)
{
args.add(irDefaultValue);
}
}
return LoweredValInfo::simple(
getBuilder()->emitMakeVector(irType, args.getCount(), args.getBuffer()));
}
else if (auto matrixType = as<MatrixExpressionType>(type))
{
UInt rowCount = (UInt)getIntVal(matrixType->getRowCount());
for (UInt rr = 0; rr < argCount; ++rr)
{
auto argExpr = expr->args[rr];
LoweredValInfo argVal = lowerRValueExpr(context, argExpr);
args.add(getSimpleVal(context, argVal));
}
if (rowCount > argCount)
{
auto rowType = matrixType->getRowType();
auto irDefaultValue = getSimpleVal(context, getDefaultVal(rowType));
for (UInt rr = argCount; rr < rowCount; ++rr)
{
args.add(irDefaultValue);
}
}
return LoweredValInfo::simple(
getBuilder()->emitMakeMatrix(irType, args.getCount(), args.getBuffer()));
}
else if (auto coopVecType = as<CoopVectorExpressionType>(type))
{
UInt elementCount = (UInt)getIntVal(coopVecType->getElementCount());
for (UInt ee = 0; ee < argCount; ++ee)
{
auto argExpr = expr->args[ee];
LoweredValInfo argVal = lowerRValueExpr(context, argExpr);
args.add(getSimpleVal(context, argVal));
}
if (elementCount > argCount)
{
auto irDefaultValue =
getSimpleVal(context, getDefaultVal(coopVecType->getElementType()));
for (UInt ee = argCount; ee < elementCount; ++ee)
{
args.add(irDefaultValue);
}
}
return LoweredValInfo::simple(
getBuilder()->emitMakeCoopVector(irType, args.getCount(), args.getBuffer()));
}
else if (auto declRefType = as<DeclRefType>(type))
{
DeclRef<Decl> declRef = declRefType->getDeclRef();
if (auto aggTypeDeclRef = declRef.as<AggTypeDecl>())
{
UInt argCounter = 0;
// If the type is a structure type that inherits from another
// structure type, then we need to treat the base type as
// an implicit first field.
//
if (auto structTypeDeclRef = aggTypeDeclRef.as<StructDecl>())
{
if (auto baseStructType =
findBaseStructType(getASTBuilder(), structTypeDeclRef))
{
UInt argIndex = argCounter++;
if (argIndex < argCount)
{
auto argExpr = expr->args[argIndex];
LoweredValInfo argVal = lowerRValueExpr(context, argExpr);
args.add(getSimpleVal(context, argVal));
}
else
{
auto irDefaultValue =
getSimpleVal(context, getDefaultVal(baseStructType));
args.add(irDefaultValue);
}
}
}
for (auto ff : getMembersOfType<VarDecl>(
getASTBuilder(),
aggTypeDeclRef,
MemberFilterStyle::Instance))
{
UInt argIndex = argCounter++;
if (argIndex < argCount)
{
auto argExpr = expr->args[argIndex];
LoweredValInfo argVal = lowerRValueExpr(context, argExpr);
args.add(getSimpleVal(context, argVal));
}
else
{
auto irDefaultValue = getSimpleVal(context, getDefaultVal(ff));
args.add(irDefaultValue);
}
}
if (as<TupleType>(type))
{
return LoweredValInfo::simple(
getBuilder()->emitMakeTuple(irType, args.getCount(), args.getBuffer()));
}
else
{
return LoweredValInfo::simple(
getBuilder()->emitMakeStruct(irType, args.getCount(), args.getBuffer()));
}
}
}
// If none of the above cases matched, then we had better
// have zero arguments in the initializer list, in which
// case we are just looking for default initialization.
//
SLANG_UNEXPECTED("unhandled case for initializer list codegen");
UNREACHABLE_RETURN(LoweredValInfo());
}
LoweredValInfo visitBoolLiteralExpr(BoolLiteralExpr* expr)
{
return LoweredValInfo::simple(context->irBuilder->getBoolValue(expr->value));
}
LoweredValInfo visitNullPtrLiteralExpr(NullPtrLiteralExpr*)
{
return LoweredValInfo::simple(context->irBuilder->getNullVoidPtrValue());
}
LoweredValInfo visitNoneLiteralExpr(NoneLiteralExpr*)
{
return LoweredValInfo::simple(context->irBuilder->getVoidValue());
}
LoweredValInfo visitIntegerLiteralExpr(IntegerLiteralExpr* expr)
{
auto type = lowerType(context, expr->type);
return LoweredValInfo::simple(context->irBuilder->getIntValue(type, expr->value));
}
LoweredValInfo visitFloatingPointLiteralExpr(FloatingPointLiteralExpr* expr)
{
auto type = lowerType(context, expr->type);
return LoweredValInfo::simple(context->irBuilder->getFloatValue(type, expr->value));
}
LoweredValInfo visitStringLiteralExpr(StringLiteralExpr* expr)
{
auto irLit = context->irBuilder->getStringValue(expr->value.getUnownedSlice());
context->shared->m_stringLiterals.add(irLit);
return LoweredValInfo::simple(irLit);
}
LoweredValInfo visitMakeOptionalExpr(MakeOptionalExpr* expr)
{
if (expr->value)
{
auto val = lowerRValueExpr(context, expr->value);
auto optType = lowerType(context, expr->type);
auto irVal = context->irBuilder->emitMakeOptionalValue(optType, val.val);
return LoweredValInfo::simple(irVal);
}
else
{
auto optType = lowerType(context, expr->type);
auto defaultVal = getDefaultVal(as<OptionalType>(expr->type)->getValueType());
auto irVal = context->irBuilder->emitMakeOptionalNone(optType, defaultVal.val);
return LoweredValInfo::simple(irVal);
}
}
LoweredValInfo visitAggTypeCtorExpr(AggTypeCtorExpr* /*expr*/)
{
SLANG_UNIMPLEMENTED_X("codegen for aggregate type constructor expression");
UNREACHABLE_RETURN(LoweredValInfo());
}
LoweredValInfo visitSelectExpr(SelectExpr* expr)
{
// A vector typed `select` expr will turn into a normal `select` op.
if (!as<BasicExpressionType>(expr->arguments[0]->type.type))
{
return visitInvokeExpr(expr);
}
// In global scope? This is a constant, and we should emit as `select` inst.
if (!getParentFunc(context->irBuilder->getInsertLoc().getInst()))
{
return visitInvokeExpr(expr);
}
// A scalar typed `select` expr will turn into an if-else to implement short circuiting
// semantics.
auto builder = context->irBuilder;
auto thenBlock = builder->createBlock();
auto elseBlock = builder->createBlock();
auto afterBlock = builder->createBlock();
auto irCond = getSimpleVal(context, lowerRValueExpr(context, expr->arguments[0]));
builder->emitIfElse(irCond, thenBlock, elseBlock, afterBlock);
builder->insertBlock(thenBlock);
builder->setInsertInto(thenBlock);
auto trueVal = getSimpleVal(context, lowerRValueExpr(context, expr->arguments[1]));
builder->emitBranch(afterBlock, 1, &trueVal);
builder->insertBlock(elseBlock);
builder->setInsertInto(elseBlock);
auto falseVal = getSimpleVal(context, lowerRValueExpr(context, expr->arguments[2]));
builder->emitBranch(afterBlock, 1, &falseVal);
builder->insertBlock(afterBlock);
builder->setInsertInto(afterBlock);
auto paramType = lowerType(context, expr->type.type);
auto result = builder->emitParam(paramType);
return LoweredValInfo::simple(result);
}
LoweredValInfo visitLogicOperatorShortCircuitExpr(LogicOperatorShortCircuitExpr* expr)
{
auto builder = context->irBuilder;
auto thenBlock = builder->createBlock();
auto elseBlock = builder->createBlock();
auto afterBlock = builder->createBlock();
auto irCond = getSimpleVal(context, lowerRValueExpr(context, expr->arguments[0]));
maybeEmitDebugLine(context, nullptr, nullptr, irCond->sourceLoc, true);
// ifElse(<first param>, %true-block, %false-block, %after-block)
builder->emitIfElse(irCond, thenBlock, elseBlock, afterBlock);
// true-block: nonconditionalBranch(%after-block, <second param> : Bool)
// true-block: nonconditionalBranch(%after-block, true) for ||
builder->insertBlock(thenBlock);
builder->setInsertInto(thenBlock);
auto trueVal = expr->flavor == LogicOperatorShortCircuitExpr::Flavor::And
? getSimpleVal(context, lowerRValueExpr(context, expr->arguments[1]))
: LoweredValInfo::simple(context->irBuilder->getBoolValue(true)).val;
builder->emitBranch(afterBlock, 1, &trueVal);
// false-block: nonconditionalBranch(%after-block, false) for &&
// false-block: nonconditionalBranch(%after-block, <second param>: Bool) for ||
builder->insertBlock(elseBlock);
builder->setInsertInto(elseBlock);
auto falseVal = expr->flavor == LogicOperatorShortCircuitExpr::Flavor::And
? LoweredValInfo::simple(context->irBuilder->getBoolValue(false)).val
: getSimpleVal(context, lowerRValueExpr(context, expr->arguments[1]));
builder->emitBranch(afterBlock, 1, &falseVal);
// after-block: return input parameter
builder->insertBlock(afterBlock);
builder->setInsertInto(afterBlock);
auto paramType = lowerType(context, expr->type.type);
auto result = builder->emitParam(paramType);
return LoweredValInfo::simple(result);
}
LoweredValInfo visitInvokeExpr(InvokeExpr* expr)
{
return sharedLoweringContext.visitInvokeExprImpl(
expr,
LoweredValInfo(),
TryClauseEnvironment());
}
LoweredValInfo visitBuiltinCastExpr(BuiltinCastExpr* expr)
{
auto irType = lowerType(context, expr->type);
auto irVal = getSimpleVal(context, lowerRValueExpr(context, expr->base));
return LoweredValInfo::simple(context->irBuilder->emitCast(irType, irVal));
}
/// Emit code for a `try` invoke.
LoweredValInfo visitTryExpr(TryExpr* expr)
{
auto invokeExpr = as<InvokeExpr>(expr->base);
assert(invokeExpr);
TryClauseEnvironment tryEnv;
tryEnv.clauseType = expr->tryClauseType;
return sharedLoweringContext.visitInvokeExprImpl(invokeExpr, LoweredValInfo(), tryEnv);
}
/// Emit code to cast `value` to a concrete `superType` (e.g., a `struct`).
///
/// The `subTypeWitness` is expected to witness the sub-type relationship
/// by naming a field (or chain of fields) that leads from the type of
/// `value` to the field that stores its members for `superType`.
///
LoweredValInfo emitCastToConcreteSuperTypeRec(
LoweredValInfo const& value,
IRType* superType,
Val* subTypeWitness)
{
if (auto declaredSubtypeWitness = as<DeclaredSubtypeWitness>(subTypeWitness))
{
// Drop the specialization info on inheritance decl struct keys, as it makes no
// sense to specialize a key.
return extractField(superType, value, declaredSubtypeWitness->getDeclRef().getDecl());
}
else if (auto transitiveSubtypeWitness = as<TransitiveSubtypeWitness>(subTypeWitness))
{
// Try to resolve the inheritance situation which may show-up with 2+ levels of
// inheritance. We will recursivly follow through the subType->midType &
// midType->superType witnesses until we resolve DeclaredSubtypeWitness's
LoweredValInfo subToMid;
if (auto witness = as<SubtypeWitness>(transitiveSubtypeWitness->getSubToMid()))
subToMid = emitCastToConcreteSuperTypeRec(
value,
lowerType(context, witness->getSup()),
witness);
else
{
SLANG_ASSERT(!"unhandled");
return nullptr;
}
if (auto witness = as<SubtypeWitness>(transitiveSubtypeWitness->getMidToSup()))
return emitCastToConcreteSuperTypeRec(subToMid, superType, witness);
else
{
SLANG_ASSERT(!"unhandled");
return nullptr;
}
}
else
{
SLANG_ASSERT(!"unhandled");
return nullptr;
}
}
LoweredValInfo visitCastToSuperTypeExpr(CastToSuperTypeExpr* expr)
{
auto superType = lowerType(context, expr->type);
auto value = lowerRValueExpr(context, expr->valueArg);
// First, we check if the witness is a type equality witness.
// If so, we can simply emit a bit cast to the target type that should eventually
// fold out to a no-op.
// Note: if we are going to equivalent but not identical types in the future,
// then the cast between equivalent types shouldn't be as simple as a bit cast
// and will require actual coercion logic between the two types.
// For now, we don't support type equivalence witness so this is safe for
// equal types.
if (isTypeEqualityWitness(expr->witnessArg))
{
return LoweredValInfo::simple(
getBuilder()->emitBitCast(superType, getSimpleVal(context, value)));
}
// The actual operation that we need to perform here
// depends on the kind of subtype relationship we
// are making use of.
//
// The first important case is when the super type is
// an interface type, such that casting from a concrete
// value to that type creates a value of existential
// type that binds together the concrete value and the
// witness table that represents the subtype relationship.
//
if (auto declRefType = as<DeclRefType>(expr->type))
{
auto declRef = declRefType->getDeclRef();
if (auto interfaceDeclRef = declRef.as<InterfaceDecl>())
{
// We have an expression that is "up-casting" some concrete value
// to an existential type (aka interface type), using a subtype witness
// (which will lower as a witness table) to show that the conversion
// is valid.
//
auto witnessTable = lowerSimpleVal(context, expr->witnessArg);
// At the IR level, this will become a `makeExistential` instruction,
// which collects the above information into a single IR-level value.
// A dynamic CPU implementation of Slang might encode an existential
// as a "fat pointer" representation, which includes a pointer to
// data for the concrete value, plus a pointer to the witness table.
//
// Note: if/when Slang supports more general existential types, such
// as compositions of interface (e.g., `IReadable & IWritable`), then
// we should probably extend the AST and IR mechanism here to accept
// a sequence of witness tables.
//
auto concreteValue = getSimpleVal(context, value);
auto existentialValue =
getBuilder()->emitMakeExistential(superType, concreteValue, witnessTable);
return LoweredValInfo::simple(existentialValue);
}
else if (auto structDeclRef = declRef.as<StructDecl>())
{
// We are up-casting to a concrete `struct` super-type,
// such that the witness will represent a field of the super-type
// that is stored in instances of the sub-type (or a chain
// of such fields for a transitive witness).
//
return emitCastToConcreteSuperTypeRec(value, superType, expr->witnessArg);
}
}
SLANG_UNEXPECTED("unexpected case of subtype relationship");
UNREACHABLE_RETURN(LoweredValInfo());
}
LoweredValInfo visitAsTypeExpr(AsTypeExpr* expr)
{
auto value = lowerLValueExpr(context, expr->value);
ExtractedExistentialValInfo* existentialInfo = nullptr;
auto optType = lowerType(context, expr->type);
SLANG_RELEASE_ASSERT(optType->getOp() == kIROp_OptionalType);
auto targetType = optType->getOperand(0);
auto builder = getBuilder();
auto var = builder->emitVar(optType);
IRInst* isType = nullptr;
if (expr->witnessArg)
{
auto witness = lowerSimpleVal(context, expr->witnessArg);
existentialInfo = value.getExtractedExistentialValInfo();
isType = builder->emitIsType(
existentialInfo->extractedVal,
existentialInfo->witnessTable,
targetType,
witness);
}
else
{
SLANG_ASSERT(value.val);
auto leftType = lowerType(context, expr->value->type);
IRInst* args[] = {leftType, targetType};
isType = builder->emitIntrinsicInst(builder->getBoolType(), kIROp_TypeEquals, 2, args);
}
IRBlock* trueBlock;
IRBlock* falseBlock;
IRBlock* afterBlock;
builder->emitIfElseWithBlocks(isType, trueBlock, falseBlock, afterBlock);
builder->setInsertInto(trueBlock);
auto irVal = builder->emitReinterpret(
targetType,
existentialInfo ? existentialInfo->extractedVal : getSimpleVal(context, value));
auto optionalVal = builder->emitMakeOptionalValue(optType, irVal);
builder->emitStore(var, optionalVal);
builder->emitBranch(afterBlock);
builder->setInsertInto(falseBlock);
auto defaultVal = getDefaultVal(as<OptionalType>(expr->type)->getValueType());
auto noneVal = builder->emitMakeOptionalNone(optType, defaultVal.val);
builder->emitStore(var, noneVal);
builder->emitBranch(afterBlock);
builder->setInsertInto(afterBlock);
auto result = builder->emitLoad(var);
return LoweredValInfo::simple(result);
}
LoweredValInfo visitIsTypeExpr(IsTypeExpr* expr)
{
auto builder = getBuilder();
if (expr->constantVal)
{
return LoweredValInfo::simple(builder->getBoolValue(expr->constantVal->value));
}
if (expr->witnessArg)
{
auto type = lowerType(context, expr->typeExpr.type);
auto witness = lowerSimpleVal(context, expr->witnessArg);
auto declWitness = as<DeclaredSubtypeWitness>(expr->witnessArg);
if (declWitness && declWitness->isOptional())
{
// Optional constraint check. NoneWitness lowers to a specific
// ID, so that we can check for that here.
auto witnessID = builder->emitGetSequentialIDInst(witness);
auto noneWitnessID = builder->getIntValue(builder->getUIntType(), -1);
auto irVal = builder->emitNeq(witnessID, noneWitnessID);
return LoweredValInfo::simple(irVal);
}
else
{ // This is a run-time type check from for an existential type.
auto value = lowerLValueExpr(context, expr->value);
auto existentialInfo = value.getExtractedExistentialValInfo();
auto irVal = builder->emitIsType(
existentialInfo->extractedVal,
existentialInfo->witnessTable,
type,
witness);
return LoweredValInfo::simple(irVal);
}
}
// For all other cases, we map to a simple type equality check in the IR.
IRType* leftType = nullptr;
if (auto typeType = as<TypeType>(expr->value->type))
{
leftType = lowerType(context, typeType->getType());
}
else
{
leftType = lowerType(context, expr->value->type);
}
auto rightType = lowerType(context, expr->typeExpr.type);
IRInst* args[] = {leftType, rightType};
auto irVal = builder->emitIntrinsicInst(builder->getBoolType(), kIROp_TypeEquals, 2, args);
return LoweredValInfo::simple(irVal);
}
LoweredValInfo visitModifierCastExpr(ModifierCastExpr* expr)
{
return this->dispatch(expr->valueArg);
}
LoweredValInfo subscriptValue(IRType* type, LoweredValInfo baseVal, IRInst* indexVal)
{
auto builder = getBuilder();
// The `tryGetAddress` operation will take a complex value representation
// and try to turn it into a single pointer, if possible.
//
baseVal = tryGetAddress(context, baseVal, TryGetAddressMode::Aggressive);
// The `materialize` operation should ensure that we only have to deal
// with the small number of base cases for lowered value representations.
//
baseVal = materialize(context, baseVal);
switch (baseVal.flavor)
{
case LoweredValInfo::Flavor::Simple:
return LoweredValInfo::simple(
builder->emitElementExtract(type, getSimpleVal(context, baseVal), indexVal));
case LoweredValInfo::Flavor::Ptr:
return LoweredValInfo::ptr(builder->emitElementAddress(baseVal.val, indexVal));
default:
SLANG_UNIMPLEMENTED_X("subscript expr");
UNREACHABLE_RETURN(LoweredValInfo());
}
}
LoweredValInfo extractField(IRType* fieldType, LoweredValInfo base, DeclRef<Decl> field)
{
return Slang::extractField(context, fieldType, base, field);
}
LoweredValInfo visitStaticMemberExpr(StaticMemberExpr* expr)
{
return emitDeclRef(context, expr->declRef, lowerType(context, expr->type));
}
LoweredValInfo visitGenericAppExpr(GenericAppExpr* /*expr*/)
{
SLANG_UNIMPLEMENTED_X("generic application expression during code generation");
UNREACHABLE_RETURN(LoweredValInfo());
}
LoweredValInfo visitSharedTypeExpr(SharedTypeExpr* /*expr*/)
{
SLANG_UNIMPLEMENTED_X("shared type expression during code generation");
UNREACHABLE_RETURN(LoweredValInfo());
}
LoweredValInfo visitThisTypeExpr(ThisTypeExpr* /*expr*/)
{
SLANG_UNIMPLEMENTED_X("this-type expression during code generation");
UNREACHABLE_RETURN(LoweredValInfo());
}
LoweredValInfo visitAndTypeExpr(AndTypeExpr* /*expr*/)
{
SLANG_UNIMPLEMENTED_X("'&' type expression during code generation");
UNREACHABLE_RETURN(LoweredValInfo());
}
LoweredValInfo visitModifiedTypeExpr(ModifiedTypeExpr* /*expr*/)
{
SLANG_UNIMPLEMENTED_X("type expression during code generation");
UNREACHABLE_RETURN(LoweredValInfo());
}
LoweredValInfo visitFuncTypeExpr(FuncTypeExpr* /*expr*/)
{
SLANG_UNIMPLEMENTED_X("type expression during code generation");
UNREACHABLE_RETURN(LoweredValInfo());
}
LoweredValInfo visitTupleTypeExpr(TupleTypeExpr* /*expr*/)
{
SLANG_UNIMPLEMENTED_X("type expression during code generation");
UNREACHABLE_RETURN(LoweredValInfo());
}
LoweredValInfo visitPointerTypeExpr(PointerTypeExpr* /*expr*/)
{
SLANG_UNIMPLEMENTED_X("'*' type expression during code generation");
UNREACHABLE_RETURN(LoweredValInfo());
}
LoweredValInfo visitAssocTypeDecl(AssocTypeDecl* /*decl*/)
{
SLANG_UNIMPLEMENTED_X("associatedtype expression during code generation");
UNREACHABLE_RETURN(LoweredValInfo());
}
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 perform an assignment
// based on the resulting values.
//
auto leftVal = lowerLValueExpr(context, expr->left);
assignExpr(context, leftVal, expr->right, expr->loc);
// 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;
}
LoweredValInfo visitLetExpr(LetExpr* expr)
{
// Note: The semantics here are annoyingly subtle.
//
// If `expr->decl->initExpr` is an l-value, then we will set things up
// so that `expr->decl` is bound as an *alias* for that l-value.
//
// Otherwise, `expr->decl` will simply be bound to the r-value.
//
// The first case is necessary to make `maybeMoveTemp` operations that
// produce l-value results work correctly, but seems slippery.
//
// TODO: We should probably have two AST node types to cover the two
// different use cases of `LetExpr`: the definitely-immutable case that
// actually behaves like a `let`, and this other mutable-alias case that
// feels kind of messy and gross.
auto initVal = lowerLValueExpr(context, expr->decl->initExpr);
context->setGlobalValue(expr->decl, initVal);
auto bodyVal = lowerSubExpr(expr->body);
return bodyVal;
}
LoweredValInfo visitExtractExistentialValueExpr(ExtractExistentialValueExpr* expr)
{
// We are being asked to extract the value from an existential, which
// is itself a single IR op. However, we also need to handle the case
// where `expr` might be used as an l-value, in which case we need
// additional information to allow any mutations through the extracted
// value to be written back.
auto existentialType = lowerType(context, getType(getASTBuilder(), expr->declRef));
auto existentialVal = emitDeclRef(context, expr->declRef, existentialType);
// Note that we make a *copy* of the existential value that is definitely
// a simple r-value. This ensures that all the `extractExistential*()` operations
// below work on the same consistent IR value.
//
auto existentialValCopy = getSimpleVal(context, existentialVal);
auto openedType = lowerType(context, expr->type);
auto extractedVal =
getBuilder()->emitExtractExistentialValue(openedType, existentialValCopy);
if (!isLValueContext())
{
// If we are in an r-value context, we can directly use the `extractExistentialValue`
// instruction as the result, and life is simple.
//
return LoweredValInfo::simple(extractedVal);
}
// In an l-value context, we need to track the information necessary so that
// if a new/modified value of `openedType` was produced, we could write it
// back into the original `existentialVal`'s location.
//
// The write-back is actually pretty simple: it is just a `makeExisential` op.
// In order to be able to emit that op later, we need to track the operands
// that it would use. The first operand would be the new concrete value (which
// would implicitly encode the concrete type via its IR type) while the second
// is the witness table for the conformance to the existential.
//
// Note: We are assuming/requiring here that any value "written back" must have
// the exact same concrete type as `extractedVal`, so taht it can use the same
// IR witness table. The front-end should be enforcing that constraint, and we
// have no way to check or enforce it at this point.
auto witnessTable = getBuilder()->emitExtractExistentialWitnessTable(existentialValCopy);
RefPtr<ExtractedExistentialValInfo> info = new ExtractedExistentialValInfo();
info->extractedVal = extractedVal;
info->existentialVal = existentialVal;
info->existentialType = existentialType;
info->witnessTable = witnessTable;
context->shared->extValues.add(info);
return LoweredValInfo::extractedExistential(info);
}
LoweredValInfo visitOpenRefExpr(OpenRefExpr* expr)
{
auto info = lowerRValueExpr(context, expr->innerExpr);
SLANG_RELEASE_ASSERT(as<IRPtrTypeBase>(info.val->getFullType()));
SLANG_RELEASE_ASSERT(info.flavor == LoweredValInfo::Flavor::Simple);
info.flavor = LoweredValInfo::Flavor::Ptr;
return info;
}
};
struct LValueExprLoweringVisitor : ExprLoweringVisitorBase<LValueExprLoweringVisitor>
{
static bool _isLValueContext() { return true; }
LoweredValInfo visitLValueImplicitCastExpr(LValueImplicitCastExpr* expr)
{
auto irType = lowerType(context, expr->type);
auto loweredArg = lowerLValueExpr(context, expr->arguments[0]);
RefPtr<ImplicitCastLValueInfo> lValueInfo = new ImplicitCastLValueInfo();
lValueInfo->type = irType;
lValueInfo->base = loweredArg;
lValueInfo->lValueType = kParameterDirection_InOut;
if (as<OutImplicitCastExpr>(expr))
lValueInfo->lValueType = kParameterDirection_Out;
context->shared->extValues.add(lValueInfo);
return LoweredValInfo::implicitCastedLValue(lValueInfo);
}
// When visiting a swizzle expression in an l-value context,
// we need to construct a "swizzled l-value."
LoweredValInfo visitMatrixSwizzleExpr(MatrixSwizzleExpr* expr)
{
auto irType = lowerType(context, expr->type);
auto loweredBase = lowerRValueExpr(context, expr->base);
RefPtr<SwizzledMatrixLValueInfo> swizzledLValue = new SwizzledMatrixLValueInfo();
swizzledLValue->type = irType;
UInt elementCount = (UInt)expr->elementCount;
swizzledLValue->elementCount = elementCount;
// In the default case, we can just copy the indices being
// used for the swizzle over directly from the expression,
// and use the base as-is.
//
swizzledLValue->base = loweredBase;
for (UInt ii = 0; ii < elementCount; ++ii)
{
swizzledLValue->elementCoords[ii] = expr->elementCoords[ii];
}
context->shared->extValues.add(swizzledLValue);
return LoweredValInfo::swizzledMatrixLValue(swizzledLValue);
}
// When visiting a swizzle expression in an l-value context,
// we need to construct a "swizzled l-value."
LoweredValInfo visitSwizzleExpr(SwizzleExpr* expr)
{
auto irType = lowerType(context, expr->type);
auto loweredBase = lowerLValueExpr(context, expr->base);
UInt elementCount = (UInt)expr->elementIndices.getCount();
// Assign to 'bs' the elements from 'as' according to the first 'n' indices in 'is'
auto backpermute = [](UInt n, const auto as, const auto is, auto bs)
{
for (UInt i = 0; i < n; ++i)
{
bs[i] = as[is[i]];
}
};
LoweredValInfo result;
// As required by the implementation of 'assign' and as a small
// optimization, we will detect if the base expression has also lowered
// into a swizzle and only return a single swizzle instead of nested
// swizzles.
//
// E.g., if we have input like `foo[i].zw.y` we should optimize it
// down to just `foo[i].w`.
if (loweredBase.flavor == LoweredValInfo::Flavor::SwizzledLValue)
{
auto baseSwizzleInfo = loweredBase.getSwizzledLValueInfo();
// Our new swizzle will use the same base expression (e.g.,
// `foo[i]` in our example above), but will need to remap
// the swizzle indices it uses.
//
RefPtr<SwizzledLValueInfo> swizzledLValue = new SwizzledLValueInfo;
swizzledLValue->type = irType;
swizzledLValue->base = baseSwizzleInfo->base;
swizzledLValue->elementIndices.add((uint32_t)elementCount);
// Take the swizzle element of the "outer" swizzle, as it was
// written by the user. In our running example of `foo[i].zw.y`
// this is the `y` element reference.
//
// Use that original element index to figure out which of the
// elements of the original swizzle this should map to.
backpermute(
swizzledLValue->elementIndices.getCount(),
baseSwizzleInfo->elementIndices,
expr->elementIndices,
swizzledLValue->elementIndices);
context->shared->extValues.add(swizzledLValue);
result = LoweredValInfo::swizzledLValue(swizzledLValue);
}
else if (loweredBase.flavor == LoweredValInfo::Flavor::SwizzledMatrixLValue)
{
auto baseSwizzleInfo = loweredBase.getSwizzledMatrixLValueInfo();
RefPtr<SwizzledMatrixLValueInfo> swizzledLValue = new SwizzledMatrixLValueInfo();
swizzledLValue->type = irType;
swizzledLValue->base = baseSwizzleInfo->base;
swizzledLValue->elementCount = elementCount;
// Use the index of our swizzle to permute the index of the base
// swizzle as above
backpermute(
swizzledLValue->elementCount,
baseSwizzleInfo->elementCoords,
expr->elementIndices,
swizzledLValue->elementCoords);
context->shared->extValues.add(swizzledLValue);
result = LoweredValInfo::swizzledMatrixLValue(swizzledLValue);
}
else
{
RefPtr<SwizzledLValueInfo> swizzledLValue = new SwizzledLValueInfo;
swizzledLValue->type = irType;
swizzledLValue->base = loweredBase;
swizzledLValue->elementIndices = expr->elementIndices;
context->shared->extValues.add(swizzledLValue);
result = LoweredValInfo::swizzledLValue(swizzledLValue);
}
// For a one-element swizzle on a tuple, we can just return the pointer to the member
// instead of a SwizzledLValue because they can't follow the same folding logic as
// vectors and matrices.
//
bool shouldUseSimpleLVal = elementCount == 1 && as<TupleType>(expr->base->type) != nullptr;
if (shouldUseSimpleLVal)
{
auto addr = getAddress(context, result, expr->loc);
return LoweredValInfo::ptr(addr);
}
return result;
}
};
struct RValueExprLoweringVisitor : public ExprLoweringVisitorBase<RValueExprLoweringVisitor>
{
static bool _isLValueContext() { return false; }
LoweredValInfo visitMatrixSwizzleExpr(MatrixSwizzleExpr* expr)
{
auto resultType = lowerType(context, expr->type);
auto base = lowerSubExpr(expr->base);
auto matType = as<MatrixExpressionType>(expr->base->type.type);
if (!matType)
SLANG_UNEXPECTED("Expected a matrix type in matrix swizzle");
auto subscript2 = lowerType(context, matType->getElementType());
auto subscript1 = lowerType(context, matType->getRowType());
auto builder = getBuilder();
auto irIntType = getIntType(context);
UInt elementCount = (UInt)expr->elementCount;
IRInst* irExtracts[4];
for (UInt ii = 0; ii < elementCount; ++ii)
{
auto index1 =
builder->getIntValue(irIntType, (IRIntegerValue)expr->elementCoords[ii].row);
auto index2 =
builder->getIntValue(irIntType, (IRIntegerValue)expr->elementCoords[ii].col);
// First index expression
auto irExtract1 = subscriptValue(subscript1, base, index1);
// Second index expression
irExtracts[ii] = getSimpleVal(context, subscriptValue(subscript2, irExtract1, index2));
}
auto irVector = builder->emitMakeVector(resultType, elementCount, irExtracts);
return LoweredValInfo::simple(irVector);
}
// A swizzle in an r-value context can save time by just
// emitting the swizzle instructions directly.
LoweredValInfo visitSwizzleExpr(SwizzleExpr* expr)
{
auto irType = lowerType(context, expr->type);
auto irBase = getSimpleVal(context, lowerRValueExpr(context, expr->base));
auto builder = getBuilder();
auto irIntType = getIntType(context);
ShortList<IRInst*, 4> irElementIndices;
irElementIndices.setCount(expr->elementIndices.getCount());
for (UInt ii = 0; ii < (UInt)expr->elementIndices.getCount(); ++ii)
{
irElementIndices[ii] =
builder->getIntValue(irIntType, (IRIntegerValue)expr->elementIndices[ii]);
}
auto irSwizzle = builder->emitSwizzle(
irType,
irBase,
(UInt)irElementIndices.getCount(),
&irElementIndices[0]);
return LoweredValInfo::simple(irSwizzle);
}
LoweredValInfo visitOpenRefExpr(OpenRefExpr* expr)
{
auto inner = lowerLValueExpr(context, expr->innerExpr);
return LoweredValInfo::ptr(inner.val);
}
};
// ExprLoweringVisitor that fuses the destination assignment.
//
struct DestinationDrivenRValueExprLoweringVisitor
: ExprVisitor<DestinationDrivenRValueExprLoweringVisitor>
{
ExprLoweringContext<DestinationDrivenRValueExprLoweringVisitor> sharedLoweringContext;
LoweredValInfo destination;
IRGenContext*& context;
DestinationDrivenRValueExprLoweringVisitor()
: context(sharedLoweringContext.context)
{
}
static bool _isLValueContext() { return false; }
// The default case is lower the rvalue expr independently and then assign to destination.
void visitExpr(Expr* expr)
{
auto rValue = lowerRValueExpr(context, expr);
assign(context, destination, rValue);
}
void visitSelectExpr(SelectExpr* expr)
{
auto rValue = lowerRValueExpr(context, expr);
assign(context, destination, rValue);
}
void visitLogicOperatorShortCircuitExpr(LogicOperatorShortCircuitExpr* expr)
{
auto rValue = lowerRValueExpr(context, expr);
assign(context, destination, rValue);
}
void visitInvokeExpr(InvokeExpr* expr)
{
LoweredValInfo resultRVal;
{
IRBuilderSourceLocRAII sourceLocInfo(context->irBuilder, expr->loc);
resultRVal = sharedLoweringContext.visitInvokeExprImpl(
expr,
destination,
TryClauseEnvironment{});
}
if (resultRVal.flavor != LoweredValInfo::Flavor::None)
{
// If we weren't able to fuse the destination write during lowering rvalue,
// we should insert the assign operation now.
assign(context, destination, resultRVal);
}
}
/// Emit code for a `try` invoke.
void visitTryExpr(TryExpr* expr)
{
auto invokeExpr = as<InvokeExpr>(expr->base);
assert(invokeExpr);
TryClauseEnvironment tryEnv;
tryEnv.clauseType = expr->tryClauseType;
auto rValue = sharedLoweringContext.visitInvokeExprImpl(invokeExpr, destination, tryEnv);
if (rValue.flavor != LoweredValInfo::Flavor::None)
{
// If we weren't able to fuse the destination write during lowering rvalue,
// we should insert the assign operation now.
assign(context, destination, rValue);
}
}
};
LoweredValInfo lowerLValueExpr(IRGenContext* context, Expr* expr)
{
IRBuilderSourceLocRAII sourceLocInfo(context->irBuilder, expr->loc);
LValueExprLoweringVisitor visitor;
visitor.context = context;
auto info = visitor.dispatch(expr);
return info;
}
LoweredValInfo lowerRValueExpr(IRGenContext* context, Expr* expr)
{
IRBuilderSourceLocRAII sourceLocInfo(context->irBuilder, expr->loc);
RValueExprLoweringVisitor visitor;
visitor.context = context;
auto info = visitor.dispatch(expr);
return info;
}
void lowerRValueExprWithDestination(IRGenContext* context, LoweredValInfo destination, Expr* expr)
{
DestinationDrivenRValueExprLoweringVisitor visitor;
visitor.context = context;
visitor.destination = destination;
visitor.dispatch(expr);
}
struct StmtLoweringVisitor : StmtVisitor<StmtLoweringVisitor>
{
IRGenContext* context;
IRBuilder* getBuilder() { return context->irBuilder; }
void visitEmptyStmt(EmptyStmt*)
{
// Nothing to do.
}
void visitUnparsedStmt(UnparsedStmt*) { SLANG_UNEXPECTED("UnparsedStmt not supported by IR"); }
void visitCaseStmtBase(CaseStmtBase*)
{
SLANG_UNEXPECTED("`case` or `default` not under `switch`");
}
void visitLabelStmt(LabelStmt* stmt) { lowerStmt(context, stmt->innerStmt); }
void visitCompileTimeForStmt(CompileTimeForStmt* stmt)
{
// The user is asking us to emit code for the loop
// body for each value in the given integer range.
// For now, we will handle this by repeatedly lowering
// the body statement, with the loop variable bound
// to a different integer literal value each time.
//
// TODO: eventually we might handle this as just an
// ordinary loop, with an `[unroll]` attribute on
// it that we would respect.
auto rangeBeginVal = getIntVal(stmt->rangeBeginVal);
auto rangeEndVal = getIntVal(stmt->rangeEndVal);
if (rangeBeginVal >= rangeEndVal)
return;
auto varDecl = stmt->varDecl;
auto varType = lowerType(context, varDecl->type);
IRGenEnv subEnvStorage;
IRGenEnv* subEnv = &subEnvStorage;
subEnv->outer = context->env;
IRGenContext subContextStorage = *context;
IRGenContext* subContext = &subContextStorage;
subContext->env = subEnv;
for (IntegerLiteralValue ii = rangeBeginVal; ii < rangeEndVal; ++ii)
{
auto constVal = getBuilder()->getIntValue(varType, ii);
subEnv->mapDeclToValue[varDecl] = LoweredValInfo::simple(constVal);
lowerStmt(subContext, stmt->body);
}
}
// Create a basic block in the current function,
// so that it can be used for a label.
IRBlock* createBlock() { return getBuilder()->createBlock(); }
/// Does the given block have a terminator?
bool isBlockTerminated(IRBlock* block) { return block->getTerminator() != nullptr; }
/// Emit a branch to the target block if the current
/// block being inserted into is not already terminated.
void emitBranchIfNeeded(IRBlock* targetBlock)
{
auto builder = getBuilder();
auto currentBlock = builder->getBlock();
// Don't emit if there is no current block.
if (!currentBlock)
return;
// Don't emit if the block already has a terminator.
if (isBlockTerminated(currentBlock))
return;
// The block is unterminated, so cap it off with
// a terminator that branches to the target.
builder->emitBranch(targetBlock);
}
/// 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->getBlock();
auto parentFunc = prevBlock ? prevBlock->getParent() : builder->getFunc();
// If the previous block doesn't already have
// a terminator instruction, then be sure to
// emit a branch to the new block.
emitBranchIfNeeded(block);
// Add the new block to the function we are building,
// and setit as the block we will be inserting into.
parentFunc->addBlock(block);
builder->setInsertInto(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;
}
/// Start a new block if there isn't a current
/// block that we can append to.
///
/// The `stmt` parameter is the statement we
/// are about to emit.
void startBlockIfNeeded(Stmt* stmt)
{
auto builder = getBuilder();
auto currentBlock = builder->getBlock();
// If there is a current block and it hasn't
// been terminated, then we can just use that.
if (currentBlock && !isBlockTerminated(currentBlock))
{
return;
}
// We are about to emit code *after* a terminator
// instruction, and there is no label to allow
// branching into this code, so whatever we are
// about to emit is going to be unreachable.
//
// Let's diagnose that here just to help the user.
//
// TODO: We might want to have a more robust check
// for unreachable code based on IR analysis instead,
// at which point we'd probably disable this check.
//
context->getSink()->diagnose(stmt, Diagnostics::unreachableCode);
startBlock();
}
/// Create a new scope end block and return the previous one.
///
/// This is needed for `defer` to be aware of scopes. `preallocated` can
/// be specified if you already have a block at the end of the scope, like
/// in `for` loops.
IRBlock* pushScopeBlock(IRBlock* preallocated = nullptr)
{
IRBlock* prevScopeEndBlock = context->scopeEndBlock;
auto builder = getBuilder();
context->scopeEndBlock = preallocated ? preallocated : builder->createBlock();
return prevScopeEndBlock;
}
/// Pop the current scope end block and restore the previous one.
///
/// This is needed for `defer` to be aware of scopes. `previous` should be
/// the block returned from the corresponding pushScopeBlock. `preallocated`
/// should be true if the corresponding pushScopeBlock was given a block
/// as a parameter.
void popScopeBlock(IRBlock* previous, bool preallocated)
{
if (!preallocated)
{
// If pushScopeBlock actually created the block, we have to insert
// or deallocate it here. Otherwise, we assume that the caller
// handles the end block.
auto builder = getBuilder();
if (context->scopeEndBlock->hasUses())
{
// The end of the scope was referenced, so we need to actually
// keep it around and jump through it.
// Move the terminator to the scope end block.
emitBranchIfNeeded(context->scopeEndBlock);
builder->insertBlock(context->scopeEndBlock);
builder->setInsertInto(context->scopeEndBlock);
}
else
{
// Scope end block was left unused, so we may as well delete it.
context->scopeEndBlock->removeAndDeallocate();
}
}
context->scopeEndBlock = previous;
}
void visitIfStmt(IfStmt* stmt)
{
auto builder = getBuilder();
startBlockIfNeeded(stmt);
auto condExpr = stmt->predicate;
auto thenStmt = stmt->positiveStatement;
auto elseStmt = stmt->negativeStatement;
auto irCond = getSimpleVal(context, lowerRValueExpr(context, condExpr));
maybeEmitDebugLine(context, this, stmt, condExpr->loc);
IRInst* ifInst = nullptr;
if (elseStmt)
{
auto thenBlock = createBlock();
auto elseBlock = createBlock();
auto afterBlock = createBlock();
ifInst = builder->emitIfElse(irCond, thenBlock, elseBlock, afterBlock);
insertBlock(thenBlock);
IRBlock* prevScopeEndBlock = pushScopeBlock(afterBlock);
lowerStmt(context, thenStmt);
emitBranchIfNeeded(afterBlock);
insertBlock(elseBlock);
lowerStmt(context, elseStmt);
popScopeBlock(prevScopeEndBlock, true);
insertBlock(afterBlock);
}
else
{
auto thenBlock = createBlock();
auto afterBlock = createBlock();
ifInst = builder->emitIf(irCond, thenBlock, afterBlock);
insertBlock(thenBlock);
IRBlock* prevScopeEndBlock = pushScopeBlock(afterBlock);
lowerStmt(context, thenStmt);
popScopeBlock(prevScopeEndBlock, true);
insertBlock(afterBlock);
}
if (stmt->findModifier<FlattenAttribute>())
{
builder->addDecoration(ifInst, kIROp_FlattenDecoration);
}
if (stmt->findModifier<BranchAttribute>())
{
builder->addDecoration(ifInst, kIROp_BranchDecoration);
}
}
void addLoopDecorations(IRInst* inst, Stmt* stmt)
{
if (stmt->findModifier<UnrollAttribute>())
{
getBuilder()->addLoopControlDecoration(inst, kIRLoopControl_Unroll);
}
else if (stmt->findModifier<LoopAttribute>())
{
getBuilder()->addLoopControlDecoration(inst, kIRLoopControl_Loop);
}
if (auto maxItersAttr = stmt->findModifier<MaxItersAttribute>())
{
auto iters = lowerVal(context, maxItersAttr->value);
getBuilder()->addLoopMaxItersDecoration(inst, getSimpleVal(context, iters));
}
else if (auto inferredMaxItersAttr = stmt->findModifier<InferredMaxItersAttribute>())
{
getBuilder()->addLoopMaxItersDecoration(inst, inferredMaxItersAttr->value);
}
if (auto forceUnrollAttr = stmt->findModifier<ForceUnrollAttribute>())
{
getBuilder()->addLoopForceUnrollDecoration(inst, forceUnrollAttr->maxIterations);
}
// TODO: handle other cases here
}
void visitForStmt(ForStmt* stmt)
{
auto builder = getBuilder();
startBlockIfNeeded(stmt);
// 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();
// Register the `break` and `continue` labels so
// that we can find them for nested statements.
context->shared->breakLabels.add(stmt->uniqueID, breakLabel);
context->shared->continueLabels.add(stmt->uniqueID, continueLabel);
// Emit the branch that will start out loop,
// and then insert the block for the head.
auto loopInst = builder->emitLoop(loopHead, breakLabel, continueLabel);
insertBlock(loopHead);
// Now that we are within the header block, we
// want to emit the expression for the loop condition:
if (const auto condExpr = stmt->predicateExpression)
{
maybeEmitDebugLine(context, this, stmt, condExpr->loc);
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);
IRBlock* prevScopeEndBlock = pushScopeBlock(continueLabel);
lowerStmt(context, stmt->statement);
popScopeBlock(prevScopeEndBlock, true);
if (auto inferredMaxIters = stmt->findModifier<InferredMaxItersAttribute>())
{
// We only use inferred max iters attribute when the loop body
// does not modify induction var.
auto inductionVar =
emitDeclRef(context, inferredMaxIters->inductionVar, builder->getIntType());
if (inductionVar.val)
{
int writes = 0;
traverseUsers(
inductionVar.val,
[&](IRInst* user)
{
if (user->getOp() != kIROp_Load)
writes++;
});
if (writes > 1)
{
removeModifier(stmt, inferredMaxIters);
}
}
}
if (auto inferredMaxIters = stmt->findModifier<InferredMaxItersAttribute>())
{
if (auto maxIters = stmt->findModifier<MaxItersAttribute>())
{
if (auto constIntVal = as<ConstantIntVal>(maxIters->value))
{
if (inferredMaxIters->value < constIntVal->getValue())
{
context->getSink()->diagnose(
maxIters,
Diagnostics::forLoopTerminatesInFewerIterationsThanMaxIters,
inferredMaxIters->value);
}
}
}
}
addLoopDecorations(loopInst, stmt);
// Insert the `continue` block
insertBlock(continueLabel);
if (auto incrExpr = stmt->sideEffectExpression)
{
maybeEmitDebugLine(context, this, stmt, incrExpr->loc);
lowerRValueExpr(context, incrExpr);
}
// At the end of the body we need to jump back to the top.
emitBranchIfNeeded(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();
startBlockIfNeeded(stmt);
// 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;
// Register the `break` and `continue` labels so
// that we can find them for nested statements.
context->shared->breakLabels.add(stmt->uniqueID, breakLabel);
context->shared->continueLabels.add(stmt->uniqueID, continueLabel);
// 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)
{
maybeEmitDebugLine(context, this, stmt, condExpr->loc);
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);
IRBlock* prevScopeEndBlock = pushScopeBlock(continueLabel);
lowerStmt(context, stmt->statement);
popScopeBlock(prevScopeEndBlock, true);
// At the end of the body we need to jump back to the top.
emitBranchIfNeeded(loopHead);
// Finally we insert the label that a `break` will jump to
insertBlock(breakLabel);
}
void visitDoWhileStmt(DoWhileStmt* stmt)
{
// Generating IR for `do {...} while` statement is similar to a
// `while` statement, just with the test in a different place
auto builder = getBuilder();
startBlockIfNeeded(stmt);
// 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 testLabel = createBlock();
auto breakLabel = createBlock();
// A `continue` inside a `do { ... } while ( ... )` loop always
// jumps to the loop test.
auto continueLabel = testLabel;
// Register the `break` and `continue` labels so
// that we can find them for nested statements.
context->shared->breakLabels.add(stmt->uniqueID, breakLabel);
context->shared->continueLabels.add(stmt->uniqueID, continueLabel);
// 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);
// Emit the body of the loop
IRBlock* prevScopeEndBlock = pushScopeBlock(continueLabel);
lowerStmt(context, stmt->statement);
popScopeBlock(prevScopeEndBlock, true);
insertBlock(testLabel);
// Now that we are within the header block, we
// want to emit the expression for the loop condition:
if (auto condExpr = stmt->predicate)
{
maybeEmitDebugLine(context, this, stmt, stmt->predicate->loc);
auto irCondition = getSimpleVal(context, lowerRValueExpr(context, condExpr));
// One thing to be careful here is that lowering irCondition
// may create additional blocks due to short circuiting, so
// the block we are current inserting into is not necessarily
// the same as `testLabel`.
//
auto invCondition = builder->emitNot(irCondition->getDataType(), irCondition);
// Now we want to `break` if the loop condition is false,
// otherwise we will jump back to the head of the loop.
//
// We need to make sure not to reuse the break block of the loop as
// the break/merge block of the ifelse test.
// Therefore, we introduce a separate merge block for the loop test.
//
// Emit the following structure:
//
// [merge(mergeBlock)]
// if (cond) goto loopHead;
// else goto mergeBlock;
//
// mergeBlock:
// goto breakLabel;
auto mergeBlock = builder->createBlock();
builder->emitIfElse(invCondition, breakLabel, mergeBlock, mergeBlock);
insertBlock(mergeBlock);
builder->emitBranch(loopHead);
}
// Finally we insert the label that a `break` will jump to
insertBlock(breakLabel);
}
void visitGpuForeachStmt(GpuForeachStmt* stmt)
{
auto builder = getBuilder();
startBlockIfNeeded(stmt);
auto device = getSimpleVal(context, lowerRValueExpr(context, stmt->device));
auto gridDims = getSimpleVal(context, lowerRValueExpr(context, stmt->gridDims));
List<IRInst*> irArgs;
if (auto callExpr = as<InvokeExpr>(stmt->kernelCall))
{
irArgs.add(device);
irArgs.add(gridDims);
auto fref = getSimpleVal(context, lowerRValueExpr(context, callExpr->functionExpr));
irArgs.add(fref);
for (auto arg : callExpr->arguments)
{
// if a reference to dispatchThreadID, don't emit
if (auto declRefExpr = as<DeclRefExpr>(arg))
{
if (declRefExpr->declRef.getDecl() == stmt->dispatchThreadID)
{
continue;
}
}
auto irArg = getSimpleVal(context, lowerRValueExpr(context, arg));
irArgs.add(irArg);
}
}
else
{
SLANG_UNEXPECTED("GPUForeach parsing produced an invalid result");
}
builder->emitGpuForeach(irArgs);
return;
}
void visitExpressionStmt(ExpressionStmt* stmt)
{
startBlockIfNeeded(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)
{
startBlockIfNeeded(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)
{
IRBlock* prevScopeEndBlock = pushScopeBlock(nullptr);
// To lower a block (scope) statement, just lower its body.
lowerStmt(context, stmt->body);
popScopeBlock(prevScopeEndBlock, false);
}
void visitReturnStmt(ReturnStmt* stmt)
{
startBlockIfNeeded(stmt);
// Check if this return is within a constructor.
auto constructorDecl = as<ConstructorDecl>(context->funcDecl);
// A `return` statement turns into a `return` instruction,
// but we have two kinds of `return`: one for returning
// a (non-`void`) value, and one for returning "no value"
// (which effectively returns a value of type `void`).
//
if (auto expr = stmt->expression)
{
if (context->returnDestination.flavor != LoweredValInfo::Flavor::None)
{
// If this function should return via a __ref parameter, do that and return void.
lowerRValueExprWithDestination(context, context->returnDestination, expr);
getBuilder()->emitReturn();
return;
}
if (constructorDecl)
{
// If this function is a constructor, but returns a value, rewrite it as
// this = val;
// return this;
lowerRValueExprWithDestination(context, context->thisVal, expr);
getBuilder()->emitReturn(getSimpleVal(context, context->thisVal));
return;
}
// If the AST `return` statement had an expression, then we
// need to lower it to the IR at this point, both to
// compute its value and (in case we are returning a
// `void`-typed expression) to execute its side effects.
//
auto loweredExpr = lowerRValueExpr(context, expr);
// If the AST `return` statement was returning a non-`void`
// value, then we need to emit an IR `return` of that value.
//
if (!expr->type.type->equals(context->astBuilder->getVoidType()))
{
getBuilder()->emitReturn(getSimpleVal(context, loweredExpr));
}
else
{
// If the type of the value returned was `void`, then
// we don't want to emit an IR-level `return` with a value,
// because that could trip up some of our back-end.
//
// TODO: We should eventually have only a single IR-level
// `return` operation that always takes a value (including
// values of type `void`), and then treat an AST `return;`
// as equivalent to something like `return void();`.
//
getBuilder()->emitReturn();
}
}
else
{
// If we hit this case, then the AST `return` was a `return;`
// with no value, which can only occur in a function with
// a `void` result type.
//
if (constructorDecl)
{
// If this `return` is within a NonCopyableType or an ordinary constructor,
// then we must either simply return or `return` the instance respectively.
if (context->returnDestination.flavor != LoweredValInfo::Flavor::None)
{
// If we have a NonCopyableType constructor of the form
// void ctor(inout this) { return; }
getBuilder()->emitReturn();
}
else
{
// If we have an ordinary constructor of the form
// Type ctor() { return; }
getBuilder()->emitReturn(getSimpleVal(context, context->thisVal));
}
return;
}
getBuilder()->emitReturn();
}
}
void visitDeferStmt(DeferStmt* stmt)
{
auto builder = getBuilder();
startBlockIfNeeded(stmt);
IRBlock* deferBlock = builder->createBlock();
IRBlock* mergeBlock = builder->createBlock();
builder->emitDefer(deferBlock, mergeBlock, context->scopeEndBlock);
builder->insertBlock(deferBlock);
builder->setInsertInto(deferBlock);
IRBlock* prevScopeEndBlock = pushScopeBlock(mergeBlock);
lowerStmt(context, stmt->statement);
popScopeBlock(prevScopeEndBlock, true);
builder->emitBranch(mergeBlock);
builder->insertBlock(mergeBlock);
builder->setInsertInto(mergeBlock);
}
void visitThrowStmt(ThrowStmt* stmt)
{
auto builder = getBuilder();
startBlockIfNeeded(stmt);
auto loweredExpr = lowerRValueExpr(context, stmt->expression);
auto loweredVal = getSimpleVal(context, loweredExpr);
auto throwType = lowerType(context, stmt->expression->type);
CatchHandler handler;
if (loweredVal && throwType)
{
handler = findErrorHandler(context, throwType);
}
if (handler.errorHandler)
{
builder->emitBranch(handler.errorHandler, 1, &loweredVal);
}
else
{
builder->emitThrow(getSimpleVal(context, loweredExpr));
}
}
void visitCatchStmt(CatchStmt* stmt)
{
auto builder = getBuilder();
startBlockIfNeeded(stmt);
// The mental model here is that the below Catch statement:
//
// let val = try MayThrowFunc();
// // Do stuff with val
// catch(err: Error)
// {
// catchBlock(err);
// }
//
// lowers similarly to:
//
// handlerLoop: for(;;)
// {
// E err; // Actually just a parameter for the catchBlock, not a real variable.
// bodyLoop: for(;;)
// {
// // Body goes here
// Result<T, E> r = mayThrowFunc();
// if(isResultError(r))
// {
// err = r.error;
// break bodyLoop;
// }
// let val = r.getSuccessValue();
// // Do stuff with val
// break handlerLoop;
// }
// catchBlock(err);
// break handlerLoop;
// }
//
// This approach allows for it to generate valid SPIR-V. Just jumping
// around with unstructured conditional jumps doesn't work there.
IRBlock* handlerLoopHead = createBlock();
IRBlock* handlerBreakLabel = createBlock();
IRBlock* bodyLoopHead = createBlock();
IRBlock* bodyBreakLabel = createBlock();
builder->emitLoop(handlerLoopHead, handlerBreakLabel, handlerLoopHead);
insertBlock(handlerLoopHead);
builder->emitLoop(bodyLoopHead, bodyBreakLabel, bodyLoopHead);
insertBlock(bodyLoopHead);
CatchHandler catchHandler;
catchHandler.errorType =
stmt->errorVar ? lowerType(context, stmt->errorVar->getType()) : nullptr;
catchHandler.errorHandler = bodyBreakLabel;
catchHandler.prev = context->catchHandler;
context->catchHandler = &catchHandler;
// Note that the tryBody doesn't actually have to have it's own scope or
// block. If there's a `defer` in the tryBody, it can run after the
// catch statement.
lowerStmt(context, stmt->tryBody);
// Put break; at the end of the body if there's nothing else there yet.
// This prevents the catch handler from running.
emitBranchIfNeeded(handlerBreakLabel);
context->catchHandler = catchHandler.prev;
insertBlock(bodyBreakLabel);
if (catchHandler.errorType)
{
auto irParam = builder->emitParam(catchHandler.errorType);
auto paramVal = LoweredValInfo::simple(irParam);
context->setGlobalValue(stmt->errorVar, paramVal);
}
IRBlock* prevScopeEndBlock = pushScopeBlock(handlerBreakLabel);
lowerStmt(context, stmt->handleBody);
popScopeBlock(prevScopeEndBlock, true);
emitBranchIfNeeded(handlerBreakLabel);
insertBlock(handlerBreakLabel);
}
void visitDiscardStmt(DiscardStmt* stmt)
{
startBlockIfNeeded(stmt);
getBuilder()->emitDiscard();
}
void visitBreakStmt(BreakStmt* stmt)
{
startBlockIfNeeded(stmt);
// Semantic checking is responsible for finding
// the statement taht this `break` breaks out of
auto targetStmtID = stmt->targetOuterStmtID;
SLANG_ASSERT(targetStmtID != BreakableStmt::kInvalidUniqueID);
// We just need to look up the basic block that
// corresponds to the break label for that statement,
// and then emit an instruction to jump to it.
IRBlock* targetBlock = nullptr;
context->shared->breakLabels.tryGetValue(targetStmtID, targetBlock);
SLANG_ASSERT(targetBlock);
getBuilder()->emitBreak(targetBlock);
}
void visitContinueStmt(ContinueStmt* stmt)
{
startBlockIfNeeded(stmt);
// Semantic checking is responsible for finding
// the loop that this `continue` statement continues
auto targetStmtID = stmt->targetOuterStmtID;
SLANG_ASSERT(targetStmtID != BreakableStmt::kInvalidUniqueID);
// We just need to look up the basic block that
// corresponds to the continue label for that statement,
// and then emit an instruction to jump to it.
IRBlock* targetBlock = nullptr;
context->shared->continueLabels.tryGetValue(targetStmtID, targetBlock);
SLANG_ASSERT(targetBlock);
getBuilder()->emitContinue(targetBlock);
}
// Lowering a `switch` statement can get pretty involved,
// so we need to track a bit of extra data:
struct SwitchStmtInfo
{
// The block that will be made to contain the `switch` statement
IRBlock* initialBlock = nullptr;
// The label for the `default` case, if any.
IRBlock* defaultLabel = nullptr;
// The label of the current "active" case block.
IRBlock* currentCaseLabel = nullptr;
// Has anything been emitted to the current "active" case block?
bool anythingEmittedToCurrentCaseBlock = false;
// The collected (value, label) pairs for
// all the `case` statements.
List<IRInst*> cases;
};
// We need a label to use for a `case` or `default` statement,
// so either create one here, or re-use the current one if
// that is okay.
IRBlock* getLabelForCase(SwitchStmtInfo* info)
{
// Look at the "current" label we are working with.
auto currentCaseLabel = info->currentCaseLabel;
// If there is a current block, and it is empty,
// then it is still a viable target (we are in
// a case of "trivial fall-through" from the previous
// block).
if (currentCaseLabel && !info->anythingEmittedToCurrentCaseBlock)
{
return currentCaseLabel;
}
// Othwerise, we need to start a new block and use that.
IRBlock* newCaseLabel = createBlock();
// Note: if the previous block failed
// to end with a `break`, then inserting
// this block will append an unconditional
// branch to the end of it that will target
// this block.
insertBlock(newCaseLabel);
info->currentCaseLabel = newCaseLabel;
info->anythingEmittedToCurrentCaseBlock = false;
return newCaseLabel;
}
bool hasSwitchCases(Stmt* inStmt)
{
Stmt* stmt = inStmt;
// Unwrap any surrounding `{ ... }` so we can look
// at the statement inside.
while (auto blockStmt = as<BlockStmt>(stmt))
{
stmt = blockStmt->body;
continue;
}
if (auto seqStmt = as<SeqStmt>(stmt))
{
// Walk through the children looking for cases
for (auto childStmt : seqStmt->stmts)
{
if (hasSwitchCases(childStmt))
{
return true;
}
}
}
else if (const auto caseStmt = as<CaseStmt>(stmt))
{
return true;
}
else if (const auto defaultStmt = as<DefaultStmt>(stmt))
{
// A 'default:' is a kind of case.
return true;
}
return false;
}
// Given a statement that appears as (or in) the body
// of a `switch` statement
void lowerSwitchCases(Stmt* inStmt, SwitchStmtInfo* info)
{
// TODO: in the general case (e.g., if we were going
// to eventual lower to an unstructured format like LLVM),
// the Right Way to handle C-style `switch` statements
// is just to emit the body directly as "normal" statements,
// and then treat `case` and `default` as special statements
// that start a new block and register a label with the
// enclosing `switch`.
//
// For now we will assume that any `case` and `default`
// statements need to be directly nested under the `switch`,
// and so we can find them with a simpler walk.
Stmt* stmt = inStmt;
// Unwrap any surrounding `{ ... }` so we can look
// at the statement inside.
while (auto blockStmt = as<BlockStmt>(stmt))
{
stmt = blockStmt->body;
continue;
}
if (auto seqStmt = as<SeqStmt>(stmt))
{
// Walk through teh children and process each.
for (auto childStmt : seqStmt->stmts)
{
lowerSwitchCases(childStmt, info);
}
}
else if (auto caseStmt = as<CaseStmt>(stmt))
{
// A full `case` statement has a value we need
// to test against. It is expected to be a
// compile-time constant, so we will emit
// it like an expression here, and then hope
// for the best.
//
// TODO: figure out something cleaner.
// Actually, one gotcha is that if we ever allow non-constant
// expressions here (or anything that requires instructions
// to be emitted to yield its value), then those instructions
// need to go into an appropriate block.
IRGenContext subContext = *context;
IRBuilder subBuilder = *getBuilder();
subBuilder.setInsertInto(info->initialBlock);
subContext.irBuilder = &subBuilder;
auto constVal = as<ConstantIntVal>(caseStmt->exprVal);
SLANG_ASSERT(constVal);
auto caseType = lowerType(context, constVal->getType());
auto caseValInfo =
LoweredValInfo::simple(getBuilder()->getIntValue(caseType, constVal->getValue()));
auto caseVal = getSimpleVal(context, caseValInfo);
// Figure out where we are branching to.
auto label = getLabelForCase(info);
// Add this `case` to the list for the enclosing `switch`.
info->cases.add(caseVal);
info->cases.add(label);
}
else if (const auto defaultStmt = as<DefaultStmt>(stmt))
{
auto label = getLabelForCase(info);
// We expect to only find a single `default` stmt.
SLANG_ASSERT(!info->defaultLabel);
info->defaultLabel = label;
}
else if (const auto emptyStmt = as<EmptyStmt>(stmt))
{
// Special-case empty statements so they don't
// mess up our "trivial fall-through" optimization.
}
else
{
// We have an ordinary statement, that needs to get
// emitted to the current case block.
if (!info->currentCaseLabel)
{
// It possible in full C/C++ to have statements
// before the first `case`. Usually these are
// unreachable, unless they start with a label.
//
// We'll ignore them here, figuring they are
// dead. If we ever add `LabelStmt` then we'd
// need to emit these statements to a dummy
// block just in case.
}
else
{
// Emit the code to our current case block,
// and record that we've done so.
lowerStmt(context, stmt);
info->anythingEmittedToCurrentCaseBlock = true;
}
}
}
void visitStageSwitchStmt(StageSwitchStmt* stmt)
{
if (!stmt->targetCases.getCount())
return;
// We will lower stage switch as a normal switch statement, so they can participate in all
// optimizations.
auto builder = getBuilder();
startBlockIfNeeded(stmt);
// First emit code to get the current stage to switch on:
auto conditionVal = builder->emitGetCurrentStage();
// Remember the initial block so that we can add to it
// after we've collected all the `case`s
auto initialBlock = builder->getBlock();
// Next, create a block to use as the target for any `break` statements
auto breakLabel = createBlock();
// Register the `break` label so
// that we can find it for nested statements.
context->shared->breakLabels.add(stmt->uniqueID, breakLabel);
builder->setInsertInto(initialBlock->getParent());
// Iterate over the body of the statement, looking
// for `case` or `default` statements:
SwitchStmtInfo info;
info.initialBlock = initialBlock;
info.defaultLabel = nullptr;
Dictionary<Stmt*, IRBlock*> mapCaseStmtToBlock;
for (auto targetCase : stmt->targetCases)
{
IRBlock* caseBlock = nullptr;
if (!mapCaseStmtToBlock.tryGetValue(targetCase->body, caseBlock))
{
caseBlock = builder->emitBlock();
lowerStmt(context, targetCase->body);
mapCaseStmtToBlock.add(targetCase->body, caseBlock);
if (!builder->getBlock()->getTerminator())
builder->emitBranch(breakLabel);
}
if (targetCase->capability == (int32_t)CapabilityName::Invalid)
{
info.defaultLabel = caseBlock;
}
else
{
auto stage = getStageFromAtom((CapabilityAtom)targetCase->capability);
info.cases.add(builder->getIntValue(builder->getIntType(), (IRIntegerValue)stage));
info.cases.add(caseBlock);
}
}
// If the current block (the end of the last
// `case`) is not terminated, then terminate with a
// `break` operation.
//
// Double check that we aren't in the initial
// block, so we don't get tripped up on an
// empty `switch`.
auto curBlock = builder->getBlock();
if (curBlock != initialBlock)
{
// Is the block already terminated?
if (!curBlock->getTerminator())
{
// Not terminated, so add one.
builder->emitBreak(breakLabel);
}
}
// If there was no `default` statement, then the
// default case will just branch directly to the end.
auto defaultLabel = info.defaultLabel ? info.defaultLabel : breakLabel;
// Now that we've collected the cases, we are
// prepared to emit the `switch` instruction
// itself.
builder->setInsertInto(initialBlock);
builder->emitSwitch(
conditionVal,
breakLabel,
defaultLabel,
info.cases.getCount(),
info.cases.getBuffer());
// Finally we insert the label that a `break` will jump to
// (and that control flow will fall through to otherwise).
// This is the block that subsequent code will go into.
insertBlock(breakLabel);
context->shared->breakLabels.remove(stmt->uniqueID);
}
void visitTargetSwitchStmt(TargetSwitchStmt* stmt)
{
if (!stmt->targetCases.getCount())
return;
auto builder = getBuilder();
startBlockIfNeeded(stmt);
auto initialBlock = builder->getBlock();
auto breakLabel = builder->createBlock();
context->shared->breakLabels.add(stmt->uniqueID, breakLabel);
builder->setInsertInto(initialBlock->getParent());
List<IRInst*> args;
args.add(breakLabel);
Dictionary<Stmt*, IRBlock*> mapCaseStmtToBlock;
for (auto targetCase : stmt->targetCases)
{
IRBlock* caseBlock = nullptr;
if (!mapCaseStmtToBlock.tryGetValue(targetCase->body, caseBlock))
{
caseBlock = builder->emitBlock();
lowerStmt(context, targetCase->body);
mapCaseStmtToBlock.add(targetCase->body, caseBlock);
if (!builder->getBlock()->getTerminator())
builder->emitBranch(breakLabel);
}
args.add(builder->getIntValue(builder->getIntType(), targetCase->capability));
args.add(caseBlock);
}
context->shared->breakLabels.remove(stmt->uniqueID);
builder->setInsertInto(initialBlock);
auto parentFunc = initialBlock->getParent();
parentFunc->addBlock(breakLabel);
builder->emitIntrinsicInst(
nullptr,
kIROp_TargetSwitch,
(UInt)args.getCount(),
args.getBuffer());
builder->setInsertInto(breakLabel);
}
void visitTargetCaseStmt(TargetCaseStmt*) { SLANG_UNREACHABLE("lowering target case"); }
void visitIntrinsicAsmStmt(IntrinsicAsmStmt* stmt)
{
auto builder = getBuilder();
ShortList<IRInst*> args;
args.add(builder->getStringValue(stmt->asmText.getUnownedSlice()));
for (auto argExpr : stmt->args)
{
if (auto typetype = as<TypeType>(argExpr->type))
{
auto type = lowerType(context, typetype->getType());
args.add(type);
}
else
{
auto argVal = lowerRValueExpr(context, argExpr);
args.add(argVal.val);
}
}
builder->emitIntrinsicInst(
nullptr,
kIROp_GenericAsm,
args.getCount(),
args.getArrayView().getBuffer());
}
void visitSwitchStmt(SwitchStmt* stmt)
{
auto builder = getBuilder();
startBlockIfNeeded(stmt);
// Given a statement:
//
// switch( CONDITION )
// {
// case V0:
// S0;
// break;
//
// case V1:
// default:
// S1;
// break;
// }
//
// we want to generate IR like:
//
// let %c = <CONDITION>;
// switch %c, // value to switch on
// %breakLabel, // join point (and break target)
// %s1, // default label
// %v0, // first case value
// %s0, // first case label
// %v1, // second case value
// %s1 // second case label
// s0:
// <S0>
// break %breakLabel
// s1:
// <S1>
// break %breakLabel
// breakLabel:
//
// First emit code to compute the condition:
auto conditionVal = getSimpleVal(context, lowerRValueExpr(context, stmt->condition));
// Check for any cases or default.
if (!hasSwitchCases(stmt->body))
{
// If we don't have any case/default then nothing inside switch can be executed (other
// than condition) so we are done.
return;
}
// Remember the initial block so that we can add to it
// after we've collected all the `case`s
auto initialBlock = builder->getBlock();
// Next, create a block to use as the target for any `break` statements
auto breakLabel = createBlock();
// Register the `break` label so
// that we can find it for nested statements.
context->shared->breakLabels.add(stmt->uniqueID, breakLabel);
builder->setInsertInto(initialBlock->getParent());
// Iterate over the body of the statement, looking
// for `case` or `default` statements:
SwitchStmtInfo info;
info.initialBlock = initialBlock;
info.defaultLabel = nullptr;
lowerSwitchCases(stmt->body, &info);
// TODO: once we've discovered the cases, we should
// be able to make a quick pass over the list and eliminate
// any cases that have the exact same label as the `default`
// case, since these don't actually need to be represented.
// If the current block (the end of the last
// `case`) is not terminated, then terminate with a
// `break` operation.
//
// Double check that we aren't in the initial
// block, so we don't get tripped up on an
// empty `switch`.
auto curBlock = builder->getBlock();
if (curBlock != initialBlock)
{
// Is the block already terminated?
if (!curBlock->getTerminator())
{
// Not terminated, so add one.
builder->emitBreak(breakLabel);
}
}
// If there was no `default` statement, then the
// default case will just branch directly to the end.
auto defaultLabel = info.defaultLabel ? info.defaultLabel : breakLabel;
// Now that we've collected the cases, we are
// prepared to emit the `switch` instruction
// itself.
builder->setInsertInto(initialBlock);
auto switchInst = builder->emitSwitch(
conditionVal,
breakLabel,
defaultLabel,
info.cases.getCount(),
info.cases.getBuffer());
// Finally we insert the label that a `break` will jump to
// (and that control flow will fall through to otherwise).
// This is the block that subsequent code will go into.
insertBlock(breakLabel);
context->shared->breakLabels.remove(stmt->uniqueID);
// If there is the branch attribute output the IR decoration
if (stmt->hasModifier<BranchAttribute>())
{
builder->addDecoration(switchInst, kIROp_BranchDecoration);
}
}
};
IRInst* getOrEmitDebugSource(IRGenContext* context, PathInfo path)
{
if (auto result = context->shared->mapSourcePathToDebugSourceInst.tryGetValue(path.foundPath))
return *result;
ComPtr<ISlangBlob> outBlob;
if (path.hasFileFoundPath())
{
context->getLinkage()->getFileSystemExt()->loadFile(
path.foundPath.getBuffer(),
outBlob.writeRef());
}
UnownedStringSlice content;
if (outBlob)
content = UnownedStringSlice((char*)outBlob->getBufferPointer(), outBlob->getBufferSize());
IRBuilder builder(*context->irBuilder);
builder.setInsertInto(context->irBuilder->getModule());
auto debugSrcInst = builder.emitDebugSource(path.foundPath.getUnownedSlice(), content, false);
context->shared->mapSourcePathToDebugSourceInst[path.foundPath] = debugSrcInst;
return debugSrcInst;
}
void maybeEmitDebugLine(
IRGenContext* context,
StmtLoweringVisitor* visitor,
Stmt* stmt,
SourceLoc loc,
bool allowNullStmt)
{
if (!context->includeDebugInfo)
return;
if (!allowNullStmt)
{
if (as<EmptyStmt>(stmt))
return;
if (!loc.isValid())
loc = stmt->loc;
}
auto sourceManager = context->getLinkage()->getSourceManager();
auto sourceView = sourceManager->findSourceView(loc);
if (!sourceView)
return;
IRInst* debugSourceInst = nullptr;
auto humaneLoc = sourceManager->getHumaneLoc(loc, SourceLocType::Emit);
// Do a best-effort attempt to retrieve the nominal source file.
auto pathInfo = sourceView->getPathInfo(loc, SourceLocType::Emit);
// If the source file path correspond to an existing SourceFile in the source manager, use it.
auto source = sourceManager->findSourceFileByPathRecursively(pathInfo.foundPath);
if (!source)
source = sourceManager->findSourceFile(pathInfo.getMostUniqueIdentity());
if (source)
{
context->shared->mapSourceFileToDebugSourceInst.tryGetValue(source, debugSourceInst);
}
// If the source manager does not have an entry for the corresponding file name, make sure we
// still emit an source file entry in the spirv module.
if (!debugSourceInst)
{
debugSourceInst = getOrEmitDebugSource(context, pathInfo);
}
if (visitor)
visitor->startBlockIfNeeded(stmt);
context->irBuilder->emitDebugLine(
debugSourceInst,
humaneLoc.line,
humaneLoc.line,
humaneLoc.column,
humaneLoc.column + 1);
}
void maybeAddDebugLocationDecoration(IRGenContext* context, IRInst* inst)
{
if (!context->includeDebugInfo)
return;
auto sourceView = context->getLinkage()->getSourceManager()->findSourceView(inst->sourceLoc);
if (!sourceView)
return;
auto source = sourceView->getSourceFile();
IRInst* debugSourceInst = nullptr;
if (context->shared->mapSourceFileToDebugSourceInst.tryGetValue(source, debugSourceInst))
{
auto humaneLoc = context->getLinkage()->getSourceManager()->getHumaneLoc(
inst->sourceLoc,
SourceLocType::Emit);
context->irBuilder
->addDebugLocationDecoration(inst, debugSourceInst, humaneLoc.line, humaneLoc.column);
}
}
void lowerStmt(IRGenContext* context, Stmt* stmt)
{
IRBuilderSourceLocRAII sourceLocInfo(context->irBuilder, stmt->loc);
StmtLoweringVisitor visitor;
visitor.context = context;
try
{
maybeEmitDebugLine(context, &visitor, stmt, stmt->loc);
visitor.dispatch(stmt);
}
// Don't emit any context message for an explicit `AbortCompilationException`
// because it should only happen when an error is already emitted.
catch (const AbortCompilationException&)
{
throw;
}
catch (...)
{
context->getSink()->noteInternalErrorLoc(stmt->loc);
throw;
}
}
/// Create and return a mutable temporary initialized with `val`
static LoweredValInfo moveIntoMutableTemp(IRGenContext* context, LoweredValInfo const& val)
{
IRInst* irVal = getSimpleVal(context, val);
auto type = irVal->getDataType();
auto var = createVar(context, type);
assign(context, var, LoweredValInfo::simple(irVal));
return var;
}
LoweredValInfo tryGetAddress(
IRGenContext* context,
LoweredValInfo const& inVal,
TryGetAddressMode mode)
{
LoweredValInfo val = inVal;
switch (val.flavor)
{
case LoweredValInfo::Flavor::Ptr:
// The `Ptr` case means that we already have an IR value with
// the address of our value. Easy!
return val;
case LoweredValInfo::Flavor::BoundStorage:
{
// If we are are trying to turn a subscript operation like `buffer[index]`
// into a pointer, then we need to find a `ref` accessor declared
// as part of the subscript operation being referenced.
//
auto subscriptInfo = val.getBoundStorageInfo();
// We don't want to immediately bind to a `ref` accessor if there is
// a `set` accessor available, unless we are in an "aggressive" mode
// where we really want/need a pointer to be able to make progress.
//
if (mode != TryGetAddressMode::Aggressive && getMembersOfType<SetterDecl>(
context->astBuilder,
subscriptInfo->declRef,
MemberFilterStyle::Instance)
.isNonEmpty())
{
// There is a setter that we should consider using,
// so don't go and aggressively collapse things just yet.
return val;
}
auto refAccessors = getMembersOfType<RefAccessorDecl>(
context->astBuilder,
subscriptInfo->declRef,
MemberFilterStyle::Instance);
if (refAccessors.isNonEmpty())
{
auto refAccessor = *refAccessors.begin();
// The `ref` accessor will return a pointer to the value, so
// we need to reflect that in the type of our `call` instruction.
IRType* ptrType = context->irBuilder->getPtrType(subscriptInfo->type);
LoweredValInfo refVal = _emitCallToAccessor(
context,
ptrType,
refAccessor,
subscriptInfo->base,
subscriptInfo->additionalArgs);
// The result from the call should be a pointer, and it
// is the address that we wanted in the first place.
return LoweredValInfo::ptr(getSimpleVal(context, refVal));
}
// Otherwise, there was no `ref` accessor, and so it is not possible
// to materialize this location into a pointer for whatever purpose
// we have in mind (e.g., passing it to an atomic operation).
}
break;
case LoweredValInfo::Flavor::BoundMember:
{
auto boundMemberInfo = val.getBoundMemberInfo();
// If we hit this case, then it means that we have a reference
// to a single field in something, but for whatever reason the
// higher-level logic was not able to turn it into a pointer
// already (maybe the base value for the field reference is
// a `BoundStorage`, etc.).
//
// We need to read the entire base value out, modify the field
// we care about, and then write it back.
auto declRef = boundMemberInfo->declRef;
if (auto fieldDeclRef = declRef.as<VarDecl>())
{
auto baseVal = boundMemberInfo->base;
auto basePtr = tryGetAddress(context, baseVal, TryGetAddressMode::Aggressive);
return extractField(context, boundMemberInfo->type, basePtr, fieldDeclRef);
}
}
break;
case LoweredValInfo::Flavor::SwizzledLValue:
{
auto originalSwizzleInfo = val.getSwizzledLValueInfo();
auto originalBase = originalSwizzleInfo->base;
UInt elementCount = (UInt)originalSwizzleInfo->elementIndices.getCount();
auto newBase = tryGetAddress(context, originalBase, TryGetAddressMode::Aggressive);
if (newBase.flavor == LoweredValInfo::Flavor::Ptr && elementCount == 1)
{
// A special case is when we have a single element swizzle,
// we can just emit an element address.
auto elementPtr = context->irBuilder->emitElementAddress(
newBase.val,
originalSwizzleInfo->elementIndices[0]);
return LoweredValInfo::ptr(elementPtr);
}
RefPtr<SwizzledLValueInfo> newSwizzleInfo = new SwizzledLValueInfo();
context->shared->extValues.add(newSwizzleInfo);
newSwizzleInfo->base = newBase;
newSwizzleInfo->type = originalSwizzleInfo->type;
newSwizzleInfo->elementIndices.setCount(elementCount);
for (UInt ee = 0; ee < elementCount; ++ee)
newSwizzleInfo->elementIndices[ee] = originalSwizzleInfo->elementIndices[ee];
return LoweredValInfo::swizzledLValue(newSwizzleInfo);
}
break;
// TODO(Ellie): There's an uncomfortable level of duplication here...
case LoweredValInfo::Flavor::SwizzledMatrixLValue:
{
auto originalSwizzleInfo = val.getSwizzledMatrixLValueInfo();
auto originalBase = originalSwizzleInfo->base;
UInt elementCount = originalSwizzleInfo->elementCount;
auto newBase = tryGetAddress(context, originalBase, TryGetAddressMode::Aggressive);
RefPtr<SwizzledMatrixLValueInfo> newSwizzleInfo = new SwizzledMatrixLValueInfo();
context->shared->extValues.add(newSwizzleInfo);
newSwizzleInfo->base = newBase;
newSwizzleInfo->type = originalSwizzleInfo->type;
newSwizzleInfo->elementCount = elementCount;
for (UInt ee = 0; ee < elementCount; ++ee)
{
newSwizzleInfo->elementCoords[ee] = originalSwizzleInfo->elementCoords[ee];
}
return LoweredValInfo::swizzledMatrixLValue(newSwizzleInfo);
}
break;
case LoweredValInfo::Flavor::ImplicitCastedLValue:
{
auto info = val.getImplicitCastedLValue();
auto baseAddr = tryGetAddress(context, info->base, TryGetAddressMode::Aggressive);
if (baseAddr.flavor == LoweredValInfo::Flavor::Ptr)
{
IRInst* result = nullptr;
if (info->lValueType == kParameterDirection_InOut)
result = context->irBuilder->emitInOutImplicitCast(
context->irBuilder->getPtrType(info->type),
baseAddr.val);
else
result = context->irBuilder->emitOutImplicitCast(
context->irBuilder->getPtrType(info->type),
baseAddr.val);
return LoweredValInfo::ptr(result);
}
}
break;
// TODO: are there other cases we need to handled here?
default:
break;
}
// If none of the special cases above applied, then we werent' able to make
// this value into a pointer, and we should just return it as-is.
return val;
}
IRInst* getAddress(IRGenContext* context, LoweredValInfo const& inVal, SourceLoc diagnosticLocation)
{
LoweredValInfo val = tryGetAddress(context, inVal, TryGetAddressMode::Aggressive);
if (val.flavor == LoweredValInfo::Flavor::Ptr)
{
return val.val;
}
context->getSink()->diagnose(diagnosticLocation, Diagnostics::invalidLValueForRefParameter);
return nullptr;
}
void assignExpr(
IRGenContext* context,
const LoweredValInfo& inLeft,
Expr* rightExpr,
SourceLoc assignmentLoc)
{
auto left = tryGetAddress(context, inLeft, TryGetAddressMode::Default);
IRBuilderSourceLocRAII locRAII(context->irBuilder, assignmentLoc);
switch (left.flavor)
{
case LoweredValInfo::Flavor::Ptr:
{
lowerRValueExprWithDestination(context, left, rightExpr);
}
break;
default:
{
auto right = lowerRValueExpr(context, rightExpr);
assign(context, inLeft, right);
}
break;
}
}
void assign(IRGenContext* context, LoweredValInfo const& inLeft, LoweredValInfo const& inRight)
{
LoweredValInfo left = inLeft;
LoweredValInfo right = inRight;
// Before doing the case analysis on the shape of the `left` value,
// we might as well go ahead and see if we can coerce it into
// a simple pointer, since that would make our life a lot easier
// when handling complex cases.
//
left = tryGetAddress(context, left, TryGetAddressMode::Default);
auto builder = context->irBuilder;
// If there's a single element, just emit a regular store, otherwise
// proceed with a swizzle store
auto swizzledStore =
[builder](IRInst* dest, IRInst* source, UInt elementCount, uint32_t const* elementIndices)
{
if (elementCount == 1)
{
return builder->emitStore(builder->emitElementAddress(dest, elementIndices[0]), source);
}
return builder->emitSwizzledStore(dest, source, elementCount, elementIndices);
};
top:
switch (left.flavor)
{
case LoweredValInfo::Flavor::Ptr:
{
// The `left` value is just a pointer, so we can emit
// a store to it directly.
//
if (as<IRAtomicType>(tryGetPointedToType(builder, left.val->getDataType())))
{
builder->emitAtomicStore(
left.val,
getSimpleVal(context, right),
builder->getIntValue(builder->getIntType(), kIRMemoryOrder_Relaxed));
}
else
{
builder->emitStore(left.val, getSimpleVal(context, right));
}
}
break;
case LoweredValInfo::Flavor::SwizzledLValue:
{
// The `left` value is of the form `<base>.<swizzleElements>`.
// How we will handle this depends on what `base` looks like:
auto swizzleInfo = left.getSwizzledLValueInfo();
auto loweredBase = swizzleInfo->base;
// Note that the call to `tryGetAddress` at the start should
// ensure that `loweredBase` has been simplified as much as
// possible (e.g., if it is possible to turn it into a
// `LoweredValInfo::ptr()` then that will have been done).
switch (loweredBase.flavor)
{
default:
{
// Our fallback position is to lower via a temporary, e.g.:
//
// float4 tmp = <base>;
// tmp.xyz = float3(...);
// <base> = tmp;
//
// Load from the base value
IRInst* irLeftVal = getSimpleVal(context, loweredBase);
// Extract a simple value for the right-hand side
IRInst* irRightVal = getSimpleVal(context, right);
// Apply the swizzle
IRInst* irSwizzled = builder->emitSwizzleSet(
irLeftVal->getDataType(),
irLeftVal,
irRightVal,
(UInt)swizzleInfo->elementIndices.getCount(),
swizzleInfo->elementIndices.getArrayView().getBuffer());
// 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::Ptr:
{
// We are writing through a pointer, which might be
// pointing into a UAV or other memory resource, so
// we can't introduce use a temporary like the case
// above, because then we would read and write bytes
// that are not strictly required for the store.
//
// Note that the messy case of a "swizzle of a swizzle"
// was handled already in lowering of a `SwizzleExpr`,
// so that we don't need to deal with that case here.
//
// TODO: we may need to consider whether there is
// enough value in a masked store like this to keep
// it around, in comparison to a simpler model where
// we simply form a pointer to each of the vector
// elements and write to them individually.
IRInst* irRightVal = getSimpleVal(context, right);
// If there is a mismatch between the signedness of the left and rigth values
// then emit a cast
if (isSignedType(swizzleInfo->type) != isSignedType(irRightVal->getDataType()))
{
irRightVal = builder->emitCast(swizzleInfo->type, irRightVal);
}
swizzledStore(
loweredBase.val,
irRightVal,
(UInt)swizzleInfo->elementIndices.getCount(),
swizzleInfo->elementIndices.getArrayView().getBuffer());
}
break;
}
}
break;
case LoweredValInfo::Flavor::SwizzledMatrixLValue:
{
// The `left` value is of the form `<base>.<swizzleElements>`.
// How we will handle this depends on what `base` looks like:
auto swizzleInfo = left.getSwizzledMatrixLValueInfo();
auto loweredBase = swizzleInfo->base;
IRInst* irRightVal = getSimpleVal(context, right);
const UInt maxRowIndex = 4;
const UInt maxCols = 4; // swizzleInfo->elementCount;
// Sort the swizzle elements according to the row to which they
// write.
// Using row-major terminology
// The number of element writes in each row
UInt rowSizes[maxRowIndex] = {};
// The columns being written to in each row
uint32_t rowWrites[maxRowIndex][maxCols];
// The RHS element indices being written in each row
UInt rowIndices[maxRowIndex][maxCols];
for (UInt i = 0; i < swizzleInfo->elementCount; ++i)
{
const auto& c = swizzleInfo->elementCoords[i];
auto& rowSize = rowSizes[c.row];
rowWrites[c.row][rowSize] = (uint32_t)c.col;
rowIndices[c.row][rowSize] = i;
++rowSize;
}
const auto rElemType = composeGetters<IRType>(
irRightVal,
&IRInst::getDataType,
&IRVectorType::getElementType);
switch (loweredBase.flavor)
{
case LoweredValInfo::Flavor::Ptr:
{
// Matrix swizzle writes are implemented as several vector swizzle writes
for (UInt r = 0; r < maxRowIndex; ++r)
{
// Skip if we have nothing in this row
if (rowSizes[r] == 0)
{
continue;
}
const auto rowAddr = builder->emitElementAddress(loweredBase.val, r);
// Only select the RHS elements if it's a vector
const auto rSwizzled =
rElemType ? builder->emitSwizzle(
builder->getVectorType(rElemType, rowSizes[r]),
irRightVal,
rowSizes[r],
rowIndices[r])
: irRightVal;
swizzledStore(rowAddr, rSwizzled, rowSizes[r], rowWrites[r]);
}
}
break;
default:
{
// As above, our fallback position is to lower via a
// temporary, e.g.:
//
// float4x3 tmp = <base>;
// tmp[0].xzy = float3(...);
// tmp[1].yxz = float3(...);
// tmp[4].yzx = float3(...);
// <base> = tmp;
//
// Create a variable, and use the ptr writing matrix
// swizzle assignment above to fill it, then write that back
// to the l value. This approach generates the neatest IR
const auto beforeLValue = getSimpleVal(context, loweredBase);
const auto type = beforeLValue->getDataType();
// Store our initial lvalue in tmp
const auto tmpVar = builder->emitVar(type);
builder->emitStore(tmpVar, beforeLValue);
// Make a new swizzle write to write into this pointer
auto nextSwizzleInfo = left.getSwizzledMatrixLValueInfo();
SwizzledMatrixLValueInfo nextInfo = *nextSwizzleInfo;
nextInfo.base = LoweredValInfo::ptr(tmpVar);
// Perform that swizzling assignment
assign(context, LoweredValInfo::swizzledMatrixLValue(&nextInfo), right);
// Write (non-swizzled) into the l value
left = loweredBase;
right = LoweredValInfo::ptr(tmpVar);
goto top;
}
break;
}
}
break;
case LoweredValInfo::Flavor::BoundStorage:
{
// 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, if there
// is one, and then fall back to a `ref` accessor if
// there is no setter.
//
auto subscriptInfo = left.getBoundStorageInfo();
// Search for an appropriate "setter" declaration
auto setters = getMembersOfType<SetterDecl>(
context->astBuilder,
subscriptInfo->declRef,
MemberFilterStyle::Instance);
if (setters.isNonEmpty())
{
auto setter = *setters.begin();
auto allArgs = subscriptInfo->additionalArgs;
// Note: here we are assuming that all setters take
// the new-value parameter as an `in` rather than
// as any kind of reference.
//
// TODO: If we add support for something like `const&`
// for input parameters, we might have to deal with
// that here.
//
addInArg(context, &allArgs, right);
_emitCallToAccessor(
context,
builder->getVoidType(),
setter,
subscriptInfo->base,
allArgs);
return;
}
auto refAccessors = getMembersOfType<RefAccessorDecl>(
context->astBuilder,
subscriptInfo->declRef,
MemberFilterStyle::Instance);
if (refAccessors.isNonEmpty())
{
auto refAccessor = *refAccessors.begin();
// The `ref` accessor will return a pointer to the value, so
// we need to reflect that in the type of our `call` instruction.
IRType* ptrType = context->irBuilder->getPtrType(subscriptInfo->type);
LoweredValInfo refVal = _emitCallToAccessor(
context,
ptrType,
refAccessor,
subscriptInfo->base,
subscriptInfo->additionalArgs);
// The result from the call needs to be implicitly dereferenced,
// so that it can work as an l-value of the desired result type.
left = LoweredValInfo::ptr(getSimpleVal(context, refVal));
// Tail-recursively attempt assignment again on the new l-value.
goto top;
}
// No setter found? Then we have an error!
SLANG_UNEXPECTED("no setter found");
break;
}
break;
case LoweredValInfo::Flavor::BoundMember:
{
auto boundMemberInfo = left.getBoundMemberInfo();
// If we hit this case, then it means that we are trying to set
// a single field in someting that is not atomically set-able.
// (e.g., an element of a value where the `subscript` operation
// has `get` and `set` but not a `ref` accessor).
//
// We need to read the entire base value out, modify the field
// we care about, and then write it back.
auto declRef = boundMemberInfo->declRef;
if (auto fieldDeclRef = declRef.as<VarDecl>())
{
// materialize the base value and move it into
// a mutable temporary if needed
auto baseVal = boundMemberInfo->base;
auto tempVal = moveIntoMutableTemp(context, baseVal);
// extract the field l-value out of the temporary
auto tempFieldVal =
extractField(context, boundMemberInfo->type, tempVal, fieldDeclRef);
// assign to the field of the temporary l-value
assign(context, tempFieldVal, right);
// write back the modified temporary to the base l-value
assign(context, baseVal, tempVal);
return;
}
else
{
SLANG_UNEXPECTED("handled member flavor");
}
}
break;
case LoweredValInfo::Flavor::ExtractedExistential:
{
// The `left` value is the result of opening an existential.
//
auto leftInfo = left.getExtractedExistentialValInfo();
auto existentialVal = leftInfo->existentialVal;
// The actual desitnation we need to store into is the
// existential value itself.
//
left = existentialVal;
// The `right` value must be of the same concrete type as
// the opened value, but the new destination is of the
// original existential type, so we need to wrap it up
// appropriately.
//
right = LoweredValInfo::simple(builder->emitMakeExistential(
leftInfo->existentialType,
getSimpleVal(context, right),
leftInfo->witnessTable));
goto top;
}
break;
case LoweredValInfo::Flavor::ImplicitCastedLValue:
{
auto leftInfo = left.getImplicitCastedLValue();
left = leftInfo->base;
auto rightVal = getSimpleVal(context, right);
right = LoweredValInfo::simple(builder->emitCast(leftInfo->type, rightVal));
goto top;
}
break;
default:
SLANG_UNIMPLEMENTED_X("assignment");
break;
}
}
struct DeclLoweringVisitor : DeclVisitor<DeclLoweringVisitor, LoweredValInfo>
{
IRGenContext* context;
DiagnosticSink* getSink() { return context->getSink(); }
IRBuilder* getBuilder() { return context->irBuilder; }
LoweredValInfo visitDeclBase(DeclBase* /*decl*/)
{
SLANG_UNIMPLEMENTED_X("decl catch-all");
UNREACHABLE_RETURN(LoweredValInfo());
}
LoweredValInfo visitDecl(Decl* /*decl*/)
{
SLANG_UNIMPLEMENTED_X("decl catch-all");
UNREACHABLE_RETURN(LoweredValInfo());
}
LoweredValInfo visitExtensionDecl(ExtensionDecl* decl)
{
for (auto& member : decl->getDirectMemberDecls())
ensureDecl(context, member);
return LoweredValInfo();
}
#define IGNORED_CASE(NAME) \
LoweredValInfo visit##NAME(NAME*) { return LoweredValInfo(); }
IGNORED_CASE(ImportDecl)
IGNORED_CASE(IncludeDecl)
IGNORED_CASE(ImplementingDecl)
IGNORED_CASE(UsingDecl)
IGNORED_CASE(SyntaxDecl)
IGNORED_CASE(AttributeDecl)
IGNORED_CASE(NamespaceDecl)
IGNORED_CASE(ModuleDeclarationDecl)
IGNORED_CASE(FileDecl)
IGNORED_CASE(RequireCapabilityDecl)
#undef IGNORED_CASE
void getAllEntryPointsNoOverride(List<IRInst*>& entryPoints)
{
if (entryPoints.getCount() != 0)
return;
for (const auto d : context->irBuilder->getModule()->getModuleInst()->getGlobalInsts())
if (d->findDecoration<IREntryPointDecoration>())
entryPoints.add(d);
}
LoweredValInfo visitEmptyDecl(EmptyDecl* decl)
{
bool verifyComputeDerivativeGroupModifier = false;
List<IRInst*> entryPoints{};
for (const auto modifier : decl->modifiers)
{
if (const auto layoutLocalSizeAttr = as<GLSLLayoutLocalSizeAttribute>(modifier))
{
verifyComputeDerivativeGroupModifier = true;
getAllEntryPointsNoOverride(entryPoints);
LoweredValInfo extents[3];
for (int i = 0; i < 3; ++i)
{
extents[i] = layoutLocalSizeAttr->specConstExtents[i]
? emitDeclRef(
context,
layoutLocalSizeAttr->specConstExtents[i],
lowerType(
context,
getType(
context->astBuilder,
layoutLocalSizeAttr->specConstExtents[i])))
: lowerVal(context, layoutLocalSizeAttr->extents[i]);
}
for (auto d : entryPoints)
as<IRNumThreadsDecoration>(getBuilder()->addNumThreadsDecoration(
d,
getSimpleVal(context, extents[0]),
getSimpleVal(context, extents[1]),
getSimpleVal(context, extents[2])));
}
else if (as<GLSLLayoutDerivativeGroupQuadAttribute>(modifier))
{
verifyComputeDerivativeGroupModifier = true;
getAllEntryPointsNoOverride(entryPoints);
for (auto d : entryPoints)
getBuilder()->addSimpleDecoration<IRDerivativeGroupQuadDecoration>(d);
}
else if (as<GLSLLayoutDerivativeGroupLinearAttribute>(modifier))
{
verifyComputeDerivativeGroupModifier = true;
getAllEntryPointsNoOverride(entryPoints);
for (auto d : entryPoints)
getBuilder()->addSimpleDecoration<IRDerivativeGroupLinearDecoration>(d);
}
}
if (!verifyComputeDerivativeGroupModifier)
return LoweredValInfo();
for (auto d : entryPoints)
{
verifyComputeDerivativeGroupModifiers(
getSink(),
decl->loc,
d->findDecoration<IRDerivativeGroupQuadDecoration>(),
d->findDecoration<IRDerivativeGroupLinearDecoration>(),
d->findDecoration<IRNumThreadsDecoration>());
}
return LoweredValInfo();
}
void ensureInsertAtGlobalScope(IRBuilder* builder)
{
auto inst = builder->getInsertLoc().getInst();
if (inst->getOp() == kIROp_ModuleInst)
return;
while (inst && inst->getParent() && inst->getParent()->getOp() != kIROp_ModuleInst)
{
inst = inst->getParent();
}
if (inst)
{
builder->setInsertBefore(inst);
}
}
LoweredValInfo visitTypeDefDecl(TypeDefDecl* decl)
{
// A type alias declaration may be generic, if it is
// nested under a generic type/function/etc.
//
NestedContext nested(this);
auto subBuilder = nested.getBuilder();
auto subContext = nested.getContext();
ensureInsertAtGlobalScope(nested.getBuilder());
IRGeneric* outerGeneric = emitOuterGenerics(subContext, decl, decl);
// TODO: if a type alias declaration can have linkage,
// we will need to lower it to some kind of global
// value in the IR so that we can attach a name to it.
//
// For now, we can only attach a name *if* the type
// alias is somehow generic.
if (outerGeneric)
{
addLinkageDecoration(context, outerGeneric, decl);
}
auto type = lowerType(subContext, decl->type.type);
return LoweredValInfo::simple(finishOuterGenerics(subBuilder, type, outerGeneric));
}
LoweredValInfo visitGenericTypeParamDecl(GenericTypeParamDecl* /*decl*/)
{
return LoweredValInfo();
}
LoweredValInfo visitGenericTypeConstraintDecl(GenericTypeConstraintDecl* decl)
{
// This might be a type constraint on an associated type,
// in which case it should lower as the key for that
// interface requirement.
if (auto assocTypeDecl = as<AssocTypeDecl>(decl->parentDecl))
{
// TODO: might need extra steps if we ever allow
// generic associated types.
if (const auto interfaceDecl = as<InterfaceDecl>(assocTypeDecl->parentDecl))
{
// Okay, this seems to be an interface rquirement, and
// we should lower it as such.
return LoweredValInfo::simple(getInterfaceRequirementKey(decl));
}
}
if (const auto globalGenericParamDecl = as<GlobalGenericParamDecl>(decl->parentDecl))
{
// This is a constraint on a global generic type parameters,
// and so it should lower as a parameter of its own.
auto supType = lowerType(context, decl->getSup().type);
auto inst = getBuilder()->emitGlobalGenericWitnessTableParam(supType);
addLinkageDecoration(context, inst, decl);
return LoweredValInfo::simple(inst);
}
// Otherwise we really don't expect to see a type constraint
// declaration like this during lowering, because a generic
// should have set up a parameter for any constraints as
// part of being lowered.
SLANG_UNEXPECTED("generic type constraint during lowering");
UNREACHABLE_RETURN(LoweredValInfo());
}
LoweredValInfo visitGlobalGenericParamDecl(GlobalGenericParamDecl* decl)
{
auto inst = getBuilder()->emitGlobalGenericTypeParam();
addLinkageDecoration(context, inst, decl);
return LoweredValInfo::simple(inst);
}
LoweredValInfo visitGlobalGenericValueParamDecl(GlobalGenericValueParamDecl* decl)
{
auto builder = getBuilder();
auto type = lowerType(context, decl->type);
auto inst = builder->emitGlobalGenericParam(type);
addLinkageDecoration(context, inst, decl);
return LoweredValInfo::simple(inst);
}
bool isExportedType(Type* type)
{
if (auto declRefType = as<DeclRefType>(type))
{
if (declRefType->getDeclRef().getDecl()->findModifier<HLSLExportModifier>())
return true;
}
return false;
}
void lowerWitnessTable(
IRGenContext* subContext,
WitnessTable* astWitnessTable,
IRWitnessTable* irWitnessTable,
Dictionary<WitnessTable*, IRWitnessTable*>& mapASTToIRWitnessTable)
{
auto subBuilder = subContext->irBuilder;
for (auto entry : astWitnessTable->getRequirementDictionary())
{
auto requiredMemberDecl = entry.key;
auto satisfyingWitness = entry.value;
auto irRequirementKey = getInterfaceRequirementKey(requiredMemberDecl);
if (!irRequirementKey)
continue;
IRInst* irSatisfyingVal = nullptr;
switch (satisfyingWitness.getFlavor())
{
case RequirementWitness::Flavor::declRef:
{
auto satisfyingDeclRef = satisfyingWitness.getDeclRef();
irSatisfyingVal = getSimpleVal(
subContext,
emitDeclRef(
subContext,
satisfyingDeclRef,
// TODO: we need to know what type to plug in here...
nullptr));
}
break;
case RequirementWitness::Flavor::val:
{
auto satisfyingVal = satisfyingWitness.getVal();
irSatisfyingVal = lowerSimpleVal(subContext, satisfyingVal);
}
break;
case RequirementWitness::Flavor::witnessTable:
{
auto astReqWitnessTable = satisfyingWitness.getWitnessTable();
IRWitnessTable* irSatisfyingWitnessTable = nullptr;
if (!mapASTToIRWitnessTable.tryGetValue(
astReqWitnessTable,
irSatisfyingWitnessTable))
{
// Need to construct a sub-witness-table
auto irWitnessTableBaseType =
lowerType(subContext, astReqWitnessTable->baseType);
auto concreteType = irWitnessTable->getConcreteType();
irSatisfyingWitnessTable =
subBuilder->createWitnessTable(irWitnessTableBaseType, concreteType);
// Avoid adding same decorations and child more than once.
if (!irSatisfyingWitnessTable->hasDecorationOrChild())
{
auto mangledName = getMangledNameForConformanceWitness(
subContext->astBuilder,
astReqWitnessTable->witnessedType,
astReqWitnessTable->baseType,
concreteType->getOp());
subBuilder->addExportDecoration(
irSatisfyingWitnessTable,
mangledName.getUnownedSlice());
if (isExportedType(astReqWitnessTable->witnessedType))
{
subBuilder->addHLSLExportDecoration(irSatisfyingWitnessTable);
subBuilder->addKeepAliveDecoration(irSatisfyingWitnessTable);
}
// Recursively lower the sub-table.
lowerWitnessTable(
subContext,
astReqWitnessTable,
irSatisfyingWitnessTable,
mapASTToIRWitnessTable);
irSatisfyingWitnessTable->moveToEnd();
}
}
irSatisfyingVal = irSatisfyingWitnessTable;
}
break;
default:
SLANG_UNEXPECTED("handled requirement witness case");
break;
}
subBuilder->createWitnessTableEntry(irWitnessTable, irRequirementKey, irSatisfyingVal);
}
}
LoweredValInfo visitInheritanceDecl(InheritanceDecl* inheritanceDecl)
{
// An inheritance clause inside of an `interface`
// declaration should not give rise to a witness
// table, because it represents something the
// interface requires, and not what it provides.
//
auto parentDecl = inheritanceDecl->parentDecl;
if (const auto parentInterfaceDecl = as<InterfaceDecl>(parentDecl))
{
return LoweredValInfo::simple(getInterfaceRequirementKey(inheritanceDecl));
}
//
// We also need to cover the case where an `extension`
// declaration is being used to add a conformance to
// an existing `interface`:
//
if (auto parentExtensionDecl = as<ExtensionDecl>(parentDecl))
{
auto targetType = parentExtensionDecl->targetType;
if (auto targetDeclRefType = as<DeclRefType>(targetType))
{
if (auto targetInterfaceDeclRef =
targetDeclRefType->getDeclRef().as<InterfaceDecl>())
{
return LoweredValInfo::simple(getInterfaceRequirementKey(inheritanceDecl));
}
}
}
// Find the type that is doing the inheriting.
// Under normal circumstances it is the type declaration that
// is the parent for the inheritance declaration, but if
// the inheritance declaration is on an `extension` declaration,
// then we need to identify the type being extended.
//
Type* subType = nullptr;
if (auto extParentDecl = as<ExtensionDecl>(parentDecl))
{
subType = extParentDecl->targetType.type;
}
else
{
subType = DeclRefType::create(context->astBuilder, makeDeclRef(parentDecl));
}
bool isGenericExtension = false;
// Test if we are in a generic extension context
if (parentDecl->parentDecl)
{
auto genDecl = as<GenericDecl>(parentDecl->parentDecl);
if (genDecl)
{
isGenericExtension = true;
}
}
// What is the super-type that we have declared we inherit from?
Type* superType = inheritanceDecl->base.type;
if (auto superDeclRefType = as<DeclRefType>(superType))
{
if (superDeclRefType->getDeclRef().as<StructDecl>() ||
superDeclRefType->getDeclRef().as<ClassDecl>())
{
// TODO: the witness that a type inherits from a `struct`
// type should probably be a key that will be used for
// a field that holds the base type...
//
auto irKey = getBuilder()->createStructKey();
addLinkageDecoration(context, irKey, inheritanceDecl);
getBuilder()->addNameHintDecoration(irKey, UnownedTerminatedStringSlice("base"));
auto keyVal = LoweredValInfo::simple(irKey);
context->setGlobalValue(inheritanceDecl, keyVal);
return keyVal;
}
}
// A witness table may need to be generic, if the outer
// declaration (either a type declaration or an `extension`)
// is generic.
//
NestedContext nested(this);
auto subBuilder = nested.getBuilder();
auto subContext = nested.getContext();
auto outerGeneric = emitOuterGenerics(subContext, inheritanceDecl, inheritanceDecl);
// Lower the super-type to force its declaration to be lowered.
//
// Note: we are using the "sub-context" here because the
// type being inherited from could reference generic parameters,
// and we need those parameters to lower as references to
// the parameters of our IR-level generic.
//
auto irWitnessTableBaseType = lowerType(subContext, superType);
// Register a dummy value to avoid infinite recursions.
// Without this, the call to lowerType() can get into an infinite recursion.
//
context->setGlobalValue(
inheritanceDecl,
LoweredValInfo::simple(findOuterMostGeneric(subBuilder->getInsertLoc().getParent())));
auto irSubType = lowerType(subContext, subType);
// Create the IR-level witness table
auto irWitnessTable = subBuilder->createWitnessTable(irWitnessTableBaseType, irSubType);
// Override with the correct witness-table
context->setGlobalValue(
inheritanceDecl,
LoweredValInfo::simple(findOuterMostGeneric(irWitnessTable)));
// Avoid adding same decorations and child more than once.
if (!irWitnessTable->hasDecorationOrChild())
{
// 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;
if (isGenericExtension)
{
mangledName =
getMangledNameForConformanceWitness(context->astBuilder, parentDecl, superType);
}
else
{
mangledName =
getMangledNameForConformanceWitness(context->astBuilder, subType, superType);
}
// TODO(JS):
// Should the mangled name take part in obfuscation if enabled?
addLinkageDecoration(
context,
irWitnessTable,
inheritanceDecl,
mangledName.getUnownedSlice());
// If the witness table is for a COM interface, always keep it alive.
if (irWitnessTableBaseType->findDecoration<IRComInterfaceDecoration>())
{
subBuilder->addHLSLExportDecoration(irWitnessTable);
}
for (auto mod : parentDecl->modifiers)
{
if (as<HLSLExportModifier>(mod))
{
subBuilder->addHLSLExportDecoration(irWitnessTable);
subBuilder->addKeepAliveDecoration(irWitnessTable);
}
else if (as<AutoDiffBuiltinAttribute>(mod))
{
subBuilder->addAutoDiffBuiltinDecoration(irWitnessTable);
}
}
// Make sure that all the entries in the witness table have been filled in,
// including any cases where there are sub-witness-tables for conformances
bool isExplicitExtern = false;
bool isImported = isImportedDecl(context, parentDecl, isExplicitExtern);
if (!isImported || isExplicitExtern)
{
Dictionary<WitnessTable*, IRWitnessTable*> mapASTToIRWitnessTable;
lowerWitnessTable(
subContext,
inheritanceDecl->witnessTable,
irWitnessTable,
mapASTToIRWitnessTable);
}
irWitnessTable->moveToEnd();
}
return LoweredValInfo::simple(
finishOuterGenerics(subBuilder, irWitnessTable, outerGeneric));
}
LoweredValInfo visitDeclGroup(DeclGroup* declGroup)
{
// To lower a group of declarations, we just
// lower each one individually.
//
for (auto decl : declGroup->decls)
{
IRBuilderSourceLocRAII sourceLocInfo(context->irBuilder, decl->loc);
// 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 visitStorageDeclCommon(ContainerDecl* 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();
}
LoweredValInfo visitSubscriptDecl(SubscriptDecl* decl) { return visitStorageDeclCommon(decl); }
LoweredValInfo visitPropertyDecl(PropertyDecl* decl) { return visitStorageDeclCommon(decl); }
bool isGlobalVarDecl(VarDecl* decl)
{
auto parent = decl->parentDecl;
if (as<NamespaceDeclBase>(parent))
{
// Variable declared at global/namespace scope? -> Global.
return true;
}
else if (as<FileDecl>(parent))
{
// Variable declared at file scope? -> Global.
return true;
}
else if (as<AggTypeDeclBase>(parent))
{
if (decl->hasModifier<HLSLStaticModifier>())
{
// A `static` member variable is effectively global.
return true;
}
}
return false;
}
bool isMemberVarDecl(VarDecl* decl)
{
auto parent = decl->parentDecl;
if (as<AggTypeDecl>(parent))
{
// A variable declared inside of an aggregate type declaration is a member.
return true;
}
if (auto extDecl = as<ExtensionDecl>(parent))
{
if (const auto declRefType = as<DeclRefType>(extDecl->targetType.type))
{
return true;
}
}
return false;
}
struct NestedContext
{
IRGenEnv subEnvStorage;
IRBuilder subBuilderStorage;
IRGenContext subContextStorage;
NestedContext(DeclLoweringVisitor* outer)
: subBuilderStorage(*outer->getBuilder()), subContextStorage(*outer->context)
{
auto outerContext = outer->context;
subEnvStorage.outer = outerContext->env;
subContextStorage.irBuilder = &subBuilderStorage;
subContextStorage.env = &subEnvStorage;
subContextStorage.thisType = outerContext->thisType;
subContextStorage.thisTypeWitness = outerContext->thisTypeWitness;
subContextStorage.returnDestination = LoweredValInfo();
subContextStorage.lowerTypeCallback = nullptr;
subContextStorage.catchHandler = nullptr;
}
IRBuilder* getBuilder() { return &subBuilderStorage; }
IRGenContext* getContext() { return &subContextStorage; }
};
LoweredValInfo lowerGlobalShaderParam(VarDecl* decl)
{
IRType* paramType = lowerType(context, decl->getType());
auto builder = getBuilder();
auto irParam = builder->createGlobalParam(paramType);
auto paramVal = LoweredValInfo::simple(irParam);
addLinkageDecoration(context, irParam, decl);
addNameHint(context, irParam, decl);
maybeSetRate(context, irParam, decl);
addVarDecorations(context, irParam, decl);
maybeAddDebugLocationDecoration(context, irParam);
if (decl)
{
builder->addHighLevelDeclDecoration(irParam, decl);
}
addTargetIntrinsicDecorations(nullptr, irParam, decl);
bool hasLayoutSemantic = false;
bool isSpecializationConstant = false;
for (auto modifier : decl->modifiers)
{
if (as<HLSLLayoutSemantic>(modifier))
{
hasLayoutSemantic = true;
}
else if (
as<SpecializationConstantAttribute>(modifier) ||
as<VkConstantIdAttribute>(modifier))
{
isSpecializationConstant = true;
}
}
if (hasLayoutSemantic)
builder->addHasExplicitHLSLBindingDecoration(irParam);
// A global variable's SSA value is a *pointer* to
// the underlying storage.
context->setGlobalValue(decl, paramVal);
if (isSpecializationConstant && decl->initExpr)
{
auto initVal = getSimpleVal(context, lowerRValueExpr(context, decl->initExpr));
builder->addDefaultValueDecoration(irParam, initVal);
}
irParam->moveToEnd();
return paramVal;
}
LoweredValInfo lowerConstantDeclCommon(VarDeclBase* decl)
{
// It's constant, so shoul dhave this modifier
SLANG_ASSERT(decl->hasModifier<ConstModifier>());
NestedContext nested(this);
auto subBuilder = nested.getBuilder();
auto subContext = nested.getContext();
IRGeneric* outerGeneric = nullptr;
bool needLinkage = true;
// If we are static, then we need to insert the declaration before the parent.
// This tries to match the behavior of previous `lowerFunctionStaticConstVarDecl`
// functionality
if (isFunctionStaticVarDecl(decl))
{
// We need to insert the constant at a level above
// the function being emitted. This will usually
// be the global scope, but it might be an outer
// generic if we are lowering a generic function.
subBuilder->setInsertBefore(subBuilder->getFunc());
// static values inside a function does not need a linkage.
// trying to insert a linkage decoration to a static constant defined
// inside a generic function can lead to errorneous IR.
needLinkage = false;
}
else if (!isFunctionVarDecl(decl))
{
outerGeneric = emitOuterGenerics(subContext, decl, decl);
}
auto initExpr = decl->initExpr;
// We want to be able to support cases where a global constant is defined in
// another module and we should not bind to its value at (front-end) compile
// time. We handle this by adding a level of indirection where a global constant
// is represented as an IR node with zero or one operands. In the zero-operand
// case the node represents a global constant with an unknown value (perhaps
// an imported constant), while in the one-operand case the operand gives us
// the concrete value to use for the constant.
//
// Using a level of indirection also gives us a well-defined place to attach
// annotation information like name hints, since otherwise two constants
// with the same value would map to identical IR nodes.
//
// TODO: For now we detect whether or not to include the value operand based on
// whether we see an initial-value expression in the AST declaration, but
// eventually we might base this on whether or not the value should be accessible
// to the module we are lowering.
IRInst* irConstant = nullptr;
if (!initExpr)
{
// If we don't know the value we want to use, then we just create
// a global constant IR node with the right type.
//
auto irType = lowerType(subContext, decl->getType());
irConstant = subBuilder->emitGlobalConstant(irType);
}
else
{
// We lower the value expression directly, which yields a
// global instruction to represent the value. There is
// no guarantee that this instruction is unique (e.g.,
// if we have two different constants definitions both
// with the value `5`, then we might have only a single
// instruction to represent `5`.
//
auto irInitVal = getSimpleVal(subContext, lowerRValueExpr(subContext, initExpr));
// We construct a distinct IR instruction to represent the
// constant itself, with the value as an operand.
//
irConstant = subBuilder->emitGlobalConstant(irInitVal->getFullType(), irInitVal);
}
// All of the attributes/decorations we can attach
// belong on the IR constant node.
//
if (needLinkage)
addLinkageDecoration(context, irConstant, decl);
addNameHint(context, irConstant, decl);
addVarDecorations(context, irConstant, decl);
getBuilder()->addHighLevelDeclDecoration(irConstant, decl);
// Finish of generic
auto loweredValue =
LoweredValInfo::simple(finishOuterGenerics(subBuilder, irConstant, outerGeneric));
// Register the value that was emitted as the value
// for any references to the constant from elsewhere
// in the code.
//
context->setGlobalValue(decl, loweredValue);
return loweredValue;
}
LoweredValInfo lowerGlobalConstantDecl(VarDecl* decl) { return lowerConstantDeclCommon(decl); }
LoweredValInfo lowerGlobalVarDecl(VarDecl* decl)
{
// A non-`static` global is actually a shader parameter in HLSL.
//
// TODO: We should probably make that case distinct at the AST
// level as well, since global shader parameters are fairly
// different from global variables.
//
if (isGlobalShaderParameter(decl))
{
return lowerGlobalShaderParam(decl);
}
// A `static const` global is actually a compile-time constant.
//
if (decl->hasModifier<HLSLStaticModifier>() && decl->hasModifier<ConstModifier>())
{
return lowerGlobalConstantDecl(decl);
}
NestedContext nested(this);
auto subBuilder = nested.getBuilder();
auto subContext = nested.getContext();
IRGeneric* outerGeneric = nullptr;
// If we are static, then we need to insert the declaration before the parent.
// This tries to match the behavior of previous `lowerFunctionStaticConstVarDecl`
// functionality
if (isFunctionStaticVarDecl(decl))
{
// We need to insert the constant at a level above
// the function being emitted. This will usually
// be the global scope, but it might be an outer
// generic if we are lowering a generic function.
subBuilder->setInsertBefore(subBuilder->getFunc());
}
else if (!isFunctionVarDecl(decl))
{
outerGeneric = emitOuterGenerics(subContext, decl, decl);
}
IRType* varType = lowerType(subContext, decl->getType());
// TODO(JS): Do we create something derived from IRGlobalVar? Or do we use
// a decoration to identify an *actual* global?
IRGlobalValueWithCode* irGlobal = subBuilder->createGlobalVar(varType);
addLinkageDecoration(subContext, irGlobal, decl);
addNameHint(subContext, irGlobal, decl);
maybeSetRate(subContext, irGlobal, decl);
addVarDecorations(subContext, irGlobal, decl);
maybeAddDebugLocationDecoration(subContext, irGlobal);
if (decl)
{
subBuilder->addHighLevelDeclDecoration(irGlobal, decl);
}
if (auto initExpr = decl->initExpr)
{
subBuilder->setInsertInto(irGlobal);
IRBlock* entryBlock = subBuilder->emitBlock();
subBuilder->setInsertInto(entryBlock);
LoweredValInfo initVal = lowerLValueExpr(subContext, initExpr);
subContext->irBuilder->emitReturn(getSimpleVal(subContext, initVal));
}
// A global variable's SSA value is a *pointer* to
// the underlying storage.
auto loweredValue =
LoweredValInfo::ptr(finishOuterGenerics(subBuilder, irGlobal, outerGeneric));
context->setGlobalValue(decl, loweredValue);
return loweredValue;
}
LoweredValInfo lowerFunctionStaticConstVarDecl(VarDeclBase* decl)
{
return lowerConstantDeclCommon(decl);
}
LoweredValInfo lowerFunctionStaticVarDecl(VarDeclBase* decl)
{
// We know the variable is `static`, but it might also be `const.
if (decl->hasModifier<ConstModifier>())
return lowerFunctionStaticConstVarDecl(decl);
// A function-scope `static` variable is effectively a global,
// and a simple solution here would be to try to emit this
// variable directly into the global scope.
//
// The one major wrinkle we need to deal with is the way that
// a function-scope `static` variable could be nested under
// a generic, leading to the situation that different instances
// of that same generic would need distinct storage for that
// variable declaration.
//
// We will handle that constraint by carefully nesting the
// IR global variable under the parent of its containing
// function.
//
auto parent = getBuilder()->getInsertLoc().getParent();
if (auto block = as<IRBlock>(parent))
parent = block->getParent();
NestedContext nestedContext(this);
auto subBuilder = nestedContext.getBuilder();
auto subContext = nestedContext.getContext();
subBuilder->setInsertBefore(parent);
IRType* subVarType = lowerType(subContext, decl->getType());
IRGlobalValueWithCode* irGlobal = subBuilder->createGlobalVar(subVarType);
addVarDecorations(subContext, irGlobal, decl);
addNameHint(context, irGlobal, decl);
maybeSetRate(context, irGlobal, decl);
subBuilder->addHighLevelDeclDecoration(irGlobal, decl);
LoweredValInfo globalVal = LoweredValInfo::ptr(irGlobal);
context->setValue(decl, globalVal);
// A `static` variable with an initializer needs special handling,
// at least if the initializer isn't a compile-time constant.
if (auto initExpr = decl->initExpr)
{
// We must create another global `bool isInitialized = false`
// to represent whether we've initialized this before.
// Then emit code like:
//
// if(!isInitialized) { <globalVal> = <initExpr>; isInitialized = true; }
//
// This will generate a lot of boilterplate code, but we optimize out the
// boilerplate functions later during `moveGlobalVarInitializationToEntryPoints`
// if we see the init function is just returning a global constant.
//
auto boolBuilder = subBuilder;
auto irBoolType = boolBuilder->getBoolType();
auto irBool = boolBuilder->createGlobalVar(irBoolType);
boolBuilder->setInsertInto(irBool);
boolBuilder->emitBlock();
boolBuilder->emitReturn(boolBuilder->getBoolValue(false));
auto boolVal = LoweredValInfo::ptr(irBool);
// Okay, with our global Boolean created, we can move on to
// generating the code we actually care about, back in the original function.
auto builder = getBuilder();
auto initBlock = builder->createBlock();
auto afterBlock = builder->createBlock();
builder->emitIfElse(getSimpleVal(context, boolVal), afterBlock, initBlock, afterBlock);
builder->insertBlock(initBlock);
LoweredValInfo initVal = lowerLValueExpr(context, initExpr);
assign(context, globalVal, initVal);
assign(context, boolVal, LoweredValInfo::simple(builder->getBoolValue(true)));
builder->emitBranch(afterBlock);
builder->insertBlock(afterBlock);
}
return globalVal;
}
LoweredValInfo visitGenericValueParamDecl(GenericValueParamDecl* decl)
{
return emitDeclRef(context, makeDeclRef(decl), lowerType(context, decl->type));
}
LoweredValInfo visitVarDecl(VarDecl* decl)
{
// Detect global (or effectively global) variables
// and handle them differently.
if (isGlobalVarDecl(decl))
{
return lowerGlobalVarDecl(decl);
}
if (isFunctionStaticVarDecl(decl))
{
return lowerFunctionStaticVarDecl(decl);
}
if (isMemberVarDecl(decl))
{
return lowerMemberVarDecl(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.
IRType* varType = lowerType(context, decl->getType());
// As a special case, an immutable local variable with an
// initializer can just lower to the SSA value of its initializer.
//
if (as<LetDecl>(decl))
{
if (auto initExpr = decl->initExpr)
{
auto initVal = lowerRValueExpr(context, initExpr);
initVal = LoweredValInfo::simple(getSimpleVal(context, initVal));
// For debug builds, still create debug information for let variables
// even though we're not creating an actual variable
if (context->includeDebugInfo && decl->loc.isValid() &&
context->shared->debugValueContext.isDebuggableType(initVal.val->getDataType()))
{
// Create a debug variable for this let declaration
auto builder = context->irBuilder;
auto humaneLoc = context->getLinkage()->getSourceManager()->getHumaneLoc(
decl->loc,
SourceLocType::Emit);
// Find the debug source for this file
auto sourceView =
context->getLinkage()->getSourceManager()->findSourceView(decl->loc);
if (sourceView)
{
auto source = sourceView->getSourceFile();
IRInst* debugSourceInst = nullptr;
if (context->shared->mapSourceFileToDebugSourceInst.tryGetValue(
source,
debugSourceInst))
{
auto debugVar = builder->emitDebugVar(
varType,
debugSourceInst,
builder->getIntValue(builder->getUIntType(), humaneLoc.line),
builder->getIntValue(builder->getUIntType(), humaneLoc.column),
nullptr);
// Copy name hint from the declaration
addNameHint(context, debugVar, decl);
// Emit debug value to associate the constant with the debug variable
builder->emitDebugValue(debugVar, initVal.val);
}
}
}
context->setGlobalValue(decl, initVal);
return initVal;
}
}
LoweredValInfo varVal = createVar(context, varType, decl);
maybeAddDebugLocationDecoration(context, varVal.val);
if (auto initExpr = decl->initExpr)
{
assignExpr(context, varVal, initExpr, decl->loc);
}
context->setGlobalValue(decl, varVal);
return varVal;
}
IRStructKey* getInterfaceRequirementKey(Decl* requirementDecl)
{
return Slang::getInterfaceRequirementKey(context, requirementDecl);
}
LoweredValInfo visitAssocTypeDecl(AssocTypeDecl* decl)
{
SLANG_ASSERT(decl->parentDecl != nullptr);
ShortList<IRInterfaceType*> constraintInterfaces;
for (auto constraintDecl : decl->getMembersOfType<GenericTypeConstraintDecl>())
{
auto baseType = lowerType(context, constraintDecl->sup.type);
if (baseType && baseType->getOp() == kIROp_InterfaceType)
constraintInterfaces.add((IRInterfaceType*)baseType);
}
auto assocType =
context->irBuilder->getAssociatedType(constraintInterfaces.getArrayView().arrayView);
context->setValue(decl, assocType);
return LoweredValInfo::simple(assocType);
}
void insertRequirementKeyAssociation(
Decl* requirementDecl,
IRInst* originalKey,
IRInst* associatedKey)
{
IROp op = kIROp_Nop;
if (as<BackwardDerivativeRequirementDecl>(requirementDecl))
{
op = kIROp_BackwardDerivativeDecoration;
}
else if (as<ForwardDerivativeRequirementDecl>(requirementDecl))
{
op = kIROp_ForwardDerivativeDecoration;
}
else
{
return;
}
context->irBuilder->addDecoration(originalKey, op, associatedKey);
}
// Given `value` defined as an independent generic of `outerGeneric`, emit IR that specializes
// it using the generic params defined in `outerGeneric`. For example:
// ```
// interface IFoo<T> { void f(); }
// ```
// We will lower `IFoo<T>::f` into `%f = IRGeneric(T) { return IRFunc(...) }`
// When we lower the interface type `IFoo`, it will become:
// ```
// %IFoo = IRGeneric(T1) { return IRInterfaceType(???); )
// ```
// We want the `???` to be `specialize(%f, T1)`.
// To do so, we will call `specializeWithOuterGeneric` with `value` = `%f`, and `outerGeneric` =
// %IFoo.
//
IRInst* specializeWithOuterGeneric(IRBuilder* irBuilder, IRInst* value, IRGeneric* outerGeneric)
{
if (!as<IRGeneric>(value))
return value;
if (!outerGeneric)
return value;
// If `outerGeneric` has a generic parent, we want to recursively specialize value
// using the parent generic first.
auto parentGeneric = getOuterGeneric(outerGeneric);
if (parentGeneric)
value = specializeWithOuterGeneric(irBuilder, value, parentGeneric);
// Now we can specialize `value` using the params defined in `outerGeneric`.
List<IRInst*> args;
for (auto param : outerGeneric->getParams())
args.add(param);
return irBuilder->emitSpecializeInst(irBuilder->getGenericKind(), value, args);
}
LoweredValInfo visitInterfaceDecl(InterfaceDecl* decl)
{
// The members of an interface will turn into the keys that will
// be used for lookup operations into witness
// tables that promise conformance to the interface.
//
// TODO: we don't handle the case here of an interface
// with concrete/default implementations for any
// of its members.
//
// TODO: If we want to support using an interface as
// an existential type, then we might need to emit
// a witness table for the interface type's conformance
// to its own interface.
//
NestedContext nestedContext(this);
auto subBuilder = nestedContext.getBuilder();
auto subContext = nestedContext.getContext();
// Emit any generics that should wrap the actual type.
auto outerGeneric = emitOuterGenerics(subContext, decl, decl);
// First, compute the number of requirement entries that will be included in this
// interface type.
UInt operandCount = 0;
for (auto requirementDecl : decl->getDirectMemberDecls())
{
auto innerRequirementDecl = requirementDecl;
if (as<InterfaceDefaultImplDecl>(requirementDecl))
continue;
if (as<GenericDecl>(requirementDecl))
innerRequirementDecl = getInner(requirementDecl);
if (as<SubscriptDecl>(innerRequirementDecl) || as<PropertyDecl>(innerRequirementDecl))
{
for (auto accessorDecl : as<ContainerDecl>(innerRequirementDecl)
->getDirectMemberDeclsOfType<AccessorDecl>())
{
SLANG_UNUSED(accessorDecl);
operandCount++;
}
}
if (!shouldDeclBeTreatedAsInterfaceRequirement(requirementDecl))
continue;
operandCount++;
// As a special case, any type constraints placed
// on an associated type will *also* need to be turned
// into requirement keys for this interface.
if (auto associatedTypeDecl = as<AssocTypeDecl>(innerRequirementDecl))
{
operandCount +=
associatedTypeDecl->getMembersOfType<TypeConstraintDecl>().getCount();
}
}
// Allocate an IRInterfaceType with the `operandCount` operands.
IRInterfaceType* irInterface = subBuilder->createInterfaceType(operandCount, nullptr);
auto finalVal = finishOuterGenerics(subBuilder, irInterface, outerGeneric);
// Add `irInterface` to decl mapping now to prevent cyclic lowering.
context->setGlobalValue(decl, LoweredValInfo::simple(finalVal));
subBuilder->setInsertBefore(irInterface);
// Setup subContext for proper lowering `ThisType`, associated types and
// the interface decl's self reference.
auto thisType = DeclRefType::create(
context->astBuilder,
createDefaultSpecializedDeclRef(subContext, nullptr, decl->getThisTypeDecl()));
subContext->thisType = thisType;
// Create a stand-in witness that represents `ThisType` conforms to the interface.
subContext->thisTypeWitness = subBuilder->createThisTypeWitness((IRType*)finalVal);
// Lower associated types first, so they can be referred to when lowering functions.
for (auto assocTypeDecl : decl->getMembersOfType<AssocTypeDecl>())
{
ensureDecl(subContext, assocTypeDecl);
}
UInt entryIndex = 0;
auto addEntry = [&](IRStructKey* requirementKey, DeclRef<Decl> requirementDeclRef)
{
auto entry = subBuilder->createInterfaceRequirementEntry(requirementKey, nullptr);
if (auto inheritance = requirementDeclRef.as<InheritanceDecl>())
{
auto irBaseType =
lowerType(subContext, getSup(subContext->astBuilder, inheritance));
auto irWitnessTableType = subBuilder->getWitnessTableType(irBaseType);
entry->setRequirementVal(irWitnessTableType);
}
else
{
auto requirementVal = ensureDecl(subContext, requirementDeclRef.getDecl()).val;
switch (requirementVal->getOp())
{
default:
// Remove linkage decorations from the requirement value to prevent
// duplicate mangled names and allow DCE to clean up unused functions.
// Interface requirements only need the type information, not the linkage.
removeLinkageDecorations(requirementVal);
// For the majority of requirements, we only care about its type in an
// interface definition, so we store only the type from the lowered IR
// in the interface entry.
// We need to make sure the type is specialized with the outer generic
// parameters in case the interface itself is inside a generic.
//
requirementVal = specializeWithOuterGeneric(
context->irBuilder,
requirementVal->getFullType(),
outerGeneric);
entry->setRequirementVal(requirementVal);
break;
case kIROp_AssociatedType:
// For associated types, we will store it directly inside the interface
// type.
entry->setRequirementVal(requirementVal);
break;
}
if (requirementDeclRef.getDecl()->findModifier<HLSLStaticModifier>())
{
getBuilder()->addStaticRequirementDecoration(requirementKey);
}
}
irInterface->setOperand(entryIndex, entry);
entryIndex++;
// Add addtional requirements for type constraints placed
// on an associated types.
if (auto associatedTypeDeclRef = requirementDeclRef.as<AssocTypeDecl>())
{
for (auto constraintDeclRef : getMembersOfType<TypeConstraintDecl>(
subContext->astBuilder,
associatedTypeDeclRef))
{
auto constraintKey = getInterfaceRequirementKey(constraintDeclRef.getDecl());
auto constraintInterfaceType =
lowerType(subContext, getSup(subContext->astBuilder, constraintDeclRef));
auto witnessTableType =
getBuilder()->getWitnessTableType(constraintInterfaceType);
auto constraintEntry = subBuilder->createInterfaceRequirementEntry(
constraintKey,
witnessTableType);
irInterface->setOperand(entryIndex, constraintEntry);
entryIndex++;
context->setValue(
constraintDeclRef.getDecl(),
LoweredValInfo::simple(constraintEntry));
}
}
else
{
CallableDecl* callableDecl = nullptr;
if (auto genDecl = as<GenericDecl>(requirementDeclRef.getDecl()))
callableDecl = as<CallableDecl>(genDecl->inner);
else
callableDecl = as<CallableDecl>(requirementDeclRef.getDecl());
if (callableDecl)
{
// Differentiable functions has additional requirements for the derivatives.
for (auto diffDecl :
callableDecl->getMembersOfType<DerivativeRequirementReferenceDecl>())
{
auto diffKey = getInterfaceRequirementKey(diffDecl->referencedDecl);
insertRequirementKeyAssociation(
diffDecl->referencedDecl,
requirementKey,
diffKey);
}
}
// Add lowered requirement entry to current decl mapping to prevent
// the function requirements from being lowered again when we get to
// `ensureAllDeclsRec`.
context->setValue(requirementDeclRef.getDecl(), LoweredValInfo::simple(entry));
}
};
for (auto requirementDecl : decl->getDirectMemberDecls())
{
auto requirementKey = getInterfaceRequirementKey(requirementDecl);
if (!requirementKey)
{
if (as<InterfaceDefaultImplDecl>(requirementDecl))
continue;
if (auto genericDecl = as<GenericDecl>(requirementDecl))
{
// We need to form a declref into the inner decls in case of a generic
// requirement.
requirementDecl = getInner(genericDecl);
}
if (as<PropertyDecl>(requirementDecl) || as<SubscriptDecl>(requirementDecl))
{
for (auto accessorDecl : as<ContainerDecl>(requirementDecl)
->getDirectMemberDeclsOfType<AccessorDecl>())
{
auto accessorKey = getInterfaceRequirementKey(accessorDecl);
if (accessorKey)
{
auto accessorDeclRef =
createDefaultSpecializedDeclRef(subContext, nullptr, accessorDecl);
addEntry(accessorKey, accessorDeclRef);
}
}
}
continue;
}
else
{
if (auto genericDecl = as<GenericDecl>(requirementDecl))
{
// We need to form a declref into the inner decls in case of a generic
// requirement.
requirementDecl = getInner(genericDecl);
}
auto requirementDeclRef =
createDefaultSpecializedDeclRef(subContext, nullptr, requirementDecl);
addEntry(requirementKey, requirementDeclRef);
}
}
addNameHint(context, irInterface, decl);
addLinkageDecoration(context, irInterface, decl);
if (auto anyValueSizeAttr = decl->findModifier<AnyValueSizeAttribute>())
{
subBuilder->addAnyValueSizeDecoration(irInterface, anyValueSizeAttr->size);
}
if (const auto specializeAttr = decl->findModifier<SpecializeAttribute>())
{
subBuilder->addSpecializeDecoration(irInterface);
}
if (auto comInterfaceAttr = decl->findModifier<ComInterfaceAttribute>())
{
subBuilder->addComInterfaceDecoration(
irInterface,
comInterfaceAttr->guid.getUnownedSlice());
}
if (const auto builtinAttr = decl->findModifier<BuiltinAttribute>())
{
subBuilder->addBuiltinDecoration(irInterface);
}
if (decl->hasModifier<TreatAsDifferentiableAttribute>())
{
subBuilder->addDecoration(irInterface, kIROp_TreatAsDifferentiableDecoration);
}
subBuilder->setInsertInto(irInterface);
addTargetIntrinsicDecorations(subContext, irInterface, decl);
return LoweredValInfo::simple(finalVal);
}
LoweredValInfo visitEnumCaseDecl(EnumCaseDecl* decl)
{
// A case within an `enum` decl will lower to a value
// of the `enum`'s "tag" type.
//
// TODO: a bit more work will be needed if we allow for
// enum cases that have payloads, because then we need
// a function that constructs the value given arguments.
//
NestedContext nestedContext(this);
auto subContext = nestedContext.getContext();
// Emit any generics that should wrap the actual type.
emitOuterGenerics(subContext, decl, decl);
return lowerRValueExpr(subContext, decl->tagExpr);
}
LoweredValInfo visitEnumDecl(EnumDecl* 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);
}
NestedContext nestedContext(this);
auto subBuilder = nestedContext.getBuilder();
auto subContext = nestedContext.getContext();
auto outerGeneric = emitOuterGenerics(subContext, decl, decl);
// TODO: if we ever support `enum` types with payloads, we would
// need to make the `enum` lower to some kind of custom "tagged union"
// type.
IRType* loweredTagType = lowerType(subContext, decl->tagType);
IRType* enumType = subBuilder->createEnumType(loweredTagType);
addLinkageDecoration(context, enumType, decl);
return LoweredValInfo::simple(finishOuterGenerics(subBuilder, enumType, outerGeneric));
}
LoweredValInfo visitThisTypeDecl(ThisTypeDecl* decl)
{
SLANG_UNUSED(decl);
return LoweredValInfo();
}
LoweredValInfo visitThisTypeConstraintDecl(ThisTypeConstraintDecl* decl)
{
SLANG_UNUSED(decl);
return LoweredValInfo();
}
LoweredValInfo visitAggTypeDecl(AggTypeDecl* decl)
{
// Don't generate an IR `struct` for intrinsic types
if (decl->findModifier<IntrinsicTypeModifier>() ||
decl->findModifier<BuiltinTypeModifier>())
{
return LoweredValInfo();
}
if (as<AssocTypeDecl>(decl))
{
SLANG_UNREACHABLE("associatedtype should have been handled by visitAssocTypeDecl.");
}
// TODO(JS):
// Not clear what to do around HLSLExportModifier.
// The HLSL spec says it only applies to functions, so we ignore for now.
// We are going to create nested IR building state
// to use when emitting the members of the type.
//
NestedContext nestedContext(this);
auto subBuilder = nestedContext.getBuilder();
auto subContext = nestedContext.getContext();
// Emit any generics that should wrap the actual type.
auto outerGeneric = emitOuterGenerics(subContext, decl, decl);
IRType* irAggType = nullptr;
if (as<StructDecl>(decl))
{
irAggType = subBuilder->createStructType();
}
else if (as<ClassDecl>(decl))
{
irAggType = subBuilder->createClassType();
}
else if (as<GLSLInterfaceBlockDecl>(decl))
{
if (decl->findModifier<GLSLBufferModifier>())
{
irAggType = subBuilder->createStructType();
}
else
{
return LoweredValInfo();
}
}
else
{
getSink()->diagnose(
decl->loc,
Diagnostics::unimplemented,
"lower unknown AggType to IR");
return LoweredValInfo::simple(subBuilder->getVoidType());
}
maybeAddDebugLocationDecoration(context, irAggType);
auto finalFinishedVal = finishOuterGenerics(subBuilder, irAggType, outerGeneric);
// We add the decl now such that if there are Ptr or other references
// to this type they can still complete
context->setValue(decl, LoweredValInfo::simple(finalFinishedVal));
subBuilder->setInsertBefore(irAggType);
// 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(subContext, inheritanceDecl);
}
addNameHint(context, irAggType, decl);
addLinkageDecoration(context, irAggType, decl);
if (const auto rayPayloadAttribute = decl->findModifier<RayPayloadAttribute>())
{
subBuilder->addDecoration(irAggType, kIROp_RayPayloadDecoration);
}
subBuilder->setInsertInto(irAggType);
// A `struct` that inherits from another `struct` must start
// with a member for the direct base type.
//
for (auto inheritanceDecl : decl->getMembersOfType<InheritanceDecl>())
{
auto superType = inheritanceDecl->base;
if (auto superDeclRefType = as<DeclRefType>(superType))
{
if (superDeclRefType->getDeclRef().as<StructDecl>() ||
superDeclRefType->getDeclRef().as<ClassDecl>() ||
superDeclRefType->getDeclRef().as<GLSLInterfaceBlockDecl>())
{
auto superKey =
(IRStructKey*)getSimpleVal(context, ensureDecl(context, inheritanceDecl));
auto irSuperType = lowerType(subContext, superType.type);
subBuilder->createStructField(irAggType, superKey, irSuperType);
}
}
}
for (auto fieldDecl : decl->getMembersOfType<VarDeclBase>())
{
if (fieldDecl->hasModifier<HLSLStaticModifier>())
{
// A `static` field is actually a global variable,
// and we should emit it as such.
ensureDecl(context, fieldDecl);
continue;
}
// Each ordinary field will need to turn into a struct "key"
// that is used for fetching the field.
IRInst* fieldKeyInst = getSimpleVal(subContext, ensureDecl(subContext, fieldDecl));
auto fieldKey = as<IRStructKey>(fieldKeyInst);
SLANG_ASSERT(fieldKey);
// Note: we lower the type of the field in the "sub"
// context, so that any generic parameters that were
// set up for the type can be referenced by the field type.
IRType* fieldType = lowerType(subContext, fieldDecl->getType());
// Then, the parent `struct` instruction itself will have
// a "field" instruction.
subBuilder->createStructField(irAggType, fieldKey, fieldType);
for (auto mod : fieldDecl->modifiers)
{
if (auto packOffsetModifier = as<HLSLPackOffsetSemantic>(mod))
{
lowerPackOffsetModifier(fieldKey, packOffsetModifier);
}
else if (as<DynamicUniformModifier>(mod))
{
subBuilder->addDynamicUniformDecoration(fieldKey);
}
}
}
// There may be members not handled by the above logic (e.g.,
// member functions), but we will not immediately force them
// to be emitted here, so as not to risk a circular dependency.
//
// Instead we will force emission of all children of aggregate
// type declarations later, from the top-level emit logic.
addTargetIntrinsicDecorations(subContext, irAggType, decl);
for (auto modifier : decl->modifiers)
{
if (as<NonCopyableTypeAttribute>(modifier))
subBuilder->addNonCopyableTypeDecoration(irAggType);
else if (as<AutoDiffBuiltinAttribute>(modifier))
subBuilder->addAutoDiffBuiltinDecoration(irAggType);
}
addTargetRequirementDecorations(irAggType, decl);
return LoweredValInfo::simple(finalFinishedVal);
}
void lowerPackOffsetModifier(IRInst* inst, HLSLPackOffsetSemantic* semantic)
{
auto builder = getBuilder();
int registerOffset =
stringToInt(semantic->registerName.getName()->text.getUnownedSlice().tail(1));
int componentOffset = 0;
if (semantic->componentMask.getContentLength() != 0)
{
switch (semantic->componentMask.getContent()[0])
{
case 'x':
componentOffset = 0;
break;
case 'y':
componentOffset = 1;
break;
case 'z':
componentOffset = 2;
break;
case 'w':
componentOffset = 3;
break;
}
}
builder->addDecoration(
inst,
kIROp_PackOffsetDecoration,
builder->getIntValue(builder->getIntType(), registerOffset),
builder->getIntValue(builder->getIntType(), componentOffset));
}
void lowerRayPayloadAccessModifier(IRInst* inst, RayPayloadAccessSemantic* semantic, IROp op)
{
auto builder = getBuilder();
List<IRInst*> operands;
for (auto stageNameToken : semantic->stageNameTokens)
{
IRInst* stageName = builder->getStringValue(stageNameToken.getContent());
operands.add(stageName);
}
builder->addDecoration(inst, op, operands.getBuffer(), operands.getCount());
}
void lowerDerivativeMemberModifier(
IRInst* inst,
Decl* memberDecl,
DerivativeMemberAttribute* derivativeMember)
{
IRInst* key = nullptr;
if (derivativeMember->memberDeclRef->declRef.getDecl() == memberDecl)
{
key = inst;
}
else
{
ensureDecl(context, derivativeMember->memberDeclRef->declRef.getDecl()->parentDecl);
key = lowerRValueExpr(context, derivativeMember->memberDeclRef).val;
}
SLANG_RELEASE_ASSERT(as<IRStructKey>(key));
auto builder = getBuilder();
builder->addDecoration(inst, kIROp_DerivativeMemberDecoration, key);
}
void lowerDifferentiableAttribute(
IRGenContext* subContext,
IRInst* inst,
DifferentiableAttribute* attr)
{
auto irDict = getBuilder()->addDifferentiableTypeDictionaryDecoration(inst);
for (auto& entry : attr->getMapTypeToIDifferentiableWitness())
{
// Lower type and witness.
IRType* irType = lowerType(subContext, entry.value->getSub());
IRInst* irWitness = lowerVal(subContext, entry.value).val;
SLANG_ASSERT(irType);
// If the witness can be lowered, and the differentiable type entry exists,
// add an entry to the context.
//
if (irWitness)
{
getBuilder()->addDifferentiableTypeEntry(irDict, irType, irWitness);
}
}
}
LoweredValInfo lowerMemberVarDecl(VarDecl* fieldDecl)
{
// Each field declaration in the AST translates into
// a "key" that can be used to extract field values
// from instances of struct types that contain the field.
//
// It is correct to say struct *types* because a `struct`
// nested under a generic can be used to realize a number
// of different concrete types, but all of these types
// will use the same space of keys.
auto builder = getBuilder();
IRInst* irFieldKey = nullptr;
if (auto extVarModifier = fieldDecl->findModifier<ExtensionExternVarModifier>())
{
irFieldKey = ensureDecl(context, extVarModifier->originalDecl.getDecl()).val;
SLANG_RELEASE_ASSERT(as<IRStructKey>(irFieldKey));
}
if (!irFieldKey)
{
irFieldKey = builder->createStructKey();
addNameHint(context, irFieldKey, fieldDecl);
addVarDecorations(context, irFieldKey, fieldDecl);
addLinkageDecoration(context, irFieldKey, fieldDecl);
}
if (auto semanticModifier = fieldDecl->findModifier<HLSLSimpleSemantic>())
{
builder->addSemanticDecoration(
irFieldKey,
semanticModifier->name.getName()->text.getUnownedSlice());
}
if (auto readModifier = fieldDecl->findModifier<RayPayloadReadSemantic>())
{
lowerRayPayloadAccessModifier(
irFieldKey,
readModifier,
kIROp_StageReadAccessDecoration);
}
if (auto writeModifier = fieldDecl->findModifier<RayPayloadWriteSemantic>())
{
lowerRayPayloadAccessModifier(
irFieldKey,
writeModifier,
kIROp_StageWriteAccessDecoration);
}
if (auto derivativeMemberModifier = fieldDecl->findModifier<DerivativeMemberAttribute>())
{
lowerDerivativeMemberModifier(irFieldKey, fieldDecl, derivativeMemberModifier);
}
// We allow a field to be marked as a target intrinsic,
// so that we can override its mangled name in the
// output for the chosen target.
addTargetIntrinsicDecorations(nullptr, irFieldKey, fieldDecl);
return LoweredValInfo::simple(irFieldKey);
}
IRType* maybeGetConstExprType(IRType* type, Decl* decl)
{
return Slang::maybeGetConstExprType(getBuilder(), type, decl);
}
/// Emit appropriate generic parameters for a constraint, and return the value of that
/// constraint.
///
/// The `supType` paramete represents the super-type that a parameter is constrained to.
IRInst* emitGenericConstraintValue(
IRGenContext* subContext,
GenericTypeConstraintDecl* constraintDecl,
IRType* supType)
{
auto subBuilder = subContext->irBuilder;
// There are two cases we care about here.
//
if (auto andType = as<IRConjunctionType>(supType))
{
// The non-trivial case is when the constraint on a generic parameter
// was of the form `T : A & B`. In this case, we really want to
// emit the function with parameters for each of the two independent
// constraints `T : A` and `T : B`.
//
// We will loop over the "cases" of the conjunction (since
// the `IRConunctionType` can support more than just binary
// conjunctions) and recursively add constraints for each.
//
List<IRInst*> caseVals;
auto caseCount = andType->getCaseCount();
for (Int i = 0; i < caseCount; ++i)
{
auto caseType = andType->getCaseType(i);
auto caseVal = emitGenericConstraintValue(subContext, constraintDecl, caseType);
caseVals.add(caseVal);
}
return subBuilder->emitMakeTuple(caseVals);
}
else
{
// The case case is any other type being used as the constraint.
//
// The constraint will then map to a single generic parameter passing
// a witness table for conformance to the given `supType`.
//
auto param = subBuilder->emitParam(subBuilder->getWitnessTableType(supType));
addNameHint(context, param, constraintDecl);
// In order to support some of the "any-value" work in dynamic dispatch
// we have to attach the interface that was used as a constraint onto the
// type that is being constrained (which we expect to be a generic type
// parameter).
//
// TODO: It feels a bit gross to be doing this here; perhaps the front-end
// should handle propgation of value-size information from constraints
// back to generic parameters?
//
if (auto genParamDeclRef =
isDeclRefTypeOf<GenericTypeParamDeclBase>(constraintDecl->sub.type))
{
auto typeParamDeclVal = subContext->findLoweredDecl(genParamDeclRef.getDecl());
SLANG_ASSERT(typeParamDeclVal && typeParamDeclVal->val);
subBuilder->addTypeConstraintDecoration(typeParamDeclVal->val, supType);
}
return param;
}
}
void emitGenericConstraintDecl(
IRGenContext* subContext,
GenericTypeConstraintDecl* constraintDecl)
{
auto supType = lowerType(subContext, constraintDecl->sup.type);
auto value = emitGenericConstraintValue(subContext, constraintDecl, supType);
subContext->setValue(constraintDecl, LoweredValInfo::simple(value));
}
IRGeneric* emitOuterGeneric(IRGenContext* subContext, GenericDecl* genericDecl, Decl* leafDecl)
{
auto subBuilder = subContext->irBuilder;
// Of course, a generic might itself be nested inside of other generics...
emitOuterGenerics(subContext, genericDecl, leafDecl);
// We need to create an IR generic
auto irGeneric = subBuilder->emitGeneric();
subBuilder->setInsertInto(irGeneric);
auto irBlock = subBuilder->emitBlock();
subBuilder->setInsertInto(irBlock);
// Now emit any parameters of the generic
//
// First we start with type and value parameters,
// in the order they were declared.
for (auto member : genericDecl->getDirectMemberDecls())
{
if (auto typeParamDecl = as<GenericTypeParamDeclBase>(member))
{
IRType* typeKind = nullptr;
if (as<GenericTypePackParamDecl>(member))
typeKind = subBuilder->getTypeParameterPackKind();
else
typeKind = subBuilder->getTypeType();
auto param = subBuilder->emitParam(typeKind);
addNameHint(context, param, typeParamDecl);
subContext->setValue(typeParamDecl, LoweredValInfo::simple(param));
}
else if (auto valDecl = as<GenericValueParamDecl>(member))
{
auto paramType = lowerType(subContext, valDecl->getType());
auto param = subBuilder->emitParam(paramType);
addNameHint(context, param, valDecl);
subContext->setValue(valDecl, LoweredValInfo::simple(param));
}
}
// Then we emit constraint parameters, again in
// declaration order.
for (auto constraintDecl :
genericDecl->getDirectMemberDeclsOfType<GenericTypeConstraintDecl>())
{
emitGenericConstraintDecl(subContext, constraintDecl);
}
return irGeneric;
}
IRGeneric* emitOuterInterfaceGeneric(
IRGenContext* subContext,
ContainerDecl* parentDecl,
DeclRefType* interfaceType,
Decl* leafDecl)
{
auto subBuilder = subContext->irBuilder;
// Of course, a generic might itself be nested inside of other generics...
emitOuterGenerics(subContext, parentDecl, leafDecl);
// We need to create an IR generic
auto irGeneric = subBuilder->emitGeneric();
subBuilder->setInsertInto(irGeneric);
auto irBlock = subBuilder->emitBlock();
subBuilder->setInsertInto(irBlock);
// The generic needs two parameters: one to represent the
// `ThisType`, and one to represent a witness that the
// `ThisType` conforms to the interface itself.
//
auto irThisTypeParam = subBuilder->emitParam(subBuilder->getTypeType());
auto irInterfaceType = lowerType(context, interfaceType);
auto irWitnessTableParam =
subBuilder->emitParam(subBuilder->getWitnessTableType(irInterfaceType));
subBuilder->addTypeConstraintDecoration(irThisTypeParam, irInterfaceType);
// Now we need to wire up the IR parameters
// we created to be used as the `ThisType` in
// the body of the code.
//
subContext->thisType = irThisTypeParam;
subContext->thisTypeWitness = irWitnessTableParam;
return irGeneric;
}
// If the given `decl` is enclosed in any generic declarations, then
// emit IR-level generics to represent them.
// The `leafDecl` represents the inner-most declaration we are actually
// trying to emit, which is the one that should receive the mangled name.
//
IRGeneric* emitOuterGenerics(IRGenContext* subContext, Decl* decl, Decl* leafDecl)
{
for (auto pp = decl->parentDecl; pp; pp = pp->parentDecl)
{
if (auto genericAncestor = as<GenericDecl>(pp))
{
return emitOuterGeneric(subContext, genericAncestor, leafDecl);
}
// We introduce IR generics in one other case, where the input
// code wasn't visibly using generics: when a concrete member
// is defined on an interface type. In that case, the resulting
// definition needs to be generic on a parameter to represent
// the `ThisType` of the interface.
//
if (auto extensionAncestor = as<ExtensionDecl>(pp))
{
if (auto targetDeclRefType = as<DeclRefType>(extensionAncestor->targetType))
{
if (auto interfaceDeclRef = targetDeclRefType->getDeclRef().as<InterfaceDecl>())
{
return emitOuterInterfaceGeneric(
subContext,
extensionAncestor,
targetDeclRefType,
leafDecl);
}
}
}
}
return nullptr;
}
static bool isChildOf(IRInst* child, IRInst* parent)
{
while (child && child->getParent() != parent)
child = child->getParent();
return child != nullptr;
}
static void markInstsToClone(InstHashSet& valuesToClone, IRInst* parentBlock, IRInst* value)
{
if (!isChildOf(value, parentBlock))
return;
if (valuesToClone.add(value))
{
for (UInt i = 0; i < value->getOperandCount(); i++)
{
auto operand = value->getOperand(i);
markInstsToClone(valuesToClone, parentBlock, operand);
}
if (value->getFullType())
markInstsToClone(valuesToClone, parentBlock, value->getFullType());
for (auto child : value->getDecorationsAndChildren())
markInstsToClone(valuesToClone, parentBlock, child);
}
auto parent = parentBlock->getParent();
while (parent && parent != parentBlock)
{
valuesToClone.add(parent);
parent = parent->getParent();
}
}
// If any generic declarations have been created by `emitOuterGenerics`,
// then finish them off by emitting `return` instructions for the
// values that they should produce.
//
// Return the outer-most generic (if there is one), or the original
// value (if there were no generics), which should be the IR-level
// representation of the original declaration.
//
IRInst* finishOuterGenerics(IRBuilder* subBuilder, IRInst* val, IRGeneric* parentGeneric)
{
IRInst* v = val;
IRInst* returnType = v->getFullType();
while (parentGeneric)
{
// Create a universal type in `outerBlock` that will be used
// as the type of this generic inst. The return value of the
// generic inst will have a specialized type.
// For example, if we have a generic function
// g0 = generic<T> { return f: T->int }
// The type for `g0` should be:
// g0Type = generic<T1> { return IRFuncType{T1->int} }
// with `g0Type`, we can rewrite `g0` into:
// ```
// g0 : g0Type = generic<T>
// {
// ftype = specialize(g0Type, T);
// return f : ftype;
// }
// ```
IRBuilder typeBuilder(subBuilder->getModule());
IRCloneEnv cloneEnv = {};
if (returnType)
{
InstHashSet valuesToClone(subBuilder->getModule());
markInstsToClone(valuesToClone, parentGeneric->getFirstBlock(), returnType);
// For Function Types, we always clone all generic parameters regardless of whether
// the generic parameter appears in the function signature or not.
if (returnType->getOp() == kIROp_FuncType || returnType->getOp() == kIROp_Generic)
{
for (auto genericParam : parentGeneric->getParams())
{
markInstsToClone(
valuesToClone,
parentGeneric->getFirstBlock(),
genericParam);
}
}
if (valuesToClone.getCount() == 0)
{
// If the new generic has no parameters, set
// the generic inst's type to just `returnType`.
parentGeneric->setFullType((IRType*)returnType);
}
else
{
// In the general case, we need to construct a separate
// generic value for the return type, and set the generic's type
// to the newly construct generic value.
typeBuilder.setInsertBefore(parentGeneric);
auto typeGeneric = typeBuilder.emitGeneric();
typeGeneric->setFullType(typeBuilder.getGenericKind());
typeBuilder.setInsertInto(typeGeneric);
auto block = typeBuilder.emitBlock();
struct ParamCloneInfo
{
IRParam* originalParam;
IRParam* clonedParam;
};
ShortList<ParamCloneInfo> paramCloneInfos;
for (auto child : parentGeneric->getFirstBlock()->getChildren())
{
if (valuesToClone.contains(child))
{
if (child->getOp() == kIROp_Param)
{
// Params may have forward references in its type and
// decorations, so we just create a placeholder for it
// in this first pass.
IRParam* clonedParam = typeBuilder.emitParam(nullptr);
cloneEnv.mapOldValToNew[child] = clonedParam;
paramCloneInfos.add({(IRParam*)child, clonedParam});
}
else
{
cloneInst(&cloneEnv, &typeBuilder, child);
}
}
}
// In a second pass, clone the types and decorations on params which may
// contain forward references.
for (auto param : paramCloneInfos)
{
typeBuilder.setInsertInto(param.clonedParam);
param.clonedParam->setFullType((IRType*)cloneInst(
&cloneEnv,
&typeBuilder,
param.originalParam->getFullType()));
cloneInstDecorationsAndChildren(
&cloneEnv,
typeBuilder.getModule(),
param.originalParam,
param.clonedParam);
}
typeBuilder.setInsertInto(block);
IRInst* clonedReturnType = nullptr;
cloneEnv.mapOldValToNew.tryGetValue(returnType, clonedReturnType);
if (clonedReturnType)
{
// If the type has explicit dependency on generic parameters, use
// the cloned type.
typeBuilder.emitReturn(clonedReturnType);
}
else
{
// Otherwise just use the original type value directly.
typeBuilder.emitReturn(returnType);
}
parentGeneric->setFullType((IRType*)typeGeneric);
returnType = typeGeneric;
}
}
subBuilder->setInsertInto(parentGeneric->getFirstBlock());
#if 0
// TODO: we cannot enable this right now as it breaks too many existing code
// that is assuming a generic function type is `IRFuncType` rather than `IRSpecialize`.
if (v->getFullType() != returnType)
{
// We need to rewrite the type of the return value as
// `specialize(returnType, ...)`.
SLANG_ASSERT(returnType->getOp() == kIROp_Generic);
auto oldType = v->getFullType();
SLANG_ASSERT(isChildOf(oldType, parentGeneric->getFirstBlock()));
List<IRInst*> specializeArgs;
for (auto param : parentGeneric->getParams())
{
IRInst* arg = nullptr;
if (cloneEnv.mapOldValToNew.tryGetValue(param, arg))
{
specializeArgs.add(arg);
}
}
auto specializedType = subBuilder->emitSpecializeInst(
subBuilder->getTypeKind(),
returnType,
(UInt)specializeArgs.getCount(),
specializeArgs.getBuffer());
oldType->replaceUsesWith(specializedType);
}
#endif
subBuilder->emitReturn(v);
parentGeneric->moveToEnd();
// There might be more outer generics,
// so we need to loop until we run out.
v = parentGeneric;
auto parentBlock = as<IRBlock>(v->getParent());
if (!parentBlock)
break;
parentGeneric = as<IRGeneric>(parentBlock->getParent());
if (!parentGeneric)
break;
}
return v;
}
void addSpecializedForTargetDecorations(IRInst* inst, Decl* 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 targetName = targetMod->targetToken.getContent();
auto targetCap = findCapabilityName(targetName);
getBuilder()->addTargetDecoration(inst, CapabilitySet(targetCap));
}
}
// Attach target-intrinsic decorations to an instruction,
// based on modifiers on an AST declaration.
void addTargetIntrinsicDecorations(IRGenContext* subContext, IRInst* irInst, Decl* decl)
{
auto builder = getBuilder();
for (auto targetMod : decl->getModifiersOfType<TargetIntrinsicModifier>())
{
String definition;
if (targetMod->isString)
{
definition = targetMod->definitionString;
}
else if (targetMod->definitionIdent.type == TokenType::Identifier)
{
definition = targetMod->definitionIdent.getContent();
}
else
{
if (isCoreModuleMemberFuncDecl(decl))
{
// We will mark member functions by appending a `.` to the
// start of their name.
//
definition.append(".");
}
definition.append(decl->getName()->text);
}
UnownedStringSlice targetName;
auto& targetToken = targetMod->targetToken;
if (targetToken.type != TokenType::Unknown)
{
targetName = targetToken.getContent();
}
CapabilitySet targetCaps;
if (targetName.getLength() == 0)
{
targetCaps = CapabilitySet::makeEmpty();
}
else
{
CapabilityName targetCap = findCapabilityName(targetName);
SLANG_ASSERT(targetCap != CapabilityName::Invalid);
targetCaps = CapabilitySet(targetCap);
}
IRInst* scrutinee = nullptr;
UnownedStringSlice predicate;
if (targetMod->scrutineeDeclRef)
{
const auto s = subContext->findLoweredDecl(targetMod->scrutineeDeclRef.getDecl());
if (s && s->flavor == LoweredValInfo::Flavor::Simple)
{
scrutinee = s->val;
predicate = targetMod->predicateToken.getContent();
}
}
builder->addTargetIntrinsicDecoration(
irInst,
targetCaps,
definition.getUnownedSlice(),
predicate,
scrutinee);
}
if (const auto nvapiMod = decl->findModifier<NVAPIMagicModifier>())
{
builder->addNVAPIMagicDecoration(irInst, decl->getName()->text.getUnownedSlice());
}
if (const auto requirePrelude = decl->findModifier<RequirePreludeAttribute>())
{
builder->addRequirePreludeDecoration(
irInst,
requirePrelude->capabilitySet,
requirePrelude->prelude.getUnownedSlice());
}
}
void addTargetRequirementDecorations(IRInst* inst, Decl* decl)
{
// If this declaration requires certain GLSL extension (or a particular GLSL version)
// for it to be usable, then declare that here. Similarly for SPIR-V or CUDA
//
// TODO: We should wrap this an `SpecializedForTargetModifier` together into a single
// case for enumerating the "capabilities" that a declaration requires.
//
for (auto extensionMod : decl->getModifiersOfType<RequiredGLSLExtensionModifier>())
{
getBuilder()->addRequireGLSLExtensionDecoration(
inst,
extensionMod->extensionNameToken.getContent());
}
for (auto versionMod : decl->getModifiersOfType<RequiredGLSLVersionModifier>())
{
getBuilder()->addRequireGLSLVersionDecoration(
inst,
Int(getIntegerLiteralValue(versionMod->versionNumberToken)));
}
for (auto versionMod : decl->getModifiersOfType<RequiredSPIRVVersionModifier>())
{
getBuilder()->addRequireSPIRVVersionDecoration(inst, versionMod->version);
}
for (auto extensionMod : decl->getModifiersOfType<RequiredWGSLExtensionModifier>())
{
getBuilder()->addRequireWGSLExtensionDecoration(
inst,
extensionMod->extensionNameToken.getContent());
}
for (auto versionMod : decl->getModifiersOfType<RequiredCUDASMVersionModifier>())
{
getBuilder()->addRequireCUDASMVersionDecoration(inst, versionMod->version);
}
}
void addBitFieldAccessorDecorations(IRInst* irFunc, Decl* decl)
{
// If this is an accessor and the parent is describing some bitfield,
// we can move the bitfield modifiers to the accessor function.
if (as<AccessorDecl>(decl))
{
if (const auto bfm = decl->parentDecl->findModifier<BitFieldModifier>())
{
getBuilder()->addDecoration(
irFunc,
kIROp_BitFieldAccessorDecoration,
getSimpleVal(context, ensureDecl(context, bfm->backingDeclRef.getDecl())),
getBuilder()->getIntValue(getBuilder()->getIntType(), bfm->width),
getBuilder()->getIntValue(getBuilder()->getIntType(), bfm->offset));
}
}
}
/// Is `decl` a member function (or effectively a member function) when considered as a core
/// module declaration?
bool isCoreModuleMemberFuncDecl(Decl* inDecl)
{
auto decl = as<CallableDecl>(inDecl);
if (!decl)
return false;
// Constructors aren't really member functions, insofar
// as they aren't called with a `this` parameter.
if (as<ConstructorDecl>(decl))
return false;
// Exclude `static` functions for same reason.
if (decl->findModifier<HLSLStaticModifier>())
{
return false;
}
auto dd = decl->parentDecl;
for (;;)
{
if (auto genericDecl = as<GenericDecl>(dd))
{
dd = genericDecl->parentDecl;
continue;
}
if (auto subscriptDecl = as<SubscriptDecl>(dd))
{
dd = subscriptDecl->parentDecl;
}
break;
}
// Note: the use of `AggTypeDeclBase` here instead of just
// `AggTypeDecl` means that we consider a declaration that
// is under a `struct` *or* an `extension` to be a member
// function for our purposes.
//
if (as<AggTypeDeclBase>(dd))
return true;
return false;
}
/// Add a "catch-all" decoration for a core module function if it would be needed
void addCatchAllIntrinsicDecorationIfNeeded(IRInst* irInst, FunctionDeclBase* decl)
{
// We don't need an intrinsic decoration on a function that has a body,
// since the body can be used as the "catch-all" case.
//
if (decl->body)
return;
// Only core module declarations should get any kind of catch-all
// treatment by default. Declarations in user case are responsible
// for marking things as target intrinsics if they want to go down
// that (unsupported) route.
//
if (!isFromCoreModule(decl))
return;
// No need to worry about functions that lower to intrinsic IR opcodes
// (or pseudo-ops).
//
if (decl->findModifier<IntrinsicOpModifier>())
return;
// We also don't need an intrinsic decoration if the function already
// had a catch-all case on one of its target overloads.
//
for (auto f = decl->primaryDecl; f; f = f->nextDecl)
{
for (auto targetMod : f->getModifiersOfType<TargetIntrinsicModifier>())
{
// If we find a catch-all case (marked as either *no* target
// token or an empty target name), then we should bail out.
//
if (targetMod->targetToken.type == TokenType::Unknown)
return;
else if (!targetMod->targetToken.hasContent())
return;
}
}
String definition;
// If we have a member function, then we want the default intrinsic
// definition to reflect this fact so that we can emit it correctly
// (the assumption is that a catch-all definition of a member function
// is itself implemented as a member function).
//
if (isCoreModuleMemberFuncDecl(decl))
{
// We will mark member functions by appending a `.` to the
// start of their name.
//
definition.append(".");
}
// We want to output the name of the declaration,
// but in some cases the actual `decl` that has
// to be emitted is not the one with the name.
//
// In particular, an accessor declaration (e.g.,
// a `get`ter` in a subscript or property) doesn't
// have a name, but its parent should.
//
Decl* declForName = decl;
if (const auto accessorDecl = as<AccessorDecl>(decl))
declForName = decl->parentDecl;
definition.append(getText(declForName->getName()));
getBuilder()->addTargetIntrinsicDecoration(
irInst,
CapabilitySet(CapabilityName::textualTarget),
definition.getUnownedSlice());
}
void addParamNameHint(IRInst* inst, IRLoweringParameterInfo const& info)
{
if (auto decl = info.decl)
{
addNameHint(context, inst, decl);
}
else if (info.isThisParam)
{
addNameHint(context, inst, "this");
}
}
IRFloatLit* _getFloatFromAttribute(IRBuilder* builder, Attribute* attrib, Index index = 0)
{
SLANG_ASSERT(attrib->args.getCount() > index);
Expr* expr = attrib->args[index];
if (auto floatLitExpr = as<FloatingPointLiteralExpr>(expr))
{
return as<IRFloatLit>(
builder->getFloatValue(builder->getFloatType(), floatLitExpr->value));
}
auto intLitExpr = as<IntegerLiteralExpr>(expr);
SLANG_ASSERT(intLitExpr);
return as<IRFloatLit>(builder->getFloatValue(
builder->getFloatType(),
(IRFloatingPointValue)(intLitExpr->value)));
}
IRIntLit* _getIntLitFromAttribute(IRBuilder* builder, Attribute* attrib, Index index = 0)
{
SLANG_ASSERT(attrib->args.getCount() > index);
Expr* expr = attrib->args[index];
auto intLitExpr = as<IntegerLiteralExpr>(expr);
SLANG_ASSERT(intLitExpr);
return as<IRIntLit>(builder->getIntValue(builder->getIntType(), intLitExpr->value));
}
IRStringLit* _getStringLitFromAttribute(IRBuilder* builder, Attribute* attrib, Index index = 0)
{
SLANG_ASSERT(attrib->args.getCount() > index);
Expr* expr = attrib->args[index];
auto stringLitExpr = as<StringLiteralExpr>(expr);
SLANG_ASSERT(stringLitExpr);
return as<IRStringLit>(builder->getStringValue(stringLitExpr->value.getUnownedSlice()));
}
bool isClassType(IRType* type)
{
type = (IRType*)unwrapAttributedType(type);
if (auto specialize = as<IRSpecialize>(type))
{
return findSpecializeReturnVal(specialize)->getOp() == kIROp_ClassType;
}
else if (auto genericInst = as<IRGeneric>(type))
{
return findGenericReturnVal(genericInst)->getOp() == kIROp_ClassType;
}
return type->getOp() == kIROp_ClassType;
}
LoweredValInfo lowerFuncDeclInContext(
IRGenContext* subContext,
IRBuilder* subBuilder,
FunctionDeclBase* decl,
bool emitBody = true)
{
bool isFromDifferentModule = isDeclInDifferentModule(context, decl);
if (isFromDifferentModule && isForceInlineEarly(decl))
{
// If a function is imported from another module then
// we usually don't want to emit it as a definition, and
// will instead only emit a declaration for it with an
// appropriate `[import(...)]` linkage decoration.
//
// However, if the function is marked with `[__unsafeForceInlineEarly]`
// then we need to make sure the IR for its definition is available
// to the mandatory optimization passes.
//
// We do so by finding the IR function from the imported module, and clone
// the body of the IRFunc from the imported module to the current module.
//
auto importedModule = getModule(decl);
auto irModule = importedModule->getIRModule();
SLANG_ASSERT(irModule && "Module containing imported decl does not have an IRModule.");
String mangledName = getMangledName(context->astBuilder, decl);
auto importedFunc = irModule->findSymbolByMangledName(mangledName);
SLANG_ASSERT(importedFunc.getCount() > 0);
subContext->shared->externalSymbolsToPrelink.add(importedFunc[0]);
}
IRGeneric* outerGeneric = nullptr;
subContext->funcDecl = decl;
if (auto derivativeRequirement = as<DerivativeRequirementDecl>(decl))
outerGeneric = emitOuterGenerics(
subContext,
derivativeRequirement->originalRequirementDecl,
derivativeRequirement->originalRequirementDecl);
else
outerGeneric = emitOuterGenerics(subContext, decl, decl);
// If our function is differentiable, register a callback so the derivative
// annotations for types can be lowered.
//
if (decl->findModifier<DifferentiableAttribute>() && !isInterfaceRequirement(decl))
{
auto diffAttr = decl->findModifier<DifferentiableAttribute>();
auto diffTypeWitnessMap = diffAttr->getMapTypeToIDifferentiableWitness();
OrderedDictionary<Type*, SubtypeWitness*> resolveddiffTypeWitnessMap;
// Go through each entry in the map and resolve the key.
for (auto& entry : diffTypeWitnessMap)
{
auto resolvedKey = as<Type>(entry.key->resolve());
resolveddiffTypeWitnessMap[resolvedKey] =
as<SubtypeWitness>(as<Val>(entry.value)->resolve());
}
subContext->registerTypeCallback(
[=](IRGenContext* context, Type* type, IRType* irType)
{
if (resolveddiffTypeWitnessMap.containsKey(type))
{
auto irWitness = lowerVal(subContext, resolveddiffTypeWitnessMap[type]).val;
if (irWitness)
{
IRInst* args[] = {irType, irWitness};
context->irBuilder->emitIntrinsicInst(
context->irBuilder->getVoidType(),
kIROp_DifferentiableTypeAnnotation,
2,
args);
}
}
return irType;
});
}
// Register the value now, to avoid any possible infinite recursion when lowering the body
// or attributes.
IRFunc* irFunc = subBuilder->createFunc();
context->setGlobalValue(decl, LoweredValInfo::simple(findOuterMostGeneric(irFunc)));
FuncDeclBaseTypeInfo info;
_lowerFuncDeclBaseTypeInfo(
subContext,
createDefaultSpecializedDeclRef(context, nullptr, decl),
info);
// need to create an IR function here
addNameHint(subContext, irFunc, decl);
addLinkageDecoration(subContext, irFunc, decl);
maybeAddDebugLocationDecoration(subContext, irFunc);
// Always force inline diff setter accessor to prevent downstream compiler from complaining
// fields are not fully initialized for the first `inout` parameter.
if (as<SetterDecl>(decl))
{
if (!decl->findModifier<ForceInlineAttribute>())
{
getBuilder()->addForceInlineDecoration(irFunc);
}
}
// For diagnostics
if (as<StructDecl>(decl->parentDecl))
getBuilder()->addSimpleDecoration<IRMethodDecoration>(irFunc);
auto irFuncType = info.type;
auto& irResultType = info.resultType;
auto& parameterLists = info.parameterLists;
auto& paramTypes = info.paramTypes;
irFunc->setFullType(irFuncType);
subBuilder->setInsertInto(irFunc);
if (emitBody && decl->body && !isFromDifferentModule)
{
// This is a function definition, so we need to actually
// construct IR for the body...
IRBlock* entryBlock = subBuilder->emitBlock();
subBuilder->setInsertInto(entryBlock);
UInt paramTypeIndex = 0;
for (auto paramInfo : parameterLists.params)
{
auto irParamType = paramTypes[paramTypeIndex++];
LoweredValInfo paramVal;
IRParam* irParam = nullptr;
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?
irParam = subBuilder->emitParam(irParamType);
if (auto paramDecl = paramInfo.decl)
{
addVarDecorations(context, irParam, paramDecl);
subBuilder->addHighLevelDeclDecoration(irParam, paramDecl);
irParam->sourceLoc = paramDecl->loc;
}
addParamNameHint(irParam, paramInfo);
paramVal = LoweredValInfo::ptr(irParam);
if (paramInfo.isReturnDestination)
subContext->returnDestination = paramVal;
if (paramInfo.declaredDirection == kParameterDirection_In &&
paramInfo.direction == kParameterDirection_ConstRef)
{
// If the parameter is originally declared as "in", but we are
// lowering it as constref for any reason (e.g. it is a varying input),
// then we need to emit a local variable to hold the original value, so
// that we can still generate correct code when the user trys to mutate
// the variable.
// The local variable introduced here is cleaned up by the SSA pass, if
// we can determine that there are no actual writes into the local var.
auto irLocal =
subBuilder->emitVar(tryGetPointedToType(subBuilder, irParamType));
auto localVal = LoweredValInfo::ptr(irLocal);
assign(subContext, localVal, paramVal);
paramVal = localVal;
}
// 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.
//
// We start by declaring an IR parameter of the same type.
//
auto paramDecl = paramInfo.decl;
irParam = subBuilder->emitParam(irParamType);
if (paramDecl)
{
addVarDecorations(context, irParam, paramDecl);
subBuilder->addHighLevelDeclDecoration(irParam, paramDecl);
irParam->sourceLoc = paramDecl->loc;
}
addParamNameHint(irParam, paramInfo);
paramVal = LoweredValInfo::simple(irParam);
//
// HLSL allows a function parameter to be used as a local
// variable in the function body (just like C/C++), so
// we need to support that case as well.
//
// However, if we notice that the parameter was marked
// `const`, then we can skip this step.
//
// TODO: we should consider having all parameter be implicitly
// immutable except in a specific "compatibility mode."
//
if (paramDecl && paramDecl->findModifier<ConstModifier>())
{
// This parameter was declared to be immutable,
// so there should be no assignment to it in the
// function body, and we don't need a temporary.
}
else
{
// The parameter migth get used as a temporary in
// the function body. We will allocate a mutable
// local variable for is value, and then assign
// from the parameter to the local at the start
// of the function.
//
auto irLocal = subBuilder->emitVar(irParamType);
auto localVal = LoweredValInfo::ptr(irLocal);
assign(subContext, localVal, paramVal);
//
// When code later in the body of the function refers
// to the parameter declaration, it will actually refer
// to the value stored in the local variable.
//
paramVal = localVal;
}
}
break;
}
if (auto paramDecl = paramInfo.decl)
{
subContext->setValue(paramDecl, paramVal);
}
if (paramInfo.isThisParam)
{
subContext->thisVal = paramVal;
}
}
{
auto attr = decl->findModifier<PatchConstantFuncAttribute>();
// I needed to test for patchConstantFuncDecl here
// because it is only set if validateEntryPoint is called with Hull as the required
// stage If I just build domain shader, and then the attribute exists, but
// patchConstantFuncDecl is not set and thus leads to a crash.
if (attr && attr->patchConstantFuncDecl)
{
// We need to lower the function
FuncDecl* patchConstantFunc = attr->patchConstantFuncDecl;
assert(patchConstantFunc);
// Convert the patch constant function into IRInst
IRInst* irPatchConstantFunc =
getSimpleVal(context, ensureDecl(subContext, patchConstantFunc));
// Attach a decoration so that our IR function references
// the patch constant function.
//
subContext->irBuilder->addPatchConstantFuncDecoration(
irFunc,
irPatchConstantFunc);
}
}
// We will now set about emitting the code for the body of
// the function/callable.
//
// In the case of an initializer ("constructor") declaration,
// the `this` value is not a parameter, but rather a placeholder
// for the value that will be returned. We thus need to set up
// a local variable to represent this value.
//
auto constructorDecl = as<ConstructorDecl>(decl);
if (constructorDecl)
{
if (subContext->returnDestination.flavor != LoweredValInfo::Flavor::None)
subContext->thisVal = subContext->returnDestination;
else
{
auto thisVar = subContext->irBuilder->emitVar(irResultType);
subContext->thisVal = LoweredValInfo::ptr(thisVar);
// For class-typed objects, we need to allocate it from heap.
if (isClassType(irResultType))
{
auto allocatedObj = subContext->irBuilder->emitAllocObj(irResultType);
subContext->irBuilder->emitStore(thisVar, allocatedObj);
}
}
// Used for diagnostics
getBuilder()->addConstructorDecoration(
irFunc,
constructorDecl->containsFlavor(
ConstructorDecl::ConstructorFlavor::SynthesizedDefault));
}
// We lower whatever statement was stored on the declaration
// as the body of the new IR function.
//
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 (!subContext->irBuilder->getBlock()->getTerminator())
{
if (constructorDecl)
{
// A constructor declaration should return the
// value of the `this` variable that was set
// up at the start.
//
// TODO: This should also apply if any code
// path in an initializer/constructor attempts
// to do an early `return;`.
//
if (subContext->returnDestination.flavor != LoweredValInfo::Flavor::None)
subContext->irBuilder->emitReturn();
else
{
subContext->irBuilder->emitReturn(
getSimpleVal(subContext, subContext->thisVal));
}
}
else if (as<IRVoidType>(irResultType))
{
// `void`-returning function can get an implicit
// return on exit of the body statement.
IRInst* returnInst = subContext->irBuilder->emitReturn();
if (BlockStmt* blockStmt = as<BlockStmt>(decl->body))
{
returnInst->sourceLoc = blockStmt->closingSourceLoc;
}
else
{
returnInst->sourceLoc = SourceLoc();
}
}
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.
subContext->irBuilder->emitMissingReturn();
}
}
}
subContext->registerTypeCallback(nullptr);
getBuilder()->addHighLevelDeclDecoration(irFunc, decl);
addSpecializedForTargetDecorations(irFunc, decl);
// If this declaration was marked as having a target-specific lowering
// for a particular target, then handle that here.
addTargetIntrinsicDecorations(subContext, irFunc, decl);
addCatchAllIntrinsicDecorationIfNeeded(irFunc, decl);
addTargetRequirementDecorations(irFunc, decl);
bool isInline = false;
addBitFieldAccessorDecorations(irFunc, decl);
IRNumThreadsDecoration* numThreadsDecor = nullptr;
IRDecoration* derivativeGroupQuadDecor = nullptr;
IRDecoration* derivativeGroupLinearDecor = nullptr;
for (auto modifier : decl->modifiers)
{
if (as<RequiresNVAPIAttribute>(modifier))
{
getBuilder()->addSimpleDecoration<IRRequiresNVAPIDecoration>(irFunc);
}
else if (as<AlwaysFoldIntoUseSiteAttribute>(modifier))
{
getBuilder()->addSimpleDecoration<IRAlwaysFoldIntoUseSiteDecoration>(irFunc);
}
else if (as<NoInlineAttribute>(modifier))
{
getBuilder()->addSimpleDecoration<IRNoInlineDecoration>(irFunc);
}
else if (as<DerivativeGroupQuadAttribute>(modifier))
{
derivativeGroupQuadDecor =
getBuilder()->addSimpleDecoration<IRDerivativeGroupQuadDecoration>(irFunc);
}
else if (as<DerivativeGroupLinearAttribute>(modifier))
{
derivativeGroupLinearDecor =
getBuilder()->addSimpleDecoration<IRDerivativeGroupLinearDecoration>(irFunc);
}
else if (as<MaximallyReconvergesAttribute>(modifier))
{
getBuilder()->addSimpleDecoration<IRMaximallyReconvergesDecoration>(irFunc);
}
else if (as<QuadDerivativesAttribute>(modifier))
{
getBuilder()->addSimpleDecoration<IRQuadDerivativesDecoration>(irFunc);
}
else if (as<RequireFullQuadsAttribute>(modifier))
{
getBuilder()->addSimpleDecoration<IRRequireFullQuadsDecoration>(irFunc);
}
else if (as<NoRefInlineAttribute>(modifier))
{
getBuilder()->addSimpleDecoration<IRNoRefInlineDecoration>(irFunc);
}
else if (auto instanceAttr = as<InstanceAttribute>(modifier))
{
IRIntLit* intLit = _getIntLitFromAttribute(getBuilder(), instanceAttr);
getBuilder()->addDecoration(irFunc, kIROp_InstanceDecoration, intLit);
}
else if (auto maxVertCountAttr = as<MaxVertexCountAttribute>(modifier))
{
IRIntLit* intLit = _getIntLitFromAttribute(getBuilder(), maxVertCountAttr);
getBuilder()->addDecoration(irFunc, kIROp_MaxVertexCountDecoration, intLit);
}
else if (auto numThreadsAttr = as<NumThreadsAttribute>(modifier))
{
LoweredValInfo extents[3];
for (int i = 0; i < 3; ++i)
{
extents[i] = numThreadsAttr->specConstExtents[i]
? emitDeclRef(
context,
numThreadsAttr->specConstExtents[i],
lowerType(
context,
getType(
context->astBuilder,
numThreadsAttr->specConstExtents[i])))
: lowerVal(context, numThreadsAttr->extents[i]);
}
numThreadsDecor = as<IRNumThreadsDecoration>(getBuilder()->addNumThreadsDecoration(
irFunc,
getSimpleVal(context, extents[0]),
getSimpleVal(context, extents[1]),
getSimpleVal(context, extents[2])));
numThreadsDecor->sourceLoc = numThreadsAttr->loc;
}
else if (auto waveSizeAttr = as<WaveSizeAttribute>(modifier))
{
getBuilder()->addWaveSizeDecoration(
irFunc,
getSimpleVal(context, lowerVal(context, waveSizeAttr->numLanes)));
}
else if (as<ReadNoneAttribute>(modifier))
{
getBuilder()->addSimpleDecoration<IRReadNoneDecoration>(irFunc);
}
else if (as<NoSideEffectAttribute>(modifier))
{
getBuilder()->addSimpleDecoration<IRNoSideEffectDecoration>(irFunc);
}
else if (as<EarlyDepthStencilAttribute>(modifier))
{
getBuilder()->addSimpleDecoration<IREarlyDepthStencilDecoration>(irFunc);
}
else if (auto domainAttr = as<DomainAttribute>(modifier))
{
IRStringLit* stringLit = _getStringLitFromAttribute(getBuilder(), domainAttr);
getBuilder()->addDecoration(irFunc, kIROp_DomainDecoration, stringLit);
}
else if (auto partitionAttr = as<PartitioningAttribute>(modifier))
{
IRStringLit* stringLit = _getStringLitFromAttribute(getBuilder(), partitionAttr);
getBuilder()->addDecoration(irFunc, kIROp_PartitioningDecoration, stringLit);
}
else if (auto outputTopAttr = as<OutputTopologyAttribute>(modifier))
{
IRStringLit* stringLit = _getStringLitFromAttribute(getBuilder(), outputTopAttr);
const auto topologyType =
convertOutputTopologyStringToEnum(stringLit->getStringSlice());
IRInst* topologyTypeInst = getBuilder()->getIntValue(
getBuilder()->getIntType(),
IRIntegerValue(topologyType));
auto outputTopologyDecoration = getBuilder()->addDecoration(
irFunc,
kIROp_OutputTopologyDecoration,
stringLit,
topologyTypeInst);
outputTopologyDecoration->sourceLoc = outputTopAttr->loc;
}
else if (auto maxTessFactortAttr = as<MaxTessFactorAttribute>(modifier))
{
IRFloatLit* floatLit = _getFloatFromAttribute(getBuilder(), maxTessFactortAttr);
getBuilder()->addDecoration(irFunc, kIROp_MaxTessFactorDecoration, floatLit);
}
else if (auto outputCtrlPtAttr = as<OutputControlPointsAttribute>(modifier))
{
IRIntLit* intLit = _getIntLitFromAttribute(getBuilder(), outputCtrlPtAttr);
getBuilder()->addDecoration(irFunc, kIROp_OutputControlPointsDecoration, intLit);
}
else if (auto spvInstOpAttr = as<SPIRVInstructionOpAttribute>(modifier))
{
auto builder = getBuilder();
IRIntLit* intLit = _getIntLitFromAttribute(builder, spvInstOpAttr, 0);
IRStringLit* setStringLit = nullptr;
if (spvInstOpAttr->args.getCount() > 1)
{
IRStringLit* checkSetStringLit =
_getStringLitFromAttribute(builder, spvInstOpAttr, 1);
if (checkSetStringLit && checkSetStringLit->getStringSlice().getLength() > 0)
{
setStringLit = checkSetStringLit;
}
}
// If it has a `set` defined, set it on the decoration
if (setStringLit)
{
builder->addDecoration(irFunc, kIROp_SPIRVOpDecoration, intLit, setStringLit);
}
else
{
builder->addDecoration(irFunc, kIROp_SPIRVOpDecoration, intLit);
}
}
else if (as<UnsafeForceInlineEarlyAttribute>(modifier))
{
getBuilder()->addDecoration(irFunc, kIROp_UnsafeForceInlineEarlyDecoration);
isInline = true;
}
else if (as<ForceInlineAttribute>(modifier))
{
getBuilder()->addDecoration(irFunc, kIROp_ForceInlineDecoration);
isInline = true;
}
else if (as<TreatAsDifferentiableAttribute>(modifier))
{
getBuilder()->addDecoration(irFunc, kIROp_TreatAsDifferentiableDecoration);
}
else if (auto intrinsicOp = as<IntrinsicOpModifier>(modifier))
{
auto op = getBuilder()->getIntValue(getBuilder()->getIntType(), intrinsicOp->op);
getBuilder()->addDecoration(irFunc, kIROp_IntrinsicOpDecoration, op);
isInline = true;
}
else if (
as<UserDefinedDerivativeAttribute>(modifier) ||
as<PrimalSubstituteAttribute>(modifier))
{
// We need to lower the decl ref to the custom derivative function to IR.
// The IR insts correspond to the decl ref is not part of the function we
// are processing. If we emit it directly to within the function, it could
// mess up the assumption on the form of the IR (e.g. having non decoration insts
// appearing in the middle of decoration insts). so we emit the decl ref to the
// function's parent for now.
subContext->irBuilder->setInsertInto(irFunc->getParent());
Expr* funcExpr = nullptr;
if (auto udAttr = as<UserDefinedDerivativeAttribute>(modifier))
funcExpr = udAttr->funcExpr;
else if (auto primalAttr = as<PrimalSubstituteAttribute>(modifier))
funcExpr = primalAttr->funcExpr;
DeclRefExpr* declRefExpr = as<DeclRefExpr>(funcExpr);
auto funcType = lowerType(subContext, funcExpr->type);
auto loweredVal = emitDeclRef(subContext, declRefExpr->declRef, funcType);
SLANG_RELEASE_ASSERT(loweredVal.flavor == LoweredValInfo::Flavor::Simple);
IRInst* derivativeFunc = loweredVal.val;
if (as<ForwardDerivativeAttribute>(modifier))
getBuilder()->addForwardDerivativeDecoration(irFunc, derivativeFunc);
else if (as<BackwardDerivativeAttribute>(modifier))
getBuilder()->addUserDefinedBackwardDerivativeDecoration(
irFunc,
derivativeFunc);
else
getBuilder()->addPrimalSubstituteDecoration(irFunc, derivativeFunc);
// Reset cursor.
subContext->irBuilder->setInsertInto(irFunc);
}
else if (as<ForwardDifferentiableAttribute>(modifier))
{
getBuilder()->addForwardDifferentiableDecoration(irFunc);
}
else if (as<BackwardDifferentiableAttribute>(modifier))
{
getBuilder()->addBackwardDifferentiableDecoration(irFunc);
}
else if (as<TreatAsDifferentiableAttribute>(modifier))
{
getBuilder()->addDecoration(irFunc, kIROp_TreatAsDifferentiableDecoration);
}
else if (as<PreferCheckpointAttribute>(modifier))
{
getBuilder()->addDecoration(irFunc, kIROp_PreferCheckpointDecoration);
}
else if (auto attr = as<PreferRecomputeAttribute>(modifier))
{
getBuilder()->addDecoration(
irFunc,
kIROp_PreferRecomputeDecoration,
getBuilder()->getIntValue(
getBuilder()->getIntType(),
attr->sideEffectBehavior));
}
else if (auto extensionMod = as<RequiredGLSLExtensionModifier>(modifier))
getBuilder()->addRequireGLSLExtensionDecoration(
irFunc,
extensionMod->extensionNameToken.getContent());
else if (auto versionMod = as<RequiredGLSLVersionModifier>(modifier))
getBuilder()->addRequireGLSLVersionDecoration(
irFunc,
Int(getIntegerLiteralValue(versionMod->versionNumberToken)));
else if (auto spvVersion = as<RequiredSPIRVVersionModifier>(modifier))
getBuilder()->addRequireSPIRVVersionDecoration(irFunc, spvVersion->version);
else if (auto wgslExtensionMod = as<RequiredWGSLExtensionModifier>(modifier))
getBuilder()->addRequireWGSLExtensionDecoration(
irFunc,
wgslExtensionMod->extensionNameToken.getContent());
else if (auto cudasmVersion = as<RequiredCUDASMVersionModifier>(modifier))
getBuilder()->addRequireCUDASMVersionDecoration(irFunc, cudasmVersion->version);
else if (as<NonDynamicUniformAttribute>(modifier))
getBuilder()->addDecoration(irFunc, kIROp_NonDynamicUniformReturnDecoration);
}
verifyComputeDerivativeGroupModifiers(
getSink(),
decl->loc,
derivativeGroupQuadDecor,
derivativeGroupLinearDecor,
numThreadsDecor);
if (!isInline)
{
// If there are any constant expr rate parameters, we should inline this function.
// TODO: consider specializing them instead of inlining.
for (auto param : decl->getParameters())
{
if (param->hasModifier<ConstExprModifier>())
{
getBuilder()->addDecoration(irFunc, kIROp_ForceInlineDecoration);
isInline = true;
break;
}
}
}
// Add debugfunction decoration and emit debug function. This
// is needed for emitting debug information
auto nameHint = irFunc->findDecoration<IRNameHintDecoration>();
IRStringLit* nameOperand = nameHint ? as<IRStringLit>(nameHint->getNameOperand()) : nullptr;
if (nameOperand)
{
getBuilder()->setInsertInto(getBuilder()->getModule()->getModuleInst());
auto locationDecor = irFunc->findDecoration<IRDebugLocationDecoration>();
IRInst* debugType = irFunc->getDataType();
if (locationDecor && debugType)
{
auto debugFuncCallee = getBuilder()->emitDebugFunction(
nameOperand,
locationDecor->getLine(),
locationDecor->getCol(),
locationDecor->getSource(),
debugType);
// Add a decoration to link the function to its debug function
getBuilder()->addDecoration(irFunc, kIROp_DebugFuncDecoration, debugFuncCallee);
}
}
// 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();
// If this function is defined inside an interface, add a reference to the IRFunc from
// the interface's type definition.
auto finalVal = finishOuterGenerics(subBuilder, irFunc, outerGeneric);
for (auto modifier : decl->modifiers)
{
if (as<DerivativeOfAttribute>(modifier) || as<PrimalSubstituteOfAttribute>(modifier))
{
Expr* funcExpr = nullptr;
Expr* backDeclRef = nullptr;
if (auto attr = as<DerivativeOfAttribute>(modifier))
{
funcExpr = attr->funcExpr;
backDeclRef = attr->backDeclRef;
}
else if (auto primalAttr = as<PrimalSubstituteOfAttribute>(modifier))
{
funcExpr = primalAttr->funcExpr;
backDeclRef = primalAttr->backDeclRef;
}
if (auto originalDeclRefExpr = as<DeclRefExpr>(funcExpr))
{
NestedContext originalContextFunc(this);
auto originalSubBuilder = originalContextFunc.getBuilder();
auto originalSubContext = originalContextFunc.getContext();
if (auto outterGeneric = getOuterGeneric(irFunc))
originalSubBuilder->setInsertBefore(outterGeneric);
else
originalSubBuilder->setInsertBefore(irFunc);
auto originalFuncDecl =
as<FunctionDeclBase>(originalDeclRefExpr->declRef.getDecl());
SLANG_RELEASE_ASSERT(originalFuncDecl);
auto originalFuncVal = lowerFuncDeclInContext(
originalSubContext,
originalSubBuilder,
originalFuncDecl,
false)
.val;
if (auto originalFuncGeneric = as<IRGeneric>(originalFuncVal))
{
originalFuncVal = findGenericReturnVal(originalFuncGeneric);
}
originalSubBuilder->setInsertBefore(originalFuncVal);
auto derivativeFuncVal = lowerRValueExpr(originalSubContext, backDeclRef);
if (as<ForwardDerivativeOfAttribute>(modifier))
{
originalSubBuilder->addForwardDerivativeDecoration(
originalFuncVal,
derivativeFuncVal.val);
getBuilder()->addForwardDifferentiableDecoration(irFunc);
}
else if (as<BackwardDerivativeOfAttribute>(modifier))
{
originalSubBuilder->addUserDefinedBackwardDerivativeDecoration(
originalFuncVal,
derivativeFuncVal.val);
}
else
{
originalSubBuilder->addPrimalSubstituteDecoration(
originalFuncVal,
derivativeFuncVal.val);
}
}
subContext->irBuilder->setInsertInto(irFunc);
finalVal->moveToEnd();
}
}
return LoweredValInfo::simple(finalVal);
}
LoweredValInfo lowerFuncDecl(FunctionDeclBase* decl)
{
// We are going to use a nested builder, because we will
// change the parent node that things get nested into.
//
NestedContext nestedContextFunc(this);
auto subBuilder = nestedContextFunc.getBuilder();
auto subContext = nestedContextFunc.getContext();
return lowerFuncDeclInContext(subContext, subBuilder, decl);
}
LoweredValInfo visitGenericDecl(GenericDecl* genDecl)
{
return ensureDecl(context, genDecl->inner);
}
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 declarations 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 = as<FunctionDeclBase>(primaryDecl);
SLANG_ASSERT(primaryFuncDecl);
LoweredValInfo result = lowerFuncDecl(primaryFuncDecl);
for (auto dd = primaryDecl->nextDecl; dd; dd = dd->nextDecl)
{
auto funcDecl = as<FunctionDeclBase>(dd);
SLANG_ASSERT(funcDecl);
lowerFuncDecl(funcDecl);
// Note: Because we are iterating over multiple declarations,
// but only one will be registered as the value for `decl`
// in the global mapping by `ensureDecl()`, we have to take
// responsibility here for registering a lowered value
// for the remaining (non-primary) declarations.
//
// It doesn't really matter which one we register here, because
// they will all have the same mangled name in the IR, but we
// default to the `result` that is returned from this visitor,
// so that all the declarations share the same IR representative.
//
context->setGlobalValue(funcDecl, result);
}
return result;
}
};
LoweredValInfo lowerDecl(IRGenContext* context, DeclBase* decl)
{
IRBuilderSourceLocRAII sourceLocInfo(context->irBuilder, decl->loc);
DeclLoweringVisitor visitor;
visitor.context = context;
try
{
return visitor.dispatch(decl);
}
// Don't emit any context message for an explicit `AbortCompilationException`
// because it should only happen when an error is already emitted.
catch (const AbortCompilationException&)
{
throw;
}
catch (...)
{
context->getSink()->noteInternalErrorLoc(decl->loc);
throw;
}
}
// We will probably want to put the
LoweredValInfo* _findLoweredValInfo(IRGenContext* context, Decl* decl)
{
// Look for an existing value installed in this context
auto env = context->env;
while (env)
{
if (auto result = env->mapDeclToValue.tryGetValue(decl))
return result;
env = env->outer;
}
return nullptr;
}
// Ensure that a version of the given declaration has been emitted to the IR
LoweredValInfo ensureDecl(IRGenContext* context, Decl* decl)
{
if (auto valInfoPtr = _findLoweredValInfo(context, decl))
{
return *valInfoPtr;
}
// If we have a decl that's a generic value/type decl then something has gone seriously
// wrong
if (as<GenericValueParamDecl>(decl) || as<GenericTypeParamDecl>(decl))
{
SLANG_UNEXPECTED("Generic type/value shouldn't be handled here!");
}
IRBuilder subIRBuilder(context->irBuilder->getModule());
if (as<VarDecl>(decl) && decl->findModifier<LocalTempVarModifier>())
{
// Do not modify insert location.
subIRBuilder.setInsertLoc(context->irBuilder->getInsertLoc());
}
else
{
subIRBuilder.setInsertInto(subIRBuilder.getModule());
}
IRGenEnv subEnv;
subEnv.outer = context->env;
IRGenContext subContext = *context;
subContext.irBuilder = &subIRBuilder;
subContext.env = &subEnv;
auto result = lowerDecl(&subContext, decl);
// By default assume that any value we are lowering represents
// something that should be installed globally.
context->setGlobalValue(decl, result);
return result;
}
// Can the IR lowered version of this declaration ever be an `IRGeneric`?
bool canDeclLowerToAGeneric(Decl* decl)
{
// A callable decl lowers to an `IRFunc`, and can be generic
if (as<CallableDecl>(decl))
return true;
// An aggregate type decl lowers to an `IRStruct`, and can be generic
if (as<AggTypeDecl>(decl))
return true;
// An inheritance decl lowers to an `IRWitnessTable`, and can be generic
if (as<InheritanceDecl>(decl))
return true;
// A `typedef` declaration nested under a generic will turn into
// a generic that returns a type (a simple type-level function).
if (as<TypeDefDecl>(decl))
return true;
// A static member variable declaration can be lowered into a generic.
if (auto varDecl = as<VarDecl>(decl))
{
if (varDecl->hasModifier<HLSLStaticModifier>())
{
return !isFunctionVarDecl(varDecl);
}
}
return false;
}
/// Add flattened "leaf" elements from `val` to the `ioArgs` list
static void _addFlattenedTupleArgs(List<IRInst*>& ioArgs, IRInst* val)
{
if (auto tupleVal = as<IRMakeTuple>(val))
{
// If the value is a tuple, we can add its element directly.
auto elementCount = tupleVal->getOperandCount();
for (UInt i = 0; i < elementCount; ++i)
{
_addFlattenedTupleArgs(ioArgs, tupleVal->getOperand(i));
}
}
//
// TODO: We should handle the case here where `val`
// is not a `makeTuple` instruction, but still has
// a tuple *type*. In that case we should apply `getTupleElement`
// for each of its elements and then recurse on them.
//
else
{
ioArgs.add(val);
}
}
bool isAbstractWitnessTable(IRInst* inst)
{
if (as<IRThisTypeWitness>(inst) || as<IRInterfaceRequirementEntry>(inst))
return true;
if (auto lookup = as<IRLookupWitnessMethod>(inst))
return isAbstractWitnessTable(lookup->getWitnessTable());
return false;
}
static IRInst* maybeCloneThisTypeWitness(
IRGenContext* context,
IRInst* thisTypeWitness,
Type* thisType)
{
auto currentInsertLoc = context->irBuilder->getInsertLoc().getParent();
auto parentOfThisTypeWitness = thisTypeWitness->parent;
while (currentInsertLoc != nullptr)
{
// If current insert location is same as scope of ThisTypeWitness, don't copy it.
if (parentOfThisTypeWitness == currentInsertLoc)
{
return thisTypeWitness;
}
currentInsertLoc = currentInsertLoc->parent;
}
auto thisTypeIR = as<IRThisType>(lowerType(context, thisType));
SLANG_RELEASE_ASSERT(thisTypeIR);
auto newThisTypeWitness =
context->irBuilder->createThisTypeWitness((IRType*)thisTypeIR->getConstraintType());
return newThisTypeWitness;
}
LoweredValInfo emitDeclRef(IRGenContext* context, Decl* decl, DeclRefBase* subst, IRType* type)
{
const auto initialSubst = subst;
SLANG_UNUSED(initialSubst);
if (as<ThisTypeDecl>(decl))
{
// A declref to ThisType decl should be lowered differently
// from other decls. In general, IFoo<T>.ThisType should lower to
// ThisType(specialize(IFoo,T)) instead of specialize(IFoo.ThisType, T).
SLANG_ASSERT(subst->getDecl() == decl);
IRType* parentInterfaceType = nullptr;
if (auto lookupDeclRef = as<LookupDeclRef>(subst))
{
parentInterfaceType = lowerType(context, lookupDeclRef->getWitness()->getSup());
}
else
{
parentInterfaceType =
lowerType(context, DeclRefType::create(context->astBuilder, subst->getParent()));
}
auto thisType = context->irBuilder->getThisType(parentInterfaceType);
return LoweredValInfo::simple(thisType);
}
// We need to proceed by considering the specializations that
// have been put in place.
subst = SubstitutionSet(subst).getInnerMostNodeWithSubstInfo();
// If the declaration would not get wrapped in a `IRGeneric`,
// even if it is nested inside of an AST `GenericDecl`, then
// we should also ignore any generic substitutions.
if (!canDeclLowerToAGeneric(decl))
{
while (auto genericSubst = SubstitutionSet(subst).findGenericAppDeclRef())
subst = genericSubst->getBase();
}
// In the simplest case, there is no specialization going
// on, and the decl-ref turns into a reference to the
// lowered IR value for the declaration.
if (!SubstitutionSet(subst) || _isTrivialLookupFromInterfaceThis(context, subst))
{
LoweredValInfo loweredDecl = ensureDecl(context, decl);
return loweredDecl;
}
// Otherwise, we look at the kind of substitution, and let it guide us.
if (auto genericSubst = as<GenericAppDeclRef>(subst))
{
// A generic substitution means we will need to output
// a `specialize` instruction to specialize the generic.
//
// First we want to emit the value without generic specialization
// applied, to get a correct value for it.
//
// Note: we only "unwrap" a single layer from the
// substitutions here, because the underlying declaration
// might be nested in multiple generics, or it might
// come from an interface.
//
LoweredValInfo genericVal = emitDeclRef(
context,
decl,
genericSubst->getBase(),
context->irBuilder->getGenericKind());
// There's no reason to specialize something that maps to a NULL pointer.
if (genericVal.flavor == LoweredValInfo::Flavor::None)
return LoweredValInfo();
// We can only really specialize things that map to single values.
// It would be an error if we got a non-`None` value that
// wasn't somehow a single value.
genericVal = materialize(context, genericVal);
auto irGenericVal = genericVal.val;
SLANG_ASSERT(irGenericVal);
// We have the IR value for the generic we'd like to specialize,
// and now we need to get the value for the arguments.
List<IRInst*> irArgs;
for (auto argVal : genericSubst->getArgs())
{
auto irArgVal = lowerSimpleVal(context, argVal);
if (!irArgVal)
continue;
// It is possible that some of the arguments to the generic
// represent conformances to conjunction types like `A & B`.
// These conjunction conformances will appear as tuples in
// the IR, and we want to "flatten" them here so that we
// pass each "leaf" witness table as its own argument (to
// match the way that generic parameters are being emitted
// to the IR).
//
// TODO: This isn't a robust strategy if we ever have to deal
// with tuples as ordinary values.
//
_addFlattenedTupleArgs(irArgs, irArgVal);
}
// Once we have both the generic and its arguments,
// we can emit a `specialize` instruction and use
// its value as the result.
auto irSpecializedVal = context->irBuilder->emitSpecializeInst(
type,
irGenericVal,
irArgs.getCount(),
irArgs.getBuffer());
switch (genericVal.flavor)
{
case LoweredValInfo::Flavor::Simple:
return LoweredValInfo::simple(irSpecializedVal);
case LoweredValInfo::Flavor::Ptr:
return LoweredValInfo::ptr(irSpecializedVal);
default:
SLANG_UNEXPECTED("unhandled lowered value flavor");
UNREACHABLE_RETURN(LoweredValInfo());
}
}
else if (auto thisTypeSubst = as<LookupDeclRef>(subst))
{
if (as<ThisTypeDecl>(decl))
{
// This is a reference to the ThisType from the interface,
// therefore we should just lower it as the sub type.
return lowerType(context, thisTypeSubst->getWitness()->getSub());
}
if (isInterfaceRequirement(decl))
{
// If we reach here, somebody is trying to look up an interface
// requirement "through" some concrete type. We need to lower this
// decl-ref as a lookup of the corresponding member in a witness
// table.
//
// The witness table itself is referenced by the this-type
// substitution, so we can just lower that.
//
// Note: unlike the case for generics above, in the interface-lookup
// case, we don't end up caring about any further outer substitutions.
// That is because even if we are naming `ISomething<Foo>.doIt()`,
// a method inside a generic interface, we don't actually care
// about the substitution of `Foo` for the parameter `T` of
// `ISomething<T>`. That is because we really care about the
// witness table for the concrete type that conforms to `ISomething<Foo>`.
//
auto irWitnessTable = lowerSimpleVal(context, thisTypeSubst->getWitness());
SLANG_RELEASE_ASSERT(irWitnessTable);
if (isAbstractWitnessTable(irWitnessTable))
{
// Copy ThisTypeWitness locally if necessary
irWitnessTable = maybeCloneThisTypeWitness(
context,
irWitnessTable,
thisTypeSubst->getLookupSource());
}
auto irRequirementKey = getInterfaceRequirementKey(context, decl);
auto irLookupWitness = context->irBuilder->emitLookupInterfaceMethodInst(
type,
irWitnessTable,
irRequirementKey);
return LoweredValInfo::simple(irLookupWitness);
}
else
{
// This case is a reference to a member declaration of the interface
// (or added by an extension of the interface) that does *not*
// represent a requirement of the interface.
//
// Our policy is that concrete methods/members on an interface type
// are lowered as generics, where the generic parameter represents
// the `ThisType`.
//
auto genericVal = emitDeclRef(
context,
decl,
thisTypeSubst->getBase(),
context->irBuilder->getGenericKind());
auto irGenericVal = getSimpleVal(context, genericVal);
// In order to reference the member for a particular type, we
// specialize the generic for that type.
//
IRInst* irSubType = lowerType(context, thisTypeSubst->getWitness()->getSub());
IRInst* irSubTypeWitness = lowerSimpleVal(context, thisTypeSubst->getWitness());
IRInst* irSpecializeArgs[] = {irSubType, irSubTypeWitness};
auto irSpecializedVal =
context->irBuilder->emitSpecializeInst(type, irGenericVal, 2, irSpecializeArgs);
return LoweredValInfo::simple(irSpecializedVal);
}
}
else
{
SLANG_UNEXPECTED("uhandled substitution type");
UNREACHABLE_RETURN(LoweredValInfo());
}
}
LoweredValInfo emitDeclRef(IRGenContext* context, DeclRef<Decl> declRef, IRType* type)
{
return emitDeclRef(context, declRef.getDecl(), declRef.declRefBase, type);
}
static void lowerFrontEndEntryPointToIR(
IRGenContext* context,
EntryPoint* entryPoint,
String moduleName)
{
// TODO: We should emit an entry point as a dedicated IR function
// (distinct from the IR function used if it were called normally),
// with a mangled name based on the original function name plus
// the stage for which it is being compiled as an entry point (so
// that entry points for distinct stages always have distinct names).
//
// For now we just have an (implicit) constraint that a given
// function should only be used as an entry point for one stage,
// and any such function should *not* be used as an ordinary function.
auto entryPointFuncDecl = entryPoint->getFuncDecl();
if (!entryPointFuncDecl->findModifier<EntryPointAttribute>())
{
// If the entry point doesn't have an explicit `[shader("...")]` attribute,
// then we make sure to add one here, so the lowering logic knows it is an
// entry point.
auto entryPointAttr = context->astBuilder->create<EntryPointAttribute>();
entryPointAttr->capabilitySet = entryPoint->getProfile().getCapabilityName();
addModifier(entryPointFuncDecl, entryPointAttr);
}
auto builder = context->irBuilder;
builder->setInsertInto(builder->getModule()->getModuleInst());
auto loweredEntryPointFunc = getSimpleVal(context, ensureDecl(context, entryPointFuncDecl));
// Attach a marker decoration so that we recognize
// this as an entry point.
//
IRInst* instToDecorate = loweredEntryPointFunc;
if (auto irGeneric = as<IRGeneric>(instToDecorate))
{
instToDecorate = findGenericReturnVal(irGeneric);
}
// If the entry-point decorations has already been created (because the user
// specified duplicate entries in the entry point list), we can stop now.
if (instToDecorate->findDecoration<IREntryPointDecoration>())
return;
{
Name* entryPointName = entryPoint->getFuncDecl()->getName();
builder->addEntryPointDecoration(
instToDecorate,
entryPoint->getProfile(),
entryPointName->text.getUnownedSlice(),
moduleName.getUnownedSlice());
}
}
static void lowerProgramEntryPointToIR(
IRGenContext* context,
EntryPoint* entryPoint,
EntryPoint::EntryPointSpecializationInfo* specializationInfo)
{
auto entryPointFuncDeclRef = entryPoint->getFuncDeclRef();
if (specializationInfo)
entryPointFuncDeclRef = specializationInfo->specializedFuncDeclRef;
// First, lower the entry point like an ordinary function
auto entryPointFuncType =
lowerType(context, getFuncType(context->astBuilder, entryPointFuncDeclRef));
auto builder = context->irBuilder;
builder->setInsertInto(builder->getModule()->getModuleInst());
auto loweredEntryPointFunc =
getSimpleVal(context, emitDeclRef(context, entryPointFuncDeclRef, entryPointFuncType));
if (!loweredEntryPointFunc->findDecoration<IRLinkageDecoration>())
{
builder->addExportDecoration(
loweredEntryPointFunc,
getMangledName(context->astBuilder, entryPointFuncDeclRef).getUnownedSlice());
}
// We may have shader parameters of interface/existential type,
// which need us to supply concrete type information for specialization.
//
if (specializationInfo && specializationInfo->existentialSpecializationArgs.getCount() != 0)
{
List<IRInst*> existentialSlotArgs;
for (auto arg : specializationInfo->existentialSpecializationArgs)
{
auto irArgType = lowerSimpleVal(context, arg.val);
existentialSlotArgs.add(irArgType);
if (auto witness = arg.witness)
{
auto irWitnessTable = lowerSimpleVal(context, witness);
existentialSlotArgs.add(irWitnessTable);
}
}
builder->addBindExistentialSlotsDecoration(
loweredEntryPointFunc,
existentialSlotArgs.getCount(),
existentialSlotArgs.getBuffer());
}
stripFrontEndOnlyInstructions(builder->getModule(), IRStripOptions());
}
/// Ensure that `decl` and all relevant declarations under it get emitted.
static void ensureAllDeclsRec(IRGenContext* context, Decl* decl)
{
ensureDecl(context, decl);
// Note: We are checking here for aggregate type declarations, and
// not for `ContainerDecl`s in general. This is because many kinds
// of container declarations will already take responsibility for emitting
// their children directly (e.g., a function declaration is responsible
// for emitting its own parameters).
//
// Aggregate types are the main case where we can emit an outer declaration
// and not the stuff nested inside of it.
//
if (auto containerDecl = as<AggTypeDeclBase>(decl))
{
for (auto memberDecl : containerDecl->getDirectMemberDecls())
{
ensureAllDeclsRec(context, memberDecl);
}
}
else if (auto namespaceDecl = as<NamespaceDecl>(decl))
{
for (auto memberDecl : namespaceDecl->getDirectMemberDecls())
{
ensureAllDeclsRec(context, memberDecl);
}
}
else if (auto fileDecl = as<FileDecl>(decl))
{
for (auto memberDecl : fileDecl->getDirectMemberDecls())
{
ensureAllDeclsRec(context, memberDecl);
}
}
else if (auto genericDecl = as<GenericDecl>(decl))
{
ensureAllDeclsRec(context, genericDecl->inner);
}
}
RefPtr<IRModule> generateIRForTranslationUnit(
ASTBuilder* astBuilder,
TranslationUnitRequest* translationUnit)
{
SLANG_PROFILE;
SLANG_AST_BUILDER_RAII(astBuilder);
auto session = translationUnit->getSession();
auto compileRequest = translationUnit->compileRequest;
Linkage* linkage = compileRequest->getLinkage();
SharedIRGenContext sharedContextStorage(
session,
translationUnit->compileRequest->getSink(),
translationUnit->compileRequest->optionSet.shouldObfuscateCode(),
translationUnit->getModuleDecl(),
translationUnit->compileRequest->getLinkage());
SharedIRGenContext* sharedContext = &sharedContextStorage;
IRGenContext contextStorage(sharedContext, astBuilder);
IRGenContext* context = &contextStorage;
RefPtr<IRModule> module = IRModule::create(session);
module->setName(translationUnit->getModuleDecl()->getName());
IRBuilder builderStorage(module);
IRBuilder* builder = &builderStorage;
context->irBuilder = builder;
context->includeDebugInfo =
compileRequest->getLinkage()->m_optionSet.getDebugInfoLevel() != DebugInfoLevel::None;
// We need to emit IR for all public/exported symbols
// in the translation unit.
//
// If debug info is enabled, we emit the DebugSource insts for each source file into IR.
if (context->includeDebugInfo)
{
builder->setInsertInto(module->getModuleInst());
for (auto source : translationUnit->getSourceFiles())
{
auto debugSource = builder->emitDebugSource(
source->getPathInfo().getMostUniqueIdentity().getUnownedSlice(),
source->getContent(),
source->isIncludedFile());
context->shared->mapSourceFileToDebugSourceInst.add(source, debugSource);
}
}
// For now, we will assume that *all* global-scope declarations
// represent public/exported symbols.
// First, ensure that all entry points have been emitted,
// in case they require special handling.
for (auto entryPoint : translationUnit->getEntryPoints())
{
List<SourceFile*> sources = translationUnit->getSourceFiles();
SourceFile* source = sources.getFirst();
PathInfo pInfo = source->getPathInfo();
String path = pInfo.getMostUniqueIdentity();
lowerFrontEndEntryPointToIR(context, entryPoint, Path::getFileNameWithoutExt(path));
}
//
// Next, ensure that all other global declarations have
// been emitted.
for (auto decl : translationUnit->getModuleDecl()->getDirectMemberDecls())
{
ensureAllDeclsRec(context, decl);
}
// Build a global instruction to hold all the string
// literals used in the module.
{
auto& stringLits = sharedContext->m_stringLiterals;
auto stringLitCount = stringLits.getCount();
if (stringLitCount != 0)
{
builder->setInsertInto(module->getModuleInst());
builder->emitIntrinsicInst(
builder->getVoidType(),
kIROp_GlobalHashedStringLiterals,
stringLitCount,
stringLits.getBuffer());
}
}
if (auto nvapiSlotModifier =
translationUnit->getModuleDecl()->findModifier<NVAPISlotModifier>())
{
builder->addNVAPISlotDecoration(
module->getModuleInst(),
nvapiSlotModifier->registerName.getUnownedSlice(),
nvapiSlotModifier->spaceName.getUnownedSlice());
}
#if 0
if (compileRequest->optionSet.shouldDumpIR())
{
DiagnosticSinkWriter writer(compileRequest->getSink());
dumpIR(
module,
compileRequest->m_irDumpOptions,
"GENERATED",
compileRequest->getSourceManager(),
&writer);
}
#endif
validateIRModuleIfEnabled(compileRequest, module);
// We will perform certain "mandatory" optimization passes now.
// These passes serve two purposes:
//
// 1. To simplify the code that we use in backend compilation,
// or when serializing/deserializing modules, so that we can
// amortize this effort when we compile multiple entry points
// that use the same module(s).
//
// 2. To ensure certain semantic properties that can't be
// validated without dataflow information. For example, we want
// to detect when a variable might be used before it is initialized.
// Note: if you need to debug the IR that is created before
// any mandatory optimizations have been applied, then
// uncomment this line while debugging.
// dumpIR(module);
// Before we can do any validation, we need to prelink [unsafeForceInlineEarly]
// functions.
prelinkIR(translationUnit->module, module, context->shared->externalSymbolsToPrelink);
// First, lower error handling logic into normal control flow.
// This includes lowering throwing functions into functions that
// returns a `Result<T,E>` value, translating `tryCall` into
// normal `call` + `ifElse`, etc.
lowerErrorHandling(module, compileRequest->getSink());
// Lower `defer` so that later passes need not be aware of it.
lowerDefer(module, compileRequest->getSink());
// Synthesize some code we want to make sure is inlined and simplified
synthesizeBitFieldAccessors(module);
// Lower `IRExpandType` types to use `IRExpand`, where the pattern type
// is nested inside the `IRExpand` as its children, instead of being same
// level entities as the ExpandType itself.
// This will unify the specialization logic for both type and value level
// expansion.
lowerExpandType(module);
// Generate DebugValue insts to store values into debug variables,
// if debug symbols are enabled.
if (context->includeDebugInfo)
{
insertDebugValueStore(context->shared->debugValueContext, module);
}
// Next, attempt to promote local variables to SSA
// temporaries and do basic simplifications.
//
constructSSA(module);
applySparseConditionalConstantPropagation(module, compileRequest->getSink());
bool minimumOptimizations =
linkage->m_optionSet.getBoolOption(CompilerOptionName::MinimumSlangOptimization);
if (!minimumOptimizations)
{
simplifyCFG(module, CFGSimplificationOptions::getDefault());
auto peepholeOptions = PeepholeOptimizationOptions::getPrelinking();
peepholeOptimize(nullptr, module, peepholeOptions);
}
IRDeadCodeEliminationOptions dceOptions = IRDeadCodeEliminationOptions();
dceOptions.keepExportsAlive = true;
dceOptions.keepLayoutsAlive = true;
dceOptions.useFastAnalysis = true;
for (auto inst : module->getGlobalInsts())
{
if (auto func = as<IRGlobalValueWithCode>(inst))
eliminateDeadCode(func, dceOptions);
}
// Where possible, move loop condition checks to the end of loops, and wrap
// the loop in an 'if(condition)'.
// This makes it so that if sccp can see that the loop will always loop
// at least once it can record this information by removing the outer
// conditional.
// This has advantages:
// - Uninitialized variable usage detection doesn't have to
// worry about a loop never being executed.
// - The loop condition is evaluated one fewer times.
// - Allegedly better performance on pipelined processors:
// https://en.wikipedia.org/wiki/Loop_inversion
//
// And disadvantages
// - If sccp is unable to eliminate the outer 'if' then we end up with
// duplicated code the the conditional value. Users don't tend to put
// huge gobs of code in the conditional expression in loops however.
if (compileRequest->getLinkage()->m_optionSet.getBoolOption(CompilerOptionName::LoopInversion))
{
invertLoops(module);
}
// Next, inline calls to any functions that have been
// marked for mandatory "early" inlining.
//
// Note: We performed certain critical simplifications
// above, before this step, so that the body of functions
// subject to mandatory inlining can be simplified ahead
// of time. By simplifying the body before inlining it,
// we can make sure that things like superfluous temporaries
// are eliminated from the callee, and not copied into
// call sites.
//
InstHashSet modifiedFuncs(module);
for (;;)
{
bool changed = false;
modifiedFuncs.clear();
changed = performMandatoryEarlyInlining(module, &modifiedFuncs.getHashSet());
if (changed)
{
changed = peepholeOptimizeGlobalScope(nullptr, module);
if (!minimumOptimizations)
{
for (auto func : modifiedFuncs.getHashSet())
{
auto codeInst = as<IRGlobalValueWithCode>(func);
changed |= constructSSA(func);
changed |=
applySparseConditionalConstantPropagation(func, compileRequest->getSink());
changed |= peepholeOptimize(nullptr, func);
changed |= simplifyCFG(codeInst, CFGSimplificationOptions::getFast());
eliminateDeadCode(func, dceOptions);
}
}
}
if (!changed)
break;
}
if (compileRequest->getLinkage()->m_optionSet.shouldRunNonEssentialValidation())
{
// We don't allow recursive types.
checkForRecursiveTypes(module, compileRequest->getSink());
if (compileRequest->getSink()->getErrorCount() != 0)
return module;
// Propagate `constexpr`-ness through the dataflow graph (and the
// call graph) based on constraints imposed by different instructions.
propagateConstExpr(module, compileRequest->getSink());
// Check for using uninitialized values
checkForUsingUninitializedValues(module, compileRequest->getSink());
// TODO: give error messages if any `undefined` or
// instructions remain.
checkForMissingReturns(module, compileRequest->getSink(), CodeGenTarget::None, true);
// Check for invalid differentiable function body.
checkAutoDiffUsages(module, compileRequest->getSink());
checkForOperatorShiftOverflow(module, linkage->m_optionSet, compileRequest->getSink());
}
// The "mandatory" optimization passes may make use of the
// `IRHighLevelDeclDecoration` type to relate IR instructions
// back to AST-level code in order to improve the quality
// of diagnostics that are emitted.
//
// While it is important for these passes to have access
// to AST-level information, allowing that information to
// flow into later steps (e.g., code generation) could lead
// to unclean layering of the parts of the compiler.
// In principle, back-end steps should not need to know where
// IR code came from.
//
// In order to avoid problems, we run a pass here to strip
// out any decorations that should not be relied upon by
// later passes.
//
{
// Because we are already stripping out undesired decorations,
// this is also a convenient place to remove any `IRNameHintDecoration`s
// in the case where we are obfuscating code. We handle this
// by setting up the options for the stripping pass appropriately.
//
IRStripOptions stripOptions;
stripOptions.shouldStripNameHints = linkage->m_optionSet.shouldObfuscateCode();
// If we are generating an obfuscated source map, we don't want to strip locs,
// we want to generate *new* locs that can be mapped (via source map)
// back to *actual* source.
//
// We don't do the obfuscation remapping here, because DCE and other passes may
// change what locs are actually needed, we need to be sure
// that if we have obfuscation enabled we don't forget to obfuscate.
stripOptions.stripSourceLocs = false;
stripFrontEndOnlyInstructions(module, stripOptions);
stripImportedWitnessTable(module);
// Stripping out decorations could leave some dead code behind
// in the module, and in some cases that extra code is also
// undesirable (e.g., the string literals referenced by name-hint
// decorations are just as undesirable as the decorations themselves).
// To clean up after ourselves we also run a dead-code elimination
// pass here, but make sure to set our options so that we don't
// eliminate anything that has been marked for export.
//
eliminateDeadCode(module, dceOptions);
if (stripOptions.shouldStripNameHints && linkage->m_optionSet.shouldHaveSourceMap())
{
// The obfuscated source map is stored on the module
obfuscateModuleLocs(module, compileRequest->getSourceManager());
}
}
// TODO: consider doing some more aggressive optimizations
// (in particular specialization of generics) here, so
// that we can avoid doing them downstream.
//
// Note: doing specialization or inlining involving code
// from other modules potentially makes the IR we generate
// "fragile" in that we'd now need to recompile when
// a module we depend on changes.
validateIRModuleIfEnabled(compileRequest, module);
// If we are being asked to dump IR during compilation,
// then we can dump the initial IR for the module here.
if (compileRequest->optionSet.shouldDumpIR())
{
DiagnosticSinkWriter writer(compileRequest->getSink());
dumpIR(
module,
compileRequest->m_irDumpOptions,
"LOWER-TO-IR",
compileRequest->getSourceManager(),
&writer);
}
module->buildMangledNameToGlobalInstMap();
return module;
}
/// Context for generating IR code to represent a `SpecializedComponentType`
struct SpecializedComponentTypeIRGenContext : ComponentTypeVisitor
{
DiagnosticSink* sink;
Linkage* linkage;
Session* session;
IRGenContext* context;
IRBuilder* builder;
RefPtr<IRModule> process(SpecializedComponentType* componentType, DiagnosticSink* inSink)
{
sink = inSink;
linkage = componentType->getLinkage();
session = linkage->getSessionImpl();
auto option = linkage->m_optionSet;
option.overrideWith(componentType->getOptionSet());
SharedIRGenContext
sharedContextStorage(session, sink, option.shouldObfuscateCode(), nullptr, linkage);
SharedIRGenContext* sharedContext = &sharedContextStorage;
IRGenContext contextStorage(sharedContext, linkage->getASTBuilder());
context = &contextStorage;
RefPtr<IRModule> module = IRModule::create(session);
IRBuilder builderStorage(module);
builder = &builderStorage;
builder->setInsertInto(module);
context->irBuilder = builder;
componentType->acceptVisitor(this, nullptr);
module->buildMangledNameToGlobalInstMap();
return module;
}
void visitEntryPoint(
EntryPoint* entryPoint,
EntryPoint::EntryPointSpecializationInfo* specializationInfo) SLANG_OVERRIDE
{
// We need to emit symbols for all of the entry
// points in the program; this is especially
// important in the case where a generic entry
// point is being specialized.
//
lowerProgramEntryPointToIR(context, entryPoint, specializationInfo);
}
void visitRenamedEntryPoint(
RenamedEntryPointComponentType* entryPoint,
EntryPoint::EntryPointSpecializationInfo* specializationInfo) SLANG_OVERRIDE
{
entryPoint->getBase()->acceptVisitor(this, specializationInfo);
}
void visitModule(Module* module, Module::ModuleSpecializationInfo* specializationInfo)
SLANG_OVERRIDE
{
// We've hit a leaf module, so we should be able to bind any global
// generic type parameters here...
//
if (specializationInfo)
{
for (auto genericArgInfo : specializationInfo->genericArgs)
{
IRInst* irParam =
getSimpleVal(context, ensureDecl(context, genericArgInfo.paramDecl));
IRInst* irVal = lowerSimpleVal(context, genericArgInfo.argVal);
// bind `irParam` to `irVal`
builder->emitBindGlobalGenericParam(irParam, irVal);
}
auto shaderParamCount = module->getShaderParamCount();
Index existentialArgOffset = 0;
for (Index ii = 0; ii < shaderParamCount; ++ii)
{
auto shaderParam = module->getShaderParam(ii);
auto specializationArgCount = shaderParam.specializationParamCount;
IRInst* irParam =
getSimpleVal(context, ensureDecl(context, shaderParam.paramDeclRef.getDecl()));
List<IRInst*> irSlotArgs;
// Tracks if there are any type args that is not an IRDynamicType.
bool hasConcreteTypeArg = false;
for (Index jj = 0; jj < specializationArgCount; ++jj)
{
auto& specializationArg =
specializationInfo->existentialArgs[existentialArgOffset++];
auto irType = lowerSimpleVal(context, specializationArg.val);
auto irWitness = lowerSimpleVal(context, specializationArg.witness);
if (irType->getOp() != kIROp_DynamicType)
hasConcreteTypeArg = true;
irSlotArgs.add(irType);
irSlotArgs.add(irWitness);
}
// Only insert a `BindExistentialSlots` decoration when there are at least
// one non-dynamic type argument.
if (hasConcreteTypeArg)
{
builder->addBindExistentialSlotsDecoration(
irParam,
irSlotArgs.getCount(),
irSlotArgs.getBuffer());
}
}
}
}
void visitComposite(
CompositeComponentType* composite,
CompositeComponentType::CompositeSpecializationInfo* specializationInfo) SLANG_OVERRIDE
{
visitChildren(composite, specializationInfo);
}
void visitSpecialized(SpecializedComponentType* specialized) SLANG_OVERRIDE
{
visitChildren(specialized);
}
void visitTypeConformance(TypeConformance* conformance) SLANG_OVERRIDE
{
SLANG_UNUSED(conformance);
}
};
RefPtr<IRModule> generateIRForSpecializedComponentType(
SpecializedComponentType* componentType,
DiagnosticSink* sink)
{
SLANG_AST_BUILDER_RAII(componentType->getLinkage()->getASTBuilder());
SpecializedComponentTypeIRGenContext context;
return context.process(componentType, sink);
}
/// Context for generating IR code to represent a `TypeConformance`
struct TypeConformanceIRGenContext
{
DiagnosticSink* sink;
Linkage* linkage;
Session* session;
IRGenContext* context;
IRBuilder* builder;
RefPtr<IRModule> process(
TypeConformance* typeConformance,
Int conformanceIdOverride,
DiagnosticSink* inSink)
{
sink = inSink;
linkage = typeConformance->getLinkage();
session = linkage->getSessionImpl();
SharedIRGenContext sharedContextStorage(
session,
sink,
linkage->m_optionSet.shouldObfuscateCode(),
nullptr,
linkage);
SharedIRGenContext* sharedContext = &sharedContextStorage;
IRGenContext contextStorage(sharedContext, linkage->getASTBuilder());
context = &contextStorage;
RefPtr<IRModule> module = IRModule::create(session);
IRBuilder builderStorage(module);
builder = &builderStorage;
builder->setInsertInto(module);
context->irBuilder = builder;
auto witness = lowerSimpleVal(context, typeConformance->getSubtypeWitness());
builder->addKeepAliveDecoration(witness);
builder->addHLSLExportDecoration(witness);
builder->addDynamicDispatchWitnessDecoration(witness);
if (conformanceIdOverride != -1)
{
builder->addSequentialIDDecoration(witness, conformanceIdOverride);
}
module->buildMangledNameToGlobalInstMap();
return module;
}
};
RefPtr<IRModule> generateIRForTypeConformance(
TypeConformance* typeConformance,
Int conformanceIdOverride,
DiagnosticSink* sink)
{
SLANG_AST_BUILDER_RAII(typeConformance->getLinkage()->getASTBuilder());
TypeConformanceIRGenContext context;
return context.process(typeConformance, conformanceIdOverride, sink);
}
RefPtr<IRModule> TargetProgram::getOrCreateIRModuleForLayout(DiagnosticSink* sink)
{
getOrCreateLayout(sink);
return m_irModuleForLayout;
}
/// Specialized IR generation context for when generating IR for layouts.
struct IRLayoutGenContext : IRGenContext
{
IRLayoutGenContext(SharedIRGenContext* shared, ASTBuilder* astBuilder)
: IRGenContext(shared, astBuilder)
{
}
/// Cache for custom key instructions used for entry-point parameter layout information.
Dictionary<ParamDecl*, IRInst*> mapEntryPointParamToKey;
};
/// Lower an AST-level type layout to an IR-level type layout.
IRTypeLayout* lowerTypeLayout(IRLayoutGenContext* context, TypeLayout* typeLayout);
/// Lower an AST-level variable layout to an IR-level variable layout.
IRVarLayout* lowerVarLayout(IRLayoutGenContext* context, VarLayout* varLayout);
/// Shared code for most `lowerTypeLayout` cases.
///
/// Handles copying of resource usage and pending data type layout
/// from the AST `typeLayout` to the specified `builder`.
///
static IRTypeLayout* _lowerTypeLayoutCommon(
IRLayoutGenContext* context,
IRTypeLayout::Builder* builder,
TypeLayout* typeLayout)
{
for (auto resInfo : typeLayout->resourceInfos)
{
builder->addResourceUsage(resInfo.kind, resInfo.count);
}
if (auto pendingTypeLayout = typeLayout->pendingDataTypeLayout)
{
builder->setPendingTypeLayout(lowerTypeLayout(context, pendingTypeLayout));
}
return builder->build();
}
IRTypeLayout* lowerTypeLayout(IRLayoutGenContext* context, TypeLayout* typeLayout)
{
// TODO: We chould consider caching the layouts we create based on `typeLayout`
// and re-using them. This isn't strictly necessary because we emit the
// instructions as "hoistable" which should give us de-duplication, and it wouldn't
// help much until/unless the AST level gets less wasteful about how it computes layout.
// We will use casting to detect if `typeLayout` is
// one of the cases that requires a dedicated sub-type
// of IR type layout.
//
if (auto paramGroupTypeLayout = as<ParameterGroupTypeLayout>(typeLayout))
{
IRParameterGroupTypeLayout::Builder builder(context->irBuilder);
builder.setContainerVarLayout(
lowerVarLayout(context, paramGroupTypeLayout->containerVarLayout));
builder.setElementVarLayout(
lowerVarLayout(context, paramGroupTypeLayout->elementVarLayout));
builder.setOffsetElementTypeLayout(
lowerTypeLayout(context, paramGroupTypeLayout->offsetElementTypeLayout));
return _lowerTypeLayoutCommon(context, &builder, paramGroupTypeLayout);
}
else if (auto structuredBufferTypeLayout = as<StructuredBufferTypeLayout>(typeLayout))
{
auto irElementTypeLayout =
lowerTypeLayout(context, structuredBufferTypeLayout->elementTypeLayout);
IRStructuredBufferTypeLayout::Builder builder(context->irBuilder, irElementTypeLayout);
return _lowerTypeLayoutCommon(context, &builder, structuredBufferTypeLayout);
}
else if (auto structTypeLayout = as<StructTypeLayout>(typeLayout))
{
IRStructTypeLayout::Builder builder(context->irBuilder);
int fieldIndex = 0;
for (auto fieldLayout : structTypeLayout->fields)
{
auto fieldDecl = fieldLayout->varDecl;
IRInst* irFieldKey = nullptr;
if (auto paramDecl = as<ParamDecl>(fieldDecl))
{
// There is a subtle special case here.
//
// A `StructTypeLayout` might be used to represent
// the parameters of an entry point, and this is the
// one and only case where the "fields" being used
// might actually be `ParamDecl`s.
//
// The IR encoding of structure type layouts relies
// on using field "key" instructions to identify
// the fields, but these don't exist (by default)
// for function parameters.
//
// To get around this problem we will create key
// instructions to stand in for the entry-point parameters
// as needed when generating layout.
//
// We need to cache the generated keys on the context,
// so that if we run into another type layout for the
// same entry point we will re-use the same keys.
//
if (!context->mapEntryPointParamToKey.tryGetValue(paramDecl.getDecl(), irFieldKey))
{
irFieldKey = context->irBuilder->createStructKey();
// TODO: It might eventually be a good idea to attach a mangled
// name to the key we just generated (derived from the entry point
// and parameter name), even though parameters don't usually have
// linkage.
//
// Doing so would ensure that if we ever combined partial layout
// information from different modules they would agree on the key
// to use for entry-point parameters.
//
// For now this is a non-issue because both the creation and use
// of these keys will be local to a single `IREntryPointLayout`,
// and we don't support combination at a finer granularity than that.
context->mapEntryPointParamToKey.add(paramDecl.getDecl(), irFieldKey);
}
}
else if (fieldDecl.getDecl())
{
irFieldKey = getSimpleVal(context, ensureDecl(context, fieldDecl.getDecl()));
}
else
{
// If we don't have a concrete field decl for the field in the layout,
// it could be that the field in the layout is for a member of a tuple
// type that hasn't been materialized into a struct decl yet.
// We will use a `IndexFieldKey(type, memberIndex)` inst as a placeholder
// for the field key.
// This placeholder can be replaced with the actual field key when the
// tuple type is materialized into a struct type.
auto irType = lowerType(context, typeLayout->getType());
irFieldKey = context->irBuilder->getIndexedFieldKey(irType, fieldIndex);
}
fieldIndex++;
SLANG_ASSERT(irFieldKey);
auto irFieldLayout = lowerVarLayout(context, fieldLayout);
builder.addField(irFieldKey, irFieldLayout);
}
return _lowerTypeLayoutCommon(context, &builder, structTypeLayout);
}
else if (auto arrayTypeLayout = as<ArrayTypeLayout>(typeLayout))
{
auto irElementTypeLayout = lowerTypeLayout(context, arrayTypeLayout->elementTypeLayout);
IRArrayTypeLayout::Builder builder(context->irBuilder, irElementTypeLayout);
return _lowerTypeLayoutCommon(context, &builder, arrayTypeLayout);
}
else if (auto ptrTypeLayout = as<PointerTypeLayout>(typeLayout))
{
// TODO(JS):
// For now we don't lower the value/target type because this could lead to inifinte
// recursion in the way this is currently implemented.
// auto irValueTypeLayout = lowerTypeLayout(context, ptrTypeLayout->valueTypeLayout);
IRPointerTypeLayout::Builder builder(context->irBuilder);
return _lowerTypeLayoutCommon(context, &builder, ptrTypeLayout);
}
else if (auto streamOutputTypeLayout = as<StreamOutputTypeLayout>(typeLayout))
{
auto irElementTypeLayout =
lowerTypeLayout(context, streamOutputTypeLayout->elementTypeLayout);
IRStreamOutputTypeLayout::Builder builder(context->irBuilder, irElementTypeLayout);
return _lowerTypeLayoutCommon(context, &builder, streamOutputTypeLayout);
}
else if (auto matrixTypeLayout = as<MatrixTypeLayout>(typeLayout))
{
// TODO: Our support for explicit layouts on matrix types is minimal, so whether
// or not we even include `IRMatrixTypeLayout` doesn't impact any behavior we
// currently test.
//
// Our handling of matrix types and their layout needs a complete overhaul, but
// that isn't something we can get to right away, so we'll just try to pass
// along this data as best we can for now.
IRMatrixTypeLayout::Builder builder(context->irBuilder, matrixTypeLayout->mode);
return _lowerTypeLayoutCommon(context, &builder, matrixTypeLayout);
}
else if (auto existentialTypeLayout = as<ExistentialTypeLayout>(typeLayout))
{
IRExistentialTypeLayout::Builder builder(context->irBuilder);
return _lowerTypeLayoutCommon(context, &builder, existentialTypeLayout);
}
else
{
// If no special case applies we will build a generic `IRTypeLayout`.
//
IRTypeLayout::Builder builder(context->irBuilder);
return _lowerTypeLayoutCommon(context, &builder, typeLayout);
}
}
IRVarLayout* lowerVarLayout(
IRLayoutGenContext* context,
VarLayout* varLayout,
IRTypeLayout* irTypeLayout)
{
IRVarLayout::Builder irLayoutBuilder(context->irBuilder, irTypeLayout);
for (auto resInfo : varLayout->resourceInfos)
{
auto irResInfo = irLayoutBuilder.findOrAddResourceInfo(resInfo.kind);
irResInfo->offset = resInfo.index;
irResInfo->space = resInfo.space;
}
if (auto pendingVarLayout = varLayout->pendingVarLayout)
{
irLayoutBuilder.setPendingVarLayout(lowerVarLayout(context, pendingVarLayout));
}
// We will only generate layout information with *either* a system-value
// semantic or a user-defined semantic, and we will always check for
// the system-value semantic first because the AST-level representation
// seems to encode both when a system-value semantic is present.
//
if (varLayout->systemValueSemantic.getLength())
{
irLayoutBuilder.setSystemValueSemantic(
varLayout->systemValueSemantic,
varLayout->systemValueSemanticIndex);
}
else if (varLayout->semanticName.getLength())
{
irLayoutBuilder.setUserSemantic(varLayout->semanticName, varLayout->semanticIndex);
}
if (varLayout->stage != Stage::Unknown)
{
irLayoutBuilder.setStage(varLayout->stage);
}
return irLayoutBuilder.build();
}
IRVarLayout* lowerVarLayout(IRLayoutGenContext* context, VarLayout* varLayout)
{
auto irTypeLayout = lowerTypeLayout(context, varLayout->typeLayout);
return lowerVarLayout(context, varLayout, irTypeLayout);
}
/// Handle the lowering of an entry-point result layout to the IR
IRVarLayout* lowerEntryPointResultLayout(IRLayoutGenContext* context, VarLayout* layout)
{
// The easy case is when there is a non-null `layout`, because we
// can handle it like any other var layout.
//
if (layout)
return lowerVarLayout(context, layout);
// Right now the AST-level layout logic will leave a null layout
// for the result when an entry point has a `void` result type.
//
// TODO: We should fix this at the AST level instead of the IR,
// but doing so would impact reflection, where clients could
// be using a null check to test for a `void` result.
//
// As a workaround, we will create an empty type layout and
// an empty var layout that represents it, consistent with the
// way that a `void` value consumes no resources.
//
IRTypeLayout::Builder typeLayoutBuilder(context->irBuilder);
auto irTypeLayout = typeLayoutBuilder.build();
IRVarLayout::Builder varLayoutBuilder(context->irBuilder, irTypeLayout);
return varLayoutBuilder.build();
}
/// Lower AST-level layout information for an entry point to the IR
IREntryPointLayout* lowerEntryPointLayout(
IRLayoutGenContext* context,
EntryPointLayout* entryPointLayout)
{
auto irParamsLayout = lowerVarLayout(context, entryPointLayout->parametersLayout);
auto irResultLayout = lowerEntryPointResultLayout(context, entryPointLayout->resultLayout);
return context->irBuilder->getEntryPointLayout(irParamsLayout, irResultLayout);
}
RefPtr<IRModule> TargetProgram::createIRModuleForLayout(DiagnosticSink* sink)
{
if (m_irModuleForLayout)
return m_irModuleForLayout;
// Okay, now we need to fill it in.
auto programLayout = getOrCreateLayout(sink);
if (!programLayout)
return nullptr;
auto program = getProgram();
auto linkage = program->getLinkage();
SLANG_AST_BUILDER_RAII(linkage->getASTBuilder());
auto session = linkage->getSessionImpl();
SharedIRGenContext sharedContextStorage(
session,
sink,
linkage->m_optionSet.shouldObfuscateCode(),
nullptr,
linkage);
auto sharedContext = &sharedContextStorage;
ASTBuilder* astBuilder = linkage->getASTBuilder();
IRLayoutGenContext contextStorage(sharedContext, astBuilder);
auto context = &contextStorage;
RefPtr<IRModule> irModule = IRModule::create(session);
IRBuilder builderStorage(irModule);
auto builder = &builderStorage;
builder->setInsertInto(irModule);
context->irBuilder = builder;
// Okay, now we need to walk through and decorate everything.
auto globalStructLayout = getScopeStructLayout(programLayout);
IRStructTypeLayout::Builder globalStructTypeLayoutBuilder(builder);
for (auto varLayout : globalStructLayout->fields)
{
auto varDecl = varLayout->varDecl;
// Ensure that an `[import(...)]` declaration for the variable
// has been emitted to this module, so that we will have something
// to decorate.
//
auto irVar = materialize(context, ensureDecl(context, varDecl.getDecl())).val;
if (!irVar)
SLANG_UNEXPECTED("unhandled value flavor");
auto irLayout = lowerVarLayout(context, varLayout);
// Now attach the decoration to the variable.
//
builder->addLayoutDecoration(irVar, irLayout);
// Also add this to our mapping for the global-scope structure type
globalStructTypeLayoutBuilder.addField(irVar, irLayout);
}
auto irGlobalStructTypeLayout =
_lowerTypeLayoutCommon(context, &globalStructTypeLayoutBuilder, globalStructLayout);
auto globalScopeVarLayout = programLayout->parametersLayout;
auto globalScopeTypeLayout = globalScopeVarLayout->typeLayout;
IRTypeLayout* irGlobalScopeTypeLayout = irGlobalStructTypeLayout;
if (auto paramGroupTypeLayout = as<ParameterGroupTypeLayout>(globalScopeTypeLayout))
{
IRParameterGroupTypeLayout::Builder globalParameterGroupTypeLayoutBuilder(builder);
auto irElementTypeLayout = irGlobalStructTypeLayout;
auto irElementVarLayout =
lowerVarLayout(context, paramGroupTypeLayout->elementVarLayout, irElementTypeLayout);
globalParameterGroupTypeLayoutBuilder.setContainerVarLayout(
lowerVarLayout(context, paramGroupTypeLayout->containerVarLayout));
globalParameterGroupTypeLayoutBuilder.setElementVarLayout(irElementVarLayout);
globalParameterGroupTypeLayoutBuilder.setOffsetElementTypeLayout(
lowerTypeLayout(context, paramGroupTypeLayout->offsetElementTypeLayout));
auto irParamGroupTypeLayout = _lowerTypeLayoutCommon(
context,
&globalParameterGroupTypeLayoutBuilder,
paramGroupTypeLayout);
irGlobalScopeTypeLayout = irParamGroupTypeLayout;
}
auto irGlobalScopeVarLayout =
lowerVarLayout(context, globalScopeVarLayout, irGlobalScopeTypeLayout);
builder->addLayoutDecoration(irModule->getModuleInst(), irGlobalScopeVarLayout);
auto latestSpirvAtom = getLatestSpirvAtom();
auto latestMetalAtom = getLatestMetalAtom();
for (auto entryPointLayout : programLayout->entryPoints)
{
auto funcDeclRef = entryPointLayout->entryPoint;
// HACK: skip over entry points that came from deserialization,
// and thus don't have AST-level information for us to work with.
//
if (!funcDeclRef)
continue;
auto irFuncType = lowerType(context, getFuncType(astBuilder, funcDeclRef));
auto irFunc = getSimpleVal(context, emitDeclRef(context, funcDeclRef, irFuncType));
if (!irFunc->findDecoration<IRLinkageDecoration>())
{
builder->addImportDecoration(
irFunc,
getMangledName(astBuilder, funcDeclRef).getUnownedSlice());
}
for (auto atomSet :
as<FuncDecl>(funcDeclRef.getDecl())->inferredCapabilityRequirements.getAtomSets())
{
for (auto atomVal : atomSet)
{
auto atom = asAtom(atomVal);
if (atom >= CapabilityAtom::_spirv_1_0 && atom <= latestSpirvAtom ||
atom >= CapabilityAtom::metallib_2_3 && atom <= latestMetalAtom)
{
builder->addRequireCapabilityAtomDecoration(irFunc, (CapabilityName)atom);
}
}
}
auto irEntryPointLayout = lowerEntryPointLayout(context, entryPointLayout);
builder->addLayoutDecoration(irFunc, irEntryPointLayout);
}
// Lets strip and run DCE here
if (linkage->m_optionSet.shouldObfuscateCode())
{
IRStripOptions stripOptions;
stripOptions.shouldStripNameHints = true;
stripOptions.stripSourceLocs = true;
;
stripFrontEndOnlyInstructions(irModule, stripOptions);
IRDeadCodeEliminationOptions options;
options.keepExportsAlive = true;
options.keepLayoutsAlive = true;
// Eliminate any dead code
eliminateDeadCode(irModule, options);
}
irModule->buildMangledNameToGlobalInstMap();
m_irModuleForLayout = irModule;
return irModule;
}
} // namespace Slang
|