1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845
|
//===--- GenCall.cpp - Swift IR Generation for Function Calls -------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements IR generation for function signature lowering
// in Swift. This includes creating the IR type, collecting IR attributes,
// performing calls, and supporting prologue and epilogue emission.
//
//===----------------------------------------------------------------------===//
#include "swift/ABI/MetadataValues.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ClangModuleLoader.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/IRGen/Linking.h"
#include "swift/Runtime/Config.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILType.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/GlobalDecl.h"
#include "clang/AST/RecordLayout.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/CodeGen/CodeGenABITypes.h"
#include "clang/CodeGen/ModuleBuilder.h"
#include "clang/Sema/Sema.h"
#include "llvm/IR/GlobalPtrAuthInfo.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/Support/Compiler.h"
#include <optional>
#include "CallEmission.h"
#include "EntryPointArgumentEmission.h"
#include "Explosion.h"
#include "GenCall.h"
#include "GenFunc.h"
#include "GenHeap.h"
#include "GenKeyPath.h"
#include "GenObjC.h"
#include "GenPointerAuth.h"
#include "GenPoly.h"
#include "GenProto.h"
#include "GenType.h"
#include "IRGenFunction.h"
#include "IRGenModule.h"
#include "LoadableTypeInfo.h"
#include "NativeConventionSchema.h"
#include "Signature.h"
#include "StructLayout.h"
using namespace swift;
using namespace irgen;
static Size getYieldOnceCoroutineBufferSize(IRGenModule &IGM) {
return NumWords_YieldOnceBuffer * IGM.getPointerSize();
}
static Alignment getYieldOnceCoroutineBufferAlignment(IRGenModule &IGM) {
return IGM.getPointerAlignment();
}
static Size getYieldManyCoroutineBufferSize(IRGenModule &IGM) {
return NumWords_YieldManyBuffer * IGM.getPointerSize();
}
static Alignment getYieldManyCoroutineBufferAlignment(IRGenModule &IGM) {
return IGM.getPointerAlignment();
}
static Size getCoroutineContextSize(IRGenModule &IGM,
CanSILFunctionType fnType) {
switch (fnType->getCoroutineKind()) {
case SILCoroutineKind::None:
llvm_unreachable("expand a coroutine");
case SILCoroutineKind::YieldOnce:
return getYieldOnceCoroutineBufferSize(IGM);
case SILCoroutineKind::YieldMany:
return getYieldManyCoroutineBufferSize(IGM);
}
llvm_unreachable("bad kind");
}
AsyncContextLayout irgen::getAsyncContextLayout(IRGenModule &IGM,
SILFunction *function) {
SubstitutionMap forwardingSubstitutionMap =
function->getForwardingSubstitutionMap();
CanSILFunctionType originalType = function->getLoweredFunctionType();
CanSILFunctionType substitutedType = originalType->substGenericArgs(
IGM.getSILModule(), forwardingSubstitutionMap,
IGM.getMaximalTypeExpansionContext());
auto layout = getAsyncContextLayout(
IGM, originalType, substitutedType, forwardingSubstitutionMap);
return layout;
}
static Size getAsyncContextHeaderSize(IRGenModule &IGM) {
return 2 * IGM.getPointerSize();
}
AsyncContextLayout irgen::getAsyncContextLayout(
IRGenModule &IGM, CanSILFunctionType originalType,
CanSILFunctionType substitutedType, SubstitutionMap substitutionMap) {
// FIXME: everything about this type is way more complicated than it
// needs to be now that we no longer pass and return things in memory
// in the async context and therefore the layout is totally static.
SmallVector<const TypeInfo *, 4> typeInfos;
SmallVector<SILType, 4> valTypes;
// AsyncContext * __ptrauth_swift_async_context_parent Parent;
{
auto ty = SILType();
auto &ti = IGM.getSwiftContextPtrTypeInfo();
valTypes.push_back(ty);
typeInfos.push_back(&ti);
}
// TaskContinuationFunction * __ptrauth_swift_async_context_resume
// ResumeParent;
{
auto ty = SILType();
auto &ti = IGM.getTaskContinuationFunctionPtrTypeInfo();
valTypes.push_back(ty);
typeInfos.push_back(&ti);
}
return AsyncContextLayout(IGM, LayoutStrategy::Optimal, valTypes, typeInfos,
originalType, substitutedType, substitutionMap);
}
AsyncContextLayout::AsyncContextLayout(
IRGenModule &IGM, LayoutStrategy strategy, ArrayRef<SILType> fieldTypes,
ArrayRef<const TypeInfo *> fieldTypeInfos, CanSILFunctionType originalType,
CanSILFunctionType substitutedType, SubstitutionMap substitutionMap)
: StructLayout(IGM, /*type=*/std::nullopt, LayoutKind::NonHeapObject,
strategy, fieldTypeInfos, /*typeToFill*/ nullptr),
originalType(originalType), substitutedType(substitutedType),
substitutionMap(substitutionMap) {
assert(fieldTypeInfos.size() == fieldTypes.size() &&
"type infos don't match types");
assert(this->isFixedLayout());
assert(this->getSize() == getAsyncContextHeaderSize(IGM));
}
Alignment IRGenModule::getAsyncContextAlignment() const {
return Alignment(MaximumAlignment);
}
std::optional<Size>
FunctionPointerKind::getStaticAsyncContextSize(IRGenModule &IGM) const {
if (!isSpecial())
return std::nullopt;
auto headerSize = getAsyncContextHeaderSize(IGM);
headerSize = headerSize.roundUpToAlignment(IGM.getPointerAlignment());
switch (getSpecialKind()) {
case SpecialKind::TaskFutureWaitThrowing:
case SpecialKind::TaskFutureWait:
case SpecialKind::AsyncLetWait:
case SpecialKind::AsyncLetWaitThrowing:
case SpecialKind::AsyncLetGet:
case SpecialKind::AsyncLetGetThrowing:
case SpecialKind::AsyncLetFinish:
case SpecialKind::TaskGroupWaitNext:
case SpecialKind::TaskGroupWaitAll:
case SpecialKind::DistributedExecuteTarget:
// The current guarantee for all of these functions is the same.
// See TaskFutureWaitAsyncContext.
//
// If you add a new special runtime function, it is highly recommended
// that you make calls to it allocate a little more memory than this!
// These frames being this small is very arguably a mistake.
return headerSize + 3 * IGM.getPointerSize();
case SpecialKind::KeyPathAccessor:
return std::nullopt;
}
llvm_unreachable("covered switch");
}
void IRGenFunction::setupAsync(unsigned asyncContextIndex) {
llvm::Value *c = CurFn->getArg(asyncContextIndex);
asyncContextLocation = createAlloca(c->getType(), IGM.getPointerAlignment());
IRBuilder builder(IGM.getLLVMContext(), IGM.DebugInfo != nullptr);
// Insert the stores after the coro.begin.
builder.SetInsertPoint(getEarliestInsertionPoint()->getParent(),
getEarliestInsertionPoint()->getIterator());
builder.CreateStore(c, asyncContextLocation);
}
llvm::Value *IRGenFunction::getAsyncTask() {
auto call = Builder.CreateCall(IGM.getGetCurrentTaskFunctionPointer(), {});
call->setDoesNotThrow();
call->setCallingConv(IGM.SwiftCC);
return call;
}
llvm::Value *IRGenFunction::getAsyncContext() {
assert(isAsync());
return Builder.CreateLoad(asyncContextLocation);
}
void IRGenFunction::storeCurrentAsyncContext(llvm::Value *context) {
context = Builder.CreateBitCast(context, IGM.SwiftContextPtrTy);
Builder.CreateStore(context, asyncContextLocation);
}
llvm::CallInst *IRGenFunction::emitSuspendAsyncCall(
unsigned asyncContextIndex, llvm::StructType *resultTy,
ArrayRef<llvm::Value *> args, bool restoreCurrentContext) {
auto *id = Builder.CreateIntrinsicCall(llvm::Intrinsic::coro_suspend_async,
{resultTy}, args);
if (restoreCurrentContext) {
llvm::Value *calleeContext =
Builder.CreateExtractValue(id, asyncContextIndex);
calleeContext =
Builder.CreateBitOrPointerCast(calleeContext, IGM.Int8PtrTy);
llvm::Function *projectFn = cast<llvm::Function>(
(cast<llvm::Constant>(args[2])->stripPointerCasts()));
auto *fnTy = projectFn->getFunctionType();
llvm::Value *context =
Builder.CreateCallWithoutDbgLoc(fnTy, projectFn, {calleeContext});
storeCurrentAsyncContext(context);
}
return id;
}
llvm::Type *ExplosionSchema::getScalarResultType(IRGenModule &IGM) const {
if (size() == 0) {
return IGM.VoidTy;
} else if (size() == 1) {
return begin()->getScalarType();
} else {
SmallVector<llvm::Type*, 16> elts;
for (auto &elt : *this) elts.push_back(elt.getScalarType());
return llvm::StructType::get(IGM.getLLVMContext(), elts);
}
}
static void addDereferenceableAttributeToBuilder(IRGenModule &IGM,
llvm::AttrBuilder &b,
const TypeInfo &ti) {
// The addresses of empty values are undefined, so we can't safely mark them
// dereferenceable.
if (ti.isKnownEmpty(ResilienceExpansion::Maximal))
return;
// If we know the type to have a fixed nonempty size, then the pointer is
// dereferenceable to at least that size.
// TODO: Would be nice to have a "getMinimumKnownSize" on TypeInfo for
// dynamic-layout aggregates.
if (auto fixedTI = dyn_cast<FixedTypeInfo>(&ti)) {
b.addAttribute(
llvm::Attribute::getWithDereferenceableBytes(IGM.getLLVMContext(),
fixedTI->getFixedSize().getValue()));
}
}
static void addIndirectValueParameterAttributes(IRGenModule &IGM,
llvm::AttributeList &attrs,
const TypeInfo &ti,
unsigned argIndex) {
llvm::AttrBuilder b(IGM.getLLVMContext());
// Value parameter pointers can't alias or be captured.
b.addAttribute(llvm::Attribute::NoAlias);
// Bitwise takable value types are guaranteed not to capture
// a pointer into itself.
if (ti.isBitwiseTakable(ResilienceExpansion::Maximal))
b.addAttribute(llvm::Attribute::NoCapture);
// The parameter must reference dereferenceable memory of the type.
addDereferenceableAttributeToBuilder(IGM, b, ti);
attrs = attrs.addParamAttributes(IGM.getLLVMContext(), argIndex, b);
}
static void addPackParameterAttributes(IRGenModule &IGM,
SILType paramSILType,
llvm::AttributeList &attrs,
unsigned argIndex) {
llvm::AttrBuilder b(IGM.getLLVMContext());
// Pack parameter pointers can't alias.
// Note: they are not marked `nocapture` as one
// pack parameter could be a value type (e.g. a C++ type)
// that captures its own pointer in itself.
b.addAttribute(llvm::Attribute::NoAlias);
// TODO: we could mark this dereferenceable when the pack has fixed
// components.
// TODO: add an alignment attribute
// TODO: add a nonnull attribute
attrs = attrs.addParamAttributes(IGM.getLLVMContext(), argIndex, b);
}
static void addInoutParameterAttributes(IRGenModule &IGM, SILType paramSILType,
llvm::AttributeList &attrs,
const TypeInfo &ti, unsigned argIndex,
bool aliasable) {
llvm::AttrBuilder b(IGM.getLLVMContext());
// Thanks to exclusivity checking, it is not possible to alias inouts except
// those that are inout_aliasable.
if (!aliasable && paramSILType.getASTType()->getAnyPointerElementType()) {
// To ward against issues with LLVM's alias analysis, for now, only add the
// attribute if it's a pointer being passed inout.
b.addAttribute(llvm::Attribute::NoAlias);
}
// Bitwise takable value types are guaranteed not to capture
// a pointer into itself.
if (ti.isBitwiseTakable(ResilienceExpansion::Maximal))
b.addAttribute(llvm::Attribute::NoCapture);
// The inout must reference dereferenceable memory of the type.
addDereferenceableAttributeToBuilder(IGM, b, ti);
attrs = attrs.addParamAttributes(IGM.getLLVMContext(), argIndex, b);
}
static llvm::CallingConv::ID getFreestandingConvention(IRGenModule &IGM) {
// TODO: use a custom CC that returns three scalars efficiently
return IGM.SwiftCC;
}
/// Expand the requirements of the given abstract calling convention
/// into a "physical" calling convention.
llvm::CallingConv::ID irgen::expandCallingConv(IRGenModule &IGM,
SILFunctionTypeRepresentation convention,
bool isAsync) {
switch (convention) {
case SILFunctionTypeRepresentation::CFunctionPointer:
case SILFunctionTypeRepresentation::ObjCMethod:
case SILFunctionTypeRepresentation::CXXMethod:
case SILFunctionTypeRepresentation::Block:
return IGM.getOptions().PlatformCCallingConvention;
case SILFunctionTypeRepresentation::Method:
case SILFunctionTypeRepresentation::WitnessMethod:
case SILFunctionTypeRepresentation::Closure:
case SILFunctionTypeRepresentation::Thin:
case SILFunctionTypeRepresentation::Thick:
case SILFunctionTypeRepresentation::KeyPathAccessorGetter:
case SILFunctionTypeRepresentation::KeyPathAccessorSetter:
case SILFunctionTypeRepresentation::KeyPathAccessorEquals:
case SILFunctionTypeRepresentation::KeyPathAccessorHash:
if (isAsync)
return IGM.SwiftAsyncCC;
return getFreestandingConvention(IGM);
}
llvm_unreachable("bad calling convention!");
}
static void addIndirectResultAttributes(IRGenModule &IGM,
llvm::AttributeList &attrs,
unsigned paramIndex, bool allowSRet,
llvm::Type *storageType,
const TypeInfo &typeInfo,
bool useInReg = false) {
llvm::AttrBuilder b(IGM.getLLVMContext());
b.addAttribute(llvm::Attribute::NoAlias);
// Bitwise takable value types are guaranteed not to capture
// a pointer into itself.
if (typeInfo.isBitwiseTakable(ResilienceExpansion::Maximal))
b.addAttribute(llvm::Attribute::NoCapture);
if (allowSRet) {
assert(storageType);
b.addStructRetAttr(storageType);
if (useInReg)
b.addAttribute(llvm::Attribute::InReg);
}
attrs = attrs.addParamAttributes(IGM.getLLVMContext(), paramIndex, b);
}
void IRGenModule::addSwiftAsyncContextAttributes(llvm::AttributeList &attrs,
unsigned argIndex) {
llvm::AttrBuilder b(getLLVMContext());
b.addAttribute(llvm::Attribute::SwiftAsync);
attrs = attrs.addParamAttributes(this->getLLVMContext(), argIndex, b);
}
void IRGenModule::addSwiftSelfAttributes(llvm::AttributeList &attrs,
unsigned argIndex) {
llvm::AttrBuilder b(getLLVMContext());
b.addAttribute(llvm::Attribute::SwiftSelf);
attrs = attrs.addParamAttributes(this->getLLVMContext(), argIndex, b);
}
void IRGenModule::addSwiftErrorAttributes(llvm::AttributeList &attrs,
unsigned argIndex) {
llvm::AttrBuilder b(getLLVMContext());
// Don't add the swifterror attribute on ABIs that don't pass it in a register.
// We create a shadow stack location of the swifterror parameter for the
// debugger on such platforms and so we can't mark the parameter with a
// swifterror attribute.
if (ShouldUseSwiftError)
b.addAttribute(llvm::Attribute::SwiftError);
// The error result should not be aliased, captured, or pointed at invalid
// addresses regardless.
b.addAttribute(llvm::Attribute::NoAlias);
b.addAttribute(llvm::Attribute::NoCapture);
b.addDereferenceableAttr(getPointerSize().getValue());
attrs = attrs.addParamAttributes(this->getLLVMContext(), argIndex, b);
}
void irgen::addByvalArgumentAttributes(IRGenModule &IGM,
llvm::AttributeList &attrs,
unsigned argIndex, Alignment align,
llvm::Type *storageType) {
llvm::AttrBuilder b(IGM.getLLVMContext());
b.addByValAttr(storageType);
b.addAttribute(llvm::Attribute::getWithAlignment(
IGM.getLLVMContext(), llvm::Align(align.getValue())));
attrs = attrs.addParamAttributes(IGM.getLLVMContext(), argIndex, b);
}
static llvm::Attribute::AttrKind attrKindForExtending(bool signExtend) {
if (signExtend)
return llvm::Attribute::SExt;
return llvm::Attribute::ZExt;
}
namespace swift {
namespace irgen {
namespace {
class SignatureExpansion {
IRGenModule &IGM;
CanSILFunctionType FnType;
bool forStaticCall = false; // Used for objc_method (direct call or not).
// Indicates this is a c++ constructor call.
const clang::CXXConstructorDecl *cxxCtorDecl = nullptr;
public:
SmallVector<llvm::Type*, 8> ParamIRTypes;
llvm::Type *ResultIRType = nullptr;
llvm::AttributeList Attrs;
ForeignFunctionInfo ForeignInfo;
CoroutineInfo CoroInfo;
bool CanUseSRet = true;
bool CanUseError = true;
bool CanUseSelf = true;
unsigned AsyncContextIdx;
unsigned AsyncResumeFunctionSwiftSelfIdx = 0;
FunctionPointerKind FnKind;
SignatureExpansion(IRGenModule &IGM, CanSILFunctionType fnType,
FunctionPointerKind fnKind, bool forStaticCall = false,
const clang::CXXConstructorDecl *cxxCtorDecl = nullptr)
: IGM(IGM), FnType(fnType), forStaticCall(forStaticCall),
cxxCtorDecl(cxxCtorDecl), FnKind(fnKind) {}
/// Expand the components of the primary entrypoint of the function type.
void expandFunctionType(
SignatureExpansionABIDetails *recordedABIDetails = nullptr);
/// Expand the components of the continuation entrypoint of the
/// function type.
void expandCoroutineContinuationType();
// Expand the components for the async continuation entrypoint of the
// function type (the function to be called on returning).
void expandAsyncReturnType();
// Expand the components for the async suspend call of the function type.
void expandAsyncAwaitType();
// Expand the components for the primary entrypoint of the async function
// type.
void expandAsyncEntryType();
Signature getSignature();
private:
const TypeInfo &expand(SILParameterInfo param);
llvm::Type *addIndirectResult(SILType resultType, bool useInReg = false);
SILFunctionConventions getSILFuncConventions() const {
return SILFunctionConventions(FnType, IGM.getSILModule());
}
unsigned getCurParamIndex() {
return ParamIRTypes.size();
}
bool claimSRet() {
bool result = CanUseSRet;
CanUseSRet = false;
return result;
}
bool claimSelf() {
auto Ret = CanUseSelf;
assert(CanUseSelf && "Multiple self parameters?!");
CanUseSelf = false;
return Ret;
}
bool claimError() {
auto Ret = CanUseError;
assert(CanUseError && "Multiple error parameters?!");
CanUseError = false;
return Ret;
}
/// Add a pointer to the given type as the next parameter.
void addPointerParameter(llvm::Type *storageType) {
ParamIRTypes.push_back(storageType->getPointerTo());
}
void addCoroutineContextParameter();
void addAsyncParameters();
void expandResult(SignatureExpansionABIDetails *recordedABIDetails);
/// Returns the LLVM type pointer and its type info for
/// the direct result of this function. If the result is passed indirectly,
/// a void type is returned instead, with a \c null type info.
std::pair<llvm::Type *, const TypeInfo *> expandDirectResult();
void expandIndirectResults();
void expandParameters(SignatureExpansionABIDetails *recordedABIDetails);
void expandKeyPathAccessorParameters();
void expandExternalSignatureTypes();
void expandCoroutineResult(bool forContinuation);
void expandCoroutineContinuationParameters();
void addIndirectThrowingResult();
llvm::Type *getErrorRegisterType();
};
} // end anonymous namespace
} // end namespace irgen
} // end namespace swift
llvm::Type *SignatureExpansion::addIndirectResult(SILType resultType,
bool useInReg) {
const TypeInfo &resultTI = IGM.getTypeInfo(resultType);
auto storageTy = resultTI.getStorageType();
addIndirectResultAttributes(IGM, Attrs, ParamIRTypes.size(), claimSRet(),
storageTy, resultTI, useInReg);
addPointerParameter(storageTy);
return IGM.VoidTy;
}
/// Expand all of the direct and indirect result types.
void SignatureExpansion::expandResult(
SignatureExpansionABIDetails *recordedABIDetails) {
if (FnType->isAsync()) {
// The result will be stored within the SwiftContext that is passed to async
// functions.
ResultIRType = IGM.VoidTy;
return;
}
if (FnType->isCoroutine()) {
// This should be easy enough to support if we need to: use the
// same algorithm but add the direct results to the results as if
// they were unioned in.
return expandCoroutineResult(/*for continuation*/ false);
}
auto fnConv = getSILFuncConventions();
// Disable the use of sret if we have multiple indirect results.
if (fnConv.getNumIndirectSILResults() > 1)
CanUseSRet = false;
// Ensure that no parameters were added before to correctly record their ABI
// details.
assert(ParamIRTypes.empty());
// Expand the direct result.
const TypeInfo *directResultTypeInfo;
std::tie(ResultIRType, directResultTypeInfo) = expandDirectResult();
// Expand the indirect results.
expandIndirectResults();
// Record ABI details if asked.
if (!recordedABIDetails)
return;
if (directResultTypeInfo)
recordedABIDetails->directResult =
SignatureExpansionABIDetails::DirectResult{*directResultTypeInfo};
for (unsigned i = 0; i < ParamIRTypes.size(); ++i) {
bool hasSRet = Attrs.hasParamAttr(i, llvm::Attribute::StructRet);
recordedABIDetails->indirectResults.push_back(
SignatureExpansionABIDetails::IndirectResult{hasSRet});
}
}
void SignatureExpansion::expandIndirectResults() {
auto fnConv = getSILFuncConventions();
// Expand the indirect results.
for (auto indirectResultType :
fnConv.getIndirectSILResultTypes(IGM.getMaximalTypeExpansionContext())) {
auto storageTy = IGM.getStorageType(indirectResultType);
auto useSRet = claimSRet();
// We need to use opaque types or non fixed size storage types because llvm
// does type based analysis based on the type of sret arguments.
const TypeInfo &typeInfo = IGM.getTypeInfo(indirectResultType);
if (useSRet && !isa<FixedTypeInfo>(typeInfo)) {
storageTy = IGM.OpaqueTy;
}
addIndirectResultAttributes(IGM, Attrs, ParamIRTypes.size(), useSRet,
storageTy, typeInfo);
addPointerParameter(storageTy);
}
}
namespace {
class YieldSchema {
SILType YieldTy;
const TypeInfo &YieldTI;
std::optional<NativeConventionSchema> NativeSchema;
bool IsIndirect;
public:
YieldSchema(IRGenModule &IGM, SILFunctionConventions fnConv,
SILYieldInfo yield)
: YieldTy(
fnConv.getSILType(yield, IGM.getMaximalTypeExpansionContext())),
YieldTI(IGM.getTypeInfo(YieldTy)) {
if (isFormalIndirect()) {
IsIndirect = true;
} else {
NativeSchema.emplace(IGM, &YieldTI, /*result*/ true);
IsIndirect = NativeSchema->requiresIndirect();
}
}
SILType getSILType() const {
return YieldTy;
}
const TypeInfo &getTypeInfo() const {
return YieldTI;
}
/// Should the yielded value be yielded as a pointer?
bool isIndirect() const { return IsIndirect; }
/// Is the yielded value formally indirect?
bool isFormalIndirect() const { return YieldTy.isAddress(); }
llvm::PointerType *getIndirectPointerType() const {
assert(isIndirect());
return YieldTI.getStorageType()->getPointerTo();
}
const NativeConventionSchema &getDirectSchema() const {
assert(!isIndirect());
return *NativeSchema;
}
void enumerateDirectComponents(llvm::function_ref<void(llvm::Type*)> fn) {
getDirectSchema().enumerateComponents([&](clang::CharUnits begin,
clang::CharUnits end,
llvm::Type *componentTy) {
fn(componentTy);
});
}
};
}
void SignatureExpansion::expandCoroutineResult(bool forContinuation) {
assert(FnType->getNumResults() == 0 &&
"having both normal and yield results is currently unsupported");
// The return type may be different for the ramp function vs. the
// continuations.
if (forContinuation) {
switch (FnType->getCoroutineKind()) {
case SILCoroutineKind::None:
llvm_unreachable("should have been filtered out before here");
// Yield-once coroutines just return void from the continuation.
case SILCoroutineKind::YieldOnce:
ResultIRType = IGM.VoidTy;
return;
// Yield-many coroutines yield the same types from the continuation
// as they do from the ramp function.
case SILCoroutineKind::YieldMany:
break;
}
}
SmallVector<llvm::Type*, 8> components;
// The continuation pointer.
components.push_back(IGM.Int8PtrTy);
auto fnConv = getSILFuncConventions();
for (auto yield : FnType->getYields()) {
YieldSchema schema(IGM, fnConv, yield);
// If the individual value must be yielded indirectly, add a pointer.
if (schema.isIndirect()) {
components.push_back(schema.getIndirectPointerType());
continue;
}
// Otherwise, collect all the component types.
schema.enumerateDirectComponents([&](llvm::Type *type) {
components.push_back(type);
});
}
// Find the maximal sequence of the component types that we can
// convince the ABI to pass directly.
// When counting components, ignore the continuation pointer.
unsigned numDirectComponents = components.size() - 1;
SmallVector<llvm::Type*, 8> overflowTypes;
while (clang::CodeGen::swiftcall::
shouldPassIndirectly(IGM.ClangCodeGen->CGM(), components,
/*asReturnValue*/ true)) {
// If we added a pointer to the end of components, remove it.
if (!overflowTypes.empty()) components.pop_back();
// Remove the last component and add it as an overflow type.
overflowTypes.push_back(components.pop_back_val());
--numDirectComponents;
// Add a pointer to the end of components.
components.push_back(IGM.Int8PtrTy);
}
// We'd better have been able to pass at least two pointers.
assert(components.size() >= 2 || overflowTypes.empty());
CoroInfo.NumDirectYieldComponents = numDirectComponents;
// Replace the pointer type we added to components with the real
// pointer-to-overflow type.
if (!overflowTypes.empty()) {
std::reverse(overflowTypes.begin(), overflowTypes.end());
// TODO: should we use some sort of real layout here instead of
// trusting LLVM's?
CoroInfo.indirectResultsType =
llvm::StructType::get(IGM.getLLVMContext(), overflowTypes);
components.back() = CoroInfo.indirectResultsType->getPointerTo();
}
ResultIRType = components.size() == 1
? components.front()
: llvm::StructType::get(IGM.getLLVMContext(), components);
}
void SignatureExpansion::expandCoroutineContinuationParameters() {
// The coroutine context.
addCoroutineContextParameter();
// Whether this is an unwind resumption.
ParamIRTypes.push_back(IGM.Int1Ty);
}
void SignatureExpansion::addAsyncParameters() {
// using TaskContinuationFunction =
// SWIFT_CC(swift)
// void (SWIFT_ASYNC_CONTEXT AsyncContext *);
AsyncContextIdx = getCurParamIndex();
Attrs = Attrs.addParamAttribute(IGM.getLLVMContext(), AsyncContextIdx,
llvm::Attribute::SwiftAsync);
ParamIRTypes.push_back(IGM.SwiftContextPtrTy);
}
void SignatureExpansion::addCoroutineContextParameter() {
// Flag that the context is dereferenceable and unaliased.
auto contextSize = getCoroutineContextSize(IGM, FnType);
Attrs = Attrs.addDereferenceableParamAttr(IGM.getLLVMContext(),
getCurParamIndex(),
contextSize.getValue());
Attrs = Attrs.addParamAttribute(IGM.getLLVMContext(),
getCurParamIndex(),
llvm::Attribute::NoAlias);
ParamIRTypes.push_back(IGM.Int8PtrTy);
}
NativeConventionSchema::NativeConventionSchema(IRGenModule &IGM,
const TypeInfo *ti,
bool IsResult)
: Lowering(IGM.ClangCodeGen->CGM()) {
if (auto *loadable = dyn_cast<LoadableTypeInfo>(ti)) {
// Lower the type according to the Swift ABI.
loadable->addToAggLowering(IGM, Lowering, Size(0));
Lowering.finish();
// Should we pass indirectly according to the ABI?
RequiresIndirect = Lowering.shouldPassIndirectly(IsResult);
} else {
Lowering.finish();
RequiresIndirect = true;
}
}
llvm::Type *NativeConventionSchema::getExpandedType(IRGenModule &IGM) const {
if (empty())
return IGM.VoidTy;
SmallVector<llvm::Type *, 8> elts;
Lowering.enumerateComponents([&](clang::CharUnits offset,
clang::CharUnits end,
llvm::Type *type) { elts.push_back(type); });
if (elts.size() == 1)
return elts[0];
auto &ctx = IGM.getLLVMContext();
return llvm::StructType::get(ctx, elts, /*packed*/ false);
}
std::pair<llvm::StructType *, llvm::StructType *>
NativeConventionSchema::getCoercionTypes(
IRGenModule &IGM, SmallVectorImpl<unsigned> &expandedTyIndicesMap) const {
auto &ctx = IGM.getLLVMContext();
if (empty()) {
auto type = llvm::StructType::get(ctx);
return {type, type};
}
clang::CharUnits lastEnd = clang::CharUnits::Zero();
llvm::SmallSet<unsigned, 8> overlappedWithSuccessor;
unsigned idx = 0;
// Mark overlapping ranges.
Lowering.enumerateComponents(
[&](clang::CharUnits offset, clang::CharUnits end, llvm::Type *type) {
if (offset < lastEnd) {
overlappedWithSuccessor.insert(idx);
}
lastEnd = end;
++idx;
});
// Create the coercion struct with only the integer portion of overlapped
// components and non-overlapped components.
idx = 0;
lastEnd = clang::CharUnits::Zero();
SmallVector<llvm::Type *, 8> elts;
bool packed = false;
Lowering.enumerateComponents(
[&](clang::CharUnits begin, clang::CharUnits end, llvm::Type *type) {
bool overlapped = overlappedWithSuccessor.count(idx) ||
(idx && overlappedWithSuccessor.count(idx - 1));
++idx;
if (overlapped && !isa<llvm::IntegerType>(type)) {
// keep the old lastEnd for padding.
return;
}
// Add padding (which may include padding for overlapped non-integer
// components).
if (begin != lastEnd) {
auto paddingSize = begin - lastEnd;
assert(!paddingSize.isNegative());
auto padding = llvm::ArrayType::get(llvm::Type::getInt8Ty(ctx),
paddingSize.getQuantity());
elts.push_back(padding);
}
if (!packed && !begin.isMultipleOf(clang::CharUnits::fromQuantity(
IGM.DataLayout.getABITypeAlign(type))))
packed = true;
elts.push_back(type);
expandedTyIndicesMap.push_back(idx - 1);
lastEnd = begin + clang::CharUnits::fromQuantity(
IGM.DataLayout.getTypeAllocSize(type));
assert(end <= lastEnd);
});
auto *coercionType = llvm::StructType::get(ctx, elts, packed);
if (overlappedWithSuccessor.empty())
return {coercionType, llvm::StructType::get(ctx)};
// Create the coercion struct with only the non-integer overlapped
// components.
idx = 0;
lastEnd = clang::CharUnits::Zero();
elts.clear();
packed = false;
Lowering.enumerateComponents(
[&](clang::CharUnits begin, clang::CharUnits end, llvm::Type *type) {
bool overlapped = overlappedWithSuccessor.count(idx) ||
(idx && overlappedWithSuccessor.count(idx - 1));
++idx;
if (!overlapped || (overlapped && isa<llvm::IntegerType>(type))) {
// Ignore and keep the old lastEnd for padding.
return;
}
// Add padding.
if (begin != lastEnd) {
auto paddingSize = begin - lastEnd;
assert(!paddingSize.isNegative());
auto padding = llvm::ArrayType::get(llvm::Type::getInt8Ty(ctx),
paddingSize.getQuantity());
elts.push_back(padding);
}
if (!packed &&
!begin.isMultipleOf(clang::CharUnits::fromQuantity(
IGM.DataLayout.getABITypeAlign(type))))
packed = true;
elts.push_back(type);
expandedTyIndicesMap.push_back(idx - 1);
lastEnd = begin + clang::CharUnits::fromQuantity(
IGM.DataLayout.getTypeAllocSize(type));
assert(end <= lastEnd);
});
auto *overlappedCoercionType = llvm::StructType::get(ctx, elts, packed);
return {coercionType, overlappedCoercionType};
}
// TODO: Direct to Indirect result conversion could be handled in a SIL
// AddressLowering pass.
std::pair<llvm::Type *, const TypeInfo *>
SignatureExpansion::expandDirectResult() {
// Handle the direct result type, checking for supposedly scalar
// result types that we actually want to return indirectly.
auto resultType = getSILFuncConventions().getSILResultType(
IGM.getMaximalTypeExpansionContext());
// Fast-path the empty tuple type.
if (auto tuple = resultType.getAs<TupleType>())
if (tuple->getNumElements() == 0)
return std::make_pair(IGM.VoidTy, nullptr);
switch (FnType->getLanguage()) {
case SILFunctionLanguage::C:
llvm_unreachable("Expanding C/ObjC parameters in the wrong place!");
break;
case SILFunctionLanguage::Swift: {
auto &ti = IGM.getTypeInfo(resultType);
auto &native = ti.nativeReturnValueSchema(IGM);
if (native.requiresIndirect())
return std::make_pair(addIndirectResult(resultType), nullptr);
// Disable the use of sret if we have a non-trivial direct result.
if (!native.empty()) CanUseSRet = false;
return std::make_pair(native.getExpandedType(IGM), &ti);
}
}
llvm_unreachable("Not a valid SILFunctionLanguage.");
}
static const clang::FieldDecl *
getLargestUnionField(const clang::RecordDecl *record,
const clang::ASTContext &ctx) {
const clang::FieldDecl *largestField = nullptr;
clang::CharUnits unionSize = clang::CharUnits::Zero();
for (auto field : record->fields()) {
assert(!field->isBitField());
clang::CharUnits fieldSize = ctx.getTypeSizeInChars(field->getType());
if (unionSize < fieldSize) {
unionSize = fieldSize;
largestField = field;
}
}
assert(largestField && "empty union?");
return largestField;
}
namespace {
/// A CRTP class for working with Clang's ABIArgInfo::Expand
/// argument type expansions.
template <class Impl, class... Args> struct ClangExpand {
IRGenModule &IGM;
const clang::ASTContext &Ctx;
ClangExpand(IRGenModule &IGM) : IGM(IGM), Ctx(IGM.getClangASTContext()) {}
Impl &asImpl() { return *static_cast<Impl*>(this); }
void visit(clang::CanQualType type, Args... args) {
switch (type->getTypeClass()) {
#define TYPE(Class, Base)
#define NON_CANONICAL_TYPE(Class, Base) \
case clang::Type::Class:
#define DEPENDENT_TYPE(Class, Base) \
case clang::Type::Class:
#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
case clang::Type::Class:
#include "clang/AST/TypeNodes.inc"
llvm_unreachable("canonical or dependent type in ABI lowering");
// These shouldn't occur in expandable struct types.
case clang::Type::IncompleteArray:
case clang::Type::VariableArray:
llvm_unreachable("variable-sized or incomplete array in ABI lowering");
// We should only ever get ObjC pointers, not underlying objects.
case clang::Type::ObjCInterface:
case clang::Type::ObjCObject:
llvm_unreachable("ObjC object type in ABI lowering");
// We should only ever get function pointers.
case clang::Type::FunctionProto:
case clang::Type::FunctionNoProto:
llvm_unreachable("non-pointer function type in ABI lowering");
// We currently never import C++ code, and we should be able to
// kill Expand before we do.
case clang::Type::LValueReference:
case clang::Type::RValueReference:
case clang::Type::MemberPointer:
case clang::Type::Auto:
case clang::Type::DeducedTemplateSpecialization:
llvm_unreachable("C++ type in ABI lowering?");
case clang::Type::Pipe:
llvm_unreachable("OpenCL type in ABI lowering?");
case clang::Type::BitInt:
llvm_unreachable("BitInt type in ABI lowering?");
case clang::Type::ConstantMatrix: {
llvm_unreachable("ConstantMatrix type in ABI lowering?");
}
case clang::Type::ConstantArray: {
auto array = Ctx.getAsConstantArrayType(type);
auto elt = Ctx.getCanonicalType(array->getElementType());
auto &&context = asImpl().beginArrayElements(elt);
uint64_t n = array->getSize().getZExtValue();
for (uint64_t i = 0; i != n; ++i) {
asImpl().visitArrayElement(elt, i, context, args...);
}
return;
}
case clang::Type::Record: {
auto record = cast<clang::RecordType>(type)->getDecl();
if (record->isUnion()) {
auto largest = getLargestUnionField(record, Ctx);
asImpl().visitUnionField(record, largest, args...);
} else {
auto &&context = asImpl().beginStructFields(record);
for (auto field : record->fields()) {
asImpl().visitStructField(record, field, context, args...);
}
}
return;
}
case clang::Type::Complex: {
auto elt = type.castAs<clang::ComplexType>().getElementType();
asImpl().visitComplexElement(elt, 0, args...);
asImpl().visitComplexElement(elt, 1, args...);
return;
}
// Just handle this types as opaque integers.
case clang::Type::Enum:
case clang::Type::Atomic:
asImpl().visitScalar(convertTypeAsInteger(type), args...);
return;
case clang::Type::Builtin:
asImpl().visitScalar(
convertBuiltinType(type.castAs<clang::BuiltinType>()),
args...);
return;
case clang::Type::Vector:
case clang::Type::ExtVector:
asImpl().visitScalar(
convertVectorType(type.castAs<clang::VectorType>()),
args...);
return;
case clang::Type::Pointer:
case clang::Type::BlockPointer:
case clang::Type::ObjCObjectPointer:
asImpl().visitScalar(IGM.Int8PtrTy, args...);
return;
}
llvm_unreachable("bad type kind");
}
Size getSizeOfType(clang::QualType type) {
auto clangSize = Ctx.getTypeSizeInChars(type);
return Size(clangSize.getQuantity());
}
private:
llvm::Type *convertVectorType(clang::CanQual<clang::VectorType> type) {
auto eltTy =
convertBuiltinType(type->getElementType().castAs<clang::BuiltinType>());
return llvm::FixedVectorType::get(eltTy, type->getNumElements());
}
llvm::Type *convertBuiltinType(clang::CanQual<clang::BuiltinType> type) {
switch (type.getTypePtr()->getKind()) {
#define BUILTIN_TYPE(Id, SingletonId)
#define PLACEHOLDER_TYPE(Id, SingletonId) \
case clang::BuiltinType::Id:
#include "clang/AST/BuiltinTypes.def"
case clang::BuiltinType::Dependent:
llvm_unreachable("placeholder type in ABI lowering");
// We should never see these unadorned.
case clang::BuiltinType::ObjCId:
case clang::BuiltinType::ObjCClass:
case clang::BuiltinType::ObjCSel:
llvm_unreachable("bare Objective-C object type in ABI lowering");
// This should never be the type of an argument or field.
case clang::BuiltinType::Void:
llvm_unreachable("bare void type in ABI lowering");
// We should never see the OpenCL builtin types at all.
case clang::BuiltinType::OCLImage1dRO:
case clang::BuiltinType::OCLImage1dRW:
case clang::BuiltinType::OCLImage1dWO:
case clang::BuiltinType::OCLImage1dArrayRO:
case clang::BuiltinType::OCLImage1dArrayRW:
case clang::BuiltinType::OCLImage1dArrayWO:
case clang::BuiltinType::OCLImage1dBufferRO:
case clang::BuiltinType::OCLImage1dBufferRW:
case clang::BuiltinType::OCLImage1dBufferWO:
case clang::BuiltinType::OCLImage2dRO:
case clang::BuiltinType::OCLImage2dRW:
case clang::BuiltinType::OCLImage2dWO:
case clang::BuiltinType::OCLImage2dArrayRO:
case clang::BuiltinType::OCLImage2dArrayRW:
case clang::BuiltinType::OCLImage2dArrayWO:
case clang::BuiltinType::OCLImage2dDepthRO:
case clang::BuiltinType::OCLImage2dDepthRW:
case clang::BuiltinType::OCLImage2dDepthWO:
case clang::BuiltinType::OCLImage2dArrayDepthRO:
case clang::BuiltinType::OCLImage2dArrayDepthRW:
case clang::BuiltinType::OCLImage2dArrayDepthWO:
case clang::BuiltinType::OCLImage2dMSAARO:
case clang::BuiltinType::OCLImage2dMSAARW:
case clang::BuiltinType::OCLImage2dMSAAWO:
case clang::BuiltinType::OCLImage2dArrayMSAARO:
case clang::BuiltinType::OCLImage2dArrayMSAARW:
case clang::BuiltinType::OCLImage2dArrayMSAAWO:
case clang::BuiltinType::OCLImage2dMSAADepthRO:
case clang::BuiltinType::OCLImage2dMSAADepthRW:
case clang::BuiltinType::OCLImage2dMSAADepthWO:
case clang::BuiltinType::OCLImage2dArrayMSAADepthRO:
case clang::BuiltinType::OCLImage2dArrayMSAADepthRW:
case clang::BuiltinType::OCLImage2dArrayMSAADepthWO:
case clang::BuiltinType::OCLImage3dRO:
case clang::BuiltinType::OCLImage3dRW:
case clang::BuiltinType::OCLImage3dWO:
case clang::BuiltinType::OCLSampler:
case clang::BuiltinType::OCLEvent:
case clang::BuiltinType::OCLClkEvent:
case clang::BuiltinType::OCLQueue:
case clang::BuiltinType::OCLReserveID:
case clang::BuiltinType::OCLIntelSubgroupAVCMcePayload:
case clang::BuiltinType::OCLIntelSubgroupAVCImePayload:
case clang::BuiltinType::OCLIntelSubgroupAVCRefPayload:
case clang::BuiltinType::OCLIntelSubgroupAVCSicPayload:
case clang::BuiltinType::OCLIntelSubgroupAVCMceResult:
case clang::BuiltinType::OCLIntelSubgroupAVCImeResult:
case clang::BuiltinType::OCLIntelSubgroupAVCRefResult:
case clang::BuiltinType::OCLIntelSubgroupAVCSicResult:
case clang::BuiltinType::OCLIntelSubgroupAVCImeResultSingleReferenceStreamout:
case clang::BuiltinType::OCLIntelSubgroupAVCImeResultDualReferenceStreamout:
case clang::BuiltinType::OCLIntelSubgroupAVCImeSingleReferenceStreamin:
case clang::BuiltinType::OCLIntelSubgroupAVCImeDualReferenceStreamin:
llvm_unreachable("OpenCL type in ABI lowering");
// We should never see ARM SVE types at all.
#define SVE_TYPE(Name, Id, ...) case clang::BuiltinType::Id:
#include "clang/Basic/AArch64SVEACLETypes.def"
llvm_unreachable("ARM SVE type in ABI lowering");
// We should never see PPC MMA types at all.
#define PPC_VECTOR_TYPE(Name, Id, Size) case clang::BuiltinType::Id:
#include "clang/Basic/PPCTypes.def"
llvm_unreachable("PPC MMA type in ABI lowering");
// We should never see RISC-V V types at all.
#define RVV_TYPE(Name, Id, Size) case clang::BuiltinType::Id:
#include "clang/Basic/RISCVVTypes.def"
llvm_unreachable("RISC-V V type in ABI lowering");
#define WASM_TYPE(Name, Id, Size) case clang::BuiltinType::Id:
#include "clang/Basic/WebAssemblyReferenceTypes.def"
llvm_unreachable("WASM type in ABI lowering");
// Handle all the integer types as opaque values.
#define BUILTIN_TYPE(Id, SingletonId)
#define SIGNED_TYPE(Id, SingletonId) \
case clang::BuiltinType::Id:
#define UNSIGNED_TYPE(Id, SingletonId) \
case clang::BuiltinType::Id:
#include "clang/AST/BuiltinTypes.def"
return convertTypeAsInteger(type);
// Lower all the floating-point values by their semantics.
case clang::BuiltinType::Half:
return convertFloatingType(Ctx.getTargetInfo().getHalfFormat());
case clang::BuiltinType::Float:
return convertFloatingType(Ctx.getTargetInfo().getFloatFormat());
case clang::BuiltinType::Double:
return convertFloatingType(Ctx.getTargetInfo().getDoubleFormat());
case clang::BuiltinType::LongDouble:
return convertFloatingType(Ctx.getTargetInfo().getLongDoubleFormat());
case clang::BuiltinType::Float16:
llvm_unreachable("When upstream support is added for Float16 in "
"clang::TargetInfo, use the implementation here");
case clang::BuiltinType::BFloat16:
return convertFloatingType(Ctx.getTargetInfo().getBFloat16Format());
case clang::BuiltinType::Float128:
return convertFloatingType(Ctx.getTargetInfo().getFloat128Format());
case clang::BuiltinType::Ibm128:
return convertFloatingType(Ctx.getTargetInfo().getIbm128Format());
// nullptr_t -> void*
case clang::BuiltinType::NullPtr:
return IGM.Int8PtrTy;
}
llvm_unreachable("bad builtin type");
}
llvm::Type *convertFloatingType(const llvm::fltSemantics &format) {
if (&format == &llvm::APFloat::IEEEhalf())
return llvm::Type::getHalfTy(IGM.getLLVMContext());
if (&format == &llvm::APFloat::IEEEsingle())
return llvm::Type::getFloatTy(IGM.getLLVMContext());
if (&format == &llvm::APFloat::IEEEdouble())
return llvm::Type::getDoubleTy(IGM.getLLVMContext());
if (&format == &llvm::APFloat::IEEEquad())
return llvm::Type::getFP128Ty(IGM.getLLVMContext());
if (&format == &llvm::APFloat::PPCDoubleDouble())
return llvm::Type::getPPC_FP128Ty(IGM.getLLVMContext());
if (&format == &llvm::APFloat::x87DoubleExtended())
return llvm::Type::getX86_FP80Ty(IGM.getLLVMContext());
llvm_unreachable("bad float format");
}
llvm::Type *convertTypeAsInteger(clang::QualType type) {
auto size = getSizeOfType(type);
return llvm::IntegerType::get(IGM.getLLVMContext(),
size.getValueInBits());
}
};
/// A CRTP specialization of ClangExpand which projects down to
/// various aggregate elements of an address.
///
/// Subclasses should only have to define visitScalar.
template <class Impl>
class ClangExpandProjection : public ClangExpand<Impl, Address> {
using super = ClangExpand<Impl, Address>;
using super::asImpl;
using super::IGM;
using super::Ctx;
using super::getSizeOfType;
protected:
IRGenFunction &IGF;
ClangExpandProjection(IRGenFunction &IGF)
: super(IGF.IGM), IGF(IGF) {}
public:
void visit(clang::CanQualType type, Address addr) {
assert(addr.getType() == IGM.Int8PtrTy);
super::visit(type, addr);
}
Size beginArrayElements(clang::CanQualType element) {
return getSizeOfType(element);
}
void visitArrayElement(clang::CanQualType element, unsigned i,
Size elementSize, Address arrayAddr) {
asImpl().visit(element, createGEPAtOffset(arrayAddr, elementSize * i));
}
void visitComplexElement(clang::CanQualType element, unsigned i,
Address complexAddr) {
Address addr = complexAddr;
if (i) { addr = createGEPAtOffset(complexAddr, getSizeOfType(element)); }
asImpl().visit(element, addr);
}
void visitUnionField(const clang::RecordDecl *record,
const clang::FieldDecl *field,
Address structAddr) {
asImpl().visit(Ctx.getCanonicalType(field->getType()), structAddr);
}
const clang::ASTRecordLayout &
beginStructFields(const clang::RecordDecl *record) {
return Ctx.getASTRecordLayout(record);
}
void visitStructField(const clang::RecordDecl *record,
const clang::FieldDecl *field,
const clang::ASTRecordLayout &layout,
Address structAddr) {
auto fieldIndex = field->getFieldIndex();
assert(!field->isBitField());
auto fieldOffset = Size(layout.getFieldOffset(fieldIndex) / 8);
asImpl().visit(Ctx.getCanonicalType(field->getType()),
createGEPAtOffset(structAddr, fieldOffset));
}
private:
Address createGEPAtOffset(Address addr, Size offset) {
if (offset.isZero()) {
return addr;
} else {
return IGF.Builder.CreateConstByteArrayGEP(addr, offset);
}
}
};
/// A class for collecting the types of a Clang ABIArgInfo::Expand
/// argument expansion.
struct ClangExpandTypeCollector : ClangExpand<ClangExpandTypeCollector> {
SmallVectorImpl<llvm::Type*> &Types;
ClangExpandTypeCollector(IRGenModule &IGM,
SmallVectorImpl<llvm::Type*> &types)
: ClangExpand(IGM), Types(types) {}
bool beginArrayElements(clang::CanQualType element) { return true; }
void visitArrayElement(clang::CanQualType element, unsigned i, bool _) {
visit(element);
}
void visitComplexElement(clang::CanQualType element, unsigned i) {
visit(element);
}
void visitUnionField(const clang::RecordDecl *record,
const clang::FieldDecl *field) {
visit(Ctx.getCanonicalType(field->getType()));
}
bool beginStructFields(const clang::RecordDecl *record) { return true; }
void visitStructField(const clang::RecordDecl *record,
const clang::FieldDecl *field,
bool _) {
visit(Ctx.getCanonicalType(field->getType()));
}
void visitScalar(llvm::Type *type) {
Types.push_back(type);
}
};
} // end anonymous namespace
static bool doesClangExpansionMatchSchema(IRGenModule &IGM,
clang::CanQualType type,
const ExplosionSchema &schema) {
assert(!schema.containsAggregate());
SmallVector<llvm::Type *, 4> expansion;
ClangExpandTypeCollector(IGM, expansion).visit(type);
if (expansion.size() != schema.size())
return false;
for (size_t i = 0, e = schema.size(); i != e; ++i) {
if (schema[i].getScalarType() != expansion[i])
return false;
}
return true;
}
/// Expand the result and parameter types to the appropriate LLVM IR
/// types for C, C++ and Objective-C signatures.
void SignatureExpansion::expandExternalSignatureTypes() {
assert(FnType->getLanguage() == SILFunctionLanguage::C);
auto SILResultTy = [&]() {
if (FnType->getNumResults() == 0)
return SILType::getPrimitiveObjectType(IGM.Context.TheEmptyTupleType);
return SILType::getPrimitiveObjectType(
FnType->getSingleResult().getReturnValueType(
IGM.getSILModule(), FnType, TypeExpansionContext::minimal()));
}();
// Convert the SIL result type to a Clang type. If this is for a c++
// constructor, use 'void' as the return type to arrange the function type.
auto clangResultTy = IGM.getClangType(
cxxCtorDecl
? SILType::getPrimitiveObjectType(IGM.Context.TheEmptyTupleType)
: SILResultTy);
// Now convert the parameters to Clang types.
auto params = FnType->getParameters();
SmallVector<clang::CanQualType,4> paramTys;
auto const &clangCtx = IGM.getClangASTContext();
switch (FnType->getRepresentation()) {
case SILFunctionTypeRepresentation::ObjCMethod: {
// ObjC methods take their 'self' argument first, followed by an
// implicit _cmd argument.
auto &self = params.back();
auto clangTy = IGM.getClangType(self, FnType);
paramTys.push_back(clangTy);
if (!forStaticCall) // objc_direct methods don't have the _cmd argumment.
paramTys.push_back(clangCtx.VoidPtrTy);
params = params.drop_back();
break;
}
case SILFunctionTypeRepresentation::Block:
// Blocks take their context argument first.
paramTys.push_back(clangCtx.VoidPtrTy);
break;
case SILFunctionTypeRepresentation::CXXMethod: {
// Cxx methods take their 'self' argument first.
auto &self = params.back();
auto clangTy = IGM.getClangType(self, FnType);
paramTys.push_back(clangTy);
params = params.drop_back();
break;
}
case SILFunctionTypeRepresentation::CFunctionPointer:
if (cxxCtorDecl) {
auto clangTy = IGM.getClangASTContext().getPointerType(
IGM.getClangType(SILResultTy));
paramTys.push_back(clangTy);
}
break;
case SILFunctionTypeRepresentation::Thin:
case SILFunctionTypeRepresentation::Thick:
case SILFunctionTypeRepresentation::Method:
case SILFunctionTypeRepresentation::WitnessMethod:
case SILFunctionTypeRepresentation::Closure:
case SILFunctionTypeRepresentation::KeyPathAccessorGetter:
case SILFunctionTypeRepresentation::KeyPathAccessorSetter:
case SILFunctionTypeRepresentation::KeyPathAccessorEquals:
case SILFunctionTypeRepresentation::KeyPathAccessorHash:
llvm_unreachable("not a C representation");
}
// Given an index within the clang parameters list, what do we need
// to subtract from it to get to the corresponding index within the
// Swift parameters list?
size_t clangToSwiftParamOffset = paramTys.size();
// Convert each parameter to a Clang type.
for (auto param : params) {
auto clangTy = IGM.getClangType(param, FnType);
paramTys.push_back(clangTy);
}
// Generate function info for this signature.
auto extInfo = clang::FunctionType::ExtInfo();
bool isCXXMethod =
FnType->getRepresentation() == SILFunctionTypeRepresentation::CXXMethod;
auto &FI = isCXXMethod ?
clang::CodeGen::arrangeCXXMethodCall(IGM.ClangCodeGen->CGM(),
clangResultTy, paramTys, extInfo, {},
clang::CodeGen::RequiredArgs::All) :
clang::CodeGen::arrangeFreeFunctionCall(IGM.ClangCodeGen->CGM(),
clangResultTy, paramTys, extInfo, {},
clang::CodeGen::RequiredArgs::All);
ForeignInfo.ClangInfo = &FI;
assert(FI.arg_size() == paramTys.size() &&
"Expected one ArgInfo for each parameter type!");
auto &returnInfo = FI.getReturnInfo();
#ifndef NDEBUG
bool formalIndirectResult = FnType->getNumResults() > 0 &&
FnType->getSingleResult().isFormalIndirect();
assert(
(cxxCtorDecl || !formalIndirectResult || returnInfo.isIndirect()) &&
"swift and clang disagree on whether the result is returned indirectly");
#endif
// Does the result need an extension attribute?
if (returnInfo.isExtend()) {
bool signExt = clangResultTy->hasSignedIntegerRepresentation();
assert((signExt || clangResultTy->hasUnsignedIntegerRepresentation()) &&
"Invalid attempt to add extension attribute to argument!");
Attrs = Attrs.addRetAttribute(IGM.getLLVMContext(),
attrKindForExtending(signExt));
}
auto emitArg = [&](size_t i) {
auto &AI = FI.arg_begin()[i].info;
// Add a padding argument if required.
if (auto *padType = AI.getPaddingType())
ParamIRTypes.push_back(padType);
switch (AI.getKind()) {
case clang::CodeGen::ABIArgInfo::Extend: {
bool signExt = paramTys[i]->hasSignedIntegerRepresentation();
assert((signExt || paramTys[i]->hasUnsignedIntegerRepresentation()) &&
"Invalid attempt to add extension attribute to argument!");
Attrs = Attrs.addParamAttribute(IGM.getLLVMContext(), getCurParamIndex(),
attrKindForExtending(signExt));
LLVM_FALLTHROUGH;
}
case clang::CodeGen::ABIArgInfo::Direct: {
switch (FI.getExtParameterInfo(i).getABI()) {
case clang::ParameterABI::Ordinary:
break;
case clang::ParameterABI::SwiftAsyncContext:
IGM.addSwiftAsyncContextAttributes(Attrs, getCurParamIndex());
break;
case clang::ParameterABI::SwiftContext:
IGM.addSwiftSelfAttributes(Attrs, getCurParamIndex());
break;
case clang::ParameterABI::SwiftErrorResult:
IGM.addSwiftErrorAttributes(Attrs, getCurParamIndex());
break;
case clang::ParameterABI::SwiftIndirectResult: {
auto ¶m = params[i - clangToSwiftParamOffset];
auto paramTy = getSILFuncConventions().getSILType(
param, IGM.getMaximalTypeExpansionContext());
auto ¶mTI = cast<FixedTypeInfo>(IGM.getTypeInfo(paramTy));
addIndirectResultAttributes(IGM, Attrs, getCurParamIndex(), claimSRet(),
paramTI.getStorageType(), paramTI);
break;
}
}
// If the coercion type is a struct which can be flattened, we need to
// expand it.
auto *coercedTy = AI.getCoerceToType();
if (AI.isDirect() && AI.getCanBeFlattened() &&
isa<llvm::StructType>(coercedTy)) {
const auto *ST = cast<llvm::StructType>(coercedTy);
for (unsigned EI : range(ST->getNumElements()))
ParamIRTypes.push_back(ST->getElementType(EI));
} else {
ParamIRTypes.push_back(coercedTy);
}
break;
}
case clang::CodeGen::ABIArgInfo::CoerceAndExpand: {
auto types = AI.getCoerceAndExpandTypeSequence();
ParamIRTypes.append(types.begin(), types.end());
break;
}
case clang::CodeGen::ABIArgInfo::IndirectAliased:
llvm_unreachable("not implemented");
case clang::CodeGen::ABIArgInfo::Indirect: {
// When `i` is 0, if the clang offset is 1, that means we mapped the last
// Swift parameter (self) to the first Clang parameter (this). In this
// case, the corresponding Swift param is the last function parameter.
assert((i >= clangToSwiftParamOffset || clangToSwiftParamOffset == 1) &&
"Unexpected index for indirect byval argument");
auto ¶m = i < clangToSwiftParamOffset
? FnType->getParameters().back()
: params[i - clangToSwiftParamOffset];
auto paramTy = getSILFuncConventions().getSILType(
param, IGM.getMaximalTypeExpansionContext());
auto ¶mTI = cast<FixedTypeInfo>(IGM.getTypeInfo(paramTy));
if (AI.getIndirectByVal() && !paramTy.isForeignReferenceType()) {
addByvalArgumentAttributes(
IGM, Attrs, getCurParamIndex(),
Alignment(AI.getIndirectAlign().getQuantity()),
paramTI.getStorageType());
}
addPointerParameter(paramTI.getStorageType());
break;
}
case clang::CodeGen::ABIArgInfo::Expand:
ClangExpandTypeCollector(IGM, ParamIRTypes).visit(paramTys[i]);
break;
case clang::CodeGen::ABIArgInfo::Ignore:
break;
case clang::CodeGen::ABIArgInfo::InAlloca:
llvm_unreachable("Need to handle InAlloca during signature expansion");
}
};
size_t firstParamToLowerNormally = 0;
// If we return indirectly, that is the first parameter type.
if (returnInfo.isIndirect()) {
auto resultType = getSILFuncConventions().getSingleSILResultType(
IGM.getMaximalTypeExpansionContext());
if (returnInfo.isSRetAfterThis()) {
// Windows ABI places `this` before the
// returned indirect values.
emitArg(0);
firstParamToLowerNormally = 1;
addIndirectResult(resultType, returnInfo.getInReg());
} else
addIndirectResult(resultType, returnInfo.getInReg());
}
// Use a special IR type for passing block pointers.
if (FnType->getRepresentation() == SILFunctionTypeRepresentation::Block) {
assert(FI.arg_begin()[0].info.isDirect() &&
"block pointer not passed directly?");
ParamIRTypes.push_back(IGM.ObjCBlockPtrTy);
firstParamToLowerNormally = 1;
}
for (auto i : indices(paramTys).slice(firstParamToLowerNormally))
emitArg(i);
if (cxxCtorDecl) {
ResultIRType = cast<llvm::Function>(IGM.getAddrOfClangGlobalDecl(
{cxxCtorDecl, clang::Ctor_Complete},
(ForDefinition_t) false))
->getReturnType();
} else if (returnInfo.isIndirect() || returnInfo.isIgnore()) {
ResultIRType = IGM.VoidTy;
} else {
ResultIRType = returnInfo.getCoerceToType();
}
}
static ArrayRef<llvm::Type *> expandScalarOrStructTypeToArray(llvm::Type *&ty) {
ArrayRef<llvm::Type*> expandedTys;
if (auto expansionTy = dyn_cast<llvm::StructType>(ty)) {
// Is there any good reason this isn't public API of llvm::StructType?
expandedTys = llvm::ArrayRef(expansionTy->element_begin(),
expansionTy->getNumElements());
} else {
expandedTys = ty;
}
return expandedTys;
}
const TypeInfo &SignatureExpansion::expand(SILParameterInfo param) {
auto paramSILType = getSILFuncConventions().getSILType(
param, IGM.getMaximalTypeExpansionContext());
auto &ti = IGM.getTypeInfo(paramSILType);
switch (auto conv = param.getConvention()) {
case ParameterConvention::Indirect_In:
case ParameterConvention::Indirect_In_Guaranteed:
addIndirectValueParameterAttributes(IGM, Attrs, ti, ParamIRTypes.size());
addPointerParameter(IGM.getStorageType(getSILFuncConventions().getSILType(
param, IGM.getMaximalTypeExpansionContext())));
return ti;
case ParameterConvention::Indirect_Inout:
case ParameterConvention::Indirect_InoutAliasable:
addInoutParameterAttributes(
IGM, paramSILType, Attrs, ti, ParamIRTypes.size(),
conv == ParameterConvention::Indirect_InoutAliasable);
addPointerParameter(IGM.getStorageType(getSILFuncConventions().getSILType(
param, IGM.getMaximalTypeExpansionContext())));
return ti;
case ParameterConvention::Pack_Guaranteed:
case ParameterConvention::Pack_Owned:
case ParameterConvention::Pack_Inout:
addPackParameterAttributes(IGM, paramSILType, Attrs, ParamIRTypes.size());
addPointerParameter(ti.getStorageType());
return ti;
case ParameterConvention::Direct_Owned:
case ParameterConvention::Direct_Unowned:
case ParameterConvention::Direct_Guaranteed:
switch (FnType->getLanguage()) {
case SILFunctionLanguage::C: {
llvm_unreachable("Unexpected C/ObjC method in parameter expansion!");
return ti;
}
case SILFunctionLanguage::Swift: {
auto &nativeSchema = ti.nativeParameterValueSchema(IGM);
if (nativeSchema.requiresIndirect()) {
addIndirectValueParameterAttributes(IGM, Attrs, ti,
ParamIRTypes.size());
ParamIRTypes.push_back(ti.getStorageType()->getPointerTo());
return ti;
}
if (nativeSchema.empty()) {
assert(ti.getSchema().empty());
return ti;
}
auto expandedTy = nativeSchema.getExpandedType(IGM);
auto expandedTysArray = expandScalarOrStructTypeToArray(expandedTy);
for (auto *Ty : expandedTysArray)
ParamIRTypes.push_back(Ty);
return ti;
}
}
llvm_unreachable("bad abstract CC");
}
llvm_unreachable("bad parameter convention");
}
/// Does the given function type have a self parameter that should be
/// given the special treatment for self parameters?
///
/// It's important that this only return true for things that are
/// passed as a single pointer.
bool irgen::hasSelfContextParameter(CanSILFunctionType fnType) {
if (!fnType->hasSelfParam())
return false;
SILParameterInfo param = fnType->getSelfParameter();
// All the indirect conventions pass a single pointer.
if (param.isFormalIndirect()) {
return true;
}
// Direct conventions depend on the type.
CanType type = param.getInterfaceType();
// Thick or @objc metatypes (but not existential metatypes).
if (auto metatype = dyn_cast<MetatypeType>(type)) {
return metatype->getRepresentation() != MetatypeRepresentation::Thin;
}
// Classes and class-bounded archetypes or ObjC existentials.
// No need to apply this to existentials.
// The direct check for SubstitutableType works because only
// class-bounded generic types can be passed directly.
if (type->mayHaveSuperclass() || isa<SubstitutableType>(type) ||
type->isObjCExistentialType()) {
return true;
}
return false;
}
static void addParamInfo(SignatureExpansionABIDetails *details,
const TypeInfo &ti, ParameterConvention convention) {
if (!details)
return;
details->parameters.push_back(
SignatureExpansionABIDetails::Parameter(ti, convention));
}
void SignatureExpansion::expandKeyPathAccessorParameters() {
auto params = FnType->getParameters();
unsigned numArgsToExpand;
SmallVector<llvm::Type *, 4> tailParams;
switch (FnType->getRepresentation()) {
case SILFunctionTypeRepresentation::KeyPathAccessorGetter:
// from: (base: CurValue, indices: (X, Y, ...))
// to: (base: CurValue, argument: UnsafeRawPointer, size: Int)
numArgsToExpand = 1;
tailParams.push_back(IGM.Int8PtrTy);
tailParams.push_back(IGM.SizeTy);
break;
case SILFunctionTypeRepresentation::KeyPathAccessorSetter:
// from: (value: NewValue, base: CurValue, indices: (X, Y, ...))
// to: (value: NewValue, base: CurValue, argument: UnsafeRawPointer, size: Int)
numArgsToExpand = 2;
tailParams.push_back(IGM.Int8PtrTy);
tailParams.push_back(IGM.SizeTy);
break;
case SILFunctionTypeRepresentation::KeyPathAccessorEquals:
// from: (lhsIndices: (X, Y, ...), rhsIndices: (X, Y, ...))
// to: (lhsArguments: UnsafeRawPointer, rhsArguments: UnsafeRawPointer, size: Int)
numArgsToExpand = 0;
tailParams.push_back(IGM.Int8PtrTy);
tailParams.push_back(IGM.Int8PtrTy);
tailParams.push_back(IGM.SizeTy);
break;
case SILFunctionTypeRepresentation::KeyPathAccessorHash:
// from: (indices: (X, Y, ...))
// to: (instanceArguments: UnsafeRawPointer, size: Int)
numArgsToExpand = 0;
tailParams.push_back(IGM.Int8PtrTy);
tailParams.push_back(IGM.SizeTy);
break;
case SILFunctionTypeRepresentation::Thick:
case SILFunctionTypeRepresentation::Block:
case SILFunctionTypeRepresentation::Thin:
case SILFunctionTypeRepresentation::Method:
case SILFunctionTypeRepresentation::ObjCMethod:
case SILFunctionTypeRepresentation::WitnessMethod:
case SILFunctionTypeRepresentation::CFunctionPointer:
case SILFunctionTypeRepresentation::Closure:
case SILFunctionTypeRepresentation::CXXMethod:
llvm_unreachable("non keypath accessor convention");
}
for (unsigned i = 0; i < numArgsToExpand; i++) {
expand(params[i]);
}
for (auto tailParam : tailParams) {
ParamIRTypes.push_back(tailParam);
}
}
/// Expand the abstract parameters of a SIL function type into the physical
/// parameters of an LLVM function type (results have already been expanded).
void SignatureExpansion::expandParameters(
SignatureExpansionABIDetails *recordedABIDetails) {
assert(FnType->getRepresentation() != SILFunctionTypeRepresentation::Block
&& "block with non-C calling conv?!");
if (FnType->isAsync()) {
assert(false && "Should not use expandParameters for async functions");
return;
}
// First, if this is a coroutine, add the coroutine-context parameter.
switch (FnType->getCoroutineKind()) {
case SILCoroutineKind::None:
break;
case SILCoroutineKind::YieldOnce:
case SILCoroutineKind::YieldMany:
addCoroutineContextParameter();
break;
}
// Next, the formal parameters. But 'self' is treated as the
// context if it has pointer representation.
auto params = FnType->getParameters();
bool hasSelfContext = false;
if (hasSelfContextParameter(FnType)) {
hasSelfContext = true;
params = params.drop_back();
}
for (auto param : params) {
const TypeInfo &ti = expand(param);
addParamInfo(recordedABIDetails, ti, param.getConvention());
}
if (recordedABIDetails && FnType->hasSelfParam() && !hasSelfContext)
recordedABIDetails->parameters.back().isSelf = true;
// Next, the generic signature.
if (hasPolymorphicParameters(FnType) &&
!FnKind.shouldSuppressPolymorphicArguments())
expandPolymorphicSignature(
IGM, FnType, ParamIRTypes,
recordedABIDetails
? &recordedABIDetails->polymorphicSignatureExpandedTypeSources
: nullptr);
// Certain special functions are passed the continuation directly.
if (FnKind.shouldPassContinuationDirectly()) {
ParamIRTypes.push_back(IGM.Int8PtrTy);
ParamIRTypes.push_back(IGM.SwiftContextPtrTy);
}
// Context is next.
if (hasSelfContext) {
auto curLength = ParamIRTypes.size(); (void) curLength;
if (claimSelf())
IGM.addSwiftSelfAttributes(Attrs, curLength);
expand(FnType->getSelfParameter());
if (recordedABIDetails)
recordedABIDetails->hasTrailingSelfParam = true;
assert(ParamIRTypes.size() == curLength + 1 &&
"adding 'self' added unexpected number of parameters");
} else {
auto needsContext = [=]() -> bool {
switch (FnType->getRepresentation()) {
case SILFunctionType::Representation::Block:
llvm_unreachable("adding block parameter in Swift CC expansion?");
// Always leave space for a context argument if we have an error result.
case SILFunctionType::Representation::CFunctionPointer:
case SILFunctionType::Representation::Method:
case SILFunctionType::Representation::WitnessMethod:
case SILFunctionType::Representation::ObjCMethod:
case SILFunctionType::Representation::CXXMethod:
case SILFunctionType::Representation::Thin:
case SILFunctionType::Representation::Closure:
return FnType->hasErrorResult();
// KeyPath accessor always has no context.
case SILFunctionType::Representation::KeyPathAccessorGetter:
case SILFunctionType::Representation::KeyPathAccessorSetter:
case SILFunctionType::Representation::KeyPathAccessorEquals:
case SILFunctionType::Representation::KeyPathAccessorHash:
return false;
case SILFunctionType::Representation::Thick:
return true;
}
llvm_unreachable("bad representation kind");
};
if (needsContext()) {
if (claimSelf())
IGM.addSwiftSelfAttributes(Attrs, ParamIRTypes.size());
ParamIRTypes.push_back(IGM.RefCountedPtrTy);
if (recordedABIDetails)
recordedABIDetails->hasContextParam = true;
}
}
// Error results are last. We always pass them as a pointer to the
// formal error type; LLVM will magically turn this into a non-pointer
// if we set the right attribute.
if (FnType->hasErrorResult()) {
if (claimError())
IGM.addSwiftErrorAttributes(Attrs, ParamIRTypes.size());
llvm::Type *errorType = getErrorRegisterType();
ParamIRTypes.push_back(errorType->getPointerTo());
if (recordedABIDetails)
recordedABIDetails->hasErrorResult = true;
if (getSILFuncConventions().isTypedError()) {
ParamIRTypes.push_back(
IGM.getStorageType(getSILFuncConventions().getSILType(
FnType->getErrorResult(), IGM.getMaximalTypeExpansionContext())
)->getPointerTo());
}
}
// Witness methods have some extra parameter types.
if (FnType->getRepresentation() ==
SILFunctionTypeRepresentation::WitnessMethod) {
expandTrailingWitnessSignature(IGM, FnType, ParamIRTypes);
}
}
/// Expand the result and parameter types of a SIL function into the
/// physical parameter types of an LLVM function and return the result
/// type.
void SignatureExpansion::expandFunctionType(
SignatureExpansionABIDetails *recordedABIDetails) {
switch (FnType->getLanguage()) {
case SILFunctionLanguage::Swift: {
if (FnType->isAsync()) {
expandAsyncEntryType();
return;
}
expandResult(recordedABIDetails);
switch (FnType->getRepresentation()) {
case SILFunctionTypeRepresentation::KeyPathAccessorGetter:
case SILFunctionTypeRepresentation::KeyPathAccessorSetter:
case SILFunctionTypeRepresentation::KeyPathAccessorEquals:
case SILFunctionTypeRepresentation::KeyPathAccessorHash:
expandKeyPathAccessorParameters();
break;
default:
expandParameters(recordedABIDetails);
break;
}
return;
}
case SILFunctionLanguage::C:
expandExternalSignatureTypes();
return;
}
llvm_unreachable("bad abstract calling convention");
}
void SignatureExpansion::expandCoroutineContinuationType() {
expandCoroutineResult(/*for continuation*/ true);
expandCoroutineContinuationParameters();
}
llvm::Type *SignatureExpansion::getErrorRegisterType() {
if (getSILFuncConventions().isTypedError())
return IGM.Int8PtrTy;
return IGM.getStorageType(getSILFuncConventions().getSILType(
FnType->getErrorResult(), IGM.getMaximalTypeExpansionContext()));
}
void SignatureExpansion::expandAsyncReturnType() {
// Build up the signature of the return continuation function.
// void (AsyncTask *, SerialExecutorRef, AsyncContext *, DirectResult0, ...,
// DirectResultN, Error*);
ResultIRType = IGM.VoidTy;
addAsyncParameters();
SmallVector<llvm::Type *, 8> components;
auto addErrorResult = [&]() {
// Add the error pointer at the end.
if (FnType->hasErrorResult()) {
llvm::Type *errorType = getErrorRegisterType();
claimSelf();
auto selfIdx = ParamIRTypes.size();
IGM.addSwiftSelfAttributes(Attrs, selfIdx);
AsyncResumeFunctionSwiftSelfIdx = selfIdx;
ParamIRTypes.push_back(errorType);
}
};
auto resultType = getSILFuncConventions().getSILResultType(
IGM.getMaximalTypeExpansionContext());
auto &ti = IGM.getTypeInfo(resultType);
auto &native = ti.nativeReturnValueSchema(IGM);
if (native.requiresIndirect() || native.empty()) {
addErrorResult();
return;
}
// Add the result type components as trailing parameters.
native.enumerateComponents(
[&](clang::CharUnits offset, clang::CharUnits end, llvm::Type *type) {
ParamIRTypes.push_back(type);
});
addErrorResult();
}
void SignatureExpansion::addIndirectThrowingResult() {
if (getSILFuncConventions().funcTy->hasErrorResult() &&
getSILFuncConventions().isTypedError()) {
auto resultType = getSILFuncConventions().getSILErrorType(
IGM.getMaximalTypeExpansionContext());
const TypeInfo &resultTI = IGM.getTypeInfo(resultType);
auto storageTy = resultTI.getStorageType();
ParamIRTypes.push_back(storageTy->getPointerTo());
}
}
void SignatureExpansion::expandAsyncEntryType() {
ResultIRType = IGM.VoidTy;
// FIXME: Claim the SRet for now. The way we have set up the function type to
// start with the three async specific arguments does not allow for use of
// sret.
CanUseSRet = false;
// Add the indirect 'direct' result type.
auto resultType = getSILFuncConventions().getSILResultType(
IGM.getMaximalTypeExpansionContext());
auto &ti = IGM.getTypeInfo(resultType);
auto &native = ti.nativeReturnValueSchema(IGM);
if (native.requiresIndirect())
addIndirectResult(resultType);
// Add the indirect result types.
expandIndirectResults();
// Add the async context parameter.
addAsyncParameters();
// Add the parameters.
auto params = FnType->getParameters();
auto hasSelfContext = false;
if (hasSelfContextParameter(FnType)) {
hasSelfContext = true;
params = params.drop_back();
}
for (auto param : params) {
expand(param);
}
// Next, the generic signature.
if (hasPolymorphicParameters(FnType) &&
!FnKind.shouldSuppressPolymorphicArguments())
expandPolymorphicSignature(IGM, FnType, ParamIRTypes);
if (FnKind.shouldPassContinuationDirectly()) {
// Async waiting functions add the resume function pointer.
// (But skip passing the metadata.)
ParamIRTypes.push_back(IGM.Int8PtrTy);
ParamIRTypes.push_back(IGM.SwiftContextPtrTy);
}
// Context is next.
if (hasSelfContext) {
auto curLength = ParamIRTypes.size();
(void)curLength;
expand(FnType->getSelfParameter());
assert(ParamIRTypes.size() == curLength + 1 &&
"adding 'self' added unexpected number of parameters");
if (claimSelf())
IGM.addSwiftSelfAttributes(Attrs, curLength);
} else {
auto needsContext = [=]() -> bool {
switch (FnType->getRepresentation()) {
case SILFunctionType::Representation::Block:
llvm_unreachable("adding block parameter in Swift CC expansion?");
// Always leave space for a context argument if we have an error result.
case SILFunctionType::Representation::CFunctionPointer:
case SILFunctionType::Representation::Method:
case SILFunctionType::Representation::WitnessMethod:
case SILFunctionType::Representation::ObjCMethod:
case SILFunctionType::Representation::Thin:
case SILFunctionType::Representation::Closure:
case SILFunctionType::Representation::CXXMethod:
case SILFunctionType::Representation::KeyPathAccessorGetter:
case SILFunctionType::Representation::KeyPathAccessorSetter:
case SILFunctionType::Representation::KeyPathAccessorEquals:
case SILFunctionType::Representation::KeyPathAccessorHash:
return false;
case SILFunctionType::Representation::Thick:
return true;
}
llvm_unreachable("bad representation kind");
};
if (needsContext()) {
if (claimSelf())
IGM.addSwiftSelfAttributes(Attrs, ParamIRTypes.size());
ParamIRTypes.push_back(IGM.RefCountedPtrTy);
}
}
addIndirectThrowingResult();
// For now we continue to store the error result in the context to be able to
// reuse non throwing functions.
// Witness methods have some extra parameter types.
if (FnType->getRepresentation() ==
SILFunctionTypeRepresentation::WitnessMethod) {
expandTrailingWitnessSignature(IGM, FnType, ParamIRTypes);
}
}
void SignatureExpansion::expandAsyncAwaitType() {
expandAsyncEntryType();
SmallVector<llvm::Type *, 8> components;
// Async context.
AsyncContextIdx = 0;
components.push_back(IGM.Int8PtrTy);
auto addErrorResult = [&]() {
if (FnType->hasErrorResult()) {
llvm::Type *errorType = getErrorRegisterType();
IGM.getStorageType(getSILFuncConventions().getSILType(
FnType->getErrorResult(), IGM.getMaximalTypeExpansionContext()));
auto selfIdx = components.size();
AsyncResumeFunctionSwiftSelfIdx = selfIdx;
components.push_back(errorType);
}
};
// Direct result type as arguments.
auto resultType = getSILFuncConventions().getSILResultType(
IGM.getMaximalTypeExpansionContext());
auto &ti = IGM.getTypeInfo(resultType);
auto &native = ti.nativeReturnValueSchema(IGM);
if (native.requiresIndirect() || native.empty()) {
addErrorResult();
ResultIRType = llvm::StructType::get(IGM.getLLVMContext(), components);
return;
}
// Add the result type components as trailing parameters.
native.enumerateComponents(
[&](clang::CharUnits offset, clang::CharUnits end, llvm::Type *type) {
components.push_back(type);
});
addErrorResult();
ResultIRType = llvm::StructType::get(IGM.getLLVMContext(), components);
}
Signature SignatureExpansion::getSignature() {
// Create the appropriate LLVM type.
llvm::FunctionType *llvmType =
llvm::FunctionType::get(ResultIRType, ParamIRTypes, /*variadic*/ false);
assert((ForeignInfo.ClangInfo != nullptr) ==
(FnType->getLanguage() == SILFunctionLanguage::C) &&
"C function type without C function info");
auto callingConv =
expandCallingConv(IGM, FnType->getRepresentation(), FnType->isAsync());
Signature result;
result.Type = llvmType;
result.CallingConv = callingConv;
result.Attributes = Attrs;
using ExtraData = Signature::ExtraData;
if (FnType->getLanguage() == SILFunctionLanguage::C) {
// This is a potentially throwing function. The use of 'noexcept' /
// 'nothrow' is applied at the call site in the \c FunctionPointer class.
ForeignInfo.canThrow = IGM.isForeignExceptionHandlingEnabled();
result.ExtraDataKind = ExtraData::kindForMember<ForeignFunctionInfo>();
result.ExtraDataStorage.emplace<ForeignFunctionInfo>(result.ExtraDataKind,
ForeignInfo);
} else if (FnType->isCoroutine()) {
result.ExtraDataKind = ExtraData::kindForMember<CoroutineInfo>();
result.ExtraDataStorage.emplace<CoroutineInfo>(result.ExtraDataKind,
CoroInfo);
} else if (FnType->isAsync()) {
result.ExtraDataKind = ExtraData::kindForMember<AsyncInfo>();
AsyncInfo info;
info.AsyncContextIdx = AsyncContextIdx;
info.AsyncResumeFunctionSwiftSelfIdx = AsyncResumeFunctionSwiftSelfIdx;
result.ExtraDataStorage.emplace<AsyncInfo>(result.ExtraDataKind, info);
} else {
result.ExtraDataKind = ExtraData::kindForMember<void>();
}
return result;
}
Signature Signature::getUncached(IRGenModule &IGM,
CanSILFunctionType formalType,
FunctionPointerKind fpKind, bool forStaticCall,
const clang::CXXConstructorDecl *cxxCtorDecl) {
GenericContextScope scope(IGM, formalType->getInvocationGenericSignature());
SignatureExpansion expansion(IGM, formalType, fpKind, forStaticCall,
cxxCtorDecl);
expansion.expandFunctionType();
return expansion.getSignature();
}
SignatureExpansionABIDetails Signature::getUncachedABIDetails(
IRGenModule &IGM, CanSILFunctionType formalType, FunctionPointerKind kind) {
GenericContextScope scope(IGM, formalType->getInvocationGenericSignature());
SignatureExpansion expansion(IGM, formalType, kind);
SignatureExpansionABIDetails result;
expansion.expandFunctionType(&result);
result.numParamIRTypesInSignature = expansion.ParamIRTypes.size();
return result;
}
Signature Signature::forCoroutineContinuation(IRGenModule &IGM,
CanSILFunctionType fnType) {
assert(fnType->isCoroutine());
SignatureExpansion expansion(IGM, fnType, FunctionPointerKind(fnType));
expansion.expandCoroutineContinuationType();
return expansion.getSignature();
}
Signature Signature::forAsyncReturn(IRGenModule &IGM,
CanSILFunctionType fnType) {
assert(fnType->isAsync());
GenericContextScope scope(IGM, fnType->getInvocationGenericSignature());
SignatureExpansion expansion(IGM, fnType, FunctionPointerKind(fnType));
expansion.expandAsyncReturnType();
return expansion.getSignature();
}
Signature Signature::forAsyncAwait(IRGenModule &IGM, CanSILFunctionType fnType,
FunctionPointerKind fnKind) {
assert(fnType->isAsync());
GenericContextScope scope(IGM, fnType->getInvocationGenericSignature());
SignatureExpansion expansion(IGM, fnType, fnKind);
expansion.expandAsyncAwaitType();
return expansion.getSignature();
}
Signature Signature::forAsyncEntry(IRGenModule &IGM, CanSILFunctionType fnType,
FunctionPointerKind fnKind) {
assert(fnType->isAsync());
GenericContextScope scope(IGM, fnType->getInvocationGenericSignature());
SignatureExpansion expansion(IGM, fnType, fnKind);
expansion.expandAsyncEntryType();
return expansion.getSignature();
}
void irgen::extractScalarResults(IRGenFunction &IGF, llvm::Type *bodyType,
llvm::Value *call, Explosion &out) {
assert(!bodyType->isVoidTy() && "Unexpected void result type!");
auto *returned = call;
auto *callType = call->getType();
// If the type of the result of the call differs from the type used
// elsewhere in the caller due to ABI type coercion, we need to
// coerce the result back from the ABI type before extracting the
// elements.
if (bodyType != callType)
returned = IGF.coerceValue(returned, bodyType, IGF.IGM.DataLayout);
if (auto *structType = dyn_cast<llvm::StructType>(bodyType))
IGF.emitAllExtractValues(returned, structType, out);
else
out.add(returned);
}
void IRGenFunction::emitAllExtractValues(llvm::Value *value,
llvm::StructType *structType,
Explosion &out) {
assert(value->getType() == structType);
for (unsigned i = 0, e = structType->getNumElements(); i != e; ++i)
out.add(Builder.CreateExtractValue(value, i));
}
namespace {
// TODO(compnerd) analyze if this should be out-lined via a runtime call rather
// than be open-coded. This needs to account for the fact that we are able to
// statically optimize this often times due to CVP changing the select to a
// `select i1 true, ...`.
llvm::Value *emitIndirectAsyncFunctionPointer(IRGenFunction &IGF,
llvm::Value *pointer) {
llvm::IntegerType *IntPtrTy = IGF.IGM.IntPtrTy;
llvm::Type *AsyncFunctionPointerPtrTy = IGF.IGM.AsyncFunctionPointerPtrTy;
llvm::Constant *Zero =
llvm::Constant::getIntegerValue(IntPtrTy, APInt(IntPtrTy->getBitWidth(),
0));
llvm::Constant *One =
llvm::Constant::getIntegerValue(IntPtrTy, APInt(IntPtrTy->getBitWidth(),
1));
llvm::Constant *NegativeOne =
llvm::Constant::getIntegerValue(IntPtrTy, APInt(IntPtrTy->getBitWidth(),
-2));
swift::irgen::Alignment PointerAlignment = IGF.IGM.getPointerAlignment();
llvm::Value *PtrToInt = IGF.Builder.CreatePtrToInt(pointer, IntPtrTy);
llvm::Value *And = IGF.Builder.CreateAnd(PtrToInt, One);
llvm::Value *ICmp = IGF.Builder.CreateICmpEQ(And, Zero);
llvm::Value *BitCast =
IGF.Builder.CreateBitCast(pointer, AsyncFunctionPointerPtrTy);
llvm::Value *UntaggedPointer = IGF.Builder.CreateAnd(PtrToInt, NegativeOne);
llvm::Value *IntToPtr =
IGF.Builder.CreateIntToPtr(UntaggedPointer,
AsyncFunctionPointerPtrTy->getPointerTo());
llvm::Value *Load = IGF.Builder.CreateLoad(
IntToPtr, AsyncFunctionPointerPtrTy, PointerAlignment);
// (select (icmp eq, (and (ptrtoint %AsyncFunctionPointer), 1), 0),
// (%AsyncFunctionPointer),
// (inttoptr (and (ptrtoint %AsyncFunctionPointer), -2)))
return IGF.Builder.CreateSelect(ICmp, BitCast, Load);
}
}
std::pair<llvm::Value *, llvm::Value *> irgen::getAsyncFunctionAndSize(
IRGenFunction &IGF, SILFunctionTypeRepresentation representation,
FunctionPointer functionPointer, llvm::Value *thickContext,
std::pair<bool, bool> values) {
assert(values.first || values.second);
assert(functionPointer.getKind() != FunctionPointer::Kind::Function);
bool emitFunction = values.first;
bool emitSize = values.second;
assert(emitFunction || emitSize);
// Ensure that the AsyncFunctionPointer is not auth'd if it is not used and
// that it is not auth'd more than once if it is needed.
//
// The AsyncFunctionPointer is not needed in the case where only the function
// is being loaded and the FunctionPointer was created from a function_ref
// instruction.
std::optional<llvm::Value *> afpPtrValue = std::nullopt;
auto getAFPPtr = [&]() {
if (!afpPtrValue) {
auto *ptr = functionPointer.getRawPointer();
if (auto authInfo = functionPointer.getAuthInfo()) {
ptr = emitPointerAuthAuth(IGF, ptr, authInfo);
}
afpPtrValue =
(IGF.IGM.getOptions().IndirectAsyncFunctionPointer)
? emitIndirectAsyncFunctionPointer(IGF, ptr)
: IGF.Builder.CreateBitCast(ptr,
IGF.IGM.AsyncFunctionPointerPtrTy);
}
return *afpPtrValue;
};
llvm::Value *fn = nullptr;
if (emitFunction) {
// If the FP is not an async FP, then we just have the direct
// address of the async function. This only happens for special
// async functions right now.
if (!functionPointer.getKind().isAsyncFunctionPointer()) {
assert(functionPointer.getStaticAsyncContextSize(IGF.IGM));
fn = functionPointer.getRawPointer();
// If we've opportunistically also emitted the direct address of the
// function, always prefer that.
} else if (auto *function = functionPointer.getRawAsyncFunction()) {
fn = function;
// Otherwise, extract the function pointer from the async FP structure.
} else {
llvm::Value *addrPtr = IGF.Builder.CreateStructGEP(
IGF.IGM.AsyncFunctionPointerTy, getAFPPtr(), 0);
fn = IGF.emitLoadOfCompactFunctionPointer(
Address(addrPtr, IGF.IGM.RelativeAddressTy,
IGF.IGM.getPointerAlignment()),
/*isFar*/ false,
/*expectedType*/ functionPointer.getFunctionType());
}
if (auto authInfo =
functionPointer.getAuthInfo().getCorrespondingCodeAuthInfo()) {
fn = emitPointerAuthSign(IGF, fn, authInfo);
}
}
llvm::Value *size = nullptr;
if (emitSize) {
if (auto staticSize = functionPointer.getStaticAsyncContextSize(IGF.IGM)) {
size = llvm::ConstantInt::get(IGF.IGM.Int32Ty, staticSize->getValue());
} else {
auto *sizePtr = IGF.Builder.CreateStructGEP(
IGF.IGM.AsyncFunctionPointerTy, getAFPPtr(), 1);
size = IGF.Builder.CreateLoad(sizePtr, IGF.IGM.Int32Ty,
IGF.IGM.getPointerAlignment());
}
}
return {fn, size};
}
static void externalizeArguments(IRGenFunction &IGF, const Callee &callee,
Explosion &in, Explosion &out,
TemporarySet &temporaries, bool isOutlined);
namespace {
class SyncCallEmission final : public CallEmission {
using super = CallEmission;
public:
SyncCallEmission(IRGenFunction &IGF, llvm::Value *selfValue, Callee &&callee)
: CallEmission(IGF, selfValue, std::move(callee)) {
setFromCallee();
}
FunctionPointer getCalleeFunctionPointer() override {
return getCallee().getFunctionPointer().getAsFunction(IGF);
}
SILType getParameterType(unsigned index) override {
SILFunctionConventions origConv(getCallee().getOrigFunctionType(),
IGF.getSILModule());
return origConv.getSILArgumentType(
index, IGF.IGM.getMaximalTypeExpansionContext());
}
llvm::CallBase *createCall(const FunctionPointer &fn,
ArrayRef<llvm::Value *> args) override {
return IGF.Builder.CreateCallOrInvoke(fn, Args, invokeNormalDest,
invokeUnwindDest);
}
void begin() override { super::begin(); }
void end() override { super::end(); }
void setFromCallee() override {
super::setFromCallee();
auto fnType = CurCallee.getOrigFunctionType();
if (fnType->getRepresentation() ==
SILFunctionTypeRepresentation::WitnessMethod) {
unsigned n = getTrailingWitnessSignatureLength(IGF.IGM, fnType);
while (n--) {
Args[--LastArgWritten] = nullptr;
}
}
llvm::Value *contextPtr = CurCallee.getSwiftContext();
// Add the error result if we have one.
if (fnType->hasErrorResult()) {
// The invariant is that this is always zero-initialized, so we
// don't need to do anything extra here.
auto substFnType = CurCallee.getSubstFunctionType();
SILFunctionConventions fnConv(substFnType, IGF.getSILModule());
Address errorResultSlot = IGF.getCalleeErrorResultSlot(
fnConv.getSILErrorType(IGF.IGM.getMaximalTypeExpansionContext()),
fnConv.isTypedError());
assert(LastArgWritten > 0);
if (fnConv.isTypedError()) {
if (fnConv.hasIndirectSILErrorResults()) {
// We will set the value later when lowering the arguments.
setIndirectTypedErrorResultSlotArgsIndex(--LastArgWritten);
Args[LastArgWritten] = nullptr;
} else {
// Return the error indirectly.
auto buf = IGF.getCalleeTypedErrorResultSlot(
fnConv.getSILErrorType(IGF.IGM.getMaximalTypeExpansionContext()));
Args[--LastArgWritten] = buf.getAddress();
}
}
Args[--LastArgWritten] = errorResultSlot.getAddress();
addParamAttribute(LastArgWritten, llvm::Attribute::NoCapture);
IGF.IGM.addSwiftErrorAttributes(CurCallee.getMutableAttributes(),
LastArgWritten);
// Fill in the context pointer if necessary.
if (!contextPtr) {
assert(!CurCallee.getOrigFunctionType()->getExtInfo().hasContext() &&
"Missing context?");
contextPtr = llvm::UndefValue::get(IGF.IGM.RefCountedPtrTy);
}
}
// Add the data pointer if we have one.
// (Note that we're emitting backwards, so this correctly goes
// *before* the error pointer.)
if (contextPtr) {
assert(LastArgWritten > 0);
Args[--LastArgWritten] = contextPtr;
IGF.IGM.addSwiftSelfAttributes(CurCallee.getMutableAttributes(),
LastArgWritten);
}
}
void setArgs(Explosion &original, bool isOutlined,
WitnessMetadata *witnessMetadata) override {
// Convert arguments to a representation appropriate to the calling
// convention.
Explosion adjusted;
auto origCalleeType = CurCallee.getOrigFunctionType();
SILFunctionConventions fnConv(origCalleeType, IGF.getSILModule());
// Pass along the indirect result pointers.
auto passIndirectResults = [&]() {
original.transferInto(adjusted, fnConv.getNumIndirectSILResults());
};
// Indirect results for C++ methods can come
// after `this`.
if (getCallee().getRepresentation() !=
SILFunctionTypeRepresentation::CXXMethod)
passIndirectResults();
// Pass along the coroutine buffer.
switch (origCalleeType->getCoroutineKind()) {
case SILCoroutineKind::YieldMany:
case SILCoroutineKind::YieldOnce:
original.transferInto(adjusted, 1);
break;
case SILCoroutineKind::None:
break;
}
// Translate the formal arguments and handle any special arguments.
switch (getCallee().getRepresentation()) {
case SILFunctionTypeRepresentation::ObjCMethod:
adjusted.add(getCallee().getObjCMethodReceiver());
if (!getCallee().isDirectObjCMethod())
adjusted.add(getCallee().getObjCMethodSelector());
externalizeArguments(IGF, getCallee(), original, adjusted, Temporaries,
isOutlined);
break;
case SILFunctionTypeRepresentation::Block:
case SILFunctionTypeRepresentation::CXXMethod:
if (getCallee().getRepresentation() == SILFunctionTypeRepresentation::Block) {
adjusted.add(getCallee().getBlockObject());
} else {
auto selfParam = origCalleeType->getSelfParameter();
auto *arg = getCallee().getCXXMethodSelf();
// We might need to fix the level of indirection for foreign reference types.
if (selfParam.getInterfaceType().isForeignReferenceType() &&
isIndirectFormalParameter(selfParam.getConvention())) {
auto paramTy = fnConv.getSILType(
selfParam, IGF.IGM.getMaximalTypeExpansionContext());
auto ¶mTI = cast<FixedTypeInfo>(IGF.IGM.getTypeInfo(paramTy));
arg = IGF.Builder.CreateLoad(arg, paramTI.getStorageType(),
IGF.IGM.getPointerAlignment());
}
// Windows ABI places `this` before the
// returned indirect values.
auto &returnInfo =
getCallee().getForeignInfo().ClangInfo->getReturnInfo();
if (returnInfo.isIndirect() && !returnInfo.isSRetAfterThis())
passIndirectResults();
adjusted.add(arg);
if (returnInfo.isIndirect() && returnInfo.isSRetAfterThis())
passIndirectResults();
}
LLVM_FALLTHROUGH;
case SILFunctionTypeRepresentation::CFunctionPointer:
externalizeArguments(IGF, getCallee(), original, adjusted, Temporaries,
isOutlined);
break;
case SILFunctionTypeRepresentation::KeyPathAccessorGetter:
case SILFunctionTypeRepresentation::KeyPathAccessorSetter:
case SILFunctionTypeRepresentation::KeyPathAccessorEquals:
case SILFunctionTypeRepresentation::KeyPathAccessorHash:
setKeyPathAccessorArguments(original, isOutlined, adjusted);
break;
case SILFunctionTypeRepresentation::WitnessMethod:
assert(witnessMetadata);
assert(witnessMetadata->SelfMetadata->getType() ==
IGF.IGM.TypeMetadataPtrTy);
assert(witnessMetadata->SelfWitnessTable->getType() ==
IGF.IGM.WitnessTablePtrTy);
Args.rbegin()[1] = witnessMetadata->SelfMetadata;
Args.rbegin()[0] = witnessMetadata->SelfWitnessTable;
LLVM_FALLTHROUGH;
case SILFunctionTypeRepresentation::Closure:
case SILFunctionTypeRepresentation::Method:
case SILFunctionTypeRepresentation::Thin:
case SILFunctionTypeRepresentation::Thick: {
// Check for value arguments that need to be passed indirectly.
// But don't expect to see 'self' if it's been moved to the context
// position.
auto params = origCalleeType->getParameters();
if (hasSelfContextParameter(origCalleeType)) {
params = params.drop_back();
}
for (auto param : params) {
addNativeArgument(IGF, original, origCalleeType, param, adjusted,
isOutlined);
}
// Anything else, just pass along. This will include things like
// generic arguments.
adjusted.add(original.claimAll());
break;
}
}
super::setArgs(adjusted, isOutlined, witnessMetadata);
}
void emitCallToUnmappedExplosion(llvm::CallBase *call,
Explosion &out) override {
// Bail out immediately on a void result.
llvm::Value *result = call;
if (result->getType()->isVoidTy())
return;
SILFunctionConventions fnConv(getCallee().getOrigFunctionType(),
IGF.getSILModule());
// If the result was returned autoreleased, implicitly insert the reclaim.
// This is only allowed on a single direct result.
if (fnConv.getNumDirectSILResults() == 1
&& (fnConv.getDirectSILResults().begin()->getConvention()
== ResultConvention::Autoreleased)) {
if (IGF.IGM.Context.LangOpts.EnableObjCInterop)
result = emitObjCRetainAutoreleasedReturnValue(IGF, result);
else
IGF.emitNativeStrongRetain(result, IGF.getDefaultAtomicity());
}
auto origFnType = getCallee().getOrigFunctionType();
// Specially handle noreturn c function which would return a 'Never' SIL result
// type.
if (origFnType->getLanguage() == SILFunctionLanguage::C &&
origFnType->isNoReturnFunction(
IGF.getSILModule(), IGF.IGM.getMaximalTypeExpansionContext())) {
auto clangResultTy = result->getType();
extractScalarResults(IGF, clangResultTy, result, out);
return;
}
// Get the natural IR type in the body of the function that makes
// the call. This may be different than the IR type returned by the
// call itself due to ABI type coercion.
auto resultType =
fnConv.getSILResultType(IGF.IGM.getMaximalTypeExpansionContext());
auto &nativeSchema = IGF.IGM.getTypeInfo(resultType).nativeReturnValueSchema(IGF.IGM);
// For ABI reasons the result type of the call might not actually match the
// expected result type.
//
// This can happen when calling C functions, or class method dispatch thunks
// for methods that have covariant ABI-compatible overrides.
auto expectedNativeResultType = nativeSchema.getExpandedType(IGF.IGM);
// If the expected result type is void, bail.
if (expectedNativeResultType->isVoidTy())
return;
if (result->getType() != expectedNativeResultType) {
result =
IGF.coerceValue(result, expectedNativeResultType, IGF.IGM.DataLayout);
}
// Gather the values.
Explosion nativeExplosion;
extractScalarResults(IGF, result->getType(), result, nativeExplosion);
out = nativeSchema.mapFromNative(IGF.IGM, IGF, nativeExplosion, resultType);
}
Address getCalleeErrorSlot(SILType errorType, bool isCalleeAsync) override {
SILFunctionConventions fnConv(getCallee().getOrigFunctionType(),
IGF.getSILModule());
return IGF.getCalleeErrorResultSlot(errorType, fnConv.isTypedError());
};
llvm::Value *getResumeFunctionPointer() override {
llvm_unreachable("Should not call getResumeFunctionPointer on a sync call");
}
llvm::Value *getAsyncContext() override {
llvm_unreachable("Should not call getAsyncContext on a sync call");
}
};
class AsyncCallEmission final : public CallEmission {
using super = CallEmission;
Address contextBuffer;
Address context;
llvm::Value *calleeFunction = nullptr;
llvm::Value *currentResumeFn = nullptr;
llvm::Value *thickContext = nullptr;
Size staticContextSize = Size(0);
std::optional<AsyncContextLayout> asyncContextLayout;
AsyncContextLayout getAsyncContextLayout() {
if (!asyncContextLayout) {
asyncContextLayout.emplace(::getAsyncContextLayout(
IGF.IGM, getCallee().getOrigFunctionType(),
getCallee().getSubstFunctionType(), getCallee().getSubstitutions()));
}
return *asyncContextLayout;
}
void saveValue(ElementLayout layout, llvm::Value *value, bool isOutlined) {
Address addr = layout.project(IGF, context, /*offsets*/ std::nullopt);
auto &ti = cast<LoadableTypeInfo>(layout.getType());
Explosion explosion;
explosion.add(value);
ti.initialize(IGF, explosion, addr, isOutlined);
}
void loadValue(ElementLayout layout, Explosion &explosion) {
Address addr = layout.project(IGF, context, /*offsets*/ std::nullopt);
auto &ti = cast<LoadableTypeInfo>(layout.getType());
ti.loadAsTake(IGF, addr, explosion);
}
public:
AsyncCallEmission(IRGenFunction &IGF, llvm::Value *selfValue, Callee &&callee)
: CallEmission(IGF, selfValue, std::move(callee)) {
setFromCallee();
}
void begin() override {
super::begin();
assert(!contextBuffer.isValid());
assert(!context.isValid());
auto layout = getAsyncContextLayout();
// Allocate space for the async context.
llvm::Value *dynamicContextSize32;
std::tie(calleeFunction, dynamicContextSize32) = getAsyncFunctionAndSize(
IGF, CurCallee.getOrigFunctionType()->getRepresentation(),
CurCallee.getFunctionPointer(), thickContext);
auto *dynamicContextSize =
IGF.Builder.CreateZExt(dynamicContextSize32, IGF.IGM.SizeTy);
if (auto staticSize = dyn_cast<llvm::ConstantInt>(dynamicContextSize)) {
staticContextSize = Size(staticSize->getZExtValue());
assert(!staticContextSize.isZero());
contextBuffer = emitStaticAllocAsyncContext(IGF, staticContextSize);
} else {
contextBuffer = emitAllocAsyncContext(IGF, dynamicContextSize);
}
context = layout.emitCastTo(IGF, contextBuffer.getAddress());
}
void end() override {
assert(contextBuffer.isValid());
assert(context.isValid());
if (getCallee().getStaticAsyncContextSize(IGF.IGM)) {
assert(!staticContextSize.isZero());
emitStaticDeallocAsyncContext(IGF, contextBuffer, staticContextSize);
} else {
emitDeallocAsyncContext(IGF, contextBuffer);
}
super::end();
}
void setFromCallee() override {
thickContext = nullptr; // TODO: this should go
super::setFromCallee();
auto fnType = CurCallee.getOrigFunctionType();
if (fnType->getRepresentation() ==
SILFunctionTypeRepresentation::WitnessMethod) {
unsigned n = getTrailingWitnessSignatureLength(IGF.IGM, fnType);
while (n--) {
Args[--LastArgWritten] = nullptr;
}
}
// Add the indirect typed error result if we have one.
SILFunctionConventions fnConv(fnType, IGF.getSILModule());
if (fnType->hasErrorResult() && fnConv.isTypedError()) {
// The invariant is that this is always zero-initialized, so we
// don't need to do anything extra here.
assert(LastArgWritten > 0);
// Return the error indirectly.
if (fnConv.hasIndirectSILErrorResults()) {
// We will set the value later when lowering the arguments.
setIndirectTypedErrorResultSlotArgsIndex(--LastArgWritten);
Args[LastArgWritten] = nullptr;
} else {
auto buf = IGF.getCalleeTypedErrorResultSlot(
fnConv.getSILErrorType(IGF.IGM.getMaximalTypeExpansionContext()));
Args[--LastArgWritten] = buf.getAddress();
}
}
llvm::Value *contextPtr = CurCallee.getSwiftContext();
// Add the data pointer if we have one.
if (contextPtr) {
assert(LastArgWritten > 0);
Args[--LastArgWritten] = contextPtr;
IGF.IGM.addSwiftSelfAttributes(CurCallee.getMutableAttributes(),
LastArgWritten);
}
}
FunctionPointer getCalleeFunctionPointer() override {
PointerAuthInfo codeAuthInfo = CurCallee.getFunctionPointer()
.getAuthInfo()
.getCorrespondingCodeAuthInfo();
auto awaitSig =
Signature::forAsyncAwait(IGF.IGM, getCallee().getOrigFunctionType(),
getCallee().getFunctionPointer().getKind());
auto awaitEntrySig =
Signature::forAsyncEntry(IGF.IGM, getCallee().getOrigFunctionType(),
getCallee().getFunctionPointer().getKind());
return FunctionPointer::createForAsyncCall(
IGF.Builder.CreateBitCast(calleeFunction,
awaitEntrySig.getType()->getPointerTo()),
codeAuthInfo, awaitSig, awaitEntrySig.getType());
}
SILType getParameterType(unsigned index) override {
SILFunctionConventions origConv(getCallee().getOrigFunctionType(),
IGF.getSILModule());
return origConv.getSILArgumentType(
index, IGF.IGM.getMaximalTypeExpansionContext());
}
void setArgs(Explosion &original, bool isOutlined,
WitnessMetadata *witnessMetadata) override {
Explosion asyncExplosion;
// Convert arguments to a representation appropriate to the calling
// convention.
auto origCalleeType = CurCallee.getOrigFunctionType();
SILFunctionConventions fnConv(origCalleeType, IGF.getSILModule());
// Pass along the indirect result pointers.
original.transferInto(asyncExplosion, fnConv.getNumIndirectSILResults());
// Pass the async context. For special direct-continuation functions,
// we pass our own async context; otherwise we pass the context
// we created.
if (getCallee().shouldPassContinuationDirectly()) {
asyncExplosion.add(IGF.getAsyncContext());
} else
asyncExplosion.add(contextBuffer.getAddress());
// Pass along the coroutine buffer.
switch (origCalleeType->getCoroutineKind()) {
case SILCoroutineKind::YieldMany:
case SILCoroutineKind::YieldOnce:
assert(false && "Should not reach this");
break;
case SILCoroutineKind::None:
break;
}
// Translate the formal arguments and handle any special arguments.
switch (getCallee().getRepresentation()) {
case SILFunctionTypeRepresentation::ObjCMethod:
case SILFunctionTypeRepresentation::Block:
case SILFunctionTypeRepresentation::CFunctionPointer:
case SILFunctionTypeRepresentation::CXXMethod:
case SILFunctionTypeRepresentation::KeyPathAccessorGetter:
case SILFunctionTypeRepresentation::KeyPathAccessorSetter:
case SILFunctionTypeRepresentation::KeyPathAccessorEquals:
case SILFunctionTypeRepresentation::KeyPathAccessorHash:
assert(false && "Should not reach this");
break;
case SILFunctionTypeRepresentation::WitnessMethod:
assert(witnessMetadata);
assert(witnessMetadata->SelfMetadata->getType() ==
IGF.IGM.TypeMetadataPtrTy);
assert(witnessMetadata->SelfWitnessTable->getType() ==
IGF.IGM.WitnessTablePtrTy);
Args.rbegin()[1] = witnessMetadata->SelfMetadata;
Args.rbegin()[0] = witnessMetadata->SelfWitnessTable;
LLVM_FALLTHROUGH;
case SILFunctionTypeRepresentation::Closure:
case SILFunctionTypeRepresentation::Method:
case SILFunctionTypeRepresentation::Thin:
case SILFunctionTypeRepresentation::Thick: {
// Check for value arguments that need to be passed indirectly.
// But don't expect to see 'self' if it's been moved to the context
// position.
auto params = origCalleeType->getParameters();
if (hasSelfContextParameter(origCalleeType)) {
params = params.drop_back();
}
for (auto param : params) {
addNativeArgument(IGF, original, origCalleeType, param, asyncExplosion,
isOutlined);
}
// Anything else, just pass along. This will include things like
// generic arguments.
asyncExplosion.add(original.claimAll());
break;
}
}
super::setArgs(asyncExplosion, false, witnessMetadata);
auto layout = getAsyncContextLayout();
// Initialize the async context for returning if we're not using
// the special convention which suppresses that.
if (!getCallee().shouldPassContinuationDirectly()) {
// Set the caller context to the current context.
Explosion explosion;
auto parentContextField = layout.getParentLayout();
auto *context = IGF.getAsyncContext();
if (auto schema = IGF.IGM.getOptions().PointerAuth.AsyncContextParent) {
Address fieldAddr =
parentContextField.project(IGF, this->context,
/*offsets*/ std::nullopt);
auto authInfo = PointerAuthInfo::emit(
IGF, schema, fieldAddr.getAddress(), PointerAuthEntity());
context = emitPointerAuthSign(IGF, context, authInfo);
}
saveValue(parentContextField, context, isOutlined);
// Set the caller resumption function to the resumption function
// for this suspension.
assert(currentResumeFn == nullptr);
auto resumeParentField = layout.getResumeParentLayout();
currentResumeFn = IGF.Builder.CreateIntrinsicCall(
llvm::Intrinsic::coro_async_resume, {});
auto fnVal = currentResumeFn;
// Sign the pointer.
if (auto schema = IGF.IGM.getOptions().PointerAuth.AsyncContextResume) {
Address fieldAddr = resumeParentField.project(IGF, this->context,
/*offsets*/ std::nullopt);
auto authInfo = PointerAuthInfo::emit(
IGF, schema, fieldAddr.getAddress(), PointerAuthEntity());
fnVal = emitPointerAuthSign(IGF, fnVal, authInfo);
}
fnVal = IGF.Builder.CreateBitCast(fnVal,
IGF.IGM.TaskContinuationFunctionPtrTy);
saveValue(resumeParentField, fnVal, isOutlined);
}
}
void emitCallToUnmappedExplosion(llvm::CallBase *call,
Explosion &out) override {
// Bail out on a void result type.
auto &IGM = IGF.IGM;
llvm::Value *result = call;
auto *suspendResultTy = cast<llvm::StructType>(result->getType());
auto numAsyncContextParams =
Signature::forAsyncReturn(IGM, getCallee().getSubstFunctionType())
.getAsyncContextIndex() +
1;
if (suspendResultTy->getNumElements() == numAsyncContextParams)
return;
auto &Builder = IGF.Builder;
auto resultTys =
llvm::ArrayRef(suspendResultTy->element_begin() + numAsyncContextParams,
suspendResultTy->element_end());
auto substCalleeType = getCallee().getSubstFunctionType();
SILFunctionConventions substConv(substCalleeType, IGF.getSILModule());
auto hasError = substCalleeType->hasErrorResult();
SILType errorType;
if (hasError)
errorType =
substConv.getSILErrorType(IGM.getMaximalTypeExpansionContext());
if (resultTys.size() == 1) {
result = Builder.CreateExtractValue(result, numAsyncContextParams);
if (hasError) {
Address errorAddr = IGF.getCalleeErrorResultSlot(errorType,
substConv.isTypedError());
Builder.CreateStore(result, errorAddr);
return;
}
} else if (resultTys.size() == 2 && hasError) {
auto tmp = result;
result = Builder.CreateExtractValue(result, numAsyncContextParams);
auto errorResult = Builder.CreateExtractValue(tmp, numAsyncContextParams + 1);
Address errorAddr = IGF.getCalleeErrorResultSlot(errorType, substConv.isTypedError());
Builder.CreateStore(errorResult, errorAddr);
} else {
auto directResultTys = hasError ? resultTys.drop_back() : resultTys;
auto resultTy = llvm::StructType::get(IGM.getLLVMContext(), directResultTys);
llvm::Value *resultAgg = llvm::UndefValue::get(resultTy);
for (unsigned i = 0, e = directResultTys.size(); i != e; ++i) {
llvm::Value *elt =
Builder.CreateExtractValue(result, numAsyncContextParams + i);
resultAgg = Builder.CreateInsertValue(resultAgg, elt, i);
}
if (hasError) {
auto errorResult = Builder.CreateExtractValue(
result, numAsyncContextParams + directResultTys.size());
Address errorAddr = IGF.getCalleeErrorResultSlot(errorType, substConv.isTypedError());
Builder.CreateStore(errorResult, errorAddr);
}
result = resultAgg;
}
SILFunctionConventions fnConv(getCallee().getOrigFunctionType(),
IGF.getSILModule());
// Get the natural IR type in the body of the function that makes
// the call. This may be different than the IR type returned by the
// call itself due to ABI type coercion.
auto resultType =
fnConv.getSILResultType(IGF.IGM.getMaximalTypeExpansionContext());
auto &nativeSchema =
IGF.IGM.getTypeInfo(resultType).nativeReturnValueSchema(IGF.IGM);
// For ABI reasons the result type of the call might not actually match the
// expected result type.
//
// This can happen when calling C functions, or class method dispatch thunks
// for methods that have covariant ABI-compatible overrides.
auto expectedNativeResultType = nativeSchema.getExpandedType(IGF.IGM);
// If the expected result type is void, bail.
if (expectedNativeResultType->isVoidTy())
return;
if (result->getType() != expectedNativeResultType) {
result =
IGF.coerceValue(result, expectedNativeResultType, IGF.IGM.DataLayout);
}
// Gather the values.
Explosion nativeExplosion;
extractScalarResults(IGF, result->getType(), result, nativeExplosion);
out = nativeSchema.mapFromNative(IGF.IGM, IGF, nativeExplosion, resultType);
}
Address getCalleeErrorSlot(SILType errorType, bool isCalleeAsync) override {
SILFunctionConventions fnConv(getCallee().getOrigFunctionType(),
IGF.getSILModule());
return IGF.getCalleeErrorResultSlot(errorType, fnConv.isTypedError());
}
llvm::CallBase *createCall(const FunctionPointer &fn,
ArrayRef<llvm::Value *> args) override {
auto &IGM = IGF.IGM;
auto &Builder = IGF.Builder;
// Setup the suspend point.
SmallVector<llvm::Value *, 8> arguments;
auto signature = fn.getSignature();
auto asyncContextIndex =
signature.getAsyncContextIndex();
auto paramAttributeFlags =
asyncContextIndex |
(signature.getAsyncResumeFunctionSwiftSelfIndex() << 8);
// Index of swiftasync context | ((index of swiftself) << 8).
arguments.push_back(
IGM.getInt32(paramAttributeFlags));
arguments.push_back(currentResumeFn);
// The special direct-continuation convention will pass our context
// when it resumes. The standard convention passes the callee's
// context, so we'll need to pop that off to get ours.
auto resumeProjFn = getCallee().shouldPassContinuationDirectly()
? IGF.getOrCreateResumeFromSuspensionFn()
: IGF.getOrCreateResumePrjFn();
arguments.push_back(
Builder.CreateBitOrPointerCast(resumeProjFn, IGM.Int8PtrTy));
auto dispatchFn = IGF.createAsyncDispatchFn(
getFunctionPointerForDispatchCall(IGM, fn), args);
arguments.push_back(
Builder.CreateBitOrPointerCast(dispatchFn, IGM.Int8PtrTy));
arguments.push_back(
Builder.CreateBitOrPointerCast(fn.getRawPointer(), IGM.Int8PtrTy));
if (auto authInfo = fn.getAuthInfo()) {
arguments.push_back(fn.getAuthInfo().getDiscriminator());
}
for (auto arg: args)
arguments.push_back(arg);
auto resultTy =
cast<llvm::StructType>(signature.getType()->getReturnType());
return IGF.emitSuspendAsyncCall(asyncContextIndex, resultTy, arguments);
}
llvm::Value *getResumeFunctionPointer() override {
assert(getCallee().shouldPassContinuationDirectly());
assert(currentResumeFn == nullptr);
currentResumeFn =
IGF.Builder.CreateIntrinsicCall(llvm::Intrinsic::coro_async_resume, {});
auto signedResumeFn = currentResumeFn;
// Sign the task resume function with the C function pointer schema.
if (auto schema = IGF.IGM.getOptions().PointerAuth.FunctionPointers) {
// Use the Clang type for TaskContinuationFunction*
// to make this work with type diversity.
if (schema.hasOtherDiscrimination())
schema =
IGF.IGM.getOptions().PointerAuth.ClangTypeTaskContinuationFunction;
auto authInfo =
PointerAuthInfo::emit(IGF, schema, nullptr, PointerAuthEntity());
signedResumeFn = emitPointerAuthSign(IGF, signedResumeFn, authInfo);
}
return signedResumeFn;
}
llvm::Value *getAsyncContext() override {
return contextBuffer.getAddress();
}
};
} // end anonymous namespace
std::unique_ptr<CallEmission> irgen::getCallEmission(IRGenFunction &IGF,
llvm::Value *selfValue,
Callee &&callee) {
if (callee.getOrigFunctionType()->isAsync()) {
return std::make_unique<AsyncCallEmission>(IGF, selfValue,
std::move(callee));
} else {
return std::make_unique<SyncCallEmission>(IGF, selfValue,
std::move(callee));
}
}
/// Emit the unsubstituted result of this call into the given explosion.
/// The unsubstituted result must be naturally returned directly.
void CallEmission::emitToUnmappedExplosion(Explosion &out) {
assert(state == State::Emitting);
assert(LastArgWritten == 0 && "emitting unnaturally to explosion");
auto call = emitCallSite();
emitCallToUnmappedExplosion(call, out);
}
/// Emit the unsubstituted result of this call to the given address.
/// The unsubstituted result must be naturally returned indirectly.
void CallEmission::emitToUnmappedMemory(Address result) {
assert(state == State::Emitting);
assert(LastArgWritten == 1 && "emitting unnaturally to indirect result");
Args[0] = result.getAddress();
auto *FI = getCallee().getForeignInfo().ClangInfo;
if (FI && FI->getReturnInfo().isIndirect() &&
FI->getReturnInfo().isSRetAfterThis() &&
Args[1] == getCallee().getCXXMethodSelf()) {
// C++ methods in MSVC ABI pass `this` before the
// indirectly returned value.
std::swap(Args[0], Args[1]);
assert(!isa<llvm::UndefValue>(Args[1]));
}
SILFunctionConventions FnConv(CurCallee.getSubstFunctionType(),
IGF.getSILModule());
#ifndef NDEBUG
LastArgWritten = 0; // appease an assert
#endif
auto call = emitCallSite();
// Async calls need to store the error result that is passed as a parameter.
if (CurCallee.getSubstFunctionType()->isAsync()) {
auto &IGM = IGF.IGM;
auto &Builder = IGF.Builder;
auto numAsyncContextParams =
Signature::forAsyncReturn(IGM, CurCallee.getSubstFunctionType())
.getAsyncContextIndex() +
1;
auto substCalleeType = CurCallee.getSubstFunctionType();
SILFunctionConventions substConv(substCalleeType, IGF.getSILModule());
auto hasError = substCalleeType->hasErrorResult();
SILType errorType;
if (hasError) {
errorType =
substConv.getSILErrorType(IGM.getMaximalTypeExpansionContext());
auto result = Builder.CreateExtractValue(call, numAsyncContextParams);
Address errorAddr = IGF.getCalleeErrorResultSlot(errorType,
substConv.isTypedError());
Builder.CreateStore(result, errorAddr);
}
}
}
/// The private routine to ultimately emit a call or invoke instruction.
llvm::CallBase *CallEmission::emitCallSite() {
assert(state == State::Emitting);
assert(LastArgWritten == 0);
assert(!EmittedCall);
EmittedCall = true;
// Make the call and clear the arguments array.
FunctionPointer fn = getCalleeFunctionPointer();
assert(fn.getKind().getBasicKind() == FunctionPointer::Kind::Function);
auto fnTy = fn.getFunctionType();
// Coerce argument types for those cases where the IR type required
// by the ABI differs from the type used within the function body.
assert(fnTy->getNumParams() == Args.size());
for (int i = 0, e = fnTy->getNumParams(); i != e; ++i) {
auto *paramTy = fnTy->getParamType(i);
auto *argTy = Args[i]->getType();
if (paramTy != argTy)
Args[i] = IGF.coerceValue(Args[i], paramTy, IGF.IGM.DataLayout);
}
if (fn.canThrowForeignException()) {
if (!fn.doesForeignCallCatchExceptionInThunk()) {
invokeNormalDest = IGF.createBasicBlock("invoke.cont");
invokeUnwindDest = IGF.createExceptionUnwindBlock();
} else
IGF.setCallsThunksWithForeignExceptionTraps();
}
auto call = createCall(fn, Args);
if (invokeNormalDest)
IGF.Builder.emitBlock(invokeNormalDest);
// Make coroutines calls opaque to LLVM analysis.
if (IsCoroutine) {
// Go back and insert some instructions right before the call.
// It's easier to do this than to mess around with copying and
// modifying the FunctionPointer above.
IGF.Builder.SetInsertPoint(call);
// Insert a call to @llvm.coro.prepare.retcon, then bitcast to the right
// function type.
auto origCallee = call->getCalledOperand();
llvm::Value *opaqueCallee = origCallee;
opaqueCallee =
IGF.Builder.CreateBitCast(opaqueCallee, IGF.IGM.Int8PtrTy);
opaqueCallee = IGF.Builder.CreateIntrinsicCall(
llvm::Intrinsic::coro_prepare_retcon, {opaqueCallee});
opaqueCallee =
IGF.Builder.CreateBitCast(opaqueCallee, origCallee->getType());
call->setCalledFunction(fn.getFunctionType(), opaqueCallee);
// Reset the insert point to after the call.
IGF.Builder.SetInsertPoint(call->getParent());
}
Args.clear();
// Destroy any temporaries we needed.
// We don't do this for coroutines because we need to wait until the
// coroutine is complete.
if (!IsCoroutine) {
Temporaries.destroyAll(IGF);
for (auto &stackAddr : RawTempraries) {
IGF.emitDeallocateDynamicAlloca(stackAddr);
}
// Clear the temporary set so that we can assert that there are no
// temporaries later.
Temporaries.clear();
RawTempraries.clear();
}
// Return.
return call;
}
llvm::CallBase *IRBuilder::CreateCallOrInvoke(
const FunctionPointer &fn, ArrayRef<llvm::Value *> args,
llvm::BasicBlock *invokeNormalDest, llvm::BasicBlock *invokeUnwindDest) {
assert(fn.getKind().getBasicKind() == FunctionPointer::Kind::Function);
SmallVector<llvm::OperandBundleDef, 1> bundles;
// Add a pointer-auth bundle if necessary.
if (const auto &authInfo = fn.getAuthInfo()) {
auto key = getInt32(authInfo.getKey());
auto discriminator = authInfo.getDiscriminator();
llvm::Value *bundleArgs[] = { key, discriminator };
bundles.emplace_back("ptrauth", bundleArgs);
}
assert(!isTrapIntrinsic(fn.getRawPointer()) && "Use CreateNonMergeableTrap");
auto fnTy = cast<llvm::FunctionType>(fn.getFunctionType());
llvm::CallBase *call;
if (!fn.shouldUseInvoke())
call = IRBuilderBase::CreateCall(fnTy, fn.getRawPointer(), args, bundles);
else
call =
IRBuilderBase::CreateInvoke(fnTy, fn.getRawPointer(), invokeNormalDest,
invokeUnwindDest, args, bundles);
llvm::AttributeList attrs = fn.getAttributes();
// If a parameter of a function is SRet, the corresponding argument should be
// wrapped in SRet(...).
if (auto func = dyn_cast<llvm::Function>(fn.getRawPointer())) {
for (unsigned argIndex = 0; argIndex < func->arg_size(); ++argIndex) {
if (func->hasParamAttribute(argIndex, llvm::Attribute::StructRet)) {
llvm::AttrBuilder builder(func->getContext());
// See if there is a sret parameter in the signature. There are cases
// where the called function has a sret parameter, but the signature
// doesn't (e.g., noreturn functions).
llvm::Type *ty = attrs.getParamStructRetType(argIndex);
if (!ty)
ty = func->getParamStructRetType(argIndex);
builder.addStructRetAttr(ty);
attrs = attrs.addParamAttributes(func->getContext(), argIndex, builder);
}
if (func->hasParamAttribute(argIndex, llvm::Attribute::ByVal)) {
llvm::AttrBuilder builder(func->getContext());
builder.addByValAttr(func->getParamByValType(argIndex));
attrs = attrs.addParamAttributes(func->getContext(), argIndex, builder);
}
}
}
call->setAttributes(attrs);
call->setCallingConv(fn.getCallingConv());
return call;
}
llvm::CallInst *IRBuilder::CreateCall(const FunctionPointer &fn,
ArrayRef<llvm::Value *> args) {
assert(!fn.shouldUseInvoke());
return cast<llvm::CallInst>(CreateCallOrInvoke(
fn, args, /*invokeNormalDest=*/nullptr, /*invokeUnwindDest=*/nullptr));
}
/// Emit the result of this call to memory.
void CallEmission::emitToMemory(Address addr,
const LoadableTypeInfo &indirectedResultTI,
bool isOutlined) {
assert(state == State::Emitting);
assert(LastArgWritten <= 1);
// If the call is naturally to an explosion, emit it that way and
// then initialize the temporary.
if (LastArgWritten == 0) {
Explosion result;
emitToExplosion(result, isOutlined);
indirectedResultTI.initialize(IGF, result, addr, isOutlined);
return;
}
// Okay, we're naturally emitting to memory.
Address origAddr = addr;
auto origFnType = CurCallee.getOrigFunctionType();
auto substFnType = CurCallee.getSubstFunctionType();
// We're never being asked to do anything with *formal*
// indirect results here, just the possibility of a direct-in-SIL
// result that's actually being passed indirectly.
//
// TODO: SIL address lowering should be able to handle such cases earlier.
auto origResultType =
origFnType
->getDirectFormalResultsType(IGF.IGM.getSILModule(),
IGF.IGM.getMaximalTypeExpansionContext())
.getASTType();
auto substResultType =
substFnType
->getDirectFormalResultsType(IGF.IGM.getSILModule(),
IGF.IGM.getMaximalTypeExpansionContext())
.getASTType();
if (origResultType->hasTypeParameter())
origResultType = IGF.IGM.getGenericEnvironment()
->mapTypeIntoContext(origResultType)
->getCanonicalType();
if (origResultType != substResultType) {
auto origTy = IGF.IGM.getStorageTypeForLowered(origResultType);
origAddr = IGF.Builder.CreateElementBitCast(origAddr, origTy);
}
emitToUnmappedMemory(origAddr);
}
static void emitCastToSubstSchema(IRGenFunction &IGF, Explosion &in,
const ExplosionSchema &schema,
Explosion &out) {
assert(in.size() == schema.size());
for (unsigned i = 0, e = schema.size(); i != e; ++i) {
llvm::Type *expectedType = schema.begin()[i].getScalarType();
llvm::Value *value = in.claimNext();
if (value->getType() != expectedType)
value = IGF.Builder.CreateBitCast(value, expectedType,
value->getName() + ".asSubstituted");
out.add(value);
}
}
void CallEmission::emitYieldsToExplosion(Explosion &out) {
assert(state == State::Emitting);
// Emit the call site.
auto call = emitCallSite();
// Pull the raw return values out.
Explosion rawReturnValues;
extractScalarResults(IGF, call->getType(), call, rawReturnValues);
auto coroInfo = getCallee().getSignature().getCoroutineInfo();
// Go ahead and forward the continuation pointer as an opaque pointer.
auto continuation = rawReturnValues.claimNext();
out.add(continuation);
// Collect the raw value components.
Explosion rawYieldComponents;
// Add all the direct yield components.
rawYieldComponents.add(
rawReturnValues.claim(coroInfo.NumDirectYieldComponents));
// Add all the indirect yield components.
assert(rawReturnValues.size() <= 1);
if (!rawReturnValues.empty()) {
// Extract the indirect yield buffer.
auto indirectPointer = rawReturnValues.claimNext();
auto indirectStructTy =
cast<llvm::StructType>(coroInfo.indirectResultsType);
auto layout = IGF.IGM.DataLayout.getStructLayout(indirectStructTy);
Address indirectBuffer(indirectPointer, indirectStructTy,
Alignment(layout->getAlignment().value()));
for (auto i : indices(indirectStructTy->elements())) {
// Skip padding.
if (indirectStructTy->getElementType(i)->isArrayTy())
continue;
auto eltAddr = IGF.Builder.CreateStructGEP(indirectBuffer, i, layout);
rawYieldComponents.add(IGF.Builder.CreateLoad(eltAddr));
}
}
auto substCoroType = getCallee().getSubstFunctionType();
SILFunctionConventions fnConv(substCoroType, IGF.getSILModule());
for (auto yield : fnConv.getYields()) {
YieldSchema schema(IGF.IGM, fnConv, yield);
// If the schema says it's indirect, then we expect a pointer.
if (schema.isIndirect()) {
auto pointer = IGF.Builder.CreateBitCast(rawYieldComponents.claimNext(),
schema.getIndirectPointerType());
// If it's formally indirect, then we should just add that pointer
// to the output.
if (schema.isFormalIndirect()) {
out.add(pointer);
continue;
}
// Otherwise, we need to load.
auto &yieldTI = cast<LoadableTypeInfo>(schema.getTypeInfo());
yieldTI.loadAsTake(IGF, yieldTI.getAddressForPointer(pointer), out);
continue;
}
// Otherwise, it's direct. Remap.
const auto &directSchema = schema.getDirectSchema();
Explosion eltValues;
rawYieldComponents.transferInto(eltValues, directSchema.size());
auto temp = directSchema.mapFromNative(IGF.IGM, IGF, eltValues,
schema.getSILType());
auto &yieldTI = cast<LoadableTypeInfo>(schema.getTypeInfo());
emitCastToSubstSchema(IGF, temp, yieldTI.getSchema(), out);
}
}
/// Emit the result of this call to an explosion.
void CallEmission::emitToExplosion(Explosion &out, bool isOutlined) {
assert(state == State::Emitting);
assert(LastArgWritten <= 1);
// For coroutine calls, we need to collect the yields, not the results;
// this looks very different.
if (IsCoroutine) {
assert(LastArgWritten == 0 && "coroutine with indirect result?");
emitYieldsToExplosion(out);
return;
}
SILFunctionConventions fnConv(getCallee().getSubstFunctionType(),
IGF.getSILModule());
SILType substResultType =
fnConv.getSILResultType(IGF.IGM.getMaximalTypeExpansionContext());
auto &substResultTI =
cast<LoadableTypeInfo>(IGF.getTypeInfo(substResultType));
auto origFnType = getCallee().getOrigFunctionType();
auto isNoReturnCFunction =
origFnType->getLanguage() == SILFunctionLanguage::C &&
origFnType->isNoReturnFunction(IGF.getSILModule(),
IGF.IGM.getMaximalTypeExpansionContext());
// If the call is naturally to memory, emit it that way and then
// explode that temporary.
if (LastArgWritten == 1) {
if (isNoReturnCFunction) {
auto fnType = getCallee().getFunctionPointer().getFunctionType();
assert(fnType->getNumParams() > 0);
// The size of the return buffer should not matter since the callee is not
// returning but lets try our best to use the right size.
llvm::Type *resultTy = IGF.IGM.Int8Ty;
auto func = dyn_cast<llvm::Function>(
getCallee().getFunctionPointer().getRawPointer());
if (func && func->hasParamAttribute(0, llvm::Attribute::StructRet)) {
resultTy = func->getParamStructRetType(0);
}
auto temp = IGF.createAlloca(resultTy, Alignment(), "indirect.result");
emitToMemory(temp, substResultTI, isOutlined);
return;
}
auto *FI = getCallee().getForeignInfo().ClangInfo;
if (FI && FI->getReturnInfo().isIndirect() &&
FI->getReturnInfo().isSRetAfterThis() && substResultType.isVoid()) {
// Some C++ methods return a value but are imported as
// returning `Void` (e.g. `operator +=`). In this case
// we should allocate the correct temp indirect return
// value for it.
// FIXME: MSVC ABI hits this as it makes some SIL direct
// returns as indirect at IR layer, so fix this for MSVC
// first to get this into Swfit 5.9. However, then investigate
// if this could also apply to Itanium ABI too.
auto fnType = getCallee().getFunctionPointer().getFunctionType();
assert(fnType->getNumParams() > 1);
auto func = dyn_cast<llvm::Function>(
getCallee().getFunctionPointer().getRawPointer());
if (func) {
// `this` comes before the returned value under the MSVC ABI
// so return value is parameter #1.
assert(func->hasParamAttribute(1, llvm::Attribute::StructRet));
auto resultTy = func->getParamStructRetType(1);
auto temp = IGF.createAlloca(resultTy, Alignment(/*safe alignment*/ 16),
"indirect.result");
emitToMemory(temp, substResultTI, isOutlined);
return;
}
}
StackAddress ctemp = substResultTI.allocateStack(IGF, substResultType,
"call.aggresult");
Address temp = ctemp.getAddress();
emitToMemory(temp, substResultTI, isOutlined);
// We can use a take.
substResultTI.loadAsTake(IGF, temp, out);
substResultTI.deallocateStack(IGF, ctemp, substResultType);
return;
}
// Okay, we're naturally emitting to an explosion.
Explosion temp;
emitToUnmappedExplosion(temp);
// Specially handle noreturn c function which would return a 'Never' SIL result
// type: there is no need to cast the result.
if (isNoReturnCFunction) {
temp.transferInto(out, temp.size());
return;
}
// We might need to bitcast the results.
emitCastToSubstSchema(IGF, temp, substResultTI.getSchema(), out);
}
CallEmission::CallEmission(CallEmission &&other)
: IGF(other.IGF),
Args(std::move(other.Args)),
CurCallee(std::move(other.CurCallee)),
LastArgWritten(other.LastArgWritten),
EmittedCall(other.EmittedCall) {
// Prevent other's destructor from asserting.
LastArgWritten = 0;
EmittedCall = true;
state = State::Finished;
}
CallEmission::~CallEmission() {
assert(LastArgWritten == 0);
assert(EmittedCall);
assert(Temporaries.hasBeenCleared());
assert(RawTempraries.empty());
assert(state == State::Finished);
}
void CallEmission::begin() {}
void CallEmission::end() {
assert(state == State::Emitting);
state = State::Finished;
}
Callee::Callee(CalleeInfo &&info, const FunctionPointer &fn,
llvm::Value *firstData, llvm::Value *secondData)
: Info(std::move(info)), Fn(fn),
FirstData(firstData), SecondData(secondData) {
#ifndef NDEBUG
// We should have foreign info if it's a foreign call.
assert((Fn.getForeignInfo().ClangInfo != nullptr) ==
(Info.OrigFnType->getLanguage() == SILFunctionLanguage::C));
// We should have the right data values for the representation.
switch (Info.OrigFnType->getRepresentation()) {
case SILFunctionTypeRepresentation::ObjCMethod:
assert(FirstData);
break;
case SILFunctionTypeRepresentation::Method:
case SILFunctionTypeRepresentation::WitnessMethod:
assert((FirstData != nullptr) ==
hasSelfContextParameter(Info.OrigFnType));
assert(!SecondData);
break;
case SILFunctionTypeRepresentation::Thick:
case SILFunctionTypeRepresentation::Block:
assert(FirstData && !SecondData);
break;
case SILFunctionTypeRepresentation::Thin:
case SILFunctionTypeRepresentation::Closure:
case SILFunctionTypeRepresentation::CFunctionPointer:
case SILFunctionTypeRepresentation::KeyPathAccessorGetter:
case SILFunctionTypeRepresentation::KeyPathAccessorSetter:
case SILFunctionTypeRepresentation::KeyPathAccessorEquals:
case SILFunctionTypeRepresentation::KeyPathAccessorHash:
assert(!FirstData && !SecondData);
break;
case SILFunctionTypeRepresentation::CXXMethod:
assert(FirstData && !SecondData);
break;
}
#endif
}
llvm::Value *Callee::getSwiftContext() const {
switch (Info.OrigFnType->getRepresentation()) {
case SILFunctionTypeRepresentation::Block:
case SILFunctionTypeRepresentation::ObjCMethod:
case SILFunctionTypeRepresentation::CFunctionPointer:
case SILFunctionTypeRepresentation::Thin:
case SILFunctionTypeRepresentation::Closure:
case SILFunctionTypeRepresentation::CXXMethod:
case SILFunctionTypeRepresentation::KeyPathAccessorGetter:
case SILFunctionTypeRepresentation::KeyPathAccessorSetter:
case SILFunctionTypeRepresentation::KeyPathAccessorEquals:
case SILFunctionTypeRepresentation::KeyPathAccessorHash:
return nullptr;
case SILFunctionTypeRepresentation::WitnessMethod:
case SILFunctionTypeRepresentation::Method:
// This may or may not be null.
return FirstData;
case SILFunctionTypeRepresentation::Thick:
assert(FirstData && "no context value set on callee");
return FirstData;
}
llvm_unreachable("bad representation");
}
llvm::Value *Callee::getBlockObject() const {
assert(Info.OrigFnType->getRepresentation() ==
SILFunctionTypeRepresentation::Block &&
"not a block");
assert(FirstData && "no block object set on callee");
return FirstData;
}
llvm::Value *Callee::getCXXMethodSelf() const {
assert(Info.OrigFnType->getRepresentation() ==
SILFunctionTypeRepresentation::CXXMethod &&
"not a C++ method");
assert(FirstData && "no self object set on callee");
return FirstData;
}
llvm::Value *Callee::getObjCMethodReceiver() const {
assert(Info.OrigFnType->getRepresentation() ==
SILFunctionTypeRepresentation::ObjCMethod &&
"not a method");
assert(FirstData && "no receiver set on callee");
return FirstData;
}
llvm::Value *Callee::getObjCMethodSelector() const {
assert(Info.OrigFnType->getRepresentation() ==
SILFunctionTypeRepresentation::ObjCMethod &&
"not a method");
assert(SecondData && "no selector set on callee");
return SecondData;
}
bool Callee::isDirectObjCMethod() const {
return Info.OrigFnType->getRepresentation() ==
SILFunctionTypeRepresentation::ObjCMethod && SecondData == nullptr;
}
/// Set up this emitter afresh from the current callee specs.
void CallEmission::setFromCallee() {
assert(state == State::Emitting);
IsCoroutine = CurCallee.getSubstFunctionType()->isCoroutine();
EmittedCall = false;
unsigned numArgs = CurCallee.getLLVMFunctionType()->getNumParams();
// Set up the args array.
assert(Args.empty());
Args.resize_for_overwrite(numArgs);
LastArgWritten = numArgs;
}
bool irgen::canCoerceToSchema(IRGenModule &IGM,
ArrayRef<llvm::Type*> expandedTys,
const ExplosionSchema &schema) {
// If the schemas don't even match in number, we have to go
// through memory.
if (expandedTys.size() != schema.size())
return false;
// If there's just one element, we can always coerce as a scalar.
if (expandedTys.size() == 1) return true;
// If there are multiple elements, the pairs of types need to
// match in size for the coercion to work.
for (size_t i = 0, e = expandedTys.size(); i != e; ++i) {
llvm::Type *inputTy = schema[i].getScalarType();
llvm::Type *outputTy = expandedTys[i];
if (inputTy != outputTy &&
IGM.DataLayout.getTypeSizeInBits(inputTy) !=
IGM.DataLayout.getTypeSizeInBits(outputTy))
return false;
}
// Okay, everything is fine.
return true;
}
static llvm::Type *getOutputType(TranslationDirection direction, unsigned index,
const ExplosionSchema &nativeSchema,
ArrayRef<llvm::Type*> expandedForeignTys) {
assert(nativeSchema.size() == expandedForeignTys.size());
return (direction == TranslationDirection::ToForeign
? expandedForeignTys[index]
: nativeSchema[index].getScalarType());
}
static void emitCoerceAndExpand(IRGenFunction &IGF, Explosion &in,
Explosion &out, SILType paramTy,
const LoadableTypeInfo ¶mTI,
llvm::StructType *coercionTy,
ArrayRef<llvm::Type *> expandedTys,
TranslationDirection direction,
bool isOutlined) {
// If we can directly coerce the scalar values, avoid going through memory.
auto schema = paramTI.getSchema();
if (canCoerceToSchema(IGF.IGM, expandedTys, schema)) {
for (auto index : indices(expandedTys)) {
llvm::Value *arg = in.claimNext();
assert(arg->getType() ==
getOutputType(reverse(direction), index, schema, expandedTys));
auto outputTy = getOutputType(direction, index, schema, expandedTys);
if (arg->getType() != outputTy)
arg = IGF.coerceValue(arg, outputTy, IGF.IGM.DataLayout);
out.add(arg);
}
return;
}
// Otherwise, materialize to a temporary.
auto temporaryAlloc =
paramTI.allocateStack(IGF, paramTy, "coerce-and-expand.temp");
Address temporary = temporaryAlloc.getAddress();
auto coercionTyLayout = IGF.IGM.DataLayout.getStructLayout(coercionTy);
// Make the alloca at least as aligned as the coercion struct, just
// so that the element accesses we make don't end up under-aligned.
Alignment coercionTyAlignment =
Alignment(coercionTyLayout->getAlignment().value());
auto alloca = cast<llvm::AllocaInst>(temporary.getAddress());
if (alloca->getAlign() < coercionTyAlignment.getValue()) {
alloca->setAlignment(
llvm::MaybeAlign(coercionTyAlignment.getValue()).valueOrOne());
temporary = Address(temporary.getAddress(), temporary.getElementType(),
coercionTyAlignment);
}
// If we're translating *to* the foreign expansion, do an ordinary
// initialization from the input explosion.
if (direction == TranslationDirection::ToForeign) {
paramTI.initialize(IGF, in, temporary, isOutlined);
}
Address coercedTemporary =
IGF.Builder.CreateElementBitCast(temporary, coercionTy);
#ifndef NDEBUG
size_t expandedTyIndex = 0;
#endif
for (auto eltIndex : indices(coercionTy->elements())) {
auto eltTy = coercionTy->getElementType(eltIndex);
// Skip padding fields.
if (eltTy->isArrayTy()) continue;
assert(expandedTys[expandedTyIndex++] == eltTy);
// Project down to the field.
Address eltAddr =
IGF.Builder.CreateStructGEP(coercedTemporary, eltIndex, coercionTyLayout);
// If we're translating *to* the foreign expansion, pull the value out
// of the field and add it to the output.
if (direction == TranslationDirection::ToForeign) {
llvm::Value *value = IGF.Builder.CreateLoad(eltAddr);
out.add(value);
// Otherwise, claim the next value from the input and store that
// in the field.
} else {
llvm::Value *value = in.claimNext();
IGF.Builder.CreateStore(value, eltAddr);
}
}
assert(expandedTyIndex == expandedTys.size());
// If we're translating *from* the foreign expansion, do an ordinary
// load into the output explosion.
if (direction == TranslationDirection::ToNative) {
paramTI.loadAsTake(IGF, temporary, out);
}
paramTI.deallocateStack(IGF, temporaryAlloc, paramTy);
}
static void emitDirectExternalArgument(IRGenFunction &IGF, SILType argType,
const clang::CodeGen::ABIArgInfo &AI,
Explosion &in, Explosion &out,
bool isOutlined) {
bool IsDirectFlattened = AI.isDirect() && AI.getCanBeFlattened();
bool IsIndirect = !AI.isDirect();
// If we're supposed to pass directly as a struct type, that
// really means expanding out as multiple arguments.
llvm::Type *coercedTy = AI.getCoerceToType();
ArrayRef<llvm::Type *> expandedTys =
expandScalarOrStructTypeToArray(coercedTy);
auto &argTI = cast<LoadableTypeInfo>(IGF.getTypeInfo(argType));
auto inputSchema = argTI.getSchema();
// Check to see if we can pairwise coerce Swift's exploded scalars
// to Clang's expanded elements.
if ((IsDirectFlattened || IsIndirect) &&
canCoerceToSchema(IGF.IGM, expandedTys, inputSchema)) {
for (auto outputTy : expandedTys) {
llvm::Value *arg = in.claimNext();
if (arg->getType() != outputTy)
arg = IGF.coerceValue(arg, outputTy, IGF.IGM.DataLayout);
out.add(arg);
}
return;
}
// Otherwise, we need to coerce through memory.
Address temporary;
Size tempSize;
std::tie(temporary, tempSize) =
allocateForCoercion(IGF, argTI.getStorageType(), coercedTy, "coerced-arg");
IGF.Builder.CreateLifetimeStart(temporary, tempSize);
// Store to a temporary.
Address tempOfArgTy =
IGF.Builder.CreateElementBitCast(temporary, argTI.getStorageType());
argTI.initializeFromParams(IGF, in, tempOfArgTy, argType, isOutlined);
// Bitcast the temporary to the expected type.
Address coercedAddr = IGF.Builder.CreateElementBitCast(temporary, coercedTy);
if (IsDirectFlattened && isa<llvm::StructType>(coercedTy)) {
// Project out individual elements if necessary.
auto *ST = cast<llvm::StructType>(coercedTy);
const auto *layout = IGF.IGM.DataLayout.getStructLayout(ST);
for (unsigned EI : range(ST->getNumElements())) {
auto offset = Size(layout->getElementOffset(EI));
auto address = IGF.Builder.CreateStructGEP(coercedAddr, EI, offset);
out.add(IGF.Builder.CreateLoad(address));
}
} else {
// Otherwise, collect the single scalar.
out.add(IGF.Builder.CreateLoad(coercedAddr));
}
IGF.Builder.CreateLifetimeEnd(temporary, tempSize);
}
namespace {
/// Load a clang argument expansion from a buffer.
struct ClangExpandLoadEmitter :
ClangExpandProjection<ClangExpandLoadEmitter> {
Explosion &Out;
ClangExpandLoadEmitter(IRGenFunction &IGF, Explosion &out)
: ClangExpandProjection(IGF), Out(out) {}
void visitScalar(llvm::Type *scalarTy, Address addr) {
addr = IGF.Builder.CreateElementBitCast(addr, scalarTy);
auto value = IGF.Builder.CreateLoad(addr);
Out.add(value);
}
};
/// Store a clang argument expansion into a buffer.
struct ClangExpandStoreEmitter :
ClangExpandProjection<ClangExpandStoreEmitter> {
Explosion &In;
ClangExpandStoreEmitter(IRGenFunction &IGF, Explosion &in)
: ClangExpandProjection(IGF), In(in) {}
void visitScalar(llvm::Type *scalarTy, Address addr) {
auto value = In.claimNext();
addr = IGF.Builder.CreateElementBitCast(addr, scalarTy);
IGF.Builder.CreateStore(value, addr);
}
};
} // end anonymous namespace
/// Given a Swift value explosion in 'in', produce a Clang expansion
/// (according to ABIArgInfo::Expand) in 'out'.
static void
emitClangExpandedArgument(IRGenFunction &IGF, Explosion &in, Explosion &out,
clang::CanQualType clangType, SILType swiftType,
const LoadableTypeInfo &swiftTI, bool isOutlined) {
// If Clang's expansion schema matches Swift's, great.
auto swiftSchema = swiftTI.getSchema();
if (doesClangExpansionMatchSchema(IGF.IGM, clangType, swiftSchema)) {
return in.transferInto(out, swiftSchema.size());
}
// Otherwise, materialize to a temporary.
auto ctemp = swiftTI.allocateStack(IGF, swiftType, "clang-expand-arg.temp");
Address temp = ctemp.getAddress();
swiftTI.initialize(IGF, in, temp, isOutlined);
Address castTemp = IGF.Builder.CreateElementBitCast(temp, IGF.IGM.Int8Ty);
ClangExpandLoadEmitter(IGF, out).visit(clangType, castTemp);
swiftTI.deallocateStack(IGF, ctemp, swiftType);
}
/// Given a Clang-expanded (according to ABIArgInfo::Expand) parameter
/// in 'in', produce a Swift value explosion in 'out'.
void irgen::emitClangExpandedParameter(IRGenFunction &IGF,
Explosion &in, Explosion &out,
clang::CanQualType clangType,
SILType swiftType,
const LoadableTypeInfo &swiftTI) {
// If Clang's expansion schema matches Swift's, great.
auto swiftSchema = swiftTI.getSchema();
if (doesClangExpansionMatchSchema(IGF.IGM, clangType, swiftSchema)) {
return in.transferInto(out, swiftSchema.size());
}
// Otherwise, materialize to a temporary.
auto tempAlloc = swiftTI.allocateStack(IGF, swiftType,
"clang-expand-param.temp");
Address temp = tempAlloc.getAddress();
Address castTemp = IGF.Builder.CreateElementBitCast(temp, IGF.IGM.Int8Ty);
ClangExpandStoreEmitter(IGF, in).visit(clangType, castTemp);
// Then load out.
swiftTI.loadAsTake(IGF, temp, out);
swiftTI.deallocateStack(IGF, tempAlloc, swiftType);
}
static void externalizeArguments(IRGenFunction &IGF, const Callee &callee,
Explosion &in, Explosion &out,
TemporarySet &temporaries,
bool isOutlined) {
auto fnType = callee.getOrigFunctionType();
auto silConv = SILFunctionConventions(fnType, IGF.IGM.silConv);
auto params = fnType->getParameters();
assert(callee.getForeignInfo().ClangInfo);
auto &FI = *callee.getForeignInfo().ClangInfo;
// The index of the first "physical" parameter from paramTys/FI that
// corresponds to a logical parameter from params.
unsigned firstParam = 0;
unsigned paramEnd = FI.arg_size();
// Handle the ObjC prefix.
if (callee.getRepresentation() == SILFunctionTypeRepresentation::ObjCMethod) {
// Ignore both the logical and the physical parameters associated
// with self and (if not objc_direct) _cmd.
firstParam += callee.isDirectObjCMethod() ? 1 : 2;
params = params.drop_back();
// Or the block prefix.
} else if (fnType->getRepresentation()
== SILFunctionTypeRepresentation::Block) {
// Ignore the physical block-object parameter.
firstParam += 1;
} else if (callee.getRepresentation() ==
SILFunctionTypeRepresentation::CXXMethod) {
// Skip the "self" param.
firstParam += 1;
params = params.drop_back();
}
bool formalIndirectResult = fnType->getNumResults() > 0 &&
fnType->getSingleResult().isFormalIndirect();
// If clang returns directly and swift returns indirectly, this must be a c++
// constructor call. In that case, skip the "self" param.
if (!FI.getReturnInfo().isIndirect() && formalIndirectResult)
firstParam += 1;
for (unsigned i = firstParam; i != paramEnd; ++i) {
auto clangParamTy = FI.arg_begin()[i].type;
auto &AI = FI.arg_begin()[i].info;
// We don't need to do anything to handle the Swift parameter-ABI
// attributes here because we shouldn't be trying to round-trip
// swiftcall function pointers through SIL as C functions anyway.
assert(FI.getExtParameterInfo(i).getABI() == clang::ParameterABI::Ordinary);
// Add a padding argument if required.
if (auto *padType = AI.getPaddingType())
out.add(llvm::UndefValue::get(padType));
SILType paramType = silConv.getSILType(
params[i - firstParam], IGF.IGM.getMaximalTypeExpansionContext());
// In Swift, values that are foreign references types will always be
// pointers. Additionally, we only import functions which use foreign
// reference types indirectly (as pointers), so we know in every case, if
// the argument type is a foreign reference type, the types will match up
// and we can simply use the input directly.
if (paramType.isForeignReferenceType()) {
auto *arg = in.claimNext();
if (isIndirectFormalParameter(params[i - firstParam].getConvention())) {
auto storageTy = IGF.IGM.getTypeInfo(paramType).getStorageType();
arg = IGF.Builder.CreateLoad(arg, storageTy,
IGF.IGM.getPointerAlignment());
}
out.add(arg);
continue;
}
switch (AI.getKind()) {
case clang::CodeGen::ABIArgInfo::Extend: {
bool signExt = clangParamTy->hasSignedIntegerRepresentation();
assert((signExt || clangParamTy->hasUnsignedIntegerRepresentation()) &&
"Invalid attempt to add extension attribute to argument!");
(void) signExt;
LLVM_FALLTHROUGH;
}
case clang::CodeGen::ABIArgInfo::Direct: {
auto toTy = AI.getCoerceToType();
// Indirect parameters are bridged as Clang pointer types.
if (silConv.isSILIndirect(params[i - firstParam])) {
assert(paramType.isAddress() && "SIL type is not an address?");
auto addr = in.claimNext();
if (addr->getType() != toTy)
addr = IGF.coerceValue(addr, toTy, IGF.IGM.DataLayout);
out.add(addr);
break;
}
emitDirectExternalArgument(IGF, paramType, AI, in, out, isOutlined);
break;
}
case clang::CodeGen::ABIArgInfo::IndirectAliased:
llvm_unreachable("not implemented");
case clang::CodeGen::ABIArgInfo::Indirect: {
auto &ti = cast<LoadableTypeInfo>(IGF.getTypeInfo(paramType));
auto temp = ti.allocateStack(IGF, paramType, "indirect-temporary");
temporaries.add({temp, paramType});
Address addr = temp.getAddress();
// Set at least the alignment the ABI expects.
if (AI.getIndirectByVal()) {
auto ABIAlign = AI.getIndirectAlign();
if (ABIAlign > addr.getAlignment()) {
auto *AS = cast<llvm::AllocaInst>(addr.getAddress());
AS->setAlignment(
llvm::MaybeAlign(ABIAlign.getQuantity()).valueOrOne());
addr = Address(addr.getAddress(), addr.getElementType(),
Alignment(ABIAlign.getQuantity()));
}
}
ti.initialize(IGF, in, addr, isOutlined);
out.add(addr.getAddress());
break;
}
case clang::CodeGen::ABIArgInfo::CoerceAndExpand: {
auto ¶mTI = cast<LoadableTypeInfo>(IGF.getTypeInfo(paramType));
emitCoerceAndExpand(IGF, in, out, paramType, paramTI,
AI.getCoerceAndExpandType(),
AI.getCoerceAndExpandTypeSequence(),
TranslationDirection::ToForeign, isOutlined);
break;
}
case clang::CodeGen::ABIArgInfo::Expand:
emitClangExpandedArgument(
IGF, in, out, clangParamTy, paramType,
cast<LoadableTypeInfo>(IGF.getTypeInfo(paramType)), isOutlined);
break;
case clang::CodeGen::ABIArgInfo::Ignore:
break;
case clang::CodeGen::ABIArgInfo::InAlloca:
llvm_unreachable("Need to handle InAlloca when externalizing arguments");
break;
}
}
}
void CallEmission::setKeyPathAccessorArguments(Explosion &in, bool isOutlined,
Explosion &out) {
auto origCalleeType = CurCallee.getOrigFunctionType();
auto params = origCalleeType->getParameters();
switch (getCallee().getRepresentation()) {
case SILFunctionTypeRepresentation::KeyPathAccessorGetter: {
// add base value
addNativeArgument(IGF, in, origCalleeType, params[0], out, isOutlined);
params = params.drop_back();
break;
}
case SILFunctionTypeRepresentation::KeyPathAccessorSetter: {
// add base value
addNativeArgument(IGF, in, origCalleeType, params[0], out, isOutlined);
// add new value
addNativeArgument(IGF, in, origCalleeType, params[1], out, isOutlined);
params = params.drop_back(2);
break;
}
default:
llvm_unreachable("unexpected representation");
}
std::optional<StackAddress> dynamicArgsBuf;
SmallVector<SILType, 4> indiceTypes;
for (auto i : indices(params)) {
auto ty = getParameterType(i);
indiceTypes.push_back(ty);
}
auto sig = origCalleeType->getInvocationGenericSignature();
auto args = emitKeyPathArgument(IGF, getCallee().getSubstitutions(), sig,
indiceTypes, in, dynamicArgsBuf);
if (dynamicArgsBuf) {
RawTempraries.push_back(*dynamicArgsBuf);
}
// add arg buffer
out.add(args.first);
// add arg buffer size
out.add(args.second);
}
/// Returns whether allocas are needed.
bool irgen::addNativeArgument(IRGenFunction &IGF,
Explosion &in,
CanSILFunctionType fnTy,
SILParameterInfo origParamInfo, Explosion &out,
bool isOutlined) {
// Addresses consist of a single pointer argument.
if (IGF.IGM.silConv.isSILIndirect(origParamInfo)) {
out.add(in.claimNext());
return false;
}
auto paramType = IGF.IGM.silConv.getSILType(
origParamInfo, fnTy, IGF.IGM.getMaximalTypeExpansionContext());
auto &ti = cast<LoadableTypeInfo>(IGF.getTypeInfo(paramType));
auto schema = ti.getSchema();
auto &nativeSchema = ti.nativeParameterValueSchema(IGF.IGM);
if (nativeSchema.requiresIndirect()) {
// Pass the argument indirectly.
auto buf = IGF.createAlloca(ti.getStorageType(),
ti.getFixedAlignment(), "");
ti.initialize(IGF, in, buf, isOutlined);
out.add(buf.getAddress());
return true;
} else {
if (schema.empty()) {
assert(nativeSchema.empty());
return false;
}
assert(!nativeSchema.empty());
// Pass the argument explosion directly, mapping into the native swift
// calling convention.
Explosion nonNativeParam;
ti.reexplode(in, nonNativeParam);
Explosion nativeParam = nativeSchema.mapIntoNative(
IGF.IGM, IGF, nonNativeParam, paramType, isOutlined);
nativeParam.transferInto(out, nativeParam.size());
return false;
}
}
/// Emit a direct parameter that was passed under a C-based CC.
static void emitDirectForeignParameter(IRGenFunction &IGF, Explosion &in,
const clang::CodeGen::ABIArgInfo &AI,
Explosion &out, SILType paramType,
const LoadableTypeInfo ¶mTI) {
// The ABI IR types for the entrypoint might differ from the
// Swift IR types for the body of the function.
llvm::Type *coercionTy = AI.getCoerceToType();
ArrayRef<llvm::Type*> expandedTys;
if (AI.isDirect() && AI.getCanBeFlattened() &&
isa<llvm::StructType>(coercionTy)) {
const auto *ST = cast<llvm::StructType>(coercionTy);
expandedTys = llvm::ArrayRef(ST->element_begin(), ST->getNumElements());
} else if (coercionTy == paramTI.getStorageType()) {
// Fast-path a really common case. This check assumes that either
// the storage type of a type is an llvm::StructType or it has a
// single-element explosion.
out.add(in.claimNext());
return;
} else {
expandedTys = coercionTy;
}
auto outputSchema = paramTI.getSchema();
// Check to see if we can pairwise-coerce Swift's exploded scalars
// to Clang's expanded elements.
if (canCoerceToSchema(IGF.IGM, expandedTys, outputSchema)) {
for (auto &outputElt : outputSchema) {
llvm::Value *param = in.claimNext();
llvm::Type *outputTy = outputElt.getScalarType();
if (param->getType() != outputTy)
param = IGF.coerceValue(param, outputTy, IGF.IGM.DataLayout);
out.add(param);
}
return;
}
// Otherwise, we need to traffic through memory.
// Create a temporary.
Address temporary; Size tempSize;
std::tie(temporary, tempSize) = allocateForCoercion(IGF,
coercionTy,
paramTI.getStorageType(),
"");
IGF.Builder.CreateLifetimeStart(temporary, tempSize);
// Write the input parameters into the temporary:
Address coercedAddr = IGF.Builder.CreateElementBitCast(temporary, coercionTy);
// Break down a struct expansion if necessary.
if (auto expansionTy = dyn_cast<llvm::StructType>(coercionTy)) {
auto layout = IGF.IGM.DataLayout.getStructLayout(expansionTy);
for (unsigned i = 0, e = expansionTy->getNumElements(); i != e; ++i) {
auto fieldOffset = Size(layout->getElementOffset(i));
auto fieldAddr = IGF.Builder.CreateStructGEP(coercedAddr, i, fieldOffset);
IGF.Builder.CreateStore(in.claimNext(), fieldAddr);
}
// Otherwise, store the single scalar.
} else {
IGF.Builder.CreateStore(in.claimNext(), coercedAddr);
}
// Pull out the elements.
temporary =
IGF.Builder.CreateElementBitCast(temporary, paramTI.getStorageType());
paramTI.loadAsTake(IGF, temporary, out);
// Deallocate the temporary.
// `deallocateStack` emits the lifetime.end marker for us.
paramTI.deallocateStack(IGF, StackAddress(temporary), paramType);
}
void irgen::emitForeignParameter(IRGenFunction &IGF, Explosion ¶ms,
ForeignFunctionInfo foreignInfo,
unsigned foreignParamIndex, SILType paramTy,
const LoadableTypeInfo ¶mTI,
Explosion ¶mExplosion, bool isOutlined) {
assert(foreignInfo.ClangInfo);
auto &FI = *foreignInfo.ClangInfo;
auto clangArgTy = FI.arg_begin()[foreignParamIndex].type;
auto AI = FI.arg_begin()[foreignParamIndex].info;
// We don't need to do anything to handle the Swift parameter-ABI
// attributes here because we shouldn't be trying to round-trip
// swiftcall function pointers through SIL as C functions anyway.
assert(FI.getExtParameterInfo(foreignParamIndex).getABI()
== clang::ParameterABI::Ordinary);
// Drop padding arguments.
if (AI.getPaddingType())
params.claimNext();
switch (AI.getKind()) {
case clang::CodeGen::ABIArgInfo::Extend:
case clang::CodeGen::ABIArgInfo::Direct:
emitDirectForeignParameter(IGF, params, AI, paramExplosion, paramTy,
paramTI);
return;
case clang::CodeGen::ABIArgInfo::IndirectAliased:
llvm_unreachable("not implemented");
case clang::CodeGen::ABIArgInfo::Indirect: {
Address address = paramTI.getAddressForPointer(params.claimNext());
paramTI.loadAsTake(IGF, address, paramExplosion);
return;
}
case clang::CodeGen::ABIArgInfo::Expand: {
emitClangExpandedParameter(IGF, params, paramExplosion, clangArgTy,
paramTy, paramTI);
return;
}
case clang::CodeGen::ABIArgInfo::CoerceAndExpand: {
auto ¶mTI = cast<LoadableTypeInfo>(IGF.getTypeInfo(paramTy));
emitCoerceAndExpand(IGF, params, paramExplosion, paramTy, paramTI,
AI.getCoerceAndExpandType(),
AI.getCoerceAndExpandTypeSequence(),
TranslationDirection::ToNative, isOutlined);
break;
}
case clang::CodeGen::ABIArgInfo::Ignore:
return;
case clang::CodeGen::ABIArgInfo::InAlloca:
llvm_unreachable("Need to handle InAlloca during signature expansion");
}
}
std::pair<PointerAuthSchema, PointerAuthEntity>
irgen::getCoroutineResumeFunctionPointerAuth(IRGenModule &IGM,
CanSILFunctionType fnType) {
switch (fnType->getCoroutineKind()) {
case SILCoroutineKind::None:
llvm_unreachable("not a coroutine");
case SILCoroutineKind::YieldMany:
return { IGM.getOptions().PointerAuth.YieldManyResumeFunctions,
PointerAuthEntity::forYieldTypes(fnType) };
case SILCoroutineKind::YieldOnce:
return { IGM.getOptions().PointerAuth.YieldOnceResumeFunctions,
PointerAuthEntity::forYieldTypes(fnType) };
}
llvm_unreachable("bad coroutine kind");
}
static void
emitRetconCoroutineEntry(IRGenFunction &IGF, CanSILFunctionType fnType,
NativeCCEntryPointArgumentEmission &emission,
llvm::Intrinsic::ID idIntrinsic, Size bufferSize,
Alignment bufferAlignment) {
auto prototype =
IGF.IGM.getOpaquePtr(IGF.IGM.getAddrOfContinuationPrototype(fnType));
// Use malloc and free as our allocator.
auto allocFn = IGF.IGM.getOpaquePtr(IGF.IGM.getMallocFn());
auto deallocFn = IGF.IGM.getOpaquePtr(IGF.IGM.getFreeFn());
// Call the right 'llvm.coro.id.retcon' variant.
llvm::Value *buffer = emission.getCoroutineBuffer();
llvm::Value *id = IGF.Builder.CreateIntrinsicCall(idIntrinsic, {
llvm::ConstantInt::get(IGF.IGM.Int32Ty, bufferSize.getValue()),
llvm::ConstantInt::get(IGF.IGM.Int32Ty, bufferAlignment.getValue()),
buffer,
prototype,
allocFn,
deallocFn
});
// Call 'llvm.coro.begin', just for consistency with the normal pattern.
// This serves as a handle that we can pass around to other intrinsics.
auto hdl = IGF.Builder.CreateIntrinsicCall(
llvm::Intrinsic::coro_begin,
{id, llvm::ConstantPointerNull::get(IGF.IGM.Int8PtrTy)});
// Set the coroutine handle; this also flags that is a coroutine so that
// e.g. dynamic allocas use the right code generation.
IGF.setCoroutineHandle(hdl);
auto *pt = IGF.Builder.IRBuilderBase::CreateAlloca(IGF.IGM.Int1Ty,
/*array size*/ nullptr,
"earliest insert point");
IGF.setEarliestInsertionPoint(pt);
}
void IRGenModule::addAsyncCoroIDMapping(llvm::GlobalVariable *asyncFunctionPointer,
llvm::CallInst *coro_id_builtin) {
AsyncCoroIDsForPadding[asyncFunctionPointer] = coro_id_builtin;
}
llvm::CallInst *
IRGenModule::getAsyncCoroIDMapping(llvm::GlobalVariable *asyncFunctionPointer) {
auto found = AsyncCoroIDsForPadding.find(asyncFunctionPointer);
if (found == AsyncCoroIDsForPadding.end())
return nullptr;
return found->second;
}
void IRGenModule::markAsyncFunctionPointerForPadding(
llvm::GlobalVariable *asyncFunctionPointer) {
AsyncCoroIDsForPadding[asyncFunctionPointer] = nullptr;
}
bool IRGenModule::isAsyncFunctionPointerMarkedForPadding(
llvm::GlobalVariable *asyncFunctionPointer) {
auto found = AsyncCoroIDsForPadding.find(asyncFunctionPointer);
if (found == AsyncCoroIDsForPadding.end())
return false;
return found->second == nullptr;
}
void irgen::emitAsyncFunctionEntry(IRGenFunction &IGF,
const AsyncContextLayout &layout,
LinkEntity asyncFunction,
unsigned asyncContextIndex) {
auto &IGM = IGF.IGM;
auto size = layout.getSize();
auto asyncFuncPointerVar = cast<llvm::GlobalVariable>(IGM.getAddrOfAsyncFunctionPointer(asyncFunction));
bool isPadded = IGM
.isAsyncFunctionPointerMarkedForPadding(asyncFuncPointerVar);
auto asyncFuncPointer = IGF.Builder.CreateBitOrPointerCast(
asyncFuncPointerVar, IGM.Int8PtrTy);
if (isPadded) {
size = std::max(layout.getSize(),
NumWords_AsyncLet * IGM.getPointerSize());
}
auto *id = IGF.Builder.CreateIntrinsicCall(
llvm::Intrinsic::coro_id_async,
{llvm::ConstantInt::get(IGM.Int32Ty, size.getValue()),
llvm::ConstantInt::get(IGM.Int32Ty, 16),
llvm::ConstantInt::get(IGM.Int32Ty, asyncContextIndex),
asyncFuncPointer});
IGM.addAsyncCoroIDMapping(asyncFuncPointerVar, id);
// Call 'llvm.coro.begin', just for consistency with the normal pattern.
// This serves as a handle that we can pass around to other intrinsics.
auto hdl = IGF.Builder.CreateIntrinsicCall(
llvm::Intrinsic::coro_begin,
{id, llvm::ConstantPointerNull::get(IGM.Int8PtrTy)});
// Set the coroutine handle; this also flags that is a coroutine so that
// e.g. dynamic allocas use the right code generation.
IGF.setCoroutineHandle(hdl);
auto *pt = IGF.Builder.IRBuilderBase::CreateAlloca(IGF.IGM.Int1Ty,
/*array size*/ nullptr,
"earliest insert point");
IGF.setEarliestInsertionPoint(pt);
IGF.setupAsync(asyncContextIndex);
}
void irgen::emitYieldOnceCoroutineEntry(
IRGenFunction &IGF, CanSILFunctionType fnType,
NativeCCEntryPointArgumentEmission &emission) {
emitRetconCoroutineEntry(IGF, fnType, emission,
llvm::Intrinsic::coro_id_retcon_once,
getYieldOnceCoroutineBufferSize(IGF.IGM),
getYieldOnceCoroutineBufferAlignment(IGF.IGM));
}
void irgen::emitYieldManyCoroutineEntry(
IRGenFunction &IGF, CanSILFunctionType fnType,
NativeCCEntryPointArgumentEmission &emission) {
emitRetconCoroutineEntry(IGF, fnType, emission,
llvm::Intrinsic::coro_id_retcon,
getYieldManyCoroutineBufferSize(IGF.IGM),
getYieldManyCoroutineBufferAlignment(IGF.IGM));
}
static Address createOpaqueBufferAlloca(IRGenFunction &IGF,
Size size, Alignment align) {
auto ty = llvm::ArrayType::get(IGF.IGM.Int8Ty, size.getValue());
auto addr = IGF.createAlloca(ty, align);
addr = IGF.Builder.CreateStructGEP(addr, 0, Size(0));
IGF.Builder.CreateLifetimeStart(addr, size);
return addr;
}
Address irgen::emitAllocYieldOnceCoroutineBuffer(IRGenFunction &IGF) {
return createOpaqueBufferAlloca(IGF, getYieldOnceCoroutineBufferSize(IGF.IGM),
getYieldOnceCoroutineBufferAlignment(IGF.IGM));
}
Address irgen::emitAllocYieldManyCoroutineBuffer(IRGenFunction &IGF) {
return createOpaqueBufferAlloca(IGF, getYieldManyCoroutineBufferSize(IGF.IGM),
getYieldManyCoroutineBufferAlignment(IGF.IGM));
}
void irgen::emitDeallocYieldOnceCoroutineBuffer(IRGenFunction &IGF,
Address buffer) {
auto bufferSize = getYieldOnceCoroutineBufferSize(IGF.IGM);
IGF.Builder.CreateLifetimeEnd(buffer, bufferSize);
}
void irgen::emitDeallocYieldManyCoroutineBuffer(IRGenFunction &IGF,
Address buffer) {
auto bufferSize = getYieldManyCoroutineBufferSize(IGF.IGM);
IGF.Builder.CreateLifetimeEnd(buffer, bufferSize);
}
Address irgen::emitAllocAsyncContext(IRGenFunction &IGF,
llvm::Value *sizeValue) {
auto alignment = IGF.IGM.getAsyncContextAlignment();
auto address = IGF.emitTaskAlloc(sizeValue, alignment);
IGF.Builder.CreateLifetimeStart(address, Size(-1) /*dynamic size*/);
return address;
}
void irgen::emitDeallocAsyncContext(IRGenFunction &IGF, Address context) {
IGF.emitTaskDealloc(context);
IGF.Builder.CreateLifetimeEnd(context, Size(-1) /*dynamic size*/);
}
Address irgen::emitStaticAllocAsyncContext(IRGenFunction &IGF,
Size size) {
auto alignment = IGF.IGM.getAsyncContextAlignment();
auto &IGM = IGF.IGM;
auto address = IGF.createAlloca(IGM.Int8Ty, IGM.getSize(size), alignment);
IGF.Builder.CreateLifetimeStart(address, size);
return address;
}
void irgen::emitStaticDeallocAsyncContext(IRGenFunction &IGF, Address context,
Size size) {
IGF.Builder.CreateLifetimeEnd(context, size);
}
llvm::Value *irgen::emitYield(IRGenFunction &IGF,
CanSILFunctionType coroutineType,
Explosion &substValues) {
// TODO: Handle async!
auto coroSignature = IGF.IGM.getSignature(coroutineType);
auto coroInfo = coroSignature.getCoroutineInfo();
// Translate the arguments to an unsubstituted form.
Explosion allComponents;
for (auto yield : coroutineType->getYields())
addNativeArgument(IGF, substValues, coroutineType,
yield, allComponents, false);
// Figure out which arguments need to be yielded directly.
SmallVector<llvm::Value*, 8> yieldArgs;
// Add the direct yield components.
auto directComponents =
allComponents.claim(coroInfo.NumDirectYieldComponents);
yieldArgs.append(directComponents.begin(), directComponents.end());
// The rest need to go into an indirect buffer.
auto indirectComponents = allComponents.claimAll();
auto resultStructTy =
dyn_cast<llvm::StructType>(coroSignature.getType()->getReturnType());
assert((!resultStructTy
&& directComponents.empty()
&& indirectComponents.empty())
|| (resultStructTy
&& resultStructTy->getNumElements() ==
(1 + directComponents.size()
+ unsigned(!indirectComponents.empty()))));
// Fill in the indirect buffer if necessary.
std::optional<Address> indirectBuffer;
Size indirectBufferSize;
if (!indirectComponents.empty()) {
auto bufferStructTy = coroInfo.indirectResultsType;
auto layout = IGF.IGM.DataLayout.getStructLayout(bufferStructTy);
indirectBuffer = IGF.createAlloca(
bufferStructTy, Alignment(layout->getAlignment().value()));
indirectBufferSize = Size(layout->getSizeInBytes());
IGF.Builder.CreateLifetimeStart(*indirectBuffer, indirectBufferSize);
for (size_t i : indices(bufferStructTy->elements())) {
// Skip padding elements.
if (bufferStructTy->getElementType(i)->isArrayTy())
continue;
assert(!indirectComponents.empty() &&
"insufficient number of indirect yield components");
auto addr = IGF.Builder.CreateStructGEP(*indirectBuffer, i, layout);
IGF.Builder.CreateStore(indirectComponents.front(), addr);
indirectComponents = indirectComponents.drop_front();
}
assert(indirectComponents.empty() && "too many indirect yield components");
// Remember to yield the indirect buffer.
yieldArgs.push_back(indirectBuffer->getAddress());
}
// Perform the yield.
auto isUnwind = IGF.Builder.CreateIntrinsicCall(
llvm::Intrinsic::coro_suspend_retcon, {IGF.IGM.Int1Ty}, yieldArgs);
// We're done with the indirect buffer.
if (indirectBuffer) {
IGF.Builder.CreateLifetimeEnd(*indirectBuffer, indirectBufferSize);
}
return isUnwind;
}
/// Add a new set of arguments to the function.
void CallEmission::setArgs(Explosion &adjusted, bool isOutlined,
WitnessMetadata *witnessMetadata) {
assert(state == State::Emitting);
// Add the given number of arguments.
assert(LastArgWritten >= adjusted.size());
size_t targetIndex = LastArgWritten - adjusted.size();
assert(targetIndex <= 1);
LastArgWritten = targetIndex;
auto argIterator = Args.begin() + targetIndex;
for (auto value : adjusted.claimAll()) {
*argIterator++ = value;
}
}
void CallEmission::addFnAttribute(llvm::Attribute::AttrKind attr) {
assert(state == State::Emitting);
auto &attrs = CurCallee.getMutableAttributes();
attrs = attrs.addFnAttribute(IGF.IGM.getLLVMContext(), attr);
}
void CallEmission::addParamAttribute(unsigned paramIndex,
llvm::Attribute::AttrKind attr) {
assert(state == State::Emitting);
auto &attrs = CurCallee.getMutableAttributes();
attrs = attrs.addParamAttribute(IGF.IGM.getLLVMContext(), paramIndex, attr);
}
/// Initialize an Explosion with the parameters of the current
/// function. All of the objects will be added unmanaged. This is
/// really only useful when writing prologue code.
Explosion IRGenFunction::collectParameters() {
Explosion params;
for (auto i = CurFn->arg_begin(), e = CurFn->arg_end(); i != e; ++i)
params.add(&*i);
return params;
}
Address IRGenFunction::createErrorResultSlot(SILType errorType, bool isAsync,
bool setSwiftErrorFlag,
bool isTypedError) {
IRBuilder builder(IGM.getLLVMContext(), IGM.DebugInfo != nullptr);
builder.SetInsertPoint(AllocaIP->getParent(), AllocaIP->getIterator());
auto errorStorageType = isTypedError ? IGM.Int8PtrTy :
cast<FixedTypeInfo>(getTypeInfo(errorType)).getStorageType();
auto errorAlignment = isTypedError ? IGM.getPointerAlignment() :
cast<FixedTypeInfo>(getTypeInfo(errorType)).getFixedAlignment();
// Pass an address for zero sized types.
if (!isTypedError && !setSwiftErrorFlag &&
cast<FixedTypeInfo>(getTypeInfo(errorType)).getFixedSize() == Size(0)) {
errorStorageType = IGM.Int8PtrTy;
errorAlignment = IGM.getPointerAlignment();
}
// Create the alloca. We don't use allocateStack because we're
// not allocating this in stack order.
auto addr = createAlloca(errorStorageType,
errorAlignment, "swifterror");
if (!isAsync) {
builder.SetInsertPoint(getEarliestInsertionPoint()->getParent(),
getEarliestInsertionPoint()->getIterator());
}
// Only add the swifterror attribute on ABIs that pass it in a register.
// We create a shadow stack location of the swifterror parameter for the
// debugger on platforms that pass swifterror by reference and so we can't
// mark the parameter with a swifterror attribute for these.
// The slot for async callees cannot be annotated swifterror because those
// errors are never passed in registers but rather are always passed
// indirectly in the async context.
if (IGM.ShouldUseSwiftError && !isAsync && setSwiftErrorFlag)
cast<llvm::AllocaInst>(addr.getAddress())->setSwiftError(true);
// Initialize at the alloca point.
if (setSwiftErrorFlag) {
auto nullError = llvm::ConstantPointerNull::get(
cast<llvm::PointerType>(errorStorageType));
builder.CreateStore(nullError, addr);
}
return addr;
}
/// Fetch the error result slot.
Address IRGenFunction::getCalleeErrorResultSlot(SILType errorType,
bool isTypedError) {
if (!CalleeErrorResultSlot.isValid()) {
CalleeErrorResultSlot = createErrorResultSlot(errorType, /*isAsync=*/false,
/*setSwiftError*/true,
isTypedError);
}
return CalleeErrorResultSlot;
}
Address IRGenFunction::getCalleeTypedErrorResultSlot(SILType errorType) {
auto &errorTI = cast<FixedTypeInfo>(getTypeInfo(errorType));
if (!CalleeTypedErrorResultSlot.isValid() ||
CalleeTypedErrorResultSlot.getElementType() != errorTI.getStorageType()) {
CalleeTypedErrorResultSlot =
createErrorResultSlot(errorType, /*isAsync=*/false,
/*setSwiftErrorFlag*/false);
}
return CalleeTypedErrorResultSlot;
}
void IRGenFunction::setCalleeTypedErrorResultSlot(Address addr) {
CalleeTypedErrorResultSlot = addr;
}
/// Fetch the error result slot received from the caller.
Address IRGenFunction::getCallerErrorResultSlot() {
assert(CallerErrorResultSlot.isValid() && "no error result slot!");
assert(isa<llvm::Argument>(CallerErrorResultSlot.getAddress()) &&
!isAsync() ||
isa<llvm::LoadInst>(CallerErrorResultSlot.getAddress()) && isAsync() &&
"error result slot is local!");
return CallerErrorResultSlot;
}
// Set the error result slot. This should only be done in the prologue.
void IRGenFunction::setCallerErrorResultSlot(Address address) {
assert(!CallerErrorResultSlot.isValid() &&
"already have a caller error result slot!");
assert(isa<llvm::PointerType>(address.getAddress()->getType()));
CallerErrorResultSlot = address;
if (!isAsync()) {
CalleeErrorResultSlot = address;
}
}
// Set the error result slot for a typed throw for the current function.
// This should only be done in the prologue.
void IRGenFunction::setCallerTypedErrorResultSlot(Address address) {
assert(!CallerTypedErrorResultSlot.isValid() &&
"already have a caller error result slot!");
assert(isa<llvm::PointerType>(address.getAddress()->getType()));
CallerTypedErrorResultSlot = address;
}
Address IRGenFunction::getCallerTypedErrorResultSlot() {
assert(CallerTypedErrorResultSlot.isValid() && "no error result slot!");
assert(isa<llvm::Argument>(CallerTypedErrorResultSlot.getAddress()));
return CallerTypedErrorResultSlot;
}
/// Emit the basic block that 'return' should branch to and insert it into
/// the current function. This creates a second
/// insertion point that most blocks should be inserted before.
void IRGenFunction::emitBBForReturn() {
ReturnBB = createBasicBlock("return");
CurFn->insert(CurFn->end(), ReturnBB);
}
llvm::BasicBlock *IRGenFunction::createExceptionUnwindBlock() {
auto *result = createBasicBlock("exception.unwind");
IRBuilder::SavedInsertionPointRAII insertRAII(Builder, result);
// Create a catch-all landing pad.
// FIXME: Refactor Clang/lib/CodeGen to call into Clang here.
// FIXME: MSVC support.
llvm::LandingPadInst *lpad = Builder.CreateLandingPad(
llvm::StructType::get(IGM.Int8PtrTy, IGM.Int32Ty), 0);
lpad->addClause(llvm::ConstantPointerNull::get(IGM.Int8PtrTy));
// The trap with a message informs the user that the exception hasn't
// been caught. The trap creates a new debug inline frame for the message,
// so ensure that the current debug location is preserved.
auto oldDebugLoc = Builder.getCurrentDebugLocation();
emitTrap(IGM.Context.LangOpts.EnableObjCInterop
? "unhandled C++ / Objective-C exception"
: "unhandled C++ exception",
/*Unreachable=*/true);
Builder.SetCurrentDebugLocation(oldDebugLoc);
ExceptionUnwindBlocks.push_back(result);
return result;
}
void IRGenFunction::createExceptionTrapScope(
llvm::function_ref<void(llvm::BasicBlock *, llvm::BasicBlock *)>
invokeEmitter) {
auto *invokeNormalDest = createBasicBlock("invoke.cont");
auto *invokeUnwindDest = createExceptionUnwindBlock();
invokeEmitter(invokeNormalDest, invokeUnwindDest);
Builder.emitBlock(invokeNormalDest);
}
/// Emit the prologue for the function.
void IRGenFunction::emitPrologue() {
// Set up the IRBuilder.
llvm::BasicBlock *EntryBB = createBasicBlock("entry");
assert(CurFn->empty() && "prologue already emitted?");
CurFn->insert(CurFn->end(), EntryBB);
Builder.SetInsertPoint(EntryBB);
// Set up the alloca insertion point.
AllocaIP = Builder.IRBuilderBase::CreateAlloca(IGM.Int1Ty,
/*array size*/ nullptr,
"alloca point");
EarliestIP = AllocaIP;
}
/// Emit a branch to the return block and set the insert point there.
/// Returns true if the return block is reachable, false otherwise.
bool IRGenFunction::emitBranchToReturnBB() {
// If there are no edges to the return block, we never want to emit it.
if (ReturnBB->use_empty()) {
ReturnBB->eraseFromParent();
// Normally this means that we'll just insert the epilogue in the
// current block, but if the current IP is unreachable then so is
// the entire epilogue.
if (!Builder.hasValidIP())
return false;
// Otherwise, branch to it if the current IP is reachable.
} else if (Builder.hasValidIP()) {
Builder.CreateBr(ReturnBB);
Builder.SetInsertPoint(ReturnBB);
// Otherwise, if there is exactly one use of the return block, merge
// it into its predecessor.
} else if (ReturnBB->hasOneUse()) {
// return statements are never emitted as conditional branches.
llvm::BranchInst *Br = cast<llvm::BranchInst>(*ReturnBB->use_begin());
assert(Br->isUnconditional());
Builder.SetInsertPoint(Br->getParent());
Br->eraseFromParent();
ReturnBB->eraseFromParent();
// Otherwise, just move the IP to the return block.
} else {
Builder.SetInsertPoint(ReturnBB);
}
return true;
}
llvm::Function *IRGenModule::getForeignExceptionHandlingPersonalityFunc() {
if (foreignExceptionHandlingPersonalityFunc)
return foreignExceptionHandlingPersonalityFunc;
foreignExceptionHandlingPersonalityFunc = llvm::Function::Create(
llvm::FunctionType::get(Int32Ty, true), llvm::Function::ExternalLinkage,
"__gxx_personality_v0", getModule());
return foreignExceptionHandlingPersonalityFunc;
}
bool IRGenModule::isForeignExceptionHandlingEnabled() const {
// FIXME: Support exceptions on windows MSVC.
if (Triple.isWindowsMSVCEnvironment())
return false;
const auto &clangLangOpts =
Context.getClangModuleLoader()->getClangASTContext().getLangOpts();
return Context.LangOpts.EnableCXXInterop && clangLangOpts.Exceptions &&
!clangLangOpts.IgnoreExceptions;
}
bool IRGenModule::isCxxNoThrow(clang::FunctionDecl *fd, bool defaultNoThrow) {
auto *fpt = fd->getType()->getAs<clang::FunctionProtoType>();
if (!fpt)
return defaultNoThrow;
if (fpt->getExceptionSpecType() ==
clang::ExceptionSpecificationType::EST_Unevaluated) {
// Clang might not have evaluated the exception spec for
// a constructor, so force the evaluation of it.
auto &clangSema = Context.getClangModuleLoader()->getClangSema();
clangSema.EvaluateImplicitExceptionSpec(fd->getLocation(), fd);
fpt = fd->getType()->getAs<clang::FunctionProtoType>();
if (!fpt)
return defaultNoThrow;
}
return fpt->isNothrow();
}
/// Emit the epilogue for the function.
void IRGenFunction::emitEpilogue() {
if (EarliestIP != AllocaIP)
EarliestIP->eraseFromParent();
// Destroy the alloca insertion point.
AllocaIP->eraseFromParent();
// Add exception unwind blocks and additional exception handling info
// if needed.
if (!ExceptionUnwindBlocks.empty() ||
callsAnyAlwaysInlineThunksWithForeignExceptionTraps) {
// The function should have an unwind table when catching exceptions.
CurFn->addFnAttr(llvm::Attribute::getWithUWTableKind(
*IGM.LLVMContext, llvm::UWTableKind::Default));
llvm::Constant *personality;
if (IGM.isSwiftExceptionPersonalityFeatureAvailable()) {
// The function should use our personality routine
auto swiftPersonality = IGM.getExceptionPersonalityFunctionPointer();
personality = swiftPersonality.getDirectPointer();
} else {
personality = IGM.getForeignExceptionHandlingPersonalityFunc();
}
CurFn->setPersonalityFn(personality);
}
for (auto *bb : ExceptionUnwindBlocks)
CurFn->insert(CurFn->end(), bb);
}
std::pair<Address, Size>
irgen::allocateForCoercion(IRGenFunction &IGF,
llvm::Type *fromTy,
llvm::Type *toTy,
const llvm::Twine &basename) {
auto &DL = IGF.IGM.DataLayout;
auto fromSize = DL.getTypeSizeInBits(fromTy);
auto toSize = DL.getTypeSizeInBits(toTy);
auto bufferTy = fromSize >= toSize
? fromTy
: toTy;
llvm::Align alignment =
std::max(DL.getABITypeAlign(fromTy), DL.getABITypeAlign(toTy));
auto buffer = IGF.createAlloca(bufferTy, Alignment(alignment.value()),
basename + ".coerced");
Size size(std::max(fromSize, toSize));
return {buffer, size};
}
llvm::Value* IRGenFunction::coerceValue(llvm::Value *value, llvm::Type *toTy,
const llvm::DataLayout &DL)
{
llvm::Type *fromTy = value->getType();
assert(fromTy != toTy && "Unexpected same types in type coercion!");
assert(!fromTy->isVoidTy()
&& "Unexpected void source type in type coercion!");
assert(!toTy->isVoidTy()
&& "Unexpected void destination type in type coercion!");
// Use the pointer/pointer and pointer/int casts if we can.
if (toTy->isPointerTy()) {
if (fromTy->isPointerTy())
return Builder.CreateBitCast(value, toTy);
if (fromTy == IGM.IntPtrTy)
return Builder.CreateIntToPtr(value, toTy);
} else if (fromTy->isPointerTy()) {
if (toTy == IGM.IntPtrTy) {
return Builder.CreatePtrToInt(value, toTy);
}
}
// Otherwise we need to store, bitcast, and load.
Address address; Size size;
std::tie(address, size) = allocateForCoercion(*this, fromTy, toTy,
value->getName() + ".coercion");
Builder.CreateLifetimeStart(address, size);
auto orig = Builder.CreateElementBitCast(address, fromTy);
Builder.CreateStore(value, orig);
auto coerced = Builder.CreateElementBitCast(address, toTy);
auto loaded = Builder.CreateLoad(coerced);
Builder.CreateLifetimeEnd(address, size);
return loaded;
}
void IRGenFunction::emitScalarReturn(llvm::Type *resultType,
Explosion &result) {
if (result.empty()) {
Builder.CreateRetVoid();
return;
}
auto *ABIType = CurFn->getReturnType();
if (result.size() == 1) {
auto *returned = result.claimNext();
if (ABIType != returned->getType())
returned = coerceValue(returned, ABIType, IGM.DataLayout);
Builder.CreateRet(returned);
return;
}
// Multiple return values are returned as a struct.
assert(cast<llvm::StructType>(resultType)->getNumElements() == result.size());
llvm::Value *resultAgg = llvm::UndefValue::get(resultType);
for (unsigned i = 0, e = result.size(); i != e; ++i) {
llvm::Value *elt = result.claimNext();
resultAgg = Builder.CreateInsertValue(resultAgg, elt, i);
}
if (ABIType != resultType)
resultAgg = coerceValue(resultAgg, ABIType, IGM.DataLayout);
Builder.CreateRet(resultAgg);
}
/// Adjust the alignment of the alloca pointed to by \p allocaAddr to the
/// required alignment of the struct \p type.
static void adjustAllocaAlignment(const llvm::DataLayout &DL,
Address allocaAddr, llvm::StructType *type) {
auto layout = DL.getStructLayout(type);
Alignment layoutAlignment = Alignment(layout->getAlignment().value());
auto alloca = cast<llvm::AllocaInst>(allocaAddr.getAddress());
if (alloca->getAlign() < layoutAlignment.getValue()) {
alloca->setAlignment(
llvm::MaybeAlign(layoutAlignment.getValue()).valueOrOne());
allocaAddr = Address(allocaAddr.getAddress(), allocaAddr.getElementType(),
layoutAlignment);
}
}
unsigned NativeConventionSchema::size() const {
if (empty())
return 0;
unsigned size = 0;
Lowering.enumerateComponents([&](clang::CharUnits offset,
clang::CharUnits end,
llvm::Type *type) { ++size; });
return size;
}
static bool canMatchByTruncation(IRGenModule &IGM,
ArrayRef<llvm::Type*> expandedTys,
const ExplosionSchema &schema) {
// If the schemas don't even match in number, we have to go
// through memory.
if (expandedTys.size() != schema.size() || expandedTys.empty())
return false;
if (expandedTys.size() == 1) return false;
// If there are multiple elements, the pairs of types need to
// match in size upto the penultimate for the truncation to work.
size_t e = expandedTys.size();
for (size_t i = 0; i != e - 1; ++i) {
// Check that we can truncate the last element.
llvm::Type *outputTy = schema[i].getScalarType();
llvm::Type *inputTy = expandedTys[i];
if (inputTy != outputTy &&
IGM.DataLayout.getTypeSizeInBits(inputTy) !=
IGM.DataLayout.getTypeSizeInBits(outputTy))
return false;
}
llvm::Type *outputTy = schema[e-1].getScalarType();
llvm::Type *inputTy = expandedTys[e-1];
return inputTy == outputTy || (IGM.DataLayout.getTypeSizeInBits(inputTy) ==
IGM.DataLayout.getTypeSizeInBits(outputTy)) ||
(IGM.DataLayout.getTypeSizeInBits(inputTy) >
IGM.DataLayout.getTypeSizeInBits(outputTy) &&
isa<llvm::IntegerType>(inputTy) && isa<llvm::IntegerType>(outputTy));
}
Explosion NativeConventionSchema::mapFromNative(IRGenModule &IGM,
IRGenFunction &IGF,
Explosion &native,
SILType type) const {
if (native.empty()) {
assert(empty() && "Empty explosion must match the native convention");
return Explosion();
}
assert(!empty());
auto *nativeTy = getExpandedType(IGM);
auto expandedTys = expandScalarOrStructTypeToArray(nativeTy);
auto &TI = IGM.getTypeInfo(type);
auto schema = TI.getSchema();
// The expected explosion type.
auto *explosionTy = schema.getScalarResultType(IGM);
// Check whether we can coerce the explosion to the expected type convention.
auto &DataLayout = IGM.DataLayout;
Explosion nonNativeExplosion;
if (canCoerceToSchema(IGM, expandedTys, schema)) {
if (native.size() == 1) {
auto *elt = native.claimNext();
if (explosionTy != elt->getType()) {
if (isa<llvm::IntegerType>(explosionTy) &&
isa<llvm::IntegerType>(elt->getType())) {
// [HACK: Atomic-Bool-IRGen] In the case of _Atomic(_Bool), Clang
// treats it as i8 whereas Swift works with i1, so we need to zext
// in that case.
elt = IGF.Builder.CreateZExtOrTrunc(elt, explosionTy);
} else {
elt = IGF.coerceValue(elt, explosionTy, DataLayout);
}
}
nonNativeExplosion.add(elt);
return nonNativeExplosion;
} else if (nativeTy == explosionTy) {
native.transferInto(nonNativeExplosion, native.size());
return nonNativeExplosion;
}
// Otherwise, we have to go through memory if we can match by truncation.
} else if (canMatchByTruncation(IGM, expandedTys, schema)) {
assert(expandedTys.size() == schema.size());
for (size_t i = 0, e = expandedTys.size(); i != e; ++i) {
auto *elt = native.claimNext();
auto *schemaTy = schema[i].getScalarType();
auto *nativeTy = elt->getType();
assert(nativeTy == expandedTys[i]);
if (schemaTy == nativeTy) {
// elt = elt
} else if (DataLayout.getTypeSizeInBits(schemaTy) ==
DataLayout.getTypeSizeInBits(nativeTy))
elt = IGF.coerceValue(elt, schemaTy, DataLayout);
else {
assert(DataLayout.getTypeSizeInBits(schemaTy) <
DataLayout.getTypeSizeInBits(nativeTy));
elt = IGF.Builder.CreateTrunc(elt, schemaTy);
}
nonNativeExplosion.add(elt);
}
return nonNativeExplosion;
}
// If not, go through memory.
auto &loadableTI = cast<LoadableTypeInfo>(TI);
// We can get two layouts if there are overlapping ranges in the legal type
// sequence.
llvm::StructType *coercionTy, *overlappedCoercionTy;
SmallVector<unsigned, 8> expandedTyIndicesMap;
std::tie(coercionTy, overlappedCoercionTy) =
getCoercionTypes(IGM, expandedTyIndicesMap);
// Get the larger layout out of those two.
auto coercionSize = DataLayout.getTypeSizeInBits(coercionTy);
auto overlappedCoercionSize =
DataLayout.getTypeSizeInBits(overlappedCoercionTy);
llvm::StructType *largerCoercion = coercionSize >= overlappedCoercionSize
? coercionTy
: overlappedCoercionTy;
// Allocate a temporary for the coercion.
Address temporary;
Size tempSize;
std::tie(temporary, tempSize) = allocateForCoercion(
IGF, largerCoercion, loadableTI.getStorageType(), "temp-coercion");
// Make sure we have sufficiently large alignment.
adjustAllocaAlignment(DataLayout, temporary, coercionTy);
adjustAllocaAlignment(DataLayout, temporary, overlappedCoercionTy);
auto &Builder = IGF.Builder;
Builder.CreateLifetimeStart(temporary, tempSize);
// Store the expanded type elements.
auto coercionAddr = Builder.CreateElementBitCast(temporary, coercionTy);
unsigned expandedMapIdx = 0;
auto eltsArray = native.claimAll();
SmallVector<llvm::Value *, 8> nativeElts(eltsArray.begin(), eltsArray.end());
auto storeToFn = [&](llvm::StructType *ty, Address structAddr) {
for (auto eltIndex : indices(ty->elements())) {
auto layout = DataLayout.getStructLayout(ty);
auto eltTy = ty->getElementType(eltIndex);
// Skip padding fields.
if (eltTy->isArrayTy())
continue;
Address eltAddr = Builder.CreateStructGEP(structAddr, eltIndex, layout);
auto index = expandedTyIndicesMap[expandedMapIdx];
assert(index < nativeElts.size() && nativeElts[index] != nullptr);
auto nativeElt = nativeElts[index];
Builder.CreateStore(nativeElt, eltAddr);
nativeElts[index] = nullptr;
++expandedMapIdx;
}
};
storeToFn(coercionTy, coercionAddr);
if (!overlappedCoercionTy->isEmptyTy()) {
auto overlappedCoercionAddr =
Builder.CreateElementBitCast(temporary, overlappedCoercionTy);
storeToFn(overlappedCoercionTy, overlappedCoercionAddr);
}
// Reload according to the types schema.
Address storageAddr =
Builder.CreateElementBitCast(temporary, loadableTI.getStorageType());
loadableTI.loadAsTake(IGF, storageAddr, nonNativeExplosion);
Builder.CreateLifetimeEnd(temporary, tempSize);
return nonNativeExplosion;
}
Explosion NativeConventionSchema::mapIntoNative(IRGenModule &IGM,
IRGenFunction &IGF,
Explosion &fromNonNative,
SILType type,
bool isOutlined) const {
if (fromNonNative.empty()) {
assert(empty() && "Empty explosion must match the native convention");
return Explosion();
}
assert(!requiresIndirect() && "Expected direct convention");
assert(!empty());
auto *nativeTy = getExpandedType(IGM);
auto expandedTys = expandScalarOrStructTypeToArray(nativeTy);
auto &TI = IGM.getTypeInfo(type);
auto schema = TI.getSchema();
auto *explosionTy = schema.getScalarResultType(IGM);
// Check whether we can coerce the explosion to the expected type convention.
auto &DataLayout = IGM.DataLayout;
Explosion nativeExplosion;
if (canCoerceToSchema(IGM, expandedTys, schema)) {
if (fromNonNative.size() == 1) {
auto *elt = fromNonNative.claimNext();
if (nativeTy != elt->getType()) {
if (isa<llvm::IntegerType>(nativeTy) &&
isa<llvm::IntegerType>(elt->getType())) {
// [HACK: Atomic-Bool-IRGen] In the case of _Atomic(_Bool), Clang
// treats it as i8 whereas Swift works with i1, so we need to trunc
// in that case.
elt = IGF.Builder.CreateZExtOrTrunc(elt, nativeTy);
} else {
elt = IGF.coerceValue(elt, nativeTy, DataLayout);
}
}
nativeExplosion.add(elt);
return nativeExplosion;
} else if (nativeTy == explosionTy) {
fromNonNative.transferInto(nativeExplosion, fromNonNative.size());
return nativeExplosion;
}
// Otherwise, we have to go through memory if we can't match by truncation.
} else if (canMatchByTruncation(IGM, expandedTys, schema)) {
assert(expandedTys.size() == schema.size());
for (size_t i = 0, e = expandedTys.size(); i != e; ++i) {
auto *elt = fromNonNative.claimNext();
auto *schemaTy = elt->getType();
auto *nativeTy = expandedTys[i];
assert(schema[i].getScalarType() == schemaTy);
if (schemaTy == nativeTy) {
// elt = elt
} else if (DataLayout.getTypeSizeInBits(schemaTy) ==
DataLayout.getTypeSizeInBits(nativeTy))
elt = IGF.coerceValue(elt, nativeTy, DataLayout);
else {
assert(DataLayout.getTypeSizeInBits(schemaTy) <
DataLayout.getTypeSizeInBits(nativeTy));
elt = IGF.Builder.CreateZExt(elt, nativeTy);
}
nativeExplosion.add(elt);
}
return nativeExplosion;
}
// If not, go through memory.
auto &loadableTI = cast<LoadableTypeInfo>(TI);
// We can get two layouts if there are overlapping ranges in the legal type
// sequence.
llvm::StructType *coercionTy, *overlappedCoercionTy;
SmallVector<unsigned, 8> expandedTyIndicesMap;
std::tie(coercionTy, overlappedCoercionTy) =
getCoercionTypes(IGM, expandedTyIndicesMap);
// Get the larger layout out of those two.
auto coercionSize = DataLayout.getTypeSizeInBits(coercionTy);
auto overlappedCoercionSize =
DataLayout.getTypeSizeInBits(overlappedCoercionTy);
llvm::StructType *largerCoercion = coercionSize >= overlappedCoercionSize
? coercionTy
: overlappedCoercionTy;
// Allocate a temporary for the coercion.
Address temporary;
Size tempSize;
std::tie(temporary, tempSize) = allocateForCoercion(
IGF, largerCoercion, loadableTI.getStorageType(), "temp-coercion");
// Make sure we have sufficiently large alignment.
adjustAllocaAlignment(DataLayout, temporary, coercionTy);
adjustAllocaAlignment(DataLayout, temporary, overlappedCoercionTy);
auto &Builder = IGF.Builder;
Builder.CreateLifetimeStart(temporary, tempSize);
// Initialize the memory of the temporary.
Address storageAddr =
Builder.CreateElementBitCast(temporary, loadableTI.getStorageType());
loadableTI.initialize(IGF, fromNonNative, storageAddr, isOutlined);
// Load the expanded type elements from memory.
auto coercionAddr = Builder.CreateElementBitCast(temporary, coercionTy);
unsigned expandedMapIdx = 0;
SmallVector<llvm::Value *, 8> expandedElts(expandedTys.size(), nullptr);
auto loadFromFn = [&](llvm::StructType *ty, Address structAddr) {
for (auto eltIndex : indices(ty->elements())) {
auto layout = DataLayout.getStructLayout(ty);
auto eltTy = ty->getElementType(eltIndex);
// Skip padding fields.
if (eltTy->isArrayTy())
continue;
Address eltAddr = Builder.CreateStructGEP(structAddr, eltIndex, layout);
llvm::Value *elt = Builder.CreateLoad(eltAddr);
auto index = expandedTyIndicesMap[expandedMapIdx];
assert(expandedElts[index] == nullptr);
expandedElts[index] = elt;
++expandedMapIdx;
}
};
loadFromFn(coercionTy, coercionAddr);
if (!overlappedCoercionTy->isEmptyTy()) {
auto overlappedCoercionAddr =
Builder.CreateElementBitCast(temporary, overlappedCoercionTy);
loadFromFn(overlappedCoercionTy, overlappedCoercionAddr);
}
Builder.CreateLifetimeEnd(temporary, tempSize);
// Add the values to the explosion.
for (auto *val : expandedElts)
nativeExplosion.add(val);
assert(expandedTys.size() == nativeExplosion.size());
return nativeExplosion;
}
Explosion IRGenFunction::coerceValueTo(SILType fromTy, Explosion &from,
SILType toTy) {
if (fromTy == toTy)
return std::move(from);
auto &fromTI = cast<LoadableTypeInfo>(IGM.getTypeInfo(fromTy));
auto &toTI = cast<LoadableTypeInfo>(IGM.getTypeInfo(toTy));
Explosion result;
if (fromTI.getStorageType()->isPointerTy() &&
toTI.getStorageType()->isPointerTy()) {
auto ptr = from.claimNext();
ptr = Builder.CreateBitCast(ptr, toTI.getStorageType());
result.add(ptr);
return result;
}
auto temporary = toTI.allocateStack(*this, toTy, "coerce.temp");
auto addr =
Address(Builder.CreateBitCast(temporary.getAddressPointer(),
fromTI.getStorageType()->getPointerTo()),
fromTI.getStorageType(), temporary.getAlignment());
fromTI.initialize(*this, from, addr, false);
toTI.loadAsTake(*this, temporary.getAddress(), result);
toTI.deallocateStack(*this, temporary, toTy);
return result;
}
void IRGenFunction::emitScalarReturn(SILType returnResultType,
SILType funcResultType, Explosion &result,
bool isSwiftCCReturn, bool isOutlined) {
if (result.empty()) {
assert(IGM.getTypeInfo(returnResultType)
.nativeReturnValueSchema(IGM)
.empty() &&
"Empty explosion must match the native calling convention");
Builder.CreateRetVoid();
return;
}
// In the native case no coercion is needed.
if (isSwiftCCReturn) {
result = coerceValueTo(returnResultType, result, funcResultType);
auto &nativeSchema =
IGM.getTypeInfo(funcResultType).nativeReturnValueSchema(IGM);
assert(!nativeSchema.requiresIndirect());
Explosion native = nativeSchema.mapIntoNative(IGM, *this, result,
funcResultType, isOutlined);
if (native.size() == 1) {
Builder.CreateRet(native.claimNext());
return;
}
llvm::Value *nativeAgg =
llvm::UndefValue::get(nativeSchema.getExpandedType(IGM));
for (unsigned i = 0, e = native.size(); i != e; ++i) {
llvm::Value *elt = native.claimNext();
nativeAgg = Builder.CreateInsertValue(nativeAgg, elt, i);
}
Builder.CreateRet(nativeAgg);
return;
}
// Otherwise we potentially need to coerce the type. We don't need to go
// through the mapping to the native calling convention.
auto *ABIType = CurFn->getReturnType();
if (result.size() == 1) {
auto *returned = result.claimNext();
if (ABIType != returned->getType())
returned = coerceValue(returned, ABIType, IGM.DataLayout);
Builder.CreateRet(returned);
return;
}
auto &resultTI = IGM.getTypeInfo(returnResultType);
auto schema = resultTI.getSchema();
auto *bodyType = schema.getScalarResultType(IGM);
// Multiple return values are returned as a struct.
assert(cast<llvm::StructType>(bodyType)->getNumElements() == result.size());
llvm::Value *resultAgg = llvm::UndefValue::get(bodyType);
for (unsigned i = 0, e = result.size(); i != e; ++i) {
llvm::Value *elt = result.claimNext();
resultAgg = Builder.CreateInsertValue(resultAgg, elt, i);
}
if (ABIType != bodyType)
resultAgg = coerceValue(resultAgg, ABIType, IGM.DataLayout);
Builder.CreateRet(resultAgg);
}
/// Modify the given variable to hold a pointer whose type is the
/// LLVM lowering of the given function type, and return the signature
/// for the type.
Signature irgen::emitCastOfFunctionPointer(IRGenFunction &IGF,
llvm::Value *&fnPtr,
CanSILFunctionType fnType,
bool forAsyncReturn) {
// Figure out the function type.
// FIXME: Cache async signature.
auto sig = forAsyncReturn ? Signature::forAsyncReturn(IGF.IGM, fnType)
: IGF.IGM.getSignature(fnType);
// Emit the cast.
fnPtr = IGF.Builder.CreateBitCast(fnPtr, sig.getType()->getPointerTo());
// Return the information.
return sig;
}
Callee irgen::getBlockPointerCallee(IRGenFunction &IGF,
llvm::Value *blockPtr,
CalleeInfo &&info) {
// Grab the block pointer and make it the first physical argument.
llvm::PointerType *blockPtrTy = IGF.IGM.ObjCBlockPtrTy;
auto castBlockPtr = IGF.Builder.CreateBitCast(blockPtr, blockPtrTy);
// Extract the invocation pointer for blocks.
llvm::Value *invokeFnPtrPtr =
IGF.Builder.CreateStructGEP(IGF.IGM.ObjCBlockStructTy, castBlockPtr, 3);
Address invokeFnPtrAddr(invokeFnPtrPtr, IGF.IGM.FunctionPtrTy,
IGF.IGM.getPointerAlignment());
llvm::Value *invokeFnPtr = IGF.Builder.CreateLoad(invokeFnPtrAddr);
auto sig = emitCastOfFunctionPointer(IGF, invokeFnPtr, info.OrigFnType);
auto &schema = IGF.getOptions().PointerAuth.BlockInvocationFunctionPointers;
auto authInfo = PointerAuthInfo::emit(IGF, schema,
invokeFnPtrAddr.getAddress(),
info.OrigFnType);
auto fn = FunctionPointer::createSigned(FunctionPointer::Kind::Function,
invokeFnPtr, authInfo, sig);
return Callee(std::move(info), fn, blockPtr);
}
Callee irgen::getSwiftFunctionPointerCallee(
IRGenFunction &IGF, llvm::Value *fnPtr, llvm::Value *dataPtr,
CalleeInfo &&calleeInfo, bool castOpaqueToRefcountedContext, bool isClosure) {
auto sig = emitCastOfFunctionPointer(IGF, fnPtr, calleeInfo.OrigFnType);
auto authInfo =
PointerAuthInfo::forFunctionPointer(IGF.IGM, calleeInfo.OrigFnType);
auto fn = isClosure ? FunctionPointer::createSignedClosure(calleeInfo.OrigFnType, fnPtr, authInfo, sig) :
FunctionPointer::createSigned(calleeInfo.OrigFnType, fnPtr, authInfo, sig,
true);
if (castOpaqueToRefcountedContext) {
assert(dataPtr && dataPtr->getType() == IGF.IGM.OpaquePtrTy &&
"Expecting trivial closure context");
dataPtr = IGF.Builder.CreateBitCast(dataPtr, IGF.IGM.RefCountedPtrTy);
}
return Callee(std::move(calleeInfo), fn, dataPtr);
}
Callee irgen::getCFunctionPointerCallee(IRGenFunction &IGF,
llvm::Value *fnPtr,
CalleeInfo &&calleeInfo) {
auto sig = emitCastOfFunctionPointer(IGF, fnPtr, calleeInfo.OrigFnType);
auto authInfo =
PointerAuthInfo::forFunctionPointer(IGF.IGM, calleeInfo.OrigFnType);
auto fn = FunctionPointer::createSigned(FunctionPointer::Kind::Function,
fnPtr, authInfo, sig);
return Callee(std::move(calleeInfo), fn);
}
FunctionPointer FunctionPointer::forDirect(IRGenModule &IGM,
llvm::Constant *fnPtr,
llvm::Constant *secondaryValue,
CanSILFunctionType fnType) {
return forDirect(fnType, fnPtr, secondaryValue, IGM.getSignature(fnType));
}
StringRef FunctionPointer::getName(IRGenModule &IGM) const {
assert(isConstant());
switch (getBasicKind()) {
case BasicKind::Function:
return getRawPointer()->getName();
case BasicKind::AsyncFunctionPointer: {
auto *asyncFnPtr = getDirectPointer();
// Handle windows style async function pointers.
if (auto *ce = dyn_cast<llvm::ConstantExpr>(asyncFnPtr)) {
if (ce->getOpcode() == llvm::Instruction::IntToPtr) {
asyncFnPtr = cast<llvm::Constant>(asyncFnPtr->getOperand(0));
}
}
asyncFnPtr = cast<llvm::Constant>(asyncFnPtr->stripPointerCasts());
return IGM
.getSILFunctionForAsyncFunctionPointer(asyncFnPtr)->getName();
}
}
llvm_unreachable("unhandled case");
}
llvm::Value *FunctionPointer::getPointer(IRGenFunction &IGF) const {
switch (getBasicKind()) {
case BasicKind::Function:
return Value;
case BasicKind::AsyncFunctionPointer: {
if (auto *rawFunction = getRawAsyncFunction()) {
// If the pointer to the underlying function is available, it means that
// this FunctionPointer instance was created via
// FunctionPointer::forDirect and as such has no AuthInfo.
assert(!AuthInfo && "have PointerAuthInfo for an async FunctionPointer "
"for which the raw function is known");
return rawFunction;
}
auto *fnPtr = Value;
if (auto authInfo = AuthInfo) {
fnPtr = emitPointerAuthAuth(IGF, fnPtr, authInfo);
if (IGF.IGM.getOptions().IndirectAsyncFunctionPointer)
fnPtr = emitIndirectAsyncFunctionPointer(IGF, fnPtr);
}
auto *descriptorPtr =
IGF.Builder.CreateBitCast(fnPtr, IGF.IGM.AsyncFunctionPointerPtrTy);
auto *addrPtr = IGF.Builder.CreateStructGEP(IGF.IGM.AsyncFunctionPointerTy,
descriptorPtr, 0);
auto *result = IGF.emitLoadOfCompactFunctionPointer(
Address(addrPtr, IGF.IGM.RelativeAddressTy,
IGF.IGM.getPointerAlignment()),
/*isFar*/ false,
/*expectedType*/ getFunctionType());
if (auto codeAuthInfo = AuthInfo.getCorrespondingCodeAuthInfo()) {
result = emitPointerAuthSign(IGF, result, codeAuthInfo);
}
return result;
}
}
llvm_unreachable("unhandled case");
}
FunctionPointer FunctionPointer::forExplosionValue(IRGenFunction &IGF,
llvm::Value *fnPtr,
CanSILFunctionType fnType) {
// Bitcast out of an opaque pointer type.
assert(fnPtr->getType() == IGF.IGM.Int8PtrTy);
auto sig = emitCastOfFunctionPointer(IGF, fnPtr, fnType);
auto authInfo = PointerAuthInfo::forFunctionPointer(IGF.IGM, fnType);
return FunctionPointer(fnType, fnPtr, authInfo, sig);
}
llvm::Value *
FunctionPointer::getExplosionValue(IRGenFunction &IGF,
CanSILFunctionType fnType) const {
llvm::Value *fnPtr = getRawPointer();
// Re-sign to the appropriate schema for this function pointer type.
auto resultAuthInfo = PointerAuthInfo::forFunctionPointer(IGF.IGM, fnType);
if (getAuthInfo() != resultAuthInfo) {
fnPtr = emitPointerAuthResign(IGF, fnPtr, getAuthInfo(), resultAuthInfo);
}
// Bitcast to an opaque pointer type.
fnPtr = IGF.Builder.CreateBitCast(fnPtr, IGF.IGM.Int8PtrTy);
return fnPtr;
}
FunctionPointer FunctionPointer::getAsFunction(IRGenFunction &IGF) const {
switch (getBasicKind()) {
case FunctionPointer::BasicKind::Function:
return *this;
case FunctionPointer::BasicKind::AsyncFunctionPointer: {
auto authInfo = AuthInfo.getCorrespondingCodeAuthInfo();
return FunctionPointer(Kind::Function, getPointer(IGF), authInfo, Sig);
}
}
llvm_unreachable("unhandled case");
}
void irgen::emitAsyncReturn(
IRGenFunction &IGF, AsyncContextLayout &asyncLayout,
CanSILFunctionType fnType,
std::optional<ArrayRef<llvm::Value *>> nativeResultArgs) {
auto contextAddr = asyncLayout.emitCastTo(IGF, IGF.getAsyncContext());
auto returnToCallerLayout = asyncLayout.getResumeParentLayout();
auto returnToCallerAddr =
returnToCallerLayout.project(IGF, contextAddr, std::nullopt);
Explosion fn;
cast<LoadableTypeInfo>(returnToCallerLayout.getType())
.loadAsCopy(IGF, returnToCallerAddr, fn);
llvm::Value *fnVal = fn.claimNext();
if (auto schema = IGF.IGM.getOptions().PointerAuth.AsyncContextResume) {
Address fieldAddr = returnToCallerLayout.project(IGF, contextAddr,
/*offsets*/ std::nullopt);
auto authInfo = PointerAuthInfo::emit(IGF, schema, fieldAddr.getAddress(),
PointerAuthEntity());
fnVal = emitPointerAuthAuth(IGF, fnVal, authInfo);
}
auto sig = emitCastOfFunctionPointer(IGF, fnVal, fnType, true);
auto fnPtr = FunctionPointer::createUnsigned(FunctionPointer::Kind::Function,
fnVal, sig);
SmallVector<llvm::Value*, 4> Args;
// Get the current async context.
Args.push_back(IGF.getAsyncContext());
if (nativeResultArgs) {
for (auto nativeResultArg : *nativeResultArgs)
Args.push_back(nativeResultArg);
}
// Setup the coro.end.async intrinsic call.
auto &Builder = IGF.Builder;
auto mustTailCallFn = IGF.createAsyncDispatchFn(fnPtr,Args);
auto handle = IGF.getCoroutineHandle();
auto rawFnPtr =
Builder.CreateBitOrPointerCast(fnPtr.getRawPointer(), IGF.IGM.Int8PtrTy);
SmallVector<llvm::Value*, 8> arguments;
arguments.push_back(handle);
arguments.push_back(/*is unwind*/Builder.getFalse());
arguments.push_back(mustTailCallFn);
arguments.push_back(rawFnPtr);
for (auto *arg: Args)
arguments.push_back(arg);
Builder.CreateIntrinsicCall(llvm::Intrinsic::coro_end_async, arguments);
if (IGF.IGM.AsyncTailCallKind == llvm::CallInst::TCK_MustTail) {
Builder.CreateUnreachable();
} else {
// If target doesn't support musttail (e.g. WebAssembly), the function
// passed to coro.end.async can return control back to the caller.
// So use ret void instead of unreachable to allow it.
Builder.CreateRetVoid();
}
}
void irgen::emitAsyncReturn(IRGenFunction &IGF, AsyncContextLayout &asyncLayout,
SILType funcResultTypeInContext,
CanSILFunctionType fnType, Explosion &result,
Explosion &error) {
assert((fnType->hasErrorResult() && !error.empty()) ||
(!fnType->hasErrorResult() && error.empty()));
auto &IGM = IGF.IGM;
// Map the explosion to the native result type.
std::optional<ArrayRef<llvm::Value *>> nativeResults = std::nullopt;
SmallVector<llvm::Value *, 16> nativeResultsStorage;
SILFunctionConventions conv(fnType, IGF.getSILModule());
auto &nativeSchema =
IGM.getTypeInfo(funcResultTypeInContext).nativeReturnValueSchema(IGM);
if (result.empty() && !nativeSchema.empty()) {
if (!nativeSchema.requiresIndirect())
// When we throw, we set the return values to undef.
nativeSchema.enumerateComponents([&](clang::CharUnits begin,
clang::CharUnits end,
llvm::Type *componentTy) {
nativeResultsStorage.push_back(llvm::UndefValue::get(componentTy));
});
if (!error.empty())
nativeResultsStorage.push_back(error.claimNext());
nativeResults = nativeResultsStorage;
} else if (!result.empty()) {
assert(!nativeSchema.empty());
assert(!nativeSchema.requiresIndirect());
Explosion native = nativeSchema.mapIntoNative(
IGM, IGF, result, funcResultTypeInContext, false /*isOutlined*/);
while (!native.empty()) {
nativeResultsStorage.push_back(native.claimNext());
}
if (!error.empty())
nativeResultsStorage.push_back(error.claimNext());
nativeResults = nativeResultsStorage;
} else if (!error.empty()) {
nativeResultsStorage.push_back(error.claimNext());
nativeResults = nativeResultsStorage;
}
emitAsyncReturn(IGF, asyncLayout, fnType, nativeResults);
}
FunctionPointer
IRGenFunction::getFunctionPointerForResumeIntrinsic(llvm::Value *resume) {
auto *fnTy = llvm::FunctionType::get(
IGM.VoidTy, {IGM.Int8PtrTy},
false /*vaargs*/);
auto attrs = IGM.constructInitialAttributes();
attrs = attrs.addParamAttribute(IGM.getLLVMContext(), 0,
llvm::Attribute::SwiftAsync);
auto signature =
Signature(fnTy, attrs, IGM.SwiftAsyncCC);
auto fnPtr = FunctionPointer::createUnsigned(
FunctionPointer::Kind::Function,
Builder.CreateBitOrPointerCast(resume, fnTy->getPointerTo()), signature);
return fnPtr;
}
Address irgen::emitAutoDiffCreateLinearMapContextWithType(
IRGenFunction &IGF, llvm::Value *topLevelSubcontextMetatype) {
topLevelSubcontextMetatype = IGF.Builder.CreateBitCast(
topLevelSubcontextMetatype, IGF.IGM.TypeMetadataPtrTy);
auto *call = IGF.Builder.CreateCall(
IGF.IGM.getAutoDiffCreateLinearMapContextWithTypeFunctionPointer(),
{topLevelSubcontextMetatype});
call->setDoesNotThrow();
call->setCallingConv(IGF.IGM.SwiftCC);
return Address(call, IGF.IGM.RefCountedStructTy,
IGF.IGM.getPointerAlignment());
}
Address irgen::emitAutoDiffProjectTopLevelSubcontext(
IRGenFunction &IGF, Address context) {
auto *call = IGF.Builder.CreateCall(
IGF.IGM.getAutoDiffProjectTopLevelSubcontextFunctionPointer(),
{context.getAddress()});
call->setDoesNotThrow();
call->setCallingConv(IGF.IGM.SwiftCC);
return Address(call, IGF.IGM.Int8Ty, IGF.IGM.getPointerAlignment());
}
Address irgen::emitAutoDiffAllocateSubcontextWithType(
IRGenFunction &IGF, Address context, llvm::Value *subcontextMetatype) {
subcontextMetatype =
IGF.Builder.CreateBitCast(subcontextMetatype, IGF.IGM.TypeMetadataPtrTy);
auto *call = IGF.Builder.CreateCall(
IGF.IGM.getAutoDiffAllocateSubcontextWithTypeFunctionPointer(),
{context.getAddress(), subcontextMetatype});
call->setDoesNotThrow();
call->setCallingConv(IGF.IGM.SwiftCC);
return Address(call, IGF.IGM.Int8Ty, IGF.IGM.getPointerAlignment());
}
FunctionPointer
irgen::getFunctionPointerForDispatchCall(IRGenModule &IGM,
const FunctionPointer &fn) {
// Strip off the return type. The original function pointer signature
// captured both the entry point type and the resume function type.
auto *fnTy = llvm::FunctionType::get(
IGM.VoidTy, fn.getSignature().getType()->params(), false /*vaargs*/);
auto signature =
Signature(fnTy, fn.getSignature().getAttributes(), IGM.SwiftAsyncCC);
auto fnPtr = FunctionPointer::createSigned(FunctionPointer::Kind::Function,
fn.getRawPointer(),
fn.getAuthInfo(), signature);
return fnPtr;
}
void irgen::forwardAsyncCallResult(IRGenFunction &IGF,
CanSILFunctionType fnType,
AsyncContextLayout &layout,
llvm::CallInst *call) {
auto &IGM = IGF.IGM;
auto numAsyncContextParams =
Signature::forAsyncReturn(IGM, fnType).getAsyncContextIndex() + 1;
llvm::Value *result = call;
auto *suspendResultTy = cast<llvm::StructType>(result->getType());
Explosion resultExplosion;
Explosion errorExplosion;
auto hasError = fnType->hasErrorResult();
std::optional<ArrayRef<llvm::Value *>> nativeResults = std::nullopt;
SmallVector<llvm::Value *, 16> nativeResultsStorage;
if (suspendResultTy->getNumElements() == numAsyncContextParams) {
// no result to forward.
assert(!hasError);
} else {
auto &Builder = IGF.Builder;
auto resultTys =
llvm::ArrayRef(suspendResultTy->element_begin() + numAsyncContextParams,
suspendResultTy->element_end());
for (unsigned i = 0, e = resultTys.size(); i != e; ++i) {
llvm::Value *elt =
Builder.CreateExtractValue(result, numAsyncContextParams + i);
nativeResultsStorage.push_back(elt);
}
nativeResults = nativeResultsStorage;
}
emitAsyncReturn(IGF, layout, fnType, nativeResults);
}
llvm::FunctionType *FunctionPointer::getFunctionType() const {
// Static async function pointers can read the type off the secondary value
// (the function definition.
if (SecondaryValue) {
assert(kind == FunctionPointer::Kind::AsyncFunctionPointer);
return cast<llvm::Function>(SecondaryValue)->getFunctionType();
}
if (awaitSignature) {
return cast<llvm::FunctionType>(awaitSignature);
}
// Read the function type off the global or else from the Signature.
if (auto *constant = dyn_cast<llvm::Constant>(Value)) {
auto *gv = dyn_cast<llvm::GlobalValue>(Value);
if (!gv) {
return Sig.getType();
}
if (useSignature) { // Because of various casting (e.g thin_to_thick) the
// signature of the function Value might mismatch
// (e.g no context argument).
return Sig.getType();
}
return cast<llvm::FunctionType>(gv->getValueType());
}
return Sig.getType();
}
|