1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287
|
//===--- GenDecl.cpp - IR Generation for Declarations ---------------------===//
//
// 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 local and global
// declarations in Swift.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/ASTContext.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/AST/Module.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/TypeMemberVisitor.h"
#include "swift/AST/Types.h"
#include "swift/ClangImporter/ClangModule.h"
#include "swift/Demangling/ManglingMacros.h"
#include "swift/IRGen/Linking.h"
#include "swift/Runtime/HeapObject.h"
#include "swift/SIL/FormalLinkage.h"
#include "swift/SIL/SILDebugScope.h"
#include "swift/SIL/SILModule.h"
#include "swift/Subsystems.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/GlobalDecl.h"
#include "clang/CodeGen/CodeGenABITypes.h"
#include "clang/CodeGen/ModuleBuilder.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/GlobalAlias.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Value.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/ConvertUTF.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SaveAndRestore.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/Utils/ModuleUtils.h"
#include "Callee.h"
#include "ClassTypeInfo.h"
#include "ConformanceDescription.h"
#include "ConstantBuilder.h"
#include "Explosion.h"
#include "FixedTypeInfo.h"
#include "GenCall.h"
#include "GenConstant.h"
#include "GenClass.h"
#include "GenDecl.h"
#include "GenMeta.h"
#include "GenObjC.h"
#include "GenOpaque.h"
#include "GenPointerAuth.h"
#include "GenProto.h"
#include "GenType.h"
#include "IRGenDebugInfo.h"
#include "IRGenFunction.h"
#include "IRGenMangler.h"
#include "IRGenModule.h"
#include "LoadableTypeInfo.h"
#include "MetadataRequest.h"
#include "ProtocolInfo.h"
#include "Signature.h"
#include "StructLayout.h"
using namespace swift;
using namespace irgen;
llvm::cl::opt<bool> UseBasicDynamicReplacement(
"basic-dynamic-replacement", llvm::cl::init(false),
llvm::cl::desc("Basic implementation of dynamic replacement"));
namespace {
/// Add methods, properties, and protocol conformances from a JITed extension
/// to an ObjC class using the ObjC runtime.
///
/// This must happen after ObjCProtocolInitializerVisitor if any @objc protocols
/// were defined in the TU.
class CategoryInitializerVisitor
: public ClassMemberVisitor<CategoryInitializerVisitor>
{
IRGenFunction &IGF;
IRGenModule &IGM = IGF.IGM;
IRBuilder &Builder = IGF.Builder;
FunctionPointer class_replaceMethod;
FunctionPointer class_addProtocol;
llvm::Value *classMetadata;
llvm::Constant *metaclassMetadata;
public:
CategoryInitializerVisitor(IRGenFunction &IGF, ExtensionDecl *ext)
: IGF(IGF)
{
class_replaceMethod = IGM.getClassReplaceMethodFunctionPointer();
class_addProtocol = IGM.getClassAddProtocolFunctionPointer();
CanType origTy = ext->getSelfNominalTypeDecl()
->getDeclaredType()->getCanonicalType();
classMetadata = emitClassHeapMetadataRef(IGF, origTy,
MetadataValueType::ObjCClass,
MetadataState::Complete,
/*allow uninitialized*/ false);
classMetadata = Builder.CreateBitCast(classMetadata, IGM.ObjCClassPtrTy);
metaclassMetadata = IGM.getAddrOfMetaclassObject(
dyn_cast_or_null<ClassDecl>(origTy->getAnyNominal()),
NotForDefinition);
metaclassMetadata = llvm::ConstantExpr::getBitCast(metaclassMetadata,
IGM.ObjCClassPtrTy);
// Register ObjC protocol conformances.
for (auto *p : ext->getLocalProtocols()) {
if (!p->isObjC())
continue;
auto protoRefAddr = IGM.getAddrOfObjCProtocolRef(p, NotForDefinition);
auto proto = Builder.CreateLoad(protoRefAddr);
Builder.CreateCall(class_addProtocol, {classMetadata, proto});
}
}
void visitMembers(ExtensionDecl *ext) {
for (Decl *member : ext->getMembers())
visit(member);
}
void visitTypeDecl(TypeDecl *type) {
// We'll visit nested types separately if necessary.
}
void visitMissingDecl(MissingDecl *missing) {
llvm_unreachable("missing decl in IRGen");
}
void visitMissingMemberDecl(MissingMemberDecl *placeholder) {}
void visitFuncDecl(FuncDecl *method) {
if (!requiresObjCMethodDescriptor(method)) return;
// Don't emit getters/setters for @NSManaged methods.
if (method->getAttrs().hasAttribute<NSManagedAttr>())
return;
auto descriptor = emitObjCMethodDescriptorParts(IGM, method,
/*concrete*/true);
// When generating JIT'd code, we need to call sel_registerName() to force
// the runtime to unique the selector.
llvm::Value *sel = Builder.CreateCall(
IGM.getObjCSelRegisterNameFunctionPointer(), descriptor.selectorRef);
llvm::Value *args[] = {
method->isStatic() ? metaclassMetadata : classMetadata,
sel,
descriptor.impl,
descriptor.typeEncoding
};
Builder.CreateCall(class_replaceMethod, args);
}
// Can't be added in an extension.
void visitDestructorDecl(DestructorDecl *dtor) {}
void visitConstructorDecl(ConstructorDecl *constructor) {
if (!requiresObjCMethodDescriptor(constructor)) return;
auto descriptor = emitObjCMethodDescriptorParts(IGM, constructor,
/*concrete*/true);
// When generating JIT'd code, we need to call sel_registerName() to force
// the runtime to unique the selector.
llvm::Value *sel = Builder.CreateCall(
IGM.getObjCSelRegisterNameFunctionPointer(), descriptor.selectorRef);
llvm::Value *args[] = {
classMetadata,
sel,
descriptor.impl,
descriptor.typeEncoding
};
Builder.CreateCall(class_replaceMethod, args);
}
void visitPatternBindingDecl(PatternBindingDecl *binding) {
// Ignore the PBD and just handle the individual vars.
}
void visitVarDecl(VarDecl *prop) {
if (!requiresObjCPropertyDescriptor(IGM, prop)) return;
// FIXME: register property metadata in addition to the methods.
// ObjC doesn't have a notion of class properties, so we'd only do this
// for instance properties.
// Don't emit getters/setters for @NSManaged properties.
if (prop->getAttrs().hasAttribute<NSManagedAttr>())
return;
auto descriptor = emitObjCGetterDescriptorParts(IGM, prop);
// When generating JIT'd code, we need to call sel_registerName() to force
// the runtime to unique the selector.
llvm::Value *sel = Builder.CreateCall(
IGM.getObjCSelRegisterNameFunctionPointer(), descriptor.selectorRef);
auto theClass = prop->isStatic() ? metaclassMetadata : classMetadata;
llvm::Value *getterArgs[] =
{theClass, sel, descriptor.impl, descriptor.typeEncoding};
Builder.CreateCall(class_replaceMethod, getterArgs);
if (prop->isSettable(prop->getDeclContext())) {
auto descriptor = emitObjCSetterDescriptorParts(IGM, prop);
sel = Builder.CreateCall(IGM.getObjCSelRegisterNameFunctionPointer(),
descriptor.selectorRef);
llvm::Value *setterArgs[] =
{theClass, sel, descriptor.impl, descriptor.typeEncoding};
Builder.CreateCall(class_replaceMethod, setterArgs);
}
}
void visitSubscriptDecl(SubscriptDecl *subscript) {
assert(!subscript->isStatic() && "objc doesn't support class subscripts");
if (!requiresObjCSubscriptDescriptor(IGM, subscript)) return;
auto descriptor = emitObjCGetterDescriptorParts(IGM, subscript);
// When generating JIT'd code, we need to call sel_registerName() to force
// the runtime to unique the selector.
llvm::Value *sel = Builder.CreateCall(
IGM.getObjCSelRegisterNameFunctionPointer(), descriptor.selectorRef);
llvm::Value *getterArgs[] =
{classMetadata, sel, descriptor.impl, descriptor.typeEncoding};
Builder.CreateCall(class_replaceMethod, getterArgs);
if (subscript->supportsMutation()) {
auto descriptor = emitObjCSetterDescriptorParts(IGM, subscript);
sel = Builder.CreateCall(IGM.getObjCSelRegisterNameFunctionPointer(),
descriptor.selectorRef);
llvm::Value *setterArgs[] =
{classMetadata, sel, descriptor.impl, descriptor.typeEncoding};
Builder.CreateCall(class_replaceMethod, setterArgs);
}
}
};
/// Create a descriptor for JITed @objc protocol using the ObjC runtime.
class ObjCProtocolInitializerVisitor
: public ClassMemberVisitor<ObjCProtocolInitializerVisitor>
{
IRGenFunction &IGF;
IRGenModule &IGM = IGF.IGM;
IRBuilder &Builder = IGF.Builder;
FunctionPointer objc_getProtocol, objc_allocateProtocol,
objc_registerProtocol, protocol_addMethodDescription,
protocol_addProtocol;
llvm::Value *NewProto = nullptr;
public:
ObjCProtocolInitializerVisitor(IRGenFunction &IGF)
: IGF(IGF)
{
objc_getProtocol = IGM.getGetObjCProtocolFunctionPointer();
objc_allocateProtocol = IGM.getAllocateObjCProtocolFunctionPointer();
objc_registerProtocol = IGM.getRegisterObjCProtocolFunctionPointer();
protocol_addMethodDescription =
IGM.getProtocolAddMethodDescriptionFunctionPointer();
protocol_addProtocol = IGM.getProtocolAddProtocolFunctionPointer();
}
void visitMembers(ProtocolDecl *proto) {
// Check if the ObjC runtime already has a descriptor for this
// protocol. If so, use it.
SmallString<32> buf;
auto protocolName
= IGM.getAddrOfGlobalString(proto->getObjCRuntimeName(buf));
auto existing = Builder.CreateCall(objc_getProtocol, protocolName);
auto isNull = Builder.CreateICmpEQ(existing,
llvm::ConstantPointerNull::get(IGM.ProtocolDescriptorPtrTy));
auto existingBB = IGF.createBasicBlock("existing_protocol");
auto newBB = IGF.createBasicBlock("new_protocol");
auto contBB = IGF.createBasicBlock("cont");
Builder.CreateCondBr(isNull, newBB, existingBB);
// Nothing to do if there's already a descriptor.
Builder.emitBlock(existingBB);
Builder.CreateBr(contBB);
Builder.emitBlock(newBB);
// Allocate the protocol descriptor.
NewProto = Builder.CreateCall(objc_allocateProtocol, protocolName);
// Add the parent protocols.
for (auto parentProto : proto->getInheritedProtocols()) {
if (!parentProto->isObjC())
continue;
auto parentAddr =
IGM.getAddrOfObjCProtocolRef(parentProto, NotForDefinition);
llvm::Value *parent = Builder.CreateLoad(parentAddr);
parent = IGF.Builder.CreateBitCast(parent, IGM.ProtocolDescriptorPtrTy);
Builder.CreateCall(protocol_addProtocol, {NewProto, parent});
}
// Add the members.
for (Decl *member : proto->getMembers())
visit(member);
// Register it.
Builder.CreateCall(objc_registerProtocol, NewProto);
Builder.CreateBr(contBB);
// Store the reference to the runtime's idea of the protocol descriptor.
Builder.emitBlock(contBB);
auto result = Builder.CreatePHI(IGM.ProtocolDescriptorPtrTy, 2);
result->addIncoming(existing, existingBB);
result->addIncoming(NewProto, newBB);
llvm::Value *ref =
IGM.getAddrOfObjCProtocolRef(proto, NotForDefinition).getAddress();
ref = IGF.Builder.CreateBitCast(ref,
IGM.ProtocolDescriptorPtrTy->getPointerTo());
Builder.CreateStore(result, ref, IGM.getPointerAlignment());
}
void visitTypeDecl(TypeDecl *type) {
// We'll visit nested types separately if necessary.
}
void visitMissingDecl(MissingDecl *missing) {
llvm_unreachable("missing decl in IRGen");
}
void visitMissingMemberDecl(MissingMemberDecl *placeholder) {}
void visitAbstractFunctionDecl(AbstractFunctionDecl *method) {
if (isa<AccessorDecl>(method)) {
// Accessors are handled as part of their AbstractStorageDecls.
return;
}
auto descriptor = emitObjCMethodDescriptorParts(IGM, method,
/*concrete*/false);
// When generating JIT'd code, we need to call sel_registerName() to force
// the runtime to unique the selector.
llvm::Value *sel = Builder.CreateCall(
IGM.getObjCSelRegisterNameFunctionPointer(), descriptor.selectorRef);
llvm::Value *args[] = {
NewProto, sel, descriptor.typeEncoding,
// required?
llvm::ConstantInt::get(IGM.ObjCBoolTy,
!method->getAttrs().hasAttribute<OptionalAttr>()),
// instance?
llvm::ConstantInt::get(IGM.ObjCBoolTy,
isa<ConstructorDecl>(method) || method->isInstanceMember()),
};
Builder.CreateCall(protocol_addMethodDescription, args);
}
void visitPatternBindingDecl(PatternBindingDecl *binding) {
// Ignore the PBD and just handle the individual vars.
}
void visitAbstractStorageDecl(AbstractStorageDecl *prop) {
// TODO: Add properties to protocol.
auto descriptor = emitObjCGetterDescriptorParts(IGM, prop);
// When generating JIT'd code, we need to call sel_registerName() to force
// the runtime to unique the selector.
llvm::Value *sel = Builder.CreateCall(
IGM.getObjCSelRegisterNameFunctionPointer(), descriptor.selectorRef);
llvm::Value *getterArgs[] = {
NewProto, sel, descriptor.typeEncoding,
// required?
llvm::ConstantInt::get(IGM.ObjCBoolTy,
!prop->getAttrs().hasAttribute<OptionalAttr>()),
// instance?
llvm::ConstantInt::get(IGM.ObjCBoolTy,
prop->isInstanceMember()),
};
Builder.CreateCall(protocol_addMethodDescription, getterArgs);
if (prop->isSettable(nullptr)) {
auto descriptor = emitObjCSetterDescriptorParts(IGM, prop);
sel = Builder.CreateCall(IGM.getObjCSelRegisterNameFunctionPointer(),
descriptor.selectorRef);
llvm::Value *setterArgs[] = {
NewProto, sel, descriptor.typeEncoding,
// required?
llvm::ConstantInt::get(IGM.ObjCBoolTy,
!prop->getAttrs().hasAttribute<OptionalAttr>()),
// instance?
llvm::ConstantInt::get(IGM.ObjCBoolTy,
prop->isInstanceMember()),
};
Builder.CreateCall(protocol_addMethodDescription, setterArgs);
}
}
};
} // end anonymous namespace
namespace {
class PrettySourceFileEmission : public llvm::PrettyStackTraceEntry {
const SourceFile &SF;
public:
explicit PrettySourceFileEmission(const SourceFile &SF) : SF(SF) {}
void print(raw_ostream &os) const override {
os << "While emitting IR for source file " << SF.getFilename() << '\n';
}
};
class PrettySynthesizedFileUnitEmission : public llvm::PrettyStackTraceEntry {
const SynthesizedFileUnit &SFU;
public:
explicit PrettySynthesizedFileUnitEmission(const SynthesizedFileUnit &SFU)
: SFU(SFU) {}
void print(raw_ostream &os) const override {
os << "While emitting IR for synthesized file" << &SFU << "\n";
}
};
} // end anonymous namespace
/// Emit all the top-level code in the source file.
void IRGenModule::emitSourceFile(SourceFile &SF) {
// Type-check the file if we haven't already (this may be necessary for .sil
// files, which don't get fully type-checked by parsing).
performTypeChecking(SF);
PrettySourceFileEmission StackEntry(SF);
// Emit types and other global decls.
for (auto *decl : SF.getTopLevelDecls())
emitGlobalDecl(decl);
for (auto *decl : SF.getHoistedDecls())
emitGlobalDecl(decl);
for (auto *localDecl : SF.getLocalTypeDecls())
emitGlobalDecl(localDecl);
for (auto *opaqueDecl : SF.getOpaqueReturnTypeDecls())
maybeEmitOpaqueTypeDecl(opaqueDecl);
}
/// Emit all the top-level code in the synthesized file unit.
void IRGenModule::emitSynthesizedFileUnit(SynthesizedFileUnit &SFU) {
PrettySynthesizedFileUnitEmission StackEntry(SFU);
for (auto *decl : SFU.getTopLevelDecls())
emitGlobalDecl(decl);
}
/// Collect elements of an already-existing global list with the given
/// \c name into \c list.
///
/// We use this when Clang code generation might populate the list.
static void collectGlobalList(IRGenModule &IGM,
SmallVectorImpl<llvm::WeakTrackingVH> &list,
StringRef name) {
if (auto *existing = IGM.Module.getGlobalVariable(name)) {
auto *globals = cast<llvm::ConstantArray>(existing->getInitializer());
for (auto &use : globals->operands()) {
auto *global = use.get();
list.push_back(global);
}
existing->eraseFromParent();
}
std::for_each(list.begin(), list.end(),
[](const llvm::WeakTrackingVH &global) {
assert(!isa<llvm::GlobalValue>(global) ||
!cast<llvm::GlobalValue>(global)->isDeclaration() &&
"all globals in the 'used' list must be definitions");
});
}
/// Emit a global list, i.e. a global constant array holding all of a
/// list of values. Generally these lists are for various LLVM
/// metadata or runtime purposes.
static llvm::GlobalVariable *
emitGlobalList(IRGenModule &IGM, ArrayRef<llvm::WeakTrackingVH> handles,
StringRef name, StringRef section,
llvm::GlobalValue::LinkageTypes linkage, llvm::Type *eltTy,
bool isConstant, bool asContiguousArray, bool canBeStrippedByLinker = false) {
// Do nothing if the list is empty.
if (handles.empty()) return nullptr;
// For global lists that actually get linked (as opposed to notional
// ones like @llvm.used), it's important to set an explicit alignment
// so that the linker doesn't accidentally put padding in the list.
Alignment alignment = IGM.getPointerAlignment();
if (!asContiguousArray) {
// Emit as individual globals, which is required for conditional runtime
// records to work.
for (auto &handle : handles) {
llvm::Constant *elt = cast<llvm::Constant>(&*handle);
std::string eltName = name.str() + "_" + elt->getName().str();
if (elt->getType() != eltTy)
elt = llvm::ConstantExpr::getBitCast(elt, eltTy);
auto var = new llvm::GlobalVariable(IGM.Module, eltTy, isConstant,
linkage, elt, eltName);
var->setSection(section);
var->setAlignment(llvm::MaybeAlign(alignment.getValue()));
disableAddressSanitizer(IGM, var);
if (llvm::GlobalValue::isLocalLinkage(linkage)) {
if (canBeStrippedByLinker)
IGM.addCompilerUsedGlobal(var);
else
IGM.addUsedGlobal(var);
}
if (IGM.IRGen.Opts.ConditionalRuntimeRecords) {
// Allow dead-stripping `var` (the runtime record from the global list)
// when `handle` / `elt` (the underlaying entity) is not referenced.
IGM.appendLLVMUsedConditionalEntry(var, elt->stripPointerCasts());
}
}
return nullptr;
}
// We have an array of value handles, but we need an array of constants.
SmallVector<llvm::Constant*, 8> elts;
elts.reserve(handles.size());
for (auto &handle : handles) {
auto elt = cast<llvm::Constant>(&*handle);
if (elt->getType() != eltTy)
elt = llvm::ConstantExpr::getBitCast(elt, eltTy);
elts.push_back(elt);
}
auto varTy = llvm::ArrayType::get(eltTy, elts.size());
auto init = llvm::ConstantArray::get(varTy, elts);
auto var = new llvm::GlobalVariable(IGM.Module, varTy, isConstant, linkage,
init, name);
var->setSection(section);
// Do not set alignment and don't set disableAddressSanitizer on @llvm.used
// and @llvm.compiler.used. Doing so confuses LTO (merging) and they're not
// going to end up as real global symbols in the binary anyways.
if (name != "llvm.used" && name != "llvm.compiler.used") {
var->setAlignment(llvm::MaybeAlign(alignment.getValue()));
disableAddressSanitizer(IGM, var);
}
// Mark the variable as used if doesn't have external linkage.
// (Note that we'd specifically like to not put @llvm.used in itself.)
if (llvm::GlobalValue::isLocalLinkage(linkage)) {
if (canBeStrippedByLinker)
IGM.addCompilerUsedGlobal(var);
else
IGM.addUsedGlobal(var);
}
return var;
}
void IRGenModule::emitRuntimeRegistration() {
// Duck out early if we have nothing to register.
// Note that we don't consider `RuntimeResolvableTypes2` here because the
// current Swift runtime is unable to handle move-only types at runtime, and
// we only use this runtime registration path in JIT mode, so there are no
// ABI forward compatibility concerns.
//
// We should incorporate the types from
// `RuntimeResolvableTypes2` into the list of types to register when we do
// have runtime support in place.
if (SwiftProtocols.empty() && ProtocolConformances.empty() &&
RuntimeResolvableTypes.empty() &&
(!ObjCInterop || (ObjCProtocols.empty() && ObjCClasses.empty() &&
ObjCCategoryDecls.empty())))
return;
// Find the entry point.
SILFunction *EntryPoint = getSILModule().lookUpFunction(
getSILModule().getASTContext().getEntryPointFunctionName());
// If we're debugging (and not in the REPL), we don't have a
// main. Find a function marked with the LLDBDebuggerFunction
// attribute instead.
if (!EntryPoint && Context.LangOpts.DebuggerSupport) {
for (SILFunction &SF : getSILModule()) {
if (SF.hasLocation()) {
if (Decl* D = SF.getLocation().getAsASTNode<Decl>()) {
if (auto *FD = dyn_cast<FuncDecl>(D)) {
if (FD->getAttrs().hasAttribute<LLDBDebuggerFunctionAttr>()) {
EntryPoint = &SF;
break;
}
}
}
}
}
}
if (!EntryPoint)
return;
llvm::Function *EntryFunction = Module.getFunction(EntryPoint->getName());
if (!EntryFunction)
return;
// Create a new function to contain our logic.
auto fnTy = llvm::FunctionType::get(VoidTy, /*varArg*/ false);
auto RegistrationFunction = llvm::Function::Create(fnTy,
llvm::GlobalValue::PrivateLinkage,
"runtime_registration",
getModule());
RegistrationFunction->setAttributes(constructInitialAttributes());
// Insert a call into the entry function.
{
llvm::BasicBlock *EntryBB = &EntryFunction->getEntryBlock();
llvm::BasicBlock::iterator IP = EntryBB->getFirstInsertionPt();
IRBuilder Builder(getLLVMContext(),
DebugInfo && !Context.LangOpts.DebuggerSupport);
Builder.llvm::IRBuilderBase::SetInsertPoint(EntryBB, IP);
if (DebugInfo && !Context.LangOpts.DebuggerSupport)
DebugInfo->setEntryPointLoc(Builder);
Builder.CreateCall(fnTy, RegistrationFunction, {});
}
IRGenFunction RegIGF(*this, RegistrationFunction);
if (DebugInfo && !Context.LangOpts.DebuggerSupport)
DebugInfo->emitArtificialFunction(RegIGF, RegistrationFunction);
// Register ObjC protocols we added.
if (ObjCInterop) {
if (!ObjCProtocols.empty()) {
// We need to initialize ObjC protocols in inheritance order, parents
// first.
llvm::DenseSet<ProtocolDecl*> protos;
for (auto &proto : ObjCProtocols)
protos.insert(proto.first);
llvm::SmallVector<ProtocolDecl*, 4> protoInitOrder;
std::function<void(ProtocolDecl*)> orderProtocol
= [&](ProtocolDecl *proto) {
// Recursively put parents first.
for (auto parent : proto->getInheritedProtocols())
orderProtocol(parent);
// Skip if we don't need to reify this protocol.
auto found = protos.find(proto);
if (found == protos.end())
return;
protos.erase(found);
protoInitOrder.push_back(proto);
};
while (!protos.empty()) {
orderProtocol(*protos.begin());
}
// Visit the protocols in the order we established.
for (auto *proto : protoInitOrder) {
ObjCProtocolInitializerVisitor(RegIGF)
.visitMembers(proto);
}
}
}
// Register Swift protocols if we added any.
if (!SwiftProtocols.empty()) {
llvm::Constant *protocols = emitSwiftProtocols(/*asContiguousArray*/ true);
llvm::Constant *beginIndices[] = {
llvm::ConstantInt::get(Int32Ty, 0),
llvm::ConstantInt::get(Int32Ty, 0),
};
auto protocolRecordsTy =
llvm::ArrayType::get(ProtocolRecordTy, SwiftProtocols.size());
auto begin = llvm::ConstantExpr::getGetElementPtr(protocolRecordsTy,
protocols, beginIndices);
llvm::Constant *endIndices[] = {
llvm::ConstantInt::get(Int32Ty, 0),
llvm::ConstantInt::get(Int32Ty, SwiftProtocols.size()),
};
auto end = llvm::ConstantExpr::getGetElementPtr(protocolRecordsTy,
protocols, endIndices);
RegIGF.Builder.CreateCall(getRegisterProtocolsFunctionPointer(),
{begin, end});
}
// Register Swift protocol conformances if we added any.
if (llvm::Constant *conformances =
emitProtocolConformances(/*asContiguousArray*/ true)) {
llvm::Constant *beginIndices[] = {
llvm::ConstantInt::get(Int32Ty, 0),
llvm::ConstantInt::get(Int32Ty, 0),
};
auto protocolRecordsTy =
llvm::ArrayType::get(RelativeAddressTy, ProtocolConformances.size());
auto begin = llvm::ConstantExpr::getGetElementPtr(
protocolRecordsTy, conformances, beginIndices);
llvm::Constant *endIndices[] = {
llvm::ConstantInt::get(Int32Ty, 0),
llvm::ConstantInt::get(Int32Ty, ProtocolConformances.size()),
};
auto end = llvm::ConstantExpr::getGetElementPtr(protocolRecordsTy,
conformances, endIndices);
RegIGF.Builder.CreateCall(getRegisterProtocolConformancesFunctionPointer(),
{begin, end});
}
if (!RuntimeResolvableTypes.empty()) {
llvm::Constant *records =
emitTypeMetadataRecords(/*asContiguousArray*/ true);
llvm::Constant *beginIndices[] = {
llvm::ConstantInt::get(Int32Ty, 0),
llvm::ConstantInt::get(Int32Ty, 0),
};
auto typemetadataRecordsTy = llvm::ArrayType::get(
TypeMetadataRecordTy, RuntimeResolvableTypes.size());
auto begin = llvm::ConstantExpr::getGetElementPtr(typemetadataRecordsTy,
records, beginIndices);
llvm::Constant *endIndices[] = {
llvm::ConstantInt::get(Int32Ty, 0),
llvm::ConstantInt::get(Int32Ty, RuntimeResolvableTypes.size()),
};
auto end = llvm::ConstantExpr::getGetElementPtr(typemetadataRecordsTy,
records, endIndices);
RegIGF.Builder.CreateCall(getRegisterTypeMetadataRecordsFunctionPointer(),
{begin, end});
}
// Register Objective-C classes and extensions we added.
if (ObjCInterop) {
for (llvm::WeakTrackingVH &ObjCClass : ObjCClasses) {
RegIGF.Builder.CreateCall(getInstantiateObjCClassFunctionPointer(),
{ObjCClass});
}
for (ExtensionDecl *ext : ObjCCategoryDecls) {
CategoryInitializerVisitor(RegIGF, ext).visitMembers(ext);
}
}
RegIGF.Builder.CreateRetVoid();
}
/// Return the address of the context descriptor representing the given
/// decl context, used as a parent reference for another decl.
///
/// For a nominal type context, this returns the address of the nominal type
/// descriptor.
/// For an extension context, this returns the address of the extension
/// context descriptor.
/// For a module or file unit context, this returns the address of the module
/// context descriptor.
/// For any other kind of context, this returns an anonymous context descriptor
/// for the context.
ConstantReference
IRGenModule::getAddrOfContextDescriptorForParent(DeclContext *parent,
DeclContext *ofChild,
bool fromAnonymousContext) {
switch (parent->getContextKind()) {
case DeclContextKind::AbstractClosureExpr:
case DeclContextKind::SerializedAbstractClosure:
case DeclContextKind::AbstractFunctionDecl:
case DeclContextKind::SubscriptDecl:
case DeclContextKind::EnumElementDecl:
case DeclContextKind::TopLevelCodeDecl:
case DeclContextKind::SerializedTopLevelCodeDecl:
case DeclContextKind::Initializer:
return {getAddrOfAnonymousContextDescriptor(
fromAnonymousContext ? parent : ofChild),
ConstantReference::Direct};
case DeclContextKind::GenericTypeDecl:
if (auto nomTy = dyn_cast<NominalTypeDecl>(parent)) {
return {getAddrOfTypeContextDescriptor(nomTy, DontRequireMetadata),
ConstantReference::Direct};
}
return {getAddrOfAnonymousContextDescriptor(
fromAnonymousContext ? parent : ofChild),
ConstantReference::Direct};
case DeclContextKind::ExtensionDecl: {
auto ext = cast<ExtensionDecl>(parent);
// If the extension is equivalent to its extended context (that is, it's
// in the same module as the original non-protocol type and
// has no constraints), then we can use the original nominal type context
// (assuming there is one).
if (ext->isEquivalentToExtendedContext()) {
auto nominal = ext->getExtendedNominal();
// If the extended type is an ObjC class, it won't have a nominal type
// descriptor, so we'll just emit an extension context.
auto clazz = dyn_cast<ClassDecl>(nominal);
if (!clazz || clazz->isForeign() || hasKnownSwiftMetadata(*this, clazz)) {
IRGen.noteUseOfTypeContextDescriptor(nominal, DontRequireMetadata);
return getAddrOfLLVMVariableOrGOTEquivalent(
LinkEntity::forNominalTypeDescriptor(nominal));
}
}
return {getAddrOfExtensionContextDescriptor(ext),
ConstantReference::Direct};
}
case DeclContextKind::Package:
assert(false && "package decl context kind should not have been reached");
case DeclContextKind::FileUnit:
case DeclContextKind::MacroDecl:
parent = parent->getParentModule();
LLVM_FALLTHROUGH;
case DeclContextKind::Module:
if (auto *D = ofChild->getAsDecl()) {
// If the top-level decl has been marked as moved from another module,
// using @_originallyDefinedIn, we should emit the original module as
// the context because all run-time names of this decl are based on the
// original module name.
auto OriginalModule = D->getAlternateModuleName();
if (!OriginalModule.empty()) {
return {getAddrOfOriginalModuleContextDescriptor(OriginalModule),
ConstantReference::Direct};
}
}
return {getAddrOfModuleContextDescriptor(cast<ModuleDecl>(parent)),
ConstantReference::Direct};
}
llvm_unreachable("unhandled kind");
}
/// Return the address of the context descriptor representing the parent of
/// the given decl context.
///
/// For a nominal type context, this returns the address of the nominal type
/// descriptor.
/// For an extension context, this returns the address of the extension
/// context descriptor.
/// For a module or file unit context, this returns the address of the module
/// context descriptor.
/// For any other kind of context, this returns an anonymous context descriptor
/// for the context.
ConstantReference
IRGenModule::getAddrOfParentContextDescriptor(DeclContext *from,
bool fromAnonymousContext) {
// Some types get special treatment.
if (auto Type = dyn_cast<NominalTypeDecl>(from)) {
// Use a special module context if we have one.
if (auto context =
Mangle::ASTMangler::getSpecialManglingContext(
Type, /*UseObjCProtocolNames=*/false)) {
switch (*context) {
case Mangle::ASTMangler::ObjCContext:
return {getAddrOfObjCModuleContextDescriptor(),
ConstantReference::Direct};
case Mangle::ASTMangler::ClangImporterContext:
return {getAddrOfClangImporterModuleContextDescriptor(),
ConstantReference::Direct};
}
}
// Wrap up private types in an anonymous context for the containing file
// unit so that the runtime knows they have unstable identity.
if (!fromAnonymousContext && Type->isOutermostPrivateOrFilePrivateScope()
&& !Type->isUsableFromInline())
return {getAddrOfAnonymousContextDescriptor(Type),
ConstantReference::Direct};
}
return getAddrOfContextDescriptorForParent(from->getParent(), from,
fromAnonymousContext);
}
static void markGlobalAsUsedBasedOnLinkage(IRGenModule &IGM, LinkInfo &link,
llvm::GlobalValue *global) {
// If we're internalizing public symbols at link time, don't make globals
// unconditionally externally visible.
if (IGM.getOptions().InternalizeAtLink)
return;
// Everything externally visible is considered used in Swift.
// That mostly means we need to be good at not marking things external.
if (link.isUsed())
IGM.addUsedGlobal(global);
else if (!IGM.IRGen.Opts.shouldOptimize() &&
!IGM.IRGen.Opts.ConditionalRuntimeRecords &&
!IGM.IRGen.Opts.VirtualFunctionElimination &&
!IGM.IRGen.Opts.WitnessMethodElimination &&
!global->isDeclaration()) {
// llvm's pipeline has decide to run GlobalDCE as part of the O0 pipeline.
// Mark non public symbols as compiler used to counter act this.
IGM.addCompilerUsedGlobal(global);
}
}
bool LinkInfo::isUsed(IRLinkage IRL) {
// Everything externally visible is considered used in Swift.
// That mostly means we need to be good at not marking things external.
return IRL.Linkage == llvm::GlobalValue::ExternalLinkage &&
(IRL.Visibility == llvm::GlobalValue::DefaultVisibility ||
IRL.Visibility == llvm::GlobalValue::ProtectedVisibility) &&
(IRL.DLLStorage == llvm::GlobalValue::DefaultStorageClass ||
IRL.DLLStorage == llvm::GlobalValue::DLLExportStorageClass);
}
/// Add the given global value to @llvm.used.
///
/// This value must have a definition by the time the module is finalized.
void IRGenModule::addUsedGlobal(llvm::GlobalValue *global) {
LLVMUsed.push_back(global);
}
/// Add the given global value to @llvm.compiler.used.
///
/// This value must have a definition by the time the module is finalized.
void IRGenModule::addCompilerUsedGlobal(llvm::GlobalValue *global) {
LLVMCompilerUsed.push_back(global);
}
void IRGenModule::addGenericROData(llvm::Constant *RODataAddr) {
GenericRODatas.push_back(RODataAddr);
}
/// Add the given global value to the Objective-C class list.
void IRGenModule::addObjCClass(llvm::Constant *classPtr, bool nonlazy) {
ObjCClasses.push_back(classPtr);
if (nonlazy)
ObjCNonLazyClasses.push_back(classPtr);
}
/// Add the given global value to the Objective-C resilient class stub list.
void IRGenModule::addObjCClassStub(llvm::Constant *classPtr) {
ObjCClassStubs.push_back(classPtr);
}
void IRGenModule::addRuntimeResolvableType(GenericTypeDecl *type) {
// Collect the nominal type records we emit into a special section.
if (isa<NominalTypeDecl>(type) &&
!cast<NominalTypeDecl>(type)->canBeCopyable()) {
// Older runtimes should not be allowed to discover noncopyable types, since
// they will try to expose them dynamically as copyable types. Record
// noncopyable type descriptors in a separate vector so that future
// noncopyable-type-aware runtimes and reflection libraries can still find
// them.
RuntimeResolvableTypes2.push_back(type);
} else {
RuntimeResolvableTypes.push_back(type);
}
if (auto nominal = dyn_cast<NominalTypeDecl>(type)) {
// As soon as the type metadata is available, all the type's conformances
// must be available, too. The reason is that a type (with the help of its
// metadata) can be checked at runtime if it conforms to a protocol.
addLazyConformances(nominal);
}
}
ConstantReference
IRGenModule::getConstantReferenceForProtocolDescriptor(ProtocolDecl *proto) {
if (proto->isObjC()) {
// ObjC protocol descriptors don't have a unique address, but get uniqued
// by the Objective-C runtime at load time.
// Get the indirected address of the protocol descriptor reference variable
// that the ObjC runtime uniques.
auto refVar = getAddrOfObjCProtocolRef(proto, NotForDefinition);
return ConstantReference(cast<llvm::Constant>(refVar.getAddress()),
ConstantReference::Indirect);
}
// Try to form a direct reference to the nominal type descriptor if it's in
// the same binary, or use the GOT entry if it's from another binary.
return getAddrOfLLVMVariableOrGOTEquivalent(
LinkEntity::forProtocolDescriptor(proto));
}
void IRGenModule::addLazyConformances(const IterableDeclContext *idc) {
for (const ProtocolConformance *conf :
idc->getLocalConformances(ConformanceLookupKind::All)) {
IRGen.addLazyWitnessTable(conf);
}
}
std::string IRGenModule::GetObjCSectionName(StringRef Section,
StringRef MachOAttributes) {
assert(Section.substr(0, 2) == "__" && "expected the name to begin with __");
switch (TargetInfo.OutputObjectFormat) {
case llvm::Triple::DXContainer:
case llvm::Triple::GOFF:
case llvm::Triple::SPIRV:
case llvm::Triple::UnknownObjectFormat:
llvm_unreachable("must know the object file format");
case llvm::Triple::MachO:
return MachOAttributes.empty()
? ("__DATA," + Section).str()
: ("__DATA," + Section + "," + MachOAttributes).str();
case llvm::Triple::ELF:
case llvm::Triple::Wasm:
return Section.substr(2).str();
case llvm::Triple::XCOFF:
case llvm::Triple::COFF:
return ("." + Section.substr(2) + "$B").str();
}
llvm_unreachable("unexpected object file format");
}
void IRGenModule::SetCStringLiteralSection(llvm::GlobalVariable *GV,
ObjCLabelType Type) {
switch (TargetInfo.OutputObjectFormat) {
case llvm::Triple::DXContainer:
case llvm::Triple::GOFF:
case llvm::Triple::SPIRV:
case llvm::Triple::UnknownObjectFormat:
llvm_unreachable("must know the object file format");
case llvm::Triple::MachO:
switch (Type) {
case ObjCLabelType::ClassName:
GV->setSection("__TEXT,__objc_classname,cstring_literals");
return;
case ObjCLabelType::MethodVarName:
GV->setSection("__TEXT,__objc_methname,cstring_literals");
return;
case ObjCLabelType::MethodVarType:
GV->setSection("__TEXT,__objc_methtype,cstring_literals");
return;
case ObjCLabelType::PropertyName:
GV->setSection("__TEXT,__cstring,cstring_literals");
return;
}
case llvm::Triple::ELF:
case llvm::Triple::Wasm:
return;
case llvm::Triple::XCOFF:
case llvm::Triple::COFF:
return;
}
llvm_unreachable("unexpected object file format");
}
void IRGenModule::emitGlobalLists() {
if (ObjCInterop) {
if (IRGen.Opts.EmitGenericRODatas) {
emitGlobalList(
*this, GenericRODatas, "generic_ro_datas",
GetObjCSectionName("__objc_clsrolist", "regular"),
llvm::GlobalValue::InternalLinkage, Int8PtrTy, /*isConstant*/ false,
/*asContiguousArray*/ true, /*canBeStrippedByLinker*/ false);
}
// Objective-C class references go in a variable with a meaningless
// name but a magic section.
emitGlobalList(
*this, ObjCClasses, "objc_classes",
GetObjCSectionName("__objc_classlist", "regular,no_dead_strip"),
llvm::GlobalValue::InternalLinkage, Int8PtrTy, /*isConstant*/ false,
/*asContiguousArray*/ false);
// So do resilient class stubs.
emitGlobalList(
*this, ObjCClassStubs, "objc_class_stubs",
GetObjCSectionName("__objc_stublist", "regular,no_dead_strip"),
llvm::GlobalValue::InternalLinkage, Int8PtrTy, /*isConstant*/ false,
/*asContiguousArray*/ true);
// So do categories.
emitGlobalList(
*this, ObjCCategories, "objc_categories",
GetObjCSectionName("__objc_catlist", "regular,no_dead_strip"),
llvm::GlobalValue::InternalLinkage, Int8PtrTy, /*isConstant*/ false,
/*asContiguousArray*/ true);
// And categories on class stubs.
emitGlobalList(
*this, ObjCCategoriesOnStubs, "objc_categories_stubs",
GetObjCSectionName("__objc_catlist2", "regular,no_dead_strip"),
llvm::GlobalValue::InternalLinkage, Int8PtrTy, /*isConstant*/ false,
/*asContiguousArray*/ true);
// Emit nonlazily realized class references in a second magic section to
// make sure they are realized by the Objective-C runtime before any
// instances are allocated.
emitGlobalList(
*this, ObjCNonLazyClasses, "objc_non_lazy_classes",
GetObjCSectionName("__objc_nlclslist", "regular,no_dead_strip"),
llvm::GlobalValue::InternalLinkage, Int8PtrTy, /*isConstant*/ false,
/*asContiguousArray*/ true);
}
// @llvm.used
// Collect llvm.used globals already in the module (coming from ClangCodeGen).
collectGlobalList(*this, LLVMUsed, "llvm.used");
emitGlobalList(*this, LLVMUsed, "llvm.used", "llvm.metadata",
llvm::GlobalValue::AppendingLinkage,
Int8PtrTy,
/*isConstant*/false, /*asContiguousArray*/true);
// Collect llvm.compiler.used globals already in the module (coming
// from ClangCodeGen).
collectGlobalList(*this, LLVMCompilerUsed, "llvm.compiler.used");
emitGlobalList(*this, LLVMCompilerUsed, "llvm.compiler.used", "llvm.metadata",
llvm::GlobalValue::AppendingLinkage,
Int8PtrTy,
/*isConstant*/false, /*asContiguousArray*/true);
}
// Eagerly emit functions that are externally visible. Functions that are
// dynamic replacements must also be eagerly emitted.
static bool isLazilyEmittedFunction(SILFunction &f, SILModule &m) {
// Embedded Swift only emits specialized function, so don't emit generic
// functions, even if they're externally visible.
if (f.getASTContext().LangOpts.hasFeature(Feature::Embedded) &&
f.getLoweredFunctionType()->getSubstGenericSignature()) {
return true;
}
if (f.isPossiblyUsedExternally())
return false;
if (f.getDynamicallyReplacedFunction())
return false;
return true;
}
void IRGenerator::emitGlobalTopLevel(
const std::vector<std::string> &linkerDirectives) {
// Generate order numbers for the functions in the SIL module that
// correspond to definitions in the LLVM module.
unsigned nextOrderNumber = 0;
for (auto &silFn : PrimaryIGM->getSILModule().getFunctions()) {
// Don't bother adding external declarations to the function order.
if (!silFn.isDefinition()) continue;
FunctionOrder.insert(std::make_pair(&silFn, nextOrderNumber++));
}
// Ensure that relative symbols are collocated in the same LLVM module.
for (auto &wt : PrimaryIGM->getSILModule().getWitnessTableList()) {
CurrentIGMPtr IGM = getGenModule(wt.getDeclContext());
ensureRelativeSymbolCollocation(wt);
}
for (auto &wt : PrimaryIGM->getSILModule().getDefaultWitnessTableList()) {
CurrentIGMPtr IGM = getGenModule(wt.getProtocol()->getDeclContext());
ensureRelativeSymbolCollocation(wt);
}
for (auto &directive: linkerDirectives) {
createLinkerDirectiveVariable(*PrimaryIGM, directive);
}
for (SILGlobalVariable &v : PrimaryIGM->getSILModule().getSILGlobals()) {
Decl *decl = v.getDecl();
CurrentIGMPtr IGM = getGenModule(decl ? decl->getDeclContext() : nullptr);
IGM->emitSILGlobalVariable(&v);
}
// Emit SIL functions.
auto &m = PrimaryIGM->getSILModule();
for (SILFunction &f : m) {
// Generic functions should not be present in embedded Swift.
//
// TODO: Cannot enable this check yet because we first need removal of
// unspecialized classes and class vtables in SIL.
//
// if (SIL.getASTContext().LangOpts.hasFeature(Feature::Embedded)) {
// if (f.isGeneric()) {
// llvm::errs() << "Unspecialized function: \n" << f << "\n";
// llvm_unreachable("unspecialized function present in embedded Swift");
// }
// }
if (isLazilyEmittedFunction(f, m))
continue;
CurrentIGMPtr IGM = getGenModule(&f);
IGM->emitSILFunction(&f);
}
// Emit witness tables.
for (SILWitnessTable &wt : PrimaryIGM->getSILModule().getWitnessTableList()) {
CurrentIGMPtr IGM = getGenModule(wt.getDeclContext());
if (!canEmitWitnessTableLazily(&wt)) {
IGM->emitSILWitnessTable(&wt);
}
}
// Emit property descriptors.
for (auto &prop : PrimaryIGM->getSILModule().getPropertyList()) {
CurrentIGMPtr IGM = getGenModule(prop.getDecl()->getInnermostDeclContext());
IGM->emitSILProperty(&prop);
}
// Emit differentiability witnesses.
for (auto &dw :
PrimaryIGM->getSILModule().getDifferentiabilityWitnessList()) {
// Emit into same IRGenModule as the original function.
// NOTE(TF-894): Investigate whether `getGenModule(dw.getVJP())` is
// significant/desirable; `getGenModule` seems relevant for multi-threaded
// compilation. When the differentiation transform canonicalizes all
// differentiability witnesses to have JVP/VJP functions, we can assert
// that JVP/VJP functions exist and use `getGenModule(dw.getVJP())`.
CurrentIGMPtr IGM = getGenModule(dw.getOriginalFunction());
IGM->emitSILDifferentiabilityWitness(&dw);
}
for (auto Iter : *this) {
IRGenModule *IGM = Iter.second;
IGM->finishEmitAfterTopLevel();
}
emitEntryPointInfo();
}
void IRGenModule::finishEmitAfterTopLevel() {
// Emit the implicit import of the swift standard library.
// FIXME: We'd get the exact set of implicit imports if we went through the
// SourceFile's getImportedModules instead, but then we'd lose location info
// for the explicit imports.
if (DebugInfo) {
if (ModuleDecl *TheStdlib = Context.getStdlibModule()) {
if (TheStdlib != getSwiftModule()) {
Located<swift::Identifier> moduleName[] = {
{ Context.StdlibModuleName, swift::SourceLoc() }
};
auto Imp = ImportDecl::create(Context, getSwiftModule(), SourceLoc(),
ImportKind::Module, SourceLoc(),
llvm::ArrayRef(moduleName));
Imp->setModule(TheStdlib);
DebugInfo->emitImport(Imp);
}
}
}
}
void IRGenerator::emitSwiftProtocols() {
for (auto &m : *this) {
m.second->emitSwiftProtocols(/*asContiguousArray*/ false);
}
}
void IRGenerator::emitProtocolConformances() {
for (auto &m : *this) {
m.second->emitProtocolConformances(/*asContiguousArray*/ false);
}
}
void IRGenerator::emitTypeMetadataRecords() {
for (auto &m : *this) {
m.second->emitTypeMetadataRecords(/*asContiguousArray*/ false);
}
}
void IRGenerator::emitAccessibleFunctions() {
for (auto &m : *this)
m.second->emitAccessibleFunctions();
}
static void
deleteAndReenqueueForEmissionValuesDependentOnCanonicalPrespecializedMetadataRecords(
IRGenModule &IGM, CanType typeWithCanonicalMetadataPrespecialization,
NominalTypeDecl &decl) {
// The accessor depends on the existence of canonical metadata records
// because their presence determine which runtime function is called.
auto *accessor = IGM.getAddrOfTypeMetadataAccessFunction(
decl.getDeclaredType()->getCanonicalType(), NotForDefinition);
accessor->deleteBody();
IGM.IRGen.noteUseOfMetadataAccessor(&decl);
IGM.IRGen.noteLazyReemissionOfNominalTypeDescriptor(&decl);
// The type context descriptor depends on canonical metadata records because
// pointers to them are attached as trailing objects to it.
//
// Don't call
//
// noteUseOfTypeContextDescriptor
//
// here because we don't want to reemit metadata.
emitLazyTypeContextDescriptor(IGM, &decl, RequireMetadata);
}
/// Emit any lazy definitions (of globals or functions or whatever
/// else) that we require.
void IRGenerator::emitLazyDefinitions() {
if (SIL.getASTContext().LangOpts.hasFeature(Feature::Embedded)) {
// In embedded Swift, the compiler cannot emit any metadata, etc.
assert(LazyTypeMetadata.empty());
assert(LazySpecializedTypeMetadataRecords.empty());
assert(LazyTypeContextDescriptors.empty());
assert(LazyOpaqueTypeDescriptors.empty());
assert(LazyExtensionDescriptors.empty());
assert(LazyFieldDescriptors.empty());
// LazyFunctionDefinitions are allowed, but they must not be generic
for (SILFunction *f : LazyFunctionDefinitions) {
assert(!f->isGeneric());
}
assert(LazyWitnessTables.empty());
assert(LazyCanonicalSpecializedMetadataAccessors.empty());
assert(LazyMetadataAccessors.empty());
// LazyClassMetadata is allowed
// LazySpecializedClassMetadata is allowed
}
while (!LazyTypeMetadata.empty() ||
!LazySpecializedTypeMetadataRecords.empty() ||
!LazyTypeContextDescriptors.empty() ||
!LazyOpaqueTypeDescriptors.empty() ||
!LazyExtensionDescriptors.empty() ||
!LazyFieldDescriptors.empty() ||
!LazyFunctionDefinitions.empty() || !LazyWitnessTables.empty() ||
!LazyCanonicalSpecializedMetadataAccessors.empty() ||
!LazyMetadataAccessors.empty() ||
!LazyClassMetadata.empty() ||
!LazySpecializedClassMetadata.empty()
) {
// Emit any lazy type metadata we require.
while (!LazyTypeMetadata.empty()) {
NominalTypeDecl *type = LazyTypeMetadata.pop_back_val();
auto &entry = LazyTypeGlobals.find(type)->second;
assert(hasLazyMetadata(type));
assert(entry.IsMetadataUsed && !entry.IsMetadataEmitted);
entry.IsMetadataEmitted = true;
CurrentIGMPtr IGM = getGenModule(type->getDeclContext());
emitLazyTypeMetadata(*IGM.get(), type);
}
while (!LazySpecializedTypeMetadataRecords.empty()) {
CanType theType;
TypeMetadataCanonicality canonicality;
std::tie(theType, canonicality) =
LazySpecializedTypeMetadataRecords.pop_back_val();
auto *nominal = theType->getNominalOrBoundGenericNominal();
CurrentIGMPtr IGMPtr = getGenModule(nominal->getDeclContext());
auto &IGM = *IGMPtr.get();
// A new canonical prespecialized metadata changes both the type
// descriptor (adding a new entry to the trailing list of metadata) and
// the metadata accessor (calling the appropriate getGenericMetadata
// variant depending on whether there are any canonical prespecialized
// metadata records to add to the metadata cache). Consequently, it is
// necessary to force these to be reemitted.
if (canonicality == TypeMetadataCanonicality::Canonical) {
deleteAndReenqueueForEmissionValuesDependentOnCanonicalPrespecializedMetadataRecords(
IGM, theType, *nominal);
}
emitLazySpecializedGenericTypeMetadata(IGM, theType);
}
while (!LazyTypeContextDescriptors.empty()) {
NominalTypeDecl *type = LazyTypeContextDescriptors.pop_back_val();
auto &entry = LazyTypeGlobals.find(type)->second;
assert(hasLazyMetadata(type));
assert(entry.IsDescriptorUsed && !entry.IsDescriptorEmitted);
entry.IsDescriptorEmitted = true;
CurrentIGMPtr IGM = getGenModule(type->getDeclContext());
emitLazyTypeContextDescriptor(*IGM.get(), type,
RequireMetadata_t(entry.IsMetadataUsed));
}
while (!LazyOpaqueTypeDescriptors.empty()) {
OpaqueTypeDecl *type = LazyOpaqueTypeDescriptors.pop_back_val();
auto &entry = LazyOpaqueTypes.find(type)->second;
assert(hasLazyMetadata(type));
assert(entry.IsDescriptorUsed && !entry.IsDescriptorEmitted);
entry.IsDescriptorEmitted = true;
CurrentIGMPtr IGM = getGenModule(type->getDeclContext());
IGM->emitOpaqueTypeDecl(type);
}
while (!LazyExtensionDescriptors.empty()) {
ExtensionDecl *ext = LazyExtensionDescriptors.back();
LazyExtensionDescriptors.pop_back();
auto &entry = LazyExtensions.find(ext)->second;
assert(entry.IsDescriptorUsed && !entry.IsDescriptorEmitted);
entry.IsDescriptorEmitted = true;
CurrentIGMPtr IGM = getGenModule(ext->getDeclContext());
IGM->getAddrOfExtensionContextDescriptor(ext);
}
while (!LazyFieldDescriptors.empty()) {
NominalTypeDecl *type = LazyFieldDescriptors.pop_back_val();
CurrentIGMPtr IGM = getGenModule(type->getDeclContext());
IGM->emitFieldDescriptor(type);
}
while (!LazyWitnessTables.empty()) {
SILWitnessTable *wt = LazyWitnessTables.pop_back_val();
CurrentIGMPtr IGM = getGenModule(wt->getDeclContext());
IGM->emitSILWitnessTable(wt);
}
// Emit any lazy function definitions we require.
while (!LazyFunctionDefinitions.empty()) {
SILFunction *f = LazyFunctionDefinitions.pop_back_val();
CurrentIGMPtr IGM = getGenModule(f);
// In embedded Swift, we can gain public / externally-visible functions
// by deserializing them from imported modules, or by the CMO pass making
// local functions public. TODO: We should internalize as a separate pass.
if (!SIL.getASTContext().LangOpts.hasFeature(Feature::Embedded)) {
assert(!f->isPossiblyUsedExternally()
&& "function with externally-visible linkage emitted lazily?");
}
IGM->emitSILFunction(f);
}
while (!LazyCanonicalSpecializedMetadataAccessors.empty()) {
CanType theType =
LazyCanonicalSpecializedMetadataAccessors.pop_back_val();
auto *nominal = theType->getAnyNominal();
assert(nominal);
CurrentIGMPtr IGMPtr = getGenModule(nominal->getDeclContext());
auto &IGM = *IGMPtr.get();
// TODO: Once non-canonical accessors are available, this variable should
// reflect the canonicality of the accessor rather than always being
// canonical.
auto canonicality = TypeMetadataCanonicality::Canonical;
if (canonicality == TypeMetadataCanonicality::Canonical) {
deleteAndReenqueueForEmissionValuesDependentOnCanonicalPrespecializedMetadataRecords(
IGM, theType, *nominal);
}
emitLazyCanonicalSpecializedMetadataAccessor(IGM, theType);
}
while (!LazyMetadataAccessors.empty()) {
NominalTypeDecl *nominal = LazyMetadataAccessors.pop_back_val();
CurrentIGMPtr IGM = getGenModule(nominal->getDeclContext());
emitLazyMetadataAccessor(*IGM.get(), nominal);
}
while (!LazyClassMetadata.empty()) {
CanType classType = LazyClassMetadata.pop_back_val();
CurrentIGMPtr IGM = getGenModule(classType->getClassOrBoundGenericClass());
emitLazyClassMetadata(*IGM.get(), classType);
}
while (!LazySpecializedClassMetadata.empty()) {
CanType classType = LazySpecializedClassMetadata.pop_back_val();
CurrentIGMPtr IGM = getGenModule(classType->getClassOrBoundGenericClass());
emitLazySpecializedClassMetadata(*IGM.get(), classType);
}
}
FinishedEmittingLazyDefinitions = true;
}
void IRGenerator::addLazyFunction(SILFunction *f) {
// Add it to the queue if it hasn't already been put there.
if (!LazilyEmittedFunctions.insert(f).second)
return;
// Embedded Swift doesn't expect any generic functions to be referenced.
if (SIL.getASTContext().LangOpts.hasFeature(Feature::Embedded)) {
assert(!f->isGeneric());
}
assert(!FinishedEmittingLazyDefinitions);
LazyFunctionDefinitions.push_back(f);
if (const SILFunction *orig = f->getOriginOfSpecialization()) {
// f is a specialization. Try to emit all specializations of the same
// original function into the same IGM. This increases the chances that
// specializations are merged by LLVM's function merging.
IRGenModule *IGM = CurrentIGM ? CurrentIGM : getPrimaryIGM();
auto iter = IGMForSpecializations.insert(std::make_pair(orig, IGM)).first;
DefaultIGMForFunction.insert(std::make_pair(f, iter->second));
return;
}
if (auto *dc = f->getDeclContext())
if (dc->getParentSourceFile())
return;
if (CurrentIGM == nullptr)
return;
// Don't update the map if we already have an entry.
DefaultIGMForFunction.insert(std::make_pair(f, CurrentIGM));
}
bool IRGenerator::hasLazyMetadata(TypeDecl *type) {
assert(isa<NominalTypeDecl>(type) ||
isa<OpaqueTypeDecl>(type));
auto found = HasLazyMetadata.find(type);
if (found != HasLazyMetadata.end())
return found->second;
auto canBeLazy = [&]() -> bool {
auto *dc = type->getDeclContext();
if (isa<ClangModuleUnit>(dc->getModuleScopeContext())) {
if (auto nominal = dyn_cast<NominalTypeDecl>(type)) {
return requiresForeignTypeMetadata(nominal);
}
} else if (dc->getParentModule() == SIL.getSwiftModule()) {
// When compiling with -Onone keep all metadata for the debugger. Even if
// it is not used by the program itself.
if (!Opts.shouldOptimize())
return false;
if (Opts.UseJIT)
return false;
if (isa<ClassDecl>(type) || isa<ProtocolDecl>(type))
return false;
switch (type->getEffectiveAccess()) {
case AccessLevel::Open:
case AccessLevel::Public:
case AccessLevel::Package:
// We can't remove metadata for externally visible types.
return false;
case AccessLevel::Internal:
// In non-whole-module mode, internal types are also visible externally.
return SIL.isWholeModule();
case AccessLevel::FilePrivate:
case AccessLevel::Private:
return true;
}
}
return false;
};
bool isLazy = canBeLazy();
HasLazyMetadata[type] = isLazy;
return isLazy;
}
void IRGenerator::noteUseOfClassMetadata(CanType classType) {
if (LazilyEmittedClassMetadata.insert(classType.getPointer()).second) {
LazyClassMetadata.push_back(classType);
}
}
void IRGenerator::noteUseOfSpecializedClassMetadata(CanType classType) {
if (LazilyEmittedSpecializedClassMetadata.insert(classType.getPointer()).second) {
LazySpecializedClassMetadata.push_back(classType);
}
}
void IRGenerator::noteUseOfTypeGlobals(NominalTypeDecl *type,
bool isUseOfMetadata,
RequireMetadata_t requireMetadata) {
if (!type)
return;
assert(type->isAvailableDuringLowering());
// Force emission of ObjC protocol descriptors used by type refs.
if (auto proto = dyn_cast<ProtocolDecl>(type)) {
if (proto->isObjC()) {
PrimaryIGM->getAddrOfObjCProtocolRecord(proto, NotForDefinition);
return;
}
}
if (!hasLazyMetadata(type))
return;
// If the type can be generated in several TU with weak linkage we don't know
// which one will be picked up so we have to require the metadata. Otherwise,
// the situation can arise where one TU contains a type descriptor with a null
// metadata access function and the other TU which requires metadata has a
// type descriptor with a valid metadata access function but the linker picks
// the first one.
if (isAccessorLazilyGenerated(getTypeMetadataAccessStrategy(
type->getDeclaredType()->getCanonicalType()))) {
requireMetadata = RequireMetadata;
}
// Try to create a new record of the fact that we used this type.
auto insertResult = LazyTypeGlobals.try_emplace(type);
auto &entry = insertResult.first->second;
bool metadataWasUsed = entry.IsMetadataUsed;
bool descriptorWasUsed = entry.IsDescriptorUsed;
bool isNovelUseOfMetadata = false;
bool isNovelUseOfDescriptor = false;
// Flag that we have a use of the metadata if
// - the reference was directly to the metadata
// - the reference was to the descriptor, but it requested the emission
// of metadata
if (!metadataWasUsed && (isUseOfMetadata || requireMetadata)) {
if (metadataWasUsed) return;
entry.IsMetadataUsed = true;
isNovelUseOfMetadata = true;
}
if (!descriptorWasUsed && !isUseOfMetadata) {
if (descriptorWasUsed) return;
entry.IsDescriptorUsed = true;
isNovelUseOfDescriptor = true;
}
// Enqueue metadata emission if we have a novel use of it.
if (isNovelUseOfMetadata) {
assert(!FinishedEmittingLazyDefinitions);
LazyTypeMetadata.push_back(type);
}
// Enqueue descriptor emission if we have a novel use of it or if we
// need to re-emit it because we're suddenly using metadata for it.
if (isNovelUseOfDescriptor ||
(isNovelUseOfMetadata && entry.IsDescriptorEmitted)) {
entry.IsDescriptorEmitted = false; // clear this in case it was true
assert(!FinishedEmittingLazyDefinitions);
LazyTypeContextDescriptors.push_back(type);
}
}
void IRGenerator::noteUseOfFieldDescriptor(NominalTypeDecl *type) {
if (!hasLazyMetadata(type))
return;
// Imported classes and protocols do not need field descriptors.
if (type->hasClangNode() &&
(isa<ClassDecl>(type) ||
isa<ProtocolDecl>(type)))
return;
if (!LazilyEmittedFieldMetadata.insert(type).second)
return;
assert(!FinishedEmittingLazyDefinitions);
LazyFieldDescriptors.push_back(type);
}
void IRGenerator::noteUseOfCanonicalSpecializedMetadataAccessor(
CanType forType) {
auto key = forType->getAnyNominal();
assert(key);
assert(key->isGenericContext());
auto &enqueuedSpecializedAccessors =
CanonicalSpecializedAccessorsForGenericTypes[key];
if (llvm::all_of(enqueuedSpecializedAccessors,
[&](CanType enqueued) { return enqueued != forType; })) {
assert(!FinishedEmittingLazyDefinitions);
LazyCanonicalSpecializedMetadataAccessors.insert(forType);
enqueuedSpecializedAccessors.push_back(forType);
}
}
static bool typeKindCanBePrespecialized(TypeKind theKind) {
switch (theKind) {
case TypeKind::Struct:
case TypeKind::BoundGenericStruct:
case TypeKind::Enum:
case TypeKind::BoundGenericEnum:
case TypeKind::Class:
case TypeKind::BoundGenericClass:
return true;
default:
return false;
}
}
void IRGenerator::noteUseOfSpecializedGenericTypeMetadata(
IRGenModule &IGM, CanType theType, TypeMetadataCanonicality canonicality) {
assert(typeKindCanBePrespecialized(theType->getKind()));
auto key = theType->getAnyNominal();
assert(key);
assert(key->isGenericContext());
auto &enqueuedSpecializedTypes =
MetadataPrespecializationsForGenericTypes[key];
if (llvm::all_of(enqueuedSpecializedTypes,
[&](auto enqueued) { return enqueued.first != theType; })) {
assert(!FinishedEmittingLazyDefinitions);
LazySpecializedTypeMetadataRecords.push_back({theType, canonicality});
enqueuedSpecializedTypes.push_back({theType, canonicality});
}
}
void IRGenerator::noteUseOfOpaqueTypeDescriptor(OpaqueTypeDecl *opaque) {
if (!opaque)
return;
if (!hasLazyMetadata(opaque))
return;
auto insertResult = LazyOpaqueTypes.try_emplace(opaque);
auto &entry = insertResult.first->second;
bool isNovelUseOfDescriptor = !entry.IsDescriptorUsed;
entry.IsDescriptorUsed = true;
if (isNovelUseOfDescriptor) {
LazyOpaqueTypeDescriptors.push_back(opaque);
}
}
void IRGenerator::noteUseOfExtensionDescriptor(ExtensionDecl *ext) {
auto insertResult = LazyExtensions.try_emplace(ext);
auto &entry = insertResult.first->second;
bool isNovelUseOfDescriptor = !entry.IsDescriptorUsed;
entry.IsDescriptorUsed = true;
if (isNovelUseOfDescriptor) {
LazyExtensionDescriptors.push_back(ext);
}
}
static std::string getDynamicReplacementSection(IRGenModule &IGM) {
std::string sectionName;
switch (IGM.TargetInfo.OutputObjectFormat) {
case llvm::Triple::DXContainer:
case llvm::Triple::GOFF:
case llvm::Triple::SPIRV:
case llvm::Triple::UnknownObjectFormat:
llvm_unreachable("Don't know how to emit field records table for "
"the selected object format.");
case llvm::Triple::MachO:
sectionName = "__TEXT, __swift5_replace, regular, no_dead_strip";
break;
case llvm::Triple::ELF:
case llvm::Triple::Wasm:
sectionName = "swift5_replace";
break;
case llvm::Triple::XCOFF:
case llvm::Triple::COFF:
sectionName = ".sw5repl$B";
break;
}
return sectionName;
}
static std::string getDynamicReplacementSomeSection(IRGenModule &IGM) {
std::string sectionName;
switch (IGM.TargetInfo.OutputObjectFormat) {
case llvm::Triple::DXContainer:
case llvm::Triple::GOFF:
case llvm::Triple::SPIRV:
case llvm::Triple::UnknownObjectFormat:
llvm_unreachable("Don't know how to emit field records table for "
"the selected object format.");
case llvm::Triple::MachO:
sectionName = "__TEXT, __swift5_replac2, regular, no_dead_strip";
break;
case llvm::Triple::ELF:
case llvm::Triple::Wasm:
sectionName = "swift5_replac2";
break;
case llvm::Triple::XCOFF:
case llvm::Triple::COFF:
sectionName = ".sw5reps$B";
break;
}
return sectionName;
}
llvm::GlobalVariable *IRGenModule::getGlobalForDynamicallyReplaceableThunk(
LinkEntity &entity, llvm::Type *type, ForDefinition_t forDefinition) {
return cast<llvm::GlobalVariable>(
getAddrOfLLVMVariable(entity, forDefinition, DebugTypeInfo()));
}
/// Creates a dynamic replacement chain entry for \p SILFn that contains either
/// the implementation function pointer \p or a nullptr, the next pointer of the
/// chain entry is set to nullptr.
/// struct ChainEntry {
/// void *funPtr;
/// struct ChainEntry *next;
/// }
static llvm::GlobalVariable *getChainEntryForDynamicReplacement(
IRGenModule &IGM, LinkEntity entity,
llvm::Constant *implFunction = nullptr,
ForDefinition_t forDefinition = ForDefinition) {
auto linkEntry = IGM.getGlobalForDynamicallyReplaceableThunk(
entity, IGM.DynamicReplacementLinkEntryTy, forDefinition);
if (!forDefinition)
return linkEntry;
auto *funPtr =
implFunction ? llvm::ConstantExpr::getBitCast(implFunction, IGM.Int8PtrTy)
: llvm::ConstantExpr::getNullValue(IGM.Int8PtrTy);
if (implFunction) {
llvm::Constant *indices[] = {llvm::ConstantInt::get(IGM.Int32Ty, 0),
llvm::ConstantInt::get(IGM.Int32Ty, 0)};
auto *storageAddr = llvm::ConstantExpr::getInBoundsGetElementPtr(
IGM.DynamicReplacementLinkEntryTy, linkEntry, indices);
bool isAsyncFunction =
entity.hasSILFunction() && entity.getSILFunction()->isAsync();
auto &schema =
isAsyncFunction
? IGM.getOptions().PointerAuth.AsyncSwiftDynamicReplacements
: IGM.getOptions().PointerAuth.SwiftDynamicReplacements;
assert(entity.hasSILFunction() || entity.isOpaqueTypeDescriptorAccessor());
auto authEntity = entity.hasSILFunction()
? PointerAuthEntity(entity.getSILFunction())
: PointerAuthEntity::Special::TypeDescriptor;
funPtr =
IGM.getConstantSignedPointer(funPtr, schema, authEntity, storageAddr);
}
auto *nextEntry =
llvm::ConstantExpr::getNullValue(IGM.DynamicReplacementLinkEntryPtrTy);
llvm::Constant *fields[] = {funPtr, nextEntry};
auto *entry =
llvm::ConstantStruct::get(IGM.DynamicReplacementLinkEntryTy, fields);
linkEntry->setInitializer(entry);
return linkEntry;
}
void IRGenerator::emitDynamicReplacements() {
if (DynamicReplacements.empty())
return;
auto &IGM = *getPrimaryIGM();
// Collect all the type metadata accessor replacements.
SmallVector<OpaqueTypeArchetypeType *, 8> newFuncTypes;
SmallVector<OpaqueTypeArchetypeType *, 8> origFuncTypes;
llvm::SmallSet<OpaqueTypeArchetypeType *, 8> newUniqueOpaqueTypes;
llvm::SmallSet<OpaqueTypeArchetypeType *, 8> origUniqueOpaqueTypes;
for (auto *newFunc : DynamicReplacements) {
auto newResultTy = newFunc->getLoweredFunctionType()
->getAllResultsSubstType(newFunc->getModule(),
TypeExpansionContext::minimal())
.getASTType();
if (!newResultTy->hasOpaqueArchetype())
continue;
newResultTy.visit([&](CanType ty) {
if (auto opaque = ty->getAs<OpaqueTypeArchetypeType>())
if (newUniqueOpaqueTypes.insert(opaque).second)
newFuncTypes.push_back(opaque);
});
auto *origFunc = newFunc->getDynamicallyReplacedFunction();
assert(origFunc);
auto origResultTy = origFunc->getLoweredFunctionType()
->getAllResultsSubstType(origFunc->getModule(),
TypeExpansionContext::minimal())
.getASTType();
assert(origResultTy->hasOpaqueArchetype());
origResultTy.visit([&](CanType ty) {
if (auto opaque = ty->getAs<OpaqueTypeArchetypeType>())
if (origUniqueOpaqueTypes.insert(opaque).second)
origFuncTypes.push_back(opaque);
});
assert(origFuncTypes.size() == newFuncTypes.size());
}
// struct ReplacementScope {
// uint32t flags; // unused
// uint32t numReplacements;
// struct Entry {
// RelativeIndirectablePointer<KeyEntry, false> replacedFunctionKey;
// RelativeDirectPointer<void> newFunction;
// RelativeDirectPointer<LinkEntry> replacement;
// uint32_t flags; // shouldChain.
// }[0]
// };
ConstantInitBuilder builder(IGM);
auto replacementScope = builder.beginStruct();
replacementScope.addInt32(0); // unused flags.
replacementScope.addInt32(DynamicReplacements.size() + newFuncTypes.size());
auto replacementsArray =
replacementScope.beginArray();
for (auto *newFunc : DynamicReplacements) {
LinkEntity entity =
LinkEntity::forDynamicallyReplaceableFunctionVariable(newFunc);
auto replacementLinkEntry =
getChainEntryForDynamicReplacement(IGM, entity);
// TODO: replacementLinkEntry->setZeroSection()
auto *origFunc = newFunc->getDynamicallyReplacedFunction();
assert(origFunc);
auto keyRef = IGM.getAddrOfLLVMVariableOrGOTEquivalent(
LinkEntity::forDynamicallyReplaceableFunctionKey(origFunc));
auto replacement = replacementsArray.beginStruct();
replacement.addRelativeAddress(keyRef); // tagged relative reference.
if (newFunc->isAsync()) {
replacement.addRelativeAddress(llvm::ConstantExpr::getBitCast(
IGM.getAddrOfAsyncFunctionPointer(
LinkEntity::forSILFunction(newFunc)),
IGM.Int8PtrTy));
} else {
replacement.addCompactFunctionReference(IGM.getAddrOfSILFunction(
newFunc, NotForDefinition)); // direct relative reference.
}
replacement.addRelativeAddress(
replacementLinkEntry); // direct relative reference.
replacement.addInt32(
Opts.EnableDynamicReplacementChaining ? 1 : 0);
replacement.finishAndAddTo(replacementsArray);
}
// Emit replacements of the opaque type descriptor accessor.
for (auto i : indices(origFuncTypes)) {
LinkEntity entity = LinkEntity::forOpaqueTypeDescriptorAccessorVar(
newFuncTypes[i]->getDecl());
auto replacementLinkEntry = getChainEntryForDynamicReplacement(IGM, entity);
auto keyRef = IGM.getAddrOfLLVMVariableOrGOTEquivalent(
LinkEntity::forOpaqueTypeDescriptorAccessorKey(
origFuncTypes[i]->getDecl()));
llvm::Constant *newFnPtr = llvm::ConstantExpr::getBitCast(
IGM.getAddrOfOpaqueTypeDescriptorAccessFunction(
newFuncTypes[i]->getDecl(), NotForDefinition, false)
.getDirectPointer(),
IGM.Int8PtrTy);
auto replacement = replacementsArray.beginStruct();
replacement.addRelativeAddress(keyRef); // tagged relative reference.
replacement.addRelativeAddress(newFnPtr); // direct relative reference.
replacement.addRelativeAddress(
replacementLinkEntry); // direct relative reference.
replacement.addInt32(0);
replacement.finishAndAddTo(replacementsArray);
}
replacementsArray.finishAndAddTo(replacementScope);
auto var = replacementScope.finishAndCreateGlobal(
"\x01l_unnamed_dynamic_replacements", IGM.getPointerAlignment(),
/*isConstant*/ true, llvm::GlobalValue::PrivateLinkage);
IGM.setTrueConstGlobal(var);
IGM.addUsedGlobal(var);
// Emit the data for automatic replacement to happen on load.
// struct AutomaticReplacements {
// uint32t flags; // unused
// uint32t numReplacements;
// struct Entry {
// RelativeDirectPointer<ReplacementScope> replacements;
// uint32_t flags; // unused.
// }[0]
// };
auto autoReplacements = builder.beginStruct();
autoReplacements.addInt32(0); // unused flags.
autoReplacements.addInt32(1); // number of replacement entries.
auto autoReplacementsArray = autoReplacements.beginArray();
autoReplacementsArray.addRelativeAddress(var);
autoReplacementsArray.addInt32(0); // unused flags.
autoReplacementsArray.finishAndAddTo(autoReplacements);
auto autoReplVar = autoReplacements.finishAndCreateGlobal(
"\x01l_auto_dynamic_replacements", IGM.getPointerAlignment(),
/*isConstant*/ true, llvm::GlobalValue::PrivateLinkage);
autoReplVar->setSection(getDynamicReplacementSection(IGM));
IGM.addUsedGlobal(autoReplVar);
if (origFuncTypes.empty())
return;
// Emit records for replacing opaque type descriptor for some types.
// struct AutomaticReplacementsSome {
// uint32t flags; // unused
// uint32t numReplacements;
// struct Entry {
// RelativeIndirectablePointer<OpaqueTypeDescriptor*> orig;
// RelativeDirectPointer<OpaqueTypeDescriptor*> replacement;
// uint32_t flags; // unused.
// }[numEntries]
// };
auto autoReplacementsSome = builder.beginStruct();
autoReplacementsSome.addInt32(0); // unused flags.
autoReplacementsSome.addInt32(
origFuncTypes.size()); // number of replacement entries.
auto someReplacementsArray = autoReplacementsSome.beginArray();
for (auto i : indices(origFuncTypes)) {
auto origDesc =
LinkEntity::forOpaqueTypeDescriptor(origFuncTypes[i]->getDecl());
auto replDesc =
LinkEntity::forOpaqueTypeDescriptor(newFuncTypes[i]->getDecl());
auto replacement = someReplacementsArray.beginStruct();
replacement.addRelativeAddress(
IGM.getAddrOfLLVMVariableOrGOTEquivalent(origDesc));
replacement.addRelativeAddress(
IGM.getAddrOfLLVMVariableOrGOTEquivalent(replDesc));
replacement.finishAndAddTo(someReplacementsArray);
}
someReplacementsArray.finishAndAddTo(autoReplacementsSome);
auto autoReplVar2 = autoReplacementsSome.finishAndCreateGlobal(
"\x01l_auto_dynamic_replacements_some", IGM.getPointerAlignment(),
/*isConstant*/ true, llvm::GlobalValue::PrivateLinkage);
autoReplVar2->setSection(getDynamicReplacementSomeSection(IGM));
IGM.addUsedGlobal(autoReplVar2);
}
void IRGenerator::emitEagerClassInitialization() {
if (ClassesForEagerInitialization.empty())
return;
// Emit the register function in the primary module.
IRGenModule *IGM = getPrimaryIGM();
llvm::Function *RegisterFn = llvm::Function::Create(
llvm::FunctionType::get(IGM->VoidTy, false),
llvm::GlobalValue::PrivateLinkage,
"_swift_eager_class_initialization");
IGM->Module.getFunctionList().push_back(RegisterFn);
IRGenFunction RegisterIGF(*IGM, RegisterFn);
if (IGM->DebugInfo)
IGM->DebugInfo->emitArtificialFunction(RegisterIGF, RegisterIGF.CurFn);
RegisterFn->setAttributes(IGM->constructInitialAttributes());
RegisterFn->setCallingConv(IGM->DefaultCC);
IGM->setColocateMetadataSection(RegisterFn);
for (ClassDecl *CD : ClassesForEagerInitialization) {
auto Ty = CD->getDeclaredType()->getCanonicalType();
llvm::Value *MetaData = RegisterIGF.emitTypeMetadataRef(Ty);
assert(CD->getAttrs().hasAttribute<StaticInitializeObjCMetadataAttr>());
// Get the metadata to make sure that the class is registered. We need to
// add a use (empty inline asm instruction) for the metadata. Otherwise
// llvm would optimize the metadata accessor call away because it's
// defined as "readnone".
llvm::FunctionType *asmFnTy =
llvm::FunctionType::get(IGM->VoidTy, {MetaData->getType()},
false /* = isVarArg */);
llvm::InlineAsm *inlineAsm =
llvm::InlineAsm::get(asmFnTy, "", "r", true /* = SideEffects */);
RegisterIGF.Builder.CreateAsmCall(inlineAsm, MetaData);
}
RegisterIGF.Builder.CreateRetVoid();
// Add the registration function as a static initializer. We use a priority
// slightly lower than used for C++ global constructors, so that the code is
// executed before C++ global constructors (in case someone uses archives
// from a C++ global constructor).
llvm::appendToGlobalCtors(IGM->Module, RegisterFn, 60000, nullptr);
}
void IRGenerator::emitObjCActorsNeedingSuperclassSwizzle() {
if (ObjCActorsNeedingSuperclassSwizzle.empty())
return;
// Emit the register function in the primary module.
IRGenModule *IGM = getPrimaryIGM();
llvm::Function *RegisterFn = llvm::Function::Create(
llvm::FunctionType::get(IGM->VoidTy, false),
llvm::GlobalValue::PrivateLinkage,
"_swift_objc_actor_initialization");
IGM->Module.getFunctionList().push_back(RegisterFn);
IRGenFunction RegisterIGF(*IGM, RegisterFn);
if (IGM->DebugInfo)
IGM->DebugInfo->emitArtificialFunction(RegisterIGF, RegisterIGF.CurFn);
RegisterFn->setAttributes(IGM->constructInitialAttributes());
RegisterFn->setCallingConv(IGM->DefaultCC);
IGM->setColocateMetadataSection(RegisterFn);
// Look up the SwiftNativeNSObject class.
auto swiftNativeNSObjectName =
IGM->getAddrOfGlobalString("SwiftNativeNSObject");
auto swiftNativeNSObjectClass = RegisterIGF.Builder.CreateCall(
RegisterIGF.IGM.getObjCGetRequiredClassFunctionPointer(),
swiftNativeNSObjectName);
for (ClassDecl *CD : ObjCActorsNeedingSuperclassSwizzle) {
// The @objc actor class.
llvm::Value *classRef = RegisterIGF.emitTypeMetadataRef(
CD->getDeclaredInterfaceType()->getCanonicalType());
classRef = RegisterIGF.Builder.CreateBitCast(classRef, IGM->ObjCClassPtrTy);
// Set its superclass to SwiftNativeNSObject.
RegisterIGF.Builder.CreateCall(
RegisterIGF.IGM.getSetSuperclassFunctionPointer(),
{classRef, swiftNativeNSObjectClass});
}
RegisterIGF.Builder.CreateRetVoid();
// Add the registration function as a static initializer. We use a priority
// slightly lower than used for C++ global constructors, so that the code is
// executed before C++ global constructors (in case someone manages to access
// an @objc actor from a global constructor).
llvm::appendToGlobalCtors(IGM->Module, RegisterFn, 60000, nullptr);
}
/// Emit symbols for eliminated dead methods, which can still be referenced
/// from other modules. This happens e.g. if a public class contains a (dead)
/// private method.
void IRGenModule::emitVTableStubs() {
llvm::Function *stub = nullptr;
for (auto I = getSILModule().zombies_begin();
I != getSILModule().zombies_end(); ++I) {
const SILFunction &F = *I;
if (! F.isExternallyUsedSymbol())
continue;
if (!stub) {
// Create a single stub function which calls swift_deletedMethodError().
stub = llvm::Function::Create(llvm::FunctionType::get(VoidTy, false),
llvm::GlobalValue::InternalLinkage,
"_swift_dead_method_stub");
stub->setAttributes(constructInitialAttributes());
Module.getFunctionList().push_back(stub);
stub->setCallingConv(DefaultCC);
auto *entry = llvm::BasicBlock::Create(getLLVMContext(), "entry", stub);
auto *errorFunc = getDeletedMethodErrorFn();
llvm::CallInst::Create(getDeletedMethodErrorFnType(),
errorFunc, ArrayRef<llvm::Value *>(), "", entry);
new llvm::UnreachableInst(getLLVMContext(), entry);
}
// For each eliminated method symbol create an alias to the stub.
llvm::GlobalValue *alias = nullptr;
if (F.isAsync()) {
// TODO: We cannot directly create a pointer to `swift_deletedAsyncMethodError`
// to workaround a linker crash.
// Instead use the stub, which calls swift_deletedMethodError. This works because
// swift_deletedMethodError takes no parameters and simply aborts the program.
auto asyncLayout = getAsyncContextLayout(*this, const_cast<SILFunction *>(&F));
auto entity = LinkEntity::forSILFunction(const_cast<SILFunction *>(&F));
auto *fnPtr = emitAsyncFunctionPointer(*this, stub, entity, asyncLayout.getSize());
alias = fnPtr;
} else {
alias = llvm::GlobalAlias::create(llvm::GlobalValue::ExternalLinkage,
F.getName(), stub);
}
if (F.getEffectiveSymbolLinkage() == SILLinkage::Hidden)
alias->setVisibility(llvm::GlobalValue::HiddenVisibility);
else
ApplyIRLinkage(IRGen.Opts.InternalizeSymbols
? IRLinkage{llvm::GlobalValue::ExternalLinkage,
llvm::GlobalValue::HiddenVisibility,
llvm::GlobalValue::DefaultStorageClass}
: IRLinkage::ExternalExport).to(alias);
}
}
static std::string getEntryPointSection(IRGenModule &IGM) {
std::string sectionName;
switch (IGM.TargetInfo.OutputObjectFormat) {
case llvm::Triple::DXContainer:
case llvm::Triple::GOFF:
case llvm::Triple::SPIRV:
case llvm::Triple::UnknownObjectFormat:
llvm_unreachable("Don't know how to emit field records table for "
"the selected object format.");
case llvm::Triple::MachO:
sectionName = "__TEXT, __swift5_entry, regular, no_dead_strip";
break;
case llvm::Triple::ELF:
case llvm::Triple::Wasm:
sectionName = "swift5_entry";
break;
case llvm::Triple::XCOFF:
case llvm::Triple::COFF:
sectionName = ".sw5entr$B";
break;
}
return sectionName;
}
void IRGenerator::emitEntryPointInfo() {
if (SIL.getOptions().EmbeddedSwift) {
return;
}
SILFunction *entrypoint = nullptr;
if (!(entrypoint = SIL.lookUpFunction(
SIL.getASTContext().getEntryPointFunctionName()))) {
return;
}
auto &IGM = *getGenModule(entrypoint);
ConstantInitBuilder builder(IGM);
auto entrypointInfo = builder.beginStruct();
entrypointInfo.addCompactFunctionReference(
IGM.getAddrOfSILFunction(entrypoint, NotForDefinition));
uint32_t flags = 0;
enum EntryPointFlags : unsigned {
HasAtMainTypeFlag = 1 << 0,
};
if (auto *mainTypeDecl = SIL.getSwiftModule()->getMainTypeDecl()) {
flags |= HasAtMainTypeFlag;
}
entrypointInfo.addInt(IGM.Int32Ty, flags);
auto var = entrypointInfo.finishAndCreateGlobal(
"\x01l_entry_point", Alignment(4),
/*isConstant*/ true, llvm::GlobalValue::PrivateLinkage);
var->setSection(getEntryPointSection(IGM));
IGM.addUsedGlobal(var);
}
static IRLinkage
getIRLinkage(StringRef name, const UniversalLinkageInfo &info,
SILLinkage linkage, ForDefinition_t isDefinition,
bool isWeakImported, bool isKnownLocal = false) {
#define RESULT(LINKAGE, VISIBILITY, DLL_STORAGE) \
IRLinkage{llvm::GlobalValue::LINKAGE##Linkage, \
llvm::GlobalValue::VISIBILITY##Visibility, \
llvm::GlobalValue::DLL_STORAGE##StorageClass}
// This is a synthetic symbol that is referenced for `#dsohandle` and is never
// a definition but needs to be handled as a definition as it will be provided
// by the linker. This is a MSVC extension that is honoured by lld as well.
if (info.IsMSVCEnvironment && name == "__ImageBase")
return RESULT(External, Default, Default);
// Use protected visibility for public symbols we define on ELF. ld.so
// doesn't support relative relocations at load time, which interferes with
// our metadata formats. Default visibility should suffice for other object
// formats.
llvm::GlobalValue::VisibilityTypes PublicDefinitionVisibility =
info.IsELFObject ? llvm::GlobalValue::ProtectedVisibility
: llvm::GlobalValue::DefaultVisibility;
llvm::GlobalValue::DLLStorageClassTypes ExportedStorage =
info.UseDLLStorage ? llvm::GlobalValue::DLLExportStorageClass
: llvm::GlobalValue::DefaultStorageClass;
llvm::GlobalValue::DLLStorageClassTypes ImportedStorage =
info.UseDLLStorage ? llvm::GlobalValue::DLLImportStorageClass
: llvm::GlobalValue::DefaultStorageClass;
switch (linkage) {
case SILLinkage::Public:
case SILLinkage::Package:
return {llvm::GlobalValue::ExternalLinkage, PublicDefinitionVisibility,
info.Internalize ? llvm::GlobalValue::DefaultStorageClass
: ExportedStorage};
case SILLinkage::PublicNonABI:
case SILLinkage::PackageNonABI:
return isDefinition ? RESULT(WeakODR, Hidden, Default)
: RESULT(External, Hidden, Default);
case SILLinkage::Shared:
return isDefinition ? RESULT(LinkOnceODR, Hidden, Default)
: RESULT(External, Hidden, Default);
case SILLinkage::Hidden:
return RESULT(External, Hidden, Default);
case SILLinkage::Private: {
if (info.forcePublicDecls() && !isDefinition)
return getIRLinkage(name, info, SILLinkage::PublicExternal, isDefinition,
isWeakImported, isKnownLocal);
auto linkage = info.needLinkerToMergeDuplicateSymbols()
? llvm::GlobalValue::LinkOnceODRLinkage
: llvm::GlobalValue::InternalLinkage;
auto visibility = info.shouldAllPrivateDeclsBeVisibleFromOtherFiles()
? llvm::GlobalValue::HiddenVisibility
: llvm::GlobalValue::DefaultVisibility;
return {linkage, visibility, llvm::GlobalValue::DefaultStorageClass};
}
case SILLinkage::PackageExternal:
case SILLinkage::PublicExternal: {
if (isDefinition)
return RESULT(AvailableExternally, Default, Default);
auto linkage = isWeakImported ? llvm::GlobalValue::ExternalWeakLinkage
: llvm::GlobalValue::ExternalLinkage;
return {linkage, llvm::GlobalValue::DefaultVisibility,
isKnownLocal
? llvm::GlobalValue::DefaultStorageClass
: ImportedStorage};
}
case SILLinkage::HiddenExternal:
if (isDefinition)
return RESULT(AvailableExternally, Hidden, Default);
return {llvm::GlobalValue::ExternalLinkage,
llvm::GlobalValue::DefaultVisibility,
isKnownLocal
? llvm::GlobalValue::DefaultStorageClass
: ImportedStorage};
}
llvm_unreachable("bad SIL linkage");
}
/// Given that we're going to define a global value but already have a
/// forward-declaration of it, update its linkage.
void irgen::updateLinkageForDefinition(IRGenModule &IGM,
llvm::GlobalValue *global,
const LinkEntity &entity) {
// TODO: there are probably cases where we can avoid redoing the
// entire linkage computation.
UniversalLinkageInfo linkInfo(IGM);
bool weakImported = entity.isWeakImported(IGM.getSwiftModule());
bool isKnownLocal = entity.isAlwaysSharedLinkage();
if (const auto *DC = entity.getDeclContextForEmission())
if (const auto *MD = DC->getParentModule())
isKnownLocal = IGM.getSwiftModule() == MD || MD->isStaticLibrary();
auto IRL =
getIRLinkage(global->hasName() ? global->getName() : StringRef(),
linkInfo, entity.getLinkage(ForDefinition), ForDefinition,
weakImported, isKnownLocal);
ApplyIRLinkage(IRL).to(global);
LinkInfo link = LinkInfo::get(IGM, entity, ForDefinition);
markGlobalAsUsedBasedOnLinkage(IGM, link, global);
}
LinkInfo LinkInfo::get(IRGenModule &IGM, const LinkEntity &entity,
ForDefinition_t isDefinition) {
return LinkInfo::get(UniversalLinkageInfo(IGM),
IGM.getSwiftModule(),
entity, isDefinition);
}
LinkInfo LinkInfo::get(const UniversalLinkageInfo &linkInfo,
ModuleDecl *swiftModule,
const LinkEntity &entity,
ForDefinition_t isDefinition) {
LinkInfo result;
entity.mangle(result.Name);
bool isKnownLocal = entity.isAlwaysSharedLinkage();
if (const auto *DC = entity.getDeclContextForEmission()) {
if (const auto *MD = DC->getParentModule())
isKnownLocal = MD == swiftModule || MD->isStaticLibrary();
if (!isKnownLocal && !isDefinition) {
bool isClangImportedEntity =
isa<ClangModuleUnit>(DC->getModuleScopeContext());
// Nominal type descriptor for a type imported from a Clang module
// is always a local declaration as it's generated on demand. When WMO is
// off, it's emitted into the current file's object file. When WMO is on,
// it's emitted into one of the object files in the current module, and
// thus it's never imported from outside of the module.
if (isClangImportedEntity && entity.isNominalTypeDescriptor())
isKnownLocal = true;
}
} else if (entity.hasSILFunction()) {
// SIL serialized entities (functions, witness tables, vtables) do not have
// an associated DeclContext and are serialized into the current module. As
// a result, we explicitly handle SIL Functions here. We do not expect other
// types to be referenced directly.
if (const auto *MD = entity.getSILFunction()->getParentModule())
isKnownLocal = MD == swiftModule || MD->isStaticLibrary();
}
bool weakImported = entity.isWeakImported(swiftModule);
result.IRL = getIRLinkage(result.Name, linkInfo,
entity.getLinkage(isDefinition), isDefinition,
weakImported, isKnownLocal);
result.ForDefinition = isDefinition;
return result;
}
LinkInfo LinkInfo::get(const UniversalLinkageInfo &linkInfo, StringRef name,
SILLinkage linkage, ForDefinition_t isDefinition,
bool isWeakImported) {
LinkInfo result;
result.Name += name;
result.IRL = getIRLinkage(name, linkInfo, linkage, isDefinition,
isWeakImported, linkInfo.Internalize);
result.ForDefinition = isDefinition;
return result;
}
/// Get or create an LLVM function with these linkage rules.
llvm::Function *irgen::createFunction(IRGenModule &IGM, LinkInfo &linkInfo,
const Signature &signature,
llvm::Function *insertBefore,
OptimizationMode FuncOptMode,
StackProtectorMode stackProtect) {
auto name = linkInfo.getName();
llvm::Function *existing = IGM.Module.getFunction(name);
if (existing) {
if (existing->getValueType() == signature.getType())
return cast<llvm::Function>(existing);
IGM.error(SourceLoc(),
"program too clever: function collides with existing symbol " +
name);
// Note that this will implicitly unique if the .unique name is also taken.
existing->setName(name + ".unique");
}
llvm::Function *fn =
llvm::Function::Create(signature.getType(), linkInfo.getLinkage(), name);
fn->setCallingConv(signature.getCallingConv());
if (insertBefore) {
IGM.Module.getFunctionList().insert(insertBefore->getIterator(), fn);
} else {
IGM.Module.getFunctionList().push_back(fn);
}
ApplyIRLinkage({linkInfo.getLinkage(),
linkInfo.getVisibility(),
linkInfo.getDLLStorage()})
.to(fn, linkInfo.isForDefinition());
llvm::AttrBuilder initialAttrs(IGM.getLLVMContext());
IGM.constructInitialFnAttributes(initialAttrs, FuncOptMode, stackProtect);
// Merge initialAttrs with attrs.
auto updatedAttrs = signature.getAttributes().addFnAttributes(
IGM.getLLVMContext(), initialAttrs);
if (!updatedAttrs.isEmpty())
fn->setAttributes(updatedAttrs);
markGlobalAsUsedBasedOnLinkage(IGM, linkInfo, fn);
return fn;
}
/// Get or create an LLVM global variable with these linkage rules.
llvm::GlobalVariable *swift::irgen::createVariable(
IRGenModule &IGM, LinkInfo &linkInfo, llvm::Type *storageType,
Alignment alignment, DebugTypeInfo DbgTy,
std::optional<SILLocation> DebugLoc, StringRef DebugName) {
auto name = linkInfo.getName();
llvm::GlobalValue *existingValue = IGM.Module.getNamedGlobal(name);
if (existingValue) {
auto existingVar = dyn_cast<llvm::GlobalVariable>(existingValue);
if (existingVar && existingVar->getValueType() == storageType)
return existingVar;
IGM.error(SourceLoc(),
"program too clever: variable collides with existing symbol " +
name);
// Note that this will implicitly unique if the .unique name is also taken.
existingValue->setName(name + ".unique");
}
auto var = new llvm::GlobalVariable(IGM.Module, storageType,
/*constant*/ false, linkInfo.getLinkage(),
/*initializer*/ nullptr, name);
ApplyIRLinkage({linkInfo.getLinkage(),
linkInfo.getVisibility(),
linkInfo.getDLLStorage()})
.to(var, linkInfo.isForDefinition());
var->setAlignment(llvm::MaybeAlign(alignment.getValue()));
markGlobalAsUsedBasedOnLinkage(IGM, linkInfo, var);
if (IGM.DebugInfo && !DbgTy.isNull() && linkInfo.isForDefinition())
IGM.DebugInfo->emitGlobalVariableDeclaration(
var, DebugName.empty() ? name : DebugName, name, DbgTy,
var->hasInternalLinkage(), DebugLoc);
return var;
}
llvm::GlobalVariable *
swift::irgen::createLinkerDirectiveVariable(IRGenModule &IGM, StringRef name) {
// A prefix of \1 can avoid further mangling of the symbol (prefixing _).
llvm::SmallString<32> NameWithFlag;
NameWithFlag.push_back('\1');
NameWithFlag.append(name);
name = NameWithFlag.str();
static const uint8_t Size = 8;
static const uint8_t Alignment = 8;
// Use a char type as the type for this linker directive.
auto ProperlySizedIntTy = SILType::getBuiltinIntegerType(
Size, IGM.getSwiftModule()->getASTContext());
auto storageType = IGM.getStorageType(ProperlySizedIntTy);
llvm::GlobalValue *existingValue = IGM.Module.getNamedGlobal(name);
if (existingValue) {
auto existingVar = dyn_cast<llvm::GlobalVariable>(existingValue);
if (existingVar && existingVar->getValueType() == storageType)
return existingVar;
IGM.error(SourceLoc(),
"program too clever: variable collides with existing symbol " +
name);
// Note that this will implicitly unique if the .unique name is also taken.
existingValue->setName(name + ".unique");
}
llvm::GlobalValue::LinkageTypes Linkage =
llvm::GlobalValue::LinkageTypes::ExternalLinkage;
auto var = new llvm::GlobalVariable(IGM.Module, storageType, /*constant*/true,
Linkage, /*Init to zero*/llvm::Constant::getNullValue(storageType), name);
ApplyIRLinkage({Linkage,
llvm::GlobalValue::VisibilityTypes::DefaultVisibility,
llvm::GlobalValue::DLLStorageClassTypes::DefaultStorageClass}).to(var);
var->setAlignment(llvm::MaybeAlign(Alignment));
disableAddressSanitizer(IGM, var);
IGM.addUsedGlobal(var);
return var;
}
void swift::irgen::disableAddressSanitizer(IRGenModule &IGM, llvm::GlobalVariable *var) {
llvm::GlobalVariable::SanitizerMetadata Meta;
if (var->hasSanitizerMetadata())
Meta = var->getSanitizerMetadata();
Meta.IsDynInit = false;
Meta.NoAddress = true;
var->setSanitizerMetadata(Meta);
}
/// Emit a global declaration.
void IRGenModule::emitGlobalDecl(Decl *D) {
if (!D->isAvailableDuringLowering())
return;
D->visitAuxiliaryDecls([&](Decl *decl) {
emitGlobalDecl(decl);
});
switch (D->getKind()) {
case DeclKind::Extension:
return emitExtension(cast<ExtensionDecl>(D));
case DeclKind::Protocol:
return emitProtocolDecl(cast<ProtocolDecl>(D));
case DeclKind::PatternBinding:
// The global initializations are in SIL.
return;
case DeclKind::Param:
llvm_unreachable("there are no global function parameters");
case DeclKind::Subscript:
llvm_unreachable("there are no global subscript operations");
case DeclKind::EnumCase:
case DeclKind::EnumElement:
llvm_unreachable("there are no global enum elements");
case DeclKind::Constructor:
llvm_unreachable("there are no global constructor");
case DeclKind::Destructor:
llvm_unreachable("there are no global destructor");
case DeclKind::MissingMember:
llvm_unreachable("there are no global member placeholders");
case DeclKind::Missing:
llvm_unreachable("missing decl in IRGen");
case DeclKind::BuiltinTuple:
llvm_unreachable("BuiltinTupleType made it to IRGen");
case DeclKind::TypeAlias:
case DeclKind::GenericTypeParam:
case DeclKind::AssociatedType:
case DeclKind::IfConfig:
case DeclKind::PoundDiagnostic:
case DeclKind::Macro:
return;
case DeclKind::Enum:
return emitEnumDecl(cast<EnumDecl>(D));
case DeclKind::Struct:
return emitStructDecl(cast<StructDecl>(D));
case DeclKind::Class:
return emitClassDecl(cast<ClassDecl>(D));
// These declarations are only included in the debug info.
case DeclKind::Import:
if (DebugInfo)
DebugInfo->emitImport(cast<ImportDecl>(D));
return;
case DeclKind::Var:
case DeclKind::Accessor:
case DeclKind::Func:
// Handled in SIL.
return;
case DeclKind::TopLevelCode:
// All the top-level code will be lowered separately.
return;
// Operator decls aren't needed for IRGen.
case DeclKind::InfixOperator:
case DeclKind::PrefixOperator:
case DeclKind::PostfixOperator:
case DeclKind::PrecedenceGroup:
return;
case DeclKind::Module:
return;
case DeclKind::OpaqueType:
// TODO: Eventually we'll need to emit descriptors to access the opaque
// type's metadata.
return;
case DeclKind::MacroExpansion:
// Expansion already visited as auxiliary decls.
return;
}
llvm_unreachable("bad decl kind!");
}
Address IRGenModule::getAddrOfSILGlobalVariable(SILGlobalVariable *var,
const TypeInfo &ti,
ForDefinition_t forDefinition) {
LinkEntity entity = LinkEntity::forSILGlobalVariable(var, *this);
LinkInfo link = LinkInfo::get(*this, entity, forDefinition);
if (auto clangDecl = var->getClangDecl()) {
auto addr = getAddrOfClangGlobalDecl(cast<clang::VarDecl>(clangDecl),
forDefinition);
// Override the linkage computed by Clang if the decl is from another
// module that imported @_weakLinked.
//
// FIXME: We should be able to set the linkage unconditionally here but
// some fixes are needed for Cxx interop.
if (auto globalVar = dyn_cast<llvm::GlobalVariable>(addr)) {
auto varModule = var->getDecl()->getModuleContext();
if (getSwiftModule()->isImportedAsWeakLinked(varModule))
globalVar->setLinkage(link.getLinkage());
}
// If we're not emitting this to define it, make sure we cast it to the
// right type.
if (!forDefinition) {
auto ptrTy = ti.getStorageType()->getPointerTo();
addr = llvm::ConstantExpr::getBitCast(addr, ptrTy);
}
auto alignment =
Alignment(getClangASTContext().getDeclAlign(clangDecl).getQuantity());
return Address(addr, ti.getStorageType(), alignment);
}
ResilienceExpansion expansion = getResilienceExpansionForLayout(var);
llvm::Type *storageType;
llvm::Type *castStorageToType = nullptr;
Size fixedSize;
Alignment fixedAlignment;
bool inFixedBuffer = false;
if (var->isInitializedObject()) {
assert(ti.isFixedSize(expansion));
StructLayout *Layout = StaticObjectLayouts[var].get();
if (!Layout) {
// Create the layout (includes the llvm type) for the statically
// initialized object and store it for later.
ObjectInst *OI = cast<ObjectInst>(var->getStaticInitializerValue());
llvm::SmallVector<SILType, 16> TailTypes;
for (SILValue TailOp : OI->getTailElements()) {
TailTypes.push_back(TailOp->getType());
}
Layout = getClassLayoutWithTailElems(*this,
var->getLoweredType(), TailTypes);
StaticObjectLayouts[var] = std::unique_ptr<StructLayout>(Layout);
}
storageType = Layout->getType();
fixedSize = Layout->getSize();
fixedAlignment = Layout->getAlignment();
castStorageToType = cast<ClassTypeInfo>(ti).getStorageType();
assert(fixedAlignment >= TargetInfo.HeapObjectAlignment);
} else if (ti.isFixedSize(expansion)) {
// Allocate static storage.
auto &fixedTI = cast<FixedTypeInfo>(ti);
storageType = fixedTI.getStorageType();
fixedSize = fixedTI.getFixedSize();
fixedAlignment = fixedTI.getFixedAlignment();
} else {
// Allocate a fixed-size buffer and possibly heap-allocate a payload at
// runtime if the runtime size of the type does not fit in the buffer.
inFixedBuffer = true;
storageType = getFixedBufferTy();
fixedSize = Size(DataLayout.getTypeAllocSize(storageType));
fixedAlignment = getFixedBufferAlignment(*this);
}
llvm::Constant *initVal = nullptr;
// Check whether we've created the global variable already.
// FIXME: We should integrate this into the LinkEntity cache more cleanly.
auto gvar = Module.getGlobalVariable(link.getName(), /*allowInternal*/ true);
if (gvar) {
if (forDefinition) {
updateLinkageForDefinition(*this, gvar, entity);
}
if (forDefinition && !gvar->hasInitializer())
initVal = getGlobalInitValue(var, storageType, fixedAlignment);
} else {
// The global doesn't exist yet. Create it.
initVal = getGlobalInitValue(var, storageType, fixedAlignment);
llvm::Type *globalTy = initVal ? initVal->getType() : storageType;
if (var->isInitializedObject()) {
// An initialized object is always a compiler-generated "outlined"
// variable. Therefore we don't generate debug info for it.
gvar = createVariable(*this, link, globalTy, fixedAlignment);
} else {
// Create a global variable with debug info.
StringRef name;
std::optional<SILLocation> loc;
if (var->getDecl()) {
// Use the VarDecl for more accurate debugging information.
loc = var->getDecl();
name = var->getDecl()->getName().str();
} else {
if (var->hasLocation())
loc = var->getLocation();
name = var->getName();
}
DebugTypeInfo DbgTy =
inFixedBuffer
? DebugTypeInfo::getGlobalFixedBuffer(
var, globalTy, fixedSize, fixedAlignment)
: DebugTypeInfo::getGlobal(var, globalTy, *this);
gvar = createVariable(*this, link, globalTy, fixedAlignment, DbgTy, loc, name);
}
if (!forDefinition)
gvar->setComdat(nullptr);
// Mark as llvm.used if @_used, set section if @_section
if (var->markedAsUsed())
addUsedGlobal(gvar);
else if (var->shouldBePreservedForDebugger() && forDefinition)
addUsedGlobal(gvar);
if (auto *sectionAttr = var->getSectionAttr())
gvar->setSection(sectionAttr->Name);
}
if (forDefinition && !gvar->hasInitializer()) {
if (initVal) {
gvar->setInitializer(initVal);
if (var->isLet() ||
(var->isInitializedObject() && canMakeStaticObjectReadOnly(var->getLoweredType()))) {
gvar->setConstant(true);
}
} else {
/// Add a zero initializer.
gvar->setInitializer(llvm::Constant::getNullValue(storageType));
}
}
llvm::Constant *addr = gvar;
if (var->isInitializedObject() && !canMakeStaticObjectReadOnly(var->getLoweredType())) {
// Project out the object from the container.
llvm::Constant *Indices[2] = {
llvm::ConstantExpr::getIntegerValue(Int32Ty, APInt(32, 0)),
llvm::ConstantExpr::getIntegerValue(Int32Ty, APInt(32, 1))
};
// Return the address of the initialized object itself (and not the address
// to a reference to it).
addr = llvm::ConstantExpr::getGetElementPtr(
gvar->getValueType(), gvar, Indices);
}
addr = llvm::ConstantExpr::getBitCast(
addr,
castStorageToType ? castStorageToType : storageType->getPointerTo());
if (castStorageToType)
storageType = cast<ClassTypeInfo>(ti).getClassLayoutType();
return Address(addr, storageType, Alignment(gvar->getAlignment()));
}
llvm::Constant *IRGenModule::getGlobalInitValue(SILGlobalVariable *var,
llvm::Type *storageType,
Alignment alignment) {
if (var->isInitializedObject()) {
StructLayout *layout = StaticObjectLayouts[var].get();
ObjectInst *oi = cast<ObjectInst>(var->getStaticInitializerValue());
llvm::Constant *initVal = emitConstantObject(*this, oi, layout);
if (!canMakeStaticObjectReadOnly(var->getLoweredType())) {
// A statically initialized object must be placed into a container struct
// because the swift_initStaticObject needs a swift_once_t at offset -1:
// struct Container {
// swift_once_t token[fixedAlignment / sizeof(swift_once_t)];
// HeapObject object;
// };
std::string typeName = storageType->getStructName().str() + 'c';
assert(alignment >= getPointerAlignment());
unsigned numTokens = alignment.getValue() /
getPointerAlignment().getValue();
auto *containerTy = llvm::StructType::create(getLLVMContext(),
{llvm::ArrayType::get(OnceTy, numTokens), initVal->getType()},
typeName);
auto *zero = llvm::ConstantAggregateZero::get(containerTy->getElementType(0));
initVal = llvm::ConstantStruct::get(containerTy, {zero , initVal});
}
return initVal;
}
if (SILInstruction *initInst = var->getStaticInitializerValue()) {
if (auto *vector = dyn_cast<AllocVectorInst>(initInst)) {
auto *capacityConst = emitConstantValue(*this, vector->getCapacity()).claimNextConstant();
uint64_t capacity = cast<llvm::ConstantInt>(capacityConst)->getZExtValue();
auto &ti = cast<FixedTypeInfo>(getTypeInfo(vector->getType()));
auto *elementTy = cast<llvm::StructType>(ti.getStorageType());
Size::int_type paddingBytes = (ti.getFixedStride() - ti.getFixedSize()).getValue();
if (paddingBytes != 0) {
llvm::ArrayType *padding = llvm::ArrayType::get(Int8Ty, paddingBytes);
elementTy = llvm::StructType::get(getLLVMContext(), {elementTy, padding});
}
auto *arrayTy = llvm::ArrayType::get(elementTy, capacity);
return llvm::ConstantAggregateZero::get(arrayTy);
}
if (auto *vector = dyn_cast<VectorInst>(initInst)) {
llvm::SmallVector<llvm::Constant *, 8> elementValues;
for (SILValue element : vector->getElements()) {
auto &ti = cast<FixedTypeInfo>(getTypeInfo(element->getType()));
Size paddingBytes = ti.getFixedStride() - ti.getFixedSize();
Explosion e = emitConstantValue(*this, element);
elementValues.push_back(getConstantValue(std::move(e), paddingBytes.getValue()));
}
auto *arrTy = llvm::ArrayType::get(elementValues[0]->getType(), elementValues.size());
return llvm::ConstantArray::get(arrTy, elementValues);
}
Explosion initExp = emitConstantValue(*this,
cast<SingleValueInstruction>(initInst));
return getConstantValue(std::move(initExp), /*paddingBytes=*/ 0);
}
return nullptr;
}
llvm::Constant *IRGenModule::getConstantValue(Explosion &&initExp, Size::int_type paddingBytes) {
if (initExp.size() == 1 && paddingBytes == 0) {
return initExp.claimNextConstant();
}
// In case of enums, the initializer might contain multiple constants,
// which does not match with the storage type.
ArrayRef<llvm::Value *> elements = initExp.claimAll();
llvm::SmallVector<llvm::Constant *, 32> constElements;
for (llvm::Value *v : elements) {
constElements.push_back(cast<llvm::Constant>(v));
}
for (Size::int_type i = 0; i < paddingBytes; i++) {
constElements.push_back(llvm::UndefValue::get(Int8Ty));
}
return llvm::ConstantStruct::getAnon(constElements, /*Packed=*/ true);
}
/// Return True if the function \p f is a 'readonly' function. Checking
/// for the SIL @_effects(readonly) attribute is not enough because this
/// definition does not match the definition of the LLVM readonly function
/// attribute. In this function we do the actual check.
static bool isReadOnlyFunction(SILFunction *f) {
// Check if the function has any 'owned' parameters. Owned parameters may
// call the destructor of the object which could violate the readonly-ness
// of the function.
if (f->hasOwnedParameters() || f->hasIndirectFormalResults())
return false;
auto Eff = f->getEffectsKind();
// Swift's readonly does not automatically match LLVM's readonly.
// Swift SIL optimizer relies on @_effects(readonly) to remove e.g.
// dead code remaining from initializers of strings or dictionaries
// of variables that are not used. But those initializers are often
// not really readonly in terms of LLVM IR. For example, the
// Dictionary.init() is marked as @_effects(readonly) in Swift, but
// it does invoke reference-counting operations.
if (Eff == EffectsKind::ReadOnly || Eff == EffectsKind::ReadNone) {
// TODO: Analyze the body of function f and return true if it is
// really readonly.
return false;
}
return false;
}
static clang::GlobalDecl getClangGlobalDeclForFunction(const clang::Decl *decl) {
if (auto ctor = dyn_cast<clang::CXXConstructorDecl>(decl))
return clang::GlobalDecl(ctor, clang::Ctor_Complete);
if (auto dtor = dyn_cast<clang::CXXDestructorDecl>(decl))
return clang::GlobalDecl(dtor, clang::Dtor_Complete);
return clang::GlobalDecl(cast<clang::FunctionDecl>(decl));
}
static void addLLVMFunctionAttributes(SILFunction *f, Signature &signature) {
auto &attrs = signature.getMutableAttributes();
switch (f->getInlineStrategy()) {
case NoInline:
attrs = attrs.addFnAttribute(signature.getType()->getContext(),
llvm::Attribute::NoInline);
break;
case AlwaysInline:
// FIXME: We do not currently transfer AlwaysInline since doing so results
// in test failures, which must be investigated first.
case InlineDefault:
break;
}
if (isReadOnlyFunction(f)) {
auto &ctx = signature.getType()->getContext();
attrs =
attrs.addFnAttribute(ctx, llvm::Attribute::getWithMemoryEffects(
ctx, llvm::MemoryEffects::readOnly()));
}
}
/// Create a key entry for a dynamic function replacement. A key entry refers to
/// the link entry for the dynamic replaceable function.
/// struct KeyEntry {
/// RelativeDirectPointer<LinkEntry> linkEntry;
/// int32_t flags;
/// }
static llvm::GlobalVariable *createGlobalForDynamicReplacementFunctionKey(
IRGenModule &IGM, LinkEntity keyEntity, llvm::GlobalVariable *linkEntry) {
auto key = IGM.getGlobalForDynamicallyReplaceableThunk(
keyEntity, IGM.DynamicReplacementKeyTy, ForDefinition);
ConstantInitBuilder builder(IGM);
auto B = builder.beginStruct(IGM.DynamicReplacementKeyTy);
B.addRelativeAddress(linkEntry);
bool isAsyncFunction =
keyEntity.hasSILFunction() && keyEntity.getSILFunction()->isAsync();
auto schema = isAsyncFunction
? IGM.getOptions().PointerAuth.AsyncSwiftDynamicReplacements
: IGM.getOptions().PointerAuth.SwiftDynamicReplacements;
if (schema) {
assert(keyEntity.hasSILFunction() ||
keyEntity.isOpaqueTypeDescriptorAccessor());
auto authEntity = keyEntity.hasSILFunction()
? PointerAuthEntity(keyEntity.getSILFunction())
: PointerAuthEntity::Special::TypeDescriptor;
B.addInt32((uint32_t)PointerAuthInfo::getOtherDiscriminator(IGM, schema,
authEntity)
->getZExtValue() |
((uint32_t)isAsyncFunction ? 0x10000 : 0x0));
} else
B.addInt32(0);
B.finishAndSetAsInitializer(key);
key->setConstant(true);
IGM.setTrueConstGlobal(key);
return key;
}
/// Creates the prolog for a dynamically replaceable function.
/// It checks if the replaced function or the original function should be called
/// (by calling the swift_getFunctionReplacement runtime function). In case of
/// the original function, it just jumps to the "real" code of the function,
/// otherwise it tail calls the replacement.
void IRGenModule::createReplaceableProlog(IRGenFunction &IGF, SILFunction *f) {
LinkEntity varEntity =
LinkEntity::forDynamicallyReplaceableFunctionVariable(f);
LinkEntity keyEntity =
LinkEntity::forDynamicallyReplaceableFunctionKey(f);
auto silFunctionType = f->getLoweredFunctionType();
Signature signature = getSignature(silFunctionType);
// Create and initialize the first link entry for the chain of replacements.
// The first implementation is initialized with 'implFn'.
auto *funPtr =
f->isAsync()
? IGF.IGM.getAddrOfAsyncFunctionPointer(LinkEntity::forSILFunction(f))
: IGF.CurFn;
auto linkEntry =
getChainEntryForDynamicReplacement(*this, varEntity, funPtr);
// Create the key data structure. This is used from other modules to refer to
// the chain of replacements.
createGlobalForDynamicReplacementFunctionKey(*this, keyEntity, linkEntry);
llvm::Constant *indices[] = {llvm::ConstantInt::get(Int32Ty, 0),
llvm::ConstantInt::get(Int32Ty, 0)};
auto *fnPtrAddr = llvm::ConstantExpr::getInBoundsGetElementPtr(
linkEntry->getValueType(), linkEntry, indices);
auto *ReplAddr =
llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(fnPtrAddr,
FunctionPtrTy->getPointerTo());
auto *FnAddr = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
funPtr, FunctionPtrTy);
auto &schema = f->isAsync()
? getOptions().PointerAuth.AsyncSwiftDynamicReplacements
: getOptions().PointerAuth.SwiftDynamicReplacements;
llvm::Value *ReplFn = nullptr, *hasReplFn = nullptr;
if (UseBasicDynamicReplacement) {
ReplFn = IGF.Builder.CreateLoad(
Address(fnPtrAddr, FunctionPtrTy, getPointerAlignment()));
llvm::Value *lhs = ReplFn;
if (schema.isEnabled()) {
lhs = emitPointerAuthStrip(IGF, lhs, schema.getKey());
}
hasReplFn = IGF.Builder.CreateICmpEQ(lhs, FnAddr);
} else {
// Call swift_getFunctionReplacement to check which function to call.
auto *callRTFunc = IGF.Builder.CreateCall(
getGetReplacementFunctionPointer(), {ReplAddr, FnAddr});
callRTFunc->setDoesNotThrow();
ReplFn = callRTFunc;
hasReplFn = IGF.Builder.CreateICmpEQ(ReplFn,
llvm::ConstantExpr::getNullValue(ReplFn->getType()));
}
auto *replacedBB = IGF.createBasicBlock("forward_to_replaced");
auto *origEntryBB = IGF.createBasicBlock("original_entry");
IGF.Builder.CreateCondBr(hasReplFn, origEntryBB, replacedBB);
IGF.Builder.emitBlock(replacedBB);
if (f->isAsync()) {
auto &IGM = IGF.IGM;
auto &Builder = IGF.Builder;
PrologueLocation AutoRestore(IGM.DebugInfo.get(), Builder);
auto authEntity = PointerAuthEntity(f);
auto authInfo = PointerAuthInfo::emit(IGF, schema, fnPtrAddr, authEntity);
auto *fnType = signature.getType()->getPointerTo();
auto *realReplFn = Builder.CreateBitCast(ReplFn, fnType);
auto asyncFnPtr = FunctionPointer::createSigned(silFunctionType, realReplFn,
authInfo, signature);
// We never emit a function that uses special conventions, so we
// can just use the default async kind.
FunctionPointerKind fpKind =
FunctionPointerKind::AsyncFunctionPointer;
PointerAuthInfo codeAuthInfo =
asyncFnPtr.getAuthInfo().getCorrespondingCodeAuthInfo();
auto newFnPtr = FunctionPointer::createSigned(
FunctionPointer::Kind::Function, asyncFnPtr.getPointer(IGF),
codeAuthInfo, Signature::forAsyncAwait(IGM, silFunctionType, fpKind));
SmallVector<llvm::Value *, 16> forwardedArgs;
for (auto &arg : IGF.CurFn->args())
forwardedArgs.push_back(&arg);
auto layout = getAsyncContextLayout(
IGM, silFunctionType, silFunctionType,
f->getForwardingSubstitutionMap());
llvm::Value *dynamicContextSize32;
llvm::Value *calleeFunction;
std::tie(calleeFunction, dynamicContextSize32) = getAsyncFunctionAndSize(
IGF, silFunctionType->getRepresentation(), asyncFnPtr, nullptr,
std::make_pair(false, true));
auto *dynamicContextSize =
Builder.CreateZExt(dynamicContextSize32, IGM.SizeTy);
auto calleeContextBuffer = emitAllocAsyncContext(IGF, dynamicContextSize);
auto calleeContext =
layout.emitCastTo(IGF, calleeContextBuffer.getAddress());
auto saveValue = [&](ElementLayout layout, Explosion &explosion) -> void {
Address addr =
layout.project(IGF, calleeContext, /*offsets*/ std::nullopt);
auto &ti = cast<LoadableTypeInfo>(layout.getType());
ti.initialize(IGF, explosion, addr, /*isOutlined*/ false);
};
// Set caller info into the context.
{ // caller context
Explosion explosion;
auto fieldLayout = layout.getParentLayout();
auto *context = IGF.getAsyncContext();
if (auto schema = IGM.getOptions().PointerAuth.AsyncContextParent) {
Address fieldAddr =
fieldLayout.project(IGF, calleeContext, /*offsets*/ std::nullopt);
auto authInfo = PointerAuthInfo::emit(
IGF, schema, fieldAddr.getAddress(), PointerAuthEntity());
context = emitPointerAuthSign(IGF, context, authInfo);
}
explosion.add(context);
saveValue(fieldLayout, explosion);
}
auto currentResumeFn =
Builder.CreateIntrinsicCall(llvm::Intrinsic::coro_async_resume, {});
{ // Return to caller function.
auto fieldLayout = layout.getResumeParentLayout();
llvm::Value *fnVal = currentResumeFn;
// Sign the pointer.
if (auto schema = IGM.getOptions().PointerAuth.AsyncContextResume) {
Address fieldAddr =
fieldLayout.project(IGF, calleeContext, /*offsets*/ std::nullopt);
auto authInfo = PointerAuthInfo::emit(
IGF, schema, fieldAddr.getAddress(), PointerAuthEntity());
fnVal = emitPointerAuthSign(IGF, fnVal, authInfo);
}
fnVal = Builder.CreateBitCast(fnVal, IGM.TaskContinuationFunctionPtrTy);
Explosion explosion;
explosion.add(fnVal);
saveValue(fieldLayout, explosion);
}
// Setup the suspend point.
SmallVector<llvm::Value *, 8> arguments;
auto signature = newFnPtr.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);
auto resumeProjFn = IGF.getOrCreateResumePrjFn(true /*forProlog*/);
arguments.push_back(
Builder.CreateBitOrPointerCast(resumeProjFn, IGM.Int8PtrTy));
auto dispatchFn = IGF.createAsyncDispatchFn(
getFunctionPointerForDispatchCall(IGM, newFnPtr), forwardedArgs);
arguments.push_back(
Builder.CreateBitOrPointerCast(dispatchFn, IGM.Int8PtrTy));
arguments.push_back(Builder.CreateBitOrPointerCast(newFnPtr.getRawPointer(),
IGM.Int8PtrTy));
if (auto authInfo = newFnPtr.getAuthInfo()) {
arguments.push_back(newFnPtr.getAuthInfo().getDiscriminator());
}
unsigned argIdx = 0;
for (auto arg : forwardedArgs) {
// Replace the context argument.
if (argIdx == asyncFnPtr.getSignature().getAsyncContextIndex())
arguments.push_back(Builder.CreateBitOrPointerCast(
calleeContextBuffer.getAddress(), IGM.SwiftContextPtrTy));
else
arguments.push_back(arg);
argIdx++;
}
auto resultTy =
cast<llvm::StructType>(signature.getType()->getReturnType());
auto suspend = IGF.emitSuspendAsyncCall(
asyncContextIndex, resultTy, arguments, false /*restore context*/);
{ // Restore the context.
llvm::Value *calleeContext =
Builder.CreateExtractValue(suspend, asyncContextIndex);
auto context = IGF.emitAsyncResumeProjectContext(calleeContext);
IGF.storeCurrentAsyncContext(context);
}
emitDeallocAsyncContext(IGF, calleeContextBuffer);
forwardAsyncCallResult(IGF, silFunctionType, layout, suspend);
} else {
// Call the replacement function.
SmallVector<llvm::Value *, 16> forwardedArgs;
for (auto &arg : IGF.CurFn->args())
forwardedArgs.push_back(&arg);
auto *fnType = signature.getType()->getPointerTo();
auto *realReplFn = IGF.Builder.CreateBitCast(ReplFn, fnType);
auto authEntity = PointerAuthEntity(f);
auto authInfo = PointerAuthInfo::emit(IGF, schema, fnPtrAddr, authEntity);
auto *Res = IGF.Builder.CreateCall(
FunctionPointer::createSigned(silFunctionType, realReplFn, authInfo,
signature)
.getAsFunction(IGF),
forwardedArgs);
if (Res->getCallingConv() == llvm::CallingConv::SwiftTail &&
Res->getCaller()->getCallingConv() == llvm::CallingConv::SwiftTail) {
Res->setTailCallKind(IGF.IGM.AsyncTailCallKind);
} else {
Res->setTailCall();
}
if (IGF.CurFn->getReturnType()->isVoidTy())
IGF.Builder.CreateRetVoid();
else
IGF.Builder.CreateRet(Res);
}
IGF.Builder.emitBlock(origEntryBB);
}
/// Emit the thunk that dispatches to the dynamically replaceable function.
static void emitDynamicallyReplaceableThunk(IRGenModule &IGM,
LinkEntity varEntity,
LinkEntity keyEntity,
llvm::Function *dispatchFn,
llvm::Function *implFn,
Signature &signature) {
// Create and initialize the first link entry for the chain of replacements.
// The first implementation is initialized with 'implFn'.
auto linkEntry = getChainEntryForDynamicReplacement(IGM, varEntity, implFn);
// Create the key data structure. This is used from other modules to refer to
// the chain of replacements.
createGlobalForDynamicReplacementFunctionKey(IGM, keyEntity, linkEntry);
// We should never inline the implementation function.
implFn->addFnAttr(llvm::Attribute::NoInline);
// Load the function and dispatch to it forwarding our arguments.
IRGenFunction IGF(IGM, dispatchFn);
if (IGM.DebugInfo)
IGM.DebugInfo->emitArtificialFunction(IGF, dispatchFn);
llvm::Constant *indices[] = {llvm::ConstantInt::get(IGM.Int32Ty, 0),
llvm::ConstantInt::get(IGM.Int32Ty, 0)};
auto *fnPtrAddr = llvm::ConstantExpr::getInBoundsGetElementPtr(
linkEntry->getValueType(), linkEntry, indices);
auto *fnPtr = IGF.Builder.CreateLoad(
Address(fnPtrAddr, IGM.FunctionPtrTy, IGM.getPointerAlignment()));
auto *typeFnPtr = IGF.Builder.CreateBitOrPointerCast(fnPtr, implFn->getType());
SmallVector<llvm::Value *, 16> forwardedArgs;
for (auto &arg : dispatchFn->args())
forwardedArgs.push_back(&arg);
bool isAsyncFunction =
keyEntity.hasSILFunction() && keyEntity.getSILFunction()->isAsync();
auto &schema =
isAsyncFunction
? IGM.getOptions().PointerAuth.AsyncSwiftDynamicReplacements
: IGM.getOptions().PointerAuth.SwiftDynamicReplacements;
assert(keyEntity.hasSILFunction() ||
keyEntity.isOpaqueTypeDescriptorAccessor());
auto authEntity = keyEntity.hasSILFunction()
? PointerAuthEntity(keyEntity.getSILFunction())
: PointerAuthEntity::Special::TypeDescriptor;
auto authInfo = PointerAuthInfo::emit(IGF, schema, fnPtrAddr, authEntity);
auto *Res = IGF.Builder.CreateCall(
FunctionPointer::createSigned(FunctionPointer::Kind::Function, typeFnPtr,
authInfo, signature),
forwardedArgs);
Res->setTailCall();
if (implFn->getReturnType()->isVoidTy())
IGF.Builder.CreateRetVoid();
else
IGF.Builder.CreateRet(Res);
}
void IRGenModule::emitOpaqueTypeDescriptorAccessor(OpaqueTypeDecl *opaque) {
auto *namingDecl = opaque->getNamingDecl();
auto *abstractStorage = dyn_cast<AbstractStorageDecl>(namingDecl);
bool isNativeDynamic = false;
const bool isDynamicReplacement = namingDecl->getDynamicallyReplacedDecl();
// Don't emit accessors for abstract storage that is not dynamic or a dynamic
// replacement.
if (abstractStorage) {
isNativeDynamic = abstractStorage->hasAnyNativeDynamicAccessors();
if (!isNativeDynamic && !isDynamicReplacement)
return;
}
// Don't emit accessors for functions that are not dynamic or dynamic
// replacements.
if (!abstractStorage) {
isNativeDynamic = namingDecl->shouldUseNativeDynamicDispatch();
if (!isNativeDynamic && !isDynamicReplacement)
return;
}
auto accessor = cast<llvm::Function>(
getAddrOfOpaqueTypeDescriptorAccessFunction(opaque, ForDefinition, false)
.getDirectPointer());
if (isNativeDynamic) {
auto thunk = accessor;
auto impl = cast<llvm::Function>(
getAddrOfOpaqueTypeDescriptorAccessFunction(opaque, ForDefinition, true)
.getDirectPointer());
auto varEntity = LinkEntity::forOpaqueTypeDescriptorAccessorVar(opaque);
auto keyEntity = LinkEntity::forOpaqueTypeDescriptorAccessorKey(opaque);
auto fnType = llvm::FunctionType::get(OpaqueTypeDescriptorPtrTy, {}, false);
Signature signature(fnType, llvm::AttributeList(), SwiftCC);
emitDynamicallyReplaceableThunk(*this, varEntity, keyEntity, thunk, impl,
signature);
// We should never inline the thunk function.
thunk->addFnAttr(llvm::Attribute::NoInline);
accessor = impl;
}
// The implementation just returns the opaque type descriptor.
llvm::BasicBlock *entryBB =
llvm::BasicBlock::Create(getLLVMContext(), "entry", accessor);
IRBuilder B(getLLVMContext(), false);
B.SetInsertPoint(entryBB);
if (DebugInfo)
DebugInfo->emitArtificialFunction(B, accessor);
auto *desc = getAddrOfOpaqueTypeDescriptor(opaque, ConstantInit());
B.CreateRet(desc);
}
/// Calls the previous implementation before this dynamic replacement became
/// active.
void IRGenModule::emitDynamicReplacementOriginalFunctionThunk(SILFunction *f) {
assert(f->getDynamicallyReplacedFunction());
if (UseBasicDynamicReplacement)
return;
auto entity = LinkEntity::forSILFunction(f, true);
auto fnType = f->getLoweredFunctionType();
Signature signature = getSignature(fnType);
addLLVMFunctionAttributes(f, signature);
LinkInfo implLink = LinkInfo::get(*this, entity, ForDefinition);
auto implFn =
createFunction(*this, implLink, signature, nullptr /*insertBefore*/,
f->getOptimizationMode(), shouldEmitStackProtector(f));
implFn->addFnAttr(llvm::Attribute::NoInline);
IRGenFunction IGF(*this, implFn);
if (DebugInfo)
DebugInfo->emitArtificialFunction(IGF, implFn);
LinkEntity varEntity =
LinkEntity::forDynamicallyReplaceableFunctionVariable(f);
auto linkEntry = getChainEntryForDynamicReplacement(*this, varEntity, nullptr,
NotForDefinition);
// Load the function and dispatch to it forwarding our arguments.
llvm::Constant *indices[] = {llvm::ConstantInt::get(Int32Ty, 0),
llvm::ConstantInt::get(Int32Ty, 0)};
auto *fnPtrAddr = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
llvm::ConstantExpr::getInBoundsGetElementPtr(linkEntry->getValueType(),
linkEntry, indices),
FunctionPtrTy->getPointerTo());
auto *OrigFn = IGF.Builder.CreateCall(
getGetOrigOfReplaceableFunctionPointer(), {fnPtrAddr});
OrigFn->setDoesNotThrow();
auto *typeFnPtr =
IGF.Builder.CreateBitOrPointerCast(OrigFn, implFn->getType());
SmallVector<llvm::Value *, 16> forwardedArgs;
for (auto &arg : implFn->args())
forwardedArgs.push_back(&arg);
auto &schema = f->isAsync()
? getOptions().PointerAuth.AsyncSwiftDynamicReplacements
: getOptions().PointerAuth.SwiftDynamicReplacements;
auto authInfo = PointerAuthInfo::emit(
IGF, schema, fnPtrAddr,
PointerAuthEntity(f->getDynamicallyReplacedFunction()));
auto *Res = IGF.Builder.CreateCall(
FunctionPointer::createSigned(fnType, typeFnPtr, authInfo, signature)
.getAsFunction(IGF),
forwardedArgs);
Res->setTailCall();
if (f->isAsync()) {
Res->setTailCallKind(IGF.IGM.AsyncTailCallKind);
}
if (implFn->getReturnType()->isVoidTy())
IGF.Builder.CreateRetVoid();
else
IGF.Builder.CreateRet(Res);
}
llvm::Constant *swift::irgen::emitCXXConstructorThunkIfNeeded(
IRGenModule &IGM, Signature signature,
const clang::CXXConstructorDecl *ctor, StringRef name,
llvm::Constant *ctorAddress) {
llvm::FunctionType *assumedFnType = signature.getType();
auto *clangFunc = cast<llvm::Function>(ctorAddress->stripPointerCasts());
llvm::FunctionType *ctorFnType =
cast<llvm::FunctionType>(clangFunc->getValueType());
// Only need a thunk if either:
// 1. The calling conventions do not match, and we need to pass arguments
// differently.
// 2. This is a default constructor, and we need to zero the backing memory of
// the struct.
if (assumedFnType == ctorFnType && !ctor->isDefaultConstructor()) {
return ctorAddress;
}
// Check whether we've created the thunk already.
if (auto *thunkFn = IGM.Module.getFunction(name))
return thunkFn;
llvm::Function *thunk = llvm::Function::Create(
assumedFnType, llvm::Function::PrivateLinkage, name, &IGM.Module);
thunk->setCallingConv(IGM.getOptions().PlatformCCallingConvention);
llvm::AttrBuilder attrBuilder(IGM.getLLVMContext());
IGM.constructInitialFnAttributes(attrBuilder);
attrBuilder.addAttribute(llvm::Attribute::AlwaysInline);
llvm::AttributeList attr = signature.getAttributes().addFnAttributes(
IGM.getLLVMContext(), attrBuilder);
thunk->setAttributes(attr);
IRGenFunction subIGF(IGM, thunk);
if (IGM.DebugInfo)
IGM.DebugInfo->emitArtificialFunction(subIGF, thunk);
SmallVector<llvm::Value *, 8> Args;
for (auto i = thunk->arg_begin(), e = thunk->arg_end(); i != e; ++i) {
auto *argTy = i->getType();
auto *paramTy = ctorFnType->getParamType(i - thunk->arg_begin());
if (paramTy != argTy)
Args.push_back(subIGF.coerceValue(i, paramTy, IGM.DataLayout));
else
Args.push_back(i);
}
if (assumedFnType != ctorFnType) {
clang::CodeGen::ImplicitCXXConstructorArgs implicitArgs =
clang::CodeGen::getImplicitCXXConstructorArgs(IGM.ClangCodeGen->CGM(),
ctor);
for (size_t i = 0; i < implicitArgs.Prefix.size(); ++i) {
Args.insert(Args.begin() + 1 + i, implicitArgs.Prefix[i]);
}
for (const auto &arg : implicitArgs.Suffix) {
Args.push_back(arg);
}
}
if (ctor->isDefaultConstructor()) {
assert(Args.size() > 0 && "expected at least 1 argument (result address) "
"for default constructor");
// Zero out the backing memory of the struct.
// This makes default initializers for C++ structs behave consistently with
// the synthesized empty initializers for C structs. When C++ interop is
// enabled in a project, all imported C structs are treated as C++ structs,
// which sometimes means that Clang will synthesize a default constructor
// for the C++ struct that does not zero out trivial fields of a struct.
auto cxxRecord = ctor->getParent();
clang::ASTContext &ctx = cxxRecord->getASTContext();
auto typeSize = ctx.getTypeSizeInChars(ctx.getRecordType(cxxRecord));
subIGF.Builder.CreateMemSet(Args[0],
llvm::ConstantInt::get(subIGF.IGM.Int8Ty, 0),
typeSize.getQuantity(), llvm::MaybeAlign());
}
auto *call =
emitCXXConstructorCall(subIGF, ctor, ctorFnType, ctorAddress, Args);
if (isa<llvm::InvokeInst>(call))
IGM.emittedForeignFunctionThunksWithExceptionTraps.insert(thunk);
if (ctorFnType->getReturnType()->isVoidTy())
subIGF.Builder.CreateRetVoid();
else
subIGF.Builder.CreateRet(call);
return thunk;
}
llvm::CallBase *swift::irgen::emitCXXConstructorCall(
IRGenFunction &IGF, const clang::CXXConstructorDecl *ctor,
llvm::FunctionType *ctorFnType, llvm::Constant *ctorAddress,
llvm::ArrayRef<llvm::Value *> args) {
bool canThrow =
IGF.IGM.isForeignExceptionHandlingEnabled() &&
!IGF.IGM.isCxxNoThrow(const_cast<clang::CXXConstructorDecl *>(ctor));
if (!canThrow)
return IGF.Builder.CreateCall(ctorFnType, ctorAddress, args);
llvm::CallBase *result;
IGF.createExceptionTrapScope([&](llvm::BasicBlock *invokeNormalDest,
llvm::BasicBlock *invokeUnwindDest) {
result = IGF.Builder.createInvoke(ctorFnType, ctorAddress, args,
invokeNormalDest, invokeUnwindDest);
});
return result;
}
StackProtectorMode IRGenModule::shouldEmitStackProtector(SILFunction *f) {
const SILOptions &opts = IRGen.SIL.getOptions();
return (opts.EnableStackProtection && f->needsStackProtection()) ?
StackProtectorMode::StackProtector : StackProtectorMode::NoStackProtector;
}
/// Find the entry point for a SIL function.
llvm::Function *IRGenModule::getAddrOfSILFunction(
SILFunction *f, ForDefinition_t forDefinition,
bool isDynamicallyReplaceableImplementation,
bool shouldCallPreviousImplementation) {
assert(forDefinition || !isDynamicallyReplaceableImplementation);
assert(!forDefinition || !shouldCallPreviousImplementation);
LinkEntity entity =
LinkEntity::forSILFunction(f, shouldCallPreviousImplementation);
auto clangDecl = f->getClangDecl();
auto cxxCtor = dyn_cast_or_null<clang::CXXConstructorDecl>(clangDecl);
// Check whether we've created the function already. If the function is a C++
// constructor, don't return the constructor here as a thunk might be needed
// to call the constructor.
// FIXME: We should integrate this into the LinkEntity cache more cleanly.
llvm::Function *fn = Module.getFunction(entity.mangleAsString());
if (fn && !cxxCtor) {
if (forDefinition) {
updateLinkageForDefinition(*this, fn, entity);
}
return fn;
}
// If it's a Clang declaration, ask Clang to generate the IR declaration.
// This might generate new functions, so we should do it before computing
// the insert-before point.
llvm::Constant *clangAddr = nullptr;
bool isObjCDirect = false;
if (clangDecl) {
// If we have an Objective-C Clang declaration, it must be a direct
// method and we want to generate the IR declaration ourselves.
if (auto objcDecl = dyn_cast<clang::ObjCMethodDecl>(clangDecl)) {
isObjCDirect = true;
assert(objcDecl->isDirectMethod());
} else {
auto globalDecl = getClangGlobalDeclForFunction(clangDecl);
clangAddr = getAddrOfClangGlobalDecl(globalDecl, forDefinition);
}
if (cxxCtor) {
Signature signature = getSignature(f->getLoweredFunctionType(), cxxCtor);
// The thunk has private linkage, so it doesn't need to have a predictable
// mangled name -- we just need to make sure the name is unique.
llvm::SmallString<32> name;
llvm::raw_svector_ostream stream(name);
stream << "__swift_cxx_ctor";
entity.mangle(stream);
clangAddr = emitCXXConstructorThunkIfNeeded(*this, signature, cxxCtor, name,
clangAddr);
}
}
LinkInfo link = LinkInfo::get(*this, entity, forDefinition);
bool isDefinition = f->isDefinition();
bool hasOrderNumber =
isDefinition && !shouldCallPreviousImplementation;
unsigned orderNumber = ~0U;
llvm::Function *insertBefore = nullptr;
// If the SIL function has a definition, we should have an order
// number for it; make sure to insert it in that position relative
// to other ordered functions.
if (hasOrderNumber) {
orderNumber = IRGen.getFunctionOrder(f);
if (auto emittedFunctionIterator
= EmittedFunctionsByOrder.findLeastUpperBound(orderNumber))
insertBefore = *emittedFunctionIterator;
}
// If it's a Clang declaration, check whether Clang gave us a declaration.
if (clangAddr) {
fn = dyn_cast<llvm::Function>(clangAddr->stripPointerCasts());
if (fn) {
if (!forDefinition) {
// Override the linkage computed by Clang if the decl is from another
// module that imported @_weakLinked.
//
// FIXME: We should be able to set the linkage unconditionally here but
// some fixes are needed for Cxx interop.
if (auto *parentModule = f->getParentModule())
if (getSwiftModule()->isImportedAsWeakLinked(parentModule))
fn->setLinkage(link.getLinkage());
}
// If we have a function, move it to the appropriate position.
if (hasOrderNumber) {
auto &fnList = Module.getFunctionList();
fnList.remove(fn);
if (insertBefore)
fnList.insert(llvm::Module::iterator(insertBefore), fn);
else
fnList.push_back(fn);
EmittedFunctionsByOrder.insert(orderNumber, fn);
}
return fn;
}
// Otherwise, if we have a lazy definition for it, be sure to queue that up.
} else if (isDefinition && !forDefinition &&
isLazilyEmittedFunction(*f, getSILModule())) {
IRGen.addLazyFunction(f);
}
auto fpKind = irgen::classifyFunctionPointerKind(f);
Signature signature =
getSignature(f->getLoweredFunctionType(), fpKind, isObjCDirect);
addLLVMFunctionAttributes(f, signature);
fn = createFunction(*this, link, signature, insertBefore,
f->getOptimizationMode(), shouldEmitStackProtector(f));
// Mark as llvm.used if @_used, set section if @_section
if (f->markedAsUsed())
addUsedGlobal(fn);
if (!f->section().empty())
fn->setSection(f->section());
llvm::AttrBuilder attrBuilder(getLLVMContext());
if (!f->wasmExportName().empty()) {
attrBuilder.addAttribute("wasm-export-name", f->wasmExportName());
}
if (!f->wasmImportFieldName().empty()) {
attrBuilder.addAttribute("wasm-import-name", f->wasmImportFieldName());
}
if (!f->wasmImportModuleName().empty()) {
attrBuilder.addAttribute("wasm-import-module", f->wasmImportModuleName());
}
fn->addFnAttrs(attrBuilder);
// Also mark as llvm.used any functions that should be kept for the debugger.
// Only definitions should be kept.
if (f->shouldBePreservedForDebugger() && forDefinition)
addUsedGlobal(fn);
// If `hasCReferences` is true, then the function is either marked with
// @_silgen_name OR @_cdecl. If it is the latter, it must have a definition
// associated with it. The combination of the two allows us to identify the
// @_silgen_name functions. These are locally defined function thunks used in
// the standard library. Do not give them DLLImport DLL Storage.
if (!forDefinition) {
fn->setComdat(nullptr);
if (f->hasCReferences())
fn->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
}
// If we have an order number for this function, set it up as appropriate.
if (hasOrderNumber) {
EmittedFunctionsByOrder.insert(orderNumber, fn);
}
return fn;
}
static llvm::GlobalVariable *createGOTEquivalent(IRGenModule &IGM,
llvm::Constant *global,
LinkEntity entity)
{
// Determine the name of this entity.
llvm::SmallString<64> globalName;
entity.mangle(globalName);
if (IGM.Triple.getObjectFormat() == llvm::Triple::COFF) {
if (cast<llvm::GlobalValue>(global)->hasDLLImportStorageClass()) {
// Add the user label prefix *prior* to the introduction of the linker
// synthetic marker `__imp_`.
// Failure to do so will re-decorate the generated symbol and miss the
// user label prefix, generating e.g. `___imp_$sBoW` instead of
// `__imp__$sBoW`.
if (auto prefix = IGM.DataLayout.getGlobalPrefix())
globalName = (llvm::Twine(prefix) + globalName).str();
// Indicate to LLVM that the symbol should not be re-decorated.
llvm::GlobalVariable *GV =
new llvm::GlobalVariable(IGM.Module, global->getType(),
/*Constant=*/true,
llvm::GlobalValue::ExternalLinkage, nullptr,
"\01__imp_" + globalName);
GV->setExternallyInitialized(true);
return GV;
}
}
auto gotEquivalent = new llvm::GlobalVariable(IGM.Module,
global->getType(),
/*constant*/ true,
llvm::GlobalValue::PrivateLinkage,
global,
llvm::Twine("got.") + globalName);
// rdar://problem/53836960: i386 ld64 also mis-links relative references
// to GOT entries.
// rdar://problem/59782487: issue with on-device JITd expressions.
// The JIT gets confused by private vars accessed across object files.
if (!IGM.getOptions().UseJIT &&
(!IGM.Triple.isOSDarwin() || IGM.Triple.getArch() != llvm::Triple::x86)) {
gotEquivalent->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
} else {
ApplyIRLinkage(IRLinkage::InternalLinkOnceODR)
.to(gotEquivalent);
}
// Context descriptor pointers need to be signed.
// TODO: We should really sign a pointer to *any* code entity or true-const
// metadata structure that may reference data structures with function
// pointers inside them.
if (entity.isContextDescriptor()) {
auto schema = IGM.getOptions().PointerAuth.TypeDescriptors;
if (schema) {
auto signedValue = IGM.getConstantSignedPointer(
global, schema, PointerAuthEntity::Special::TypeDescriptor,
/*storageAddress*/ gotEquivalent);
gotEquivalent->setInitializer(signedValue);
}
} else if (entity.isDynamicallyReplaceableKey()) {
auto schema = IGM.getOptions().PointerAuth.SwiftDynamicReplacementKeys;
if (schema) {
auto signedValue = IGM.getConstantSignedPointer(
global, schema, PointerAuthEntity::Special::DynamicReplacementKey,
/*storageAddress*/ gotEquivalent);
gotEquivalent->setInitializer(signedValue);
}
}
return gotEquivalent;
}
llvm::Constant *IRGenModule::getOrCreateGOTEquivalent(llvm::Constant *global,
LinkEntity entity) {
auto &gotEntry = GlobalGOTEquivalents[entity];
if (gotEntry) {
return gotEntry;
}
if (auto *Stats = Context.Stats)
++Stats->getFrontendCounters().NumGOTEntries;
// Use the global as the initializer for an anonymous constant. LLVM can treat
// this as equivalent to the global's GOT entry.
auto gotEquivalent = createGOTEquivalent(*this, global, entity);
gotEntry = gotEquivalent;
return gotEquivalent;
}
static llvm::Constant *getElementBitCast(llvm::GlobalValue *ptr,
llvm::Type *newEltType) {
if (ptr->getValueType() == newEltType) {
return ptr;
} else {
auto newPtrType = newEltType->getPointerTo(
cast<llvm::PointerType>(ptr->getType())->getAddressSpace());
return llvm::ConstantExpr::getBitCast(ptr, newPtrType);
}
}
llvm::Constant *
IRGenModule::getOrCreateLazyGlobalVariable(LinkEntity entity,
llvm::function_ref<ConstantInitFuture(ConstantInitBuilder &)> build,
llvm::function_ref<void(llvm::GlobalVariable *)> finish) {
auto defaultType = entity.getDefaultDeclarationType(*this);
LazyConstantInitializer lazyInitializer = {
defaultType, build, finish
};
return getAddrOfLLVMVariable(entity,
ConstantInit::getLazy(&lazyInitializer),
DebugTypeInfo(), defaultType);
}
/// Return a reference to an object that's suitable for being used for
/// the given kind of reference.
///
/// Note that, if the requested reference kind is a relative reference.
/// the returned constant will not actually be a relative reference.
/// To form the actual relative reference, you must pass the returned
/// result to emitRelativeReference, passing the correct base-address
/// information.
ConstantReference
IRGenModule::getAddrOfLLVMVariable(LinkEntity entity,
ConstantInit definition,
DebugTypeInfo debugType,
SymbolReferenceKind refKind,
llvm::Type *overrideDeclType) {
switch (refKind) {
case SymbolReferenceKind::Relative_Direct:
case SymbolReferenceKind::Far_Relative_Direct:
assert(!definition);
// FIXME: don't just fall through; force the creation of a weak
// definition so that we can emit a relative reference.
LLVM_FALLTHROUGH;
case SymbolReferenceKind::Absolute:
return { getAddrOfLLVMVariable(entity, definition, debugType,
overrideDeclType),
ConstantReference::Direct };
case SymbolReferenceKind::Relative_Indirectable:
case SymbolReferenceKind::Far_Relative_Indirectable:
assert(!definition);
return getAddrOfLLVMVariableOrGOTEquivalent(entity);
}
llvm_unreachable("bad reference kind");
}
/// A convenient wrapper around getAddrOfLLVMVariable which uses the
/// default type as the definition type.
llvm::Constant *
IRGenModule::getAddrOfLLVMVariable(LinkEntity entity,
ForDefinition_t forDefinition,
DebugTypeInfo debugType) {
auto definition = forDefinition
? ConstantInit::getDelayed(entity.getDefaultDeclarationType(*this))
: ConstantInit();
return getAddrOfLLVMVariable(entity, definition, debugType);
}
/// Get or create an llvm::GlobalVariable.
///
/// If a definition type is given, the result will always be an
/// llvm::GlobalVariable of that type. Otherwise, the result will
/// have type pointerToDefaultType and may involve bitcasts.
llvm::Constant *
IRGenModule::getAddrOfLLVMVariable(LinkEntity entity,
ConstantInit definition,
DebugTypeInfo DbgTy,
llvm::Type *overrideDeclType) {
// This function assumes that 'globals' only contains GlobalValue
// values for the entities that it will look up.
llvm::Type *definitionType = (definition ? definition.getType() : nullptr);
auto defaultType = overrideDeclType
? overrideDeclType
: entity.getDefaultDeclarationType(*this);
auto existingGlobal = GlobalVars[entity];
if (existingGlobal) {
auto existing = cast<llvm::GlobalValue>(existingGlobal);
// If we're looking to define something, we may need to replace a
// forward declaration.
if (!definition.isLazy() && definitionType) {
assert(existing->isDeclaration() && "already defined");
updateLinkageForDefinition(*this, existing, entity);
// If the existing entry is a variable of the right type,
// set the initializer on it and return.
if (auto var = dyn_cast<llvm::GlobalVariable>(existing)) {
if (definitionType == var->getValueType()) {
if (definition.hasInit())
definition.getInit().installInGlobal(var);
return var;
}
}
// Fall out to the case below, clearing the name so that
// createVariable doesn't detect a collision.
existingGlobal->setName("");
// Otherwise, we have a previous declaration or definition which
// we need to ensure has the right type.
} else {
return getElementBitCast(existing, defaultType);
}
}
ForDefinition_t forDefinition = (ForDefinition_t) (definitionType != nullptr);
LinkInfo link = LinkInfo::get(*this, entity, forDefinition);
// Clang may have defined the variable already.
if (auto existing = Module.getNamedGlobal(link.getName()))
return getElementBitCast(existing, defaultType);
const LazyConstantInitializer *lazyInitializer = nullptr;
std::optional<ConstantInitBuilder> lazyBuilder;
if (definition.isLazy()) {
lazyInitializer = definition.getLazy();
lazyBuilder.emplace(*this);
// Build the lazy initializer as a future.
auto future = lazyInitializer->Build(*lazyBuilder);
// Set the future as our definition and set its type as the
// definition type.
definitionType = future.getType();
definition = future;
}
// If we're not defining the object now, forward declare it with the default
// type.
if (!definitionType) definitionType = defaultType;
// Create the variable.
auto var = createVariable(*this, link, definitionType,
entity.getAlignment(*this), DbgTy);
// Install the concrete definition if we have one.
if (definition && definition.hasInit()) {
definition.getInit().installInGlobal(var);
}
// Call the creation callback.
if (lazyInitializer) {
lazyInitializer->Create(var);
}
if (lazyInitializer) {
// Protect against self-references that might've been created during
// the lazy emission.
existingGlobal = GlobalVars[entity];
}
// If we have an existing entry, destroy it, replacing it with the
// new variable. We only really have to do
if (existingGlobal) {
auto existing = cast<llvm::GlobalValue>(existingGlobal);
auto castVar = llvm::ConstantExpr::getBitCast(var, existing->getType());
existing->replaceAllUsesWith(castVar);
existing->eraseFromParent();
}
// If there's also an existing GOT-equivalent entry, rewrite it too, since
// LLVM won't recognize a global with bitcasts in its initializers as GOT-
// equivalent. rdar://problem/22388190
auto foundGOTEntry = GlobalGOTEquivalents.find(entity);
if (foundGOTEntry != GlobalGOTEquivalents.end() && foundGOTEntry->second) {
auto existingGOTEquiv = cast<llvm::GlobalVariable>(foundGOTEntry->second);
// Make a new GOT equivalent referring to the new variable with its
// definition type.
auto newGOTEquiv = createGOTEquivalent(*this, var, entity);
auto castGOTEquiv = llvm::ConstantExpr::getBitCast(newGOTEquiv,
existingGOTEquiv->getType());
existingGOTEquiv->replaceAllUsesWith(castGOTEquiv);
existingGOTEquiv->eraseFromParent();
GlobalGOTEquivalents[entity] = newGOTEquiv;
}
// Cache and return.
GlobalVars[entity] = var;
return var;
}
/// Get or create a "GOT equivalent" llvm::GlobalVariable, if applicable.
///
/// Creates a private, unnamed constant containing the address of another
/// global variable. LLVM can replace relative references to this variable with
/// relative references to the GOT entry for the variable in the object file.
ConstantReference
IRGenModule::getAddrOfLLVMVariableOrGOTEquivalent(LinkEntity entity) {
auto canDirectlyReferenceSILFunction = [&](SILFunction *silFn) {
return (silFn->isDefinition() &&
!isAvailableExternally(silFn->getLinkage()) &&
this == IRGen.getGenModule(silFn));
};
// Handle SILFunctions specially, because unlike other entities they aren't
// variables and aren't kept in the GlobalVars table.
if (entity.isSILFunction()) {
auto *silFn = entity.getSILFunction();
auto fn = getAddrOfSILFunction(silFn, NotForDefinition);
if (canDirectlyReferenceSILFunction(silFn)) {
return {fn, ConstantReference::Direct};
}
auto gotEquivalent = getOrCreateGOTEquivalent(fn, entity);
return {gotEquivalent, ConstantReference::Indirect};
}
// ObjC class references can always be directly referenced, even in
// the weird cases where we don't see a definition.
if (entity.isObjCClassRef()) {
auto value = getAddrOfObjCClassRef(
const_cast<ClassDecl *>(cast<ClassDecl>(entity.getDecl())));
return { cast<llvm::Constant>(value.getAddress()),
ConstantReference::Direct };
}
// Ensure the variable is at least forward-declared.
getAddrOfLLVMVariable(entity, ConstantInit(), DebugTypeInfo());
auto entry = GlobalVars[entity];
/// Returns a direct reference.
auto direct = [&]() -> ConstantReference {
// FIXME: Relative references to aliases break MC on 32-bit Mach-O
// platforms (rdar://problem/22450593 ), so substitute an alias with its
// aliasee to work around that.
if (auto alias = dyn_cast<llvm::GlobalAlias>(entry))
return {alias->getAliasee(), ConstantReference::Direct};
return {entry, ConstantReference::Direct};
};
/// Returns an indirect reference.
auto indirect = [&]() -> ConstantReference {
auto gotEquivalent = getOrCreateGOTEquivalent(
cast<llvm::GlobalValue>(entry), entity);
return {gotEquivalent, ConstantReference::Indirect};
};
// Dynamically replaceable function keys are stored in the GlobalVars
// table, but they don't have an associated Decl, so they require
// special treatment here.
if (entity.isDynamicallyReplaceableFunctionKey()) {
auto *silFn = entity.getSILFunction();
if (canDirectlyReferenceSILFunction(silFn))
return direct();
return indirect();
}
if (auto *entityDC = entity.getDeclContextForEmission()) {
auto *entitySF = entityDC->getModuleScopeContext();
bool clangImportedEntity = isa<ClangModuleUnit>(entitySF);
auto &mod = getSILModule();
if (!mod.isWholeModule()) {
// In non-WMO builds, the associated context of the SILModule must
// be a source file. Every source file is its own translation unit.
auto *modDC = mod.getAssociatedContext();
auto *modSF = modDC->getModuleScopeContext();
assert(modSF != nullptr);
// Imported entities are in a different Swift module, but are emitted
// on demand and can be referenced directly. Entities in the same
// source file can also be referenced directly.
if (clangImportedEntity ||
modSF == entitySF)
return direct();
// Everything else must be referenced indirectly.
return indirect();
}
// We're performing a WMO build.
//
// The associated context of the SILModule is the entire AST ModuleDecl,
// but we might be doing a multi-threaded IRGen build, in which case
// there is one translation unit per source file.
// Imported entities are in a different Swift module and are emitted
// on demand. In multi-threaded builds, they will be emitted into one
// translation unit only.
if (clangImportedEntity ||
entitySF->getParentModule() == mod.getSwiftModule()) {
// If we're doing a single-threaded WMO build, or if the entity is
// scheduled to be emitted in the same translation unit, reference
// it directly.
if (this == IRGen.getGenModule(entitySF))
return direct();
}
}
// Fall back to an indirect reference if we can't establish that a direct
// reference is OK.
return indirect();
}
TypeEntityReference
IRGenModule::getContextDescriptorEntityReference(const LinkEntity &entity) {
// TODO: consider using a symbolic reference (i.e. a symbol string
// to be looked up dynamically) for types defined outside the module.
auto ref = getAddrOfLLVMVariableOrGOTEquivalent(entity);
auto kind = ref.isIndirect()
? TypeReferenceKind::IndirectTypeDescriptor
: TypeReferenceKind::DirectTypeDescriptor;
return TypeEntityReference(kind, ref.getValue());
}
static TypeEntityReference
getTypeContextDescriptorEntityReference(IRGenModule &IGM,
NominalTypeDecl *decl) {
auto entity = LinkEntity::forNominalTypeDescriptor(decl);
IGM.IRGen.noteUseOfTypeContextDescriptor(decl, DontRequireMetadata);
return IGM.getContextDescriptorEntityReference(entity);
}
static TypeEntityReference
getProtocolDescriptorEntityReference(IRGenModule &IGM, ProtocolDecl *protocol) {
assert(!protocol->hasClangNode() &&
"objc protocols don't have swift protocol descriptors");
auto entity = LinkEntity::forProtocolDescriptor(protocol);
return IGM.getContextDescriptorEntityReference(entity);
}
static TypeEntityReference
getObjCClassByNameReference(IRGenModule &IGM, ClassDecl *cls) {
auto kind = TypeReferenceKind::DirectObjCClassName;
SmallString<64> objcRuntimeNameBuffer;
auto ref = IGM.getAddrOfGlobalString(
cls->getObjCRuntimeName(objcRuntimeNameBuffer),
/*willBeRelativelyAddressed=*/true);
return TypeEntityReference(kind, ref);
}
TypeEntityReference
IRGenModule::getTypeEntityReference(GenericTypeDecl *decl) {
if (auto protocol = dyn_cast<ProtocolDecl>(decl)) {
assert(!protocol->hasClangNode() && "imported protocols not handled here");
return getProtocolDescriptorEntityReference(*this, protocol);
}
if (auto opaque = dyn_cast<OpaqueTypeDecl>(decl)) {
auto entity = LinkEntity::forOpaqueTypeDescriptor(opaque);
IRGen.noteUseOfOpaqueTypeDescriptor(opaque);
return getContextDescriptorEntityReference(entity);
}
if (auto nominal = dyn_cast<NominalTypeDecl>(decl)) {
auto clazz = dyn_cast<ClassDecl>(decl);
if (!clazz || clazz->isForeignReferenceType()) {
return getTypeContextDescriptorEntityReference(*this, nominal);
}
switch (clazz->getForeignClassKind()) {
case ClassDecl::ForeignKind::RuntimeOnly:
return getObjCClassByNameReference(*this, clazz);
case ClassDecl::ForeignKind::CFType:
return getTypeContextDescriptorEntityReference(*this, clazz);
case ClassDecl::ForeignKind::Normal:
if (hasKnownSwiftMetadata(*this, clazz)) {
return getTypeContextDescriptorEntityReference(*this, clazz);
}
// Note: we would like to use an Objective-C class reference, but the
// Darwin linker currently has a bug where it will coalesce these symbols
// *after* computing a relative offset, causing incorrect relative
// offsets in the metadata. Therefore, reference Objective-C classes by
// their runtime names.
return getObjCClassByNameReference(*this, clazz);
}
}
llvm_unreachable("bad foreign type kind");
}
/// Form an LLVM constant for the relative distance between a reference
/// (appearing at gep (0, indices) of `base`) and `target`.
llvm::Constant *
IRGenModule::emitRelativeReference(ConstantReference target,
llvm::GlobalValue *base,
ArrayRef<unsigned> baseIndices) {
llvm::Constant *relativeAddr =
emitDirectRelativeReference(target.getValue(), base, baseIndices);
// If the reference is indirect, flag it by setting the low bit.
// (All of the base, direct target, and GOT entry need to be pointer-aligned
// for this to be OK.)
if (target.isIndirect()) {
relativeAddr = llvm::ConstantExpr::getAdd(relativeAddr,
llvm::ConstantInt::get(RelativeAddressTy, 1));
}
return relativeAddr;
}
/// Form an LLVM constant for the relative distance between a reference
/// (appearing at gep (0, indices...) of `base`) and `target`. For now,
/// for this to succeed portably, both need to be globals defined in the
/// current translation unit.
llvm::Constant *
IRGenModule::emitDirectRelativeReference(llvm::Constant *target,
llvm::GlobalValue *base,
// llvm::Constant *base,
ArrayRef<unsigned> baseIndices) {
// Convert the target to an integer.
auto targetAddr = llvm::ConstantExpr::getPtrToInt(target, SizeTy);
SmallVector<llvm::Constant*, 4> indices;
indices.push_back(llvm::ConstantInt::get(Int32Ty, 0));
for (unsigned baseIndex : baseIndices) {
indices.push_back(llvm::ConstantInt::get(Int32Ty, baseIndex));
};
// Drill down to the appropriate address in the base, then convert
// that to an integer.
auto baseElt = llvm::ConstantExpr::getInBoundsGetElementPtr(
base->getValueType(), base, indices);
auto baseAddr = llvm::ConstantExpr::getPtrToInt(baseElt, SizeTy);
// The relative address is the difference between those.
auto relativeAddr = llvm::ConstantExpr::getSub(targetAddr, baseAddr);
// Relative addresses can be 32-bit even on 64-bit platforms.
if (SizeTy != RelativeAddressTy)
relativeAddr = llvm::ConstantExpr::getTrunc(relativeAddr,
RelativeAddressTy);
return relativeAddr;
}
/// Expresses that `var` is removable (dead-strippable) when `dependsOn` is not
/// referenced.
void IRGenModule::appendLLVMUsedConditionalEntry(llvm::GlobalVariable *var,
llvm::Constant *dependsOn) {
llvm::Metadata *metadata[] = {
// (1) which variable is being conditionalized, "target"
llvm::ConstantAsMetadata::get(var),
// (2) type, not relevant for a single-edge condition
llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
llvm::Type::getInt32Ty(Module.getContext()), 0)),
// (3) the "edge" that holds the target alive, if it's missing the target
// is allowed to be removed
llvm::MDNode::get(Module.getContext(),
{
llvm::ConstantAsMetadata::get(dependsOn),
}),
};
UsedConditionals.push_back(llvm::MDNode::get(Module.getContext(), metadata));
}
/// Expresses that `var` is removable (dead-strippable) when either the protocol
/// from `record` is not referenced or the type from `record` is not referenced.
void IRGenModule::appendLLVMUsedConditionalEntry(
llvm::GlobalVariable *var, const ProtocolConformance *conformance) {
auto *protocol = getAddrOfProtocolDescriptor(conformance->getProtocol())
->stripPointerCasts();
auto *type = getAddrOfTypeContextDescriptor(
conformance->getDeclContext()->getSelfNominalTypeDecl(),
DontRequireMetadata)->stripPointerCasts();
llvm::Metadata *metadata[] = {
// (1) which variable is being conditionalized, "target"
llvm::ConstantAsMetadata::get(var),
// (2) type, "1" = if either edge is missing, the target is allowed to be
// removed.
llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
llvm::Type::getInt32Ty(Module.getContext()), 1)),
// (3) list of edges
llvm::MDNode::get(Module.getContext(),
{
llvm::ConstantAsMetadata::get(protocol),
llvm::ConstantAsMetadata::get(type),
}),
};
UsedConditionals.push_back(llvm::MDNode::get(Module.getContext(), metadata));
}
void IRGenModule::emitUsedConditionals() {
if (UsedConditionals.empty())
return;
auto *usedConditional =
Module.getOrInsertNamedMetadata("llvm.used.conditional");
for (auto *M : UsedConditionals) {
// Process the dependencies ("edges") and strip any pointer casts on them.
// Those might appear when a dependency is originally added against a
// declaration only, and later the declaration is RAUW'd with a definition
// causing a bitcast to get added to the metadata entry in the dependency.
auto *DependenciesMD =
dyn_cast_or_null<llvm::MDNode>(M->getOperand(2).get());
for (unsigned int I = 0; I < DependenciesMD->getNumOperands(); I++) {
auto *Dependency = DependenciesMD->getOperand(I).get();
auto *C = llvm::mdconst::extract_or_null<llvm::Constant>(Dependency)
->stripPointerCasts();
DependenciesMD->replaceOperandWith(I, llvm::ConstantAsMetadata::get(C));
}
usedConditional->addOperand(M);
}
}
/// Emit the protocol descriptors list and return it (if asContiguousArray is
/// true, otherwise the descriptors are emitted as individual globals and
/// nullptr is returned).
llvm::Constant *IRGenModule::emitSwiftProtocols(bool asContiguousArray) {
if (SwiftProtocols.empty())
return nullptr;
StringRef sectionName;
switch (TargetInfo.OutputObjectFormat) {
case llvm::Triple::DXContainer:
case llvm::Triple::GOFF:
case llvm::Triple::SPIRV:
case llvm::Triple::UnknownObjectFormat:
llvm_unreachable("Don't know how to emit protocols for "
"the selected object format.");
case llvm::Triple::MachO:
sectionName = "__TEXT, __swift5_protos, regular";
break;
case llvm::Triple::ELF:
case llvm::Triple::Wasm:
sectionName = "swift5_protocols";
break;
case llvm::Triple::XCOFF:
case llvm::Triple::COFF:
sectionName = ".sw5prt$B";
break;
}
// For JIT, emit the protocol list as a single global array, and return it.
if (asContiguousArray) {
ConstantInitBuilder builder(*this);
auto recordsArray = builder.beginArray(ProtocolRecordTy);
for (auto *protocol : SwiftProtocols) {
auto record = recordsArray.beginStruct(ProtocolRecordTy);
// Relative reference to the protocol descriptor.
auto descriptorRef = getAddrOfLLVMVariableOrGOTEquivalent(
LinkEntity::forProtocolDescriptor(protocol));
record.addRelativeAddress(descriptorRef);
record.finishAndAddTo(recordsArray);
}
// Define the global variable for the protocol list.
// FIXME: This needs to be a linker-local symbol in order for Darwin ld to
// resolve relocations relative to it.
auto var = recordsArray.finishAndCreateGlobal(
"\x01l_protocols", Alignment(4),
/*isConstant*/ true, llvm::GlobalValue::PrivateLinkage);
var->setSection(sectionName);
disableAddressSanitizer(*this, var);
addUsedGlobal(var);
return var;
}
// In non-JIT mode, emit the protocol records as individual globals.
for (auto *protocol : SwiftProtocols) {
auto entity = LinkEntity::forProtocolDescriptor(protocol);
auto link = LinkInfo::get(*this, entity, NotForDefinition);
auto recordMangledName =
LinkEntity::forProtocolDescriptorRecord(protocol).mangleAsString();
auto var =
new llvm::GlobalVariable(Module, ProtocolRecordTy, /*isConstant*/ true,
llvm::GlobalValue::PrivateLinkage,
/*initializer*/ nullptr, recordMangledName);
auto descriptorRef = getAddrOfLLVMVariableOrGOTEquivalent(entity);
llvm::Constant *relativeAddr =
emitDirectRelativeReference(descriptorRef.getValue(), var, {0});
llvm::Constant *recordFields[] = {relativeAddr};
auto record = llvm::ConstantStruct::get(ProtocolRecordTy, recordFields);
var->setInitializer(record);
var->setSection(sectionName);
var->setAlignment(llvm::MaybeAlign(4));
disableAddressSanitizer(*this, var);
addUsedGlobal(var);
if (IRGen.Opts.ConditionalRuntimeRecords) {
// Allow dead-stripping `var` (the protocol record) when the protocol
// (descriptorRef) is not referenced.
appendLLVMUsedConditionalEntry(var, descriptorRef.getValue());
}
}
return nullptr;
}
/// Determine whether the given protocol conformance can be found via
/// metadata for dynamic lookup.
static bool conformanceIsVisibleViaMetadata(
RootProtocolConformance *conformance) {
auto normal = dyn_cast<NormalProtocolConformance>(conformance);
if (!normal)
return true;
// Conformances of a protocol to another protocol cannot be looked up
// dynamically.
return !normal->isConformanceOfProtocol();
}
void IRGenModule::addProtocolConformance(ConformanceDescription &&record) {
emitProtocolConformance(record);
if (conformanceIsVisibleViaMetadata(record.conformance)) {
// Add this conformance to the conformance list.
ProtocolConformances.push_back(std::move(record));
}
}
AccessibleFunction AccessibleFunction::forSILFunction(IRGenModule &IGM,
SILFunction *func) {
assert(!func->isDistributed() && "use forDistributed(...) instead");
llvm::Constant *funcAddr = nullptr;
if (func->isAsync()) {
funcAddr = IGM.getAddrOfAsyncFunctionPointer(func);
} else {
funcAddr = IGM.getAddrOfSILFunction(func, NotForDefinition);
}
return AccessibleFunction(
/*recordName=*/LinkEntity::forAccessibleFunctionRecord(func)
.mangleAsString(),
/*funcName=*/LinkEntity::forSILFunction(func).mangleAsString(),
/*isDistributed=*/false, func->getLoweredFunctionType(), funcAddr);
}
AccessibleFunction AccessibleFunction::forDistributed(std::string recordName,
std::string accessorName,
CanSILFunctionType type,
llvm::Constant *address) {
return AccessibleFunction(recordName, accessorName,
/*isDistributed=*/true, type, address);
}
void IRGenModule::addAccessibleFunction(AccessibleFunction func) {
AccessibleFunctions.push_back(std::move(func));
}
/// Emit the protocol conformance list and return it (if asContiguousArray is
/// true, otherwise the records are emitted as individual globals and
/// nullptr is returned).
llvm::Constant *IRGenModule::emitProtocolConformances(bool asContiguousArray) {
if (ProtocolConformances.empty())
return nullptr;
StringRef sectionName;
switch (TargetInfo.OutputObjectFormat) {
case llvm::Triple::DXContainer:
case llvm::Triple::GOFF:
case llvm::Triple::SPIRV:
case llvm::Triple::UnknownObjectFormat:
llvm_unreachable("Don't know how to emit protocol conformances for "
"the selected object format.");
case llvm::Triple::MachO:
sectionName = "__TEXT, __swift5_proto, regular";
break;
case llvm::Triple::ELF:
case llvm::Triple::Wasm:
sectionName = "swift5_protocol_conformances";
break;
case llvm::Triple::XCOFF:
case llvm::Triple::COFF:
sectionName = ".sw5prtc$B";
break;
}
// For JIT, emit the protocol conformance list as a single global array, and
// return it.
if (asContiguousArray) {
ConstantInitBuilder builder(*this);
auto descriptorArray = builder.beginArray(RelativeAddressTy);
for (const auto &record : ProtocolConformances) {
auto conformance = record.conformance;
auto entity = LinkEntity::forProtocolConformanceDescriptor(conformance);
auto descriptor =
getAddrOfLLVMVariable(entity, ConstantInit(), DebugTypeInfo());
descriptorArray.addRelativeAddress(descriptor);
}
// Define the global variable for the conformance list.
// FIXME: This needs to be a linker-local symbol in order for Darwin ld to
// resolve relocations relative to it.
auto var = descriptorArray.finishAndCreateGlobal(
"\x01l_protocol_conformances", Alignment(4),
/*isConstant*/ true, llvm::GlobalValue::PrivateLinkage);
var->setSection(sectionName);
disableAddressSanitizer(*this, var);
addUsedGlobal(var);
return var;
}
// In non-JIT mode, emit the protocol conformance records as individual
// globals.
for (const auto &record : ProtocolConformances) {
auto entity =
LinkEntity::forProtocolConformanceDescriptor(record.conformance);
auto link = LinkInfo::get(*this, entity, NotForDefinition);
auto recordMangledName =
LinkEntity::forProtocolConformanceDescriptorRecord(record.conformance)
.mangleAsString();
auto var = new llvm::GlobalVariable(
Module, RelativeAddressTy, /*isConstant*/ true,
llvm::GlobalValue::PrivateLinkage, /*initializer*/ nullptr,
recordMangledName);
auto descriptorRef = getAddrOfLLVMVariableOrGOTEquivalent(entity);
llvm::Constant *relativeAddr =
emitDirectRelativeReference(descriptorRef.getValue(), var, {});
var->setInitializer(relativeAddr);
var->setSection(sectionName);
var->setAlignment(llvm::MaybeAlign(4));
disableAddressSanitizer(*this, var);
addUsedGlobal(var);
if (IRGen.Opts.ConditionalRuntimeRecords) {
// Allow dead-stripping `var` (the conformance record) when the protocol
// or type (from the conformance) is not referenced.
appendLLVMUsedConditionalEntry(var, record.conformance);
}
}
return nullptr;
}
/// Emit list of type metadata records for types that might not have explicit
/// protocol conformances, and return it (if asContiguousArray is true,
/// otherwise the descriptors are emitted as individual globals and nullptr is
/// returned).
llvm::Constant *IRGenModule::emitTypeMetadataRecords(bool asContiguousArray) {
if (RuntimeResolvableTypes.empty()
&& RuntimeResolvableTypes2.empty())
return nullptr;
std::string sectionName;
std::string section2Name;
switch (TargetInfo.OutputObjectFormat) {
case llvm::Triple::MachO:
sectionName = "__TEXT, __swift5_types, regular";
section2Name = "__TEXT, __swift5_types2, regular";
break;
case llvm::Triple::ELF:
case llvm::Triple::Wasm:
sectionName = "swift5_type_metadata";
section2Name = "swift5_type_metadata_2";
break;
case llvm::Triple::XCOFF:
case llvm::Triple::COFF:
sectionName = ".sw5tymd$B";
section2Name = ".sw5tym2$B";
break;
case llvm::Triple::DXContainer:
case llvm::Triple::GOFF:
case llvm::Triple::SPIRV:
case llvm::Triple::UnknownObjectFormat:
llvm_unreachable("Don't know how to emit type metadata table for "
"the selected object format.");
}
auto generateRecord = [this](TypeEntityReference ref,
llvm::GlobalVariable *var,
ArrayRef<unsigned> baseIndices) {
// Form the relative address, with the type reference kind in the low bits.
llvm::Constant *relativeAddr =
emitDirectRelativeReference(ref.getValue(), var, baseIndices);
unsigned lowBits = static_cast<unsigned>(ref.getKind());
if (lowBits != 0) {
relativeAddr = llvm::ConstantExpr::getAdd(
relativeAddr, llvm::ConstantInt::get(RelativeAddressTy, lowBits));
}
llvm::Constant *recordFields[] = {relativeAddr};
auto record = llvm::ConstantStruct::get(TypeMetadataRecordTy, recordFields);
return record;
};
// For JIT, emit the type list as a single global array, and return it.
if (asContiguousArray) {
// Define the global variable for the list of types.
// We have to do this before defining the initializer since the entries will
// contain offsets relative to themselves.
// FIXME: This needs to be a linker-local symbol in order for Darwin ld to
// resolve relocations relative to it.
auto arrayTy = llvm::ArrayType::get(TypeMetadataRecordTy,
RuntimeResolvableTypes.size());
auto var = new llvm::GlobalVariable(
Module, arrayTy,
/*isConstant*/ true, llvm::GlobalValue::PrivateLinkage,
/*initializer*/ nullptr, "\x01l_type_metadata_table");
SmallVector<llvm::Constant *, 8> elts;
for (auto type : RuntimeResolvableTypes) {
auto ref = getTypeEntityReference(type);
unsigned arrayIdx = elts.size();
auto record = generateRecord(ref, var, { arrayIdx, 0 });
elts.push_back(record);
}
auto initializer = llvm::ConstantArray::get(arrayTy, elts);
var->setInitializer(initializer);
var->setSection(sectionName);
var->setAlignment(llvm::MaybeAlign(4));
disableAddressSanitizer(*this, var);
addUsedGlobal(var);
return var;
}
// In non-JIT mode, emit the type records as individual globals.
auto generateGlobalTypeList = [&](ArrayRef<GenericTypeDecl *> typesList,
StringRef section) {
if (typesList.empty()) {
return;
}
for (auto type : typesList) {
auto ref = getTypeEntityReference(type);
std::string recordMangledName;
if (auto opaque = dyn_cast<OpaqueTypeDecl>(type)) {
recordMangledName =
LinkEntity::forOpaqueTypeDescriptorRecord(opaque).mangleAsString();
} else if (auto nominal = dyn_cast<NominalTypeDecl>(type)) {
recordMangledName =
LinkEntity::forNominalTypeDescriptorRecord(nominal).mangleAsString();
} else {
llvm_unreachable("bad type in RuntimeResolvableTypes");
}
auto var = new llvm::GlobalVariable(
Module, TypeMetadataRecordTy, /*isConstant*/ true,
llvm::GlobalValue::PrivateLinkage, /*initializer*/ nullptr,
recordMangledName);
auto record = generateRecord(ref, var, {0});
var->setInitializer(record);
var->setSection(section);
var->setAlignment(llvm::MaybeAlign(4));
disableAddressSanitizer(*this, var);
addUsedGlobal(var);
if (IRGen.Opts.ConditionalRuntimeRecords) {
// Allow dead-stripping `var` (the type record) when the type (`ref`) is
// not referenced.
appendLLVMUsedConditionalEntry(var, ref.getValue());
}
}
};
generateGlobalTypeList(RuntimeResolvableTypes, sectionName);
generateGlobalTypeList(RuntimeResolvableTypes2, section2Name);
return nullptr;
}
void IRGenModule::emitAccessibleFunction(StringRef sectionName,
const AccessibleFunction &func) {
auto var = new llvm::GlobalVariable(
Module, AccessibleFunctionRecordTy, /*isConstant=*/true,
llvm::GlobalValue::PrivateLinkage, /*initializer=*/nullptr,
func.getRecordName());
ConstantInitBuilder builder(*this);
// ==== Store fields of 'TargetAccessibleFunctionRecord'
ConstantStructBuilder fields =
builder.beginStruct(AccessibleFunctionRecordTy);
// -- Field: Name (record name)
{
llvm::Constant *name =
getAddrOfGlobalString(func.getFunctionName(),
/*willBeRelativelyAddressed=*/true);
fields.addRelativeAddress(name);
}
// -- Field: GenericEnvironment
llvm::Constant *genericEnvironment = nullptr;
GenericSignature signature = func.getType()->getInvocationGenericSignature();
if (signature) {
// Drop all the marker protocols because they are effect-less
// at runtime.
signature = signature.withoutMarkerProtocols();
genericEnvironment =
getAddrOfGenericEnvironment(signature.getCanonicalSignature());
}
fields.addRelativeAddressOrNull(genericEnvironment);
// -- Field: FunctionType
llvm::Constant *type =
getTypeRef(func.getType(), signature, MangledTypeRefRole::Metadata).first;
fields.addRelativeAddress(type);
// -- Field: Function
fields.addRelativeAddress(func.getAddress());
// -- Field: Flags
AccessibleFunctionFlags flags;
flags.setDistributed(func.isDistributed());
fields.addInt32(flags.getOpaqueValue());
// ---- End of 'TargetAccessibleFunctionRecord' fields
fields.finishAndSetAsInitializer(var);
var->setSection(sectionName);
var->setAlignment(llvm::MaybeAlign(4));
disableAddressSanitizer(*this, var);
addUsedGlobal(var);
}
void IRGenModule::emitAccessibleFunctions() {
if (AccessibleFunctions.empty())
return;
StringRef fnsSectionName;
switch (TargetInfo.OutputObjectFormat) {
case llvm::Triple::DXContainer:
case llvm::Triple::GOFF:
case llvm::Triple::SPIRV:
case llvm::Triple::UnknownObjectFormat:
llvm_unreachable("Don't know how to emit accessible functions for "
"the selected object format.");
case llvm::Triple::MachO:
fnsSectionName = "__TEXT, __swift5_acfuncs, regular";
break;
case llvm::Triple::ELF:
case llvm::Triple::Wasm:
fnsSectionName = "swift5_accessible_functions";
break;
case llvm::Triple::XCOFF:
case llvm::Triple::COFF:
fnsSectionName = ".sw5acfn$B";
break;
}
for (const auto &func : AccessibleFunctions) {
emitAccessibleFunction(fnsSectionName, func);
}
}
/// Fetch a global reference to a reference to the given Objective-C class.
/// The result is of type ObjCClassPtrTy->getPointerTo().
Address IRGenModule::getAddrOfObjCClassRef(ClassDecl *theClass) {
assert(ObjCInterop && "getting address of ObjC class ref in no-interop mode");
LinkEntity entity = LinkEntity::forObjCClassRef(theClass);
auto DbgTy = DebugTypeInfo::getObjCClass(
theClass, ObjCClassPtrTy, getPointerSize(), getPointerAlignment());
auto addr = getAddrOfLLVMVariable(entity, ConstantInit(), DbgTy);
// Define it lazily.
if (auto global = dyn_cast<llvm::GlobalVariable>(addr)) {
if (global->isDeclaration()) {
global->setSection(GetObjCSectionName("__objc_classrefs",
"regular,no_dead_strip"));
global->setLinkage(llvm::GlobalVariable::PrivateLinkage);
global->setExternallyInitialized(true);
global->setInitializer(getAddrOfObjCClass(theClass, NotForDefinition));
addCompilerUsedGlobal(global);
}
}
return Address(addr, ObjCClassPtrTy, entity.getAlignment(*this));
}
/// Fetch a global reference to the given Objective-C class. The
/// result is of type ObjCClassPtrTy.
llvm::Constant *IRGenModule::getAddrOfObjCClass(ClassDecl *theClass,
ForDefinition_t forDefinition) {
assert(ObjCInterop && "getting address of ObjC class in no-interop mode");
assert(!theClass->isForeign());
LinkEntity entity = LinkEntity::forObjCClass(theClass);
auto DbgTy = DebugTypeInfo::getObjCClass(
theClass, ObjCClassPtrTy, getPointerSize(), getPointerAlignment());
auto addr = getAddrOfLLVMVariable(entity, forDefinition, DbgTy);
return addr;
}
/// Fetch the declaration of a metaclass object. The result is always a
/// GlobalValue of ObjCClassPtrTy, and is either the Objective-C metaclass or
/// the Swift metaclass stub, depending on whether the class is published as an
/// ObjC class.
llvm::Constant *
IRGenModule::getAddrOfMetaclassObject(ClassDecl *decl,
ForDefinition_t forDefinition) {
assert((!decl->isGenericContext() || decl->hasClangNode()) &&
"generic classes do not have a static metaclass object");
auto entity = decl->getMetaclassKind() == ClassDecl::MetaclassKind::ObjC
? LinkEntity::forObjCMetaclass(decl)
: LinkEntity::forSwiftMetaclassStub(decl);
auto DbgTy = DebugTypeInfo::getObjCClass(
decl, ObjCClassPtrTy, getPointerSize(), getPointerAlignment());
auto addr = getAddrOfLLVMVariable(entity, forDefinition, DbgTy);
return addr;
}
llvm::Constant *
IRGenModule::getAddrOfCanonicalSpecializedGenericMetaclassObject(
CanType concreteType, ForDefinition_t forDefinition) {
auto *theClass = concreteType->getClassOrBoundGenericClass();
assert(theClass && "only classes have metaclasses");
assert(concreteType->getClassOrBoundGenericClass()->isGenericContext());
auto entity =
LinkEntity::forSpecializedGenericSwiftMetaclassStub(concreteType);
auto DbgTy = DebugTypeInfo::getObjCClass(
theClass, ObjCClassPtrTy, getPointerSize(), getPointerAlignment());
auto addr = getAddrOfLLVMVariable(entity, forDefinition, DbgTy);
return addr;
}
/// Fetch the declaration of an Objective-C metadata update callback.
llvm::Function *
IRGenModule::getAddrOfObjCMetadataUpdateFunction(ClassDecl *classDecl,
ForDefinition_t forDefinition) {
assert(ObjCInterop);
LinkEntity entity = LinkEntity::forObjCMetadataUpdateFunction(classDecl);
auto found = GlobalFuncs.find(entity);
llvm::Function *entry = nullptr;
if (found != GlobalFuncs.end()) {
entry = found->second;
if (forDefinition) updateLinkageForDefinition(*this, entry, entity);
return entry;
}
// Class _Nullable callback(Class _Nonnull cls, void * _Nullable arg);
Signature signature(ObjCUpdateCallbackTy, llvm::AttributeList(), DefaultCC);
LinkInfo link = LinkInfo::get(*this, entity, forDefinition);
entry = createFunction(*this, link, signature);
GlobalFuncs.insert({entity, entry});
return entry;
}
/// Fetch the declaration of an Objective-C resilient class stub.
llvm::Constant *
IRGenModule::getAddrOfObjCResilientClassStub(ClassDecl *classDecl,
ForDefinition_t forDefinition,
TypeMetadataAddress addr) {
assert(ObjCInterop);
assert(getClassMetadataStrategy(classDecl) ==
ClassMetadataStrategy::Resilient);
LinkEntity entity = LinkEntity::forObjCResilientClassStub(classDecl, addr);
return getAddrOfLLVMVariable(entity, forDefinition, DebugTypeInfo());
}
llvm::IntegerType *IRGenModule::getTypeMetadataRequestParamTy() {
return SizeTy;
}
llvm::StructType *IRGenModule::getTypeMetadataResponseTy() {
return TypeMetadataResponseTy;
}
/// Fetch the type metadata access function for a non-generic type.
llvm::Function *
IRGenModule::getAddrOfTypeMetadataAccessFunction(CanType type,
ForDefinition_t forDefinition) {
assert(!type->hasArchetype() && !type->hasTypeParameter());
NominalTypeDecl *Nominal = type->getNominalOrBoundGenericNominal();
IRGen.noteUseOfTypeMetadata(Nominal);
LinkEntity entity = LinkEntity::forTypeMetadataAccessFunction(type);
auto found = GlobalFuncs.find(entity);
llvm::Function *entry = nullptr;
if (found != GlobalFuncs.end()) {
entry = found->second;
if (forDefinition) updateLinkageForDefinition(*this, entry, entity);
return entry;
}
llvm::Type *params[] = {getTypeMetadataRequestParamTy()}; // MetadataRequest
auto fnType =
llvm::FunctionType::get(getTypeMetadataResponseTy(), params, false);
Signature signature(fnType, llvm::AttributeList(), SwiftCC);
LinkInfo link = LinkInfo::get(*this, entity, forDefinition);
entry = createFunction(*this, link, signature);
GlobalFuncs.insert({entity, entry});
return entry;
}
/// Fetch the opaque type descriptor access function.
FunctionPointer IRGenModule::getAddrOfOpaqueTypeDescriptorAccessFunction(
OpaqueTypeDecl *decl, ForDefinition_t forDefinition, bool implementation) {
IRGen.noteUseOfOpaqueTypeDescriptor(decl);
LinkEntity entity =
implementation ? LinkEntity::forOpaqueTypeDescriptorAccessorImpl(decl)
: LinkEntity::forOpaqueTypeDescriptorAccessor(decl);
auto fnType = llvm::FunctionType::get(OpaqueTypeDescriptorPtrTy, {}, false);
Signature signature(fnType, llvm::AttributeList(), SwiftCC);
auto found = GlobalFuncs.find(entity);
llvm::Function *entry = nullptr;
if (found != GlobalFuncs.end()) {
entry = found->second;
if (forDefinition) updateLinkageForDefinition(*this, entry, entity);
return FunctionPointer::forDirect(FunctionPointer::Kind::Function, entry,
nullptr, signature);
}
LinkInfo link = LinkInfo::get(*this, entity, forDefinition);
entry = createFunction(*this, link, signature);
GlobalFuncs.insert({entity, entry});
return FunctionPointer::forDirect(FunctionPointer::Kind::Function, entry,
nullptr, signature);
}
/// Fetch the type metadata access function for the given generic type.
llvm::Function *
IRGenModule::getAddrOfGenericTypeMetadataAccessFunction(
NominalTypeDecl *nominal,
ArrayRef<llvm::Type *> genericArgs,
ForDefinition_t forDefinition) {
assert(nominal->isGenericContext());
assert(!genericArgs.empty() ||
nominal->getGenericSignature()->areAllParamsConcrete());
IRGen.noteUseOfTypeMetadata(nominal);
auto type = nominal->getDeclaredType()->getCanonicalType();
assert(type->hasUnboundGenericType());
LinkEntity entity = LinkEntity::forTypeMetadataAccessFunction(type);
auto found = GlobalFuncs.find(entity);
llvm::Function *entry = nullptr;
if (found != GlobalFuncs.end()) {
entry = found->second;
if (forDefinition) updateLinkageForDefinition(*this, entry, entity);
return entry;
}
// If we have more arguments than can be passed directly, all of the
// generic arguments are passed as an array.
llvm::Type *paramTypesArray[NumDirectGenericTypeMetadataAccessFunctionArgs+1];
paramTypesArray[0] = SizeTy; // MetadataRequest
size_t numParams = 1;
size_t numGenericArgs = genericArgs.size();
if (numGenericArgs > NumDirectGenericTypeMetadataAccessFunctionArgs) {
paramTypesArray[1] = Int8PtrPtrTy;
++numParams;
} else {
for (size_t i : indices(genericArgs))
paramTypesArray[i + 1] = genericArgs[i];
numParams += numGenericArgs;
}
auto paramTypes = llvm::ArrayRef(paramTypesArray, numParams);
auto fnType = llvm::FunctionType::get(TypeMetadataResponseTy,
paramTypes, false);
Signature signature(fnType, llvm::AttributeList(), SwiftCC);
LinkInfo link = LinkInfo::get(*this, entity, forDefinition);
entry = createFunction(*this, link, signature);
GlobalFuncs.insert({entity, entry});
return entry;
}
llvm::Function *
IRGenModule::getAddrOfCanonicalSpecializedGenericTypeMetadataAccessFunction(
CanType theType, ForDefinition_t forDefinition) {
assert(shouldPrespecializeGenericMetadata());
assert(!theType->hasUnboundGenericType());
auto *nominal = theType->getAnyNominal();
assert(nominal);
assert(nominal->isGenericContext());
IRGen.noteUseOfCanonicalSpecializedMetadataAccessor(theType);
LinkEntity entity =
LinkEntity::forPrespecializedTypeMetadataAccessFunction(theType);
auto found = GlobalFuncs.find(entity);
llvm::Function *entry = nullptr;
if (found != GlobalFuncs.end()) {
entry = found->second;
if (forDefinition) updateLinkageForDefinition(*this, entry, entity);
return entry;
}
llvm::Type *paramTypesArray[1];
paramTypesArray[0] = SizeTy; // MetadataRequest
auto paramTypes = llvm::ArrayRef(paramTypesArray, 1);
auto functionType =
llvm::FunctionType::get(TypeMetadataResponseTy, paramTypes, false);
Signature signature(functionType, llvm::AttributeList(), SwiftCC);
LinkInfo link = LinkInfo::get(*this, entity, forDefinition);
entry = createFunction(*this, link, signature);
GlobalFuncs.insert({entity, entry});
return entry;
}
/// Get or create a type metadata cache variable. These are an
/// implementation detail of type metadata access functions.
llvm::Constant *
IRGenModule::getAddrOfTypeMetadataLazyCacheVariable(CanType type) {
assert(!type->hasArchetype() && !type->hasTypeParameter());
LinkEntity entity = LinkEntity::forTypeMetadataLazyCacheVariable(type);
auto variable =
getAddrOfLLVMVariable(entity, ForDefinition, DebugTypeInfo());
// Zero-initialize if we're asking for a definition.
cast<llvm::GlobalVariable>(variable)->setInitializer(
llvm::ConstantPointerNull::get(TypeMetadataPtrTy));
return variable;
}
llvm::Constant *
IRGenModule::getAddrOfCanonicalPrespecializedGenericTypeCachingOnceToken(
NominalTypeDecl *decl) {
assert(decl->isGenericContext());
LinkEntity entity =
LinkEntity::forCanonicalPrespecializedGenericTypeCachingOnceToken(decl);
if (auto &entry = GlobalVars[entity]) {
return entry;
}
auto variable = getAddrOfLLVMVariable(entity, ForDefinition, DebugTypeInfo());
// Zero-initialize if we're asking for a definition.
cast<llvm::GlobalVariable>(variable)->setInitializer(
llvm::ConstantInt::get(OnceTy, 0));
return variable;
}
llvm::Constant *
IRGenModule::getAddrOfNoncanonicalSpecializedGenericTypeMetadataCacheVariable(CanType type) {
assert(!type->hasArchetype() && !type->hasTypeParameter());
LinkEntity entity = LinkEntity::forNoncanonicalSpecializedGenericTypeMetadataCacheVariable(type);
if (auto &entry = GlobalVars[entity]) {
return entry;
}
auto variable =
getAddrOfLLVMVariable(entity, ForDefinition, DebugTypeInfo());
cast<llvm::GlobalVariable>(variable)->setInitializer(
llvm::ConstantPointerNull::get(TypeMetadataPtrTy));
return variable;
}
/// Get or create a type metadata cache variable. These are an
/// implementation detail of type metadata access functions.
llvm::Constant *
IRGenModule::getAddrOfTypeMetadataDemanglingCacheVariable(CanType type,
ConstantInit definition) {
assert(!type->hasArchetype() && !type->hasTypeParameter());
LinkEntity entity = LinkEntity::forTypeMetadataDemanglingCacheVariable(type);
return getAddrOfLLVMVariable(entity, definition, DebugTypeInfo());
}
llvm::Constant *
IRGenModule::getAddrOfTypeMetadataSingletonInitializationCache(
NominalTypeDecl *D,
ForDefinition_t forDefinition) {
auto entity = LinkEntity::forTypeMetadataSingletonInitializationCache(D);
auto variable =
getAddrOfLLVMVariable(entity, forDefinition, DebugTypeInfo());
// Zero-initialize if we're asking for a definition.
if (forDefinition) {
auto globalVar = cast<llvm::GlobalVariable>(variable);
globalVar->setInitializer(
llvm::Constant::getNullValue(globalVar->getValueType()));
}
return variable;
}
llvm::GlobalValue *IRGenModule::defineAlias(LinkEntity entity,
llvm::Constant *definition,
llvm::Type *typeOfValue) {
// Check for an existing forward declaration of the alias.
auto &entry = GlobalVars[entity];
llvm::GlobalValue *existingVal = nullptr;
if (entry) {
existingVal = cast<llvm::GlobalValue>(entry);
// Clear the existing value's name so we can steal it.
existingVal->setName("");
}
LinkInfo link = LinkInfo::get(*this, entity, ForDefinition);
auto *ptrTy = cast<llvm::PointerType>(definition->getType());
auto *alias = llvm::GlobalAlias::create(typeOfValue, ptrTy->getAddressSpace(),
link.getLinkage(), link.getName(),
definition, &Module);
ApplyIRLinkage({link.getLinkage(), link.getVisibility(), link.getDLLStorage()})
.to(alias);
markGlobalAsUsedBasedOnLinkage(*this, link, alias);
// Replace an existing external declaration for the address point.
if (entry) {
auto existingVal = cast<llvm::GlobalValue>(entry);
for (auto iterator = std::begin(LLVMUsed); iterator < std::end(LLVMUsed); ++iterator) {
llvm::Value *thisValue = *iterator;
if (thisValue == existingVal) {
LLVMUsed.erase(iterator);
}
}
for (auto iterator = std::begin(LLVMCompilerUsed); iterator < std::end(LLVMCompilerUsed); ++iterator) {
llvm::Value *thisValue = *iterator;
if (thisValue == existingVal) {
LLVMCompilerUsed.erase(iterator);
}
}
// FIXME: MC breaks when emitting alias references on some platforms
// (rdar://problem/22450593 ). Work around this by referring to the aliasee
// instead.
llvm::Constant *aliasCast = alias->getAliasee();
aliasCast = llvm::ConstantExpr::getBitCast(aliasCast,
entry->getType());
existingVal->replaceAllUsesWith(aliasCast);
existingVal->eraseFromParent();
}
entry = alias;
return alias;
}
/// Define the metadata for a type.
///
/// Some type metadata has information before the address point that the
/// public symbol for the metadata references. This function will rewrite any
/// existing external declaration to the address point as an alias into the
/// full metadata object.
llvm::GlobalValue *IRGenModule::defineTypeMetadata(
CanType concreteType, bool isPattern, bool isConstant,
ConstantInitFuture init, llvm::StringRef section,
SmallVector<std::pair<Size, SILDeclRef>, 8> vtableEntries) {
assert(init);
auto concreteTypeDecl = concreteType->getAnyGeneric();
auto isPrespecialized = concreteTypeDecl &&
concreteTypeDecl->isGenericContext();
bool isObjCImpl = concreteTypeDecl &&
concreteTypeDecl->getObjCImplementationDecl();
if (isPattern) {
assert(isConstant && "Type metadata patterns must be constant");
auto addr = getAddrOfTypeMetadataPattern(concreteType->getAnyNominal(),
init, section);
return cast<llvm::GlobalValue>(addr);
}
auto entity =
(isPrespecialized &&
!irgen::isCanonicalInitializableTypeMetadataStaticallyAddressable(
*this, concreteType))
? LinkEntity::forNoncanonicalSpecializedGenericTypeMetadata(
concreteType)
: (isObjCImpl
? LinkEntity::forObjCClass(
concreteType->getClassOrBoundGenericClass())
: LinkEntity::forTypeMetadata(
concreteType, TypeMetadataAddress::FullMetadata));
if (Context.LangOpts.hasFeature(Feature::Embedded)) {
entity = LinkEntity::forTypeMetadata(concreteType,
TypeMetadataAddress::AddressPoint);
}
auto DbgTy = DebugTypeInfo::getGlobalMetadata(
MetatypeType::get(concreteType),
entity.getDefaultDeclarationType(*this)->getPointerTo(), Size(0),
Alignment(1));
// Define the variable.
llvm::GlobalVariable *var = cast<llvm::GlobalVariable>(
getAddrOfLLVMVariable(entity, init, DbgTy));
var->setConstant(isConstant);
if (!section.empty())
var->setSection(section);
if (getOptions().VirtualFunctionElimination) {
if (auto classDecl = concreteType->getClassOrBoundGenericClass()) {
addVTableTypeMetadata(classDecl, var, vtableEntries);
}
}
LinkInfo link = LinkInfo::get(*this, entity, ForDefinition);
markGlobalAsUsedBasedOnLinkage(*this, link, var);
if (Context.LangOpts.hasFeature(Feature::Embedded)) {
return var;
}
/// For concrete metadata, we want to use the initializer on the
/// "full metadata", and define the "direct" address point as an alias.
unsigned adjustmentIndex = MetadataAdjustmentIndex::ValueType;
if (auto nominal = concreteType->getAnyNominal()) {
// Keep type metadata around for all types (except @_objcImplementation,
// since we're using ObjC metadata for that).
if (!isObjCImpl)
addRuntimeResolvableType(nominal);
// Don't define the alias for foreign type metadata, prespecialized
// generic metadata, or @_objcImplementation classes, since they're not ABI.
if (requiresForeignTypeMetadata(nominal) || isPrespecialized || isObjCImpl)
return var;
// Native Swift class metadata has a destructor before the address point.
if (isa<ClassDecl>(nominal)) {
adjustmentIndex = MetadataAdjustmentIndex::Class;
}
if (concreteType->is<TupleType>()) {
adjustmentIndex = MetadataAdjustmentIndex::NoTypeLayoutString;
}
}
llvm::Constant *indices[] = {
llvm::ConstantInt::get(Int32Ty, 0),
llvm::ConstantInt::get(Int32Ty, adjustmentIndex)};
auto addr = llvm::ConstantExpr::getInBoundsGetElementPtr(var->getValueType(),
var, indices);
addr = llvm::ConstantExpr::getBitCast(addr, TypeMetadataPtrTy);
// For concrete metadata, declare the alias to its address point.
auto directEntity = LinkEntity::forTypeMetadata(
concreteType, TypeMetadataAddress::AddressPoint);
return defineAlias(directEntity, addr, TypeMetadataStructTy);
}
/// Fetch the declaration of the (possibly uninitialized) metadata for a type.
llvm::Constant *
IRGenModule::getAddrOfTypeMetadata(CanType concreteType,
TypeMetadataCanonicality canonicality) {
return getAddrOfTypeMetadata(concreteType, SymbolReferenceKind::Absolute,
canonicality)
.getDirectValue();
}
ConstantReference
IRGenModule::getAddrOfTypeMetadata(CanType concreteType,
SymbolReferenceKind refKind,
TypeMetadataCanonicality canonicality) {
assert(!isa<UnboundGenericType>(concreteType));
auto nominal = concreteType->getAnyNominal();
bool foreign = nominal && requiresForeignTypeMetadata(nominal);
// Foreign classes and prespecialized generic types do not use an alias into
// the full metadata and therefore require a GEP.
bool fullMetadata =
!Context.LangOpts.hasFeature(Feature::Embedded) &&
(foreign || (concreteType->getAnyGeneric() &&
concreteType->getAnyGeneric()->isGenericContext()));
llvm::Type *defaultVarTy;
unsigned adjustmentIndex;
if (concreteType->isAny() || concreteType->isAnyObject() || concreteType->isVoid() || concreteType->is<TupleType>() || concreteType->is<BuiltinType>()) {
defaultVarTy = FullExistentialTypeMetadataStructTy;
adjustmentIndex = MetadataAdjustmentIndex::NoTypeLayoutString;
} else if (fullMetadata) {
defaultVarTy = FullTypeMetadataStructTy;
if (concreteType->getClassOrBoundGenericClass() && !foreign) {
adjustmentIndex = MetadataAdjustmentIndex::Class;
} else {
adjustmentIndex = MetadataAdjustmentIndex::ValueType;
}
} else if (nominal) {
// The symbol for native non-generic nominal type metadata is generated at
// the aliased address point (see defineTypeMetadata() above).
if (nominal->getObjCImplementationDecl()) {
defaultVarTy = ObjCClassStructTy;
} else {
assert(!nominal->hasClangNode());
defaultVarTy = TypeMetadataStructTy;
}
adjustmentIndex = 0;
} else {
// FIXME: Non-nominal metadata provided by the C++ runtime is exported
// with the address of the start of the full metadata object, since
// Clang doesn't provide an easy way to emit symbols aliasing into the
// middle of an object.
defaultVarTy = FullTypeMetadataStructTy;
adjustmentIndex = MetadataAdjustmentIndex::ValueType;
}
// If this is a use, and the type metadata is emitted lazily,
// trigger lazy emission of the metadata.
if (NominalTypeDecl *nominal = concreteType->getAnyNominal()) {
IRGen.noteUseOfTypeMetadata(nominal);
if (Context.LangOpts.hasFeature(Feature::Embedded)) {
if (auto *classDecl = dyn_cast<ClassDecl>(nominal)) {
if (classDecl->isGenericContext()) {
IRGen.noteUseOfSpecializedClassMetadata(concreteType);
} else {
IRGen.noteUseOfClassMetadata(concreteType);
}
}
}
}
if (shouldPrespecializeGenericMetadata()) {
if (auto nominal = concreteType->getAnyNominal()) {
if (nominal->isGenericContext()) {
IRGen.noteUseOfSpecializedGenericTypeMetadata(*this, concreteType,
canonicality);
}
}
}
std::optional<LinkEntity> entity;
DebugTypeInfo DbgTy;
switch (canonicality) {
case TypeMetadataCanonicality::Canonical: {
auto classDecl = concreteType->getClassOrBoundGenericClass();
if (classDecl && classDecl->getObjCImplementationDecl()) {
entity = LinkEntity::forObjCClass(classDecl);
} else {
entity = LinkEntity::forTypeMetadata(
concreteType, fullMetadata ? TypeMetadataAddress::FullMetadata
: TypeMetadataAddress::AddressPoint);
}
break;
}
case TypeMetadataCanonicality::Noncanonical:
entity =
LinkEntity::forNoncanonicalSpecializedGenericTypeMetadata(concreteType);
break;
}
DbgTy = DebugTypeInfo::getGlobalMetadata(MetatypeType::get(concreteType),
defaultVarTy->getPointerTo(),
Size(0), Alignment(1));
ConstantReference addr;
llvm::Type *typeOfValue = nullptr;
if (fullMetadata && !foreign) {
addr = getAddrOfLLVMVariable(*entity, ConstantInit(), DbgTy, refKind,
/*overrideDeclType=*/nullptr);
typeOfValue = entity->getDefaultDeclarationType(*this);
} else {
addr = getAddrOfLLVMVariable(*entity, ConstantInit(), DbgTy, refKind,
/*overrideDeclType=*/defaultVarTy);
typeOfValue = defaultVarTy;
}
if (auto *GV = dyn_cast<llvm::GlobalVariable>(addr.getValue()))
if (GV->isDeclaration())
GV->setComdat(nullptr);
// FIXME: MC breaks when emitting alias references on some platforms
// (rdar://problem/22450593 ). Work around this by referring to the aliasee
// instead.
if (auto alias = dyn_cast<llvm::GlobalAlias>(addr.getValue())) {
addr = ConstantReference(alias->getAliasee(), addr.isIndirect());
}
// Adjust if necessary.
if (adjustmentIndex) {
llvm::Constant *indices[] = {
llvm::ConstantInt::get(Int32Ty, 0),
llvm::ConstantInt::get(Int32Ty, adjustmentIndex)
};
addr = ConstantReference(llvm::ConstantExpr::getInBoundsGetElementPtr(
typeOfValue, addr.getValue(), indices),
addr.isIndirect());
}
return addr;
}
llvm::Constant *
IRGenModule::getAddrOfTypeMetadataPattern(NominalTypeDecl *D) {
return getAddrOfTypeMetadataPattern(D, ConstantInit(), "");
}
llvm::Constant *
IRGenModule::getAddrOfTypeMetadataPattern(NominalTypeDecl *D,
ConstantInit init,
StringRef section) {
if (!init)
IRGen.noteUseOfTypeMetadata(D);
LinkEntity entity = LinkEntity::forTypeMetadataPattern(D);
auto addr = getAddrOfLLVMVariable(entity, init, DebugTypeInfo());
if (init) {
auto var = cast<llvm::GlobalVariable>(addr);
var->setConstant(true);
if (!section.empty())
var->setSection(section);
// Keep type metadata around for all types.
addRuntimeResolvableType(D);
}
return addr;
}
/// Returns the address of a class metadata base offset.
llvm::Constant *
IRGenModule::getAddrOfClassMetadataBounds(ClassDecl *D,
ForDefinition_t forDefinition) {
LinkEntity entity = LinkEntity::forClassMetadataBaseOffset(D);
return getAddrOfLLVMVariable(entity, forDefinition, DebugTypeInfo());
}
/// Return the address of a generic type's metadata instantiation cache.
llvm::Constant *
IRGenModule::getAddrOfTypeMetadataInstantiationCache(NominalTypeDecl *D,
ForDefinition_t forDefinition) {
auto entity = LinkEntity::forTypeMetadataInstantiationCache(D);
return getAddrOfLLVMVariable(entity, forDefinition, DebugTypeInfo());
}
llvm::Function *
IRGenModule::getAddrOfTypeMetadataInstantiationFunction(NominalTypeDecl *D,
ForDefinition_t forDefinition) {
LinkEntity entity = LinkEntity::forTypeMetadataInstantiationFunction(D);
auto found = GlobalFuncs.find(entity);
llvm::Function *entry = nullptr;
if (found != GlobalFuncs.end()) {
entry = found->second;
if (forDefinition) updateLinkageForDefinition(*this, entry, entity);
return entry;
}
// This function is used in two cases -- allocating generic type metadata,
// and relocating non-generic resilient class metadata.
llvm::FunctionType *fnType;
if (D->isGenericContext()) {
// MetadataInstantiator in ABI/Metadata.h
llvm::Type *argTys[] = {
/// Type descriptor.
TypeContextDescriptorPtrTy,
/// Generic arguments.
Int8PtrPtrTy,
/// Generic metadata pattern.
Int8PtrTy
};
fnType = llvm::FunctionType::get(TypeMetadataPtrTy, argTys,
/*isVarArg*/ false);
} else {
assert(isa<ClassDecl>(D));
// MetadataRelocator in ABI/Metadata.h
llvm::Type *argTys[] = {
/// Type descriptor.
TypeContextDescriptorPtrTy,
/// Resilient metadata pattern.
Int8PtrTy
};
fnType = llvm::FunctionType::get(TypeMetadataPtrTy, argTys,
/*isVarArg*/ false);
}
Signature signature(fnType, llvm::AttributeList(), DefaultCC);
LinkInfo link = LinkInfo::get(*this, entity, forDefinition);
entry = createFunction(*this, link, signature);
GlobalFuncs.insert({entity, entry});
return entry;
}
llvm::Function *
IRGenModule::getAddrOfTypeMetadataCompletionFunction(NominalTypeDecl *D,
ForDefinition_t forDefinition) {
LinkEntity entity = LinkEntity::forTypeMetadataCompletionFunction(D);
auto found = GlobalFuncs.find(entity);
llvm::Function *entry = nullptr;
if (found != GlobalFuncs.end()) {
entry = found->second;
if (forDefinition) updateLinkageForDefinition(*this, entry, entity);
return entry;
}
llvm::Type *argTys[] = {
/// Type metadata.
TypeMetadataPtrTy,
/// Metadata completion context.
Int8PtrTy,
/// Generic metadata pattern.
Int8PtrPtrTy
};
auto fnType = llvm::FunctionType::get(TypeMetadataResponseTy,
argTys, /*isVarArg*/ false);
Signature signature(fnType, llvm::AttributeList(), SwiftCC);
LinkInfo link = LinkInfo::get(*this, entity, forDefinition);
entry = createFunction(*this, link, signature);
GlobalFuncs.insert({entity, entry});
return entry;
}
/// Return the address of a nominal type descriptor.
llvm::Constant *IRGenModule::getAddrOfTypeContextDescriptor(NominalTypeDecl *D,
RequireMetadata_t requireMetadata,
ConstantInit definition) {
IRGen.noteUseOfTypeContextDescriptor(D, requireMetadata);
auto entity = LinkEntity::forNominalTypeDescriptor(D);
return getAddrOfLLVMVariable(entity,
definition,
DebugTypeInfo());
}
llvm::Constant *IRGenModule::getAddrOfOpaqueTypeDescriptor(
OpaqueTypeDecl *opaqueType,
ConstantInit definition) {
IRGen.noteUseOfOpaqueTypeDescriptor(opaqueType);
auto entity = LinkEntity::forOpaqueTypeDescriptor(opaqueType);
return getAddrOfLLVMVariable(entity,
definition,
DebugTypeInfo());
}
llvm::Constant *IRGenModule::
getAddrOfReflectionBuiltinDescriptor(CanType type,
ConstantInit definition) {
auto entity = LinkEntity::forReflectionBuiltinDescriptor(type);
return getAddrOfLLVMVariable(entity,
definition,
DebugTypeInfo());
}
llvm::Constant *IRGenModule::
getAddrOfReflectionFieldDescriptor(CanType type,
ConstantInit definition) {
auto entity = LinkEntity::forReflectionFieldDescriptor(type);
return getAddrOfLLVMVariable(entity,
definition,
DebugTypeInfo());
}
llvm::Constant *IRGenModule::
getAddrOfReflectionAssociatedTypeDescriptor(const ProtocolConformance *c,
ConstantInit definition) {
auto entity = LinkEntity::forReflectionAssociatedTypeDescriptor(c);
return getAddrOfLLVMVariable(entity,
definition,
DebugTypeInfo());
}
/// Return the address of a property descriptor.
llvm::Constant *IRGenModule::getAddrOfPropertyDescriptor(AbstractStorageDecl *D,
ConstantInit definition) {
auto entity = LinkEntity::forPropertyDescriptor(D);
return getAddrOfLLVMVariable(entity,
definition,
DebugTypeInfo());
}
llvm::Constant *IRGenModule::getAddrOfProtocolDescriptor(ProtocolDecl *D,
ConstantInit definition) {
if (D->isObjC()) {
assert(!definition &&
"cannot define an @objc protocol descriptor this way");
return getAddrOfObjCProtocolRecord(D, NotForDefinition);
}
auto entity = LinkEntity::forProtocolDescriptor(D);
return getAddrOfLLVMVariable(entity, definition,
DebugTypeInfo());
}
llvm::Constant *IRGenModule::getAddrOfProtocolRequirementsBaseDescriptor(
ProtocolDecl *proto) {
auto entity = LinkEntity::forProtocolRequirementsBaseDescriptor(proto);
return getAddrOfLLVMVariable(entity, ConstantInit(),
DebugTypeInfo());
}
llvm::GlobalValue *IRGenModule::defineProtocolRequirementsBaseDescriptor(
ProtocolDecl *proto,
llvm::Constant *definition) {
auto entity = LinkEntity::forProtocolRequirementsBaseDescriptor(proto);
return defineAlias(entity, definition,
entity.getDefaultDeclarationType(*this));
}
llvm::Constant *IRGenModule::getAddrOfAssociatedTypeDescriptor(
AssociatedTypeDecl *assocType) {
auto entity = LinkEntity::forAssociatedTypeDescriptor(assocType);
return getAddrOfLLVMVariable(entity, ConstantInit(),
DebugTypeInfo());
}
llvm::GlobalValue *IRGenModule::defineAssociatedTypeDescriptor(
AssociatedTypeDecl *assocType,
llvm::Constant *definition) {
auto entity = LinkEntity::forAssociatedTypeDescriptor(assocType);
return defineAlias(entity, definition,
entity.getDefaultDeclarationType(*this));
}
llvm::Constant *IRGenModule::getAddrOfAssociatedConformanceDescriptor(
AssociatedConformance conformance) {
auto entity = LinkEntity::forAssociatedConformanceDescriptor(conformance);
return getAddrOfLLVMVariable(entity, ConstantInit(), DebugTypeInfo());
}
llvm::GlobalValue *IRGenModule::defineAssociatedConformanceDescriptor(
AssociatedConformance conformance,
llvm::Constant *definition) {
auto entity = LinkEntity::forAssociatedConformanceDescriptor(conformance);
return defineAlias(entity, definition,
entity.getDefaultDeclarationType(*this));
}
llvm::Constant *IRGenModule::getAddrOfBaseConformanceDescriptor(
BaseConformance conformance) {
auto entity = LinkEntity::forBaseConformanceDescriptor(conformance);
return getAddrOfLLVMVariable(entity, ConstantInit(), DebugTypeInfo());
}
llvm::GlobalValue *IRGenModule::defineBaseConformanceDescriptor(
BaseConformance conformance,
llvm::Constant *definition) {
auto entity = LinkEntity::forBaseConformanceDescriptor(conformance);
return defineAlias(entity, definition,
entity.getDefaultDeclarationType(*this));
}
llvm::Constant *IRGenModule::getAddrOfProtocolConformanceDescriptor(
const RootProtocolConformance *conformance,
ConstantInit definition) {
IRGen.addLazyWitnessTable(conformance);
auto entity = LinkEntity::forProtocolConformanceDescriptor(conformance);
return getAddrOfLLVMVariable(entity, definition,
DebugTypeInfo());
}
/// Fetch the declaration of the ivar initializer for the given class.
std::optional<llvm::Function *>
IRGenModule::getAddrOfIVarInitDestroy(ClassDecl *cd, bool isDestroyer,
bool isForeign,
ForDefinition_t forDefinition) {
auto silRef = SILDeclRef(cd,
isDestroyer
? SILDeclRef::Kind::IVarDestroyer
: SILDeclRef::Kind::IVarInitializer)
.asForeign(isForeign);
// Find the SILFunction for the ivar initializer or destroyer.
if (auto silFn = getSILModule().lookUpFunction(silRef)) {
return getAddrOfSILFunction(silFn, forDefinition);
}
return std::nullopt;
}
/// Returns the address of a value-witness function.
llvm::Function *IRGenModule::getAddrOfValueWitness(CanType abstractType,
ValueWitness index,
ForDefinition_t forDefinition) {
LinkEntity entity = LinkEntity::forValueWitness(abstractType, index);
auto found = GlobalFuncs.find(entity);
llvm::Function *entry = nullptr;
if (found != GlobalFuncs.end()) {
entry = found->second;
if (forDefinition) updateLinkageForDefinition(*this, entry, entity);
return entry;
}
auto signature = getValueWitnessSignature(index);
LinkInfo link = LinkInfo::get(*this, entity, forDefinition);
entry = createFunction(*this, link, signature);
GlobalFuncs.insert({entity, entry});
return entry;
}
/// Returns the address of a value-witness table. If a definition
/// type is provided, the table is created with that type; the return
/// value will be an llvm::GlobalValue. Otherwise, the result will
/// have type WitnessTablePtrTy.
llvm::Constant *
IRGenModule::getAddrOfValueWitnessTable(CanType concreteType,
ConstantInit definition) {
LinkEntity entity = LinkEntity::forValueWitnessTable(concreteType);
return getAddrOfLLVMVariable(entity, definition, DebugTypeInfo());
}
static Address getAddrOfSimpleVariable(IRGenModule &IGM,
llvm::DenseMap<LinkEntity, llvm::Constant*> &cache,
LinkEntity entity,
ForDefinition_t forDefinition) {
auto alignment = entity.getAlignment(IGM);
auto type = entity.getDefaultDeclarationType(IGM);
// Check whether it's already cached.
llvm::Constant *&entry = cache[entity];
if (entry) {
auto existing = cast<llvm::GlobalVariable>(entry);
assert(alignment == Alignment(existing->getAlignment()));
if (forDefinition) updateLinkageForDefinition(IGM, existing, entity);
return Address(entry, type, alignment);
}
// Otherwise, we need to create it.
LinkInfo link = LinkInfo::get(IGM, entity, forDefinition);
auto addr = createVariable(IGM, link, type, alignment);
entry = addr;
return Address(addr, type, alignment);
}
/// getAddrOfFieldOffset - Get the address of the global variable
/// which contains an offset to apply to either an object (if direct)
/// or a metadata object in order to find an offset to apply to an
/// object (if indirect).
///
/// The result is always a GlobalValue.
Address IRGenModule::getAddrOfFieldOffset(VarDecl *var,
ForDefinition_t forDefinition) {
assert(var->isAvailableDuringLowering());
LinkEntity entity = LinkEntity::forFieldOffset(var);
return getAddrOfSimpleVariable(*this, GlobalVars, entity,
forDefinition);
}
Address IRGenModule::getAddrOfEnumCase(EnumElementDecl *Case,
ForDefinition_t forDefinition) {
assert(Case->isAvailableDuringLowering());
LinkEntity entity = LinkEntity::forEnumCase(Case);
auto addr = getAddrOfSimpleVariable(*this, GlobalVars, entity, forDefinition);
auto *global = cast<llvm::GlobalVariable>(addr.getAddress());
global->setConstant(true);
return addr;
}
void IRGenModule::emitNestedTypeDecls(DeclRange members) {
for (Decl *member : members) {
if (!member->isAvailableDuringLowering())
continue;
member->visitAuxiliaryDecls([&](Decl *decl) {
emitNestedTypeDecls({decl, nullptr});
});
switch (member->getKind()) {
case DeclKind::Import:
case DeclKind::TopLevelCode:
case DeclKind::Extension:
case DeclKind::InfixOperator:
case DeclKind::PrefixOperator:
case DeclKind::PostfixOperator:
case DeclKind::Param:
case DeclKind::Module:
case DeclKind::PrecedenceGroup:
llvm_unreachable("decl not allowed in type context");
case DeclKind::BuiltinTuple:
llvm_unreachable("BuiltinTupleType made it to IRGen");
case DeclKind::Missing:
llvm_unreachable("missing decl in IRGen");
case DeclKind::IfConfig:
case DeclKind::PoundDiagnostic:
case DeclKind::Macro:
continue;
case DeclKind::Func:
case DeclKind::Var:
case DeclKind::Subscript:
// Handled in SIL.
continue;
case DeclKind::PatternBinding:
case DeclKind::Accessor:
case DeclKind::Constructor:
case DeclKind::Destructor:
case DeclKind::EnumCase:
case DeclKind::EnumElement:
case DeclKind::MissingMember:
// Skip non-type members.
continue;
case DeclKind::AssociatedType:
case DeclKind::GenericTypeParam:
// Do nothing.
continue;
case DeclKind::TypeAlias:
case DeclKind::OpaqueType:
// Do nothing.
continue;
case DeclKind::Enum:
emitEnumDecl(cast<EnumDecl>(member));
continue;
case DeclKind::Struct:
emitStructDecl(cast<StructDecl>(member));
continue;
case DeclKind::Class:
emitClassDecl(cast<ClassDecl>(member));
continue;
case DeclKind::Protocol:
emitProtocolDecl(cast<ProtocolDecl>(member));
continue;
case DeclKind::MacroExpansion:
// Expansion already visited as auxiliary decls.
continue;
}
}
}
static bool shouldEmitCategory(IRGenModule &IGM, ExtensionDecl *ext) {
if (ext->isObjCImplementation()) {
assert(ext->getCategoryNameForObjCImplementation() != Identifier());
return true;
}
for (auto conformance : ext->getLocalConformances()) {
if (conformance->getProtocol()->isObjC())
return true;
}
for (auto member : ext->getAllMembers()) {
if (auto func = dyn_cast<FuncDecl>(member)) {
if (requiresObjCMethodDescriptor(func))
return true;
} else if (auto constructor = dyn_cast<ConstructorDecl>(member)) {
if (requiresObjCMethodDescriptor(constructor))
return true;
} else if (auto var = dyn_cast<VarDecl>(member)) {
if (requiresObjCPropertyDescriptor(IGM, var))
return true;
} else if (auto subscript = dyn_cast<SubscriptDecl>(member)) {
if (requiresObjCSubscriptDescriptor(IGM, subscript))
return true;
}
}
return false;
}
void IRGenModule::emitExtension(ExtensionDecl *ext) {
emitNestedTypeDecls(ext->getMembers());
if (Context.LangOpts.hasFeature(Feature::Embedded)) {
return;
}
addLazyConformances(ext);
// Generate a category if the extension either introduces a
// conformance to an ObjC protocol or introduces a method
// that requires an Objective-C entry point.
ClassDecl *origClass = ext->getSelfClassDecl();
if (!origClass)
return;
if (ext->isObjCImplementation()
&& ext->getCategoryNameForObjCImplementation() == Identifier()) {
// This is the @_objcImplementation for the class--generate its class
// metadata.
emitClassDecl(origClass);
} else if (shouldEmitCategory(*this, ext)) {
assert(origClass && !origClass->isForeign() &&
"foreign types cannot have categories emitted");
llvm::Constant *category = emitCategoryData(*this, ext);
category = llvm::ConstantExpr::getBitCast(category, Int8PtrTy);
auto *theClass = ext->getSelfClassDecl();
// Categories on class stubs are added to a separate list.
if (theClass->checkAncestry(AncestryFlags::ResilientOther))
ObjCCategoriesOnStubs.push_back(category);
else
ObjCCategories.push_back(category);
ObjCCategoryDecls.push_back(ext);
}
}
/// Create an allocation on the stack.
Address IRGenFunction::createAlloca(llvm::Type *type,
Alignment alignment,
const llvm::Twine &name) {
llvm::AllocaInst *alloca =
new llvm::AllocaInst(type, IGM.DataLayout.getAllocaAddrSpace(), name,
AllocaIP);
alloca->setAlignment(llvm::MaybeAlign(alignment.getValue()).valueOrOne());
return Address(alloca, type, alignment);
}
/// Create an allocation of an array on the stack.
Address IRGenFunction::createAlloca(llvm::Type *type,
llvm::Value *ArraySize,
Alignment alignment,
const llvm::Twine &name) {
llvm::AllocaInst *alloca = new llvm::AllocaInst(
type, IGM.DataLayout.getAllocaAddrSpace(), ArraySize,
llvm::MaybeAlign(alignment.getValue()).valueOrOne(), name, AllocaIP);
return Address(alloca, type, alignment);
}
/// Get or create a global string constant.
///
/// \returns an i8* with a null terminator; note that embedded nulls
/// are okay
///
/// FIXME: willBeRelativelyAddressed is only needed to work around an ld64 bug
/// resolving relative references to coalesceable symbols.
/// It should be removed when fixed. rdar://problem/22674524
llvm::Constant *IRGenModule::getAddrOfGlobalString(StringRef data,
bool willBeRelativelyAddressed,
bool useOSLogSection) {
useOSLogSection = useOSLogSection &&
TargetInfo.OutputObjectFormat == llvm::Triple::MachO;
// Check whether this string already exists.
auto &entry = useOSLogSection ? GlobalOSLogStrings[data] :
GlobalStrings[data];
if (entry.second) {
// FIXME: Clear unnamed_addr if the global will be relative referenced
// to work around an ld64 bug. rdar://problem/22674524
if (willBeRelativelyAddressed)
entry.first->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::None);
return entry.second;
}
SmallString<64> name;
(llvm::Twine(".str.") + llvm::Twine(data.size()) + "." + data).toVector(name);
// \0 is not allowed in variable names. Rewrite any \0s into _s and append
// information about their original locations so the name remains unique.
for (size_t i = name.find('\0');
i != StringRef::npos;
i = name.find('\0', i)) {
name[i] = '_';
(llvm::Twine(".nul") + llvm::Twine(i)).toVector(name);
}
auto sectionName =
useOSLogSection ? "__TEXT,__oslogstring,cstring_literals" : "";
entry = createStringConstant(data, willBeRelativelyAddressed,
sectionName, name);
return entry.second;
}
/// Get or create a global UTF-16 string constant.
///
/// \returns an i16* with a null terminator; note that embedded nulls
/// are okay
llvm::Constant *IRGenModule::getAddrOfGlobalUTF16String(StringRef utf8) {
// Check whether this string already exists.
auto &entry = GlobalUTF16Strings[utf8];
if (entry) return entry;
// If not, first transcode it to UTF16.
SmallVector<llvm::UTF16, 128> buffer(utf8.size() + 1); // +1 for ending nulls.
const llvm::UTF8 *fromPtr = (const llvm::UTF8 *) utf8.data();
llvm::UTF16 *toPtr = &buffer[0];
(void) ConvertUTF8toUTF16(&fromPtr, fromPtr + utf8.size(),
&toPtr, toPtr + utf8.size(),
llvm::strictConversion);
// The length of the transcoded string in UTF-8 code points.
size_t utf16Length = toPtr - &buffer[0];
// Null-terminate the UTF-16 string.
*toPtr = 0;
ArrayRef<llvm::UTF16> utf16(&buffer[0], utf16Length + 1);
auto init = llvm::ConstantDataArray::get(getLLVMContext(), utf16);
auto global = new llvm::GlobalVariable(
Module, init->getType(), true, llvm::GlobalValue::PrivateLinkage, init,
".str" /* match how Clang creates strings */);
global->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
// Drill down to make an i16*.
auto zero = llvm::ConstantInt::get(SizeTy, 0);
llvm::Constant *indices[] = { zero, zero };
auto address = llvm::ConstantExpr::getInBoundsGetElementPtr(
global->getValueType(), global, indices);
// Cache and return.
entry = address;
return address;
}
/// Can not treat a treat the layout of a class as resilient if the current
/// class is defined in an external module and
/// not publicly accessible (e.g private or internal).
/// This would normally not happen except if we compile theClass's module with
/// enable-testing.
/// Do we have to use resilient access patterns when working with this
/// declaration?
///
/// IRGen is primarily concerned with resilient handling of the following:
/// - For structs, a struct's size might change
/// - For enums, new cases can be added
/// - For classes, the superclass might change the size or number
/// of stored properties
bool IRGenModule::isResilient(NominalTypeDecl *D,
ResilienceExpansion expansion,
ClassDecl *asViewedFromRootClass) {
assert(!asViewedFromRootClass || isa<ClassDecl>(D));
// Ignore resilient protocols if requested.
if (isa<ProtocolDecl>(D) && IRGen.Opts.UseFragileResilientProtocolWitnesses) {
return false;
}
if (D->getModuleContext()->getBypassResilience())
return false;
if (expansion == ResilienceExpansion::Maximal &&
Types.getLoweringMode() == TypeConverter::Mode::CompletelyFragile) {
return false;
}
return D->isResilient(getSwiftModule(), expansion);
}
/// Do we have to use resilient access patterns when working with this
/// class?
///
/// For classes, this means that virtual method calls use dispatch thunks
/// rather than accessing metadata members directly.
bool IRGenModule::hasResilientMetadata(ClassDecl *D,
ResilienceExpansion expansion,
ClassDecl *asViewedFromRootClass) {
if (expansion == ResilienceExpansion::Maximal &&
Types.getLoweringMode() == TypeConverter::Mode::CompletelyFragile) {
return false;
}
return D->hasResilientMetadata(getSwiftModule(), expansion);
}
// The most general resilience expansion where the given declaration is visible.
ResilienceExpansion
IRGenModule::getResilienceExpansionForAccess(NominalTypeDecl *decl) {
if (decl->getModuleContext() == getSwiftModule() &&
decl->getEffectiveAccess() < AccessLevel::Package)
return ResilienceExpansion::Maximal;
return ResilienceExpansion::Minimal;
}
// The most general resilience expansion which has knowledge of the declaration's
// layout. Calling isResilient() with this scope will always return false.
ResilienceExpansion
IRGenModule::getResilienceExpansionForLayout(NominalTypeDecl *decl) {
if (Types.getLoweringMode() == TypeConverter::Mode::CompletelyFragile)
return ResilienceExpansion::Minimal;
if (isResilient(decl, ResilienceExpansion::Minimal))
return ResilienceExpansion::Maximal;
return getResilienceExpansionForAccess(decl);
}
// The most general resilience expansion which has knowledge of the global
// variable's layout.
ResilienceExpansion
IRGenModule::getResilienceExpansionForLayout(SILGlobalVariable *global) {
if (hasPublicVisibility(global->getLinkage()))
return ResilienceExpansion::Minimal;
return ResilienceExpansion::Maximal;
}
llvm::Function *
IRGenModule::getAddrOfGenericWitnessTableInstantiationFunction(
const NormalProtocolConformance *conf) {
auto forDefinition = ForDefinition;
LinkEntity entity =
LinkEntity::forGenericProtocolWitnessTableInstantiationFunction(conf);
auto found = GlobalFuncs.find(entity);
llvm::Function *entry = nullptr;
if (found != GlobalFuncs.end()) {
entry = found->second;
if (forDefinition) updateLinkageForDefinition(*this, entry, entity);
return entry;
}
auto fnType = llvm::FunctionType::get(
VoidTy, {WitnessTablePtrTy, TypeMetadataPtrTy, Int8PtrPtrTy},
/*varargs*/ false);
Signature signature(fnType, llvm::AttributeList(), DefaultCC);
LinkInfo link = LinkInfo::get(*this, entity, forDefinition);
entry = createFunction(*this, link, signature);
GlobalFuncs.insert({entity, entry});
return entry;
}
/// Fetch the lazy witness table access function for a protocol conformance.
llvm::Function *
IRGenModule::getAddrOfWitnessTableLazyAccessFunction(
const NormalProtocolConformance *conf,
CanType conformingType,
ForDefinition_t forDefinition) {
LinkEntity entity =
LinkEntity::forProtocolWitnessTableLazyAccessFunction(conf, conformingType);
auto found = GlobalFuncs.find(entity);
llvm::Function *entry = nullptr;
if (found != GlobalFuncs.end()) {
entry = found->second;
if (forDefinition) updateLinkageForDefinition(*this, entry, entity);
return entry;
}
llvm::FunctionType *fnType
= llvm::FunctionType::get(WitnessTablePtrTy, false);
Signature signature(fnType, llvm::AttributeList(), DefaultCC);
LinkInfo link = LinkInfo::get(*this, entity, forDefinition);
entry = createFunction(*this, link, signature);
ApplyIRLinkage({link.getLinkage(), link.getVisibility(), link.getDLLStorage()})
.to(entry, link.isForDefinition());
GlobalFuncs.insert({entity, entry});
return entry;
}
/// Get or create a witness table cache variable. These are an
/// implementation detail of witness table lazy access functions.
llvm::Constant *
IRGenModule::getAddrOfWitnessTableLazyCacheVariable(
const NormalProtocolConformance *conf,
CanType conformingType,
ForDefinition_t forDefinition) {
assert(!conformingType->hasArchetype());
LinkEntity entity =
LinkEntity::forProtocolWitnessTableLazyCacheVariable(conf, conformingType);
auto variable = getAddrOfLLVMVariable(entity,
forDefinition,
DebugTypeInfo());
// Zero-initialize if we're asking for a definition.
if (forDefinition) {
cast<llvm::GlobalVariable>(variable)->setInitializer(
llvm::ConstantPointerNull::get(WitnessTablePtrTy));
}
return variable;
}
/// Look up the address of a witness table.
///
/// This can only be used with non-dependent conformances.
llvm::Constant*
IRGenModule::getAddrOfWitnessTable(const RootProtocolConformance *conf,
ConstantInit definition) {
IRGen.addLazyWitnessTable(conf);
auto entity = LinkEntity::forProtocolWitnessTable(conf);
return getAddrOfLLVMVariable(entity, definition, DebugTypeInfo());
}
/// Look up the address of a witness table pattern.
///
/// This can only be used with dependent conformances from inside the
/// defining module.
llvm::Constant*
IRGenModule::getAddrOfWitnessTablePattern(const NormalProtocolConformance *conf,
ConstantInit definition) {
IRGen.addLazyWitnessTable(conf);
auto entity = LinkEntity::forProtocolWitnessTablePattern(conf);
return getAddrOfLLVMVariable(entity, definition, DebugTypeInfo());
}
/// Look up the address of a differentiability witness.
llvm::Constant *IRGenModule::getAddrOfDifferentiabilityWitness(
const SILDifferentiabilityWitness *witness, ConstantInit definition) {
auto entity = LinkEntity::forDifferentiabilityWitness(witness);
return getAddrOfLLVMVariable(entity, definition, DebugTypeInfo());
}
llvm::Function *
IRGenModule::getAddrOfAssociatedTypeWitnessTableAccessFunction(
const NormalProtocolConformance *conformance,
const AssociatedConformance &association) {
auto forDefinition = ForDefinition;
LinkEntity entity =
LinkEntity::forAssociatedTypeWitnessTableAccessFunction(conformance,
association);
auto found = GlobalFuncs.find(entity);
llvm::Function *entry = nullptr;
if (found != GlobalFuncs.end()) {
entry = found->second;
if (forDefinition) updateLinkageForDefinition(*this, entry, entity);
return entry;
}
auto signature = getAssociatedTypeWitnessTableAccessFunctionSignature();
LinkInfo link = LinkInfo::get(*this, entity, forDefinition);
entry = createFunction(*this, link, signature);
GlobalFuncs.insert({entity, entry});
return entry;
}
llvm::Function *
IRGenModule::getAddrOfDefaultAssociatedConformanceAccessor(
AssociatedConformance requirement) {
auto forDefinition = ForDefinition;
LinkEntity entity =
LinkEntity::forDefaultAssociatedConformanceAccessor(requirement);
auto found = GlobalFuncs.find(entity);
llvm::Function *entry = nullptr;
if (found != GlobalFuncs.end()) {
entry = found->second;
if (forDefinition) updateLinkageForDefinition(*this, entry, entity);
return entry;
}
auto signature = getAssociatedTypeWitnessTableAccessFunctionSignature();
LinkInfo link = LinkInfo::get(*this, entity, forDefinition);
entry = createFunction(*this, link, signature);
GlobalFuncs.insert({entity, entry});
return entry;
}
llvm::Function *
IRGenModule::getAddrOfContinuationPrototype(CanSILFunctionType fnType) {
LinkEntity entity = LinkEntity::forCoroutineContinuationPrototype(fnType);
auto found = GlobalFuncs.find(entity);
llvm::Function *entry = nullptr;
if (found != GlobalFuncs.end()) {
entry = found->second;
return entry;
}
auto signature = Signature::forCoroutineContinuation(*this, fnType);
LinkInfo link = LinkInfo::get(*this, entity, NotForDefinition);
entry = createFunction(*this, link, signature);
GlobalFuncs.insert({entity, entry});
return entry;
}
/// Should we be defining the given helper function?
static llvm::Function *shouldDefineHelper(IRGenModule &IGM,
llvm::Constant *fn,
bool setIsNoInline) {
auto *def = dyn_cast<llvm::Function>(fn);
if (!def) return nullptr;
if (!def->empty()) return nullptr;
def->setAttributes(IGM.constructInitialAttributes());
ApplyIRLinkage(IRLinkage::InternalLinkOnceODR).to(def);
def->setDoesNotThrow();
def->setCallingConv(IGM.DefaultCC);
if (setIsNoInline)
def->addFnAttr(llvm::Attribute::NoInline);
return def;
}
/// Get or create a helper function with the given name and type, lazily
/// using the given generation function to fill in its body.
///
/// The helper function will be shared between translation units within the
/// current linkage unit, so choose the name carefully to ensure that it
/// does not collide with any other helper function. In general, it should
/// be a Swift-specific C reserved name; that is, it should start with
// "__swift".
llvm::Constant *
IRGenModule::getOrCreateHelperFunction(StringRef fnName, llvm::Type *resultTy,
ArrayRef<llvm::Type*> paramTys,
llvm::function_ref<void(IRGenFunction &IGF)> generate,
bool setIsNoInline,
bool forPrologue,
bool isPerformanceConstraint) {
llvm::FunctionType *fnTy =
llvm::FunctionType::get(resultTy, paramTys, false);
llvm::Constant *fn =
cast<llvm::Constant>(
Module.getOrInsertFunction(fnName, fnTy).getCallee());
if (llvm::Function *def = shouldDefineHelper(*this, fn, setIsNoInline)) {
IRGenFunction IGF(*this, def, isPerformanceConstraint);
if (DebugInfo && !forPrologue)
DebugInfo->emitArtificialFunction(IGF, def);
generate(IGF);
}
return fn;
}
void IRGenModule::setColocateTypeDescriptorSection(llvm::GlobalVariable *v) {
switch (TargetInfo.OutputObjectFormat) {
case llvm::Triple::MachO:
if (IRGen.Opts.ColocateTypeDescriptors)
v->setSection("__TEXT,__constg_swiftt");
else
setTrueConstGlobal(v);
break;
case llvm::Triple::DXContainer:
case llvm::Triple::GOFF:
case llvm::Triple::SPIRV:
case llvm::Triple::UnknownObjectFormat:
case llvm::Triple::Wasm:
case llvm::Triple::ELF:
case llvm::Triple::XCOFF:
case llvm::Triple::COFF:
setTrueConstGlobal(v);
break;
}
}
void IRGenModule::setColocateMetadataSection(llvm::Function *f) {
if (!IRGen.Opts.CollocatedMetadataFunctions)
return;
switch (TargetInfo.OutputObjectFormat) {
case llvm::Triple::MachO:
f->setSection("__TEXT, __textg_swiftm, regular, pure_instructions");
break;
case llvm::Triple::DXContainer:
case llvm::Triple::GOFF:
case llvm::Triple::SPIRV:
case llvm::Triple::UnknownObjectFormat:
case llvm::Triple::Wasm:
case llvm::Triple::ELF:
case llvm::Triple::XCOFF:
case llvm::Triple::COFF:
break;
}
}
|