Hash :
dc59772e
Author :
Date :
2021-06-22T22:37:26
Vulkan: SPIR-V Gen: Support switch With the infrastructure to support this in place, switch is simply implemented as a conditional with multiple blocks. Each block either ends with a branch to the merge block or the next block, implementing fallthrough. Bug: angleproject:4889 Change-Id: I5831531d918ac06648cced7707d1d48ffeb6b1b0 Reviewed-on: https://chromium-review.googlesource.com/c/angle/angle/+/2983559 Commit-Queue: Shahbaz Youssefi <syoussefi@chromium.org> Reviewed-by: Tim Van Patten <timvp@google.com> Reviewed-by: Jamie Madill <jmadill@chromium.org>
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
//
// Copyright 2021 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// OutputSPIRV: Generate SPIR-V from the AST.
//
#include "compiler/translator/OutputSPIRV.h"
#include "angle_gl.h"
#include "common/debug.h"
#include "common/mathutil.h"
#include "common/spirv/spirv_instruction_builder_autogen.h"
#include "compiler/translator/BuildSPIRV.h"
#include "compiler/translator/Compiler.h"
#include "compiler/translator/tree_util/IntermTraverse.h"
#include <cfloat>
// Extended instructions
namespace spv
{
#include <spirv/unified1/GLSL.std.450.h>
}
// SPIR-V tools include for disassembly
#include <spirv-tools/libspirv.hpp>
// Enable this for debug logging of pre-transform SPIR-V:
#if !defined(ANGLE_DEBUG_SPIRV_GENERATION)
# define ANGLE_DEBUG_SPIRV_GENERATION 0
#endif // !defined(ANGLE_DEBUG_SPIRV_GENERATION)
namespace sh
{
namespace
{
// A struct to hold either SPIR-V ids or literal constants. If id is not valid, a literal is
// assumed.
struct SpirvIdOrLiteral
{
SpirvIdOrLiteral() = default;
SpirvIdOrLiteral(const spirv::IdRef idIn) : id(idIn) {}
SpirvIdOrLiteral(const spirv::LiteralInteger literalIn) : literal(literalIn) {}
spirv::IdRef id;
spirv::LiteralInteger literal;
};
// A data structure to facilitate generating array indexing, block field selection, swizzle and
// such. Used in conjunction with NodeData which includes the access chain's baseId and idList.
//
// - rvalue[literal].field[literal] generates OpCompositeExtract
// - rvalue.x generates OpCompositeExtract
// - rvalue.xyz generates OpVectorShuffle
// - rvalue.xyz[i] generates OpVectorExtractDynamic (xyz[i] itself generates an
// OpVectorExtractDynamic as well)
// - rvalue[i].field[j] generates a temp variable OpStore'ing rvalue and then generating an
// OpAccessChain and OpLoad
//
// - lvalue[i].field[j].x generates OpAccessChain and OpStore
// - lvalue.xyz generates an OpLoad followed by OpVectorShuffle and OpStore
// - lvalue.xyz[i] generates OpAccessChain and OpStore (xyz[i] itself generates an
// OpVectorExtractDynamic as well)
//
// storageClass == Max implies an rvalue.
//
struct AccessChain
{
// The storage class for lvalues. If Max, it's an rvalue.
spv::StorageClass storageClass = spv::StorageClassMax;
// If the access chain ends in swizzle, the swizzle components are specified here. Swizzles
// select multiple components so need special treatment when used as lvalue.
std::vector<uint32_t> swizzles;
// If a vector component is selected dynamically (i.e. indexed with a non-literal index),
// dynamicComponent will contain the id of the index.
spirv::IdRef dynamicComponent;
// Type of base expression, before swizzle is applied, after swizzle is applied and after
// dynamic component is applied.
spirv::IdRef baseTypeId;
spirv::IdRef preSwizzleTypeId;
spirv::IdRef postSwizzleTypeId;
spirv::IdRef postDynamicComponentTypeId;
// If the OpAccessChain is already generated (done by accessChainCollapse()), this caches the
// id.
spirv::IdRef accessChainId;
// Whether all indices are literal. Avoids looping through indices to determine this
// information.
bool areAllIndicesLiteral = true;
// The number of components in the vector, if vector and swizzle is used. This is cached to
// avoid a type look up when handling swizzles.
uint8_t swizzledVectorComponentCount = 0;
// The block storage of the base id. Used to correctly select the SPIR-V type id when visiting
// EOpIndex* binary nodes.
TLayoutBlockStorage baseBlockStorage;
};
// As each node is traversed, it produces data. When visiting back the parent, this data is used to
// complete the data of the parent. For example, the children of a function call (i.e. the
// arguments) each produce a SPIR-V id corresponding to the result of their expression. The
// function call node itself in PostVisit uses those ids to generate the function call instruction.
struct NodeData
{
// An id whose meaning depends on the node. It could be a temporary id holding the result of an
// expression, a reference to a variable etc.
spirv::IdRef baseId;
// List of relevant SPIR-V ids accumulated while traversing the children. Meaning depends on
// the node, for example a list of parameters to be passed to a function, a set of ids used to
// construct an access chain etc.
std::vector<SpirvIdOrLiteral> idList;
// For constructing access chains.
AccessChain accessChain;
};
struct FunctionIds
{
// Id of the function type, return type and parameter types.
spirv::IdRef functionTypeId;
spirv::IdRef returnTypeId;
spirv::IdRefList parameterTypeIds;
// Id of the function itself.
spirv::IdRef functionId;
};
bool IsAccessChainRValue(const AccessChain &accessChain)
{
return accessChain.storageClass == spv::StorageClassMax;
}
bool IsAccessChainUnindexedLValue(const NodeData &data)
{
return !IsAccessChainRValue(data.accessChain) && data.idList.empty() &&
data.accessChain.swizzles.empty() && !data.accessChain.dynamicComponent.valid();
}
// A traverser that generates SPIR-V as it walks the AST.
class OutputSPIRVTraverser : public TIntermTraverser
{
public:
OutputSPIRVTraverser(TCompiler *compiler, ShCompileOptions compileOptions, bool forceHighp);
~OutputSPIRVTraverser() override;
spirv::Blob getSpirv();
protected:
void visitSymbol(TIntermSymbol *node) override;
void visitConstantUnion(TIntermConstantUnion *node) override;
bool visitSwizzle(Visit visit, TIntermSwizzle *node) override;
bool visitBinary(Visit visit, TIntermBinary *node) override;
bool visitUnary(Visit visit, TIntermUnary *node) override;
bool visitTernary(Visit visit, TIntermTernary *node) override;
bool visitIfElse(Visit visit, TIntermIfElse *node) override;
bool visitSwitch(Visit visit, TIntermSwitch *node) override;
bool visitCase(Visit visit, TIntermCase *node) override;
void visitFunctionPrototype(TIntermFunctionPrototype *node) override;
bool visitFunctionDefinition(Visit visit, TIntermFunctionDefinition *node) override;
bool visitAggregate(Visit visit, TIntermAggregate *node) override;
bool visitBlock(Visit visit, TIntermBlock *node) override;
bool visitGlobalQualifierDeclaration(Visit visit,
TIntermGlobalQualifierDeclaration *node) override;
bool visitDeclaration(Visit visit, TIntermDeclaration *node) override;
bool visitLoop(Visit visit, TIntermLoop *node) override;
bool visitBranch(Visit visit, TIntermBranch *node) override;
void visitPreprocessorDirective(TIntermPreprocessorDirective *node) override;
private:
spirv::IdRef getSymbolIdAndStorageClass(const TSymbol *symbol,
const TType &type,
spv::StorageClass *storageClass);
// Access chain handling.
void accessChainPush(NodeData *data, spirv::IdRef index, spirv::IdRef typeId) const;
void accessChainPushLiteral(NodeData *data,
spirv::LiteralInteger index,
spirv::IdRef typeId) const;
void accessChainPushSwizzle(NodeData *data,
const TVector<int> &swizzle,
spirv::IdRef typeId,
uint8_t componentCount) const;
void accessChainPushDynamicComponent(NodeData *data, spirv::IdRef index, spirv::IdRef typeId);
spirv::IdRef accessChainCollapse(NodeData *data);
spirv::IdRef accessChainLoad(NodeData *data, const SpirvDecorations &decorations);
void accessChainStore(NodeData *data, spirv::IdRef value);
// Access chain helpers.
void makeAccessChainIdList(NodeData *data, spirv::IdRefList *idsOut);
void makeAccessChainLiteralList(NodeData *data, spirv::LiteralIntegerList *literalsOut);
spirv::IdRef getAccessChainTypeId(NodeData *data);
// Node data handling.
void nodeDataInitLValue(NodeData *data,
spirv::IdRef baseId,
spirv::IdRef typeId,
spv::StorageClass storageClass,
TLayoutBlockStorage blockStorage) const;
void nodeDataInitRValue(NodeData *data, spirv::IdRef baseId, spirv::IdRef typeId) const;
void declareSpecConst(TIntermDeclaration *decl);
spirv::IdRef createConstant(const TType &type,
TBasicType expectedBasicType,
const TConstantUnion *constUnion);
spirv::IdRef createComplexConstant(const TType &type,
spirv::IdRef typeId,
const spirv::IdRefList ¶meters);
spirv::IdRef createConstructor(TIntermAggregate *node, spirv::IdRef typeId);
spirv::IdRef createArrayOrStructConstructor(TIntermAggregate *node,
spirv::IdRef typeId,
const spirv::IdRefList ¶meters);
spirv::IdRef createConstructorVectorFromScalar(const TType &type,
spirv::IdRef typeId,
const spirv::IdRefList ¶meters);
spirv::IdRef createConstructorVectorFromNonScalar(TIntermAggregate *node,
spirv::IdRef typeId,
const spirv::IdRefList ¶meters);
spirv::IdRef createConstructorMatrixFromScalar(TIntermAggregate *node,
spirv::IdRef typeId,
const spirv::IdRefList ¶meters);
spirv::IdRef createConstructorMatrixFromVectors(TIntermAggregate *node,
spirv::IdRef typeId,
const spirv::IdRefList ¶meters);
spirv::IdRef createConstructorMatrixFromMatrix(TIntermAggregate *node,
spirv::IdRef typeId,
const spirv::IdRefList ¶meters);
spirv::IdRefList loadAllParams(TIntermOperator *node);
void extractComponents(TIntermAggregate *node,
size_t componentCount,
const spirv::IdRefList ¶meters,
spirv::IdRefList *extractedComponentsOut);
void startShortCircuit(TIntermBinary *node);
spirv::IdRef endShortCircuit(TIntermBinary *node, spirv::IdRef *typeId);
spirv::IdRef visitOperator(TIntermOperator *node, spirv::IdRef resultTypeId);
spirv::IdRef createIncrementDecrement(TIntermOperator *node, spirv::IdRef resultTypeId);
spirv::IdRef createAtomicBuiltIn(TIntermOperator *node, spirv::IdRef resultTypeId);
spirv::IdRef createTextureBuiltIn(TIntermOperator *node, spirv::IdRef resultTypeId);
spirv::IdRef createImageBuiltIn(TIntermOperator *node, spirv::IdRef resultTypeId);
spirv::IdRef createFunctionCall(TIntermAggregate *node, spirv::IdRef resultTypeId);
ANGLE_MAYBE_UNUSED TCompiler *mCompiler;
ShCompileOptions mCompileOptions;
SPIRVBuilder mBuilder;
// Traversal state. Nodes generally push() once to this stack on PreVisit. On InVisit and
// PostVisit, they pop() once (data corresponding to the result of the child) and accumulate it
// in back() (data corresponding to the node itself). On PostVisit, code is generated.
std::vector<NodeData> mNodeData;
// A map of TSymbol to its SPIR-V id. This could be a:
//
// - TVariable, or
// - TInterfaceBlock: because TIntermSymbols referencing a field of an unnamed interface block
// don't reference the TVariable that defines the struct, but the TInterfaceBlock itself.
angle::HashMap<const TSymbol *, spirv::IdRef> mSymbolIdMap;
// A map of TFunction to its various SPIR-V ids.
angle::HashMap<const TFunction *, FunctionIds> mFunctionIdMap;
// Whether the current symbol being visited is being declared.
bool mIsSymbolBeingDeclared = false;
};
spv::StorageClass GetStorageClass(const TType &type)
{
// Opaque uniforms (samplers and images) have the UniformConstant storage class
if (type.isSampler() || type.isImage())
{
return spv::StorageClassUniformConstant;
}
const TQualifier qualifier = type.getQualifier();
// Input varying and IO blocks have the Input storage class
if (IsShaderIn(qualifier))
{
return spv::StorageClassInput;
}
// Output varying and IO blocks have the Input storage class
if (IsShaderOut(qualifier))
{
return spv::StorageClassOutput;
}
// Uniform and storage buffers have the Uniform storage class. Default uniforms are gathered in
// a uniform block as well.
if (type.isInterfaceBlock() || qualifier == EvqUniform)
{
// I/O blocks must have already been classified as input or output above.
ASSERT(!IsShaderIoBlock(qualifier));
return spv::StorageClassUniform;
}
switch (qualifier)
{
case EvqShared:
// Compute shader shared memory has the Workgroup storage class
return spv::StorageClassWorkgroup;
case EvqGlobal:
// Global variables have the Private class.
return spv::StorageClassPrivate;
case EvqTemporary:
case EvqIn:
case EvqOut:
case EvqInOut:
// Function-local variables have the Function class
return spv::StorageClassFunction;
case EvqVertexID:
case EvqInstanceID:
case EvqFragCoord:
case EvqFrontFacing:
case EvqPointCoord:
case EvqHelperInvocation:
case EvqNumWorkGroups:
case EvqWorkGroupID:
case EvqLocalInvocationID:
case EvqGlobalInvocationID:
case EvqLocalInvocationIndex:
return spv::StorageClassInput;
case EvqFragDepth:
return spv::StorageClassOutput;
default:
// TODO: http://anglebug.com/4889
UNIMPLEMENTED();
}
UNREACHABLE();
return spv::StorageClassPrivate;
}
OutputSPIRVTraverser::OutputSPIRVTraverser(TCompiler *compiler,
ShCompileOptions compileOptions,
bool forceHighp)
: TIntermTraverser(true, true, true, &compiler->getSymbolTable()),
mCompiler(compiler),
mCompileOptions(compileOptions),
mBuilder(compiler,
compileOptions,
forceHighp,
compiler->getHashFunction(),
compiler->getNameMap())
{}
OutputSPIRVTraverser::~OutputSPIRVTraverser()
{
ASSERT(mNodeData.empty());
}
spirv::IdRef OutputSPIRVTraverser::getSymbolIdAndStorageClass(const TSymbol *symbol,
const TType &type,
spv::StorageClass *storageClass)
{
*storageClass = GetStorageClass(type);
auto iter = mSymbolIdMap.find(symbol);
if (iter != mSymbolIdMap.end())
{
return iter->second;
}
// This must be an implicitly defined variable, define it now.
const char *name = nullptr;
spv::BuiltIn builtInDecoration = spv::BuiltInMax;
switch (type.getQualifier())
{
case EvqVertexID:
name = "gl_VertexIndex";
builtInDecoration = spv::BuiltInVertexIndex;
break;
case EvqInstanceID:
name = "gl_InstanceIndex";
builtInDecoration = spv::BuiltInInstanceIndex;
break;
// Fragment shader built-ins
case EvqFragCoord:
name = "gl_FragCoord";
builtInDecoration = spv::BuiltInFragCoord;
break;
case EvqFrontFacing:
name = "gl_FrontFacing";
builtInDecoration = spv::BuiltInFrontFacing;
break;
case EvqPointCoord:
name = "gl_PointCoord";
builtInDecoration = spv::BuiltInPointCoord;
break;
case EvqFragDepth:
name = "gl_FragDepth";
builtInDecoration = spv::BuiltInFragDepth;
break;
case EvqHelperInvocation:
name = "gl_HelperInvocation";
builtInDecoration = spv::BuiltInHelperInvocation;
break;
// Compute shader built-ins
case EvqNumWorkGroups:
name = "gl_NumWorkGroups";
builtInDecoration = spv::BuiltInNumWorkgroups;
break;
case EvqWorkGroupID:
name = "gl_WorkGroupID";
builtInDecoration = spv::BuiltInWorkgroupId;
break;
case EvqLocalInvocationID:
name = "gl_LocalInvocationID";
builtInDecoration = spv::BuiltInLocalInvocationId;
break;
case EvqGlobalInvocationID:
name = "gl_GlobalInvocationID";
builtInDecoration = spv::BuiltInGlobalInvocationId;
break;
case EvqLocalInvocationIndex:
name = "gl_LocalInvocationIndex";
builtInDecoration = spv::BuiltInLocalInvocationIndex;
break;
default:
// TODO: more built-ins. http://anglebug.com/4889
UNIMPLEMENTED();
}
const spirv::IdRef typeId = mBuilder.getTypeData(type, EbsUnspecified).id;
const spirv::IdRef varId = mBuilder.declareVariable(
typeId, *storageClass, mBuilder.getDecorations(type), nullptr, name);
mBuilder.addEntryPointInterfaceVariableId(varId);
spirv::WriteDecorate(mBuilder.getSpirvDecorations(), varId, spv::DecorationBuiltIn,
{spirv::LiteralInteger(builtInDecoration)});
mSymbolIdMap.insert({symbol, varId});
return varId;
}
void OutputSPIRVTraverser::nodeDataInitLValue(NodeData *data,
spirv::IdRef baseId,
spirv::IdRef typeId,
spv::StorageClass storageClass,
TLayoutBlockStorage blockStorage) const
{
*data = {};
// Initialize the access chain as an lvalue. Useful when an access chain is resolved, but needs
// to be replaced by a reference to a temporary variable holding the result.
data->baseId = baseId;
data->accessChain.baseTypeId = typeId;
data->accessChain.preSwizzleTypeId = typeId;
data->accessChain.storageClass = storageClass;
data->accessChain.baseBlockStorage = blockStorage;
}
void OutputSPIRVTraverser::nodeDataInitRValue(NodeData *data,
spirv::IdRef baseId,
spirv::IdRef typeId) const
{
*data = {};
// Initialize the access chain as an rvalue. Useful when an access chain is resolved, and needs
// to be replaced by a reference to it.
data->baseId = baseId;
data->accessChain.baseTypeId = typeId;
data->accessChain.preSwizzleTypeId = typeId;
}
void OutputSPIRVTraverser::accessChainPush(NodeData *data,
spirv::IdRef index,
spirv::IdRef typeId) const
{
// Simply add the index to the chain of indices.
data->idList.emplace_back(index);
data->accessChain.areAllIndicesLiteral = false;
data->accessChain.preSwizzleTypeId = typeId;
}
void OutputSPIRVTraverser::accessChainPushLiteral(NodeData *data,
spirv::LiteralInteger index,
spirv::IdRef typeId) const
{
// Add the literal integer in the chain of indices. Since this is an id list, fake it as an id.
data->idList.emplace_back(index);
data->accessChain.preSwizzleTypeId = typeId;
}
void OutputSPIRVTraverser::accessChainPushSwizzle(NodeData *data,
const TVector<int> &swizzle,
spirv::IdRef typeId,
uint8_t componentCount) const
{
AccessChain &accessChain = data->accessChain;
// Record the swizzle as multi-component swizzles require special handling. When loading
// through the access chain, the swizzle is applied after loading the vector first (see
// |accessChainLoad()|). When storing through the access chain, the whole vector is loaded,
// swizzled components overwritten and the whoel vector written back (see |accessChainStore()|).
ASSERT(accessChain.swizzles.empty());
if (swizzle.size() == 1)
{
// If this swizzle is selecting a single component, fold it into the access chain.
accessChainPushLiteral(data, spirv::LiteralInteger(swizzle[0]), typeId);
}
else
{
// Otherwise keep them separate.
accessChain.swizzles.insert(accessChain.swizzles.end(), swizzle.begin(), swizzle.end());
accessChain.postSwizzleTypeId = typeId;
accessChain.swizzledVectorComponentCount = componentCount;
}
}
void OutputSPIRVTraverser::accessChainPushDynamicComponent(NodeData *data,
spirv::IdRef index,
spirv::IdRef typeId)
{
AccessChain &accessChain = data->accessChain;
// Record the index used to dynamically select a component of a vector.
ASSERT(!accessChain.dynamicComponent.valid());
if (IsAccessChainRValue(accessChain) && accessChain.areAllIndicesLiteral)
{
// If the access chain is an rvalue with all-literal indices, keep this index separate so
// that OpCompositeExtract can be used for the access chain up to this index.
accessChain.dynamicComponent = index;
accessChain.postDynamicComponentTypeId = typeId;
return;
}
if (!accessChain.swizzles.empty())
{
// Otherwise if there's a swizzle, fold the swizzle and dynamic component selection into a
// single dynamic component selection.
ASSERT(accessChain.swizzles.size() > 1);
// Create a vector constant from the swizzles.
spirv::IdRefList swizzleIds;
for (uint32_t component : accessChain.swizzles)
{
swizzleIds.push_back(mBuilder.getUintConstant(component));
}
SpirvType type;
type.type = EbtUInt;
const spirv::IdRef uintTypeId = mBuilder.getSpirvTypeData(type, nullptr).id;
type.primarySize = static_cast<uint8_t>(swizzleIds.size());
const spirv::IdRef uvecTypeId = mBuilder.getSpirvTypeData(type, nullptr).id;
const spirv::IdRef swizzlesId = mBuilder.getNewId({});
spirv::WriteConstantComposite(mBuilder.getSpirvTypeAndConstantDecls(), uvecTypeId,
swizzlesId, swizzleIds);
// Index that vector constant with the dynamic index. For example, vec.ywxz[i] becomes the
// constant {1, 3, 0, 2} indexed with i, and that index used on vec.
const spirv::IdRef newIndex = mBuilder.getNewId({});
spirv::WriteVectorExtractDynamic(mBuilder.getSpirvCurrentFunctionBlock(), uintTypeId,
newIndex, swizzlesId, index);
index = newIndex;
accessChain.swizzles.clear();
}
// Fold it into the access chain.
accessChainPush(data, index, typeId);
}
spirv::IdRef OutputSPIRVTraverser::accessChainCollapse(NodeData *data)
{
AccessChain &accessChain = data->accessChain;
ASSERT(accessChain.storageClass != spv::StorageClassMax);
if (accessChain.accessChainId.valid())
{
return accessChain.accessChainId;
}
// If there are no indices, the baseId is where access is done to/from.
if (data->idList.empty())
{
accessChain.accessChainId = data->baseId;
return accessChain.accessChainId;
}
// Otherwise create an OpAccessChain instruction. Swizzle handling is special as it selects
// multiple components, and is done differently for load and store.
spirv::IdRefList indexIds;
makeAccessChainIdList(data, &indexIds);
const spirv::IdRef typePointerId =
mBuilder.getTypePointerId(accessChain.preSwizzleTypeId, accessChain.storageClass);
accessChain.accessChainId = mBuilder.getNewId({});
spirv::WriteAccessChain(mBuilder.getSpirvCurrentFunctionBlock(), typePointerId,
accessChain.accessChainId, data->baseId, indexIds);
return accessChain.accessChainId;
}
spirv::IdRef OutputSPIRVTraverser::accessChainLoad(NodeData *data,
const SpirvDecorations &decorations)
{
// Loading through the access chain can generate different instructions based on whether it's an
// rvalue, the indices are literal, there's a swizzle etc.
//
// - If rvalue:
// * With indices:
// + All literal: OpCompositeExtract which uses literal integers to access the rvalue.
// + Otherwise: Can't use OpAccessChain on an rvalue, so create a temporary variable, OpStore
// the rvalue into it, then use OpAccessChain and OpLoad to load from it.
// * Without indices: Take the base id.
// - If lvalue:
// * With indices: Use OpAccessChain and OpLoad
// * Without indices: Use OpLoad
// - With swizzle: Use OpVectorShuffle on the result of the previous step
// - With dynamic component: Use OpVectorExtractDynamic on the result of the previous step
AccessChain &accessChain = data->accessChain;
spirv::IdRef loadResult = data->baseId;
if (IsAccessChainRValue(accessChain))
{
if (data->idList.size() > 0)
{
if (accessChain.areAllIndicesLiteral)
{
// Use OpCompositeExtract on an rvalue with all literal indices.
spirv::LiteralIntegerList indexList;
makeAccessChainLiteralList(data, &indexList);
const spirv::IdRef result = mBuilder.getNewId(decorations);
spirv::WriteCompositeExtract(mBuilder.getSpirvCurrentFunctionBlock(),
accessChain.preSwizzleTypeId, result, loadResult,
indexList);
loadResult = result;
}
else
{
// Create a temp variable to hold the rvalue so an access chain can be made on it.
const spirv::IdRef tempVar =
mBuilder.declareVariable(accessChain.baseTypeId, spv::StorageClassFunction,
decorations, nullptr, "indexable");
// Write the rvalue into the temp variable
spirv::WriteStore(mBuilder.getSpirvCurrentFunctionBlock(), tempVar, loadResult,
nullptr);
// Make the temp variable the source of the access chain.
data->baseId = tempVar;
data->accessChain.storageClass = spv::StorageClassFunction;
// Load from the temp variable.
const spirv::IdRef accessChainId = accessChainCollapse(data);
loadResult = mBuilder.getNewId(decorations);
spirv::WriteLoad(mBuilder.getSpirvCurrentFunctionBlock(),
accessChain.preSwizzleTypeId, loadResult, accessChainId, nullptr);
}
}
}
else
{
// Load from the access chain.
const spirv::IdRef accessChainId = accessChainCollapse(data);
loadResult = mBuilder.getNewId(decorations);
spirv::WriteLoad(mBuilder.getSpirvCurrentFunctionBlock(), accessChain.preSwizzleTypeId,
loadResult, accessChainId, nullptr);
}
if (!accessChain.swizzles.empty())
{
// Single-component swizzles are already folded into the index list.
ASSERT(accessChain.swizzles.size() > 1);
// Take the loaded value and use OpVectorShuffle to create the swizzle.
spirv::LiteralIntegerList swizzleList;
for (uint32_t component : accessChain.swizzles)
{
swizzleList.push_back(spirv::LiteralInteger(component));
}
const spirv::IdRef result = mBuilder.getNewId(decorations);
spirv::WriteVectorShuffle(mBuilder.getSpirvCurrentFunctionBlock(),
accessChain.postSwizzleTypeId, result, loadResult, loadResult,
swizzleList);
loadResult = result;
}
if (accessChain.dynamicComponent.valid())
{
// Dynamic component in combination with swizzle is already folded.
ASSERT(accessChain.swizzles.empty());
// Use OpVectorExtractDynamic to select the component.
const spirv::IdRef result = mBuilder.getNewId(decorations);
spirv::WriteVectorExtractDynamic(mBuilder.getSpirvCurrentFunctionBlock(),
accessChain.postDynamicComponentTypeId, result, loadResult,
accessChain.dynamicComponent);
loadResult = result;
}
return loadResult;
}
void OutputSPIRVTraverser::accessChainStore(NodeData *data, spirv::IdRef value)
{
// Storing through the access chain can generate different instructions based on whether the
// there's a swizzle.
//
// - Without swizzle: Use OpAccessChain and OpStore
// - With swizzle: Use OpAccessChain and OpLoad to load the vector, then use OpVectorShuffle to
// replace the components being overwritten. Finally, use OpStore to write the result back.
AccessChain &accessChain = data->accessChain;
// Single-component swizzles are already folded into the indices.
ASSERT(accessChain.swizzles.size() != 1);
// Since store can only happen through lvalues, it's impossible to have a dynamic component as
// that always gets folded into the indices except for rvalues.
ASSERT(!accessChain.dynamicComponent.valid());
const spirv::IdRef accessChainId = accessChainCollapse(data);
if (!accessChain.swizzles.empty())
{
// Load the vector before the swizzle.
const spirv::IdRef loadResult = mBuilder.getNewId({});
spirv::WriteLoad(mBuilder.getSpirvCurrentFunctionBlock(), accessChain.preSwizzleTypeId,
loadResult, accessChainId, nullptr);
// Overwrite the components being written. This is done by first creating an identity
// swizzle, then replacing the components being written with a swizzle from the value. For
// example, take the following:
//
// vec4 v;
// v.zx = u;
//
// The OpVectorShuffle instruction takes two vectors (v and u) and selects components from
// each (in this example, swizzles [0, 3] select from v and [4, 7] select from u). This
// algorithm first creates the identity swizzles {0, 1, 2, 3}, then replaces z and x (the
// 0th and 2nd element) with swizzles from u (4 + {0, 1}) to get the result
// {4+1, 1, 4+0, 3}.
spirv::LiteralIntegerList swizzleList;
for (uint32_t component = 0; component < accessChain.swizzledVectorComponentCount;
++component)
{
swizzleList.push_back(spirv::LiteralInteger(component));
}
uint32_t srcComponent = 0;
for (uint32_t dstComponent : accessChain.swizzles)
{
swizzleList[dstComponent] =
spirv::LiteralInteger(accessChain.swizzledVectorComponentCount + srcComponent);
++srcComponent;
}
// Use the generated swizzle to select components from the loaded vector and the value to be
// written. Use the final result as the value to be written to the vector.
const spirv::IdRef result = mBuilder.getNewId({});
spirv::WriteVectorShuffle(mBuilder.getSpirvCurrentFunctionBlock(),
accessChain.preSwizzleTypeId, result, loadResult, value,
swizzleList);
value = result;
}
// Store through the access chain.
spirv::WriteStore(mBuilder.getSpirvCurrentFunctionBlock(), accessChainId, value, nullptr);
}
void OutputSPIRVTraverser::makeAccessChainIdList(NodeData *data, spirv::IdRefList *idsOut)
{
for (size_t index = 0; index < data->idList.size(); ++index)
{
spirv::IdRef indexId = data->idList[index].id;
if (!indexId.valid())
{
// The index is a literal integer, so replace it with an OpConstant id.
indexId = mBuilder.getUintConstant(data->idList[index].literal);
}
idsOut->push_back(indexId);
}
}
void OutputSPIRVTraverser::makeAccessChainLiteralList(NodeData *data,
spirv::LiteralIntegerList *literalsOut)
{
for (size_t index = 0; index < data->idList.size(); ++index)
{
ASSERT(!data->idList[index].id.valid());
literalsOut->push_back(data->idList[index].literal);
}
}
spirv::IdRef OutputSPIRVTraverser::getAccessChainTypeId(NodeData *data)
{
// Load and store through the access chain may be done in multiple steps. These steps produce
// the following types:
//
// - preSwizzleTypeId
// - postSwizzleTypeId
// - postDynamicComponentTypeId
//
// The last of these types is the final type of the expression this access chain corresponds to.
const AccessChain &accessChain = data->accessChain;
if (accessChain.postDynamicComponentTypeId.valid())
{
return accessChain.postDynamicComponentTypeId;
}
if (accessChain.postSwizzleTypeId.valid())
{
return accessChain.postSwizzleTypeId;
}
ASSERT(accessChain.preSwizzleTypeId.valid());
return accessChain.preSwizzleTypeId;
}
void OutputSPIRVTraverser::declareSpecConst(TIntermDeclaration *decl)
{
const TIntermSequence &sequence = *decl->getSequence();
ASSERT(sequence.size() == 1);
TIntermBinary *assign = sequence.front()->getAsBinaryNode();
ASSERT(assign != nullptr && assign->getOp() == EOpInitialize);
TIntermSymbol *symbol = assign->getLeft()->getAsSymbolNode();
ASSERT(symbol != nullptr && symbol->getType().getQualifier() == EvqSpecConst);
TIntermConstantUnion *initializer = assign->getRight()->getAsConstantUnion();
ASSERT(initializer != nullptr);
const TType &type = symbol->getType();
const TVariable *variable = &symbol->variable();
// All spec consts in ANGLE are initialized to 0.
ASSERT(initializer->isZero(0));
const spirv::IdRef specConstId =
mBuilder.declareSpecConst(type.getBasicType(), type.getLayoutQualifier().location,
mBuilder.hashName(variable).data());
// Remember the id of the variable for future look up.
ASSERT(mSymbolIdMap.count(variable) == 0);
mSymbolIdMap[variable] = specConstId;
}
spirv::IdRef OutputSPIRVTraverser::createConstant(const TType &type,
TBasicType expectedBasicType,
const TConstantUnion *constUnion)
{
const spirv::IdRef typeId = mBuilder.getTypeData(type, EbsUnspecified).id;
spirv::IdRefList componentIds;
if (type.getBasicType() == EbtStruct)
{
// If it's a struct constant, get the constant id for each field.
for (const TField *field : type.getStruct()->fields())
{
const TType *fieldType = field->type();
componentIds.push_back(
createConstant(*fieldType, fieldType->getBasicType(), constUnion));
constUnion += fieldType->getObjectSize();
}
}
else
{
// Otherwise get the constant id for each component.
const size_t size = type.getObjectSize();
ASSERT(expectedBasicType == EbtFloat || expectedBasicType == EbtInt ||
expectedBasicType == EbtUInt || expectedBasicType == EbtBool);
for (size_t component = 0; component < size; ++component, ++constUnion)
{
spirv::IdRef componentId;
// If the constant has a different type than expected, cast it right away.
TConstantUnion castConstant;
bool valid = castConstant.cast(expectedBasicType, *constUnion);
ASSERT(valid);
switch (castConstant.getType())
{
case EbtFloat:
componentId = mBuilder.getFloatConstant(castConstant.getFConst());
break;
case EbtInt:
componentId = mBuilder.getIntConstant(castConstant.getIConst());
break;
case EbtUInt:
componentId = mBuilder.getUintConstant(castConstant.getUConst());
break;
case EbtBool:
componentId = mBuilder.getBoolConstant(castConstant.getBConst());
break;
default:
UNREACHABLE();
}
componentIds.push_back(componentId);
}
}
// If this is a composite, create a composite constant from the components.
if (type.getBasicType() == EbtStruct || componentIds.size() > 1)
{
return createComplexConstant(type, typeId, componentIds);
}
// Otherwise return the sole component.
ASSERT(componentIds.size() == 1);
return componentIds[0];
}
spirv::IdRef OutputSPIRVTraverser::createComplexConstant(const TType &type,
spirv::IdRef typeId,
const spirv::IdRefList ¶meters)
{
if (type.isMatrix() && !type.isArray())
{
// Matrices are constructed from its columns.
spirv::IdRefList columnIds;
SpirvType columnType = mBuilder.getSpirvType(type, EbsUnspecified);
columnType.primarySize = columnType.secondarySize;
columnType.secondarySize = 1;
const spirv::IdRef columnTypeId = mBuilder.getSpirvTypeData(columnType, nullptr).id;
for (int columnIndex = 0; columnIndex < type.getCols(); ++columnIndex)
{
auto columnParametersStart = parameters.begin() + columnIndex * type.getRows();
spirv::IdRefList columnParameters(columnParametersStart,
columnParametersStart + type.getRows());
columnIds.push_back(mBuilder.getCompositeConstant(columnTypeId, columnParameters));
}
return mBuilder.getCompositeConstant(typeId, columnIds);
}
return mBuilder.getCompositeConstant(typeId, parameters);
}
spirv::IdRef OutputSPIRVTraverser::createConstructor(TIntermAggregate *node, spirv::IdRef typeId)
{
const TType &type = node->getType();
const TIntermSequence &arguments = *node->getSequence();
const TType &arg0Type = arguments[0]->getAsTyped()->getType();
// Take each constructor argument that is visited and evaluate it as rvalue
spirv::IdRefList parameters = loadAllParams(node);
// Constructors in GLSL can take various shapes, resulting in different translations to SPIR-V
// (in each case, if the parameter doesn't match the type being constructed, it must be cast):
//
// - float(f): This should translate to just f
// - vecN(f): This should translate to OpCompositeConstruct %vecN %f %f .. %f
// - vecN(v1.zy, v2.x): This can technically translate to OpCompositeConstruct with two ids; the
// results of v1.zy and v2.x. However, for simplicity it's easier to generate that
// instruction with three ids; the results of v1.z, v1.y and v2.x (see below where a matrix is
// used as parameter).
// - vecN(m): This takes N components from m in column-major order (for example, vec4
// constructed out of a 4x3 matrix would select components (0,0), (0,1), (0,2) and (1,0)).
// This translates to OpCompositeConstruct with the id of the individual components extracted
// from m.
// - matNxM(f): This creates a diagonal matrix. It generates N OpCompositeConstruct
// instructions for each column (which are vecM), followed by an OpCompositeConstruct that
// constructs the final result.
// - matNxM(m):
// * With m larger than NxM, this extracts a submatrix out of m. It generates
// OpCompositeExtracts for N columns of m, followed by an OpVectorShuffle (swizzle) if the
// rows of m are more than M. OpCompositeConstruct is used to construct the final result.
// * If m is not larger than NxM, an identity matrix is created and superimposed with m.
// OpCompositeExtract is used to extract each component of m (that is necessary), and
// together with the zero or one constants necessary used to create the columns (with
// OpCompositeConstruct). OpCompositeConstruct is used to construct the final result.
// - matNxM(v1.zy, v2.x, ...): Similarly to constructing a vector, a list of single components
// are extracted from the parameters, which are divided up and used to construct each column,
// which is finally constructed into the final result.
//
// Additionally, array and structs are constructed by OpCompositeConstruct followed by ids of
// each parameter which must enumerate every individual element / field.
// In some cases, constructors with constant value are not folded. That is handled here.
if (node->hasConstantValue())
{
return createComplexConstant(node->getType(), typeId, parameters);
}
if (type.isArray() || type.getStruct() != nullptr)
{
return createArrayOrStructConstructor(node, typeId, parameters);
}
if (type.isScalar())
{
// TODO: handle casting. http://anglebug.com/4889.
return parameters[0];
}
if (type.isVector())
{
if (arguments.size() == 1 && arg0Type.isScalar())
{
return createConstructorVectorFromScalar(node->getType(), typeId, parameters);
}
return createConstructorVectorFromNonScalar(node, typeId, parameters);
}
ASSERT(type.isMatrix());
if (arg0Type.isScalar())
{
return createConstructorMatrixFromScalar(node, typeId, parameters);
}
if (arg0Type.isMatrix())
{
return createConstructorMatrixFromMatrix(node, typeId, parameters);
}
return createConstructorMatrixFromVectors(node, typeId, parameters);
}
spirv::IdRef OutputSPIRVTraverser::createArrayOrStructConstructor(
TIntermAggregate *node,
spirv::IdRef typeId,
const spirv::IdRefList ¶meters)
{
const spirv::IdRef result = mBuilder.getNewId(mBuilder.getDecorations(node->getType()));
spirv::WriteCompositeConstruct(mBuilder.getSpirvCurrentFunctionBlock(), typeId, result,
parameters);
return result;
}
spirv::IdRef OutputSPIRVTraverser::createConstructorVectorFromScalar(
const TType &type,
spirv::IdRef typeId,
const spirv::IdRefList ¶meters)
{
// vecN(f) translates to OpCompositeConstruct %vecN %f ... %f
ASSERT(parameters.size() == 1);
spirv::IdRefList replicatedParameter(type.getNominalSize(), parameters[0]);
const spirv::IdRef result = mBuilder.getNewId(mBuilder.getDecorations(type));
spirv::WriteCompositeConstruct(mBuilder.getSpirvCurrentFunctionBlock(), typeId, result,
replicatedParameter);
return result;
}
spirv::IdRef OutputSPIRVTraverser::createConstructorVectorFromNonScalar(
TIntermAggregate *node,
spirv::IdRef typeId,
const spirv::IdRefList ¶meters)
{
// vecN(v1.zy, v2.x) translates to OpCompositeConstruct %vecN %v1.z %v1.y %v2.x
// vecN(m) translates to OpCompositeConstruct %vecN %m[0][0] %m[0][1] ...
spirv::IdRefList extractedComponents;
extractComponents(node, node->getType().getNominalSize(), parameters, &extractedComponents);
const spirv::IdRef result = mBuilder.getNewId(mBuilder.getDecorations(node->getType()));
spirv::WriteCompositeConstruct(mBuilder.getSpirvCurrentFunctionBlock(), typeId, result,
extractedComponents);
return result;
}
spirv::IdRef OutputSPIRVTraverser::createConstructorMatrixFromScalar(
TIntermAggregate *node,
spirv::IdRef typeId,
const spirv::IdRefList ¶meters)
{
// matNxM(f) translates to
//
// %c0 = OpCompositeConstruct %vecM %f %zero %zero ..
// %c1 = OpCompositeConstruct %vecM %zero %f %zero ..
// %c2 = OpCompositeConstruct %vecM %zero %zero %f ..
// ...
// %m = OpCompositeConstruct %matNxM %c0 %c1 %c2 ...
const TType &type = node->getType();
// TODO: handle casting. http://anglebug.com/4889.
const spirv::IdRef scalarId = parameters[0];
spirv::IdRef zeroId;
SpirvDecorations decorations = mBuilder.getDecorations(type);
switch (type.getBasicType())
{
case EbtFloat:
zeroId = mBuilder.getFloatConstant(0);
break;
case EbtInt:
zeroId = mBuilder.getIntConstant(0);
break;
case EbtUInt:
zeroId = mBuilder.getUintConstant(0);
break;
case EbtBool:
zeroId = mBuilder.getBoolConstant(0);
break;
default:
UNREACHABLE();
}
spirv::IdRefList componentIds(type.getRows(), zeroId);
spirv::IdRefList columnIds;
SpirvType columnType = mBuilder.getSpirvType(type, EbsUnspecified);
columnType.primarySize = columnType.secondarySize;
columnType.secondarySize = 1;
const spirv::IdRef columnTypeId = mBuilder.getSpirvTypeData(columnType, nullptr).id;
for (int columnIndex = 0; columnIndex < type.getCols(); ++columnIndex)
{
columnIds.push_back(mBuilder.getNewId(decorations));
// Place the scalar at the correct index (diagonal of the matrix, i.e. row == col).
componentIds[columnIndex] = scalarId;
if (columnIndex > 0)
{
componentIds[columnIndex - 1] = zeroId;
}
// Create the column.
spirv::WriteCompositeConstruct(mBuilder.getSpirvCurrentFunctionBlock(), columnTypeId,
columnIds.back(), componentIds);
}
// Create the matrix out of the columns.
const spirv::IdRef result = mBuilder.getNewId(decorations);
spirv::WriteCompositeConstruct(mBuilder.getSpirvCurrentFunctionBlock(), typeId, result,
columnIds);
return result;
}
spirv::IdRef OutputSPIRVTraverser::createConstructorMatrixFromVectors(
TIntermAggregate *node,
spirv::IdRef typeId,
const spirv::IdRefList ¶meters)
{
// matNxM(v1.zy, v2.x, ...) translates to:
//
// %c0 = OpCompositeConstruct %vecM %v1.z %v1.y %v2.x ..
// ...
// %m = OpCompositeConstruct %matNxM %c0 %c1 %c2 ...
const TType &type = node->getType();
SpirvDecorations decorations = mBuilder.getDecorations(type);
spirv::IdRefList extractedComponents;
extractComponents(node, type.getCols() * type.getRows(), parameters, &extractedComponents);
spirv::IdRefList columnIds;
SpirvType columnType = mBuilder.getSpirvType(type, EbsUnspecified);
columnType.primarySize = columnType.secondarySize;
columnType.secondarySize = 1;
const spirv::IdRef columnTypeId = mBuilder.getSpirvTypeData(columnType, nullptr).id;
// Chunk up the extracted components by column and construct intermediary vectors.
for (int columnIndex = 0; columnIndex < type.getCols(); ++columnIndex)
{
columnIds.push_back(mBuilder.getNewId(decorations));
auto componentsStart = extractedComponents.begin() + columnIndex * type.getRows();
const spirv::IdRefList componentIds(componentsStart, componentsStart + type.getRows());
// Create the column.
spirv::WriteCompositeConstruct(mBuilder.getSpirvCurrentFunctionBlock(), columnTypeId,
columnIds.back(), componentIds);
}
const spirv::IdRef result = mBuilder.getNewId(decorations);
spirv::WriteCompositeConstruct(mBuilder.getSpirvCurrentFunctionBlock(), typeId, result,
columnIds);
return result;
}
spirv::IdRef OutputSPIRVTraverser::createConstructorMatrixFromMatrix(
TIntermAggregate *node,
spirv::IdRef typeId,
const spirv::IdRefList ¶meters)
{
// matNxM(m) translates to:
//
// - If m is SxR where S>=N and R>=M:
//
// %c0 = OpCompositeExtract %vecR %m 0
// %c1 = OpCompositeExtract %vecR %m 1
// ...
// // If R (column size of m) != M, OpVectorShuffle to extract M components out of %ci.
// ...
// %m = OpCompositeConstruct %matNxM %c0 %c1 %c2 ...
//
// - Otherwise, an identity matrix is created and super imposed by m:
//
// %c0 = OpCompositeConstruct %vecM %m[0][0] %m[0][1] %0 %0
// %c1 = OpCompositeConstruct %vecM %m[1][0] %m[1][1] %0 %0
// %c2 = OpCompositeConstruct %vecM %m[2][0] %m[2][1] %1 %0
// %c3 = OpCompositeConstruct %vecM %0 %0 %0 %1
// %m = OpCompositeConstruct %matNxM %c0 %c1 %c2 %c3
const TType &type = node->getType();
const TType ¶meterType = (*node->getSequence())[0]->getAsTyped()->getType();
SpirvDecorations decorations = mBuilder.getDecorations(type);
// TODO: handle casting. http://anglebug.com/4889.
ASSERT(parameters.size() == 1);
spirv::IdRefList columnIds;
SpirvType columnType = mBuilder.getSpirvType(type, EbsUnspecified);
columnType.primarySize = columnType.secondarySize;
columnType.secondarySize = 1;
const spirv::IdRef columnTypeId = mBuilder.getSpirvTypeData(columnType, nullptr).id;
if (parameterType.getCols() >= type.getCols() && parameterType.getRows() >= type.getRows())
{
// If the parameter is a larger matrix than the constructor type, extract the columns
// directly and potentially swizzle them.
SpirvType paramColumnType = mBuilder.getSpirvType(parameterType, EbsUnspecified);
paramColumnType.secondarySize = 1;
const spirv::IdRef paramColumnTypeId =
mBuilder.getSpirvTypeData(paramColumnType, nullptr).id;
const bool needsSwizzle = parameterType.getRows() > type.getRows();
spirv::LiteralIntegerList swizzle = {spirv::LiteralInteger(0), spirv::LiteralInteger(1),
spirv::LiteralInteger(2), spirv::LiteralInteger(3)};
swizzle.resize(type.getRows());
for (int columnIndex = 0; columnIndex < type.getCols(); ++columnIndex)
{
// Extract the column.
const spirv::IdRef parameterColumnId = mBuilder.getNewId(decorations);
spirv::WriteCompositeExtract(mBuilder.getSpirvCurrentFunctionBlock(), paramColumnTypeId,
parameterColumnId, parameters[0],
{spirv::LiteralInteger(columnIndex)});
// If the column has too many components, select the appropriate number of components.
spirv::IdRef constructorColumnId = parameterColumnId;
if (needsSwizzle)
{
constructorColumnId = mBuilder.getNewId(decorations);
spirv::WriteVectorShuffle(mBuilder.getSpirvCurrentFunctionBlock(), columnTypeId,
constructorColumnId, parameterColumnId, parameterColumnId,
swizzle);
}
columnIds.push_back(constructorColumnId);
}
}
else
{
// Otherwise create an identity matrix and fill in the components that can be taken from the
// given parameter.
SpirvType paramComponentType = mBuilder.getSpirvType(parameterType, EbsUnspecified);
paramComponentType.primarySize = 1;
paramComponentType.secondarySize = 1;
const spirv::IdRef paramComponentTypeId =
mBuilder.getSpirvTypeData(paramComponentType, nullptr).id;
for (int columnIndex = 0; columnIndex < type.getCols(); ++columnIndex)
{
spirv::IdRefList componentIds;
for (int componentIndex = 0; componentIndex < type.getRows(); ++componentIndex)
{
// Take the component from the constructor parameter if possible.
spirv::IdRef componentId;
if (componentIndex < parameterType.getRows())
{
componentId = mBuilder.getNewId(decorations);
spirv::WriteCompositeExtract(mBuilder.getSpirvCurrentFunctionBlock(),
paramComponentTypeId, componentId, parameters[0],
{spirv::LiteralInteger(columnIndex),
spirv::LiteralInteger(componentIndex)});
}
else
{
const bool isOnDiagonal = columnIndex == componentIndex;
switch (type.getBasicType())
{
case EbtFloat:
componentId = mBuilder.getFloatConstant(isOnDiagonal ? 0.0f : 1.0f);
break;
case EbtInt:
componentId = mBuilder.getIntConstant(isOnDiagonal ? 0 : 1);
break;
case EbtUInt:
componentId = mBuilder.getUintConstant(isOnDiagonal ? 0 : 1);
break;
case EbtBool:
componentId = mBuilder.getBoolConstant(isOnDiagonal);
break;
default:
UNREACHABLE();
}
}
componentIds.push_back(componentId);
}
// Create the column vector.
columnIds.push_back(mBuilder.getNewId(decorations));
spirv::WriteCompositeConstruct(mBuilder.getSpirvCurrentFunctionBlock(), columnTypeId,
columnIds.back(), componentIds);
}
}
const spirv::IdRef result = mBuilder.getNewId(decorations);
spirv::WriteCompositeConstruct(mBuilder.getSpirvCurrentFunctionBlock(), typeId, result,
columnIds);
return result;
}
spirv::IdRefList OutputSPIRVTraverser::loadAllParams(TIntermOperator *node)
{
const size_t parameterCount = node->getChildCount();
spirv::IdRefList parameters;
for (size_t paramIndex = 0; paramIndex < parameterCount; ++paramIndex)
{
// Take each parameter that is visited and evaluate it as rvalue
NodeData ¶m = mNodeData[mNodeData.size() - parameterCount + paramIndex];
const spirv::IdRef paramValue = accessChainLoad(
¶m,
mBuilder.getDecorations(node->getChildNode(paramIndex)->getAsTyped()->getType()));
// TODO: handle mismatching types. http://anglebug.com/6000
parameters.push_back(paramValue);
}
return parameters;
}
void OutputSPIRVTraverser::extractComponents(TIntermAggregate *node,
size_t componentCount,
const spirv::IdRefList ¶meters,
spirv::IdRefList *extractedComponentsOut)
{
// A helper function that takes the list of parameters passed to a constructor (which may have
// more components than necessary) and extracts the first componentCount components.
const TIntermSequence &arguments = *node->getSequence();
SpirvDecorations decorations = mBuilder.getDecorations(node->getType());
// TODO: handle casting. http://anglebug.com/4889.
ASSERT(arguments.size() == parameters.size());
for (size_t argumentIndex = 0;
argumentIndex < arguments.size() && extractedComponentsOut->size() < componentCount;
++argumentIndex)
{
const TType &argumentType = arguments[argumentIndex]->getAsTyped()->getType();
const spirv::IdRef parameterId = parameters[argumentIndex];
if (argumentType.isScalar())
{
// For scalar parameters, there's nothing to do.
extractedComponentsOut->push_back(parameterId);
continue;
}
if (argumentType.isVector())
{
SpirvType componentType = mBuilder.getSpirvType(argumentType, EbsUnspecified);
componentType.primarySize = 1;
const spirv::IdRef componentTypeId =
mBuilder.getSpirvTypeData(componentType, nullptr).id;
// For vector parameters, take components out of the vector one by one.
for (int componentIndex = 0; componentIndex < argumentType.getNominalSize() &&
extractedComponentsOut->size() < componentCount;
++componentIndex)
{
const spirv::IdRef componentId = mBuilder.getNewId(decorations);
spirv::WriteCompositeExtract(mBuilder.getSpirvCurrentFunctionBlock(),
componentTypeId, componentId, parameterId,
{spirv::LiteralInteger(componentIndex)});
extractedComponentsOut->push_back(componentId);
}
continue;
}
ASSERT(argumentType.isMatrix());
SpirvType componentType = mBuilder.getSpirvType(argumentType, EbsUnspecified);
componentType.primarySize = 1;
componentType.secondarySize = 1;
const spirv::IdRef componentTypeId = mBuilder.getSpirvTypeData(componentType, nullptr).id;
// For matrix parameters, take components out of the matrix one by one in column-major
// order.
for (int columnIndex = 0; columnIndex < argumentType.getCols() &&
extractedComponentsOut->size() < componentCount;
++columnIndex)
{
for (int componentIndex = 0; componentIndex < argumentType.getRows() &&
extractedComponentsOut->size() < componentCount;
++componentIndex)
{
const spirv::IdRef componentId = mBuilder.getNewId(decorations);
spirv::WriteCompositeExtract(
mBuilder.getSpirvCurrentFunctionBlock(), componentTypeId, componentId,
parameterId,
{spirv::LiteralInteger(columnIndex), spirv::LiteralInteger(componentIndex)});
extractedComponentsOut->push_back(componentId);
}
}
}
}
void OutputSPIRVTraverser::startShortCircuit(TIntermBinary *node)
{
// Emulate && and || as such:
//
// || => if (!left) result = right
// && => if ( left) result = right
//
// When this function is called, |left| has already been visited, so it creates the appropriate
// |if| construct in preparation for visiting |right|.
// Load |left| and replace the access chain with an rvalue that's the result.
const spirv::IdRef typeId = getAccessChainTypeId(&mNodeData.back());
const spirv::IdRef left =
accessChainLoad(&mNodeData.back(), mBuilder.getDecorations(node->getLeft()->getType()));
nodeDataInitRValue(&mNodeData.back(), left, typeId);
// Keep the id of the block |left| was evaluated in.
mNodeData.back().idList.push_back(mBuilder.getSpirvCurrentFunctionBlockId());
// Two blocks necessary, one for the |if| block, and one for the merge block.
mBuilder.startConditional(2, false, false);
// Generate the branch instructions.
const SpirvConditional *conditional = mBuilder.getCurrentConditional();
const spirv::IdRef mergeBlock = conditional->blockIds.back();
const spirv::IdRef ifBlock = conditional->blockIds.front();
const spirv::IdRef trueBlock = node->getOp() == EOpLogicalAnd ? ifBlock : mergeBlock;
const spirv::IdRef falseBlock = node->getOp() == EOpLogicalOr ? ifBlock : mergeBlock;
// Note that no logical not is necessary. For ||, the branch will target the merge block in the
// true case.
mBuilder.writeBranchConditional(left, trueBlock, falseBlock, mergeBlock);
}
spirv::IdRef OutputSPIRVTraverser::endShortCircuit(TIntermBinary *node, spirv::IdRef *typeId)
{
// Load the right hand side.
const spirv::IdRef right =
accessChainLoad(&mNodeData.back(), mBuilder.getDecorations(node->getRight()->getType()));
mNodeData.pop_back();
// Get the id of the block |right| is evaluated in.
const spirv::IdRef rightBlockId = mBuilder.getSpirvCurrentFunctionBlockId();
// And the cached id of the block |left| is evaluated in.
ASSERT(mNodeData.back().idList.size() == 1);
const spirv::IdRef leftBlockId = mNodeData.back().idList[0].id;
mNodeData.back().idList.clear();
// Move on to the merge block.
mBuilder.writeBranchConditionalBlockEnd();
// Pop from the conditional stack.
mBuilder.endConditional();
// Get the previously loaded result of the left hand side.
*typeId = getAccessChainTypeId(&mNodeData.back());
const spirv::IdRef left = mNodeData.back().baseId;
// Create an OpPhi instruction that selects either the |left| or |right| based on which block
// was traversed.
const spirv::IdRef result = mBuilder.getNewId(mBuilder.getDecorations(node->getType()));
spirv::WritePhi(
mBuilder.getSpirvCurrentFunctionBlock(), *typeId, result,
{spirv::PairIdRefIdRef{left, leftBlockId}, spirv::PairIdRefIdRef{right, rightBlockId}});
return result;
}
spirv::IdRef OutputSPIRVTraverser::createFunctionCall(TIntermAggregate *node,
spirv::IdRef resultTypeId)
{
const TFunction *function = node->getFunction();
ASSERT(function);
ASSERT(mFunctionIdMap.count(function) > 0);
const spirv::IdRef functionId = mFunctionIdMap[function].functionId;
// Get the list of parameters passed to the function. The function parameters can only be
// memory variables, or if the function argument is |const|, an rvalue.
//
// For in variables:
//
// - If the parameter is const, pass it directly as rvalue, otherwise
// - If the parameter is an unindexed lvalue, pass it directly, otherwise
// - Write it to a temp variable first and pass that.
//
// For out variables:
//
// - If the parameter is an unindexed lvalue, pass it directly, otherwise
// - Pass a temporary variable. After the function call, copy that variable to the parameter.
//
// For inout variables:
//
// - If the parameter is an unindexed lvalue, pass it directly, otherwise
// - Write the parameter to a temp variable and pass that. After the function call, copy that
// variable back to the parameter.
//
// - For opaque uniforms, pass it directly as lvalue,
//
const size_t parameterCount = node->getChildCount();
spirv::IdRefList parameters;
spirv::IdRefList tempVarIds(parameterCount);
spirv::IdRefList tempVarTypeIds(parameterCount);
for (size_t paramIndex = 0; paramIndex < parameterCount; ++paramIndex)
{
const TType ¶mType = function->getParam(paramIndex)->getType();
const TQualifier ¶mQualifier = paramType.getQualifier();
NodeData ¶m = mNodeData[mNodeData.size() - parameterCount + paramIndex];
spirv::IdRef paramValue;
SpirvDecorations decorations = mBuilder.getDecorations(paramType);
if (IsOpaqueType(paramType.getBasicType()) || paramQualifier == EvqConst)
{
// The following parameters are passed as rvalue:
//
// - Opaque uniforms,
// - const parameters,
paramValue = accessChainLoad(¶m, decorations);
}
else if (IsAccessChainUnindexedLValue(param) &&
(mCompileOptions & SH_GENERATE_SPIRV_WORKAROUNDS) == 0)
{
// The following parameters are passed directly:
//
// - unindexed lvalues.
//
// This optimization is not applied on buggy drivers. http://anglebug.com/6110.
paramValue = param.baseId;
}
else
{
ASSERT(paramQualifier == EvqIn || paramQualifier == EvqOut ||
paramQualifier == EvqInOut);
// Need to create a temp variable and pass that.
tempVarTypeIds[paramIndex] = mBuilder.getTypeData(paramType, EbsUnspecified).id;
tempVarIds[paramIndex] =
mBuilder.declareVariable(tempVarTypeIds[paramIndex], spv::StorageClassFunction,
decorations, nullptr, "param");
// If it's an in or inout parameter, the temp variable needs to be initialized with the
// value of the parameter first.
//
// TODO: handle mismatching types. http://anglebug.com/6000
if (paramQualifier == EvqIn || paramQualifier == EvqInOut)
{
paramValue = accessChainLoad(¶m, decorations);
spirv::WriteStore(mBuilder.getSpirvCurrentFunctionBlock(), tempVarIds[paramIndex],
paramValue, nullptr);
}
paramValue = tempVarIds[paramIndex];
}
parameters.push_back(paramValue);
}
// Make the actual function call.
const spirv::IdRef result = mBuilder.getNewId(mBuilder.getDecorations(node->getType()));
spirv::WriteFunctionCall(mBuilder.getSpirvCurrentFunctionBlock(), resultTypeId, result,
functionId, parameters);
// Copy from the out and inout temp variables back to the original parameters.
for (size_t paramIndex = 0; paramIndex < parameterCount; ++paramIndex)
{
if (!tempVarIds[paramIndex].valid())
{
continue;
}
const TType ¶mType = function->getParam(paramIndex)->getType();
const TQualifier ¶mQualifier = paramType.getQualifier();
NodeData ¶m = mNodeData[mNodeData.size() - parameterCount + paramIndex];
if (paramQualifier == EvqIn)
{
continue;
}
// Copy from the temp variable to the parameter.
//
// TODO: handle mismatching types. http://anglebug.com/6000
NodeData tempVarData;
nodeDataInitLValue(&tempVarData, tempVarIds[paramIndex], tempVarTypeIds[paramIndex],
spv::StorageClassFunction, EbsUnspecified);
const spirv::IdRef tempVarValue =
accessChainLoad(&tempVarData, mBuilder.getDecorations(paramType));
accessChainStore(¶m, tempVarValue);
}
return result;
}
bool IsShortCircuitNeeded(TIntermOperator *node)
{
TOperator op = node->getOp();
// Short circuit is only necessary for && and ||.
if (op != EOpLogicalAnd && op != EOpLogicalOr)
{
return false;
}
ASSERT(node->getChildCount() == 2);
// If the right hand side does not have side effects, short-circuiting is unnecessary.
// TODO: experiment with the performance of OpLogicalAnd/Or vs short-circuit based on the
// complexity of the right hand side expression. We could potentially only allow
// OpLogicalAnd/Or if the right hand side is a constant or an access chain and have more complex
// expressions be placed inside an if block. http://anglebug.com/4889
return node->getChildNode(1)->getAsTyped()->hasSideEffects();
}
using WriteUnaryOp = void (*)(spirv::Blob *blob,
spirv::IdResultType idResultType,
spirv::IdResult idResult,
spirv::IdRef operand);
using WriteBinaryOp = void (*)(spirv::Blob *blob,
spirv::IdResultType idResultType,
spirv::IdResult idResult,
spirv::IdRef operand1,
spirv::IdRef operand2);
using WriteTernaryOp = void (*)(spirv::Blob *blob,
spirv::IdResultType idResultType,
spirv::IdResult idResult,
spirv::IdRef operand1,
spirv::IdRef operand2,
spirv::IdRef operand3);
using WriteQuaternaryOp = void (*)(spirv::Blob *blob,
spirv::IdResultType idResultType,
spirv::IdResult idResult,
spirv::IdRef operand1,
spirv::IdRef operand2,
spirv::IdRef operand3,
spirv::IdRef operand4);
using WriteAtomicOp = void (*)(spirv::Blob *blob,
spirv::IdResultType idResultType,
spirv::IdResult idResult,
spirv::IdRef pointer,
spirv::IdScope scope,
spirv::IdMemorySemantics semantics,
spirv::IdRef value);
spirv::IdRef OutputSPIRVTraverser::visitOperator(TIntermOperator *node, spirv::IdRef resultTypeId)
{
// Handle special groups.
const TOperator op = node->getOp();
if (op == EOpPostIncrement || op == EOpPreIncrement || op == EOpPostDecrement ||
op == EOpPreDecrement)
{
return createIncrementDecrement(node, resultTypeId);
}
if (BuiltInGroup::IsAtomicMemory(op) || BuiltInGroup::IsImageAtomic(op))
{
return createAtomicBuiltIn(node, resultTypeId);
}
if (BuiltInGroup::IsTexture(op))
{
return createTextureBuiltIn(node, resultTypeId);
}
if (BuiltInGroup::IsImage(op))
{
return createImageBuiltIn(node, resultTypeId);
}
const size_t childCount = node->getChildCount();
TIntermTyped *firstChild = node->getChildNode(0)->getAsTyped();
const TType &firstOperandType = firstChild->getType();
const TBasicType basicType = firstOperandType.getBasicType();
const bool isFloat = basicType == EbtFloat || basicType == EbtDouble;
const bool isUnsigned = basicType == EbtUInt;
const bool isBool = basicType == EbtBool;
// Whether the operation needs to be applied column by column.
TIntermBinary *asBinary = node->getAsBinaryNode();
bool operateOnColumns = asBinary && (asBinary->getLeft()->getType().isMatrix() ||
asBinary->getRight()->getType().isMatrix());
// Whether the operands need to be swapped in the (binary) instruction
bool binarySwapOperands = false;
// Whether the scalar operand needs to be extended to match the other operand which is a vector
// (in a binary operation).
bool binaryExtendScalarToVector = true;
WriteUnaryOp writeUnaryOp = nullptr;
WriteBinaryOp writeBinaryOp = nullptr;
WriteTernaryOp writeTernaryOp = nullptr;
WriteQuaternaryOp writeQuaternaryOp = nullptr;
// Some operators are implemented with an extended instruction.
spv::GLSLstd450 extendedInst = spv::GLSLstd450Bad;
switch (op)
{
case EOpNegative:
if (isFloat)
writeUnaryOp = spirv::WriteFNegate;
else
writeUnaryOp = spirv::WriteSNegate;
break;
case EOpPositive:
// This is a noop.
return accessChainLoad(&mNodeData.back(), mBuilder.getDecorations(firstOperandType));
case EOpLogicalNot:
case EOpNotComponentWise:
writeUnaryOp = spirv::WriteLogicalNot;
break;
case EOpBitwiseNot:
writeUnaryOp = spirv::WriteNot;
break;
case EOpAdd:
case EOpAddAssign:
if (isFloat)
writeBinaryOp = spirv::WriteFAdd;
else
writeBinaryOp = spirv::WriteIAdd;
break;
case EOpSub:
case EOpSubAssign:
if (isFloat)
writeBinaryOp = spirv::WriteFSub;
else
writeBinaryOp = spirv::WriteISub;
break;
case EOpMul:
case EOpMulAssign:
case EOpMatrixCompMult:
if (isFloat)
writeBinaryOp = spirv::WriteFMul;
else
writeBinaryOp = spirv::WriteIMul;
break;
case EOpDiv:
case EOpDivAssign:
if (isFloat)
writeBinaryOp = spirv::WriteFDiv;
else if (isUnsigned)
writeBinaryOp = spirv::WriteUDiv;
else
writeBinaryOp = spirv::WriteSDiv;
break;
case EOpIMod:
case EOpIModAssign:
if (isFloat)
writeBinaryOp = spirv::WriteFMod;
else if (isUnsigned)
writeBinaryOp = spirv::WriteUMod;
else
writeBinaryOp = spirv::WriteSMod;
break;
case EOpEqual:
case EOpEqualComponentWise:
// TODO: handle vector, matrix and other complex comparisons. EOpEqual must use OpAll
// to reduce to a bool. http://anglebug.com/4889.
if (isFloat)
writeBinaryOp = spirv::WriteFOrdEqual;
else if (isBool)
writeBinaryOp = spirv::WriteLogicalEqual;
else
writeBinaryOp = spirv::WriteIEqual;
break;
case EOpNotEqual:
case EOpNotEqualComponentWise:
// TODO: handle vector, matrix and other complex comparisons. EOpNotEqual must use
// OpAny to reduce to a bool. http://anglebug.com/4889.
if (isFloat)
writeBinaryOp = spirv::WriteFUnordNotEqual;
else if (isBool)
writeBinaryOp = spirv::WriteLogicalNotEqual;
else
writeBinaryOp = spirv::WriteINotEqual;
break;
case EOpLessThan:
case EOpLessThanComponentWise:
if (isFloat)
writeBinaryOp = spirv::WriteFOrdLessThan;
else if (isUnsigned)
writeBinaryOp = spirv::WriteULessThan;
else
writeBinaryOp = spirv::WriteSLessThan;
break;
case EOpGreaterThan:
case EOpGreaterThanComponentWise:
if (isFloat)
writeBinaryOp = spirv::WriteFOrdGreaterThan;
else if (isUnsigned)
writeBinaryOp = spirv::WriteUGreaterThan;
else
writeBinaryOp = spirv::WriteSGreaterThan;
break;
case EOpLessThanEqual:
case EOpLessThanEqualComponentWise:
if (isFloat)
writeBinaryOp = spirv::WriteFOrdLessThanEqual;
else if (isUnsigned)
writeBinaryOp = spirv::WriteULessThanEqual;
else
writeBinaryOp = spirv::WriteSLessThanEqual;
break;
case EOpGreaterThanEqual:
case EOpGreaterThanEqualComponentWise:
if (isFloat)
writeBinaryOp = spirv::WriteFOrdGreaterThanEqual;
else if (isUnsigned)
writeBinaryOp = spirv::WriteUGreaterThanEqual;
else
writeBinaryOp = spirv::WriteSGreaterThanEqual;
break;
case EOpVectorTimesScalar:
case EOpVectorTimesScalarAssign:
if (isFloat)
{
writeBinaryOp = spirv::WriteVectorTimesScalar;
binarySwapOperands = node->getChildNode(1)->getAsTyped()->getType().isVector();
binaryExtendScalarToVector = false;
}
else
writeBinaryOp = spirv::WriteIMul;
break;
case EOpVectorTimesMatrix:
case EOpVectorTimesMatrixAssign:
writeBinaryOp = spirv::WriteVectorTimesMatrix;
operateOnColumns = false;
break;
case EOpMatrixTimesVector:
writeBinaryOp = spirv::WriteMatrixTimesVector;
operateOnColumns = false;
break;
case EOpMatrixTimesScalar:
case EOpMatrixTimesScalarAssign:
writeBinaryOp = spirv::WriteMatrixTimesScalar;
binarySwapOperands = asBinary->getRight()->getType().isMatrix();
operateOnColumns = false;
break;
case EOpMatrixTimesMatrix:
case EOpMatrixTimesMatrixAssign:
writeBinaryOp = spirv::WriteMatrixTimesMatrix;
operateOnColumns = false;
break;
case EOpLogicalOr:
ASSERT(!IsShortCircuitNeeded(node));
binaryExtendScalarToVector = false;
writeBinaryOp = spirv::WriteLogicalOr;
break;
case EOpLogicalXor:
binaryExtendScalarToVector = false;
writeBinaryOp = spirv::WriteLogicalNotEqual;
break;
case EOpLogicalAnd:
ASSERT(!IsShortCircuitNeeded(node));
binaryExtendScalarToVector = false;
writeBinaryOp = spirv::WriteLogicalAnd;
break;
case EOpBitShiftLeft:
case EOpBitShiftLeftAssign:
writeBinaryOp = spirv::WriteShiftLeftLogical;
break;
case EOpBitShiftRight:
case EOpBitShiftRightAssign:
if (isUnsigned)
writeBinaryOp = spirv::WriteShiftRightLogical;
else
writeBinaryOp = spirv::WriteShiftRightArithmetic;
break;
case EOpBitwiseAnd:
case EOpBitwiseAndAssign:
writeBinaryOp = spirv::WriteBitwiseAnd;
break;
case EOpBitwiseXor:
case EOpBitwiseXorAssign:
writeBinaryOp = spirv::WriteBitwiseXor;
break;
case EOpBitwiseOr:
case EOpBitwiseOrAssign:
writeBinaryOp = spirv::WriteBitwiseOr;
break;
case EOpRadians:
extendedInst = spv::GLSLstd450Radians;
break;
case EOpDegrees:
extendedInst = spv::GLSLstd450Degrees;
break;
case EOpSin:
extendedInst = spv::GLSLstd450Sin;
break;
case EOpCos:
extendedInst = spv::GLSLstd450Cos;
break;
case EOpTan:
extendedInst = spv::GLSLstd450Tan;
break;
case EOpAsin:
extendedInst = spv::GLSLstd450Asin;
break;
case EOpAcos:
extendedInst = spv::GLSLstd450Acos;
break;
case EOpAtan:
extendedInst = spv::GLSLstd450Atan;
break;
case EOpSinh:
extendedInst = spv::GLSLstd450Sinh;
break;
case EOpCosh:
extendedInst = spv::GLSLstd450Cosh;
break;
case EOpTanh:
extendedInst = spv::GLSLstd450Tanh;
break;
case EOpAsinh:
extendedInst = spv::GLSLstd450Asinh;
break;
case EOpAcosh:
extendedInst = spv::GLSLstd450Acosh;
break;
case EOpAtanh:
extendedInst = spv::GLSLstd450Atanh;
break;
case EOpPow:
extendedInst = spv::GLSLstd450Pow;
break;
case EOpExp:
extendedInst = spv::GLSLstd450Exp;
break;
case EOpLog:
extendedInst = spv::GLSLstd450Log;
break;
case EOpExp2:
extendedInst = spv::GLSLstd450Exp2;
break;
case EOpLog2:
extendedInst = spv::GLSLstd450Log2;
break;
case EOpSqrt:
extendedInst = spv::GLSLstd450Sqrt;
break;
case EOpInversesqrt:
extendedInst = spv::GLSLstd450InverseSqrt;
break;
case EOpAbs:
if (isFloat)
extendedInst = spv::GLSLstd450FAbs;
else
extendedInst = spv::GLSLstd450SAbs;
break;
case EOpSign:
if (isFloat)
extendedInst = spv::GLSLstd450FSign;
else
extendedInst = spv::GLSLstd450SSign;
break;
case EOpFloor:
extendedInst = spv::GLSLstd450Floor;
break;
case EOpTrunc:
extendedInst = spv::GLSLstd450Trunc;
break;
case EOpRound:
extendedInst = spv::GLSLstd450Round;
break;
case EOpRoundEven:
extendedInst = spv::GLSLstd450RoundEven;
break;
case EOpCeil:
extendedInst = spv::GLSLstd450Ceil;
break;
case EOpFract:
extendedInst = spv::GLSLstd450Fract;
break;
case EOpMod:
if (isFloat)
writeBinaryOp = spirv::WriteFMod;
else if (isUnsigned)
writeBinaryOp = spirv::WriteUMod;
else
writeBinaryOp = spirv::WriteSMod;
break;
case EOpMin:
if (isFloat)
extendedInst = spv::GLSLstd450FMin;
else if (isUnsigned)
extendedInst = spv::GLSLstd450UMin;
else
extendedInst = spv::GLSLstd450SMin;
break;
case EOpMax:
if (isFloat)
extendedInst = spv::GLSLstd450FMax;
else if (isUnsigned)
extendedInst = spv::GLSLstd450UMax;
else
extendedInst = spv::GLSLstd450SMax;
break;
case EOpClamp:
if (isFloat)
extendedInst = spv::GLSLstd450FClamp;
else if (isUnsigned)
extendedInst = spv::GLSLstd450UClamp;
else
extendedInst = spv::GLSLstd450SClamp;
break;
case EOpMix:
if (node->getChildNode(childCount - 1)->getAsTyped()->getType().getBasicType() ==
EbtBool)
{
writeTernaryOp = spirv::WriteSelect;
}
else
{
ASSERT(isFloat);
extendedInst = spv::GLSLstd450FMix;
}
break;
case EOpStep:
extendedInst = spv::GLSLstd450Step;
break;
case EOpSmoothstep:
extendedInst = spv::GLSLstd450SmoothStep;
break;
case EOpModf:
// TODO: modf has an out parameter. http://anglebug.com/4889.
UNIMPLEMENTED();
break;
case EOpIsnan:
writeUnaryOp = spirv::WriteIsNan;
break;
case EOpIsinf:
writeUnaryOp = spirv::WriteIsInf;
break;
case EOpFloatBitsToInt:
case EOpFloatBitsToUint:
case EOpIntBitsToFloat:
case EOpUintBitsToFloat:
writeUnaryOp = spirv::WriteBitcast;
break;
case EOpFma:
extendedInst = spv::GLSLstd450Fma;
break;
case EOpFrexp:
// TODO: frexp has an out parameter. http://anglebug.com/4889.
UNIMPLEMENTED();
break;
case EOpLdexp:
extendedInst = spv::GLSLstd450Ldexp;
break;
case EOpPackSnorm2x16:
extendedInst = spv::GLSLstd450PackSnorm2x16;
break;
case EOpPackUnorm2x16:
extendedInst = spv::GLSLstd450PackUnorm2x16;
break;
case EOpPackHalf2x16:
extendedInst = spv::GLSLstd450PackHalf2x16;
break;
case EOpUnpackSnorm2x16:
extendedInst = spv::GLSLstd450UnpackSnorm2x16;
break;
case EOpUnpackUnorm2x16:
extendedInst = spv::GLSLstd450UnpackUnorm2x16;
break;
case EOpUnpackHalf2x16:
extendedInst = spv::GLSLstd450UnpackHalf2x16;
break;
case EOpPackUnorm4x8:
extendedInst = spv::GLSLstd450PackUnorm4x8;
break;
case EOpPackSnorm4x8:
extendedInst = spv::GLSLstd450PackSnorm4x8;
break;
case EOpUnpackUnorm4x8:
extendedInst = spv::GLSLstd450UnpackUnorm4x8;
break;
case EOpUnpackSnorm4x8:
extendedInst = spv::GLSLstd450UnpackSnorm4x8;
break;
case EOpPackDouble2x32:
case EOpUnpackDouble2x32:
// TODO: support desktop GLSL. http://anglebug.com/4889
UNIMPLEMENTED();
break;
case EOpLength:
extendedInst = spv::GLSLstd450Length;
break;
case EOpDistance:
extendedInst = spv::GLSLstd450Distance;
break;
case EOpDot:
// Use normal multiplication for scalars.
if (firstOperandType.isScalar())
{
if (isFloat)
writeBinaryOp = spirv::WriteFMul;
else
writeBinaryOp = spirv::WriteIMul;
}
else
{
writeBinaryOp = spirv::WriteDot;
}
break;
case EOpCross:
extendedInst = spv::GLSLstd450Cross;
break;
case EOpNormalize:
extendedInst = spv::GLSLstd450Normalize;
break;
case EOpFaceforward:
extendedInst = spv::GLSLstd450FaceForward;
break;
case EOpReflect:
extendedInst = spv::GLSLstd450Reflect;
break;
case EOpRefract:
extendedInst = spv::GLSLstd450Refract;
break;
case EOpFtransform:
// TODO: support desktop GLSL. http://anglebug.com/4889
UNIMPLEMENTED();
break;
case EOpOuterProduct:
writeBinaryOp = spirv::WriteOuterProduct;
break;
case EOpTranspose:
writeUnaryOp = spirv::WriteTranspose;
break;
case EOpDeterminant:
extendedInst = spv::GLSLstd450Determinant;
break;
case EOpInverse:
extendedInst = spv::GLSLstd450MatrixInverse;
break;
case EOpAny:
writeUnaryOp = spirv::WriteAny;
break;
case EOpAll:
writeUnaryOp = spirv::WriteAll;
break;
case EOpBitfieldExtract:
if (isUnsigned)
writeTernaryOp = spirv::WriteBitFieldUExtract;
else
writeTernaryOp = spirv::WriteBitFieldSExtract;
break;
case EOpBitfieldInsert:
writeQuaternaryOp = spirv::WriteBitFieldInsert;
break;
case EOpBitfieldReverse:
writeUnaryOp = spirv::WriteBitReverse;
break;
case EOpBitCount:
writeUnaryOp = spirv::WriteBitCount;
break;
case EOpFindLSB:
extendedInst = spv::GLSLstd450FindILsb;
break;
case EOpFindMSB:
if (isUnsigned)
extendedInst = spv::GLSLstd450FindUMsb;
else
extendedInst = spv::GLSLstd450FindSMsb;
break;
case EOpUaddCarry:
// TODO: uaddCarry has an out parameter. http://anglebug.com/4889.
UNIMPLEMENTED();
break;
case EOpUsubBorrow:
// TODO: usubBorrow has an out parameter. http://anglebug.com/4889.
UNIMPLEMENTED();
break;
case EOpUmulExtended:
// TODO: umulExtended has an out parameter. http://anglebug.com/4889.
UNIMPLEMENTED();
break;
case EOpImulExtended:
// TODO: imulExtended has an out parameter. http://anglebug.com/4889.
UNIMPLEMENTED();
break;
case EOpRgb_2_yuv:
case EOpYuv_2_rgb:
// TODO: There doesn't seem to be an equivalent in SPIR-V, and should likley be emulated
// as an AST transformation. Not supported by the Vulkan at the moment.
// http://anglebug.com/4889.
UNIMPLEMENTED();
break;
case EOpDFdx:
writeUnaryOp = spirv::WriteDPdx;
break;
case EOpDFdy:
writeUnaryOp = spirv::WriteDPdy;
break;
case EOpFwidth:
writeUnaryOp = spirv::WriteFwidth;
break;
case EOpDFdxFine:
writeUnaryOp = spirv::WriteDPdxFine;
break;
case EOpDFdyFine:
writeUnaryOp = spirv::WriteDPdyFine;
break;
case EOpDFdxCoarse:
writeUnaryOp = spirv::WriteDPdxCoarse;
break;
case EOpDFdyCoarse:
writeUnaryOp = spirv::WriteDPdyCoarse;
break;
case EOpFwidthFine:
writeUnaryOp = spirv::WriteFwidthFine;
break;
case EOpFwidthCoarse:
writeUnaryOp = spirv::WriteFwidthCoarse;
break;
// TODO: for the EOpInterpolate* built-ins, must convert interpolateX(vec.yz) to
// interpolate(vec).yz. This can either be done apriori by an AST transformation, or
// simply by taking the base id only when generating the instruction and keeping the
// indices/swizzle intact. http://anglebug.com/4889.
case EOpInterpolateAtCentroid:
extendedInst = spv::GLSLstd450InterpolateAtCentroid;
break;
case EOpInterpolateAtSample:
extendedInst = spv::GLSLstd450InterpolateAtSample;
break;
case EOpInterpolateAtOffset:
extendedInst = spv::GLSLstd450InterpolateAtOffset;
break;
case EOpNoise1:
case EOpNoise2:
case EOpNoise3:
case EOpNoise4:
// TODO: support desktop GLSL. http://anglebug.com/4889
UNIMPLEMENTED();
break;
case EOpSubpassLoad:
// TODO: support framebuffer fetch. http://anglebug.com/4889
UNIMPLEMENTED();
break;
case EOpAnyInvocation:
case EOpAllInvocations:
case EOpAllInvocationsEqual:
// TODO: support desktop GLSL. http://anglebug.com/4889
break;
default:
UNREACHABLE();
}
const SpirvDecorations decorations = mBuilder.getDecorations(node->getType());
spirv::IdRef result = mBuilder.getNewId(decorations);
// Load the parameters.
spirv::IdRefList parameters = loadAllParams(node);
if (operateOnColumns)
{
// If negating a matrix or multiplying them, do that column by column.
spirv::IdRefList columnIds;
const SpirvDecorations operandDecorations = mBuilder.getDecorations(firstOperandType);
SpirvType columnType = mBuilder.getSpirvType(firstOperandType, EbsUnspecified);
columnType.primarySize = columnType.secondarySize;
columnType.secondarySize = 1;
const spirv::IdRef columnTypeId = mBuilder.getSpirvTypeData(columnType, nullptr).id;
if (binarySwapOperands)
{
std::swap(parameters[0], parameters[1]);
}
// Extract and apply the operator to each column.
for (int columnIndex = 0; columnIndex < firstOperandType.getCols(); ++columnIndex)
{
const spirv::IdRef columnIdA = mBuilder.getNewId(operandDecorations);
spirv::WriteCompositeExtract(mBuilder.getSpirvCurrentFunctionBlock(), columnTypeId,
columnIdA, parameters[0],
{spirv::LiteralInteger(columnIndex)});
columnIds.push_back(mBuilder.getNewId(decorations));
if (writeUnaryOp)
{
writeUnaryOp(mBuilder.getSpirvCurrentFunctionBlock(), columnTypeId,
columnIds.back(), columnIdA);
}
else
{
ASSERT(writeBinaryOp);
const spirv::IdRef columnIdB = mBuilder.getNewId(operandDecorations);
spirv::WriteCompositeExtract(mBuilder.getSpirvCurrentFunctionBlock(), columnTypeId,
columnIdB, parameters[1],
{spirv::LiteralInteger(columnIndex)});
writeBinaryOp(mBuilder.getSpirvCurrentFunctionBlock(), columnTypeId,
columnIds.back(), columnIdA, columnIdB);
}
}
// Construct the result.
spirv::WriteCompositeConstruct(mBuilder.getSpirvCurrentFunctionBlock(), resultTypeId,
result, columnIds);
}
else if (writeUnaryOp)
{
ASSERT(parameters.size() == 1);
writeUnaryOp(mBuilder.getSpirvCurrentFunctionBlock(), resultTypeId, result, parameters[0]);
}
else if (writeBinaryOp)
{
ASSERT(parameters.size() == 2);
// For vector<op>scalar operations that require it, turn the scalar into a vector of the
// same size.
if (binaryExtendScalarToVector)
{
const TType &leftType = node->getChildNode(0)->getAsTyped()->getType();
const TType &rightType = node->getChildNode(1)->getAsTyped()->getType();
if (leftType.isScalar() && rightType.isVector())
{
parameters[0] =
createConstructorVectorFromScalar(rightType, resultTypeId, {{parameters[0]}});
}
else if (rightType.isScalar() && leftType.isVector())
{
parameters[1] =
createConstructorVectorFromScalar(leftType, resultTypeId, {{parameters[1]}});
}
}
if (binarySwapOperands)
{
std::swap(parameters[0], parameters[1]);
}
// Write the operation that combines the left and right values.
writeBinaryOp(mBuilder.getSpirvCurrentFunctionBlock(), resultTypeId, result, parameters[0],
parameters[1]);
}
else if (writeTernaryOp)
{
ASSERT(parameters.size() == 3);
// mix(a, b, bool) is the same as bool ? b : a;
if (op == EOpMix)
{
std::swap(parameters[0], parameters[2]);
}
writeTernaryOp(mBuilder.getSpirvCurrentFunctionBlock(), resultTypeId, result, parameters[0],
parameters[1], parameters[2]);
}
else if (writeQuaternaryOp)
{
ASSERT(parameters.size() == 4);
writeQuaternaryOp(mBuilder.getSpirvCurrentFunctionBlock(), resultTypeId, result,
parameters[0], parameters[1], parameters[2], parameters[3]);
}
else
{
// It's an extended instruction.
ASSERT(extendedInst != spv::GLSLstd450Bad);
spirv::WriteExtInst(mBuilder.getSpirvCurrentFunctionBlock(), resultTypeId, result,
mBuilder.getExtInstImportIdStd(),
spirv::LiteralExtInstInteger(extendedInst), parameters);
}
// If it's an assignment, store the calculated value.
if (IsAssignment(node->getOp()))
{
ASSERT(mNodeData.size() >= 2);
ASSERT(parameters.size() == 2);
accessChainStore(&mNodeData[mNodeData.size() - 2], result);
}
return result;
}
spirv::IdRef OutputSPIRVTraverser::createIncrementDecrement(TIntermOperator *node,
spirv::IdRef resultTypeId)
{
TIntermTyped *operand = node->getChildNode(0)->getAsTyped();
const TType &operandType = operand->getType();
const TBasicType basicType = operandType.getBasicType();
const bool isFloat = basicType == EbtFloat || basicType == EbtDouble;
// ++ and -- are implemented with binary SPIR-V ops.
WriteBinaryOp writeBinaryOp = nullptr;
switch (node->getOp())
{
case EOpPostIncrement:
case EOpPreIncrement:
if (isFloat)
writeBinaryOp = spirv::WriteFAdd;
else
writeBinaryOp = spirv::WriteIAdd;
break;
case EOpPostDecrement:
case EOpPreDecrement:
if (isFloat)
writeBinaryOp = spirv::WriteFSub;
else
writeBinaryOp = spirv::WriteISub;
break;
default:
UNREACHABLE();
}
// Load the operand.
spirv::IdRef value =
accessChainLoad(&mNodeData.back(), mBuilder.getDecorations(operand->getType()));
spirv::IdRef result = mBuilder.getNewId(mBuilder.getDecorations(operandType));
const spirv::IdRef one = isFloat ? mBuilder.getFloatConstant(1) : mBuilder.getIntConstant(1);
writeBinaryOp(mBuilder.getSpirvCurrentFunctionBlock(), resultTypeId, result, value, one);
// The result is always written back.
accessChainStore(&mNodeData.back(), result);
// Initialize the access chain with either the result or the value based on whether pre or
// post increment/decrement was used. The result is always an rvalue.
if (node->getOp() == EOpPostIncrement || node->getOp() == EOpPostDecrement)
{
result = value;
}
return result;
}
spirv::IdRef OutputSPIRVTraverser::createAtomicBuiltIn(TIntermOperator *node,
spirv::IdRef resultTypeId)
{
// Most atomic instructions are in the form of:
//
// %result = OpAtomicX %pointer Scope MemorySemantics %value
//
// OpAtomicCompareSwap is exceptionally different (note that compare and value are in different
// order than in GLSL):
//
// %result = OpAtomicCompareExchange %pointer
// Scope MemorySemantics MemorySemantics
// %value %comparator
//
// In all cases, the first parameter is the pointer, and the rest are rvalues.
const size_t parameterCount = node->getChildCount();
spirv::IdRef pointerId;
spirv::IdRefList parameters;
ASSERT(parameterCount >= 2);
pointerId = accessChainCollapse(&mNodeData[mNodeData.size() - parameterCount]);
for (size_t paramIndex = 1; paramIndex < parameterCount; ++paramIndex)
{
NodeData ¶m = mNodeData[mNodeData.size() - parameterCount + paramIndex];
parameters.push_back(accessChainLoad(
¶m,
mBuilder.getDecorations(node->getChildNode(paramIndex)->getAsTyped()->getType())));
}
// The scope of the operation is always Device as we don't enable the Vulkan memory model
// extension.
const spirv::IdScope scopeId = mBuilder.getUintConstant(spv::ScopeDevice);
// The memory semantics is always relaxed as we don't enable the Vulkan memory model extension.
const spirv::IdMemorySemantics semanticsId =
mBuilder.getUintConstant(spv::MemorySemanticsMaskNone);
WriteAtomicOp writeAtomicOp = nullptr;
const spirv::IdRef result = mBuilder.getNewId(mBuilder.getDecorations(node->getType()));
// TODO: determine isUnsigned correctly for image types. Should rearrange TBasicType enums to
// group images based on basic type and do range check. http://anglebug.com/4889.
const bool isUnsigned =
node->getChildNode(0)->getAsTyped()->getType().getBasicType() == EbtUInt;
switch (node->getOp())
{
case EOpAtomicAdd:
case EOpImageAtomicAdd:
writeAtomicOp = spirv::WriteAtomicIAdd;
break;
case EOpAtomicMin:
case EOpImageAtomicMin:
writeAtomicOp = isUnsigned ? spirv::WriteAtomicUMin : spirv::WriteAtomicSMin;
break;
case EOpAtomicMax:
case EOpImageAtomicMax:
writeAtomicOp = isUnsigned ? spirv::WriteAtomicUMax : spirv::WriteAtomicSMax;
break;
case EOpAtomicAnd:
case EOpImageAtomicAnd:
writeAtomicOp = spirv::WriteAtomicAnd;
break;
case EOpAtomicOr:
case EOpImageAtomicOr:
writeAtomicOp = spirv::WriteAtomicOr;
break;
case EOpAtomicXor:
case EOpImageAtomicXor:
writeAtomicOp = spirv::WriteAtomicXor;
break;
case EOpAtomicExchange:
case EOpImageAtomicExchange:
writeAtomicOp = spirv::WriteAtomicExchange;
break;
case EOpAtomicCompSwap:
case EOpImageAtomicCompSwap:
// Generate this special instruction right here and early out. Note again that the
// value and compare parameters of OpAtomicCompareExchange are in the opposite order
// from GLSL.
ASSERT(parameters.size() == 2);
spirv::WriteAtomicCompareExchange(mBuilder.getSpirvCurrentFunctionBlock(), resultTypeId,
result, pointerId, scopeId, semanticsId, semanticsId,
parameters[1], parameters[0]);
return result;
default:
UNREACHABLE();
}
// Write the instruction.
ASSERT(parameters.size() == 1);
writeAtomicOp(mBuilder.getSpirvCurrentFunctionBlock(), resultTypeId, result, pointerId, scopeId,
semanticsId, parameters[0]);
return result;
}
spirv::IdRef OutputSPIRVTraverser::createTextureBuiltIn(TIntermOperator *node,
spirv::IdRef resultTypeId)
{
// TODO: http://anglebug.com/4889
UNIMPLEMENTED();
return spirv::IdRef{};
}
spirv::IdRef OutputSPIRVTraverser::createImageBuiltIn(TIntermOperator *node,
spirv::IdRef resultTypeId)
{
// TODO: http://anglebug.com/4889
UNIMPLEMENTED();
return spirv::IdRef{};
}
void OutputSPIRVTraverser::visitSymbol(TIntermSymbol *node)
{
// Constants are expected to be folded.
ASSERT(!node->hasConstantValue());
// No-op visits to symbols that are being declared. They are handled in visitDeclaration.
if (mIsSymbolBeingDeclared)
{
// Make sure this does not affect other symbols, for example in the initializer expression.
mIsSymbolBeingDeclared = false;
return;
}
mNodeData.emplace_back();
// The symbol is either:
//
// - A specialization constant
// - A variable (local, varying etc)
// - An interface block
// - A field of an unnamed interface block
//
// Specialization constants in SPIR-V are treated largely like constants, in which case make
// this behave like visitConstantUnion().
const TType &type = node->getType();
const TInterfaceBlock *interfaceBlock = type.getInterfaceBlock();
const TSymbol *symbol = interfaceBlock;
if (interfaceBlock == nullptr)
{
symbol = &node->variable();
}
// Track the block storage; it's needed to determine the derived type in an access chain, but is
// not promoted in intermediate nodes' TType.
TLayoutBlockStorage blockStorage = EbsUnspecified;
if (interfaceBlock)
{
blockStorage = mBuilder.getBlockStorage(type);
}
const spirv::IdRef typeId = mBuilder.getTypeData(type, blockStorage).id;
// If the symbol is a const variable, such as a const function parameter or specialization
// constant, create an rvalue.
if (type.getQualifier() == EvqConst || type.getQualifier() == EvqSpecConst)
{
ASSERT(mSymbolIdMap.count(symbol) > 0);
nodeDataInitRValue(&mNodeData.back(), mSymbolIdMap[symbol], typeId);
return;
}
// Otherwise create an lvalue.
spv::StorageClass storageClass;
const spirv::IdRef symbolId = getSymbolIdAndStorageClass(symbol, type, &storageClass);
nodeDataInitLValue(&mNodeData.back(), symbolId, typeId, storageClass, blockStorage);
// If a field of a nameless interface block, create an access chain.
if (interfaceBlock && !type.isInterfaceBlock())
{
uint32_t fieldIndex = static_cast<uint32_t>(type.getInterfaceBlockFieldIndex());
accessChainPushLiteral(&mNodeData.back(), spirv::LiteralInteger(fieldIndex), typeId);
}
}
void OutputSPIRVTraverser::visitConstantUnion(TIntermConstantUnion *node)
{
mNodeData.emplace_back();
const TType &type = node->getType();
// Find out the expected type for this constant, so it can be cast right away and not need an
// instruction to do that.
TIntermNode *parent = getParentNode();
const size_t childIndex = getParentChildIndex(PreVisit);
TBasicType expectedBasicType = type.getBasicType();
if (parent->getAsAggregate())
{
TIntermAggregate *parentAggregate = parent->getAsAggregate();
// There are three possibilities:
//
// - It's a struct constructor: The basic type must match that of the corresponding field of
// the struct.
// - It's a non struct constructor: The basic type must match that of the the type being
// constructed.
// - It's a function call: The basic type must match that of the corresponding argument.
if (parentAggregate->isConstructor())
{
const TStructure *structure = parentAggregate->getType().getStruct();
if (structure != nullptr)
{
expectedBasicType = structure->fields()[childIndex]->type()->getBasicType();
}
else
{
expectedBasicType = parentAggregate->getType().getBasicType();
}
}
else
{
expectedBasicType =
parentAggregate->getFunction()->getParam(childIndex)->getType().getBasicType();
}
}
// TODO: other node types such as binary, ternary etc. http://anglebug.com/4889
const spirv::IdRef typeId = mBuilder.getTypeData(type, EbsUnspecified).id;
const spirv::IdRef constId = createConstant(type, expectedBasicType, node->getConstantValue());
nodeDataInitRValue(&mNodeData.back(), constId, typeId);
}
bool OutputSPIRVTraverser::visitSwizzle(Visit visit, TIntermSwizzle *node)
{
// Constants are expected to be folded.
ASSERT(!node->hasConstantValue());
if (visit == PreVisit)
{
// Don't add an entry to the stack. The child will create one, which we won't pop.
return true;
}
ASSERT(visit == PostVisit);
ASSERT(mNodeData.size() >= 1);
const TType &vectorType = node->getOperand()->getType();
const uint8_t vectorComponentCount = static_cast<uint8_t>(vectorType.getNominalSize());
const TVector<int> &swizzle = node->getSwizzleOffsets();
// As an optimization, do nothing if the swizzle is selecting all the components of the vector
// in order.
bool isIdentity = swizzle.size() == vectorComponentCount;
for (size_t index = 0; index < swizzle.size(); ++index)
{
isIdentity = isIdentity && static_cast<size_t>(swizzle[index]) == index;
}
if (isIdentity)
{
return true;
}
const spirv::IdRef typeId =
mBuilder.getTypeData(node->getType(), mNodeData.back().accessChain.baseBlockStorage).id;
accessChainPushSwizzle(&mNodeData.back(), swizzle, typeId, vectorComponentCount);
return true;
}
bool OutputSPIRVTraverser::visitBinary(Visit visit, TIntermBinary *node)
{
// Constants are expected to be folded.
ASSERT(!node->hasConstantValue());
if (visit == PreVisit)
{
// Don't add an entry to the stack. The left child will create one, which we won't pop.
return true;
}
// If this is a variable initialization node, defer any code generation to visitDeclaration.
if (node->getOp() == EOpInitialize)
{
ASSERT(getParentNode()->getAsDeclarationNode() != nullptr);
return true;
}
if (IsShortCircuitNeeded(node))
{
// For && and ||, if short-circuiting behavior is needed, we need to emulate it with an
// |if| construct. At this point, the left-hand side is already evaluated, so we need to
// create an appropriate conditional on in-visit and visit the right-hand-side inside the
// conditional block. On post-visit, OpPhi is used to calculate the result.
if (visit == InVisit)
{
startShortCircuit(node);
return true;
}
spirv::IdRef typeId;
const spirv::IdRef result = endShortCircuit(node, &typeId);
// Replace the access chain with an rvalue that's the result.
nodeDataInitRValue(&mNodeData.back(), result, typeId);
return true;
}
if (visit == InVisit)
{
// Left child visited. Take the entry it created as the current node's.
ASSERT(mNodeData.size() >= 1);
// As an optimization, if the index is EOpIndexDirect*, take the constant index directly and
// add it to the access chain as literal.
switch (node->getOp())
{
case EOpIndexDirect:
case EOpIndexDirectStruct:
case EOpIndexDirectInterfaceBlock:
accessChainPushLiteral(
&mNodeData.back(),
spirv::LiteralInteger(node->getRight()->getAsConstantUnion()->getIConst(0)),
mBuilder
.getTypeData(node->getType(), mNodeData.back().accessChain.baseBlockStorage)
.id);
// Don't visit the right child, it's already processed.
return false;
default:
break;
}
return true;
}
// There are at least two entries, one for the left node and one for the right one.
ASSERT(mNodeData.size() >= 2);
TLayoutBlockStorage blockStorage = EbsUnspecified;
if (node->getOp() == EOpIndexIndirect || node->getOp() == EOpAssign)
{
blockStorage = mNodeData[mNodeData.size() - 2].accessChain.baseBlockStorage;
}
const spirv::IdRef resultTypeId = mBuilder.getTypeData(node->getType(), blockStorage).id;
// For EOpIndex* operations, push the right value as an index to the left value's access chain.
// For the other operations, evaluate the expression.
switch (node->getOp())
{
case EOpIndexDirect:
case EOpIndexDirectStruct:
case EOpIndexDirectInterfaceBlock:
UNREACHABLE();
break;
case EOpIndexIndirect:
{
// Load the index.
const spirv::IdRef rightValue = accessChainLoad(
&mNodeData.back(), mBuilder.getDecorations(node->getRight()->getType()));
mNodeData.pop_back();
if (!node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
{
accessChainPushDynamicComponent(&mNodeData.back(), rightValue, resultTypeId);
}
else
{
accessChainPush(&mNodeData.back(), rightValue, resultTypeId);
}
break;
}
case EOpAssign:
{
// Load the right hand side of assignment.
const spirv::IdRef rightValue = accessChainLoad(
&mNodeData.back(), mBuilder.getDecorations(node->getRight()->getType()));
mNodeData.pop_back();
// Store into the access chain. Since the result of the (a = b) expression is b, change
// the access chain to an unindexed rvalue which is |rightValue|.
// TODO: handle mismatching types. http://anglebug.com/4889.
accessChainStore(&mNodeData.back(), rightValue);
nodeDataInitRValue(&mNodeData.back(), rightValue, resultTypeId);
break;
}
case EOpComma:
// When the expression a,b is visited, all side effects of a and b are already
// processed. What's left is to to replace the expression with the result of b. This
// is simply done by dropping the left node and placing the right node as the result.
mNodeData.erase(mNodeData.begin() + mNodeData.size() - 2);
break;
default:
const spirv::IdRef result = visitOperator(node, resultTypeId);
mNodeData.pop_back();
nodeDataInitRValue(&mNodeData.back(), result, resultTypeId);
// TODO: Handle NoContraction decoration. http://anglebug.com/4889
break;
}
return true;
}
bool OutputSPIRVTraverser::visitUnary(Visit visit, TIntermUnary *node)
{
// Constants are expected to be folded.
ASSERT(!node->hasConstantValue());
if (visit == PreVisit)
{
// Don't add an entry to the stack. The child will create one, which we won't pop.
return true;
}
// It's a unary operation, so there can't be an InVisit.
ASSERT(visit != InVisit);
// There is at least on entry for the child.
ASSERT(mNodeData.size() >= 1);
// Special case EOpArrayLength. .length() on sized arrays is already constant folded, so this
// operation only applies to ssbo.last_member.length(). OpArrayLength takes the ssbo block
// *type* and the field index of last_member, so those need to be extracted from the access
// chain. Additionally, OpArrayLength produces an unsigned int while GLSL produces an int, so a
// final cast is necessary.
if (node->getOp() == EOpArrayLength)
{
// The access chain must only include the base ssbo + one literal field index.
ASSERT(mNodeData.back().idList.size() == 1 && !mNodeData.back().idList.back().id.valid());
const spirv::LiteralInteger fieldIndex = mNodeData.back().idList.back().literal;
// Get the interface block type from the operand, which is either a symbol or a binary
// operator based on whether the interface block is nameless or not.
TIntermTyped *operand = node->getOperand();
TIntermTyped *ssbo =
operand->getAsBinaryNode() ? operand->getAsBinaryNode()->getLeft() : operand;
const spirv::IdRef typeId = mBuilder.getTypeData(ssbo->getType(), EbsUnspecified).id;
// Get the int and uint type ids.
SpirvType intType;
intType.type = EbtInt;
const spirv::IdRef intTypeId = mBuilder.getSpirvTypeData(intType, nullptr).id;
intType.type = EbtUInt;
const spirv::IdRef uintTypeId = mBuilder.getSpirvTypeData(intType, nullptr).id;
// Generate the instruction.
const spirv::IdRef resultId = mBuilder.getNewId({});
spirv::WriteArrayLength(mBuilder.getSpirvCurrentFunctionBlock(), uintTypeId, resultId,
typeId, fieldIndex);
// Cast to int.
const spirv::IdRef castResultId = mBuilder.getNewId({});
spirv::WriteBitcast(mBuilder.getSpirvCurrentFunctionBlock(), intTypeId, castResultId,
resultId);
// Replace the access chain with an rvalue that's the result.
nodeDataInitRValue(&mNodeData.back(), castResultId, intTypeId);
return true;
}
const spirv::IdRef resultTypeId = mBuilder.getTypeData(node->getType(), EbsUnspecified).id;
const spirv::IdRef result = visitOperator(node, resultTypeId);
// Keep the result as rvalue.
nodeDataInitRValue(&mNodeData.back(), result, resultTypeId);
return true;
}
bool OutputSPIRVTraverser::visitTernary(Visit visit, TIntermTernary *node)
{
if (visit == PreVisit)
{
// Don't add an entry to the stack. The condition will create one, which we won't pop.
return true;
}
size_t lastChildIndex = getLastTraversedChildIndex(visit);
// If the condition was just visited, evaluate it and decide if OpSelect could be used or an
// if-else must be emitted. OpSelect is only used if the type is scalar or vector (required by
// OpSelect) and if neither side has a side effect.
const TType &type = node->getType();
const bool canUseOpSelect = (type.isScalar() || type.isVector()) &&
!node->getTrueExpression()->hasSideEffects() &&
!node->getFalseExpression()->hasSideEffects();
if (lastChildIndex == 0)
{
spirv::IdRef typeId = getAccessChainTypeId(&mNodeData.back());
spirv::IdRef conditionValue = accessChainLoad(
&mNodeData.back(), mBuilder.getDecorations(node->getCondition()->getType()));
// If OpSelect can be used, keep the condition for later usage.
if (canUseOpSelect)
{
// SPIR-V 1.0 requires that the condition value have as many components as the result.
// So when selecting between vectors, we must replicate the condition scalar.
if (type.isVector())
{
SpirvType spirvType;
spirvType.type = node->getCondition()->getType().getBasicType();
spirvType.primarySize = static_cast<uint8_t>(type.getNominalSize());
typeId = mBuilder.getSpirvTypeData(spirvType, nullptr).id;
conditionValue =
createConstructorVectorFromScalar(type, typeId, {{conditionValue}});
}
nodeDataInitRValue(&mNodeData.back(), conditionValue, typeId);
return true;
}
// Otherwise generate an if-else construct.
// Three blocks necessary; the true, false and merge.
mBuilder.startConditional(3, false, false);
// Generate the branch instructions.
const SpirvConditional *conditional = mBuilder.getCurrentConditional();
const spirv::IdRef trueBlockId = conditional->blockIds[0];
const spirv::IdRef falseBlockId = conditional->blockIds[1];
const spirv::IdRef mergeBlockId = conditional->blockIds.back();
mBuilder.writeBranchConditional(conditionValue, trueBlockId, falseBlockId, mergeBlockId);
return true;
}
// Load the result of the true or false part, and keep it for the end. It's either used in
// OpSelect or OpPhi.
// TODO: handle mismatching types. http://anglebug.com/4889.
const spirv::IdRef typeId = getAccessChainTypeId(&mNodeData.back());
const spirv::IdRef value = accessChainLoad(&mNodeData.back(), mBuilder.getDecorations(type));
mNodeData.pop_back();
mNodeData.back().idList.push_back(value);
if (!canUseOpSelect)
{
// Move on to the next block.
mBuilder.writeBranchConditionalBlockEnd();
}
// When done, generate either OpSelect or OpPhi.
if (visit == PostVisit)
{
const spirv::IdRef result = mBuilder.getNewId(mBuilder.getDecorations(node->getType()));
ASSERT(mNodeData.back().idList.size() == 2);
const spirv::IdRef trueValue = mNodeData.back().idList[0].id;
const spirv::IdRef falseValue = mNodeData.back().idList[1].id;
if (canUseOpSelect)
{
const spirv::IdRef conditionValue = mNodeData.back().baseId;
spirv::WriteSelect(mBuilder.getSpirvCurrentFunctionBlock(), typeId, result,
conditionValue, trueValue, falseValue);
}
else
{
const SpirvConditional *conditional = mBuilder.getCurrentConditional();
const spirv::IdRef trueBlockId = conditional->blockIds[0];
const spirv::IdRef falseBlockId = conditional->blockIds[1];
spirv::WritePhi(mBuilder.getSpirvCurrentFunctionBlock(), typeId, result,
{spirv::PairIdRefIdRef{trueValue, trueBlockId},
spirv::PairIdRefIdRef{falseValue, falseBlockId}});
mBuilder.endConditional();
}
// Replace the access chain with an rvalue that's the result.
nodeDataInitRValue(&mNodeData.back(), result, typeId);
}
return true;
}
bool OutputSPIRVTraverser::visitIfElse(Visit visit, TIntermIfElse *node)
{
if (visit == PreVisit)
{
// Don't add an entry to the stack. The condition will create one, which we won't pop.
return true;
}
const size_t lastChildIndex = getLastTraversedChildIndex(visit);
// If the condition was just visited, evaluate it and create the branch instructions.
if (lastChildIndex == 0)
{
const spirv::IdRef conditionValue = accessChainLoad(
&mNodeData.back(), mBuilder.getDecorations(node->getCondition()->getType()));
// Create a conditional with maximum 3 blocks, one for the true block (if any), one for the
// else block (if any), and one for the merge block. getChildCount() works here as it
// produces an identical count.
mBuilder.startConditional(node->getChildCount(), false, false);
// Generate the branch instructions.
const SpirvConditional *conditional = mBuilder.getCurrentConditional();
const spirv::IdRef mergeBlock = conditional->blockIds.back();
spirv::IdRef trueBlock = mergeBlock;
spirv::IdRef falseBlock = mergeBlock;
size_t nextBlockIndex = 0;
if (node->getTrueBlock())
{
trueBlock = conditional->blockIds[nextBlockIndex++];
}
if (node->getFalseBlock())
{
falseBlock = conditional->blockIds[nextBlockIndex++];
}
mBuilder.writeBranchConditional(conditionValue, trueBlock, falseBlock, mergeBlock);
return true;
}
// Otherwise move on to the next block, inserting a branch to the merge block at the end of each
// block.
mBuilder.writeBranchConditionalBlockEnd();
// Pop from the conditional stack when done.
if (visit == PostVisit)
{
mBuilder.endConditional();
}
return true;
}
bool OutputSPIRVTraverser::visitSwitch(Visit visit, TIntermSwitch *node)
{
// Take the following switch:
//
// switch (c)
// {
// case A:
// ABlock;
// break;
// case B:
// default:
// BBlock;
// break;
// case C:
// CBlock;
// // fallthrough
// case D:
// DBlock;
// }
//
// In SPIR-V, this is implemented similarly to the following pseudo-code:
//
// switch c:
// A -> jump %A
// B -> jump %B
// C -> jump %C
// D -> jump %D
// default -> jump %B
//
// %A:
// ABlock
// jump %merge
//
// %B:
// BBlock
// jump %merge
//
// %C:
// CBlock
// jump %D
//
// %D:
// DBlock
// jump %merge
//
// The OpSwitch instruction contains the jump labels for the default and other cases. Each
// block either terminates with a jump to the merge block or the next block as fallthrough.
//
// // pre-switch block
// OpSelectionMerge %merge None
// OpSwitch %cond %C A %A B %B C %C D %D
//
// %A = OpLabel
// ABlock
// OpBranch %merge
//
// %B = OpLabel
// BBlock
// OpBranch %merge
//
// %C = OpLabel
// CBlock
// OpBranch %D
//
// %D = OpLabel
// DBlock
// OpBranch %merge
if (visit == PreVisit)
{
// Don't add an entry to the stack. The condition will create one, which we won't pop.
return true;
}
// If the condition was just visited, evaluate it and create the switch instruction.
if (visit == InVisit)
{
ASSERT(getLastTraversedChildIndex(visit) == 0);
const spirv::IdRef conditionValue =
accessChainLoad(&mNodeData.back(), mBuilder.getDecorations(node->getInit()->getType()));
// First, need to find out how many blocks are there in the switch.
const TIntermSequence &statements = *node->getStatementList()->getSequence();
bool lastWasCase = true;
size_t blockIndex = 0;
size_t defaultBlockIndex = std::numeric_limits<size_t>::max();
TVector<uint32_t> caseValues;
TVector<size_t> caseBlockIndices;
for (TIntermNode *statement : statements)
{
TIntermCase *caseLabel = statement->getAsCaseNode();
const bool isCaseLabel = caseLabel != nullptr;
if (isCaseLabel)
{
// For every case label, remember its block index. This is used later to generate
// the OpSwitch instruction.
if (caseLabel->hasCondition())
{
// All switch conditions are literals.
TIntermConstantUnion *condition =
caseLabel->getCondition()->getAsConstantUnion();
ASSERT(condition != nullptr);
TConstantUnion caseValue;
caseValue.cast(EbtUInt, *condition->getConstantValue());
caseValues.push_back(caseValue.getUConst());
caseBlockIndices.push_back(blockIndex);
}
else
{
// Remember the block index of the default case.
defaultBlockIndex = blockIndex;
}
lastWasCase = true;
}
else if (lastWasCase)
{
// Every time a non-case node is visited and the previous statement was a case node,
// it's a new block.
++blockIndex;
lastWasCase = false;
}
}
// Block count is the number of blocks based on cases + 1 for the merge block.
const size_t blockCount = blockIndex + 1;
mBuilder.startConditional(blockCount, false, true);
// Generate the switch instructions.
const SpirvConditional *conditional = mBuilder.getCurrentConditional();
// Generate the list of caseValue->blockIndex mapping used by the OpSwitch instruction. If
// the switch ends in a number of cases with no statements following them, they will
// naturally jump to the merge block!
spirv::PairLiteralIntegerIdRefList switchTargets;
for (size_t caseIndex = 0; caseIndex < caseValues.size(); ++caseIndex)
{
uint32_t value = caseValues[caseIndex];
size_t caseBlockIndex = caseBlockIndices[caseIndex];
switchTargets.push_back(
{spirv::LiteralInteger(value), conditional->blockIds[caseBlockIndex]});
}
const spirv::IdRef mergeBlock = conditional->blockIds.back();
const spirv::IdRef defaultBlock = defaultBlockIndex < caseValues.size()
? conditional->blockIds[defaultBlockIndex]
: mergeBlock;
mBuilder.writeSwitch(conditionValue, defaultBlock, switchTargets, mergeBlock);
return true;
}
// Terminate the last block if not already and end the conditional.
mBuilder.writeSwitchCaseBlockEnd();
mBuilder.endConditional();
return true;
}
bool OutputSPIRVTraverser::visitCase(Visit visit, TIntermCase *node)
{
ASSERT(visit == PreVisit);
mNodeData.emplace_back();
TIntermBlock *parent = getParentNode()->getAsBlock();
const size_t childIndex = getParentChildIndex(PreVisit);
ASSERT(parent);
const TIntermSequence &parentStatements = *parent->getSequence();
// Check the previous statement. If it was not a |case|, then a new block is being started so
// handle fallthrough:
//
// ...
// statement;
// case X: <--- end the previous block here
// case Y:
//
//
if (childIndex > 0 && parentStatements[childIndex - 1]->getAsCaseNode() == nullptr)
{
mBuilder.writeSwitchCaseBlockEnd();
}
// Don't traverse the condition, as it was processed in visitSwitch.
return false;
}
bool OutputSPIRVTraverser::visitBlock(Visit visit, TIntermBlock *node)
{
// If global block, nothing to do.
if (getCurrentTraversalDepth() == 0)
{
return true;
}
// Any construct that needs code blocks must have already handled creating the necessary blocks
// and setting the right one "current". If there's a block opened in GLSL for scoping reasons,
// it's ignored here as there are no scopes within a function in SPIR-V.
if (visit == PreVisit)
{
return node->getChildCount() > 0;
}
// Any node that needed to generate code has already done so, just clean up its data. If
// the child node has no effect, it's automatically discarded (such as variable.field[n].x,
// side effects of n already having generated code).
//
// Blocks inside blocks like:
//
// {
// statement;
// {
// statement2;
// }
// }
//
// don't generate nodes.
const size_t childIndex = getLastTraversedChildIndex(visit);
const TIntermSequence &statements = *node->getSequence();
if (statements[childIndex]->getAsBlock() == nullptr)
{
mNodeData.pop_back();
}
return true;
}
bool OutputSPIRVTraverser::visitFunctionDefinition(Visit visit, TIntermFunctionDefinition *node)
{
if (visit == PreVisit)
{
return true;
}
// After the prototype is visited, generate the initial code for the function.
if (visit == InVisit)
{
const TFunction *function = node->getFunction();
ASSERT(mFunctionIdMap.count(function) > 0);
const FunctionIds &ids = mFunctionIdMap[function];
// Declare the function.
spirv::WriteFunction(mBuilder.getSpirvFunctions(), ids.returnTypeId, ids.functionId,
spv::FunctionControlMaskNone, ids.functionTypeId);
for (size_t paramIndex = 0; paramIndex < function->getParamCount(); ++paramIndex)
{
const TVariable *paramVariable = function->getParam(paramIndex);
const spirv::IdRef paramId =
mBuilder.getNewId(mBuilder.getDecorations(paramVariable->getType()));
spirv::WriteFunctionParameter(mBuilder.getSpirvFunctions(),
ids.parameterTypeIds[paramIndex], paramId);
// Remember the id of the variable for future look up.
ASSERT(mSymbolIdMap.count(paramVariable) == 0);
mSymbolIdMap[paramVariable] = paramId;
spirv::WriteName(mBuilder.getSpirvDebug(), paramId,
mBuilder.hashName(paramVariable).data());
}
mBuilder.startNewFunction(ids.functionId, function);
return true;
}
// If no explicit return was specified, add one automatically here.
if (!mBuilder.isCurrentFunctionBlockTerminated())
{
// Only meaningful if the function returns void. Otherwise it must have had a return
// value.
ASSERT(node->getFunction()->getReturnType().getBasicType() == EbtVoid);
spirv::WriteReturn(mBuilder.getSpirvCurrentFunctionBlock());
mBuilder.terminateCurrentFunctionBlock();
}
mBuilder.assembleSpirvFunctionBlocks();
// End the function
spirv::WriteFunctionEnd(mBuilder.getSpirvFunctions());
return true;
}
bool OutputSPIRVTraverser::visitGlobalQualifierDeclaration(Visit visit,
TIntermGlobalQualifierDeclaration *node)
{
if (node->isPrecise())
{
// TODO: handle precise. http://anglebug.com/4889.
UNIMPLEMENTED();
return false;
}
// Global qualifier declarations apply to variables that are already declared. Invariant simply
// adds a decoration to the variable declaration, which can be done right away. Note that
// invariant cannot be applied to block members like this, except for gl_PerVertex built-ins,
// which are applied to the members directly by DeclarePerVertexBlocks.
ASSERT(node->isInvariant());
const TVariable *variable = &node->getSymbol()->variable();
ASSERT(mSymbolIdMap.count(variable) > 0);
const spirv::IdRef variableId = mSymbolIdMap[variable];
spirv::WriteDecorate(mBuilder.getSpirvDecorations(), variableId, spv::DecorationInvariant, {});
return false;
}
void OutputSPIRVTraverser::visitFunctionPrototype(TIntermFunctionPrototype *node)
{
const TFunction *function = node->getFunction();
// If the function was previously forward declared, skip this.
if (mFunctionIdMap.count(function) > 0)
{
return;
}
FunctionIds ids;
// Declare the function type
ids.returnTypeId = mBuilder.getTypeData(function->getReturnType(), EbsUnspecified).id;
spirv::IdRefList paramTypeIds;
for (size_t paramIndex = 0; paramIndex < function->getParamCount(); ++paramIndex)
{
const TType ¶mType = function->getParam(paramIndex)->getType();
spirv::IdRef paramId = mBuilder.getTypeData(paramType, EbsUnspecified).id;
// const function parameters are intermediate values, while the rest are "variables"
// with the Function storage class.
if (paramType.getQualifier() != EvqConst)
{
paramId = mBuilder.getTypePointerId(paramId, spv::StorageClassFunction);
}
ids.parameterTypeIds.push_back(paramId);
}
ids.functionTypeId = mBuilder.getFunctionTypeId(ids.returnTypeId, ids.parameterTypeIds);
// Allocate an id for the function up-front.
//
// Apply decorations to the return value of the function by applying them to the OpFunction
// instruction.
ids.functionId = mBuilder.getNewId(mBuilder.getDecorations(function->getReturnType()));
// Remember the ID of main() for the sake of OpEntryPoint.
if (function->isMain())
{
mBuilder.setEntryPointId(ids.functionId);
}
// Remember the id of the function for future look up.
mFunctionIdMap[function] = ids;
}
bool OutputSPIRVTraverser::visitAggregate(Visit visit, TIntermAggregate *node)
{
// Constants are expected to be folded. However, large constructors (such as arrays) are not
// folded and are handled here.
ASSERT(node->getOp() == EOpConstruct || !node->hasConstantValue());
if (visit == PreVisit)
{
mNodeData.emplace_back();
return true;
}
// Keep the parameters on the stack. If a function call contains out or inout parameters, we
// need to know the access chains for the eventual write back to them.
if (visit == InVisit)
{
return true;
}
// Expect to have accumulated as many parameters as the node requires.
ASSERT(mNodeData.size() > node->getChildCount());
const spirv::IdRef resultTypeId = mBuilder.getTypeData(node->getType(), EbsUnspecified).id;
spirv::IdRef result;
switch (node->getOp())
{
case EOpConstruct:
// Construct a value out of the accumulated parameters.
result = createConstructor(node, resultTypeId);
break;
case EOpCallFunctionInAST:
// Create a call to the function.
result = createFunctionCall(node, resultTypeId);
break;
case EOpMemoryBarrier:
case EOpMemoryBarrierAtomicCounter:
case EOpMemoryBarrierBuffer:
case EOpMemoryBarrierImage:
case EOpBarrier:
case EOpMemoryBarrierShared:
case EOpGroupMemoryBarrier:
case EOpBarrierTCS:
// TODO: support barriers. http://anglebug.com/4889
UNIMPLEMENTED();
break;
case EOpEmitVertex:
case EOpEndPrimitive:
case EOpEmitStreamVertex:
case EOpEndStreamPrimitive:
// TODO: support geometry shaders. http://anglebug.com/4889
UNIMPLEMENTED();
break;
default:
result = visitOperator(node, resultTypeId);
break;
}
// Pop the parameters.
mNodeData.resize(mNodeData.size() - node->getChildCount());
// Keep the result as rvalue.
nodeDataInitRValue(&mNodeData.back(), result, resultTypeId);
return false;
}
bool OutputSPIRVTraverser::visitDeclaration(Visit visit, TIntermDeclaration *node)
{
const TIntermSequence &sequence = *node->getSequence();
// Enforced by ValidateASTOptions::validateMultiDeclarations.
ASSERT(sequence.size() == 1);
// Declare specialization constants especially; they don't require processing the left and right
// nodes, and they are like constant declarations with special instructions and decorations.
if (sequence.front()->getAsTyped()->getType().getQualifier() == EvqSpecConst)
{
declareSpecConst(node);
return false;
}
if (!mInGlobalScope && visit == PreVisit)
{
mNodeData.emplace_back();
}
mIsSymbolBeingDeclared = visit == PreVisit;
if (visit != PostVisit)
{
return true;
}
TIntermSymbol *symbol = sequence.front()->getAsSymbolNode();
spirv::IdRef initializerId;
bool initializeWithDeclaration = false;
// Handle declarations with initializer.
if (symbol == nullptr)
{
TIntermBinary *assign = sequence.front()->getAsBinaryNode();
ASSERT(assign != nullptr && assign->getOp() == EOpInitialize);
symbol = assign->getLeft()->getAsSymbolNode();
ASSERT(symbol != nullptr);
// In SPIR-V, it's only possible to initialize a variable together with its declaration if
// the initializer is a constant or a global variable. We ignore the global variable case
// to avoid tracking whether the variable has been modified since the beginning of the
// function. Since variable declarations are always placed at the beginning of the function
// in SPIR-V, it would be wrong for example to initialize |var| below with the global
// variable at declaration time:
//
// vec4 global = A;
// void f()
// {
// global = B;
// {
// vec4 var = global;
// }
// }
//
// So the initializer is only used when declarating a variable when it's a constant
// expression. Note that if the variable being declared is itself global (and the
// initializer is not constant), a previous AST transformation (DeferGlobalInitializers)
// makes sure their initialization is deferred to the beginning of main.
//
// Additionally, if the variable is being defined inside a loop, the initializer is not used
// as that would prevent it from being reintialized in the next iteration of the loop.
TIntermTyped *initializer = assign->getRight();
initializeWithDeclaration =
!mBuilder.isInLoop() &&
(initializer->getAsConstantUnion() != nullptr || initializer->hasConstantValue());
if (initializeWithDeclaration)
{
// If a constant, take the Id directly.
initializerId = mNodeData.back().baseId;
}
else
{
// Otherwise generate code to load from right hand side expression.
initializerId =
accessChainLoad(&mNodeData.back(), mBuilder.getDecorations(initializer->getType()));
}
// TODO: handle mismatching types. http://anglebug.com/4889.
// Clean up the initializer data.
mNodeData.pop_back();
}
const TType &type = symbol->getType();
const TVariable *variable = &symbol->variable();
// If this is just a struct declaration (and not a variable declaration), don't declare the
// struct up-front and let it be lazily defined. If the struct is only used inside an interface
// block for example, this avoids it being doubly defined (once with the unspecified block
// storage and once with interface block's).
if (type.isStructSpecifier() && variable->symbolType() == SymbolType::Empty)
{
return false;
}
const spirv::IdRef typeId = mBuilder.getTypeData(type, EbsUnspecified).id;
spv::StorageClass storageClass = GetStorageClass(type);
SpirvDecorations decorations = mBuilder.getDecorations(type);
if (mBuilder.isInvariantOutput(type))
{
// Apply the Invariant decoration to output variables if specified or if globally enabled.
decorations.push_back(spv::DecorationInvariant);
}
const spirv::IdRef variableId = mBuilder.declareVariable(
typeId, storageClass, decorations, initializeWithDeclaration ? &initializerId : nullptr,
mBuilder.hashName(variable).data());
if (!initializeWithDeclaration && initializerId.valid())
{
// If not initializing at the same time as the declaration, issue a store instruction.
spirv::WriteStore(mBuilder.getSpirvCurrentFunctionBlock(), variableId, initializerId,
nullptr);
}
const bool isShaderInOut = IsShaderIn(type.getQualifier()) || IsShaderOut(type.getQualifier());
const bool isInterfaceBlock = type.getBasicType() == EbtInterfaceBlock;
// Add decorations, which apply to the element type of arrays, if array.
spirv::IdRef nonArrayTypeId = typeId;
if (type.isArray() && (isShaderInOut || isInterfaceBlock))
{
SpirvType elementType = mBuilder.getSpirvType(type, EbsUnspecified);
elementType.arraySizes = {};
nonArrayTypeId = mBuilder.getSpirvTypeData(elementType, nullptr).id;
}
if (isShaderInOut)
{
// Add in and out variables to the list of interface variables.
mBuilder.addEntryPointInterfaceVariableId(variableId);
if (IsShaderIoBlock(type.getQualifier()) && type.isInterfaceBlock())
{
// For gl_PerVertex in particular, write the necessary BuiltIn decorations
if (type.getQualifier() == EvqPerVertexIn || type.getQualifier() == EvqPerVertexOut)
{
mBuilder.writePerVertexBuiltIns(type, nonArrayTypeId);
}
// I/O blocks are decorated with Block
spirv::WriteDecorate(mBuilder.getSpirvDecorations(), nonArrayTypeId,
spv::DecorationBlock, {});
}
}
else if (isInterfaceBlock)
{
// For uniform and buffer variables, add Block and BufferBlock decorations respectively.
const spv::Decoration decoration =
type.getQualifier() == EvqUniform ? spv::DecorationBlock : spv::DecorationBufferBlock;
spirv::WriteDecorate(mBuilder.getSpirvDecorations(), nonArrayTypeId, decoration, {});
}
// Write DescriptorSet, Binding, Location etc decorations if necessary.
mBuilder.writeInterfaceVariableDecorations(type, variableId);
// Remember the id of the variable for future look up. For interface blocks, also remember the
// id of the interface block.
ASSERT(mSymbolIdMap.count(variable) == 0);
mSymbolIdMap[variable] = variableId;
if (type.isInterfaceBlock())
{
ASSERT(mSymbolIdMap.count(type.getInterfaceBlock()) == 0);
mSymbolIdMap[type.getInterfaceBlock()] = variableId;
}
return false;
}
void GetLoopBlocks(const SpirvConditional *conditional,
TLoopType loopType,
bool hasCondition,
spirv::IdRef *headerBlock,
spirv::IdRef *condBlock,
spirv::IdRef *bodyBlock,
spirv::IdRef *continueBlock,
spirv::IdRef *mergeBlock)
{
// The order of the blocks is for |for| and |while|:
//
// %header %cond [optional] %body %continue %merge
//
// and for |do-while|:
//
// %header %body %cond %merge
//
// Note that the |break| target is always the last block and the |continue| target is the one
// before last.
//
// If %continue is not present, all jumps are made to %cond (which is necessarily present).
// If %cond is not present, all jumps are made to %body instead.
size_t nextBlock = 0;
*headerBlock = conditional->blockIds[nextBlock++];
// %cond, if any is after header except for |do-while|.
if (loopType != ELoopDoWhile && hasCondition)
{
*condBlock = conditional->blockIds[nextBlock++];
}
*bodyBlock = conditional->blockIds[nextBlock++];
// After the block is either %cond or %continue based on |do-while| or not.
if (loopType != ELoopDoWhile)
{
*continueBlock = conditional->blockIds[nextBlock++];
}
else
{
*condBlock = conditional->blockIds[nextBlock++];
}
*mergeBlock = conditional->blockIds[nextBlock++];
ASSERT(nextBlock == conditional->blockIds.size());
if (!continueBlock->valid())
{
ASSERT(condBlock->valid());
*continueBlock = *condBlock;
}
if (!condBlock->valid())
{
*condBlock = *bodyBlock;
}
}
bool OutputSPIRVTraverser::visitLoop(Visit visit, TIntermLoop *node)
{
// There are three kinds of loops, and they translate as such:
//
// for (init; cond; expr) body;
//
// // pre-loop block
// init
// OpBranch %header
//
// %header = OpLabel
// OpLoopMerge %merge %continue None
// OpBranch %cond
//
// // Note: if cond doesn't exist, this section is not generated. The above
// // OpBranch would jump directly to %body.
// %cond = OpLabel
// %v = cond
// OpBranchConditional %v %body %merge None
//
// %body = OpLabel
// body
// OpBranch %continue
//
// %continue = OpLabel
// expr
// OpBranch %header
//
// // post-loop block
// %merge = OpLabel
//
//
// while (cond) body;
//
// // pre-for block
// OpBranch %header
//
// %header = OpLabel
// OpLoopMerge %merge %continue None
// OpBranch %cond
//
// %cond = OpLabel
// %v = cond
// OpBranchConditional %v %body %merge None
//
// %body = OpLabel
// body
// OpBranch %continue
//
// %continue = OpLabel
// OpBranch %header
//
// // post-loop block
// %merge = OpLabel
//
//
// do body; while (cond);
//
// // pre-for block
// OpBranch %header
//
// %header = OpLabel
// OpLoopMerge %merge %cond None
// OpBranch %body
//
// %body = OpLabel
// body
// OpBranch %cond
//
// %cond = OpLabel
// %v = cond
// OpBranchConditional %v %header %merge None
//
// // post-loop block
// %merge = OpLabel
//
// The order of the blocks is not necessarily the same as traversed, so it's much simpler if
// this function enforces traversal in the right order.
ASSERT(visit == PreVisit);
mNodeData.emplace_back();
const TLoopType loopType = node->getType();
// The init statement of a for loop is placed in the previous block, so continue generating code
// as-is until that statement is done.
if (node->getInit())
{
ASSERT(loopType == ELoopFor);
node->getInit()->traverse(this);
mNodeData.pop_back();
}
const bool hasCondition = node->getCondition() != nullptr;
// Once the init node is visited, if any, we need to set up the loop.
//
// For |for| and |while|, we need %header, %body, %continue and %merge. For |do-while|, we
// need %header, %body and %merge. If condition is present, an additional %cond block is
// needed in each case.
const size_t blockCount = (loopType == ELoopDoWhile ? 3 : 4) + (hasCondition ? 1 : 0);
mBuilder.startConditional(blockCount, true, true);
// Generate the %header block.
const SpirvConditional *conditional = mBuilder.getCurrentConditional();
spirv::IdRef headerBlock, condBlock, bodyBlock, continueBlock, mergeBlock;
GetLoopBlocks(conditional, loopType, hasCondition, &headerBlock, &condBlock, &bodyBlock,
&continueBlock, &mergeBlock);
mBuilder.writeLoopHeader(loopType == ELoopDoWhile ? bodyBlock : condBlock, continueBlock,
mergeBlock);
// %cond, if any is after header except for |do-while|.
if (loopType != ELoopDoWhile && hasCondition)
{
node->getCondition()->traverse(this);
// Generate the branch at the end of the %cond block.
const spirv::IdRef conditionValue = accessChainLoad(
&mNodeData.back(), mBuilder.getDecorations(node->getCondition()->getType()));
mBuilder.writeLoopConditionEnd(conditionValue, bodyBlock, mergeBlock);
mNodeData.pop_back();
}
// Next comes %body.
{
node->getBody()->traverse(this);
// Generate the branch at the end of the %body block.
mBuilder.writeLoopBodyEnd(continueBlock);
}
switch (loopType)
{
case ELoopFor:
// For |for| loops, the expression is placed after the body and acts as the continue
// block.
if (node->getExpression())
{
node->getExpression()->traverse(this);
mNodeData.pop_back();
}
// Generate the branch at the end of the %continue block.
mBuilder.writeLoopContinueEnd(headerBlock);
break;
case ELoopWhile:
// |for| loops have the expression in the continue block and |do-while| loops have their
// condition block act as the loop's continue block. |while| loops need a branch-only
// continue loop, which is generated here.
mBuilder.writeLoopContinueEnd(headerBlock);
break;
case ELoopDoWhile:
// For |do-while|, %cond comes last.
ASSERT(hasCondition);
node->getCondition()->traverse(this);
// Generate the branch at the end of the %cond block.
const spirv::IdRef conditionValue = accessChainLoad(
&mNodeData.back(), mBuilder.getDecorations(node->getCondition()->getType()));
mBuilder.writeLoopConditionEnd(conditionValue, headerBlock, mergeBlock);
mNodeData.pop_back();
break;
}
// Pop from the conditional stack when done.
mBuilder.endConditional();
// Don't traverse the children, that's done already.
return false;
}
bool OutputSPIRVTraverser::visitBranch(Visit visit, TIntermBranch *node)
{
if (visit == PreVisit)
{
mNodeData.emplace_back();
return true;
}
// There is only ever one child at most.
ASSERT(visit != InVisit);
switch (node->getFlowOp())
{
case EOpKill:
spirv::WriteKill(mBuilder.getSpirvCurrentFunctionBlock());
mBuilder.terminateCurrentFunctionBlock();
break;
case EOpBreak:
spirv::WriteBranch(mBuilder.getSpirvCurrentFunctionBlock(),
mBuilder.getBreakTargetId());
mBuilder.terminateCurrentFunctionBlock();
break;
case EOpContinue:
spirv::WriteBranch(mBuilder.getSpirvCurrentFunctionBlock(),
mBuilder.getContinueTargetId());
mBuilder.terminateCurrentFunctionBlock();
break;
case EOpReturn:
// Evaluate the expression if any, and return.
if (node->getExpression() != nullptr)
{
ASSERT(mNodeData.size() >= 1);
const spirv::IdRef expressionValue = accessChainLoad(
&mNodeData.back(), mBuilder.getDecorations(node->getExpression()->getType()));
mNodeData.pop_back();
// TODO: handle mismatching types. http://anglebug.com/6000
spirv::WriteReturnValue(mBuilder.getSpirvCurrentFunctionBlock(), expressionValue);
mBuilder.terminateCurrentFunctionBlock();
}
else
{
spirv::WriteReturn(mBuilder.getSpirvCurrentFunctionBlock());
mBuilder.terminateCurrentFunctionBlock();
}
break;
default:
UNREACHABLE();
}
return true;
}
void OutputSPIRVTraverser::visitPreprocessorDirective(TIntermPreprocessorDirective *node)
{
// No preprocessor directives expected at this point.
UNREACHABLE();
}
spirv::Blob OutputSPIRVTraverser::getSpirv()
{
spirv::Blob result = mBuilder.getSpirv();
// Validate that correct SPIR-V was generated
ASSERT(spirv::Validate(result));
#if ANGLE_DEBUG_SPIRV_GENERATION
// Disassemble and log the generated SPIR-V for debugging.
spvtools::SpirvTools spirvTools(SPV_ENV_VULKAN_1_1);
std::string readableSpirv;
spirvTools.Disassemble(result, &readableSpirv, 0);
fprintf(stderr, "%s\n", readableSpirv.c_str());
#endif // ANGLE_DEBUG_SPIRV_GENERATION
return result;
}
} // anonymous namespace
bool OutputSPIRV(TCompiler *compiler,
TIntermBlock *root,
ShCompileOptions compileOptions,
bool forceHighp)
{
// Traverse the tree and generate SPIR-V instructions
OutputSPIRVTraverser traverser(compiler, compileOptions, forceHighp);
root->traverse(&traverser);
// Generate the final SPIR-V and store in the sink
spirv::Blob spirvBlob = traverser.getSpirv();
compiler->getInfoSink().obj.setBinary(std::move(spirvBlob));
return true;
}
} // namespace sh