summaryrefslogtreecommitdiff
path: root/tools/gfx/debug-layer/debug-resource-views.cpp
blob: 4044591815ee786a8049f19954cbf06b29b20408 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// debug-resource-views.cpp
#include "debug-resource-views.h"

#include "debug-helper-functions.h"

namespace gfx
{
using namespace Slang;

namespace debug
{

IResourceView::Desc* DebugResourceView::getViewDesc()
{
    SLANG_GFX_API_FUNC;

    return baseObject->getViewDesc();
}

Result DebugResourceView::getNativeHandle(InteropHandle* outNativeHandle)
{
    SLANG_GFX_API_FUNC;

    return baseObject->getNativeHandle(outNativeHandle);
}

DeviceAddress DebugAccelerationStructure::getDeviceAddress()
{
    SLANG_GFX_API_FUNC;

    return baseObject->getDeviceAddress();
}

Result DebugAccelerationStructure::getNativeHandle(InteropHandle* outNativeHandle)
{
    SLANG_GFX_API_FUNC;

    return baseObject->getNativeHandle(outNativeHandle);
}

IResourceView::Desc* DebugAccelerationStructure::getViewDesc()
{
    SLANG_GFX_API_FUNC;

    return baseObject->getViewDesc();
}

} // namespace debug
} // namespace gfx
> 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527
// slang-check-expr.cpp
#include "slang-check-impl.h"

// This file contains semantic-checking logic for the various
// expression types in the AST.
//
// Note that some cases of expression checking are split
// of into their own files. Notably:
//
// * `slang-check-overload.cpp` is responsible for the logic of resolving overloaded calls
//
// * `slang-check-conversion.cpp` is responsible for the logic of handling type conversion/coercion

#include "slang-ast-natural-layout.h"

#include "slang-lookup.h"
#include "slang-lookup-spirv.h"
#include "slang-ast-print.h"

namespace Slang
{
    DeclRefType* SemanticsVisitor::getExprDeclRefType(Expr * expr)
    {
        if (auto typetype = as<TypeType>(expr->type))
            return dynamicCast<DeclRefType>(typetype->getType());
        else
            return as<DeclRefType>(expr->type);
    }

    void SemanticsContext::ExprLocalScope::addBinding(LetExpr* binding)
    {
        if (!m_innerMostBinding)
        {
            SLANG_ASSERT(!m_outerMostBinding);

            // If we haven't added any bindings, then `binding`
            // becomes both the inner-most and outer most.
            //
            m_innerMostBinding = binding;
            m_outerMostBinding = binding;
        }
        else
        {
            SLANG_ASSERT(m_outerMostBinding);

            // If we already have bindings, then `binding`
            // will become the new inner-most binding.
            //
            m_innerMostBinding->body = binding;
            m_innerMostBinding = binding;
        }
    }


        /// Move `expr` into a temporary variable and execute `func` on that variable.
        ///
        /// Returns an expression that wraps both the creation and initialization of
        /// the temporary, and the computation created by `func`.
        ///
    template<typename F>
    Expr* SemanticsVisitor::moveTemp(Expr* const& expr, F const& func)
    {
        VarDecl* varDecl = m_astBuilder->create<VarDecl>();
        varDecl->parentDecl = nullptr; // TODO: need to fill this in somehow!
        varDecl->checkState = DeclCheckState::DefinitionChecked;
        varDecl->nameAndLoc.loc = expr->loc;
        varDecl->initExpr = expr;
        varDecl->type.type = expr->type.type;

        auto varDeclRef = makeDeclRef(varDecl);

        LetExpr* letExpr = m_astBuilder->create<LetExpr>();
        letExpr->decl = varDecl;

        auto body = func(varDeclRef);
        Expr* result = body;
        if (auto exprLocalScope = getExprLocalScope())
        {
            // We want to add the `LetExpr` to the set of such expressions
            // in the local scope, so that it can be emitted properly.
            //
            exprLocalScope->addBinding(letExpr);
        }
        else
        {
            // If we somehow got in here and there wasn't an expression-local
            // scope established yet, it almost certainly represents an error.
            //
            SLANG_ASSERT(exprLocalScope);

            // As a fallback, though, we will try to wire up the `letExpr`
            // to surround the body directly and return that.
            //
            letExpr->body = body;
            letExpr->type = body->type;

            result = letExpr;
        }
        return result;
    }

        /// Execute `func` on a variable with the value of `expr`.
        ///
        /// If `expr` is just a reference to an immutable (e.g., `let`) variable
        /// then this might use the existing variable. Otherwise it will create
        /// a new variable to hold `expr`, using `moveTemp()`.
        ///
    template<typename F>
    Expr* SemanticsVisitor::maybeMoveTemp(Expr* const& expr, F const& func)
    {
        // TODO: Eventually this operation could consider any case where the
        // input `expr` names an immutable "path": one that starts at an
        // immutable binding and follows a (possibly empty) chain of accesses
        // to immutable members.

        if(auto varExpr = as<VarExpr>(expr))
        {
            auto declRef = varExpr->declRef;
            if(auto varDeclRef = declRef.as<LetDecl>())
                return func(varDeclRef);
        }

        return moveTemp(expr, func);
    }

        /// Return an expression that represents "opening" the existential `expr`.
        ///
        /// The type of `expr` must be an interface type, matching `interfaceDeclRef`.
        ///
        /// If we scope down the PL theory to just the case that Slang cares about,
        /// a value of an existential type like `IMover` is a tuple of:
        ///
        ///  * a concrete type `X`
        ///  * a witness `w` of the fact that `X` implements `IMover`
        ///  * a value `v` of type `X`
        ///
        /// "Opening" an existential value is the process of decomposing a single
        /// value `e : IMover` into the pieces `X`, `w`, and `v`.
        ///
        /// Rather than return all those pieces individually, this operation
        /// returns an expression that logically corresponds to `v`: an expression
        /// of type `X`, where the type carries the knowledge that `X` implements `IMover`.
        ///
    Expr* SemanticsVisitor::openExistential(
        Expr*            expr,
        DeclRef<InterfaceDecl>  interfaceDeclRef)
    {
        // If `expr` refers to an immutable binding,
        // then we can use it directly. If it refers
        // to an arbitrary expression or a mutable
        // binding, we will move its value into an
        // immutable temporary so that we can use
        // it directly.
        //
        return maybeMoveTemp(expr, [&](DeclRef<VarDeclBase> varDeclRef)
        {
            ExtractExistentialType* openedType = m_astBuilder->getOrCreate<ExtractExistentialType>(
                varDeclRef, expr->type.type, interfaceDeclRef);

            ExtractExistentialValueExpr* openedValue = m_astBuilder->create<ExtractExistentialValueExpr>();
            openedValue->declRef = varDeclRef;
            openedValue->type = QualType(openedType);
            openedValue->originalExpr = expr;

            // The result of opening an existential is an l-value
            // if the original existential is an l-value.
            //
            if(expr->type.isLeftValue)
            {
                // Marking the opened value as an l-value is the easy part.
                //
                openedValue->type.isLeftValue = true;

                // The more challenging bit is that in this case the `maybeMoveTemp()`
                // operation will have copied the original existential value into
                // a temporary.
                //
                // If this expression is used in an l-value context, then we need
                // to be able to generate code to "write back" the modified value
                // (which will be of `openedType`) to the original location named
                // by `expr` (an existential for `interfaceDeclRef`).
                //
            }

            return openedValue;
        });
    }

        /// If `expr` has existential type, then open it.
        ///
        /// Returns an expression that opens `expr` if it had existential type.
        /// Otherwise returns `expr` itself.
        ///
        /// See `openExistential` for a discussion of what "opening" an
        /// existential-type value means.
        ///
    Expr* SemanticsVisitor::maybeOpenExistential(Expr* expr)
    {
        auto exprType = expr->type.type;

        if(auto declRefType = as<DeclRefType>(exprType))
        {
            if(auto interfaceDeclRef = declRefType->getDeclRef().as<InterfaceDecl>())
            {
                return openExistential(expr, interfaceDeclRef);
            }
        }

        // Default: apply the callback to the original expression;
        return expr;
    }

    Expr* SemanticsVisitor::maybeOpenRef(Expr* expr)
    {
        auto exprType = expr->type.type;

        if (auto refType = as<RefTypeBase>(exprType))
        {
            auto openRef = m_astBuilder->create<OpenRefExpr>();
            openRef->innerExpr = expr;
            openRef->type.isLeftValue = (as<RefType>(exprType) != nullptr);
            openRef->type.type = refType->getValueType();
            return openRef;
        }
        return expr;
    }

    Scope* SemanticsVisitor::getScope(SyntaxNode* node)
    {
        while (auto declBase = as<Decl>(node))
        {
            if (auto container = as<ContainerDecl>(node))
            {
                if (container->ownedScope)
                    return container->ownedScope;
            }
            node = declBase->parentDecl;
        }
        return nullptr;
    }

    static SourceLoc _getMemberOpLoc(Expr* expr)
    {
        if (auto m = as<MemberExpr>(expr))
            return m->memberOperatorLoc;
        if (auto m = as<StaticMemberExpr>(expr))
            return m->memberOperatorLoc;
        return SourceLoc();
    }

    void addSiblingScopeForContainerDecl(ASTBuilder* builder, ContainerDecl* dest, ContainerDecl* source)
    {
        addSiblingScopeForContainerDecl(builder, dest->ownedScope, source);
    }

    void addSiblingScopeForContainerDecl(ASTBuilder* builder, Scope* destScope, ContainerDecl* source)
    {
        auto subScope = builder->create<Scope>();
        subScope->containerDecl = source;

        subScope->nextSibling = destScope->nextSibling;
        destScope->nextSibling = subScope;
    }

    void SemanticsVisitor::diagnoseDeprecatedDeclRefUsage(
        DeclRef<Decl> declRef,
        SourceLoc loc,
        Expr* originalExpr)
    {
        // This is slightly subtle, because we don't want to warn more than
        // once for the same occurrence, however in some cases this function is
        // called more than once for the same declref (specifically in the case
        // of a non-overloaded function, once when the function is identified at
        // first, and again when it's checked from
        // CheckInvokeExprWithCheckedOperands).
        //
        // The correct fix is probably to make
        // CheckInvokeExprWithCheckedOperands reuse the original declref,
        // however that doesn't appear to be a simple change.
        //
        // What we do instead is see if there's already been a declRef
        // constructed for this expression and rest assured that it's already
        // had a diagnostic emitted.
        auto originalAppExpr = as<AppExprBase>(originalExpr);
        auto originalAppFunDecl = originalAppExpr ? as<DeclRefExpr>(originalAppExpr->functionExpr) : nullptr;
        if(originalAppFunDecl && originalAppFunDecl->declRef)
        {
            return;
        }
        if (auto deprecatedAttr = declRef.getDecl()->findModifier<DeprecatedAttribute>())
        {
            getSink()->diagnose(
                loc,
                Diagnostics::deprecatedUsage,
                declRef.getName(),
                deprecatedAttr->message);
        }
    }

    static bool isMutableGLSLBufferBlockVarExpr(Expr* expr)
    {
        const auto derefExpr = as<DerefExpr>(expr);
        if(!derefExpr)
            return false;
        const auto varExpr = as<VarExpr>(derefExpr->base);
        // Check the declaration type
        if(!varExpr)
            return false;

        const auto varExprType = varExpr->type->getCanonicalType();
        const auto ssbt = as<GLSLShaderStorageBufferType>(varExprType);
        if(!ssbt)
            return false;

        // Check the modifiers on the declaration
        const auto d = varExpr->declRef.getDecl();
        auto collection = d->findModifier<MemoryQualifierSetModifier>();
        if(collection && collection->getMemoryQualifierBit() & MemoryQualifierSetModifier::Flags::kReadOnly)
            return false;

        return true;
    }

    DeclRefExpr* SemanticsVisitor::ConstructDeclRefExpr(
        DeclRef<Decl>   declRef,
        Expr*    baseExpr,
        SourceLoc loc,
        Expr*    originalExpr)
    {
        // Compute the type that this declaration reference will have in context.
        //
        auto type = GetTypeForDeclRef(declRef, loc);

        // This is the bottleneck for using declarations which might be
        // deprecated, diagnose here.
        diagnoseDeprecatedDeclRefUsage(declRef, loc, originalExpr);

        // Construct an appropriate expression based on the structured of
        // the declaration reference.
        //
        if (baseExpr)
        {
            // If there was a base expression, we will have some kind of
            // member expression.

            // We want to check for the case where the base "expression"
            // actually names a type, because in that case we are doing
            // a static member reference.
            //
            if (auto typeType = as<TypeType>(baseExpr->type->getCanonicalType()))
            {
                // Before forming the reference, we will check if the
                // member being referenced can even be used as a static
                // member, and if not we will diagnose an error.
                //
                // TODO: It is conceptually possible to allow static
                // references to many instance members, provided we
                // change the exposed type/signature.
                //
                // E.g., if we have:
                //
                //      struct Test { float getVal() { ... } }
                //
                // Then a reference to `Test.getVal` could be allowed,
                // and given a type of `(Test) -> float` to indicate
                // that it is an "unbound" instance method.
                //
                if( !isDeclUsableAsStaticMember(declRef.getDecl()) )
                {
                    getSink()->diagnose(
                        loc,
                        Diagnostics::staticRefToNonStaticMember,
                        typeType->getType(),
                        declRef.getName());
                }

                auto expr = m_astBuilder->create<StaticMemberExpr>();
                expr->loc = loc;
                expr->type = type;
                expr->baseExpression = baseExpr;
                expr->name = declRef.getName();
                expr->declRef = declRef;
                expr->memberOperatorLoc = _getMemberOpLoc(originalExpr);
                return expr;
            }
            else if(isEffectivelyStatic(declRef.getDecl()))
            {
                // Extract the type of the baseExpr
                auto baseExprType = baseExpr->type.type;
                SharedTypeExpr* baseTypeExpr = m_astBuilder->create<SharedTypeExpr>();
                baseTypeExpr->base.type = baseExprType;
                baseTypeExpr->type.type = m_astBuilder->getTypeType(baseExprType);

                auto expr = m_astBuilder->create<StaticMemberExpr>();
                expr->loc = loc;
                expr->type = type;
                expr->baseExpression = baseTypeExpr;
                expr->name = declRef.getName();
                expr->declRef = declRef;
                expr->memberOperatorLoc = _getMemberOpLoc(originalExpr);
                return expr;
            }
            else
            {
                // If the base expression wasn't a type, then this
                // is a normal member expression.
                //
                auto expr = m_astBuilder->create<MemberExpr>();
                expr->loc = loc;
                expr->type = type;
                expr->baseExpression = baseExpr;
                expr->name = declRef.getName();
                expr->declRef = declRef;
                expr->memberOperatorLoc = _getMemberOpLoc(originalExpr);

                // If any member declares the following value is a
                // write only, we must declare the parent as a write
                // only to avoid modifying the child
                expr->type.isWriteOnly = baseExpr->type.isWriteOnly || expr->type.isWriteOnly;

                // When referring to a member through an expression,
                // the result is only an l-value if both the base
                // expression and the member agree that it should be.
                //
                // We have already used the `QualType` from the member
                // above (that is `type`), so we need to take the
                // l-value status of the base expression into account now.
                if(!baseExpr->type.isLeftValue)
                {
                    // One exception to this is if we're reading the contents
                    // of a GLSL buffer interface block which isn't marked as
                    // read_only
                    expr->type.isLeftValue = isMutableGLSLBufferBlockVarExpr(baseExpr) && (expr->type.hasReadOnlyOnTarget == false);
                }
                else
                {
                    // If we are accessing a readonly property, then the result
                    // is not an l-value.
                    if (auto propertyDecl = as<PropertyDecl>(declRef.getDecl()))
                    {
                        bool isLValue = false;
                        for (auto member : propertyDecl->members)
                        {
                            if (as<SetterDecl>(member) || as< RefAccessorDecl>(member))
                            {
                                isLValue = true;
                                break;
                            }
                        }
                        expr->type.isLeftValue = isLValue;
                    }
                }
                return expr;
            }
        }
        else
        {
            // If there is no base expression, then the result must
            // be an ordinary variable expression.
            //
            auto expr = m_astBuilder->create<VarExpr>();
            expr->loc = loc;
            expr->name = declRef.getName();
            expr->type = type;
            expr->declRef = declRef;
            // Keep a reference to the original expr if it was a genericApp/member.
            // This is needed by the language server to locate the original tokens.
            if (as<GenericAppExpr>(originalExpr) || as<MemberExpr>(originalExpr) || as<StaticMemberExpr>(originalExpr))
            {
                expr->originalExpr = originalExpr;
            }
            return expr;
        }
    }

    Expr* SemanticsVisitor::ConstructDerefExpr(
        Expr*    base,
        SourceLoc       loc)
    {
        auto elementType = getPointedToTypeIfCanImplicitDeref(base->type);
        SLANG_ASSERT(elementType);

        auto derefExpr = m_astBuilder->create<DerefExpr>();
        derefExpr->loc = loc;
        derefExpr->base = base;
        derefExpr->type = QualType(elementType);

        if (as<PtrType>(base->type))
            derefExpr->type.isLeftValue = true;
        else
            derefExpr->type.isLeftValue = base->type.isLeftValue;

        return derefExpr;
    }

    InvokeExpr* SemanticsVisitor::constructUncheckedInvokeExpr(Expr* callee, const List<Expr*>& arguments)
    {
        auto result = m_astBuilder->create<InvokeExpr>();
        result->loc = callee->loc;
        result->functionExpr = callee;
        result->arguments.addRange(arguments);
        return result;
    }

    Expr* SemanticsVisitor::maybeUseSynthesizedDeclForLookupResult(
        LookupResultItem const& item,
        Expr* originalExpr)
    {
        // If the only result from lookup is an entry in an interface decl, it could be that
        // the user is leaving out an explicit definition for the requirement and depending on
        // the compiler to synthesis the definition.
        // In this case, if the lookup is triggered from a location such that the satisfying
        // definition should be returned should it existed, we should create a placeholder decl for
        // the definition and return a reference to to newly created decl instead of the requirement
        // decl in the interface.
        switch (item.declRef.getDecl()->astNodeType)
        {
        case ASTNodeType::AssocTypeDecl:
            break;
        case ASTNodeType::FuncDecl:
            // We don't need to intercept lookup results with synthesized decls for methods,
            // because function lookups will only take place when we are checking the decl bodies.
            // At that point conformance check and synthesis is already done so they will always resolve
            // to the synthesized method.
            return nullptr;
        default:
            return nullptr;
        }

        // We need to check if the lookup should resolve to a definition in an implementation type
        // if it existed.
        // This will be the case when the lookup is initiated from the concrete implementation type instead of
        // directly from the Interface decl. The breadcrumbs of the lookup should provide this information.

        // If no breadcrumbs existed, then the lookup should just resolve to the interface requirement.

        if (!item.breadcrumbs)
            return nullptr;

        // We will only ever need to synthesis a type to satisfy an associatedtype requirement.
        // In this case the lookup should have resolved to a known associatedtype decl.
        auto builtinAssocTypeAttr = item.declRef.getDecl()->findModifier<BuiltinRequirementModifier>();
        if (!builtinAssocTypeAttr)
            return nullptr;

        DeclRefType* subType = nullptr;

        // Check if we are reaching the associated type decl through inheritance from a concrete type.
        for (auto breadcrumb = item.breadcrumbs; breadcrumb; breadcrumb = breadcrumb->next)
        {
            switch (breadcrumb->kind)
            {
            case LookupResultItem::Breadcrumb::Kind::SuperType:
            {
                auto witness = as<SubtypeWitness>(breadcrumb->val);
                if (auto subDeclRefType = as<DeclRefType>(witness->getSub()))
                {
                    if (!as<InterfaceDecl>(subDeclRefType->getDeclRef().getDecl()))
                    {
                        // Store the inner most concrete super type.
                        subType = subDeclRefType;
                    }
                }
            }
            break;
            default:
                break;
            }
        }
        if (!subType)
            return nullptr;

        subType = as<DeclRefType>(subType->getCanonicalType());
        if (!subType)
            return nullptr;

        // Don't synthesize for generic parameters.
        auto parent = as<AggTypeDecl>(subType->getDeclRef().getDecl());
        if (!parent)
            return nullptr;

        // Don't synthesize for ThisType.
        if (as<ThisTypeDecl>(subType->getDeclRef().getDecl()))
            return nullptr;
        
        // If the inner most subtype is itself an associated type, then we're dealing
        // with an abstract type. There's not need to synthesize anythin at this point.
        // 
        if (as<AssocTypeDecl>(subType->getDeclRef().getDecl()))
            return nullptr;

        // If we reach here, we are expecting a synthesized decl defined in `subType`.
        // Instead of returning a DeclRefExpr to the requirement decl, we synthesize a placeholder decl
        // in `subType` and return a DeclRefExpr to the synthesized decl.

        Decl* synthesizedDecl = nullptr;
        switch (builtinAssocTypeAttr->kind)
        {
        case BuiltinRequirementKind::DifferentialType:
            {
                auto structDecl = m_astBuilder->create<StructDecl>();
                auto conformanceDecl = m_astBuilder->create<InheritanceDecl>();
                conformanceDecl->base.type = m_astBuilder->getDiffInterfaceType();
                conformanceDecl->parentDecl = structDecl;
                structDecl->members.add(conformanceDecl);
                structDecl->parentDecl = parent;

                synthesizedDecl = structDecl;
                auto typeDef = m_astBuilder->create<TypeAliasDecl>();
                typeDef->nameAndLoc.name = getName("Differential");
                typeDef->parentDecl = structDecl;

                auto synthDeclRef = createDefaultSubstitutionsIfNeeded(m_astBuilder, this, makeDeclRef(structDecl));

                typeDef->type.type = DeclRefType::create(m_astBuilder, synthDeclRef);
                structDecl->members.add(typeDef);
            }
            break;
        default:
            return nullptr;
        }
        synthesizedDecl->parentDecl = parent;
        synthesizedDecl->nameAndLoc.name = item.declRef.getName();
        synthesizedDecl->loc = parent->loc;
        parent->members.add(synthesizedDecl);
        parent->invalidateMemberDictionary();

        // Mark the newly synthesized decl as `ToBeSynthesized` so future checking can differentiate it
        // from user-provided definitions, and proceed to fill in its definition.
        auto toBeSynthesized = m_astBuilder->create<ToBeSynthesizedModifier>();
        addModifier(synthesizedDecl, toBeSynthesized);

        auto synthDeclMemberRef = m_astBuilder->getMemberDeclRef(subType->getDeclRef(), synthesizedDecl);
        return ConstructDeclRefExpr(
            synthDeclMemberRef,
            nullptr,
            originalExpr ? originalExpr->loc : SourceLoc(),
            originalExpr);
    }

    Expr* SemanticsVisitor::ConstructLookupResultExpr(
        LookupResultItem const& item,
        Expr*            baseExpr,
        SourceLoc loc,
        Expr* originalExpr)
    {
        if (!item.declRef)
        {
            originalExpr->type = QualType(m_astBuilder->getErrorType());
            return originalExpr;
        }

        // We could be referencing a decl that will be synthesized. If so create a placeholder
        // and return a DeclRefExpr to it.
        if (auto lookupResultExpr = maybeUseSynthesizedDeclForLookupResult(item, originalExpr))
            return lookupResultExpr;

        // If we collected any breadcrumbs, then these represent
        // additional segments of the lookup path that we need
        // to expand here.
        auto bb = baseExpr;
        for (auto breadcrumb = item.breadcrumbs; breadcrumb; breadcrumb = breadcrumb->next)
        {
            switch (breadcrumb->kind)
            {
            case LookupResultItem::Breadcrumb::Kind::Member:
                bb = ConstructDeclRefExpr(breadcrumb->declRef, bb, loc, originalExpr);
                break;

            case LookupResultItem::Breadcrumb::Kind::Deref:
                bb = ConstructDerefExpr(bb, loc);
                break;

            case LookupResultItem::Breadcrumb::Kind::SuperType:
                {
                    // Note: a lookup through a super-type can
                    // occur even in the case of a `static` member,
                    // so we only modify the base expression here
                    // if there is one.
                    //
                    if( bb )
                    {
                        // We know that the breadcrumb reprsents a
                        // cast of the base expression to a super type,
                        // so we construct that cast explicitly here.
                        //
                        auto witness = as<SubtypeWitness>(breadcrumb->val);
                        SLANG_ASSERT(witness);
                        auto expr = createCastToSuperTypeExpr(witness->getSup(), bb, witness);

                        // Note that we allow a cast of an l-value to
                        // be used as an l-value here because it enables
                        // `[mutating]` methods to be called, and
                        // mutable properties to be modified, but this
                        // is probably not *technically* correct, since
                        // treating an l-value of type `Derived` as
                        // an l-value of type `Base` implies that we
                        // can assign an arbitrary value of type `Base`
                        // to that l-value (which would be an error).
                        //
                        // TODO: make sure we believe there are no
                        // issues here.
                        //
                        if(bb && bb->type.isLeftValue)
                        {
                            expr->type.isLeftValue = true;
                        }

                        bb = expr;
                    }
                }
                break;

            case LookupResultItem::Breadcrumb::Kind::This:
                {
                    // We expect a `this` to always come
                    // at the start of a chain.
                    SLANG_ASSERT(bb == nullptr);

                    // We will compute the type to use for `This` using
                    // the same logic that a direct reference to `This`
                    // uses.
                    //
                    auto thisType = calcThisType(breadcrumb->declRef);

                    // Next we construct an appropriate expression to
                    // stand in for the implicit `this` or `This` reference.
                    //
                    // The lookup process will have computed the appropriate
                    // "mode" to use for the implicit `this` or `This`.
                    //
                    auto thisParameterMode = breadcrumb->thisParameterMode;
                    if(thisParameterMode == LookupResultItem::Breadcrumb::ThisParameterMode::Type)
                    {
                        // If we are in a static context, then we do not
                        // have implicit `this` expression, and the expression
                        // we construct will need to start with the `This`
                        // type.
                        //
                        // Because we are constrained to yield an expression
                        // here, we must construct an expression that
                        // references `This`, and the *type* of that expression
                        // will be `typeof(This)`, which conceptually
                        // `typeof(typeof(this))`
                        //
                        auto thisTypeType = m_astBuilder->getTypeType(thisType);

                        auto typeExpr = m_astBuilder->create<SharedTypeExpr>();
                        typeExpr->type.type = thisTypeType;
                        typeExpr->base.type = thisType;

                        bb = typeExpr;
                    }
                    else
                    {
                        // In a context where both static and instance members can
                        // be referenced, we will construct a reference to `this`,
                        // and then rely on downstream logic to ensure that a
                        // refernece to `this.someStaticMember` will be translated
                        // over to `This.someStaticMember`.
                        //
                        ThisExpr* expr = m_astBuilder->create<ThisExpr>();
                        expr->type.type = thisType;
                        expr->loc = loc;
                        if (auto declRefExpr = as<DeclRefExpr>(originalExpr))
                            expr->scope = declRefExpr->scope;
                        else if (auto invokeExpr = as<InvokeExpr>(originalExpr))
                        {
                            if (auto calleeDeclRefExpr = as<DeclRefExpr>(invokeExpr->originalFunctionExpr))
                                expr->scope = calleeDeclRefExpr->scope;
                        }
                        // Whether or not the implicit `this` is mutable depends
                        // on the context in which it is used, and the lookup
                        // logic will have computed an appropriate "mode" based
                        // on the context during lookup.
                        //
                        expr->type.isLeftValue = thisParameterMode == LookupResultItem::Breadcrumb::ThisParameterMode::MutableValue;

                        bb = expr;
                    }
                }
                break;

            default:
                SLANG_UNREACHABLE("all cases handle");
            }
            if (getShared()->isInLanguageServer())
            {
                // Don't make breadcrumb nodes carry any source loc info,
                // as they may confuse language server functionalities.
                if (bb)
                {
                    bb->loc = SourceLoc();
                }
            }
        }

        return ConstructDeclRefExpr(item.declRef, bb, loc, originalExpr);
    }

    void SemanticsVisitor::suggestCompletionItems(
        CompletionSuggestions::ScopeKind scopeKind, LookupResult const& lookupResult)
    {
        auto& suggestions = getLinkage()->contentAssistInfo.completionSuggestions;
        suggestions.clear();
        suggestions.scopeKind = scopeKind;
        for (auto item : lookupResult)
        {
            suggestions.candidateItems.add(item);
        }
    }


    Expr* SemanticsVisitor::createLookupResultExpr(
        Name*                   name,
        LookupResult const&     lookupResult,
        Expr*            baseExpr,
        SourceLoc loc,
        Expr* originalExpr)
    {
        if (lookupResult.isOverloaded())
        {
            auto overloadedExpr = m_astBuilder->create<OverloadedExpr>();
            overloadedExpr->name = name;
            overloadedExpr->loc = loc;
            overloadedExpr->type = QualType(
                m_astBuilder->getOverloadedType());
            overloadedExpr->base = baseExpr;
            overloadedExpr->lookupResult2 = lookupResult;
            overloadedExpr->originalExpr = originalExpr;
            return overloadedExpr;
        }
        else
        {
            return ConstructLookupResultExpr(lookupResult.item, baseExpr, loc, originalExpr);
        }
    }

    DeclVisibility SemanticsVisitor::getTypeVisibility(Type* type)
    {
        if (auto declRefType = as<DeclRefType>(type))
        {
            auto v = getDeclVisibility(declRefType->getDeclRef().getDecl());
            auto args = findInnerMostGenericArgs(SubstitutionSet(declRefType->getDeclRef()));
            for (auto arg : args)
            {
                if (auto typeArg = as<DeclRefType>(arg))
                    v = Math::Min(v, getTypeVisibility(typeArg));
            }
            return v;
        }
        return DeclVisibility::Public;
    }

    bool SemanticsVisitor::isDeclVisibleFromScope(DeclRef<Decl> declRef, Scope* scope)
    {
        auto visibility = getDeclVisibility(declRef.getDecl());
        if (visibility == DeclVisibility::Public)
            return true;
        if (visibility == DeclVisibility::Internal)
        {
            // Check that the decl is in the same module as the scope.
            auto declModule = getModuleDecl(declRef.getDecl());
            if (declModule == getModuleDecl(scope))
                return true;
        }
        if (visibility == DeclVisibility::Private)
        {
            // Check that the decl is in the same or parent container decl as scope.
            Decl* parentContainer = declRef.getDecl();
            for (;parentContainer; parentContainer = parentContainer->parentDecl)
            {
                if (as<AggTypeDeclBase>(parentContainer))
                    break;
                if (as<NamespaceDeclBase>(parentContainer))
                    break;
            }

            for (auto s = scope; s; s = s->parent)
            {
                if (s->containerDecl == parentContainer)
                    return true;
            }
            return false;
        }
        return false;
    }

    LookupResult SemanticsVisitor::filterLookupResultByVisibility(const LookupResult& lookupResult)
    {
        if (!m_outerScope)
            return lookupResult;
        LookupResult filteredResult;
        for (auto item : lookupResult)
        {
            if (isDeclVisibleFromScope(item.declRef, m_outerScope))
                AddToLookupResult(filteredResult, item);
        }
        return filteredResult;
    }

    LookupResult SemanticsVisitor::filterLookupResultByVisibilityAndDiagnose(const LookupResult& lookupResult, SourceLoc loc, bool& outDiagnosed)
    {
        outDiagnosed = false;
        auto result = filterLookupResultByVisibility(lookupResult);
        if (lookupResult.isValid() && !result.isValid())
        {
            getSink()->diagnose(loc, Diagnostics::declIsNotVisible, lookupResult.item.declRef);
            outDiagnosed = true;

            if (getShared()->isInLanguageServer())
            {
                // When in language server mode, return the unfiltered result so we can still
                // provide language service around it.
                return lookupResult;
            }
        }
        return result;
    }

    LookupResult SemanticsVisitor::resolveOverloadedLookup(LookupResult const& inResult)
    {
        // If the result isn't actually overloaded, it is fine as-is
        if (!inResult.isValid()) return inResult;
        if (!inResult.isOverloaded()) return inResult;

        // We are going to build up a list of items to return.
        List<LookupResultItem> items;
        for( auto item : inResult.items )
        {
            // For each item we consider adding, we will compare it
            // to those items we've already added.
            //
            // If any of the existing items is "better" than `item`,
            // then we will skip adding `item`.
            //
            // If `item` is "better" than any of the existing items,
            // we will remove those from `items`.
            //
            bool shouldAdd = true;
            for( Index ii = 0; ii < items.getCount(); ++ii )
            {
                int cmp = CompareLookupResultItems(item, items[ii]);
                if( cmp < 0 )
                {
                    // The new `item` is strictly better
                    items.fastRemoveAt(ii);
                    --ii;
                }
                else if( cmp > 0 )
                {
                    // The existing item is strictly better
                    shouldAdd = false;
                }
            }
            if( shouldAdd )
            {
                items.add(item);
            }
        }

        // The resulting `items` list should be all those items
        // that were neither better nor worse than one another.
        //
        // There should always be at least one such item.
        //
        SLANG_ASSERT(items.getCount() != 0);

        LookupResult result;
        for( auto item : items )
        {
            AddToLookupResult(result, item);
        }
        return result;
    }

    void SemanticsVisitor::diagnoseAmbiguousReference(OverloadedExpr* overloadedExpr, LookupResult const& lookupResult)
    {
        getSink()->diagnose(overloadedExpr, Diagnostics::ambiguousReference, lookupResult.items[0].declRef.getName());

        for(auto item : lookupResult.items)
        {
            String declString = ASTPrinter::getDeclSignatureString(item, m_astBuilder);
            getSink()->diagnose(item.declRef, Diagnostics::overloadCandidate, declString);
        }
    }

    void SemanticsVisitor::diagnoseAmbiguousReference(Expr* expr)
    {
        if( auto overloadedExpr = as<OverloadedExpr>(expr) )
        {
            diagnoseAmbiguousReference(overloadedExpr, overloadedExpr->lookupResult2);
        }
        else
        {
            getSink()->diagnose(expr, Diagnostics::ambiguousExpression);
        }
    }

    Expr* SemanticsVisitor::_resolveOverloadedExprImpl(OverloadedExpr* overloadedExpr, LookupMask mask, DiagnosticSink* diagSink)
    {
        auto lookupResult = overloadedExpr->lookupResult2;
        SLANG_RELEASE_ASSERT(lookupResult.isValid() && lookupResult.isOverloaded());

        // Take the lookup result we had, and refine it based on what is expected in context.
        //
        // E.g., if there is both a type and a variable named `Foo`, but in context we know
        // that a type is expected, then we can disambiguate by assuming the type is intended.
        //
        lookupResult = refineLookup(lookupResult, mask);

        // Try to filter out overload candidates based on which ones are "better" than one another.
        lookupResult = resolveOverloadedLookup(lookupResult);

        if (!lookupResult.isValid())
        {
            // If we didn't find any symbols after filtering, then just
            // use the original and report errors that way
            return overloadedExpr;
        }

        if(!lookupResult.isOverloaded())
        {
            // If there is only a single item left in the lookup result,
            // then we can proceed to use that item alone as the resolved
            // expression.
            //
            return ConstructLookupResultExpr(
                lookupResult.item, overloadedExpr->base, overloadedExpr->loc, overloadedExpr);
        }

        // Otherwise, we weren't able to resolve the overloading given
        // the information available in context.
        //
        // If the client is asking for us to emit diagnostics about
        // this fact, we should do so here:
        //
        if( diagSink )
        {
            diagnoseAmbiguousReference(overloadedExpr, lookupResult);

            // TODO(tfoley): should we construct a new ErrorExpr here?
            return CreateErrorExpr(overloadedExpr);
        }
        else
        {
            // If the client isn't trying to *force* overload resolution
            // to complete just yet (e.g., they are just trying out one
            // candidate for an overloaded call site), then we return
            // the input expression as-is.
            //
            return overloadedExpr;
        }
    }

    Expr* SemanticsVisitor::maybeResolveOverloadedExpr(Expr* expr, LookupMask mask, DiagnosticSink* diagSink)
    {
        if (IsErrorExpr(expr))
            return expr;

        if( auto overloadedExpr = as<OverloadedExpr>(expr) )
        {
            return _resolveOverloadedExprImpl(overloadedExpr, mask, diagSink);
        }
        else
        {
            return expr;
        }
    }

    Expr* SemanticsVisitor::resolveOverloadedExpr(OverloadedExpr* overloadedExpr, LookupMask mask)
    {
        return _resolveOverloadedExprImpl(overloadedExpr, mask, getSink());
    }

    Type* SemanticsVisitor::tryGetDifferentialType(ASTBuilder* builder, Type* type)
    {
        if (auto ptrType = as<PtrTypeBase>(type))
        {
            auto baseDiffType = tryGetDifferentialType(builder, ptrType->getValueType());
            if (!baseDiffType) return nullptr;
            return builder->getPtrType(
                baseDiffType,
                ptrType->getClassInfo().m_name);
        }
        else if (auto arrayType = as<ArrayExpressionType>(type))
        {
            auto baseDiffType = tryGetDifferentialType(builder, arrayType->getElementType());
            if (!baseDiffType) return nullptr;
            return builder->getArrayType(
                baseDiffType,
                arrayType->getElementCount());
        }

        if (auto declRefType = as<DeclRefType>(type))
        {
            if (auto builtinRequirement = declRefType->getDeclRef().getDecl()->findModifier<BuiltinRequirementModifier>())
            {
                if (builtinRequirement->kind == BuiltinRequirementKind::DifferentialType)
                {
                    // We are trying to get differential type from a differential type.
                    // The result is itself.
                    return type;
                }
            }
            type = resolveType(type);
            if (const auto witness = as<SubtypeWitness>(tryGetInterfaceConformanceWitness(type, builder->getDifferentiableInterfaceType())))
            {
                auto diffTypeLookupResult = lookUpMember(
                    getASTBuilder(),
                    this,
                    getName("Differential"),
                    type,
                    nullptr,
                    Slang::LookupMask::type,
                    Slang::LookupOptions::None);

                diffTypeLookupResult = resolveOverloadedLookup(diffTypeLookupResult);

                if (!diffTypeLookupResult.isValid())
                {
                    return nullptr;
                }
                else if (diffTypeLookupResult.isOverloaded())
                {
                    return nullptr;
                }
                else
                {
                    SharedTypeExpr* baseTypeExpr = m_astBuilder->create<SharedTypeExpr>();
                    baseTypeExpr->base.type = type;
                    baseTypeExpr->type.type = m_astBuilder->getTypeType(type);

                    auto diffTypeExpr = ConstructLookupResultExpr(
                        diffTypeLookupResult.item,
                        baseTypeExpr,
                        declRefType->getDeclRef().getLoc(),
                        baseTypeExpr);

                    return resolveType(ExtractTypeFromTypeRepr(diffTypeExpr));
                }
            }
        }

        return nullptr;
    }

    Type* SemanticsVisitor::getDifferentialType(ASTBuilder* builder, Type* type, SourceLoc loc)
    {
        auto result = tryGetDifferentialType(builder, type);
        if (!result)
        {
            getSink()->diagnose(loc, Diagnostics::typeDoesntImplementInterfaceRequirement, type, getName("Differential"));
            return m_astBuilder->getErrorType();
        }
        return result;
    }

    void SemanticsVisitor::addDifferentiableTypeToDiffTypeRegistry(DeclRefType* type, SubtypeWitness* witness)
    {
        SLANG_RELEASE_ASSERT(m_parentDifferentiableAttr);
        if (witness)
        {
            m_parentDifferentiableAttr->addType(type->getDeclRef(), witness);
        }
    }

    void SemanticsVisitor::maybeRegisterDifferentiableType(ASTBuilder* builder, Type* type)
    {
        if (!builder->isDifferentiableInterfaceAvailable())
        {
            return;
        }

        if (!m_parentDifferentiableAttr)
        {
            return;
        }

        maybeRegisterDifferentiableTypeImplRecursive(builder, type);
    }

    void SemanticsVisitor::maybeRegisterDifferentiableTypeImplRecursive(ASTBuilder* builder, Type* type)
    {
        // Recursively visit the tree of type and register all differentiable types along the way.
        
        if (as<TypeType>(type))
            return;
        if (!type)
            return;

        // Have we already registered this type? If so we can exit now.
        if (m_parentDifferentiableAttr->m_typeRegistrationWorkingSet.contains(type))
            return;

        m_parentDifferentiableAttr->m_typeRegistrationWorkingSet.add(type);

        // Check for special cases such as PtrTypeBase<T> or Array<T>
        // This could potentially be handled later by simply defining extensions
        // for Ptr<T:IDifferentiable> etc..
        //
        if (auto ptrType = as<PtrTypeBase>(type))
        {
            maybeRegisterDifferentiableTypeImplRecursive(builder, ptrType->getValueType());
            return;
        }

        if (auto arrayType = as<ArrayExpressionType>(type))
        {
            maybeRegisterDifferentiableTypeImplRecursive(builder, arrayType->getElementType());
            // Fall through to register the array type itself.
        }

        if (auto declRefType = as<DeclRefType>(type))
        {
            if (auto subtypeWitness = as<SubtypeWitness>(
                tryGetInterfaceConformanceWitness(type, getASTBuilder()->getDifferentiableInterfaceType())))
            {
                addDifferentiableTypeToDiffTypeRegistry((DeclRefType*)type, subtypeWitness);
            }
            if (auto aggTypeDeclRef = declRefType->getDeclRef().as<AggTypeDecl>())
            {
                foreachDirectOrExtensionMemberOfType<InheritanceDecl>(this, aggTypeDeclRef, [&](DeclRef<InheritanceDecl> member)
                    {
                        auto subType = DeclRefType::create(m_astBuilder, member);
                        maybeRegisterDifferentiableTypeImplRecursive(m_astBuilder, subType);
                    });
                foreachDirectOrExtensionMemberOfType<VarDeclBase>(this, aggTypeDeclRef, [&](DeclRef<VarDeclBase> member)
                    {
                        auto fieldType = getType(m_astBuilder, member);
                        maybeRegisterDifferentiableTypeImplRecursive(m_astBuilder, fieldType);
                    });
            }
            SubstitutionSet(declRefType->getDeclRef()).forEachSubstitutionArg([&](Val* arg)
                {
                    if (auto typeArg = as<Type>(arg))
                    {
                        maybeRegisterDifferentiableTypeImplRecursive(m_astBuilder, typeArg);
                    }
                });
            return;
        }
    }


    Expr* SemanticsVisitor::CheckTerm(Expr* term)
    {
        auto checkedTerm = _CheckTerm(term);
        // Differentiable type checking.
        // TODO: This can be super slow.
        if (this->m_parentFunc &&
            this->m_parentFunc->findModifier<DifferentiableAttribute>())
        {
            maybeRegisterDifferentiableType(getASTBuilder(), checkedTerm->type.type);
        }
        return checkedTerm;
    }

    Expr* SemanticsVisitor::_CheckTerm(Expr* term)
    {
        if (!term) return nullptr;

        // The process of checking a term/expression can end up introducing
        // temporaries that need to be added to an outer scope. When jumping
        // into expression checking, we want to check if we already have such
        // a scope in place. If we do, we will re-use it for any sub-expressions.
        // If not, we need to create one.
        //
        if (getExprLocalScope())
        {
            return dispatchExpr(term, *this);
        }

        ExprLocalScope exprLocalScope;

        Expr* checkedTerm = dispatchExpr(term, withExprLocalScope(&exprLocalScope));

        if (IsErrorExpr(checkedTerm))
            return checkedTerm;

        LetExpr* outerMostBinding = exprLocalScope.getOuterMostBinding();
        if(!outerMostBinding)
        {
            return checkedTerm;
        }

        LetExpr* binding = outerMostBinding;
        auto type = checkedTerm->type;
        while (binding)
        {
            binding->type = type;

            if (const auto body = binding->body)
            {
                binding = as<LetExpr>(binding->body);
                SLANG_ASSERT(binding);
                continue;
            }
            else
            {
                binding->body = checkedTerm;
                break;
            }
        }

        return outerMostBinding;
    }

    Expr* SemanticsVisitor::CreateErrorExpr(Expr* expr)
    {
        if (!expr)
        {
            expr = m_astBuilder->create<IncompleteExpr>();
        }
        expr->type = QualType(m_astBuilder->getErrorType());
        return expr;
    }

    bool SemanticsVisitor::IsErrorExpr(Expr* expr)
    {
        // TODO: we may want other cases here...

        if (const auto errorType = as<ErrorType>(expr->type))
            return true;

        return false;
    }

    Expr* SemanticsVisitor::GetBaseExpr(Expr* expr)
    {
        if (auto memberExpr = as<MemberExpr>(expr))
        {
            return memberExpr->baseExpression;
        }
        else if(auto overloadedExpr = as<OverloadedExpr>(expr))
        {
            return overloadedExpr->base;
        }
        else if (auto overloadedExpr2 = as<OverloadedExpr2>(expr))
        {
            return overloadedExpr2->base;
        }
        else if (auto genApp = as<GenericAppExpr>(expr))
        {
            return GetBaseExpr(genApp->functionExpr);
        }
        else if (auto partiallyApplied = as<PartiallyAppliedGenericExpr>(expr))
        {
            return GetBaseExpr(partiallyApplied->originalExpr);
        }
        return nullptr;
    }

    Expr* SemanticsExprVisitor::visitIncompleteExpr(IncompleteExpr* expr)
    {
        expr->type = m_astBuilder->getErrorType();
        return expr;
    }

    Expr* SemanticsExprVisitor::visitBoolLiteralExpr(BoolLiteralExpr* expr)
    {
        expr->type = m_astBuilder->getBoolType();
        return expr;
    }

    Expr* SemanticsExprVisitor::visitNullPtrLiteralExpr(NullPtrLiteralExpr* expr)
    {
        expr->type = m_astBuilder->getNullPtrType();
        return expr;
    }

    Expr* SemanticsExprVisitor::visitNoneLiteralExpr(NoneLiteralExpr* expr)
    {
        expr->type = m_astBuilder->getNoneType();
        return expr;
    }

    Expr* SemanticsExprVisitor::visitIntegerLiteralExpr(IntegerLiteralExpr* expr)
    {
        // The expression might already have a type, determined by its suffix.
        // It it doesn't, we will give it a default type.
        //
        // TODO: We should be careful to pick a "big enough" type
        // based on the size of the value (e.g., don't try to stuff
        // a constant in an `int` if it requires 64 or more bits).
        //
        // The long-term solution here is to give a type to a literal
        // based on the context where it is used, but that requires
        // a more sophisticated type system than we have today.
        //
        if(!expr->type.type)
        {
            expr->type = m_astBuilder->getBuiltinType(expr->suffixType);
        }
        return expr;
    }

    Expr* SemanticsExprVisitor::visitFloatingPointLiteralExpr(FloatingPointLiteralExpr* expr)
    {
        if(!expr->type.type)
        {
            expr->type = m_astBuilder->getBuiltinType(expr->suffixType);
        }
        return expr;
    }

    Expr* SemanticsExprVisitor::visitStringLiteralExpr(StringLiteralExpr* expr)
    {
        expr->type = m_astBuilder->getStringType();
        return expr;
    }

    IntVal* SemanticsVisitor::getIntVal(IntegerLiteralExpr* expr)
    {
        return m_astBuilder->getIntVal(expr->type.type, expr->value);
    }

    IntVal* SemanticsVisitor::tryConstantFoldExpr(
        SubstExpr<InvokeExpr>           invokeExpr,
        ConstantFoldingKind             kind,
        ConstantFoldingCircularityInfo* circularityInfo)
    {
        // We need all the operands to the expression

        // Check if the callee is an operation that is amenable to constant-folding.
        //
        // For right now we will look for calls to intrinsic functions, and then inspect
        // their names (this is bad and slow).
        auto funcDeclRefExpr = getBaseExpr(invokeExpr).as<DeclRefExpr>();
        if (!funcDeclRefExpr) return nullptr;

        auto funcDeclRef = getDeclRef(m_astBuilder, funcDeclRefExpr);
        if (!funcDeclRef)
            return nullptr;
        auto intrinsicMod = funcDeclRef.getDecl()->findModifier<IntrinsicOpModifier>();
        auto implicitCast = funcDeclRef.getDecl()->findModifier<ImplicitConversionModifier>();
        if (!intrinsicMod && !implicitCast)
        {
            // We can't constant fold anything that doesn't map to a builtin
            // operation right now.
            //
            // TODO: we should really allow constant-folding for anything
            // that can be lowered to our bytecode...
            return nullptr;
        }

        // Let's not constant-fold operations with more than a certain number of arguments, for simplicity
        static const int kMaxArgs = 8;
        auto argCount = getArgCount(invokeExpr);
        if (argCount > kMaxArgs)
            return nullptr;

        // Before checking the operation name, let's look at the arguments
        IntVal* argVals[kMaxArgs];
        IntegerLiteralValue constArgVals[kMaxArgs];
        bool allConst = true;
        for(Index a = 0; a < argCount; ++a)
        {
            auto argExpr = getArg(invokeExpr, a);
            auto argVal = tryFoldIntegerConstantExpression(argExpr, kind, circularityInfo);
            if (!argVal)
                return nullptr;

            argVals[a] = argVal;

            if (auto constArgVal = as<ConstantIntVal>(argVal))
            {
                constArgVals[a] = constArgVal->getValue();
            }
            else
            {
                allConst = false;
            }
        }

        if (!allConst)
        {
            // We support a very limited number of operations
            // on "constants" that aren't actually known, to be able to handle a generic
            // that takes an integer `N` but then constructs a vector of size `N+1`.
            //
            // The hard part there is implementing the rules for value unification in the
            // presence of more complicated `IntVal` subclasses, like `SumIntVal`. You'd
            // need inference to be smart enough to know that `2 + N` and `N + 2` are the
            // same value, as are `N + M + 1 + 1` and `M + 2 + N`.
            //
            // This is done by constructing a 'PolynomialIntVal' and rely on its
            // `canonicalize` operation.
            if (implicitCast)
            {
                // We cannot support casting in this case.
                return nullptr;
            }

            auto opName = funcDeclRef.getName();

            // handle binary operators
            if (opName == getName("-"))
            {
                if (argCount == 1)
                {
                    return PolynomialIntVal::neg(m_astBuilder, argVals[0]);
                }
                else if (argCount == 2)
                {
                    return PolynomialIntVal::sub(m_astBuilder, argVals[0], argVals[1]);
                }
            }
            else if (opName == getName("+"))
            {
                if (argCount == 1)
                {
                    return argVals[0];
                }
                else if (argCount == 2)
                {
                    return PolynomialIntVal::add(m_astBuilder, argVals[0], argVals[1]);
                }
            }
            else if (opName == getName("*"))
            {
                if (argCount == 2)
                {
                    return PolynomialIntVal::mul(m_astBuilder, argVals[0], argVals[1]);
                }
            }
            else if (opName == getName("/") || opName == getName("==") || opName == getName(">=") || opName == getName("<=") || opName == getName("!=")
                || opName == getName(">") || opName == getName("<") || opName == getName("&&") || opName == getName("||") || opName == getName("!")
                || opName == getName("|") || opName == getName("&") || opName == getName("^") || opName == getName("~") || opName == getName("%") ||
                opName == getName("?:") || opName == getName("<<") || opName == getName(">>"))
            {
                auto result = m_astBuilder->getOrCreate<FuncCallIntVal>(
                    invokeExpr.getExpr()->type.type,
                    funcDeclRef,
                    as<Type>(funcDeclRefExpr.getExpr()->type->substitute(
                        m_astBuilder, funcDeclRefExpr.getSubsts())),
                    makeArrayView(argVals, argCount));
                SLANG_RELEASE_ASSERT(result->getFuncType());
                return result;
            }
            return nullptr;
        }

        // At this point, all the operands had simple integer values, so we are golden.
        IntegerLiteralValue resultValue = 0;
        // If this is an implicit cast, we can try to fold.
        if (implicitCast)
        {
            auto targetBasicType = as<BasicExpressionType>(invokeExpr.getExpr()->type.type);
            if (!targetBasicType)
                return nullptr;
            auto foldVal = as<IntVal>(
                TypeCastIntVal::tryFoldImpl(m_astBuilder, targetBasicType, argVals[0], getSink()));
            if (foldVal)
                return foldVal;
            auto result = m_astBuilder->getTypeCastIntVal(targetBasicType, argVals[0]);
            return result;
        }
        else
        {
            auto opName = funcDeclRef.getName();

            // handle binary operators
            if (opName == getName("-"))
            {
                if (argCount == 1)
                {
                    resultValue = -constArgVals[0];
                }
                else if (argCount == 2)
                {
                    resultValue = constArgVals[0] - constArgVals[1];
                }
            }
            else if (opName == getName("!"))
            {
                resultValue = constArgVals[0] != 0;
            }
            else if (opName == getName("~"))
            {
                resultValue = ~constArgVals[0];
            }

            // simple binary operators
#define CASE(OP)                                                    \
            else if(opName == getName(#OP)) do {                    \
                if(argCount != 2) return nullptr;                   \
                resultValue = constArgVals[0] OP constArgVals[1];   \
            } while(0)

            CASE(+); // TODO: this can also be unary...
            CASE(*);
            CASE(<<);
            CASE(>>);
            CASE(&);
            CASE(|);
            CASE(^);
            CASE(!=);
            CASE(==);
            CASE(>=);
            CASE(<=);
            CASE(<);
            CASE(>);
#undef CASE
            // binary operators with chance of divide-by-zero
            // TODO: issue a suitable error in that case
#define CASE(OP)                                                    \
            else if(opName == getName(#OP)) do {                    \
                if(argCount != 2) return nullptr;                   \
                if(!constArgVals[1]) return nullptr;                \
                resultValue = constArgVals[0] OP constArgVals[1];   \
            } while(0)
            CASE(/);
            CASE(%);
#undef CASE
            else if (opName == getName("?:"))
            {
                if (argCount != 3)
                    return nullptr;
                if (constArgVals[0] != 0)
                    resultValue = constArgVals[1];
                else
                    resultValue = constArgVals[2];
            }
            // TODO(tfoley): more cases
            else
            {
                return nullptr;
            }
        }

        IntVal* result = m_astBuilder->getIntVal(invokeExpr.getExpr()->type.type, resultValue);
        return result;
    }

    bool SemanticsVisitor::_checkForCircularityInConstantFolding(
        Decl*                           decl,
        ConstantFoldingCircularityInfo* circularityInfo)
    {
        // TODO: If the `decl` is already on the chain of `circularityInfo`,
        // then we know that we are trying to recursively fold the
        // same declaration as part of its own definition, and we need
        // to diagnose that as an error.
        //
        for( auto info = circularityInfo; info; info = info->next )
        {
            if(decl == info->decl)
            {
                getSink()->diagnose(decl, Diagnostics::variableUsedInItsOwnDefinition, decl);
                return true;
            }
        }

        return false;
    }

    IntVal* SemanticsVisitor::tryConstantFoldDeclRef(
        DeclRef<VarDeclBase> const&     declRef,
        ConstantFoldingKind             kind,
        ConstantFoldingCircularityInfo* circularityInfo)
    {
        auto decl = declRef.getDecl();

        if(_checkForCircularityInConstantFolding(decl, circularityInfo))
            return nullptr;

        // In HLSL, `const` is used to mark compile-time constant expressions.
        if(!decl->hasModifier<ConstModifier>())
            return nullptr;
        if (decl->hasModifier<ExternModifier>())
        {
            // Extern const is not considered compile-time constant by the front-end.
            if (kind == ConstantFoldingKind::CompileTime)
                return nullptr;
            // But if we are OK with link-time constants, we can still fold it into a val.
            auto rs = m_astBuilder->getOrCreate<GenericParamIntVal>(
                declRef.substitute(m_astBuilder, declRef.getDecl()->getType()),
                declRef);
            return rs;
        }

        if (isInterfaceRequirement(decl))
        {
            auto witness = findThisTypeWitness(SubstitutionSet(declRef), as<InterfaceDecl>(decl->parentDecl));

            auto val = WitnessLookupIntVal::tryFold(
                m_astBuilder,
                witness,
                decl,
                declRef.substitute(m_astBuilder, decl->type.type));
            return as<IntVal>(val);
        }

        if (!getInitExpr(m_astBuilder, declRef))
            return nullptr;

        ensureDecl(declRef.getDecl(), DeclCheckState::DefinitionChecked);
        ConstantFoldingCircularityInfo newCircularityInfo(decl, circularityInfo);
        return tryConstantFoldExpr(getInitExpr(m_astBuilder, declRef), kind, &newCircularityInfo);
    }

    IntVal* SemanticsVisitor::tryConstantFoldExpr(
        SubstExpr<Expr>                 expr,
        ConstantFoldingKind             kind,
        ConstantFoldingCircularityInfo* circularityInfo)
    {
        
        // Unwrap any "identity" expressions
        while (auto parenExpr = expr.as<ParenExpr>())
        {
            expr = getBaseExpr(parenExpr);
        }

        if (auto intLitExpr = expr.as<IntegerLiteralExpr>())
        {
            return getIntVal(intLitExpr);
        }

        if (auto boolLitExpr = expr.as<BoolLiteralExpr>())
        {
            // If it's a boolean, we allow promotion to int.
            const IntegerLiteralValue value = IntegerLiteralValue(boolLitExpr.getExpr()->value);
            return m_astBuilder->getIntVal(m_astBuilder->getBoolType(), value);
        }

        if (auto arrayLengthExpr = expr.as<GetArrayLengthExpr>())
        {
            if (arrayLengthExpr.getExpr()->arrayExpr && arrayLengthExpr.getExpr()->arrayExpr->type)
            {
                auto type = arrayLengthExpr.getExpr()->arrayExpr->type.type->substitute(m_astBuilder, expr.getSubsts());
                if (auto arrayType = as<ArrayExpressionType>(type))
                {
                    if (!arrayType->isUnsized())
                    {
                        if (auto val = as<IntVal>(arrayType->getElementCount()))
                            return val;
                    }
                }
            }
        }

        // it is possible that we are referring to a generic value param
        if (auto declRefExpr = expr.as<DeclRefExpr>())
        {
            auto declRef = getDeclRef(m_astBuilder, declRefExpr);

            if (auto genericValParamRef = declRef.as<GenericValueParamDecl>())
            {
                Val* valResult = m_astBuilder->getOrCreate<GenericParamIntVal>(
                    declRef.substitute(m_astBuilder, genericValParamRef.getDecl()->getType()),
                    genericValParamRef);
                valResult = valResult->substitute(m_astBuilder, expr.getSubsts());
                return as<IntVal>(valResult);
            }

            // We may also need to check for references to variables that
            // are defined in a way that can be used as a constant expression:
            if(auto varRef = declRef.as<VarDeclBase>())
            {
                return tryConstantFoldDeclRef(varRef, kind, circularityInfo);
            }
            else if(auto enumRef = declRef.as<EnumCaseDecl>())
            {
                // The cases in an `enum` declaration can also be used as constant expressions,
                if(auto tagExpr = getTagExpr(m_astBuilder, enumRef))
                {
                    auto enumCaseDecl = enumRef.getDecl();
                    if(_checkForCircularityInConstantFolding(enumCaseDecl, circularityInfo))
                        return nullptr;

                    ConstantFoldingCircularityInfo newCircularityInfo(enumCaseDecl, circularityInfo);
                    auto intVal = as<IntVal>(tryConstantFoldExpr(tagExpr, kind, &newCircularityInfo));
                    if (!intVal)
                        return nullptr;
                    return as<IntVal>(m_astBuilder->getTypeCastIntVal(enumCaseDecl->getType(), intVal)->resolve());
                }
            }
        }

        if(auto castExpr = expr.as<TypeCastExpr>())
        {
            auto substType = getType(m_astBuilder, expr);
            if (!substType)
                return nullptr;
            if (!isValidCompileTimeConstantType(substType))
                return nullptr;
            auto val = tryConstantFoldExpr(getArg(castExpr, 0), kind, circularityInfo);
            if (val)
            {
                if (!castExpr.getExpr()->type)
                    return nullptr;
                auto foldVal = as<IntVal>(
                    TypeCastIntVal::tryFoldImpl(m_astBuilder, substType, val, getSink()));
                if (foldVal)
                    return foldVal;
                auto result = m_astBuilder->getTypeCastIntVal(substType, val);
                return result;
            }
        }
        else if (auto invokeExpr = expr.as<InvokeExpr>())
        {
            auto val = tryConstantFoldExpr(invokeExpr, kind, circularityInfo);
            if (val)
                return val;
        }
        else if (auto sizeOfLikeExpr = as<SizeOfLikeExpr>(expr.getExpr()))
        {
            ASTNaturalLayoutContext context(getASTBuilder(), nullptr);
            const auto size = context.calcSize(sizeOfLikeExpr->sizedType);
            if (!size)
            {
                return nullptr;
            }

            auto value = as<AlignOfExpr>(sizeOfLikeExpr) ? 
                size.alignment :
                size.size;
            
            // We can return as an IntVal
            return getASTBuilder()->getIntVal(expr.getExpr()->type, value);
        }
        
        return nullptr;
    }

    IntVal* SemanticsVisitor::tryFoldIntegerConstantExpression(
        SubstExpr<Expr>                 expr,
        ConstantFoldingKind             kind,
        ConstantFoldingCircularityInfo* circularityInfo)
    {
        // Check if type is acceptable for an integer constant expression
        //
        if(!isValidCompileTimeConstantType(getType(m_astBuilder, expr)))
            return nullptr;

        // Consider operations that we might be able to constant-fold...
        //
        return tryConstantFoldExpr(expr, kind, circularityInfo);
    }

    IntVal* SemanticsVisitor::CheckIntegerConstantExpression(Expr* inExpr, IntegerConstantExpressionCoercionType coercionType, Type* expectedType, ConstantFoldingKind kind, DiagnosticSink* sink)
    {
        // No need to issue further errors if the expression didn't even type-check.
        if(IsErrorExpr(inExpr)) return nullptr;

        // First coerce the expression to the expected type
        Expr* expr = nullptr;
        switch (coercionType)
        {
        case IntegerConstantExpressionCoercionType::SpecificType:
            expr = coerce(CoercionSite::General, expectedType, inExpr);
            break;
        case IntegerConstantExpressionCoercionType::AnyInteger:
            if (isScalarIntegerType(inExpr->type))
                expr = inExpr;
            else
                expr = coerce(CoercionSite::General, m_astBuilder->getIntType(), inExpr);
            break;
        default:
            break;
        }

        // No need to issue further errors if the type coercion failed.
        if(IsErrorExpr(expr)) return nullptr;

        auto result = tryFoldIntegerConstantExpression(expr, kind, nullptr);
        if (!result && sink)
        {
            sink->diagnose(expr, Diagnostics::expectedIntegerConstantNotConstant);
        }
        return result;
    }

    IntVal* SemanticsVisitor::CheckIntegerConstantExpression(Expr* inExpr, IntegerConstantExpressionCoercionType coercionType, Type* expectedType, ConstantFoldingKind kind)
    {
        return CheckIntegerConstantExpression(inExpr, coercionType, expectedType, kind, getSink());
    }

    IntVal* SemanticsVisitor::CheckEnumConstantExpression(Expr* expr, ConstantFoldingKind kind)
    {
        // No need to issue further errors if the expression didn't even type-check.
        if(IsErrorExpr(expr)) return nullptr;

        // No need to issue further errors if the type coercion failed.
        if(IsErrorExpr(expr)) return nullptr;

        auto result = tryConstantFoldExpr(expr, kind, nullptr);
        if (!result)
        {
            getSink()->diagnose(expr, Diagnostics::expectedIntegerConstantNotConstant);
        }
        return result;
    }

    Expr* SemanticsVisitor::CheckSimpleSubscriptExpr(
        IndexExpr*   subscriptExpr,
        Type*              elementType)
    {
        auto baseExpr = subscriptExpr->baseExpression;
        if (subscriptExpr->indexExprs.getCount() < 1)
        {
            getSink()->diagnose(subscriptExpr, Diagnostics::notEnoughArguments, subscriptExpr->indexExprs.getCount(), 1);
            return CreateErrorExpr(subscriptExpr);
        }
        else if (subscriptExpr->indexExprs.getCount() > 1)
        {
            getSink()->diagnose(subscriptExpr, Diagnostics::tooManyArguments, subscriptExpr->indexExprs.getCount(), 1);
            return CreateErrorExpr(subscriptExpr);
        }

        auto indexExpr = subscriptExpr->indexExprs[0];

        if (!indexExpr->type->equals(m_astBuilder->getIntType()) &&
            !indexExpr->type->equals(m_astBuilder->getUIntType()))
        {
            getSink()->diagnose(indexExpr, Diagnostics::subscriptIndexNonInteger);
            return CreateErrorExpr(subscriptExpr);
        }

        subscriptExpr->type = QualType(elementType);

        // TODO(tfoley): need to be more careful about this stuff
        subscriptExpr->type.isLeftValue = baseExpr->type.isLeftValue;

        return subscriptExpr;
    }

    Expr* SemanticsExprVisitor::visitIndexExpr(IndexExpr* subscriptExpr)
    {
        bool needDeref = false;
        auto baseExpr = checkBaseForMemberExpr(subscriptExpr->baseExpression, needDeref);

        // If the base expression is a type, it means that this is an array declaration,
        // then we should disable short-circuit in case there is logical expression in
        // the subscript
        auto baseType = baseExpr->type.Ptr();
        auto baseTypeType = as<TypeType>(baseType);
        auto subVisitor = (baseTypeType && m_shouldShortCircuitLogicExpr)?
            SemanticsVisitor(disableShortCircuitLogicalExpr()) : *this;

        for (auto& arg : subscriptExpr->indexExprs)
        {
            arg = subVisitor.CheckTerm(arg);
        }

        // If anything went wrong in the base expression,
        // then just move along...
        if (IsErrorExpr(baseExpr))
            return CreateErrorExpr(subscriptExpr);

        subscriptExpr->baseExpression = baseExpr;

        // Otherwise, we need to look at the type of the base expression,
        // to figure out how subscripting should work.
        if (baseTypeType)
        {
            // We are trying to "index" into a type, so we have an expression like `float[2]`
            // which should be interpreted as resolving to an array type.

            IntVal* elementCount = nullptr;
            if (subscriptExpr->indexExprs.getCount() == 1)
            {
                elementCount = CheckIntegerConstantExpression(subscriptExpr->indexExprs[0], IntegerConstantExpressionCoercionType::AnyInteger, nullptr, ConstantFoldingKind::LinkTime);
            }
            else if (subscriptExpr->indexExprs.getCount() != 0)
            {
                getSink()->diagnose(subscriptExpr, Diagnostics::multiDimensionalArrayNotSupported);
            }

            auto elementType = CoerceToUsableType(TypeExp(baseExpr, baseTypeType->getType()));
            auto arrayType = getArrayType(
                m_astBuilder,
                elementType,
                elementCount);

            subscriptExpr->type = QualType(m_astBuilder->getTypeType(arrayType));
            return subscriptExpr;
        }
        else if (auto baseArrayType = as<ArrayExpressionType>(baseType))
        {
            return CheckSimpleSubscriptExpr(
                subscriptExpr,
                baseArrayType->getElementType());
        }
        else if (auto vecType = as<VectorExpressionType>(baseType))
        {
            return CheckSimpleSubscriptExpr(
                subscriptExpr,
                vecType->getElementType());
        }
        else if (auto matType = as<MatrixExpressionType>(baseType))
        {
            // TODO(tfoley): We shouldn't go and recompute
            // row types over and over like this... :(
            auto rowType = createVectorType(
                matType->getElementType(),
                matType->getColumnCount());

            return CheckSimpleSubscriptExpr(
                subscriptExpr,
                rowType);
        }

        // Default behavior is to look at all available `__subscript`
        // declarations on the type and try to call one of them.

        auto operatorName = getName("operator[]");

        LookupResult lookupResult = lookUpMember(
            m_astBuilder,
            this,
            operatorName,
            baseType,
            m_outerScope,
            LookupMask::Default,
            LookupOptions::NoDeref);
        bool diagnosed = false;
        lookupResult = filterLookupResultByVisibilityAndDiagnose(lookupResult, subscriptExpr->loc, diagnosed);
        if (!lookupResult.isValid())
        {
            if (!diagnosed)
                getSink()->diagnose(subscriptExpr, Diagnostics::subscriptNonArray, baseType);
            return CreateErrorExpr(subscriptExpr);
        }
        auto subscriptFuncExpr = createLookupResultExpr(
            operatorName,
            lookupResult,
            subscriptExpr->baseExpression,
            subscriptExpr->loc,
            subscriptExpr);

        InvokeExpr* subscriptCallExpr = m_astBuilder->create<InvokeExpr>();
        subscriptCallExpr->loc = subscriptExpr->loc;
        subscriptCallExpr->functionExpr = subscriptFuncExpr;
        subscriptCallExpr->arguments.addRange(subscriptExpr->indexExprs);
        subscriptCallExpr->argumentDelimeterLocs.addRange(subscriptExpr->argumentDelimeterLocs);

        return CheckInvokeExprWithCheckedOperands(subscriptCallExpr);
    }

    Expr* SemanticsExprVisitor::visitParenExpr(ParenExpr* expr)
    {
        auto base = expr->base;
        base = CheckTerm(base);

        expr->base = base;
        expr->type = base->type;
        return expr;
    }

    void SemanticsVisitor::maybeDiagnoseThisNotLValue(Expr* expr)
    {
        // We will try to handle expressions of the form:
        //
        //      e ::= "this"
        //          | e . name
        //          | e [ expr ]
        //
        // We will unwrap the `e.name` and `e[expr]` cases in a loop.
        Expr* e = expr;
        for(;;)
        {
            if(auto memberExpr = as<MemberExpr>(e))
            {
                e = memberExpr->baseExpression;
            }
            else if(auto subscriptExpr = as<IndexExpr>(e))
            {
                e = subscriptExpr->baseExpression;
            }
            else
            {
                break;
            }
        }
        //
        // Now we check to see if we have a `this` expression,
        // and if it is immutable.
        if(auto thisExpr = as<ThisExpr>(e))
        {
            if(!thisExpr->type.isLeftValue)
            {
                getSink()->diagnoseWithoutSourceView(thisExpr, Diagnostics::thisIsImmutableByDefault);
            }
        }
    }

    Expr* SemanticsVisitor::checkAssignWithCheckedOperands(AssignExpr* expr)
    {
        if (expr->right->type.isWriteOnly)
            getSink()->diagnose(expr, Diagnostics::readingFromWriteOnly);

        expr->left = maybeOpenRef(expr->left);
        auto type = expr->left->type;
        auto right = maybeOpenRef(expr->right);
        expr->right = coerce(CoercionSite::Assignment, type, right);

        if (!type.isLeftValue)
        {
            if (as<ErrorType>(type))
            {
                // Don't report an l-value issue on an erroneous expression
            }
            else
            {
                getSink()->diagnose(expr, Diagnostics::assignNonLValue);

                // As a special case, check if the LHS expression is derived
                // from a `this` parameter (implicitly or explicitly), which
                // is immutable. We can give the user a bit more context into
                // what is going on.
                //
                maybeDiagnoseThisNotLValue(expr->left);
            }
        }
        expr->type = type;
        return expr;
    }

    Expr* SemanticsExprVisitor::visitAssignExpr(AssignExpr* expr)
    {
        expr->left = CheckExpr(expr->left);
        expr->right = CheckTerm(expr->right);

        return checkAssignWithCheckedOperands(expr);
    }

    Expr* SemanticsVisitor::CheckExpr(Expr* uncheckedExpr)
    {
        auto checkedTerm = CheckTerm(uncheckedExpr);

        // First, we want to do any disambiguation that is needed in order
        // to turn the `term` into an expression that names a single
        // value (and not something overloaded).
        //
        auto checkedExpr = maybeResolveOverloadedExpr(checkedTerm, LookupMask::Default, getSink());

        // Next, we want to ensure that the `expr` actually has a type
        // that is allowable in an expression context (e.g., make sure
        // that `expr` names a value and not a type).
        //
        // TODO: Implement this step.

        return checkedExpr;
    }

    static bool _canLValueCoerceScalarType(Type* a, Type* b)
    {
        auto basicTypeA = as<BasicExpressionType>(a);
        auto basicTypeB = as<BasicExpressionType>(b);

        if (basicTypeA && basicTypeB)
        {
            const auto& infoA = BaseTypeInfo::getInfo(basicTypeA->getBaseType());
            const auto& infoB = BaseTypeInfo::getInfo(basicTypeB->getBaseType());

            // TODO(JS): Initially this tries to limit where LValueImplict casts happen.
            // We could in principal allow different sizes, as long as we converted to a temprorary
            // and back again. 
            // 
            // For now we just stick with the simple case. 
            // // We only allow on integer types for now. In effect just allowing any size uint/int conversions
            if (infoA.sizeInBytes == infoB.sizeInBytes && 
                (infoA.flags & infoB.flags & BaseTypeInfo::Flag::Integer))
            {
                return true;
            }

        }
        return false;
    }

    static bool _canLValueCoerce(Type* a, Type* b)
    {
        // We can *assume* here that if they are coercable, that dimensions of vectors
        // and matrices match. We might want to assert to be sure...
        SLANG_ASSERT(a != b);
        if (a->astNodeType == b->astNodeType)
        {
            if (auto matA = as<MatrixExpressionType>(a))
            {
                return _canLValueCoerceScalarType(matA->getElementType(), static_cast<MatrixExpressionType*>(b)->getElementType());   
            }
            else if (auto vecA = as<VectorExpressionType>(a))
            {
                return  _canLValueCoerceScalarType(vecA->getScalarType(), static_cast<VectorExpressionType*>(b)->getScalarType());   
            }
        }
        return _canLValueCoerceScalarType(a, b);
    }


    void SemanticsVisitor::compareMemoryQualifierOfParamToArgument(
        ParamDecl* paramIn,
        Expr* argIn)
    {
        auto arg = as<VarExpr>(argIn);
        if (!paramIn || !arg)
            return;

        auto argDeclRef = arg->declRef;
        if (!argDeclRef)
            return;
        auto argDecl =  argDeclRef.getDecl();
        auto argMemMods = argDecl->findModifier<MemoryQualifierSetModifier>();
        if(!argMemMods)
            return;
        uint32_t argQualifiers = argMemMods->getMemoryQualifierBit();    

        uint32_t paramQualifiers = 0;
        auto paramMemMods = paramIn->findModifier<MemoryQualifierSetModifier>();
        if(paramMemMods)
            paramQualifiers = paramMemMods->getMemoryQualifierBit();

        if(argQualifiers & MemoryQualifierSetModifier::Flags::kCoherent
            && !(paramQualifiers & MemoryQualifierSetModifier::Flags::kCoherent))
                getSink()->diagnose(arg, Diagnostics::argumentHasMoreMemoryQualifiersThanParam, "coherent");
        if(argQualifiers & MemoryQualifierSetModifier::Flags::kReadOnly
            && !(paramQualifiers & MemoryQualifierSetModifier::Flags::kReadOnly))
                getSink()->diagnose(arg, Diagnostics::argumentHasMoreMemoryQualifiersThanParam, "readonly");
        if(argQualifiers & MemoryQualifierSetModifier::Flags::kWriteOnly
            && !(paramQualifiers & MemoryQualifierSetModifier::Flags::kWriteOnly))
                getSink()->diagnose(arg, Diagnostics::argumentHasMoreMemoryQualifiersThanParam, "writeonly");
        if(argQualifiers & MemoryQualifierSetModifier::Flags::kVolatile
            && !(paramQualifiers & MemoryQualifierSetModifier::Flags::kVolatile))
                getSink()->diagnose(arg, Diagnostics::argumentHasMoreMemoryQualifiersThanParam, "volatile");
        // dropping a `restrict` qualifier from arguments is allowed in GLSL with memory qualifiers
    }

    Expr* SemanticsVisitor::CheckInvokeExprWithCheckedOperands(InvokeExpr *expr)
    {
        auto rs = ResolveInvoke(expr);
        if (auto invoke = as<InvokeExpr>(rs))
        {
            // if this is still an invoke expression, test arguments passed to inout/out parameter are LValues
            if(auto funcType = as<FuncType>(invoke->functionExpr->type))
            {
                if (!funcType->getErrorType()->equals(m_astBuilder->getBottomType()))
                {
                    // If the callee throws, make sure we are inside a try clause.
                    if (m_enclosingTryClauseType == TryClauseType::None)
                    {
                        getSink()->diagnose(invoke, Diagnostics::mustUseTryClauseToCallAThrowFunc);
                    }
                }

                auto funcDeclRefExpr = as<DeclRefExpr>(invoke->functionExpr);
                FunctionDeclBase* funcDeclBase = nullptr;
                if (funcDeclRefExpr)
                    funcDeclBase = as<FunctionDeclBase>(funcDeclRefExpr->declRef.getDecl());

                Index paramCount = funcType->getParamCount();
                for (Index pp = 0; pp < paramCount; ++pp)
                {
                    auto paramType = funcType->getParamType(pp);
                    Expr* argExpr = nullptr;
                    ParamDecl* paramDecl = nullptr;
                    if (pp < expr->arguments.getCount())
                    {
                        argExpr = expr->arguments[pp];
                        if(funcDeclBase)
                            paramDecl = funcDeclBase->getParameters()[pp];
                    }
                    compareMemoryQualifierOfParamToArgument(paramDecl, argExpr);

                    if (as<OutTypeBase>(paramType) || as<RefType>(paramType))
                    {
                        // `out`, `inout`, and `ref` parameters currently require
                        // an *exact* match on the type of the argument.
                        //
                        // TODO: relax this requirement by allowing an argument
                        // for an `inout` parameter to be converted in both
                        // directions.
                        //
                        if( argExpr )
                        {
                            if( !argExpr->type.isLeftValue)
                            {
                                auto implicitCastExpr = as<ImplicitCastExpr>(argExpr);

                                // NOTE: 
                                // This is currently only enabled for in/inout based scenarios. Ie NOT ref.
                                // 
                                // Depending on the target there can be an issue around atomics.
                                // The fall back transformation with InOut/OutImplicitCast is to introduce 
                                // a temporary, and do the work on that and copy back.
                                // 
                                // This doesn't work with an atomic. So the work around is to not enable
                                // the transformation with ref types, which atomics are defined on.
                                // 
                                // An argument can be made that transformation shouldn't apply to the ref scenario in general.
                                if (implicitCastExpr && 
                                    as<OutTypeBase>(paramType) && 
                                    _canLValueCoerce(implicitCastExpr->arguments[0]->type, implicitCastExpr->type))
                                {
                                    // This is to work around issues like
                                    //
                                    // ```
                                    // int a = 0;
                                    // uint b = 1;
                                    // a += b;
                                    // ```
                                    // That strictly speaking it's not allowed, but we are going to allow it for now 
                                    // for situations were the types are uint/int and vector/matrix varieties of those types
                                    // 
                                    // Then in lowering we are going to insert code to do something like
                                    // ```
                                    // var OutType: tmp = arg;
                                    // f(... tmp);
                                    // arg = tmp;
                                    // ```

                                    TypeCastExpr* lValueImplicitCast;

                                    // We want to record if the cast is being used for `out` or `inout`/`ref` as 
                                    // if it's just `out` we won't need to convert before passing in.
                                    if (as<OutType>(paramType))
                                    {
                                        lValueImplicitCast = getASTBuilder()->create<OutImplicitCastExpr>(*implicitCastExpr);
                                    }
                                    else
                                    {
                                        lValueImplicitCast = getASTBuilder()->create<InOutImplicitCastExpr>(*implicitCastExpr);
                                    }

                                    // Replace the expression. This should make this situation easier to detect.
                                    expr->arguments[pp] = lValueImplicitCast;
                                }
                                else if (!as<ErrorType>(argExpr->type))
                                {
                                    getSink()->diagnose(
                                        argExpr,
                                        Diagnostics::argumentExpectedLValue,
                                        pp);

                                    
                                    if(implicitCastExpr)
                                    {
                                        const DiagnosticInfo* diagnostic = nullptr;

                                        // Try and determine reason for failure
                                        if (as<RefType>(paramType))
                                        {
                                            // Ref types are not allowed to use this mechanism because it breaks atomics 
                                            diagnostic = &Diagnostics::implicitCastUsedAsLValueRef;
                                        }
                                        else if (!_canLValueCoerce(implicitCastExpr->arguments[0]->type, implicitCastExpr->type))
                                        {
                                            // We restict what types can use this mechanism - currently int/uint and same sized matrix/vectors
                                            // of those types.
                                            diagnostic = &Diagnostics::implicitCastUsedAsLValueType;
                                        }
                                        else
                                        {
                                            // Fall back, in case there are other reasons...
                                            diagnostic = &Diagnostics::implicitCastUsedAsLValue;
                                        }
                                        getSink()->diagnoseWithoutSourceView(
                                            argExpr,
                                            *diagnostic,
                                            implicitCastExpr->arguments[0]->type,
                                            implicitCastExpr->type);
                                    }

                                    maybeDiagnoseThisNotLValue(argExpr);
                                }
                            }
                        }
                        else
                        {
                            // There are two ways we could get here, both involving
                            // a call where the number of argument expressions is
                            // less than the number of parameters on the callee:
                            //
                            // 1. There might be fewer arguments than parameters
                            // because the trailing parameters should be defaulted
                            //
                            // 2. There might be fewer arguments than parameters
                            // because the call is incorrect.
                            //
                            // In case (2) an error would have already been diagnosed,
                            // and we don't want to emit another cascading error here.
                            //
                            // In case (1) this implies the user declared an `out`
                            // or `inout` parameter with a default argument expression.
                            // That should be an error, but it should be detected
                            // on the declaration instead of here at the use site.
                            //
                            // Thus, it makes sense to ignore this case here.
                        }
                    }
                }

                if (auto higherOrderInvoke = as<DifferentiateExpr>(invoke->functionExpr))
                {
                    FunctionDifferentiableLevel requiredLevel;
                    if (auto funcDeclExpr = as<DeclRefExpr>(
                            getInnerMostExprFromHigherOrderExpr(higherOrderInvoke, requiredLevel)))
                    {
                        auto funcDecl = as<FunctionDeclBase>(funcDeclExpr->declRef.getDecl());
                        if (funcDecl)
                        {
                            if (requiredLevel == FunctionDifferentiableLevel::Forward &&
                                !getShared()->isDifferentiableFunc(funcDecl))
                            {
                                getSink()->diagnose(funcDeclExpr, Diagnostics::functionNotMarkedAsDifferentiable, funcDecl, "forward");
                            }
                            if (requiredLevel == FunctionDifferentiableLevel::Backward &&
                                !getShared()->isBackwardDifferentiableFunc(funcDecl))
                            {
                                getSink()->diagnose(funcDeclExpr, Diagnostics::functionNotMarkedAsDifferentiable, funcDecl, "backward");
                            }
                            if (!isEffectivelyStatic(funcDecl) && !isGlobalDecl(funcDecl))
                            {
                                getSink()->diagnose(invoke->functionExpr, Diagnostics::nonStaticMemberFunctionNotAllowedAsDiffOperand, funcDecl);
                            }
                        }
                    }
                }
            }
        }
        return rs;
    }


    Expr* SemanticsExprVisitor::visitSelectExpr(SelectExpr* expr)
    {
        auto result = visitInvokeExpr(expr);
        if (as<ErrorType>(result->type.type))
            return result;
        auto invokeExpr = as<InvokeExpr>(result);
        if (!result)
            return result;
        if (invokeExpr->arguments.getCount() != 3)
            return result;

        if (as<BasicExpressionType>(invokeExpr->arguments[0]->type.type))
        {
            auto newArgs = invokeExpr->arguments;
            expr->arguments.clear();
            expr->arguments = newArgs;
            expr->type = invokeExpr->type;
            return expr;
        }

        if (getParentDifferentiableAttribute())
        {
            // If we are in a differentiable func, issue
            // a diagnostic on use of non short-circuiting select.
            getSink()->diagnose(expr->loc, Diagnostics::useOfNonShortCircuitingOperatorInDiffFunc);
        }
        else
        {
            // For all other functions, we issue a warning for deprecation of vector-typed ?: operator.
            getSink()->diagnose(expr->loc, Diagnostics::useOfNonShortCircuitingOperator);
        }
        return result;
    }

    Expr* SemanticsExprVisitor::convertToLogicOperatorExpr(InvokeExpr* expr)
    {
        LogicOperatorShortCircuitExpr* newExpr = nullptr;

        // If the logic expression is inside the generic parameter list, it cannot support short-circuit
        // which will generate the ifelse branch.
        if (!m_shouldShortCircuitLogicExpr)
        {
            return nullptr;
        }

        if (auto varExpr = as<VarExpr>(expr->functionExpr))
        {
            if ((varExpr->name->text == "&&") || (varExpr->name->text == "||"))
            {
                // We only use short-circuiting in scalar input, will fall back
                // to non-short-circuiting in vector input.
                bool shortCircuitSupport = true;
                for (auto & arg : expr->arguments)
                {
                    if(!as<BasicExpressionType>(arg->type.type))
                    {
                        shortCircuitSupport = false;
                    }
                }

                if (!shortCircuitSupport)
                {
                    return nullptr;
                }

                // We do the cast in the 2nd pass because we want to leave it for 'visitInvokeExpr'
                // to handle if this expression doesn't support short-circuiting.
                for (auto & arg : expr->arguments)
                {
                    arg = coerce(CoercionSite::Argument, m_astBuilder->getBoolType(), arg);
                }

                expr->functionExpr = CheckTerm(expr->functionExpr);
                newExpr = m_astBuilder->create<LogicOperatorShortCircuitExpr>();
                if (varExpr->name->text == "&&")
                {
                   newExpr->flavor = LogicOperatorShortCircuitExpr::Flavor::And;
                }
                else
                {
                   newExpr->flavor = LogicOperatorShortCircuitExpr::Flavor::Or;
                }
                newExpr->loc = expr->loc;
                newExpr->functionExpr = expr->functionExpr;
                newExpr->type = m_astBuilder->getBoolType();
                newExpr->arguments = expr->arguments;
            }
        }

        return newExpr;
    }

    Expr* SemanticsExprVisitor::visitInvokeExpr(InvokeExpr* expr)
    {
        // check the base expression first
        if (!expr->originalFunctionExpr)
            expr->originalFunctionExpr = expr->functionExpr;
        auto treatAsDifferentiableExpr = m_treatAsDifferentiableExpr;
        m_treatAsDifferentiableExpr = nullptr;
        // Next check the argument expressions
        for (auto & arg : expr->arguments)
        {
            arg = CheckTerm(arg);
        }

        // if the expression is '&&' or '||', we will convert it
        // to use short-circuit evaluation.
        if (auto newExpr = convertToLogicOperatorExpr(expr))
            return newExpr;

        expr->functionExpr = CheckTerm(expr->functionExpr);
        m_treatAsDifferentiableExpr = treatAsDifferentiableExpr;

        // If we are in a differentiable function, register differential witness tables involved in
        // this call.
        if (m_parentFunc && m_parentFunc->hasModifier<DifferentiableAttribute>())
        {
            for (auto& arg : expr->arguments)
            {
                maybeRegisterDifferentiableType(m_astBuilder, arg->type.type);
            }
        }

        auto checkedExpr = CheckInvokeExprWithCheckedOperands(expr);

        if (m_parentDifferentiableAttr)
        {
            FunctionDifferentiableLevel callerDiffLevel = FunctionDifferentiableLevel::None;
            if (m_parentFunc)
                callerDiffLevel = getShared()->getFuncDifferentiableLevel(m_parentFunc);

            if (auto checkedInvokeExpr = as<InvokeExpr>(checkedExpr))
            {
                // Register types for final resolved invoke arguments again.
                for (auto& arg : expr->arguments)
                {
                    maybeRegisterDifferentiableType(m_astBuilder, arg->type.type);
                }

                if (auto calleeExpr = as<DeclRefExpr>(checkedInvokeExpr->functionExpr))
                {
                    if (auto calleeDecl = as<FunctionDeclBase>(calleeExpr->declRef.getDecl()))
                    {
                        auto calleeDiffLevel = getShared()->getFuncDifferentiableLevel(calleeDecl);
                        if (calleeDiffLevel >= callerDiffLevel)
                        {
                            if (!m_treatAsDifferentiableExpr)
                            {
                                auto newFuncExpr =
                                    getASTBuilder()->create<TreatAsDifferentiableExpr>();
                                newFuncExpr->type = checkedInvokeExpr->type;
                                newFuncExpr->innerExpr = checkedInvokeExpr;
                                newFuncExpr->loc = checkedInvokeExpr->loc;
                                newFuncExpr->flavor = TreatAsDifferentiableExpr::Flavor::Differentiable;
                                checkedExpr = newFuncExpr;
                            }
                            else
                            {
                                getSink()->diagnose(
                                    m_treatAsDifferentiableExpr,
                                    Diagnostics::useOfNoDiffOnDifferentiableFunc);
                            }
                        }
                    }
                }
            }
            maybeRegisterDifferentiableType(m_astBuilder, checkedExpr->type.type);
        }
        return checkedExpr;
    }

    Expr* SemanticsExprVisitor::visitVarExpr(VarExpr *expr)
    {
        // If we've already resolved this expression, don't try again.
        if (expr->declRef)
        {
            if (!expr->type)
                expr->type = GetTypeForDeclRef(expr->declRef, expr->loc);
            return expr;
        }
        expr->type = QualType(m_astBuilder->getErrorType());
        auto lookupResult = lookUp(
            m_astBuilder, this, expr->name, expr->scope, LookupMask::Default, false, getDeclToExcludeFromLookup());
        
        bool diagnosed = false;
        lookupResult = filterLookupResultByVisibilityAndDiagnose(lookupResult, expr->loc, diagnosed);

        if (expr->name == getSession()->getCompletionRequestTokenName())
        {
            auto scopeKind = CompletionSuggestions::ScopeKind::Expr;
            if (!m_parentFunc)
                scopeKind = CompletionSuggestions::ScopeKind::Decl;
            suggestCompletionItems(scopeKind, lookupResult);
            return expr;
        }

        if (lookupResult.isValid())
        {
            return createLookupResultExpr(
                expr->name,
                lookupResult,
                nullptr,
                expr->loc,
                expr);
        }

        if (!diagnosed)
            getSink()->diagnose(expr, Diagnostics::undefinedIdentifier2, expr->name);

        return expr;
    }

    Type* SemanticsVisitor::_toDifferentialParamType(Type* primalType)
    {
        // Check for type modifiers like 'out' and 'inout'. We need to differentiate the
        // nested type.
        //
        if (auto primalOutType = as<OutType>(primalType))
        {
            return m_astBuilder->getOutType(_toDifferentialParamType(primalOutType->getValueType()));
        }
        else if (auto primalInOutType = as<InOutType>(primalType))
        {
            return m_astBuilder->getInOutType(_toDifferentialParamType(primalInOutType->getValueType()));
        }
        return getDifferentialPairType(primalType);
    }

    Type* SemanticsVisitor::getDifferentialPairType(Type* primalType)
    {
        if (auto modifiedType = as<ModifiedType>(primalType))
        {
            if (modifiedType->findModifier<NoDiffModifierVal>())
                return modifiedType->getBase();
        }

        // Get a reference to the builtin 'IDifferentiable' interface
        auto differentiableInterface = getASTBuilder()->getDifferentiableInterfaceType();

        auto conformanceWitness = as<Witness>(isSubtype(primalType, differentiableInterface));
        // Check if the provided type inherits from IDifferentiable.
        // If not, return the original type.
        if (conformanceWitness)
        {
            return m_astBuilder->getDifferentialPairType(primalType, conformanceWitness);
        }
        else
            return primalType;
    }

    Type* SemanticsVisitor::getForwardDiffFuncType(FuncType* originalType)
    {
        // Resolve JVP type here. 
        // Note that this type checking needs to be in sync with
        // the auto-generation logic in slang-ir-jvp-diff.cpp
        List<Type*> paramTypes;

        // The JVP return type is float if primal return type is float
        // void otherwise.
        //
        auto resultType = getDifferentialPairType(originalType->getResultType());
        
        // No support for differentiating function that throw errors, for now.
        SLANG_ASSERT(originalType->getErrorType()->equals(m_astBuilder->getBottomType()));
        auto errorType = originalType->getErrorType();

        for (Index i = 0; i < originalType->getParamCount(); i++)
        {
            if(auto jvpParamType = _toDifferentialParamType(originalType->getParamType(i)))
                paramTypes.add(jvpParamType);
        }
        FuncType* jvpType = m_astBuilder->getOrCreate<FuncType>(paramTypes.getArrayView(), resultType, errorType);

        return jvpType;
    }

    Type* SemanticsVisitor::getBackwardDiffFuncType(FuncType* originalType)
    {
        // Resolve backward diff type here. 
        // Note that this type checking needs to be in sync with
        // the auto-generation logic in slang-ir-jvp-diff.cpp
        List<Type*> paramTypes;

        // The backward diff return type is void
        //
        auto resultType = m_astBuilder->getVoidType();

        // No support for differentiating function that throw errors, for now.
        SLANG_ASSERT(originalType->getErrorType()->equals(m_astBuilder->getBottomType()));
        auto errorType = originalType->getErrorType();

        for (Index i = 0; i < originalType->getParamCount(); i++)
        {
            if (auto outType = as<OutType>(originalType->getParamType(i)))
            {
                auto diffElementType =
                    tryGetDifferentialType(m_astBuilder, outType->getValueType());
                if (diffElementType)
                {
                    paramTypes.add(diffElementType);
                }
                else
                {
                    continue;
                }
            }
            else if (auto derivType = _toDifferentialParamType(originalType->getParamType(i)))
            {
                if (as<DifferentialPairType>(derivType))
                {
                    // An `in` differentiable parameter becomes an `inout` parameter.
                    derivType = m_astBuilder->getInOutType(derivType);
                }
                else if (auto inoutType = as<InOutType>(derivType))
                {
                    if (!as<DifferentialPairType>(inoutType->getValueType()))
                    {
                        // An `inout` non differentiable parameter becomes an `in` parameter
                        // (removing `out`).
                        derivType = inoutType->getValueType();
                    }
                }
                paramTypes.add(derivType);
            }
        }
        
        // Last parameter is the initial derivative of the original return type
        auto dOutType = tryGetDifferentialType(m_astBuilder, originalType->getResultType());
        if (dOutType)
            paramTypes.add(dOutType);

        return m_astBuilder->getOrCreate<FuncType>(paramTypes.getArrayView(), resultType, errorType);
    }

    struct HigherOrderInvokeExprCheckingActions
    {
        virtual HigherOrderInvokeExpr* createHigherOrderInvokeExpr(SemanticsVisitor* semantics) = 0;
        virtual void fillHigherOrderInvokeExpr(HigherOrderInvokeExpr* resultDiffExpr, SemanticsVisitor* semantics, Expr* funcExpr) = 0;
        FuncType* getBaseFunctionType(SemanticsVisitor* semantics, Expr* funcExpr)
        {
            if (auto funcType = as<FuncType>(funcExpr->type.type))
                return funcType;
            auto astBuilder = semantics->getASTBuilder();
            if (auto declRefExpr = as<DeclRefExpr>(funcExpr))
            {
                if (auto baseFuncGenericDeclRef = declRefExpr->declRef.as<GenericDecl>())
                {
                    // Get inner function
                    DeclRef<Decl> unspecializedInnerRef = createDefaultSubstitutionsIfNeeded(astBuilder, semantics,
                        astBuilder->getMemberDeclRef(baseFuncGenericDeclRef, getInner(baseFuncGenericDeclRef)));
                    auto callableDeclRef = unspecializedInnerRef.as<CallableDecl>();
                    if (!callableDeclRef)
                        return nullptr;
                    auto funcType = getFuncType(astBuilder, callableDeclRef);
                    return funcType;
                }
            }
            return nullptr;
        }
    };

    struct ForwardDifferentiateExprCheckingActions : HigherOrderInvokeExprCheckingActions
    {
        virtual HigherOrderInvokeExpr* createHigherOrderInvokeExpr(SemanticsVisitor* semantics) override
        {
            return semantics->getASTBuilder()->create<ForwardDifferentiateExpr>();
        }
        void fillHigherOrderInvokeExpr(HigherOrderInvokeExpr* resultDiffExpr, SemanticsVisitor* semantics, Expr* funcExpr) override
        {
            resultDiffExpr->baseFunction = funcExpr;
            auto baseFuncType = getBaseFunctionType(semantics, funcExpr);
            if (!baseFuncType)
            {
                resultDiffExpr->type = semantics->getASTBuilder()->getErrorType();
                semantics->getSink()->diagnose(funcExpr, Diagnostics::expectedFunction, funcExpr->type.type);
                return;
            }
            resultDiffExpr->type = semantics->getForwardDiffFuncType(baseFuncType);
            if (auto declRefExpr = as<DeclRefExpr>(getInnerMostExprFromHigherOrderExpr(funcExpr)))
            {
                auto funcDecl = declRefExpr->declRef.as<CallableDecl>().getDecl();
                if (auto genDecl = as<GenericDecl>(declRefExpr->declRef.getDecl()))
                {
                    funcDecl = as<CallableDecl>(genDecl->inner);
                }
                if (funcDecl)
                {
                    for (auto param : funcDecl->getParameters())
                    {
                        resultDiffExpr->newParameterNames.add(param->getName());
                    }
                }
            }
        }
    };

    struct BackwardDifferentiateExprCheckingActions : HigherOrderInvokeExprCheckingActions
    {
        virtual HigherOrderInvokeExpr* createHigherOrderInvokeExpr(SemanticsVisitor* semantics) override
        {
            return semantics->getASTBuilder()->create<BackwardDifferentiateExpr>();
        }
        void fillHigherOrderInvokeExpr(HigherOrderInvokeExpr* resultDiffExpr, SemanticsVisitor* semantics, Expr* funcExpr) override
        {
            resultDiffExpr->baseFunction = funcExpr;
            auto baseFuncType = getBaseFunctionType(semantics, funcExpr);
            if (!baseFuncType)
            {
                resultDiffExpr->type = semantics->getASTBuilder()->getErrorType();
                semantics->getSink()->diagnose(funcExpr, Diagnostics::expectedFunction, funcExpr->type.type);
                return;
            }
            resultDiffExpr->type = semantics->getBackwardDiffFuncType(baseFuncType);
            if (auto declRefExpr = as<DeclRefExpr>(getInnerMostExprFromHigherOrderExpr(funcExpr)))
            {
                auto funcDecl = declRefExpr->declRef.as<CallableDecl>().getDecl();
                if (auto genDecl = as<GenericDecl>(declRefExpr->declRef.getDecl()))
                {
                    funcDecl = as<CallableDecl>(genDecl->inner);
                }
                if (funcDecl)
                {
                    for (auto param : funcDecl->getParameters())
                    {
                        if (param->findModifier<NoDiffModifier>())
                        {
                            if (param->findModifier<OutModifier>() &&
                                !param->findModifier<InModifier>() &&
                                !param->findModifier<InOutModifier>())
                                continue;
                        }
                        resultDiffExpr->newParameterNames.add(param->getName());
                    }
                    resultDiffExpr->newParameterNames.add(semantics->getName("resultGradient"));
                }
            }
        }
    };

    template<typename ExprASTType>
    struct PassthroughHighOrderExprCheckingActionsBase : HigherOrderInvokeExprCheckingActions
    {
        virtual HigherOrderInvokeExpr* createHigherOrderInvokeExpr(SemanticsVisitor* semantics) override
        {
            return semantics->getASTBuilder()->create<ExprASTType>();
        }
        void fillHigherOrderInvokeExpr(HigherOrderInvokeExpr* resultDiffExpr, SemanticsVisitor* semantics, Expr* funcExpr) override
        {
            resultDiffExpr->baseFunction = funcExpr;
            auto baseFuncType = getBaseFunctionType(semantics, funcExpr);
            if (!baseFuncType)
            {
                resultDiffExpr->type = semantics->getASTBuilder()->getErrorType();
                semantics->getSink()->diagnose(funcExpr, Diagnostics::expectedFunction, funcExpr->type.type);
                return;
            }
            resultDiffExpr->type = baseFuncType;
            if (auto declRefExpr = as<DeclRefExpr>(getInnerMostExprFromHigherOrderExpr(funcExpr)))
            {
                auto funcDecl = declRefExpr->declRef.as<CallableDecl>().getDecl();
                if (auto genDecl = as<GenericDecl>(declRefExpr->declRef.getDecl()))
                {
                    funcDecl = as<CallableDecl>(genDecl->inner);
                }
                if (funcDecl)
                {
                    for (auto param : funcDecl->getParameters())
                    {
                        resultDiffExpr->newParameterNames.add(param->getName());
                    }
                }
            }
        }
    };

    static Expr* _checkHigherOrderInvokeExpr(
        SemanticsVisitor* semantics,
        HigherOrderInvokeExpr* expr,
        HigherOrderInvokeExprCheckingActions* actions)
    {
        // Check/Resolve inner function declaration.
        expr->baseFunction = semantics->CheckTerm(expr->baseFunction);

        auto astBuilder = semantics->getASTBuilder();

        // If base is overloaded expr, we want to return an overloaded expr as check result.
        // This is done by pushing the `differentiate` operator to each item in the overloaded expr.
        if (auto overloadedExpr = as<OverloadedExpr>(expr->baseFunction))
        {
            OverloadedExpr2* result = astBuilder->create<OverloadedExpr2>();
            for (auto item : overloadedExpr->lookupResult2)
            {
                auto lookupResultExpr = semantics->ConstructLookupResultExpr(item,
                    nullptr,
                    overloadedExpr->loc,
                    nullptr);
                auto candidateExpr = actions->createHigherOrderInvokeExpr(semantics);
                actions->fillHigherOrderInvokeExpr(candidateExpr, semantics, lookupResultExpr);
                candidateExpr->loc = expr->loc;
                result->candidiateExprs.add(candidateExpr);
            }
            result->type.type = astBuilder->getOverloadedType();
            result->loc = expr->loc;
            return result;
        }
        else if (auto overloadedExpr2 = as<OverloadedExpr2>(expr->baseFunction))
        {
            OverloadedExpr2* result = astBuilder->create<OverloadedExpr2>();
            for (auto item : overloadedExpr2->candidiateExprs)
            {
                auto candidateExpr = actions->createHigherOrderInvokeExpr(semantics);
                actions->fillHigherOrderInvokeExpr(candidateExpr, semantics, item);
                candidateExpr->loc = expr->loc;
                result->candidiateExprs.add(candidateExpr);
            }
            result->type.type = astBuilder->getOverloadedType();
            result->loc = expr->loc;
            return result;
        }

        actions->fillHigherOrderInvokeExpr(expr, semantics, expr->baseFunction);
        return expr;
    }

    Expr* SemanticsExprVisitor::visitForwardDifferentiateExpr(ForwardDifferentiateExpr* expr)
    {
        ForwardDifferentiateExprCheckingActions actions;
        return _checkHigherOrderInvokeExpr(this, expr, &actions);
    }

    Expr* SemanticsExprVisitor::visitBackwardDifferentiateExpr(BackwardDifferentiateExpr* expr)
    {
        BackwardDifferentiateExprCheckingActions actions;
        return _checkHigherOrderInvokeExpr(this, expr, &actions);
    }

    Expr* SemanticsExprVisitor::visitPrimalSubstituteExpr(PrimalSubstituteExpr* expr)
    {
        PassthroughHighOrderExprCheckingActionsBase<PrimalSubstituteExpr> actions;
        return _checkHigherOrderInvokeExpr(this, expr, &actions);
    }

    Expr* SemanticsExprVisitor::visitDispatchKernelExpr(DispatchKernelExpr* expr)
    {
        auto isInt3Type = [this](Type* type)
        {
            auto vectorType = as<VectorExpressionType>(type);
            if (!vectorType)
                return false;
            if (!isIntegerBaseType(getVectorBaseType(vectorType)))
                return false;
            auto constElementCount = as<ConstantIntVal>(vectorType->getElementCount());
            if (!constElementCount)
                return false;
            return constElementCount->getValue() == 3;
        };
        expr->threadGroupSize = dispatchExpr(expr->threadGroupSize, *this);
        if (!isInt3Type(expr->threadGroupSize->type.type))
        {
            getSink()->diagnose(
                expr->threadGroupSize,
                Diagnostics::typeMismatch,
                "uint3",
                expr->threadGroupSize->type);
        }
        expr->dispatchSize = dispatchExpr(expr->dispatchSize, *this);
        if (!isInt3Type(expr->dispatchSize->type.type))
        {
            getSink()->diagnose(
                expr->dispatchSize,
                Diagnostics::typeMismatch,
                "uint3",
                expr->dispatchSize->type);
        }
        PassthroughHighOrderExprCheckingActionsBase<DispatchKernelExpr> actions;
        return _checkHigherOrderInvokeExpr(this, expr, &actions);
    }

    Expr* SemanticsExprVisitor::visitTreatAsDifferentiableExpr(TreatAsDifferentiableExpr* expr)
    {
        auto subContext = withTreatAsDifferentiable(expr);
        expr->innerExpr = dispatchExpr(expr->innerExpr, subContext);
        expr->type = expr->innerExpr->type;
        auto innerExpr = expr->innerExpr;
        while (auto parenExpr = as<ParenExpr>(innerExpr))
        {
            innerExpr = parenExpr->base;
        }
        if (!as<InvokeExpr>(innerExpr) && !as<IndexExpr>(innerExpr))
        {
            getSink()->diagnose(expr, Diagnostics::invalidUseOfNoDiff);
        }
        else if (!m_parentDifferentiableAttr)
        {
            getSink()->diagnose(expr, Diagnostics::cannotUseNoDiffInNonDifferentiableFunc);
        }
        return expr;
    }

    Expr* SemanticsExprVisitor::visitGetArrayLengthExpr(GetArrayLengthExpr* expr)
    {
        expr->arrayExpr = CheckTerm(expr->arrayExpr);
        if (auto arrType = as<ArrayExpressionType>(expr->arrayExpr->type))
        {
            expr->type = m_astBuilder->getIntType();
            if (arrType->isUnsized())
            {
                getSink()->diagnose(expr, Diagnostics::invalidArraySize);
            }
        }
        else
        {
            if (!as<ErrorType>(expr->arrayExpr->type))
            {
                getSink()->diagnose(
                    expr, Diagnostics::typeMismatch, "array", expr->arrayExpr->type);
            }
            expr->type = m_astBuilder->getErrorType();
        }
        return expr;
    }

    static bool _isSizeOfType(Type* type)
    {
        if (!type)
        {
            return false;
        }

        if (as<ArithmeticExpressionType>(type) ||
            as<ArrayExpressionType>(type) ||
            as<PtrTypeBase>(type) ||
            as<TupleType>(type) ||
            as<GenericDeclRefType>(type))
        {
            return true;
        }

        if (as<DeclRefType>(type))
        {
            return true;
        }
        
        return false;
    }

    Expr* SemanticsExprVisitor::visitSizeOfLikeExpr(SizeOfLikeExpr* sizeOfLikeExpr)
    {
        auto valueExpr = dispatch(sizeOfLikeExpr->value);
        
        Type* type = nullptr;

        if (as<TypeType>(valueExpr->type))
        {
            TypeExp typeExp;
            typeExp.exp = valueExpr;

            auto properTypeExpr = CoerceToProperType(typeExp);

            type = properTypeExpr.type;
        }
        else
        {
            // Is this a proper type?
            TypeExp typeExp(valueExpr->type);
            TypeExp properType = tryCoerceToProperType(typeExp);

            type = properType.type;
        }

        if (!_isSizeOfType(type))
        {
            getSink()->diagnose(sizeOfLikeExpr, Diagnostics::sizeOfArgumentIsInvalid);

            sizeOfLikeExpr->type = m_astBuilder->getErrorType();
            return sizeOfLikeExpr;
        }

        sizeOfLikeExpr->sizedType = type;

        return sizeOfLikeExpr;
    }

    Expr* SemanticsExprVisitor::visitTypeCastExpr(TypeCastExpr * expr)
    {
        if (expr->type)
            return expr;

        // Check the term we are applying first
        auto funcExpr = expr->functionExpr;
        funcExpr = CheckTerm(funcExpr);

        // Now ensure that the term represents a (proper) type.
        TypeExp typeExp;
        typeExp.exp = funcExpr;
        typeExp = CheckProperType(typeExp);

        expr->functionExpr = typeExp.exp;
        expr->type.type = typeExp.type;

        // Next check the argument expression (there should be only one)
        for (auto & arg : expr->arguments)
        {
            arg = CheckTerm(arg);
        }

        // LEGACY FEATURE: As a backwards-compatibility feature
        // for HLSL, we will allow for a cast to a `struct` type
        // from a literal zero, with the semantics of default
        // initialization.
        //
        if( auto declRefType = as<DeclRefType>(typeExp.type) )
        {
            if(const auto structDeclRef = as<StructDecl>(declRefType->getDeclRef()))
            {
                if( expr->arguments.getCount() == 1 )
                {
                    auto arg = expr->arguments[0];
                    if( auto intLitArg = as<IntegerLiteralExpr>(arg) )
                    {
                        if(getIntegerLiteralValue(intLitArg->token) == 0)
                        {
                            // At this point we have confirmed that the cast
                            // has the right form, so we want to apply our special case.
                            //
                            // TODO: If/when we allow for user-defined initializer/constructor
                            // definitions we would have to be careful here because it is
                            // possible that the target type has defined an initializer/constructor
                            // that takes a single `int` parmaeter and means to call that instead.
                            //
                            // For now that should be a non-issue, and in a pinch such a user
                            // could use `T(0)` instead of `(T) 0` to get around this special
                            // HLSL legacy feature.

                            // We will type-check code like:
                            //
                            //      MyStruct s = (MyStruct) 0;
                            //
                            // the same as:
                            //
                            //      MyStruct s = {};
                            //
                            // That is, we construct an empty initializer list, and then coerce
                            // that initializer list expression to the desired type (letting
                            // the code for handling initializer lists work out all of the
                            // details of what is/isn't valid). This choice means we get
                            // to benefit from the existing codegen support for initializer
                            // lists, rather than needing the `(MyStruct) 0` idiom to be
                            // special-cased in later stages of the compiler.
                            //
                            // Note: we use an empty initializer list `{}` instead of an
                            // initializer list with a single zero `{0}`, which is semantically
                            // significant if the first field of `MyStruct` had its own
                            // default initializer defined as part of the `struct` definition.
                            // Basically we have chosen to interpret the "cast from zero" syntax
                            // as sugar for default initialization, and *not* specifically
                            // for zero-initialization. That choice could be revisited if
                            // users express displeasure. For now there isn't enough usage
                            // of explicit default initializers for `struct` fields to
                            // make this a major concern (since they aren't supported in HLSL).
                            //
                            InitializerListExpr* initListExpr = m_astBuilder->create<InitializerListExpr>();
                            initListExpr->loc = expr->loc;
                            auto checkedInitListExpr = visitInitializerListExpr(initListExpr);

                            return coerce(CoercionSite::General, typeExp.type, checkedInitListExpr);
                        }
                    }
                }
            }
        }


        // Now process this like any other explicit call (so casts
        // and constructor calls are semantically equivalent).
        return CheckInvokeExprWithCheckedOperands(expr);
    }

    Expr* SemanticsExprVisitor::visitTryExpr(TryExpr* expr)
    {
        auto prevTryClauseType = m_enclosingTryClauseType;
        m_enclosingTryClauseType = expr->tryClauseType;
        expr->base = CheckTerm(expr->base);
        m_enclosingTryClauseType = prevTryClauseType;
        expr->type = expr->base->type;
        if (as<ErrorType>(expr->type))
            return expr;
        
        auto parentFunc = this->m_parentFunc;
        // TODO: check if the try clause is caught.
        // For now we assume all `try`s are not caught (because we don't have catch yet).
        if (!parentFunc)
        {
            getSink()->diagnose(expr, Diagnostics::uncaughtTryCallInNonThrowFunc);
            return expr;
        }
        if (parentFunc->errorType->equals(m_astBuilder->getBottomType()))
        {
            getSink()->diagnose(expr, Diagnostics::uncaughtTryCallInNonThrowFunc);
            return expr;
        }
        if (!as<InvokeExpr>(expr->base))
        {
            getSink()->diagnose(expr, Diagnostics::tryClauseMustApplyToInvokeExpr);
            return expr;
        }
        auto base = as<InvokeExpr>(expr->base);
        if (auto callee = as<DeclRefExpr>(base->functionExpr))
        {
            if (auto funcCallee = as<FuncDecl>(callee->declRef.getDecl()))
            {
                if (funcCallee->errorType->equals(m_astBuilder->getBottomType()))
                {
                    getSink()->diagnose(expr, Diagnostics::tryInvokeCalleeShouldThrow, callee->declRef);
                }
                if (!parentFunc->errorType->equals(funcCallee->errorType))
                {
                    getSink()->diagnose(
                        expr,
                        Diagnostics::errorTypeOfCalleeIncompatibleWithCaller,
                        callee->declRef,
                        funcCallee->errorType,
                        parentFunc->errorType);
                }
                return expr;
            }
        }
        getSink()->diagnose(expr, Diagnostics::calleeOfTryCallMustBeFunc);
        return expr;
    }

    Expr* SemanticsExprVisitor::visitIsTypeExpr(IsTypeExpr* expr)
    {
        expr->typeExpr = CheckProperType(expr->typeExpr);
        auto originalVal = CheckTerm(expr->value);
        expr->type = m_astBuilder->getBoolType();
        expr->value = originalVal;

        auto valueType = expr->value->type.type;
        if (auto typeType = as<TypeType>(valueType))
            valueType = typeType->getType();

        // If value is a subtype of `type`, then this expr is always true.
        if(isSubtype(valueType, expr->typeExpr.type))
        {
            // Instead of returning a BoolLiteralExpr, we use a field to indicate this scenario,
            // so that the language server can still see the original syntax tree.
            expr->constantVal = m_astBuilder->create<BoolLiteralExpr>();
            expr->constantVal->type = m_astBuilder->getBoolType();
            expr->constantVal->value = true;
            expr->constantVal->loc = expr->loc;
            return expr;
        }

        // Otherwise, if the target type is a subtype of value->type, we need to grab the
        // subtype witness for runtime checks.

        expr->value = maybeOpenExistential(originalVal);
        expr->witnessArg = tryGetSubtypeWitness(expr->typeExpr.type, valueType);
        if (expr->witnessArg)
        {
            // For now we can only support the scenario where `expr->value` is an interface type.
            if (!isInterfaceType(originalVal->type))
            {
                getSink()->diagnose(expr, Diagnostics::isOperatorValueMustBeInterfaceType);
            }
            return expr;
        }
        return expr;
    }

    Expr* SemanticsExprVisitor::visitAsTypeExpr(AsTypeExpr* expr)
    {
        TypeExp typeExpr;
        typeExpr.exp = expr->typeExpr;
        typeExpr = CheckProperType(typeExpr);
        expr->value = CheckTerm(expr->value);
        auto optType = m_astBuilder->getOptionalType(typeExpr.type);
        expr->type = optType;

        // If value is a subtype of `type`, then this expr is equivalent to a CastToSuperTypeExpr.
        if (auto witness = tryGetSubtypeWitness(expr->value->type.type, typeExpr.type))
        {
            auto castToSuperType = createCastToSuperTypeExpr(typeExpr.type, expr->value, witness);
            auto makeOptional = m_astBuilder->create<MakeOptionalExpr>();
            makeOptional->loc = expr->loc;
            makeOptional->type = optType;
            makeOptional->value = castToSuperType;
            makeOptional->typeExpr = typeExpr.exp;
            return makeOptional;
        }

        // If target type is an interface type, we will obtain the witness here for
        // runtime casting.
        expr->witnessArg = tryGetSubtypeWitness(typeExpr.type, expr->value->type.type);
        if (expr->witnessArg)
        {
            // For now we can only support the scenario where `expr->value` is an interface type.
            if (!isInterfaceType(expr->value->type.type))
            {
                getSink()->diagnose(expr, Diagnostics::isOperatorValueMustBeInterfaceType);
            }
            expr->value = maybeOpenExistential(expr->value);
            return expr;
        }

        expr->typeExpr = typeExpr.exp;
        return expr;
    }

    Expr* SemanticsVisitor::MaybeDereference(Expr* inExpr)
    {
        Expr* expr = inExpr;
        for (;;)
        {
            auto baseType = expr->type;
            if (auto pointerLikeType = as<PointerLikeType>(baseType))
            {
                auto elementType = QualType(pointerLikeType->getElementType());
                elementType.isLeftValue = baseType.isLeftValue;
                elementType.hasReadOnlyOnTarget = baseType.hasReadOnlyOnTarget;
                elementType.isWriteOnly = baseType.isWriteOnly;

                auto derefExpr = m_astBuilder->create<DerefExpr>();
                derefExpr->base = expr;
                derefExpr->type = elementType;

                expr = derefExpr;
                continue;
            }

            // Default case: just use the expression as-is
            return expr;
        }
    }

    Expr* SemanticsVisitor::CheckMatrixSwizzleExpr(
        MemberExpr* memberRefExpr,
        Type*      baseElementType,
        IntegerLiteralValue baseElementRowCount,
        IntegerLiteralValue baseElementColCount)
    {
        MatrixSwizzleExpr* swizExpr = m_astBuilder->create<MatrixSwizzleExpr>();
        swizExpr->loc = memberRefExpr->loc;
        swizExpr->base = memberRefExpr->baseExpression;
        swizExpr->memberOpLoc = memberRefExpr->memberOperatorLoc;

        // We can have up to 4 swizzles of two elements each
        MatrixCoord elementCoords[4];
        int elementCount = 0;

        bool anyDuplicates = false;
        int zeroIndexOffset = -1;

        if (memberRefExpr->name == getSession()->getCompletionRequestTokenName())
        {
            auto& suggestions = getLinkage()->contentAssistInfo.completionSuggestions;
            suggestions.clear();
            suggestions.scopeKind = CompletionSuggestions::ScopeKind::Swizzle;
            suggestions.swizzleBaseType =
                memberRefExpr->baseExpression ? memberRefExpr->baseExpression->type : nullptr;
            suggestions.elementCount[0] = baseElementRowCount;
            suggestions.elementCount[1] = baseElementColCount;
        }

        String swizzleText = getText(memberRefExpr->name);
        auto cursor = swizzleText.begin();

        // The contents of the string are 0-terminated
        // Every update to cursor corresponds to a check against 0-termination
        while (*cursor)
        {
            // Throw out swizzling with more than 4 output elements
            if (elementCount >= 4)
            {
                getSink()->diagnose(swizExpr, Diagnostics::invalidSwizzleExpr, swizzleText, baseElementType->toString());
                return CreateErrorExpr(memberRefExpr);
            }
            MatrixCoord elementCoord = { 0, 0 };

            // Check for the preceding underscore
            if (*cursor++ != '_')
            {
                getSink()->diagnose(swizExpr, Diagnostics::invalidSwizzleExpr, swizzleText, baseElementType->toString());
                return CreateErrorExpr(memberRefExpr);
            }

            // Check for one or zero indexing            
            if (*cursor == 'm')
            {
                // Can't mix one and zero indexing
                if (zeroIndexOffset == 1)
                {
                    getSink()->diagnose(swizExpr, Diagnostics::invalidSwizzleExpr, swizzleText, baseElementType->toString());
                    return CreateErrorExpr(memberRefExpr);
                }
                zeroIndexOffset = 0;
                // Increment the index since we saw 'm'
                cursor++;
            }
            else
            {
                // Can't mix one and zero indexing
                if (zeroIndexOffset == 0)
                {
                    getSink()->diagnose(swizExpr, Diagnostics::invalidSwizzleExpr, swizzleText, baseElementType->toString());
                    return CreateErrorExpr(memberRefExpr);
                }
                zeroIndexOffset = 1;
            }

            // Check for the ij components
            for (Index j = 0; j < 2; j++)
            {
                auto ch = *cursor++;
                
                if (ch < '0' || ch > '4')
                {
                    // An invalid character in the swizzle is an error
                    getSink()->diagnose(swizExpr, Diagnostics::invalidSwizzleExpr, swizzleText, baseElementType->toString());
                    return CreateErrorExpr(memberRefExpr);
                }
                const int subIndex = ch - '0' - zeroIndexOffset;

                // Check the limit for either the row or column, depending on the step
                IntegerLiteralValue elementLimit;
                if (j == 0)
                {
                    elementLimit = baseElementRowCount;
                    elementCoord.row = subIndex;
                }
                else
                {
                    elementLimit = baseElementColCount;
                    elementCoord.col = subIndex;
                }
                // Make sure the index is in range for the source type
                // Account for off-by-one and reject 0 if oneIndexed
                if (subIndex >= elementLimit || subIndex < 0)
                {
                    getSink()->diagnose(swizExpr, Diagnostics::invalidSwizzleExpr, swizzleText, baseElementType->toString());
                    return CreateErrorExpr(memberRefExpr);
                }
            }
            // Check if we've seen this index before
            for (int ee = 0; ee < elementCount; ee++)
            {
                if (elementCoords[ee] == elementCoord)
                    anyDuplicates = true;
            }

            // add to our list...
            elementCoords[elementCount] = elementCoord;
            elementCount++;
        }

        // Store our list in the actual AST node
        for (int ee = 0; ee < elementCount; ++ee)
        {
            swizExpr->elementCoords[ee] = elementCoords[ee];
        }
        swizExpr->elementCount = elementCount;

        if (elementCount == 1)
        {
            // single-component swizzle produces a scalar
            //
            // Note(tfoley): the official HLSL rules seem to be that it produces
            // a one-component vector, which is then implicitly convertible to
            // a scalar, but that seems like it just adds complexity.
            swizExpr->type = QualType(baseElementType);
        }
        else
        {
            // TODO(tfoley): would be nice to "re-sugar" type
            // here if the input type had a sugared name...
            swizExpr->type = QualType(createVectorType(
                baseElementType,
                m_astBuilder->getIntVal(m_astBuilder->getIntType(), elementCount)));
        }

        // A swizzle can be used as an l-value as long as there
        // were no duplicates in the list of components
        swizExpr->type.isLeftValue = !anyDuplicates;

        return swizExpr;
    }

    Expr* SemanticsVisitor::CheckMatrixSwizzleExpr(
        MemberExpr* memberRefExpr,
        Type*		baseElementType,
        IntVal*				baseRowCount,
        IntVal*				baseColCount)
    {
        if (auto constantRowCount = as<ConstantIntVal>(baseRowCount))
        {
            if (auto constantColCount = as<ConstantIntVal>(baseColCount))
            {
                return CheckMatrixSwizzleExpr(memberRefExpr, baseElementType,
                    constantRowCount->getValue(), constantColCount->getValue());
            }
        }
        getSink()->diagnose(memberRefExpr, Diagnostics::unimplemented, "swizzle on matrix of unknown size");
        return CreateErrorExpr(memberRefExpr);
    }

    Expr* SemanticsVisitor::CheckSwizzleExpr(
        MemberExpr* memberRefExpr,
        Type*      baseElementType,
        IntegerLiteralValue         baseElementCount)
    {
        SwizzleExpr* swizExpr = m_astBuilder->create<SwizzleExpr>();
        swizExpr->loc = memberRefExpr->loc;
        swizExpr->base = memberRefExpr->baseExpression;
        swizExpr->elementIndices[0] = 0;
        swizExpr->elementIndices[1] = 0;
        swizExpr->elementIndices[2] = 0;
        swizExpr->elementIndices[3] = 0;
        swizExpr->memberOpLoc = memberRefExpr->memberOperatorLoc;
        IntegerLiteralValue limitElement = baseElementCount;

        int elementIndices[4];
        int elementCount = 0;

        bool anyDuplicates = false;
        bool anyError = false;
        if (memberRefExpr->name == getSession()->getCompletionRequestTokenName())
        {
            auto& suggestions = getLinkage()->contentAssistInfo.completionSuggestions;
            suggestions.clear();
            suggestions.scopeKind = CompletionSuggestions::ScopeKind::Swizzle;
            suggestions.swizzleBaseType =
                memberRefExpr->baseExpression ? memberRefExpr->baseExpression->type : nullptr;
            suggestions.elementCount[0] = baseElementCount;
            suggestions.elementCount[1] = 0;
        }
        auto swizzleText = getText(memberRefExpr->name);

        for (Index i = 0; i < swizzleText.getLength(); i++)
        {
            auto ch = swizzleText[i];
            int elementIndex = -1;
            switch (ch)
            {
            case 'x': case 'r': elementIndex = 0; break;
            case 'y': case 'g': elementIndex = 1; break;
            case 'z': case 'b': elementIndex = 2; break;
            case 'w': case 'a': elementIndex = 3; break;
            default:
                // An invalid character in the swizzle is an error
                getSink()->diagnose(swizExpr, Diagnostics::invalidSwizzleExpr, swizzleText, baseElementType->toString());
                anyError = true;
                continue;
            }

            // TODO(tfoley): GLSL requires that all component names
            // come from the same "family"...

            // Make sure the index is in range for the source type
            if (elementIndex >= limitElement)
            {
                getSink()->diagnose(swizExpr, Diagnostics::invalidSwizzleExpr, swizzleText, baseElementType->toString());
                anyError = true;
                continue;
            }

            // Check if we've seen this index before
            for (int ee = 0; ee < elementCount; ee++)
            {
                if (elementIndices[ee] == elementIndex)
                    anyDuplicates = true;
            }

            // add to our list...
            elementIndices[elementCount++] = elementIndex;
        }

        for (int ee = 0; ee < elementCount; ++ee)
        {
            swizExpr->elementIndices[ee] = elementIndices[ee];
        }
        swizExpr->elementCount = elementCount;

        if (anyError)
        {
            return CreateErrorExpr(memberRefExpr);
        }
        else if (elementCount == 1)
        {
            // single-component swizzle produces a scalar
            //
            // Note(tfoley): the official HLSL rules seem to be that it produces
            // a one-component vector, which is then implicitly convertible to
            // a scalar, but that seems like it just adds complexity.
            swizExpr->type = QualType(baseElementType);
        }
        else
        {
            // TODO(tfoley): would be nice to "re-sugar" type
            // here if the input type had a sugared name...
            swizExpr->type = QualType(createVectorType(
                baseElementType,
                m_astBuilder->getIntVal(m_astBuilder->getIntType(), elementCount)));
        }

        // A swizzle can be used as an l-value as long as there
        // were no duplicates in the list of components
        swizExpr->type.isLeftValue = !anyDuplicates &&
            swizExpr->base &&
            swizExpr->base->type &&
            swizExpr->base->type.isLeftValue;

        return swizExpr;
    }

    Expr* SemanticsVisitor::CheckSwizzleExpr(
        MemberExpr*	memberRefExpr,
        Type*		baseElementType,
        IntVal*				baseElementCount)
    {
        if (auto constantElementCount = as<ConstantIntVal>(baseElementCount))
        {
            return CheckSwizzleExpr(memberRefExpr, baseElementType, constantElementCount->getValue());
        }
        else
        {
            getSink()->diagnose(memberRefExpr, Diagnostics::unimplemented, "swizzle on vector of unknown size");
            return CreateErrorExpr(memberRefExpr);
        }
    }

    Expr* SemanticsVisitor::_lookupStaticMember(DeclRefExpr* expr, Expr* baseExpression)
    {
        LookupResult globalLookupResult;
        bool hasErrors = false;
        Expr* base = nullptr;

        // Keep track of namespace scopes we've already looked up in to avoid producing
        // duplicates.
        HashSet<ContainerDecl*> processedNamespaceScopes;

        auto handleLeafCase = [&](DeclRef<Decl> baseDeclRef, Type* type)
            {
                auto aggTypeDeclRef = as<AggTypeDeclBase>(baseDeclRef);

                if (auto namespaceDeclRef = as<NamespaceDeclBase>(baseDeclRef))
                {
                    // We are looking up a namespace member.
                    //
                    // We should lookup in all sibling scopes of the namespace.
                    // Another detail here is that we need to skip scopes that are transitively imported.
                    // For example, given:
                    // ```
                    //     module a;
                    //     namespace ns { int f_a(); }
                    // 
                    //     module b;
                    //     namespace ns { int f_b(); } // will have a sibling scope that refers to a::ns.
                    // 
                    //     module c;
                    //     import b;
                    //     void test() {ns.f_a(); // should not be valid, because c does not import a. }
                    // ```
                    // Note that this logic doesn't work nicely with __exported import, but we should consider
                    // deprecate this feature anyway.
                    //
                    auto namespaceModule = getModuleDecl(namespaceDeclRef.getDecl());
                    auto thisModule = m_outerScope ? getModuleDecl(m_outerScope->containerDecl) : namespaceModule;

                    for (auto scope = namespaceDeclRef.getDecl()->ownedScope; scope; scope = scope->nextSibling)
                    {
                        auto namespaceDecl = as<NamespaceDeclBase>(scope->containerDecl);
                        if (!namespaceDecl)
                            continue;
                        if (thisModule != namespaceModule && namespaceModule != getModuleDecl(namespaceDecl))
                            continue;
                        if (processedNamespaceScopes.add(scope->containerDecl))
                        {
                            LookupResult nsLookupResult = lookUpDirectAndTransparentMembers(
                                m_astBuilder,
                                this,
                                expr->name,
                                namespaceDecl,
                                DeclRef(namespaceDecl),
                                LookupMask::Default,
                                getDeclToExcludeFromLookup());
                            AddToLookupResult(globalLookupResult, nsLookupResult);
                        }
                    }
                }
                else if (aggTypeDeclRef || type)
                {
                    // We are looking up a member inside a type.
                    // We want to be careful here because we should only find members
                    // that are implicitly or explicitly `static`.
                    //
                    if (type == nullptr)
                        type = DeclRefType::create(m_astBuilder, aggTypeDeclRef);

                    if (as<ErrorType>(type))
                    {
                        return;
                    }

                    LookupResult lookupResult = lookUpMember(
                        m_astBuilder,
                        this,
                        expr->name,
                        type,
                        m_outerScope,
                        LookupMask::Default,
                        LookupOptions::NoDeref);

                    // We need to confirm that whatever member we
                    // are trying to refer to is usable via static reference.
                    //
                    // TODO: eventually we might allow a non-static
                    // member to be adapted by turning it into something
                    // like a closure that takes the missing `this` parameter.
                    //
                    // E.g., a static reference to a method could be treated
                    // as a value with a function type, where the first parameter
                    // is `type`.
                    //
                    // The biggest challenge there is that we'd need to arrange
                    // to generate "dispatcher" functions that could be used
                    // to implement that function, in the case where we are
                    // making a static reference to some kind of polymorphic declaration.
                    //
                    // (Also, static references to fields/properties would get even
                    // harder, because you'd have to know whether a getter/setter/ref-er
                    // is needed).
                    //
                    // For now let's just be expedient and disallow all of that, because
                    // we can always add it back in later.

                    // If the lookup result is valid, then we want to filter
                    // it to just those candidates that can be referenced statically,
                    // and ignore any that would only be allowed as instance members.
                    //
                    if (lookupResult.isValid())
                    {
                        // We track both the usable items, and whether or
                        // not there were any non-static items that need
                        // to be ignored.
                        //
                        bool anyNonStatic = false;
                        List<LookupResultItem> staticItems;
                        for (auto item : lookupResult)
                        {
                            // Is this item usable as a static member?
                            if (isUsableAsStaticMember(item))
                            {
                                // If yes, then it will be part of the output.
                                staticItems.add(item);
                            }
                            else
                            {
                                // If no, then we might need to output an error.
                                anyNonStatic = true;
                            }
                        }

                        // Was there anything non-static in the list?
                        if (anyNonStatic)
                        {
                            // If we had some static items, then that's okay,
                            // we just want to use our newly-filtered list.
                            if (staticItems.getCount())
                            {
                                lookupResult.items = staticItems;
                                lookupResult.item = staticItems[0];
                            }
                            else
                            {
                                // Otherwise, it is time to report an error.
                                getSink()->diagnose(
                                    expr->loc,
                                    Diagnostics::staticRefToNonStaticMember,
                                    type,
                                    expr->name);
                                hasErrors = true;
                                return;
                            }
                        }
                        // If there were no non-static items, then the `items`
                        // array already represents what we'd get by filtering...

                        AddToLookupResult(globalLookupResult, lookupResult);
                        base = baseExpression;
                    }
                }
            };

        auto handleLeafExpr = [&](Expr* e)
            {
                if (auto nsType = as<NamespaceType>(e->type))
                    handleLeafCase(nsType->getDeclRef(), nsType);
                else if (auto aggType = as<DeclRefType>(e->type))
                    handleLeafCase(aggType->getDeclRef(), aggType);
                else if (auto typetype = as<TypeType>(e->type))
                    handleLeafCase(DeclRef<Decl>(), typetype->getType());
            };

        auto& baseType = baseExpression->type;
        if (as<ErrorType>(baseType))
        {
            return CreateErrorExpr(expr);
        }

        if (auto overloaded = as<OverloadedExpr>(baseExpression))
        {
            for (auto candidate : overloaded->lookupResult2.items)
                handleLeafCase(candidate.declRef, nullptr);
        }
        else if (auto overloaded2 = as<OverloadedExpr2>(baseExpression))
        {
            for (auto candidate : overloaded2->candidiateExprs)
            {
                handleLeafExpr(candidate);
            }
        }
        else
        {
            handleLeafExpr(baseExpression);
        }

        bool diagnosed = false;
        globalLookupResult = filterLookupResultByVisibilityAndDiagnose(globalLookupResult, expr->loc, diagnosed);
        diagnosed |= hasErrors;
        if (!globalLookupResult.isValid())
        {
            return lookupMemberResultFailure(expr, baseType, diagnosed);
        }

        if (expr->name == getSession()->getCompletionRequestTokenName())
        {
            suggestCompletionItems(CompletionSuggestions::ScopeKind::Member, globalLookupResult);
        }
        return createLookupResultExpr(
            expr->name,
            globalLookupResult,
            base,
            expr->loc,
            expr);
    }

    Expr* SemanticsExprVisitor::visitStaticMemberExpr(StaticMemberExpr* expr)
    {
        expr->baseExpression = CheckTerm(expr->baseExpression);

        // Not sure this is needed -> but guess someone could do 
        expr->baseExpression = MaybeDereference(expr->baseExpression);

        // If the base of the member lookup has an interface type
        // *without* a suitable this-type substitution, then we are
        // trying to perform lookup on a value of existential type,
        // and we should "open" the existential here so that we
        // can expose its structure.
        //

        expr->baseExpression = maybeOpenExistential(expr->baseExpression);
        // Do a static lookup
        return _lookupStaticMember(expr, expr->baseExpression);
    }

    Expr* SemanticsVisitor::lookupMemberResultFailure(
        DeclRefExpr*     expr,
        QualType const& baseType,
        bool supressDiagnostic)
    {
        // Check it's a member expression
        SLANG_ASSERT(as<StaticMemberExpr>(expr) || as<MemberExpr>(expr));

        if (!supressDiagnostic)
            getSink()->diagnose(expr, Diagnostics::noMemberOfNameInType, expr->name, baseType);
        expr->type = QualType(m_astBuilder->getErrorType());
        return expr;
    }

    Expr* SemanticsVisitor::checkBaseForMemberExpr(Expr* inBaseExpr, bool& outNeedDeref)
    {
        auto baseExpr = inBaseExpr;

        baseExpr = CheckTerm(baseExpr);

        auto derefExpr = MaybeDereference(baseExpr);

        if (derefExpr != baseExpr)
            outNeedDeref = true;

        baseExpr = derefExpr;

        // If the base of the member lookup has an interface type
        // *without* a suitable this-type substitution, then we are
        // trying to perform lookup on a value of existential type,
        // and we should "open" the existential here so that we
        // can expose its structure.
        //
        baseExpr = maybeOpenExistential(baseExpr);

        // Handle the case of an overloaded base expression
        // here, in case we can use the name of the member to
        // disambiguate which of the candidates is meant, or if
        // we can return an overloaded result.
        if (auto overloadedExpr = as<OverloadedExpr>(baseExpr))
        {
            // If a member (dynamic or static) lookup result contains both the actual definition
            // and the interface definition obtained from inheritance, we want to filter out
            // the interface definitions.
            LookupResult filteredLookupResult;
            for (auto lookupResult : overloadedExpr->lookupResult2)
            {
                bool shouldRemove = false;
                if (lookupResult.declRef.getParent().as<InterfaceDecl>())
                {
                    shouldRemove = true;
                }
                if (lookupResult.declRef.getDecl()->hasModifier<ExtensionExternVarModifier>())
                    shouldRemove = true;
                if (!shouldRemove)
                {
                    filteredLookupResult.items.add(lookupResult);
                }
            }
            if (filteredLookupResult.items.getCount() == 1)
                filteredLookupResult.item = filteredLookupResult.items.getFirst();
            baseExpr = createLookupResultExpr(
                overloadedExpr->name,
                filteredLookupResult,
                overloadedExpr->base,
                overloadedExpr->loc,
                overloadedExpr);
            // TODO: handle other cases of OverloadedExpr that need filtering.
        }

        return baseExpr;
    }

    Expr* SemanticsExprVisitor::visitMemberExpr(MemberExpr * expr)
    {
        bool needDeref = false;
        expr->baseExpression = checkBaseForMemberExpr(expr->baseExpression, needDeref);

        if (!needDeref && as<DerefMemberExpr>(expr) && !as<PtrType>(expr->baseExpression->type))
        {
            // The user is trying to use the `->` operator on something that can't be
            // dereferenced, so we should diagnose that.
            if (!as<ErrorType>(expr->baseExpression->type))
                getSink()->diagnose(expr->memberOperatorLoc, Diagnostics::cannotDereferenceType, expr->baseExpression->type);
        }

        auto baseType = expr->baseExpression->type;

        // If we are looking up through a modified type, just pass straight
        // through the inner type.
        if (auto modifiedType = as<ModifiedType>(baseType))
            baseType = modifiedType->getBase();

        // Note: Checking for vector types before declaration-reference types,
        // because vectors are also declaration reference types...
        //
        // Also note: the way this is done right now means that the ability
        // to swizzle vectors interferes with any chance o<f looking up
        // members via extension, for vector or scalar types.
        //
        // TODO: Matrix swizzles probably need to be handled at some point.
        if (auto baseMatrixType = as<MatrixExpressionType>(baseType))
        {
            return CheckMatrixSwizzleExpr(
                expr,
                baseMatrixType->getElementType(),
                baseMatrixType->getRowCount(),
                baseMatrixType->getColumnCount());
        }
        if (auto baseVecType = as<VectorExpressionType>(baseType))
        {
            return CheckSwizzleExpr(
                expr,
                baseVecType->getElementType(),
                baseVecType->getElementCount());
        }
        else if(auto baseScalarType = as<BasicExpressionType>(baseType))
        {
            // Treat scalar like a 1-element vector when swizzling
            return CheckSwizzleExpr(
                expr,
                baseScalarType,
                1);
        }
        else if( as<NamespaceType>(baseType) )
        {
            return _lookupStaticMember(expr, expr->baseExpression);
        }
        else if(const auto typeType = as<TypeType>(baseType))
        {
            return _lookupStaticMember(expr, expr->baseExpression);
        }
        else if (as<OverloadedExpr>(expr->baseExpression))
        {
            return _lookupStaticMember(expr, expr->baseExpression);
        }
        else if (as<OverloadedExpr2>(expr->baseExpression))
        {
            return _lookupStaticMember(expr, expr->baseExpression);
        }
        else if (as<ErrorType>(baseType))
        {
            return CreateErrorExpr(expr);
        }
        else
        {
            LookupResult lookupResult = lookUpMember(
                m_astBuilder,
                this,
                expr->name,
                baseType.Ptr(),
                m_outerScope);
            bool diagnosed = false;
            lookupResult = filterLookupResultByVisibilityAndDiagnose(lookupResult, expr->loc, diagnosed);
            if (!lookupResult.isValid())
            {
                return lookupMemberResultFailure(expr, baseType, diagnosed);
            }
            if (expr->name == getSession()->getCompletionRequestTokenName())
            {
                suggestCompletionItems(CompletionSuggestions::ScopeKind::Member, lookupResult);
            }
            return createLookupResultExpr(
                expr->name,
                lookupResult,
                expr->baseExpression,
                expr->loc,
                expr);
        }
    }

    Expr* SemanticsExprVisitor::visitInitializerListExpr(InitializerListExpr* expr)
    {
        // When faced with an initializer list, we first just check the sub-expressions blindly.
        // Actually making them conform to a desired type will wait for when we know the desired
        // type based on context.

        for( auto& arg : expr->args )
        {
            arg = CheckTerm(arg);
        }

        expr->type = m_astBuilder->getInitializerListType();

        return expr;
    }

    // Perform semantic checking of an object-oriented `this`
    // expression.
    Expr* SemanticsExprVisitor::visitThisExpr(ThisExpr* expr)
    {
        // A `this` expression will default to immutable.
        expr->type.isLeftValue = false;

        // We will do an upwards search starting in the current
        // scope, looking for a surrounding type (or `extension`)
        // declaration that could be the referrant of the expression.
        auto scope = expr->scope;
        while (scope)
        {
            auto containerDecl = scope->containerDecl;

            if( const auto ctorDecl = as<ConstructorDecl>(containerDecl) )
            {
                expr->type.isLeftValue = true;
            }
            else if( const auto setterDecl = as<SetterDecl>(containerDecl) )
            {