1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733
|
//===--- Metadata.cpp - Swift Language ABI Metadata Support ---------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// Implementations of the metadata ABI functions.
//
//===----------------------------------------------------------------------===//
#include "swift/Runtime/LibPrespecialized.h"
#if defined(_WIN32)
#define WIN32_LEAN_AND_MEAN
// Avoid defining macro max(), min() which conflict with std::max(), std::min()
#define NOMINMAX
#include <windows.h>
#endif
#include "MetadataCache.h"
#include "BytecodeLayouts.h"
#include "swift/ABI/TypeIdentity.h"
#include "swift/Basic/MathUtils.h"
#include "swift/Basic/Lazy.h"
#include "swift/Basic/Range.h"
#include "swift/Basic/STLExtras.h"
#include "swift/Demangling/Demangler.h"
#include "swift/RemoteInspection/GenericMetadataCacheEntry.h"
#include "swift/Runtime/Casting.h"
#include "swift/Runtime/EnvironmentVariables.h"
#include "swift/Runtime/ExistentialContainer.h"
#include "swift/Runtime/HeapObject.h"
#include "swift/Runtime/Metadata.h"
#include "swift/Runtime/Once.h"
#include "swift/Runtime/Portability.h"
#include "swift/Strings.h"
#include "swift/Threading/Mutex.h"
#include "llvm/ADT/StringExtras.h"
#include <algorithm>
#include <cctype>
#include <cinttypes>
#include <condition_variable>
#include <new>
#include <unordered_set>
#include <vector>
#if SWIFT_PTRAUTH
#include <ptrauth.h>
#endif
#if SWIFT_OBJC_INTEROP
extern "C" void _objc_setClassCopyFixupHandler(void (* _Nonnull newFixupHandler)
(Class _Nonnull oldClass, Class _Nonnull newClass));
#endif
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/Hashing.h"
#include "../CompatibilityOverride/CompatibilityOverride.h"
#include "ErrorObject.h"
#include "ExistentialMetadataImpl.h"
#include "swift/Runtime/Debug.h"
#include "Private.h"
#if SWIFT_OBJC_INTEROP
#include "ObjCRuntimeGetImageNameFromClass.h"
#endif
#include <cstdio>
#if defined(__APPLE__) && defined(VM_MEMORY_SWIFT_METADATA)
#define VM_TAG_FOR_SWIFT_METADATA VM_MAKE_TAG(VM_MEMORY_SWIFT_METADATA)
#else
#define VM_TAG_FOR_SWIFT_METADATA (-1)
#endif
using namespace swift;
using namespace metadataimpl;
#if defined(__APPLE__)
// Binaries using noncopyable types check the address of the symbol
// `swift_runtimeSupportsNoncopyableTypes` before exposing any noncopyable
// type metadata through in-process reflection, to prevent existing code
// that expects all types to be copyable from crashing or causing bad behavior
// by copying noncopyable types. The runtime does not yet support noncopyable
// types, so we explicitly define this symbol to be zero for now. Binaries
// weak-import this symbol so they will resolve it to a zero address on older
// runtimes as well.
//
// Note: If this symbol's value ever gets updated, the corresponding condition
// handled by IRGen MUST be updated in tandem.
__asm__(" .globl _swift_runtimeSupportsNoncopyableTypes\n");
__asm__(".set _swift_runtimeSupportsNoncopyableTypes, 0\n");
#endif
// GenericParamDescriptor is a single byte, so while it's difficult to
// imagine needing even a quarter this many generic params, there's very
// little harm in doing it.
const GenericParamDescriptor
swift::ImplicitGenericParamDescriptors[MaxNumImplicitGenericParamDescriptors] = {
#define D GenericParamDescriptor::implicit()
D,D,D,D, D,D,D,D, D,D,D,D, D,D,D,D, D,D,D,D, D,D,D,D, D,D,D,D, D,D,D,D,
D,D,D,D, D,D,D,D, D,D,D,D, D,D,D,D, D,D,D,D, D,D,D,D, D,D,D,D, D,D,D,D
#undef D
};
static_assert(MaxNumImplicitGenericParamDescriptors == 64, "length mismatch");
static ClassMetadata *
_swift_relocateClassMetadata(const ClassDescriptor *description,
const ResilientClassMetadataPattern *pattern);
template<>
Metadata *TargetSingletonMetadataInitialization<InProcess>::allocate(
const TypeContextDescriptor *description) const {
// If this class has resilient ancestry, the size of the metadata is not known
// at compile time, so we allocate it dynamically, filling it in from a
// pattern.
if (hasResilientClassPattern(description)) {
auto *pattern = ResilientPattern.get();
// If there is a relocation function, call it.
if (auto *fn = ResilientPattern->RelocationFunction.get())
return fn(description, pattern);
// Otherwise, use the default behavior.
auto *classDescription = cast<ClassDescriptor>(description);
return _swift_relocateClassMetadata(classDescription, pattern);
}
// Otherwise, we have a static template that we can initialize in-place.
auto *metadata = IncompleteMetadata.get();
// If this is a class, we have to initialize the value witness table early
// so that two-phase initialization can proceed as if this metadata is
// complete for layout purposes when it appears as part of an aggregate type.
//
// Note that we can't use (dyn_)cast<ClassMetadata> here because the static
// template may have the "wrong" isSwift bit set in its Data pointer, if the
// binary was built to deploy back to pre-stable-Swift Objective-C runtimes.
// Such a template will fail the `isTypeMetadata` test and we'll think that it
// isn't Swift metadata but a plain old ObjC class instead.
if (metadata->getKind() == MetadataKind::Class) {
auto *fullMetadata = asFullMetadata(metadata);
// Begin by initializing the value witness table; everything else is
// initialized by swift_initClassMetadata().
#if SWIFT_OBJC_INTEROP
auto *classMetadata = static_cast<ClassMetadata*>(metadata);
classMetadata->setAsTypeMetadata();
fullMetadata->ValueWitnesses =
(classMetadata->Flags & ClassFlags::UsesSwiftRefcounting)
? &VALUE_WITNESS_SYM(Bo)
: &VALUE_WITNESS_SYM(BO);
#else
fullMetadata->ValueWitnesses = &VALUE_WITNESS_SYM(Bo);
#endif
}
return metadata;
}
void MetadataCacheKey::installGenericArguments(
uint16_t numKeyArguments,
uint16_t numPacks,
const GenericPackShapeDescriptor *PackShapeDescriptors,
const void **dst, const void * const *src) {
memcpy(dst, src, numKeyArguments * sizeof(void *));
// If we don't have any pack arguments, there is nothing more to do.
if (numPacks == 0)
return;
// Heap-allocate all installed metadata and witness table packs.
for (unsigned i = 0; i < numPacks; ++i) {
auto pack = PackShapeDescriptors[i];
size_t count = reinterpret_cast<size_t>(dst[pack.ShapeClass]);
switch (pack.Kind) {
case GenericPackKind::Metadata:
dst[pack.Index] = swift_allocateMetadataPack(
reinterpret_cast<const Metadata * const *>(dst[pack.Index]),
count);
break;
case GenericPackKind::WitnessTable:
dst[pack.Index] = swift_allocateWitnessTablePack(
reinterpret_cast<const WitnessTable * const *>(dst[pack.Index]),
count);
break;
}
}
}
/// Copy the generic arguments into place in a newly-allocated metadata.
static void installGenericArguments(Metadata *metadata,
const TypeContextDescriptor *description,
const void *arguments) {
const auto &genericContext = *description->getGenericContext();
const auto &header = genericContext.getGenericContextHeader();
auto dst = (reinterpret_cast<const void **>(metadata) +
description->getGenericArgumentOffset());
auto src = reinterpret_cast<const void * const *>(arguments);
auto packShapeHeader = genericContext.getGenericPackShapeHeader();
MetadataCacheKey::installGenericArguments(
header.NumKeyArguments,
packShapeHeader.NumPacks,
genericContext.getGenericPackShapeDescriptors().data(),
dst, src);
}
#if SWIFT_OBJC_INTEROP
static ClassMetadataBounds computeMetadataBoundsForObjCClass(Class cls) {
cls = swift_getInitializedObjCClass(cls);
auto metadata = reinterpret_cast<const ClassMetadata *>(cls);
return metadata->getClassBoundsAsSwiftSuperclass();
}
#endif
static ClassMetadataBounds
computeMetadataBoundsForSuperclass(const void *ref,
TypeReferenceKind refKind) {
switch (refKind) {
case TypeReferenceKind::IndirectTypeDescriptor: {
auto description = *reinterpret_cast<const ClassDescriptor * const __ptrauth_swift_type_descriptor *>(ref);
if (!description) {
swift::fatalError(0, "instantiating class metadata for class with "
"missing weak-linked ancestor");
}
return description->getMetadataBounds();
}
case TypeReferenceKind::DirectTypeDescriptor: {
auto description = reinterpret_cast<const ClassDescriptor *>(ref);
return description->getMetadataBounds();
}
case TypeReferenceKind::DirectObjCClassName: {
#if SWIFT_OBJC_INTEROP
auto cls = objc_lookUpClass(reinterpret_cast<const char *>(ref));
return computeMetadataBoundsForObjCClass(cls);
#else
break;
#endif
}
case TypeReferenceKind::IndirectObjCClass: {
#if SWIFT_OBJC_INTEROP
auto cls = *reinterpret_cast<const Class *>(ref);
return computeMetadataBoundsForObjCClass(cls);
#else
break;
#endif
}
}
swift_unreachable("unsupported superclass reference kind");
}
static ClassMetadataBounds computeMetadataBoundsFromSuperclass(
const ClassDescriptor *description,
StoredClassMetadataBounds &storedBounds) {
ClassMetadataBounds bounds;
// Compute the bounds for the superclass, extending it to the minimum
// bounds of a Swift class.
if (const void *superRef = description->getResilientSuperclass()) {
bounds = computeMetadataBoundsForSuperclass(superRef,
description->getResilientSuperclassReferenceKind());
} else {
bounds = ClassMetadataBounds::forSwiftRootClass();
}
// Add the subclass's immediate members.
bounds.adjustForSubclass(description->areImmediateMembersNegative(),
description->NumImmediateMembers);
// Cache before returning.
storedBounds.initialize(bounds);
return bounds;
}
ClassMetadataBounds
swift::getResilientMetadataBounds(const ClassDescriptor *description) {
assert(description->hasResilientSuperclass());
auto &storedBounds = *description->ResilientMetadataBounds.get();
ClassMetadataBounds bounds;
if (storedBounds.tryGet(bounds)) {
return bounds;
}
return computeMetadataBoundsFromSuperclass(description, storedBounds);
}
int32_t
swift::getResilientImmediateMembersOffset(const ClassDescriptor *description) {
assert(description->hasResilientSuperclass());
auto &storedBounds = *description->ResilientMetadataBounds.get();
ptrdiff_t result;
if (storedBounds.tryGetImmediateMembersOffset(result)) {
return result / sizeof(void*);
}
auto bounds = computeMetadataBoundsFromSuperclass(description, storedBounds);
return bounds.ImmediateMembersOffset / sizeof(void*);
}
static bool
areAllTransitiveMetadataComplete_cheap(const Metadata *metadata);
static MetadataDependency
checkTransitiveCompleteness(const Metadata *metadata);
static PrivateMetadataState inferStateForMetadata(Metadata *metadata) {
if (metadata->getValueWitnesses()->isIncomplete())
return PrivateMetadataState::Abstract;
// TODO: internal vs. external layout-complete?
return PrivateMetadataState::LayoutComplete;
}
namespace {
struct GenericCacheEntry final :
VariadicMetadataCacheEntryBase<GenericCacheEntry> {
static const char *getName() { return "GenericCache"; }
// The constructor/allocate operations that take a `const Metadata *`
// are used for the insertion of canonical specializations.
// The metadata is always complete after construction.
GenericCacheEntry(MetadataCacheKey key,
MetadataWaitQueue::Worker &worker,
MetadataRequest request,
const Metadata *candidate)
: VariadicMetadataCacheEntryBase(key, worker,
PrivateMetadataState::Complete,
const_cast<Metadata*>(candidate)) {}
AllocationResult allocate(const Metadata *candidate) {
swift_unreachable("always short-circuited");
}
static bool allowMangledNameVerification(const Metadata *candidate) {
// Disallow mangled name verification for specialized candidates
// because it will trigger recursive entry into the swift_once
// in cacheCanonicalSpecializedMetadata.
// TODO: verify mangled names in a second pass in that function.
return false;
}
// The constructor/allocate operations that take a descriptor
// and arguments are used along the normal allocation path.
GenericCacheEntry(MetadataCacheKey key,
MetadataWaitQueue::Worker &worker,
MetadataRequest request,
const TypeContextDescriptor *description,
const void * const *arguments)
: VariadicMetadataCacheEntryBase(key, worker,
PrivateMetadataState::Allocating,
/*candidate*/ nullptr) {}
AllocationResult allocate(const TypeContextDescriptor *description,
const void * const *arguments) {
if (auto *prespecialized =
getLibPrespecializedMetadata(description, arguments))
return {prespecialized, PrivateMetadataState::Complete};
// Find a pattern. Currently we always use the default pattern.
auto &generics = description->getFullGenericContextHeader();
auto pattern = generics.DefaultInstantiationPattern.get();
// Call the pattern's instantiation function.
auto metadata =
pattern->InstantiationFunction(description, arguments, pattern);
// If there's no completion function, do a quick-and-dirty check to
// see if all of the type arguments are already complete. If they
// are, we can broadcast completion immediately and potentially avoid
// some extra locking.
PrivateMetadataState state;
if (pattern->CompletionFunction.isNull()) {
if (areAllTransitiveMetadataComplete_cheap(metadata)) {
state = PrivateMetadataState::Complete;
} else {
state = PrivateMetadataState::NonTransitiveComplete;
}
} else {
state = inferStateForMetadata(metadata);
}
return { metadata, state };
}
static bool allowMangledNameVerification(
const TypeContextDescriptor *description,
const void * const *arguments) {
return true;
}
void verifyBuiltMetadata(const Metadata *original,
const Metadata *candidate) {}
void verifyBuiltMetadata(const Metadata *original,
const TypeContextDescriptor *description,
const void *const *arguments) {
if (swift::runtime::environment::
SWIFT_DEBUG_VALIDATE_EXTERNAL_GENERIC_METADATA_BUILDER())
validateExternalGenericMetadataBuilder(original, description,
arguments);
}
MetadataStateWithDependency tryInitialize(Metadata *metadata,
PrivateMetadataState state,
PrivateMetadataCompletionContext *context) {
assert(state != PrivateMetadataState::Complete);
// Finish the completion function.
if (state < PrivateMetadataState::NonTransitiveComplete) {
// Find a pattern. Currently we always use the default pattern.
auto &generics = metadata->getTypeContextDescriptor()
->getFullGenericContextHeader();
auto pattern = generics.DefaultInstantiationPattern.get();
// Complete the metadata's instantiation.
auto dependency =
pattern->CompletionFunction(metadata, &context->Public, pattern);
// If this failed with a dependency, infer the current metadata state
// and return.
if (dependency) {
return { inferStateForMetadata(metadata), dependency };
}
}
// Check for transitive completeness.
if (auto dependency = checkTransitiveCompleteness(metadata)) {
return { PrivateMetadataState::NonTransitiveComplete, dependency };
}
// We're done.
return { PrivateMetadataState::Complete, MetadataDependency() };
}
};
} // end anonymous namespace
namespace swift {
struct StaticAssertGenericMetadataCacheEntryValueOffset {
static_assert(
offsetof(GenericCacheEntry, Value) ==
offsetof(swift::GenericMetadataCacheEntry<InProcess::StoredPointer>,
Value),
"The generic metadata cache entry layout mismatch");
};
}
namespace {
class GenericMetadataCache :
public MetadataCache<GenericCacheEntry, GenericMetadataCacheTag> {
public:
GenericSignatureLayout<InProcess> SigLayout;
GenericMetadataCache(const TargetGenericContext<InProcess> &genericContext)
: SigLayout(genericContext.getGenericSignature()) {
}
};
using LazyGenericMetadataCache = Lazy<GenericMetadataCache>;
class GlobalMetadataCacheEntry {
public:
const TypeContextDescriptor *Description;
GenericMetadataCache Cache;
GlobalMetadataCacheEntry(const TypeContextDescriptor *description)
: Description(description), Cache(*description->getGenericContext()) {}
intptr_t getKeyIntValueForDump() {
return reinterpret_cast<intptr_t>(Description);
}
bool matchesKey(const TypeContextDescriptor *description) const {
return description == Description;
}
friend llvm::hash_code hash_value(const GlobalMetadataCacheEntry &value) {
return llvm::hash_value(value.Description);
}
static size_t
getExtraAllocationSize(const TypeContextDescriptor *description) {
return 0;
}
size_t getExtraAllocationSize() const { return 0; }
};
static SimpleGlobalCache<GlobalMetadataCacheEntry, GlobalMetadataCacheTag>
GlobalMetadataCache;
} // end anonymous namespace
/// Fetch the metadata cache for a generic metadata structure.
static GenericMetadataCache &getCache(
const TypeContextDescriptor &description) {
auto &generics = description.getFullGenericContextHeader();
// Keep this assert even if you change the representation above.
static_assert(sizeof(LazyGenericMetadataCache) <=
sizeof(GenericMetadataInstantiationCache::PrivateData),
"metadata cache is larger than the allowed space");
auto *cacheStorage = generics.getInstantiationCache();
if (cacheStorage == nullptr) {
return GlobalMetadataCache.getOrInsert(&description).first->Cache;
}
auto lazyCache =
reinterpret_cast<LazyGenericMetadataCache*>(
generics.getInstantiationCache()->PrivateData);
return lazyCache->getWithInit(*description.getGenericContext());
}
#if SWIFT_PTRAUTH && SWIFT_OBJC_INTEROP
// See [NOTE: Dynamic-subclass-KVO]
static void swift_objc_classCopyFixupHandler(Class oldClass, Class newClass) {
auto oldClassMetadata = reinterpret_cast<const ClassMetadata *>(oldClass);
// Bail out if this isn't a Swift.
if (!oldClassMetadata->isTypeMetadata())
return;
// Copy the value witness table and pointer and heap object destroyer for
// pointer authentication.
auto newClassMetadata = reinterpret_cast<ClassMetadata *>(newClass);
newClassMetadata->setValueWitnesses(oldClassMetadata->getValueWitnesses());
newClassMetadata->setHeapObjectDestroyer(oldClassMetadata->getHeapObjectDestroyer());
// Otherwise, re-sign v-table entries using the extra discriminators stored
// in the v-table descriptor.
auto *srcWords = reinterpret_cast<void **>(oldClass);
auto *dstWords = reinterpret_cast<void **>(newClass);
while (oldClassMetadata && oldClassMetadata->isTypeMetadata()) {
const auto *description = oldClassMetadata->getDescription();
// Copy the vtable entries.
if (description && description->hasVTable()) {
auto *vtable = description->getVTableDescriptor();
auto descriptors = description->getMethodDescriptors();
auto src = srcWords + vtable->getVTableOffset(description);
auto dest = dstWords + vtable->getVTableOffset(description);
for (size_t i = 0, e = vtable->VTableSize; i != e; ++i) {
swift_ptrauth_copy_code_or_data(
reinterpret_cast<void **>(&dest[i]),
reinterpret_cast<void *const *>(&src[i]),
descriptors[i].Flags.getExtraDiscriminator(),
!descriptors[i].Flags.isAsync(),
/*allowNull*/ true); // NULL allowed for VFE (methods in the vtable
// might be proven unused and null'ed)
}
}
oldClassMetadata = oldClassMetadata->Superclass;
}
}
SWIFT_ALLOWED_RUNTIME_GLOBAL_CTOR_BEGIN
static bool fixupHandlerInstaller = [] {
_objc_setClassCopyFixupHandler(&swift_objc_classCopyFixupHandler);
return true;
}();
SWIFT_ALLOWED_RUNTIME_GLOBAL_CTOR_END
#endif
#if SWIFT_OBJC_INTEROP
extern "C" void *_objc_empty_cache;
#endif
template <> bool Metadata::isStaticallySpecializedGenericMetadata() const {
if (auto *metadata = dyn_cast<StructMetadata>(this))
return metadata->isStaticallySpecializedGenericMetadata();
if (auto *metadata = dyn_cast<EnumMetadata>(this))
return metadata->isStaticallySpecializedGenericMetadata();
if (auto *metadata = dyn_cast<ClassMetadata>(this))
return metadata->isStaticallySpecializedGenericMetadata();
return false;
}
template <> const TypeContextDescriptor *Metadata::getDescription() const {
if (auto *metadata = dyn_cast<StructMetadata>(this))
return metadata->getDescription();
if (auto *metadata = dyn_cast<EnumMetadata>(this))
return metadata->getDescription();
if (auto *metadata = dyn_cast<ClassMetadata>(this))
return metadata->getDescription();
return nullptr;
}
template <>
bool Metadata::isCanonicalStaticallySpecializedGenericMetadata() const {
if (auto *metadata = dyn_cast<StructMetadata>(this))
return metadata->isCanonicalStaticallySpecializedGenericMetadata();
if (auto *metadata = dyn_cast<EnumMetadata>(this))
return metadata->isCanonicalStaticallySpecializedGenericMetadata();
if (auto *metadata = dyn_cast<ClassMetadata>(this))
return metadata->isCanonicalStaticallySpecializedGenericMetadata();
return false;
}
static void copyMetadataPattern(void **section,
const GenericMetadataPartialPattern *pattern) {
memcpy(section + pattern->OffsetInWords,
pattern->Pattern.get(),
size_t(pattern->SizeInWords) * sizeof(void*));
}
static void
initializeClassMetadataFromPattern(ClassMetadata *metadata,
ClassMetadataBounds bounds,
const ClassDescriptor *description,
const GenericClassMetadataPattern *pattern) {
auto fullMetadata = asFullMetadata(metadata);
char *rawMetadata = reinterpret_cast<char*>(metadata);
// Install the extra-data pattern.
void **metadataExtraData =
reinterpret_cast<void**>(rawMetadata) + bounds.PositiveSizeInWords;
if (pattern->hasExtraDataPattern()) {
auto extraDataPattern = pattern->getExtraDataPattern();
// Zero memory up to the offset.
// [pre-5.2-extra-data-zeroing] Before Swift 5.2, the runtime did not
// correctly zero the zero-prefix of the extra-data pattern.
memset(metadataExtraData, 0,
size_t(extraDataPattern->OffsetInWords) * sizeof(void *));
// Copy the pattern into the rest of the extra data.
copyMetadataPattern(metadataExtraData, extraDataPattern);
}
// Install the immediate members pattern:
void **immediateMembers =
reinterpret_cast<void**>(rawMetadata + bounds.ImmediateMembersOffset);
// Zero out the entire immediate-members section.
// TODO: only memset the parts that aren't covered by the pattern.
memset(immediateMembers, 0, description->getImmediateMembersSize());
// Copy in the immediate arguments.
// Copy the immediate-members pattern.
if (pattern->hasImmediateMembersPattern()) {
auto immediateMembersPattern = pattern->getImmediateMembersPattern();
copyMetadataPattern(immediateMembers, immediateMembersPattern);
}
// Initialize the header:
// Heap destructor.
fullMetadata->destroy = pattern->Destroy.get();
// Value witness table.
#if SWIFT_OBJC_INTEROP
fullMetadata->ValueWitnesses =
(pattern->Flags & ClassFlags::UsesSwiftRefcounting)
? &VALUE_WITNESS_SYM(Bo)
: &VALUE_WITNESS_SYM(BO);
#else
fullMetadata->ValueWitnesses = &VALUE_WITNESS_SYM(Bo);
#endif
#if SWIFT_OBJC_INTEROP
// Install the metaclass's RO-data pointer.
auto metaclass = reinterpret_cast<AnyClassMetadata *>(
metadataExtraData + pattern->MetaclassObjectOffset);
auto metaclassRO = metadataExtraData + pattern->MetaclassRODataOffset;
metaclass->Data = reinterpret_cast<uintptr_t>(metaclassRO);
#endif
// MetadataKind / isa.
#if SWIFT_OBJC_INTEROP
metadata->setClassISA(metaclass);
#else
metadata->setKind(MetadataKind::Class);
#endif
// Superclass.
metadata->Superclass = nullptr;
#if SWIFT_OBJC_INTEROP
// Cache data. Install the same initializer that the compiler is
// required to use. We don't need to do this in non-ObjC-interop modes.
metadata->CacheData[0] = &_objc_empty_cache;
metadata->CacheData[1] = nullptr;
#endif
// RO-data pointer.
#if SWIFT_OBJC_INTEROP
auto classRO = metadataExtraData + pattern->ClassRODataOffset;
metadata->Data =
reinterpret_cast<uintptr_t>(classRO) | SWIFT_CLASS_IS_SWIFT_MASK;
#endif
// Class flags.
metadata->Flags = pattern->Flags;
// Instance layout.
metadata->InstanceAddressPoint = 0;
metadata->InstanceSize = 0;
metadata->InstanceAlignMask = 0;
// Reserved.
metadata->Reserved = 0;
// Class metadata layout.
metadata->ClassSize = bounds.getTotalSizeInBytes();
metadata->ClassAddressPoint = bounds.getAddressPointInBytes();
// Class descriptor.
metadata->setDescription(description);
// I-var destroyer.
metadata->IVarDestroyer = pattern->IVarDestroyer;
}
ClassMetadata *
swift::swift_allocateGenericClassMetadata(const ClassDescriptor *description,
const void *arguments,
const GenericClassMetadataPattern *pattern){
description = swift_auth_data_non_address(
description, SpecialPointerAuthDiscriminators::TypeDescriptor);
// Compute the formal bounds of the metadata.
auto bounds = description->getMetadataBounds();
// Augment that with any required extra data from the pattern.
auto allocationBounds = bounds;
if (pattern->hasExtraDataPattern()) {
auto extraDataPattern = pattern->getExtraDataPattern();
allocationBounds.PositiveSizeInWords +=
extraDataPattern->OffsetInWords + extraDataPattern->SizeInWords;
}
auto bytes = (char*)
MetadataAllocator(GenericClassMetadataTag)
.Allocate(allocationBounds.getTotalSizeInBytes(), alignof(void*));
auto addressPoint = bytes + allocationBounds.getAddressPointInBytes();
auto metadata = reinterpret_cast<ClassMetadata *>(addressPoint);
initializeClassMetadataFromPattern(metadata, bounds, description, pattern);
assert(metadata->isTypeMetadata());
// Copy the generic arguments into place.
installGenericArguments(metadata, description, arguments);
return metadata;
}
ClassMetadata *
swift::swift_allocateGenericClassMetadataWithLayoutString(
const ClassDescriptor *description,
const void *arguments,
const GenericClassMetadataPattern *pattern) {
return swift::swift_allocateGenericClassMetadata(description,
arguments,
pattern);
}
static void
initializeValueMetadataFromPattern(ValueMetadata *metadata,
const ValueTypeDescriptor *description,
const GenericValueMetadataPattern *pattern) {
auto fullMetadata = asFullMetadata(metadata);
char *rawMetadata = reinterpret_cast<char*>(metadata);
if (pattern->hasExtraDataPattern()) {
void **metadataExtraData =
reinterpret_cast<void**>(rawMetadata + sizeof(ValueMetadata));
auto extraDataPattern = pattern->getExtraDataPattern();
// Zero memory up to the offset.
// [pre-5.3-extra-data-zeroing] Before Swift 5.3, the runtime did not
// correctly zero the zero-prefix of the extra-data pattern.
memset(metadataExtraData, 0,
size_t(extraDataPattern->OffsetInWords) * sizeof(void *));
// Copy the pattern into the rest of the extra data.
copyMetadataPattern(metadataExtraData, extraDataPattern);
}
// Put the VWT pattern in place as if it was the real VWT.
// The various initialization functions will instantiate this as
// necessary.
fullMetadata->setValueWitnesses(pattern->getValueWitnessesPattern());
// Set the metadata kind.
metadata->setKind(pattern->getMetadataKind());
// Set the type descriptor.
metadata->Description = description;
}
ValueMetadata *
swift::swift_allocateGenericValueMetadata(const ValueTypeDescriptor *description,
const void *arguments,
const GenericValueMetadataPattern *pattern,
size_t extraDataSize) {
description = swift_auth_data_non_address(description, SpecialPointerAuthDiscriminators::TypeDescriptor);
static_assert(sizeof(StructMetadata::HeaderType)
== sizeof(ValueMetadata::HeaderType),
"struct metadata header unexpectedly has extra members");
static_assert(sizeof(StructMetadata) == sizeof(ValueMetadata),
"struct metadata unexpectedly has extra members");
static_assert(sizeof(EnumMetadata::HeaderType)
== sizeof(ValueMetadata::HeaderType),
"enum metadata header unexpectedly has extra members");
static_assert(sizeof(EnumMetadata) == sizeof(ValueMetadata),
"enum metadata unexpectedly has extra members");
assert(!pattern->hasExtraDataPattern() ||
(extraDataSize == (pattern->getExtraDataPattern()->OffsetInWords +
pattern->getExtraDataPattern()->SizeInWords) *
sizeof(void *)));
size_t totalSize = sizeof(FullMetadata<ValueMetadata>) + extraDataSize;
auto bytes = (char*) MetadataAllocator(GenericValueMetadataTag)
.Allocate(totalSize, alignof(void*));
auto addressPoint = bytes + sizeof(ValueMetadata::HeaderType);
auto metadata = reinterpret_cast<ValueMetadata *>(addressPoint);
initializeValueMetadataFromPattern(metadata, description, pattern);
// Copy the generic arguments into place.
installGenericArguments(metadata, description, arguments);
return metadata;
}
ValueMetadata *
swift::swift_allocateGenericValueMetadataWithLayoutString(
const ValueTypeDescriptor *description,
const void *arguments,
const GenericValueMetadataPattern *pattern,
size_t extraDataSize) {
return swift::swift_allocateGenericValueMetadata(description,
arguments,
pattern,
extraDataSize);
}
// Look into the canonical prespecialized metadata attached to the type
// descriptor and add them to the metadata cache.
static void
_cacheCanonicalSpecializedMetadata(const TypeContextDescriptor *description) {
auto &cache = getCache(*description);
auto request =
MetadataRequest(MetadataState::Complete, /*isNonBlocking*/ true);
assert(description->getFullGenericContextHeader().Base.NumKeyArguments ==
cache.SigLayout.sizeInWords());
if (auto *classDescription = dyn_cast<ClassDescriptor>(description)) {
auto canonicalMetadataAccessors = classDescription->getCanonicalMetadataPrespecializationAccessors();
for (auto &canonicalMetadataAccessorPtr : canonicalMetadataAccessors) {
auto *canonicalMetadataAccessor = canonicalMetadataAccessorPtr.get();
auto response = canonicalMetadataAccessor(request);
auto *canonicalMetadata = response.Value;
const void *const *arguments =
reinterpret_cast<const void *const *>(canonicalMetadata->getGenericArgs());
auto key = MetadataCacheKey(cache.SigLayout, arguments);
auto result = cache.getOrInsert(key, MetadataRequest(MetadataState::Complete, /*isNonBlocking*/true), canonicalMetadata);
(void)result;
assert(result.second.Value == canonicalMetadata);
}
} else {
auto canonicalMetadatas = description->getCanonicalMetadataPrespecializations();
for (auto &canonicalMetadataPtr : canonicalMetadatas) {
Metadata *canonicalMetadata = canonicalMetadataPtr.get();
const void *const *arguments =
reinterpret_cast<const void *const *>(canonicalMetadata->getGenericArgs());
auto key = MetadataCacheKey(cache.SigLayout, arguments);
auto result = cache.getOrInsert(key, MetadataRequest(MetadataState::Complete, /*isNonBlocking*/true), canonicalMetadata);
(void)result;
assert(result.second.Value == canonicalMetadata);
}
}
}
static void
cacheCanonicalSpecializedMetadata(const TypeContextDescriptor *description,
swift_once_t *token) {
swift::once(
*token,
[](void *uncastDescription) {
auto *description = (const TypeContextDescriptor *)uncastDescription;
_cacheCanonicalSpecializedMetadata(description);
},
(void *)description);
}
MetadataResponse swift::swift_getCanonicalSpecializedMetadata(
MetadataRequest request, const Metadata *candidate,
const Metadata **cacheMetadataPtr) {
assert(candidate->isStaticallySpecializedGenericMetadata() &&
!candidate->isCanonicalStaticallySpecializedGenericMetadata());
auto *description = candidate->getDescription();
assert(description);
using CachedMetadata = std::atomic<const Metadata *>;
auto cachedMetadataAddr = ((CachedMetadata *)cacheMetadataPtr);
auto *cachedMetadata = cachedMetadataAddr->load(SWIFT_MEMORY_ORDER_CONSUME);
if (SWIFT_LIKELY(cachedMetadata != nullptr)) {
// Cached metadata pointers are always complete.
return MetadataResponse{(const Metadata *)cachedMetadata,
MetadataState::Complete};
}
if (auto *token =
description
->getCanonicalMetadataPrespecializationCachingOnceToken()) {
cacheCanonicalSpecializedMetadata(description, token);
// NOTE: If there is no token, then there are no canonical prespecialized
// metadata records, either.
}
const void *const *arguments =
reinterpret_cast<const void *const *>(candidate->getGenericArgs());
auto &cache = getCache(*description);
auto key = MetadataCacheKey(cache.SigLayout, arguments);
auto result = cache.getOrInsert(key, request, candidate);
cachedMetadataAddr->store(result.second.Value, std::memory_order_release);
return result.second;
}
SWIFT_CC(swift)
static MetadataResponse
_swift_getGenericMetadata(MetadataRequest request, const void *const *arguments,
const TypeContextDescriptor *description) {
auto &cache = getCache(*description);
assert(description->getFullGenericContextHeader().Base.NumKeyArguments ==
cache.SigLayout.sizeInWords());
auto key = MetadataCacheKey(cache.SigLayout, arguments);
auto result = cache.getOrInsert(key, request, description, arguments);
return result.second;
}
/// The primary entrypoint.
MetadataResponse
swift::swift_getGenericMetadata(MetadataRequest request,
const void *const *arguments,
const TypeContextDescriptor *description) {
description = swift_auth_data_non_address(
description, SpecialPointerAuthDiscriminators::TypeDescriptor);
return _swift_getGenericMetadata(request, arguments, description);
}
MetadataResponse swift::swift_getCanonicalPrespecializedGenericMetadata(
MetadataRequest request, const void *const *arguments,
const TypeContextDescriptor *description, swift_once_t *token) {
description = swift_auth_data_non_address(
description, SpecialPointerAuthDiscriminators::TypeDescriptor);
cacheCanonicalSpecializedMetadata(description, token);
return _swift_getGenericMetadata(request, arguments, description);
}
/***************************************************************************/
/*** In-place metadata initialization **************************************/
/***************************************************************************/
namespace {
/// A cache entry for "in-place" metadata initializations.
class SingletonMetadataCacheEntry final
: public MetadataCacheEntryBase<SingletonMetadataCacheEntry, int> {
ValueType Value = nullptr;
friend MetadataCacheEntryBase;
ValueType getValue() {
return Value;
}
void setValue(ValueType value) {
Value = value;
}
public:
// We have to give MetadataCacheEntryBase a non-empty list of trailing
// objects or else it gets annoyed.
static size_t numTrailingObjects(OverloadToken<int>) { return 0; }
static const char *getName() { return "SingletonMetadataCache"; }
SingletonMetadataCacheEntry(MetadataWaitQueue::Worker &worker,
MetadataRequest request,
const TypeContextDescriptor *description)
: MetadataCacheEntryBase(worker) {}
AllocationResult allocate(const TypeContextDescriptor *description) {
auto &initialization = description->getSingletonMetadataInitialization();
// Classes with resilient superclasses might require their metadata to
// be relocated.
auto metadata = initialization.allocate(description);
auto state = inferStateForMetadata(metadata);
return { metadata, state };
}
MetadataStateWithDependency tryInitialize(Metadata *metadata,
PrivateMetadataState state,
PrivateMetadataCompletionContext *context) {
assert(state != PrivateMetadataState::Complete);
// Finish the completion function.
if (state < PrivateMetadataState::NonTransitiveComplete) {
// Find a pattern. Currently we always use the default pattern.
auto &initialization =
metadata->getTypeContextDescriptor()
->getSingletonMetadataInitialization();
// Complete the metadata's instantiation.
auto dependency =
initialization.CompletionFunction(metadata, &context->Public,
/*pattern*/ nullptr);
// If this failed with a dependency, infer the current metadata state
// and return.
if (dependency) {
return { inferStateForMetadata(metadata), dependency };
}
}
// Check for transitive completeness.
if (auto dependency = checkTransitiveCompleteness(metadata)) {
return { PrivateMetadataState::NonTransitiveComplete, dependency };
}
// We're done.
publishCompleteMetadata(metadata);
return { PrivateMetadataState::Complete, MetadataDependency() };
}
void publishCompleteMetadata(Metadata *metadata) {
auto &init = metadata->getTypeContextDescriptor()
->getSingletonMetadataInitialization();
auto &cache = *init.InitializationCache.get();
cache.Metadata.store(metadata, std::memory_order_release);
}
};
/// An implementation of LockingConcurrentMapStorage that's more
/// appropriate for the in-place metadata cache.
///
/// TODO: delete the cache entry when initialization is complete.
class SingletonMetadataCacheStorage {
ConcurrencyControl Concurrency;
public:
using KeyType = const TypeContextDescriptor *;
using EntryType = SingletonMetadataCacheEntry;
ConcurrencyControl &getConcurrency() { return Concurrency; }
template <class... ArgTys>
std::pair<EntryType*, bool>
getOrInsert(KeyType key, ArgTys &&...args) {
auto &init = key->getSingletonMetadataInitialization();
auto &cache = *init.InitializationCache.get();
// Check for an existing entry.
auto existingEntry = cache.Private.load(std::memory_order_acquire);
// If there isn't one there, optimistically create an entry and
// try to swap it in.
if (!existingEntry) {
auto allocatedEntry = swift_cxx_newObject<SingletonMetadataCacheEntry>(
std::forward<ArgTys>(args)...);
if (cache.Private.compare_exchange_strong(existingEntry,
allocatedEntry,
std::memory_order_acq_rel,
std::memory_order_acquire)) {
// If that succeeded, return the entry we allocated and tell the
// caller we allocated it.
return { allocatedEntry, true };
}
// Otherwise, use the new entry and destroy the one we allocated.
assert(existingEntry && "spurious failure of strong compare-exchange?");
swift_cxx_deleteObject(allocatedEntry);
}
return { static_cast<SingletonMetadataCacheEntry*>(existingEntry), false };
}
EntryType *find(KeyType key) {
auto &init = key->getSingletonMetadataInitialization();
return static_cast<SingletonMetadataCacheEntry*>(
init.InitializationCache->Private.load(std::memory_order_acquire));
}
/// A default implementation for resolveEntry that assumes that the
/// key type is a lookup key for the map.
EntryType *resolveExistingEntry(KeyType key) {
auto entry = find(key);
assert(entry && "entry doesn't already exist!");
return entry;
}
};
class SingletonTypeMetadataCache
: public LockingConcurrentMap<SingletonMetadataCacheEntry,
SingletonMetadataCacheStorage> {
};
} // end anonymous namespace
/// The cache of all in-place metadata initializations.
static Lazy<SingletonTypeMetadataCache> SingletonMetadata;
MetadataResponse
swift::swift_getSingletonMetadata(MetadataRequest request,
const TypeContextDescriptor *description) {
auto result = SingletonMetadata.get().getOrInsert(description, request,
description);
return result.second;
}
/***************************************************************************/
/*** Objective-C class wrappers ********************************************/
/***************************************************************************/
#if SWIFT_OBJC_INTEROP
namespace {
class ObjCClassCacheEntry {
public:
FullMetadata<ObjCClassWrapperMetadata> Data;
ObjCClassCacheEntry(const ClassMetadata *theClass) {
Data.setKind(MetadataKind::ObjCClassWrapper);
Data.ValueWitnesses = &VALUE_WITNESS_SYM(BO);
Data.Class = theClass;
}
intptr_t getKeyIntValueForDump() {
return reinterpret_cast<intptr_t>(Data.Class);
}
bool matchesKey(const ClassMetadata *theClass) const {
return theClass == Data.Class;
}
friend llvm::hash_code hash_value(const ObjCClassCacheEntry &value) {
return llvm::hash_value(value.Data.Class);
}
static size_t getExtraAllocationSize(const ClassMetadata *key) {
return 0;
}
size_t getExtraAllocationSize() const {
return 0;
}
};
}
/// The uniquing structure for ObjC class-wrapper metadata.
static SimpleGlobalCache<ObjCClassCacheEntry, ObjCClassWrappersTag>
ObjCClassWrappers;
const Metadata *
swift::swift_getObjCClassMetadata(const ClassMetadata *theClass) {
// Make calls resilient against receiving a null Objective-C class. This can
// happen when classes are weakly linked and not available.
if (theClass == nullptr)
return nullptr;
// If the class pointer is valid as metadata, no translation is required.
if (theClass->isTypeMetadata()) {
return theClass;
}
return &ObjCClassWrappers.getOrInsert(theClass).first->Data;
}
const ClassMetadata *
swift::swift_getObjCClassFromMetadata(const Metadata *theMetadata) {
// We're not supposed to accept NULL, but older runtimes somehow did as a
// side effect of UB in dyn_cast, so we'll keep that going.
if (!theMetadata)
return nullptr;
// Unwrap ObjC class wrappers.
if (auto wrapper = dyn_cast<ObjCClassWrapperMetadata>(theMetadata)) {
return wrapper->Class;
}
// Otherwise, the input should already be a Swift class object.
auto theClass = cast<ClassMetadata>(theMetadata);
assert(theClass->isTypeMetadata());
return theClass;
}
const ClassMetadata *
swift::swift_getObjCClassFromMetadataConditional(const Metadata *theMetadata) {
// We're not supposed to accept NULL, but older runtimes somehow did as a
// side effect of UB in dyn_cast, so we'll keep that going.
if (!theMetadata)
return nullptr;
// If it's an ordinary class, return it.
if (auto theClass = dyn_cast<ClassMetadata>(theMetadata)) {
return theClass;
}
// Unwrap ObjC class wrappers.
if (auto wrapper = dyn_cast<ObjCClassWrapperMetadata>(theMetadata)) {
return wrapper->Class;
}
// Not an ObjC class after all.
return nil;
}
#endif
/***************************************************************************/
/*** Metadata and witness table packs **************************************/
/***************************************************************************/
namespace {
template<typename PackType>
class PackCacheEntry {
public:
size_t Count;
const PackType * const * getElements() const {
return reinterpret_cast<const PackType * const *>(this + 1);
}
const PackType ** getElements() {
return reinterpret_cast<const PackType **>(this + 1);
}
struct Key {
const PackType *const *Data;
const size_t Count;
size_t getCount() const {
return Count;
}
const PackType *getElement(size_t index) const {
assert(index < Count);
return Data[index];
}
friend llvm::hash_code hash_value(const Key &key) {
llvm::hash_code hash = 0;
for (size_t i = 0; i != key.getCount(); ++i)
hash = llvm::hash_combine(hash, key.getElement(i));
return hash;
}
};
PackCacheEntry(const Key &key);
intptr_t getKeyIntValueForDump() {
return 0; // No single meaningful value here.
}
bool matchesKey(const Key &key) const {
if (key.getCount() != Count)
return false;
for (unsigned i = 0; i != Count; ++i) {
if (key.getElement(i) != getElements()[i])
return false;
}
return true;
}
friend llvm::hash_code hash_value(const PackCacheEntry<PackType> &value) {
llvm::hash_code hash = 0;
for (size_t i = 0; i != value.Count; ++i)
hash = llvm::hash_combine(hash, value.getElements()[i]);
return hash;
}
static size_t getExtraAllocationSize(const Key &key) {
return getExtraAllocationSize(key.Count);
}
size_t getExtraAllocationSize() const {
return getExtraAllocationSize(Count);
}
static size_t getExtraAllocationSize(unsigned count) {
return count * sizeof(const Metadata * const *);
}
};
template<typename PackType>
PackCacheEntry<PackType>::PackCacheEntry(
const typename PackCacheEntry<PackType>::Key &key) {
Count = key.getCount();
for (unsigned i = 0; i < Count; ++i)
getElements()[i] = key.getElement(i);
}
} // end anonymous namespace
/// The uniquing structure for metadata packs.
static SimpleGlobalCache<PackCacheEntry<Metadata>,
MetadataPackTag> MetadataPacks;
SWIFT_RUNTIME_EXPORT SWIFT_CC(swift)
const Metadata * const *
swift_allocateMetadataPack(const Metadata * const *ptr, size_t count) {
if (MetadataPackPointer(reinterpret_cast<uintptr_t>(ptr)).getLifetime()
== PackLifetime::OnHeap)
return ptr;
PackCacheEntry<Metadata>::Key key{ptr, count};
auto bytes = MetadataPacks.getOrInsert(key).first->getElements();
MetadataPackPointer pack(bytes, PackLifetime::OnHeap);
assert(pack.getNumElements() == count);
return pack.getPointer();
}
/// The uniquing structure for witness table packs.
static SimpleGlobalCache<PackCacheEntry<WitnessTable>,
WitnessTablePackTag> WitnessTablePacks;
SWIFT_RUNTIME_EXPORT SWIFT_CC(swift)
const WitnessTable * const *
swift_allocateWitnessTablePack(const WitnessTable * const *ptr, size_t count) {
if (WitnessTablePackPointer(reinterpret_cast<uintptr_t>(ptr)).getLifetime()
== PackLifetime::OnHeap)
return ptr;
PackCacheEntry<WitnessTable>::Key key{ptr, count};
auto bytes = WitnessTablePacks.getOrInsert(key).first->getElements();
WitnessTablePackPointer pack(bytes, PackLifetime::OnHeap);
assert(pack.getNumElements() == count);
return pack.getPointer();
}
/***************************************************************************/
/*** Functions *************************************************************/
/***************************************************************************/
namespace {
class FunctionCacheEntry {
public:
FullMetadata<FunctionTypeMetadata> Data;
struct Key {
const FunctionTypeFlags Flags;
const FunctionMetadataDifferentiabilityKind DifferentiabilityKind;
const Metadata *const *Parameters;
const ::ParameterFlags *ParameterFlags;
const Metadata *Result;
const Metadata *GlobalActor;
const ExtendedFunctionTypeFlags ExtFlags;
const Metadata *ThrownError;
FunctionTypeFlags getFlags() const { return Flags; }
ExtendedFunctionTypeFlags getExtFlags() const { return ExtFlags; }
FunctionMetadataDifferentiabilityKind getDifferentiabilityKind() const {
return DifferentiabilityKind;
}
const Metadata *getParameter(unsigned index) const {
assert(index < Flags.getNumParameters());
return Parameters[index];
}
const Metadata *getResult() const { return Result; }
const ::ParameterFlags *getParameterFlags() const {
return ParameterFlags;
}
::ParameterFlags getParameterFlags(unsigned index) const {
assert(index < Flags.getNumParameters());
return Flags.hasParameterFlags() ? ParameterFlags[index] : ::ParameterFlags();
}
const Metadata *getGlobalActor() const { return GlobalActor; }
const Metadata *getThrownError() const { return ThrownError; }
friend llvm::hash_code hash_value(const Key &key) {
auto hash = llvm::hash_combine(
key.Flags.getIntValue(),
key.DifferentiabilityKind.getIntValue(),
key.Result, key.GlobalActor,
key.ExtFlags.getIntValue(), key.ThrownError);
for (unsigned i = 0, e = key.getFlags().getNumParameters(); i != e; ++i) {
hash = llvm::hash_combine(hash, key.getParameter(i));
hash = llvm::hash_combine(hash, key.getParameterFlags(i).getIntValue());
}
return hash;
}
};
FunctionCacheEntry(const Key &key);
intptr_t getKeyIntValueForDump() {
return 0; // No single meaningful value here.
}
bool matchesKey(const Key &key) const {
if (key.getFlags().getIntValue() != Data.Flags.getIntValue())
return false;
if (key.getDifferentiabilityKind().Value !=
Data.getDifferentiabilityKind().Value)
return false;
if (key.getResult() != Data.ResultType)
return false;
if (key.getGlobalActor() != Data.getGlobalActor())
return false;
if (key.getExtFlags().getIntValue() != Data.getExtendedFlags().getIntValue())
return false;
if (key.getThrownError() != Data.getThrownError())
return false;
for (unsigned i = 0, e = key.getFlags().getNumParameters(); i != e; ++i) {
if (key.getParameter(i) != Data.getParameter(i))
return false;
if (key.getParameterFlags(i).getIntValue() !=
Data.getParameterFlags(i).getIntValue())
return false;
}
return true;
}
friend llvm::hash_code hash_value(const FunctionCacheEntry &value) {
Key key = {value.Data.Flags, value.Data.getDifferentiabilityKind(),
value.Data.getParameters(), value.Data.getParameterFlags(),
value.Data.ResultType, value.Data.getGlobalActor(),
value.Data.getExtendedFlags(), value.Data.getThrownError()};
return hash_value(key);
}
static size_t getExtraAllocationSize(const Key &key) {
return getExtraAllocationSize(key.Flags, key.ExtFlags);
}
size_t getExtraAllocationSize() const {
return getExtraAllocationSize(Data.Flags, Data.getExtendedFlags());
}
static size_t getExtraAllocationSize(const FunctionTypeFlags &flags,
const ExtendedFunctionTypeFlags &extFlags) {
const auto numParams = flags.getNumParameters();
return FunctionTypeMetadata::additionalSizeToAlloc<
const Metadata *, ParameterFlags, FunctionMetadataDifferentiabilityKind,
FunctionGlobalActorMetadata, ExtendedFunctionTypeFlags,
FunctionThrownErrorMetadata>(numParams,
flags.hasParameterFlags() ? numParams : 0,
flags.isDifferentiable() ? 1 : 0,
flags.hasGlobalActor() ? 1 : 0,
flags.hasExtendedFlags() ? 1 : 0,
extFlags.isTypedThrows() ? 1 : 0);
}
};
} // end anonymous namespace
/// The uniquing structure for function type metadata.
static SimpleGlobalCache<FunctionCacheEntry, FunctionTypesTag> FunctionTypes;
const FunctionTypeMetadata *
swift::swift_getFunctionTypeMetadata0(FunctionTypeFlags flags,
const Metadata *result) {
assert(flags.getNumParameters() == 0
&& "wrong number of arguments in function metadata flags?!");
return swift_getFunctionTypeMetadata(flags, nullptr, nullptr, result);
}
const FunctionTypeMetadata *
swift::swift_getFunctionTypeMetadata1(FunctionTypeFlags flags,
const Metadata *arg0,
const Metadata *result) {
assert(flags.getNumParameters() == 1
&& "wrong number of arguments in function metadata flags?!");
const Metadata *parameters[] = { arg0 };
return swift_getFunctionTypeMetadata(flags, parameters, nullptr, result);
}
const FunctionTypeMetadata *
swift::swift_getFunctionTypeMetadata2(FunctionTypeFlags flags,
const Metadata *arg0,
const Metadata *arg1,
const Metadata *result) {
assert(flags.getNumParameters() == 2
&& "wrong number of arguments in function metadata flags?!");
const Metadata *parameters[] = { arg0, arg1 };
return swift_getFunctionTypeMetadata(flags, parameters, nullptr, result);
}
const FunctionTypeMetadata *
swift::swift_getFunctionTypeMetadata3(FunctionTypeFlags flags,
const Metadata *arg0,
const Metadata *arg1,
const Metadata *arg2,
const Metadata *result) {
assert(flags.getNumParameters() == 3
&& "wrong number of arguments in function metadata flags?!");
const Metadata *parameters[] = { arg0, arg1, arg2 };
return swift_getFunctionTypeMetadata(flags, parameters, nullptr, result);
}
const FunctionTypeMetadata *
swift::swift_getFunctionTypeMetadata(FunctionTypeFlags flags,
const Metadata *const *parameters,
const uint32_t *parameterFlags,
const Metadata *result) {
assert(!flags.isDifferentiable()
&& "Differentiable function type metadata should be obtained using "
"'swift_getFunctionTypeMetadataDifferentiable'");
assert(!flags.hasGlobalActor()
&& "Global actor function type metadata should be obtained using "
"'swift_getFunctionTypeMetadataGlobalActor'");
assert(!flags.hasExtendedFlags()
&& "Extended flags function type metadata should be obtained using "
"'swift_getExtendedFunctionTypeMetadata'");
FunctionCacheEntry::Key key = {
flags, FunctionMetadataDifferentiabilityKind::NonDifferentiable, parameters,
reinterpret_cast<const ParameterFlags *>(parameterFlags), result, nullptr,
ExtendedFunctionTypeFlags(), nullptr
};
return &FunctionTypes.getOrInsert(key).first->Data;
}
const FunctionTypeMetadata *
swift::swift_getFunctionTypeMetadataDifferentiable(
FunctionTypeFlags flags, FunctionMetadataDifferentiabilityKind diffKind,
const Metadata *const *parameters, const uint32_t *parameterFlags,
const Metadata *result) {
assert(!flags.hasGlobalActor()
&& "Global actor function type metadata should be obtained using "
"'swift_getFunctionTypeMetadataGlobalActor'");
assert(!flags.hasExtendedFlags()
&& "Extended flags function type metadata should be obtained using "
"'swift_getExtendedFunctionTypeMetadata'");
assert(flags.isDifferentiable());
assert(diffKind.isDifferentiable());
FunctionCacheEntry::Key key = {
flags, diffKind, parameters,
reinterpret_cast<const ParameterFlags *>(parameterFlags), result, nullptr,
ExtendedFunctionTypeFlags(), nullptr
};
return &FunctionTypes.getOrInsert(key).first->Data;
}
const FunctionTypeMetadata *
swift::swift_getFunctionTypeMetadataGlobalActor(
FunctionTypeFlags flags, FunctionMetadataDifferentiabilityKind diffKind,
const Metadata *const *parameters, const uint32_t *parameterFlags,
const Metadata *result, const Metadata *globalActor) {
assert(!flags.hasExtendedFlags()
&& "Extended flags function type metadata should be obtained using "
"'swift_getExtendedFunctionTypeMetadata'");
FunctionCacheEntry::Key key = {
flags, diffKind, parameters,
reinterpret_cast<const ParameterFlags *>(parameterFlags), result,
globalActor, ExtendedFunctionTypeFlags(), nullptr
};
return &FunctionTypes.getOrInsert(key).first->Data;
}
extern "C" const EnumDescriptor NOMINAL_TYPE_DESCR_SYM(s5NeverO);
extern "C" const ProtocolDescriptor PROTOCOL_DESCR_SYM(s5Error);
namespace {
/// Classification for a given thrown error type.
enum class ThrownErrorClassification {
/// An arbitrary thrown error.
Arbitrary,
/// 'Never', which means a function type is non-throwing.
Never,
/// 'any Error', which means the function type uses untyped throws.
AnyError,
};
/// Classify a thrown error type.
ThrownErrorClassification classifyThrownError(const Metadata *type) {
if (auto enumMetadata = dyn_cast<EnumMetadata>(type)) {
if (enumMetadata->getDescription() == &NOMINAL_TYPE_DESCR_SYM(s5NeverO))
return ThrownErrorClassification::Never;
} else if (auto existential = dyn_cast<ExistentialTypeMetadata>(type)) {
auto protocols = existential->getProtocols();
if (protocols.size() == 1 &&
!protocols[0].isObjC() &&
protocols[0].getSwiftProtocol() == &PROTOCOL_DESCR_SYM(s5Error) &&
!existential->isClassBounded() &&
!existential->isObjC())
return ThrownErrorClassification::AnyError;
}
return ThrownErrorClassification::Arbitrary;
}
}
const FunctionTypeMetadata *
swift::swift_getExtendedFunctionTypeMetadata(
FunctionTypeFlags flags, FunctionMetadataDifferentiabilityKind diffKind,
const Metadata *const *parameters, const uint32_t *parameterFlags,
const Metadata *result, const Metadata *globalActor,
ExtendedFunctionTypeFlags extFlags, const Metadata *thrownError) {
assert(flags.hasExtendedFlags() || extFlags.getIntValue() == 0);
assert(flags.hasExtendedFlags() || thrownError == nullptr);
if (thrownError) {
// Perform adjustments based on the given thrown error.
switch (classifyThrownError(thrownError)){
case ThrownErrorClassification::Arbitrary:
// Nothing to do.
break;
case ThrownErrorClassification::Never:
// The thrown error was 'Never', so make this a non-throwing function
flags = flags.withThrows(false);
// Fall through to clear out the error.
SWIFT_FALLTHROUGH;
case ThrownErrorClassification::AnyError:
// Clear out the thrown error and extended flags.
thrownError = nullptr;
extFlags = extFlags.withTypedThrows(false);
if (extFlags.getIntValue() == 0)
flags = flags.withExtendedFlags(false);
break;
}
}
FunctionCacheEntry::Key key = {
flags, diffKind, parameters,
reinterpret_cast<const ParameterFlags *>(parameterFlags), result,
globalActor, extFlags, thrownError
};
return &FunctionTypes.getOrInsert(key).first->Data;
}
FunctionCacheEntry::FunctionCacheEntry(const Key &key) {
auto flags = key.getFlags();
// Pick a value witness table appropriate to the function convention.
// All function types of a given convention have the same value semantics,
// so they share a value witness table.
switch (flags.getConvention()) {
case FunctionMetadataConvention::Swift:
if (!flags.isEscaping()) {
Data.ValueWitnesses = &VALUE_WITNESS_SYM(NOESCAPE_FUNCTION_MANGLING);
} else {
switch (key.getDifferentiabilityKind().Value) {
case FunctionMetadataDifferentiabilityKind::Reverse:
Data.ValueWitnesses = &VALUE_WITNESS_SYM(DIFF_FUNCTION_MANGLING);
break;
default:
swift_unreachable("unsupported function witness");
case FunctionMetadataDifferentiabilityKind::NonDifferentiable:
Data.ValueWitnesses = &VALUE_WITNESS_SYM(FUNCTION_MANGLING);
break;
}
}
break;
case FunctionMetadataConvention::Thin:
case FunctionMetadataConvention::CFunctionPointer:
Data.ValueWitnesses = &VALUE_WITNESS_SYM(THIN_FUNCTION_MANGLING);
break;
case FunctionMetadataConvention::Block:
#if SWIFT_OBJC_INTEROP
// Blocks are ObjC objects, so can share the AnyObject value
// witnesses (stored as "BO" rather than "yXl" for ABI compat).
Data.ValueWitnesses = &VALUE_WITNESS_SYM(BO);
#else
assert(false && "objc block without objc interop?");
#endif
break;
}
unsigned numParameters = flags.getNumParameters();
Data.setKind(MetadataKind::Function);
Data.Flags = flags;
Data.ResultType = key.getResult();
if (flags.hasGlobalActor())
*Data.getGlobalActorAddr() = key.getGlobalActor();
if (flags.isDifferentiable())
*Data.getDifferentiabilityKindAddress() = key.getDifferentiabilityKind();
if (flags.hasExtendedFlags()) {
auto extFlags = key.getExtFlags();
*Data.getExtendedFlagsAddr() = extFlags;
if (extFlags.isTypedThrows())
*Data.getThrownErrorAddr() = key.getThrownError();
}
for (unsigned i = 0; i < numParameters; ++i) {
Data.getParameters()[i] = key.getParameter(i);
if (flags.hasParameterFlags())
Data.getParameterFlags()[i] = key.getParameterFlags(i);
}
}
/***************************************************************************/
/*** Tuples ****************************************************************/
/***************************************************************************/
namespace {
class TupleCacheEntry
: public MetadataCacheEntryBase<TupleCacheEntry,
TupleTypeMetadata::Element> {
public:
static const char *getName() { return "TupleCache"; }
// NOTE: if you change the layout of this type, you'll also need
// to update tuple_getValueWitnesses().
unsigned ExtraInhabitantProvidingElement;
ValueWitnessTable Witnesses;
FullMetadata<TupleTypeMetadata> Data;
struct Key {
size_t NumElements;
const Metadata * const *Elements;
const char *Labels;
template <class Range>
static llvm::hash_code hash_value(Range elements, const char *labels) {
auto hash = llvm::hash_combine_range(elements.begin(), elements.end());
hash = llvm::hash_combine(hash, llvm::StringRef(labels));
return hash;
}
friend llvm::hash_code hash_value(const Key &key) {
auto elements =
llvm::ArrayRef<const Metadata *>(key.Elements, key.NumElements);
return hash_value(elements, key.Labels);
}
};
ValueType getValue() {
return &Data;
}
void setValue(ValueType value) {
assert(value == &Data);
}
TupleCacheEntry(const Key &key, MetadataWaitQueue::Worker &worker,
MetadataRequest request,
const ValueWitnessTable *proposedWitnesses);
AllocationResult allocate(const ValueWitnessTable *proposedWitnesses) {
swift_unreachable("allocated during construction");
}
MetadataStateWithDependency tryInitialize(Metadata *metadata,
PrivateMetadataState state,
PrivateMetadataCompletionContext *context);
MetadataStateWithDependency checkTransitiveCompleteness() {
auto dependency = ::checkTransitiveCompleteness(&Data);
return { dependency ? PrivateMetadataState::NonTransitiveComplete
: PrivateMetadataState::Complete,
dependency };
}
size_t getNumElements() const {
return Data.NumElements;
}
intptr_t getKeyIntValueForDump() {
return 0; // No single meaningful value
}
friend llvm::hash_code hash_value(const TupleCacheEntry &value) {
auto elements = llvm::ArrayRef<TupleTypeMetadata::Element>(
value.Data.getElements(), value.Data.NumElements);
auto types =
makeTransformRange(elements, [](TupleTypeMetadata::Element element) {
return element.Type;
});
return Key::hash_value(types, value.Data.Labels);
}
bool matchesKey(const Key &key) {
if (key.NumElements != Data.NumElements)
return false;
for (size_t i = 0, e = key.NumElements; i != e; ++i)
if (key.Elements[i] != Data.getElement(i).Type)
return false;
// It's unlikely that we'll get pointer-equality here unless we're being
// called from the same module or both label strings are null, but
// those are important cases.
if (key.Labels == Data.Labels)
return true;
if (!key.Labels || !Data.Labels)
return false;
return strcmp(key.Labels, Data.Labels) == 0;
}
size_t numTrailingObjects(OverloadToken<TupleTypeMetadata::Element>) const {
return getNumElements();
}
template <class... Args>
static size_t numTrailingObjects(OverloadToken<TupleTypeMetadata::Element>,
const Key &key,
Args &&...extraArgs) {
return key.NumElements;
}
};
class TupleCacheStorage :
public LockingConcurrentMapStorage<TupleCacheEntry, TupleCacheTag> {
public:
// FIXME: https://github.com/apple/swift/issues/43763.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
static TupleCacheEntry *
resolveExistingEntry(const TupleTypeMetadata *metadata) {
// The correctness of this arithmetic is verified by an assertion in
// the TupleCacheEntry constructor.
auto bytes = reinterpret_cast<const char*>(asFullMetadata(metadata));
bytes -= offsetof(TupleCacheEntry, Data);
auto entry = reinterpret_cast<const TupleCacheEntry*>(bytes);
return const_cast<TupleCacheEntry*>(entry);
}
#pragma clang diagnostic pop
};
class TupleCache :
public LockingConcurrentMap<TupleCacheEntry, TupleCacheStorage> {
};
} // end anonymous namespace
/// The uniquing structure for tuple type metadata.
static Lazy<TupleCache> TupleTypes;
/// Given a metatype pointer, produce the value-witness table for it.
/// This is equivalent to metatype->ValueWitnesses but more efficient.
static const ValueWitnessTable *tuple_getValueWitnesses(const Metadata *metatype) {
return asFullMetadata(metatype)->ValueWitnesses;
}
/// Generic tuple value witness for 'projectBuffer'.
template <bool IsPOD, bool IsInline>
static OpaqueValue *tuple_projectBuffer(ValueBuffer *buffer,
const Metadata *metatype) {
assert(IsPOD == tuple_getValueWitnesses(metatype)->isPOD());
assert(IsInline == tuple_getValueWitnesses(metatype)->isValueInline());
if (IsInline)
return reinterpret_cast<OpaqueValue*>(buffer);
auto wtable = tuple_getValueWitnesses(metatype);
unsigned alignMask = wtable->getAlignmentMask();
// Compute the byte offset of the object in the box.
unsigned byteOffset = (sizeof(HeapObject) + alignMask) & ~alignMask;
auto *bytePtr =
reinterpret_cast<char *>(*reinterpret_cast<HeapObject **>(buffer));
return reinterpret_cast<OpaqueValue *>(bytePtr + byteOffset);
}
/// Generic tuple value witness for 'allocateBuffer'
template <bool IsPOD, bool IsInline>
static OpaqueValue *tuple_allocateBuffer(ValueBuffer *buffer,
const Metadata *metatype) {
assert(IsPOD == tuple_getValueWitnesses(metatype)->isPOD());
assert(IsInline == tuple_getValueWitnesses(metatype)->isValueInline());
if (IsInline)
return reinterpret_cast<OpaqueValue*>(buffer);
BoxPair refAndValueAddr(swift_allocBox(metatype));
*reinterpret_cast<HeapObject **>(buffer) = refAndValueAddr.object;
return refAndValueAddr.buffer;
}
/// Generic tuple value witness for 'destroy'.
template <bool IsPOD, bool IsInline>
static void tuple_destroy(OpaqueValue *tuple, const Metadata *_metadata) {
auto &metadata = *(const TupleTypeMetadata*) _metadata;
assert(IsPOD == tuple_getValueWitnesses(&metadata)->isPOD());
assert(IsInline == tuple_getValueWitnesses(&metadata)->isValueInline());
if (IsPOD) return;
for (size_t i = 0, e = metadata.NumElements; i != e; ++i) {
auto &eltInfo = metadata.getElements()[i];
OpaqueValue *elt = eltInfo.findIn(tuple);
auto eltWitnesses = eltInfo.Type->getValueWitnesses();
eltWitnesses->destroy(elt, eltInfo.Type);
}
}
// The operation doesn't have to be initializeWithCopy, but they all
// have basically the same type.
typedef ValueWitnessTypes::initializeWithCopyUnsigned forEachOperation;
/// Perform an operation for each field of two tuples.
static OpaqueValue *tuple_forEachField(OpaqueValue *destTuple,
OpaqueValue *srcTuple,
const Metadata *_metatype,
forEachOperation operation) {
auto &metatype = *(const TupleTypeMetadata*) _metatype;
for (size_t i = 0, e = metatype.NumElements; i != e; ++i) {
auto &eltInfo = metatype.getElement(i);
OpaqueValue *destElt = eltInfo.findIn(destTuple);
OpaqueValue *srcElt = eltInfo.findIn(srcTuple);
operation(destElt, srcElt, eltInfo.Type);
}
return destTuple;
}
/// Perform a naive memcpy of src into dest.
static OpaqueValue *tuple_memcpy(OpaqueValue *dest,
OpaqueValue *src,
const Metadata *metatype) {
assert(metatype->getValueWitnesses()->isPOD());
return (OpaqueValue*)
memcpy(dest, src, metatype->getValueWitnesses()->getSize());
}
/// Generic tuple value witness for 'initializeWithCopy'.
template <bool IsPOD, bool IsInline>
static OpaqueValue *tuple_initializeWithCopy(OpaqueValue *dest,
OpaqueValue *src,
const Metadata *metatype) {
assert(IsPOD == tuple_getValueWitnesses(metatype)->isPOD());
assert(IsInline == tuple_getValueWitnesses(metatype)->isValueInline());
if (IsPOD) return tuple_memcpy(dest, src, metatype);
return tuple_forEachField(dest, src, metatype,
[](OpaqueValue *dest, OpaqueValue *src, const Metadata *eltType) {
return eltType->vw_initializeWithCopy(dest, src);
});
}
/// Generic tuple value witness for 'initializeWithTake'.
template <bool IsPOD, bool IsInline>
static OpaqueValue *tuple_initializeWithTake(OpaqueValue *dest,
OpaqueValue *src,
const Metadata *metatype) {
assert(IsPOD == tuple_getValueWitnesses(metatype)->isPOD());
assert(IsInline == tuple_getValueWitnesses(metatype)->isValueInline());
if (IsPOD) return tuple_memcpy(dest, src, metatype);
return tuple_forEachField(dest, src, metatype,
[](OpaqueValue *dest, OpaqueValue *src, const Metadata *eltType) {
return eltType->vw_initializeWithTake(dest, src);
});
}
/// Generic tuple value witness for 'assignWithCopy'.
template <bool IsPOD, bool IsInline>
static OpaqueValue *tuple_assignWithCopy(OpaqueValue *dest,
OpaqueValue *src,
const Metadata *metatype) {
assert(IsPOD == tuple_getValueWitnesses(metatype)->isPOD());
assert(IsInline == tuple_getValueWitnesses(metatype)->isValueInline());
if (IsPOD) return tuple_memcpy(dest, src, metatype);
return tuple_forEachField(dest, src, metatype,
[](OpaqueValue *dest, OpaqueValue *src, const Metadata *eltType) {
return eltType->vw_assignWithCopy(dest, src);
});
}
/// Generic tuple value witness for 'assignWithTake'.
template <bool IsPOD, bool IsInline>
static OpaqueValue *tuple_assignWithTake(OpaqueValue *dest,
OpaqueValue *src,
const Metadata *metatype) {
if (IsPOD) return tuple_memcpy(dest, src, metatype);
return tuple_forEachField(dest, src, metatype,
[](OpaqueValue *dest, OpaqueValue *src, const Metadata *eltType) {
return eltType->vw_assignWithTake(dest, src);
});
}
/// Generic tuple value witness for 'initializeBufferWithCopyOfBuffer'.
template <bool IsPOD, bool IsInline>
static OpaqueValue *tuple_initializeBufferWithCopyOfBuffer(ValueBuffer *dest,
ValueBuffer *src,
const Metadata *metatype) {
assert(IsPOD == tuple_getValueWitnesses(metatype)->isPOD());
assert(IsInline == tuple_getValueWitnesses(metatype)->isValueInline());
if (IsInline) {
return tuple_initializeWithCopy<IsPOD, IsInline>(
tuple_projectBuffer<IsPOD, IsInline>(dest, metatype),
tuple_projectBuffer<IsPOD, IsInline>(src, metatype), metatype);
}
auto *srcReference = *reinterpret_cast<HeapObject**>(src);
*reinterpret_cast<HeapObject**>(dest) = srcReference;
swift_retain(srcReference);
return tuple_projectBuffer<IsPOD, IsInline>(dest, metatype);
}
SWIFT_CC(swift)
static void tuple_storeExtraInhabitantTag(OpaqueValue *tuple,
unsigned tag,
unsigned xiCount,
const Metadata *_metatype) {
auto &metatype = *(const TupleTypeMetadata*) _metatype;
auto cacheEntry = TupleCacheStorage::resolveExistingEntry(&metatype);
auto &eltInfo =
metatype.getElement(cacheEntry->ExtraInhabitantProvidingElement);
assert(xiCount == eltInfo.Type->vw_getNumExtraInhabitants());
auto *elt = (OpaqueValue*)((uintptr_t)tuple + eltInfo.Offset);
assert(tag >= 1);
assert(tag <= xiCount);
eltInfo.Type->vw_storeEnumTagSinglePayload(elt, tag, xiCount);
}
SWIFT_CC(swift)
static unsigned tuple_getExtraInhabitantTag(const OpaqueValue *tuple,
unsigned xiCount,
const Metadata *_metatype) {
auto &metatype = *(const TupleTypeMetadata*) _metatype;
auto cacheEntry = TupleCacheStorage::resolveExistingEntry(&metatype);
auto &eltInfo =
metatype.getElement(cacheEntry->ExtraInhabitantProvidingElement);
assert(xiCount == eltInfo.Type->vw_getNumExtraInhabitants());
auto *elt = (const OpaqueValue*)((uintptr_t)tuple + eltInfo.Offset);
return eltInfo.Type->vw_getEnumTagSinglePayload(elt, xiCount);
}
template <bool IsPOD, bool IsInline>
static unsigned tuple_getEnumTagSinglePayload(const OpaqueValue *enumAddr,
unsigned numEmptyCases,
const Metadata *self) {
auto *witnesses = tuple_getValueWitnesses(self);
auto size = witnesses->getSize();
auto numExtraInhabitants = witnesses->getNumExtraInhabitants();
auto getExtraInhabitantTag = tuple_getExtraInhabitantTag;
return getEnumTagSinglePayloadImpl(enumAddr, numEmptyCases, self, size,
numExtraInhabitants,
getExtraInhabitantTag);
}
template <bool IsPOD, bool IsInline>
static void
tuple_storeEnumTagSinglePayload(OpaqueValue *enumAddr, unsigned whichCase,
unsigned numEmptyCases, const Metadata *self) {
auto *witnesses = tuple_getValueWitnesses(self);
auto size = witnesses->getSize();
auto numExtraInhabitants = witnesses->getNumExtraInhabitants();
auto storeExtraInhabitantTag = tuple_storeExtraInhabitantTag;
storeEnumTagSinglePayloadImpl(enumAddr, whichCase, numEmptyCases, self, size,
numExtraInhabitants, storeExtraInhabitantTag);
}
/// Various standard witness table for tuples.
static const ValueWitnessTable tuple_witnesses_pod_inline = {
#define WANT_ONLY_REQUIRED_VALUE_WITNESSES
#define VALUE_WITNESS(LOWER_ID, UPPER_ID) &tuple_##LOWER_ID<true, true>,
#define DATA_VALUE_WITNESS(LOWER_ID, UPPER_ID, TYPE)
#include "swift/ABI/ValueWitness.def"
0,
0,
ValueWitnessFlags(),
0
};
static const ValueWitnessTable tuple_witnesses_nonpod_inline = {
#define WANT_ONLY_REQUIRED_VALUE_WITNESSES
#define VALUE_WITNESS(LOWER_ID, UPPER_ID) &tuple_##LOWER_ID<false, true>,
#define DATA_VALUE_WITNESS(LOWER_ID, UPPER_ID, TYPE)
#include "swift/ABI/ValueWitness.def"
0,
0,
ValueWitnessFlags(),
0
};
static const ValueWitnessTable tuple_witnesses_pod_noninline = {
#define WANT_ONLY_REQUIRED_VALUE_WITNESSES
#define VALUE_WITNESS(LOWER_ID, UPPER_ID) &tuple_##LOWER_ID<true, false>,
#define DATA_VALUE_WITNESS(LOWER_ID, UPPER_ID, TYPE)
#include "swift/ABI/ValueWitness.def"
0,
0,
ValueWitnessFlags(),
0
};
static const ValueWitnessTable tuple_witnesses_nonpod_noninline = {
#define WANT_ONLY_REQUIRED_VALUE_WITNESSES
#define VALUE_WITNESS(LOWER_ID, UPPER_ID) &tuple_##LOWER_ID<false, false>,
#define DATA_VALUE_WITNESS(LOWER_ID, UPPER_ID, TYPE)
#include "swift/ABI/ValueWitness.def"
0,
0,
ValueWitnessFlags(),
0
};
static constexpr TypeLayout getInitialLayoutForValueType() {
return {0, 0, ValueWitnessFlags().withAlignment(1).withPOD(true), 0};
}
static constexpr TypeLayout getInitialLayoutForHeapObject() {
return {sizeof(HeapObject),
sizeof(HeapObject),
ValueWitnessFlags().withAlignment(alignof(HeapObject)),
0};
}
/// Perform basic sequential layout given a vector of metadata pointers,
/// calling a functor with the offset of each field, and returning the
/// final layout characteristics of the type.
///
/// GetLayoutFn should have signature:
/// const TypeLayout *(ElementType &type);
///
/// SetOffsetFn should have signature:
/// void (size_t index, ElementType &type, size_t offset)
template<typename ElementType, typename GetLayoutFn, typename SetOffsetFn>
static void performBasicLayout(TypeLayout &layout,
ElementType *elements,
size_t numElements,
GetLayoutFn &&getLayout,
SetOffsetFn &&setOffset) {
size_t size = layout.size;
size_t alignMask = layout.flags.getAlignmentMask();
bool isPOD = layout.flags.isPOD();
bool isBitwiseTakable = layout.flags.isBitwiseTakable();
for (unsigned i = 0; i != numElements; ++i) {
auto &elt = elements[i];
// Lay out this element.
const TypeLayout *eltLayout = getLayout(i, elt);
size = roundUpToAlignMask(size, eltLayout->flags.getAlignmentMask());
// Report this record to the functor.
setOffset(i, elt, size);
// Update the size and alignment of the aggregate..
size += eltLayout->size;
alignMask = std::max(alignMask, eltLayout->flags.getAlignmentMask());
if (!eltLayout->flags.isPOD()) isPOD = false;
if (!eltLayout->flags.isBitwiseTakable()) isBitwiseTakable = false;
}
bool isInline =
ValueWitnessTable::isValueInline(isBitwiseTakable, size, alignMask + 1);
layout.size = size;
layout.flags = ValueWitnessFlags()
.withAlignmentMask(alignMask)
.withPOD(isPOD)
.withBitwiseTakable(isBitwiseTakable)
.withInlineStorage(isInline);
layout.extraInhabitantCount = 0;
layout.stride = std::max(size_t(1), roundUpToAlignMask(size, alignMask));
}
size_t swift::swift_getTupleTypeLayout2(TypeLayout *result,
const TypeLayout *elt0,
const TypeLayout *elt1) {
const TypeLayout *elts[] = { elt0, elt1 };
uint32_t offsets[2];
swift_getTupleTypeLayout(result, offsets,
TupleTypeFlags().withNumElements(2), elts);
assert(offsets[0] == 0);
return offsets[1];
}
OffsetPair swift::swift_getTupleTypeLayout3(TypeLayout *result,
const TypeLayout *elt0,
const TypeLayout *elt1,
const TypeLayout *elt2) {
const TypeLayout *elts[] = { elt0, elt1, elt2 };
uint32_t offsets[3];
swift_getTupleTypeLayout(result, offsets,
TupleTypeFlags().withNumElements(3), elts);
assert(offsets[0] == 0);
return {offsets[1], offsets[2]};
}
void swift::swift_getTupleTypeLayout(TypeLayout *result,
uint32_t *elementOffsets,
TupleTypeFlags flags,
const TypeLayout * const *elements) {
*result = TypeLayout();
unsigned numExtraInhabitants = 0;
performBasicLayout(*result, elements, flags.getNumElements(),
[](size_t i, const TypeLayout *elt) { return elt; },
[elementOffsets, &numExtraInhabitants]
(size_t i, const TypeLayout *elt, size_t offset) {
if (elementOffsets)
elementOffsets[i] = uint32_t(offset);
numExtraInhabitants = std::max(numExtraInhabitants,
elt->getNumExtraInhabitants());
});
if (numExtraInhabitants > 0) {
*result = TypeLayout(result->size,
result->stride,
result->flags,
numExtraInhabitants);
}
}
MetadataResponse
swift::swift_getTupleTypeMetadata(MetadataRequest request,
TupleTypeFlags flags,
const Metadata * const *elements,
const char *labels,
const ValueWitnessTable *proposedWitnesses) {
auto numElements = flags.getNumElements();
// Bypass the cache for the empty tuple. We might reasonably get called
// by generic code, like a demangler that produces type objects.
if (numElements == 0)
return MetadataResponse{ &METADATA_SYM(EMPTY_TUPLE_MANGLING), MetadataState::Complete };
// Search the cache.
TupleCacheEntry::Key key = { numElements, elements, labels };
auto &cache = TupleTypes.get();
// If we have constant labels, directly check the cache.
if (!flags.hasNonConstantLabels())
return cache.getOrInsert(key, request, proposedWitnesses).second;
// If we have non-constant labels, we can't simply record the result.
// Look for an existing result, first.
if (auto response = cache.tryAwaitExisting(key, request))
return *response;
// Allocate a copy of the labels string within the tuple type allocator.
size_t labelsLen = strlen(labels);
size_t labelsAllocSize = roundUpToAlignment(labelsLen + 2, sizeof(void *));
char *newLabels =
(char *) MetadataAllocator(TupleCacheTag).Allocate(labelsAllocSize, alignof(char));
_swift_strlcpy(newLabels, labels, labelsAllocSize);
key.Labels = newLabels;
// Update the metadata cache.
auto result = cache.getOrInsert(key, request, proposedWitnesses).second;
// If we didn't manage to perform the insertion, free the memory associated
// with the copy of the labels: nobody else can reference it.
if (cast<TupleTypeMetadata>(result.Value)->Labels != newLabels) {
MetadataAllocator(TupleCacheTag).Deallocate(newLabels, labelsAllocSize, alignof(char));
}
// Done.
return result;
}
TupleCacheEntry::TupleCacheEntry(const Key &key,
MetadataWaitQueue::Worker &worker,
MetadataRequest request,
const ValueWitnessTable *proposedWitnesses)
: MetadataCacheEntryBase(worker, PrivateMetadataState::Abstract) {
Data.setKind(MetadataKind::Tuple);
Data.NumElements = key.NumElements;
Data.Labels = key.Labels;
// Stash the proposed witnesses in the value-witnesses slot for now.
Data.ValueWitnesses = proposedWitnesses;
for (size_t i = 0, e = key.NumElements; i != e; ++i)
Data.getElement(i).Type = key.Elements[i];
assert(TupleCacheStorage::resolveExistingEntry(&Data) == this);
}
MetadataStateWithDependency
TupleCacheEntry::tryInitialize(Metadata *metadata,
PrivateMetadataState state,
PrivateMetadataCompletionContext *context) {
// If we've already reached non-transitive completeness, just check that.
if (state == PrivateMetadataState::NonTransitiveComplete)
return checkTransitiveCompleteness();
// Otherwise, we must still be abstract, because tuples don't have an
// intermediate state between that and non-transitive completeness.
assert(state == PrivateMetadataState::Abstract);
bool allElementsTransitivelyComplete = true;
const Metadata *knownIncompleteElement = nullptr;
// Require all of the elements to be layout-complete.
for (size_t i = 0, e = Data.NumElements; i != e; ++i) {
auto request = MetadataRequest(MetadataState::LayoutComplete,
/*non-blocking*/ true);
auto eltType = Data.getElement(i).Type;
MetadataResponse response = swift_checkMetadataState(request, eltType);
// Immediately continue in the most common scenario, which is that
// the element is transitively complete.
if (response.State == MetadataState::Complete)
continue;
// If the metadata is not layout-complete, we have to suspend.
if (!isAtLeast(response.State, MetadataState::LayoutComplete))
return { PrivateMetadataState::Abstract,
MetadataDependency(eltType, MetadataState::LayoutComplete) };
// Remember that there's a non-fully-complete element.
allElementsTransitivelyComplete = false;
// Remember the first element that's not even non-transitively complete.
if (!knownIncompleteElement &&
!isAtLeast(response.State, MetadataState::NonTransitiveComplete))
knownIncompleteElement = eltType;
}
// Okay, we're going to succeed now.
// Reload the proposed witness from where we stashed them.
auto proposedWitnesses = Data.ValueWitnesses;
// Set the real value-witness table.
Data.ValueWitnesses = &Witnesses;
// Perform basic layout on the tuple.
auto layout = getInitialLayoutForValueType();
performBasicLayout(layout, Data.getElements(), Data.NumElements,
[](size_t i, const TupleTypeMetadata::Element &elt) {
return elt.getTypeLayout();
},
[](size_t i, TupleTypeMetadata::Element &elt, size_t offset) {
elt.Offset = offset;
});
Witnesses.size = layout.size;
Witnesses.flags = layout.flags;
Witnesses.stride = layout.stride;
// We have extra inhabitants if any element does.
// Pick the element with the most, favoring the earliest element in a tie.
unsigned extraInhabitantProvidingElement = ~0u;
unsigned numExtraInhabitants = 0;
for (unsigned i = 0, e = Data.NumElements; i < e; ++i) {
unsigned eltEI = Data.getElement(i).Type->getValueWitnesses()
->getNumExtraInhabitants();
if (eltEI > numExtraInhabitants) {
extraInhabitantProvidingElement = i;
numExtraInhabitants = eltEI;
}
}
Witnesses.extraInhabitantCount = numExtraInhabitants;
if (numExtraInhabitants > 0) {
ExtraInhabitantProvidingElement = extraInhabitantProvidingElement;
}
// Copy the function witnesses in, either from the proposed
// witnesses or from the standard table.
if (!proposedWitnesses) {
// Try to pattern-match into something better than the generic witnesses.
if (layout.flags.isInlineStorage() && layout.flags.isPOD()) {
if (numExtraInhabitants == 0
&& layout.size == 8
&& layout.flags.getAlignmentMask() == 7)
proposedWitnesses = &VALUE_WITNESS_SYM(Bi64_);
else if (numExtraInhabitants == 0
&& layout.size == 4
&& layout.flags.getAlignmentMask() == 3)
proposedWitnesses = &VALUE_WITNESS_SYM(Bi32_);
else if (numExtraInhabitants == 0
&& layout.size == 2
&& layout.flags.getAlignmentMask() == 1)
proposedWitnesses = &VALUE_WITNESS_SYM(Bi16_);
else if (numExtraInhabitants == 0 && layout.size == 1)
proposedWitnesses = &VALUE_WITNESS_SYM(Bi8_);
else
proposedWitnesses = &tuple_witnesses_pod_inline;
} else if (layout.flags.isInlineStorage()
&& !layout.flags.isPOD()) {
proposedWitnesses = &tuple_witnesses_nonpod_inline;
} else if (!layout.flags.isInlineStorage()
&& layout.flags.isPOD()) {
proposedWitnesses = &tuple_witnesses_pod_noninline;
} else {
assert(!layout.flags.isInlineStorage()
&& !layout.flags.isPOD());
proposedWitnesses = &tuple_witnesses_nonpod_noninline;
}
}
#define WANT_ONLY_REQUIRED_VALUE_WITNESSES
#define VALUE_WITNESS(LOWER_ID, UPPER_ID) \
Witnesses.LOWER_ID = proposedWitnesses->LOWER_ID;
#define DATA_VALUE_WITNESS(LOWER_ID, UPPER_ID, TYPE)
#include "swift/ABI/ValueWitness.def"
// Okay, we're all done with layout and setting up the elements.
// Check transitive completeness.
// We don't need to check the element statuses again in a couple of cases:
// - If all the elements are transitively complete, we are, too.
if (allElementsTransitivelyComplete)
return { PrivateMetadataState::Complete, MetadataDependency() };
// - If there was an incomplete element, wait for it to be become
// at least non-transitively complete.
if (knownIncompleteElement)
return { PrivateMetadataState::NonTransitiveComplete,
MetadataDependency(knownIncompleteElement,
MetadataState::NonTransitiveComplete) };
// Otherwise, we need to do a more expensive check.
return checkTransitiveCompleteness();
}
MetadataResponse
swift::swift_getTupleTypeMetadata2(MetadataRequest request,
const Metadata *elt0, const Metadata *elt1,
const char *labels,
const ValueWitnessTable *proposedWitnesses) {
const Metadata *elts[] = { elt0, elt1 };
return swift_getTupleTypeMetadata(request,
TupleTypeFlags().withNumElements(2),
elts, labels, proposedWitnesses);
}
MetadataResponse
swift::swift_getTupleTypeMetadata3(MetadataRequest request,
const Metadata *elt0, const Metadata *elt1,
const Metadata *elt2,
const char *labels,
const ValueWitnessTable *proposedWitnesses) {
const Metadata *elts[] = { elt0, elt1, elt2 };
return swift_getTupleTypeMetadata(request,
TupleTypeFlags().withNumElements(3),
elts, labels, proposedWitnesses);
}
/***************************************************************************/
/*** Nominal type descriptors **********************************************/
/***************************************************************************/
namespace {
/// A class encapsulating everything interesting about the identity of
/// a type context *except* the identity of the parent context.
class TypeContextIdentity {
StringRef Name;
public:
explicit TypeContextIdentity(const TypeContextDescriptor *type) {
Name = ParsedTypeIdentity::parse(type).FullIdentity;
}
bool operator==(const TypeContextIdentity &other) const {
return Name == other.Name;
}
friend llvm::hash_code hash_value(const TypeContextIdentity &value) {
return llvm::hash_value(value.Name);
}
};
}
bool swift::equalContexts(const ContextDescriptor *a,
const ContextDescriptor *b)
{
// Fast path: pointer equality.
if (a == b) return true;
// If either context is null, we're done.
if (a == nullptr || b == nullptr)
return false;
// If either descriptor is known to be unique, we're done.
if (a->isUnique() || b->isUnique()) return false;
// Do the kinds match?
if (a->getKind() != b->getKind()) return false;
// Do the parents match?
if (!equalContexts(a->Parent.get(), b->Parent.get()))
return false;
// Compare kind-specific details.
switch (auto kind = a->getKind()) {
case ContextDescriptorKind::Module: {
// Modules with the same name are equivalent.
auto moduleA = cast<ModuleContextDescriptor>(a);
auto moduleB = cast<ModuleContextDescriptor>(b);
return strcmp(moduleA->Name.get(), moduleB->Name.get()) == 0;
}
case ContextDescriptorKind::Extension:
case ContextDescriptorKind::Anonymous:
// These context kinds are always unique.
return false;
default:
// Types in the same context with the same name are equivalent.
if (kind >= ContextDescriptorKind::Type_First
&& kind <= ContextDescriptorKind::Type_Last) {
auto typeA = cast<TypeContextDescriptor>(a);
auto typeB = cast<TypeContextDescriptor>(b);
return TypeContextIdentity(typeA) == TypeContextIdentity(typeB);
}
// Otherwise, this runtime doesn't know anything about this context kind.
// Conservatively return false.
return false;
}
}
SWIFT_CC(swift)
bool swift::swift_compareTypeContextDescriptors(
const TypeContextDescriptor *a, const TypeContextDescriptor *b) {
a = swift_auth_data_non_address(
a, SpecialPointerAuthDiscriminators::TypeDescriptor);
b = swift_auth_data_non_address(
b, SpecialPointerAuthDiscriminators::TypeDescriptor);
// The implementation is the same as the implementation of
// swift::equalContexts except that the handling of non-type
// context descriptors and casts to TypeContextDescriptor are removed.
// Fast path: pointer equality.
if (a == b) return true;
// If either context is null, we're done.
if (a == nullptr || b == nullptr)
return false;
// If either descriptor is known to be unique, we're done.
if (a->isUnique() || b->isUnique()) return false;
// Do the kinds match?
if (a->getKind() != b->getKind()) return false;
// Do the parents match?
if (!equalContexts(a->Parent.get(), b->Parent.get()))
return false;
return TypeContextIdentity(a) == TypeContextIdentity(b);
}
/***************************************************************************/
/*** Common value witnesses ************************************************/
/***************************************************************************/
// Value witness methods for an arbitrary trivial type.
// The buffer operations assume that the value is stored indirectly, because
// installCommonValueWitnesses will install the direct equivalents instead.
namespace {
template<typename T>
struct pointer_function_cast_impl;
template<typename OutRet, typename...OutArgs>
struct pointer_function_cast_impl<OutRet * (*)(OutArgs *...)> {
template<typename InRet, typename...InArgs>
static constexpr auto perform(InRet * (*function)(InArgs *...))
-> OutRet * (*)(OutArgs *...)
{
static_assert(sizeof...(InArgs) == sizeof...(OutArgs),
"cast changed number of arguments");
return (OutRet *(*)(OutArgs *...))function;
}
};
template<typename...OutArgs>
struct pointer_function_cast_impl<void (*)(OutArgs *...)> {
template<typename...InArgs>
static constexpr auto perform(void (*function)(InArgs *...))
-> void (*)(OutArgs *...)
{
static_assert(sizeof...(InArgs) == sizeof...(OutArgs),
"cast changed number of arguments");
return (void (*)(OutArgs *...))function;
}
};
} // end anonymous namespace
/// Cast a function that takes all pointer arguments and returns to a
/// function type that takes different pointer arguments and returns.
/// In any reasonable calling convention the input and output function types
/// should be ABI-compatible.
template<typename Out, typename In>
static constexpr Out pointer_function_cast(In *function) {
return pointer_function_cast_impl<Out>::perform(function);
}
SWIFT_RUNTIME_STDLIB_SPI
OpaqueValue *_swift_pod_indirect_initializeBufferWithCopyOfBuffer(
ValueBuffer *dest, ValueBuffer *src, const Metadata *self) {
auto wtable = self->getValueWitnesses();
auto *srcReference = *reinterpret_cast<HeapObject**>(src);
*reinterpret_cast<HeapObject**>(dest) = srcReference;
swift_retain(srcReference);
// Project the address of the value in the buffer.
unsigned alignMask = wtable->getAlignmentMask();
// Compute the byte offset of the object in the box.
unsigned byteOffset = (sizeof(HeapObject) + alignMask) & ~alignMask;
auto *bytePtr = reinterpret_cast<char *>(srcReference);
return reinterpret_cast<OpaqueValue *>(bytePtr + byteOffset);
}
SWIFT_RUNTIME_STDLIB_SPI
void _swift_pod_destroy(OpaqueValue *object, const Metadata *self) {}
SWIFT_RUNTIME_STDLIB_SPI
OpaqueValue *_swift_pod_copy(OpaqueValue *dest, OpaqueValue *src,
const Metadata *self) {
memcpy(dest, src, self->getValueWitnesses()->size);
return dest;
}
SWIFT_RUNTIME_STDLIB_SPI
OpaqueValue *_swift_pod_direct_initializeBufferWithCopyOfBuffer(
ValueBuffer *dest, ValueBuffer *src, const Metadata *self) {
return _swift_pod_copy(reinterpret_cast<OpaqueValue *>(dest),
reinterpret_cast<OpaqueValue *>(src), self);
}
static constexpr uint64_t sizeWithAlignmentMask(uint64_t size,
uint64_t alignmentMask,
uint64_t hasExtraInhabitants) {
return (hasExtraInhabitants << 48) | (size << 16) | alignmentMask;
}
void swift::installCommonValueWitnesses(const TypeLayout &layout,
ValueWitnessTable *vwtable) {
auto flags = layout.flags;
if (flags.isPOD()) {
// Use POD value witnesses.
// If the value has a common size and alignment, use specialized value
// witnesses we already have lying around for the builtin types.
const ValueWitnessTable *commonVWT;
bool hasExtraInhabitants = layout.hasExtraInhabitants();
switch (sizeWithAlignmentMask(layout.size, flags.getAlignmentMask(),
hasExtraInhabitants)) {
default:
// For uncommon layouts, use value witnesses that work with an arbitrary
// size and alignment.
if (flags.isInlineStorage()) {
vwtable->initializeBufferWithCopyOfBuffer =
_swift_pod_direct_initializeBufferWithCopyOfBuffer;
} else {
vwtable->initializeBufferWithCopyOfBuffer =
_swift_pod_indirect_initializeBufferWithCopyOfBuffer;
}
vwtable->destroy = _swift_pod_destroy;
vwtable->initializeWithCopy = _swift_pod_copy;
vwtable->initializeWithTake = _swift_pod_copy;
vwtable->assignWithCopy = _swift_pod_copy;
vwtable->assignWithTake = _swift_pod_copy;
// getEnumTagSinglePayload and storeEnumTagSinglePayload are not
// interestingly optimizable based on POD-ness.
return;
case sizeWithAlignmentMask(1, 0, 0):
commonVWT = &VALUE_WITNESS_SYM(Bi8_);
break;
case sizeWithAlignmentMask(2, 1, 0):
commonVWT = &VALUE_WITNESS_SYM(Bi16_);
break;
case sizeWithAlignmentMask(4, 3, 0):
commonVWT = &VALUE_WITNESS_SYM(Bi32_);
break;
case sizeWithAlignmentMask(8, 7, 0):
commonVWT = &VALUE_WITNESS_SYM(Bi64_);
break;
case sizeWithAlignmentMask(16, 15, 0):
commonVWT = &VALUE_WITNESS_SYM(Bi128_);
break;
case sizeWithAlignmentMask(32, 31, 0):
commonVWT = &VALUE_WITNESS_SYM(Bi256_);
break;
case sizeWithAlignmentMask(64, 63, 0):
commonVWT = &VALUE_WITNESS_SYM(Bi512_);
break;
}
#define WANT_ONLY_REQUIRED_VALUE_WITNESSES
#define VALUE_WITNESS(LOWER_ID, UPPER_ID) \
vwtable->LOWER_ID = commonVWT->LOWER_ID;
#define DATA_VALUE_WITNESS(LOWER_ID, UPPER_ID, TYPE)
#include "swift/ABI/ValueWitness.def"
return;
}
if (flags.isBitwiseTakable()) {
// Use POD value witnesses for operations that do an initializeWithTake.
vwtable->initializeWithTake = _swift_pod_copy;
return;
}
}
/***************************************************************************/
/*** Structs ***************************************************************/
/***************************************************************************/
static ValueWitnessTable *getMutableVWTableForInit(StructMetadata *self,
StructLayoutFlags flags) {
auto oldTable = self->getValueWitnesses();
// If we can alter the existing table in-place, do so.
if (isValueWitnessTableMutable(flags))
return const_cast<ValueWitnessTable*>(oldTable);
// Otherwise, allocate permanent memory for it and copy the existing table.
void *memory = allocateMetadata(sizeof(ValueWitnessTable),
alignof(ValueWitnessTable));
auto newTable = ::new (memory) ValueWitnessTable(*oldTable);
// If we ever need to check layout-completeness asynchronously from
// initialization, we'll need this to be a store-release (and rely on
// consume ordering on the asynchronous check path); and we'll need to
// ensure that the current state says that the type is incomplete.
self->setValueWitnesses(newTable);
return newTable;
}
/// Initialize the value witness table and struct field offset vector for a
/// struct.
void swift::swift_initStructMetadata(StructMetadata *structType,
StructLayoutFlags layoutFlags,
size_t numFields,
const TypeLayout *const *fieldTypes,
uint32_t *fieldOffsets) {
auto layout = getInitialLayoutForValueType();
performBasicLayout(
layout, fieldTypes, numFields,
[&](size_t i, const TypeLayout *fieldType) { return fieldType; },
[&](size_t i, const TypeLayout *fieldType, uint32_t offset) {
assignUnlessEqual(fieldOffsets[i], offset);
});
// We have extra inhabitants if any element does. Use the field with the most.
unsigned extraInhabitantCount = 0;
for (unsigned i = 0; i < numFields; ++i) {
unsigned fieldExtraInhabitantCount =
fieldTypes[i]->getNumExtraInhabitants();
if (fieldExtraInhabitantCount > extraInhabitantCount) {
extraInhabitantCount = fieldExtraInhabitantCount;
}
}
auto vwtable = getMutableVWTableForInit(structType, layoutFlags);
layout.extraInhabitantCount = extraInhabitantCount;
// Substitute in better value witnesses if we have them.
installCommonValueWitnesses(layout, vwtable);
vwtable->publishLayout(layout);
}
void swift::swift_initStructMetadataWithLayoutString(
StructMetadata *structType, StructLayoutFlags layoutFlags, size_t numFields,
const uint8_t *const *fieldTypes, const uint8_t *fieldTags,
uint32_t *fieldOffsets) {
assert(structType->hasLayoutString());
auto layout = getInitialLayoutForValueType();
performBasicLayout(
layout, fieldTypes, numFields,
[&](size_t i, const uint8_t *fieldType) {
if (fieldTags[i]) {
return (const TypeLayout*)fieldType;
}
return ((const Metadata*)fieldType)->getTypeLayout();
},
[&](size_t i, const uint8_t *fieldType, uint32_t offset) {
assignUnlessEqual(fieldOffsets[i], offset);
});
// We have extra inhabitants if any element does. Use the field with the most.
unsigned extraInhabitantCount = 0;
// Compute total combined size of the layout string
size_t refCountBytes = 0;
for (unsigned i = 0; i < numFields; ++i) {
auto fieldTag = fieldTags[i];
if (fieldTag) {
if (fieldTag <= 0x4) {
refCountBytes += sizeof(uint64_t);
}
const TypeLayout *fieldType = (const TypeLayout*)fieldTypes[i];
unsigned fieldExtraInhabitantCount = fieldType->getNumExtraInhabitants();
if (fieldExtraInhabitantCount > extraInhabitantCount) {
extraInhabitantCount = fieldExtraInhabitantCount;
}
continue;
}
const Metadata *fieldType = (const Metadata*)fieldTypes[i];
unsigned fieldExtraInhabitantCount =
fieldType->vw_getNumExtraInhabitants();
if (fieldExtraInhabitantCount > extraInhabitantCount) {
extraInhabitantCount = fieldExtraInhabitantCount;
}
refCountBytes += _swift_refCountBytesForMetatype(fieldType);
}
const size_t fixedLayoutStringSize =
layoutStringHeaderSize + sizeof(uint64_t);
uint8_t *layoutStr =
(uint8_t *)MetadataAllocator(LayoutStringTag)
.Allocate(llvm::alignTo(fixedLayoutStringSize + refCountBytes,
sizeof(void *)),
alignof(uint8_t));
LayoutStringWriter writer{layoutStr, sizeof(uint64_t)};
writer.writeBytes(refCountBytes);
size_t fullOffset = 0;
size_t previousFieldOffset = 0;
LayoutStringFlags flags = LayoutStringFlags::Empty;
for (unsigned i = 0; i < numFields; ++i) {
size_t unalignedOffset = fullOffset;
auto fieldTag = fieldTags[i];
if (fieldTag) {
const TypeLayout *fieldType = (const TypeLayout*)fieldTypes[i];
auto alignmentMask = fieldType->flags.getAlignmentMask();
fullOffset = roundUpToAlignMask(fullOffset, alignmentMask);
if (fieldTag <= 0x4) {
size_t offset = fullOffset - unalignedOffset + previousFieldOffset;
auto tag = fieldTag <= 0x2 ? RefCountingKind::UnknownUnowned :
RefCountingKind::UnknownWeak;
auto tagAndOffset = ((uint64_t)tag << 56) | offset;
writer.writeBytes(tagAndOffset);
}
fullOffset += fieldType->size;
previousFieldOffset = fieldType->size - sizeof(uintptr_t);
continue;
}
const Metadata *fieldType = (const Metadata*)fieldTypes[i];
_swift_addRefCountStringForMetatype(writer, flags, fieldType, fullOffset,
previousFieldOffset);
}
writer.writeBytes((uint64_t)previousFieldOffset);
// we mask out HasRelativePointers, because at this point they have all been
// resolved to metadata pointers
writer.offset = 0;
writer.writeBytes(((uint64_t)flags) &
~((uint64_t)LayoutStringFlags::HasRelativePointers));
structType->setLayoutString(layoutStr);
auto *vwtable = getMutableVWTableForInit(structType, layoutFlags);
vwtable->destroy = swift_generic_destroy;
vwtable->initializeWithCopy = swift_generic_initWithCopy;
vwtable->initializeWithTake = swift_generic_initWithTake;
vwtable->assignWithCopy = swift_generic_assignWithCopy;
vwtable->assignWithTake = swift_generic_assignWithTake;
layout.extraInhabitantCount = extraInhabitantCount;
// Substitute in better value witnesses if we have them.
installCommonValueWitnesses(layout, vwtable);
vwtable->publishLayout(layout);
}
size_t swift::_swift_refCountBytesForMetatype(const Metadata *type) {
auto *vwt = type->getValueWitnesses();
if (type->vw_size() == 0 || vwt->isPOD()) {
return 0;
} else if (auto *tuple = dyn_cast<TupleTypeMetadata>(type)) {
size_t res = 0;
for (InProcess::StoredSize i = 0; i < tuple->NumElements; i++) {
res += _swift_refCountBytesForMetatype(tuple->getElement(i).Type);
}
return res;
} else if (vwt == &VALUE_WITNESS_SYM(Bo) ||
vwt == &VALUE_WITNESS_SYM(BO) ||
vwt == &VALUE_WITNESS_SYM(Bb)) {
return sizeof(uint64_t);
} else if (auto *cls = type->getClassObject()) {
if (cls->isTypeMetadata()) {
goto metadata;
}
return sizeof(uint64_t);
} else if (type->hasLayoutString()) {
size_t offset = sizeof(uint64_t);
return LayoutStringReader{type->getLayoutString(), offset}
.readBytes<size_t>();
} else if (type->isAnyExistentialType()) {
return sizeof(uint64_t);
} else {
metadata:
return sizeof(uint64_t) + sizeof(uintptr_t);
}
}
void swift::_swift_addRefCountStringForMetatype(LayoutStringWriter &writer,
LayoutStringFlags &flags,
const Metadata *fieldType,
size_t &fullOffset,
size_t &previousFieldOffset) {
size_t unalignedOffset = fullOffset;
fullOffset = roundUpToAlignMask(fullOffset, fieldType->vw_alignment() - 1);
size_t offset = fullOffset - unalignedOffset + previousFieldOffset;
auto *vwt = fieldType->getValueWitnesses();
if (fieldType->vw_size() == 0) {
return;
} else if (vwt->isPOD()) {
// No need to handle PODs
previousFieldOffset = offset + fieldType->vw_size();
fullOffset += fieldType->vw_size();
} else if (auto *tuple = dyn_cast<TupleTypeMetadata>(fieldType)) {
previousFieldOffset = offset;
for (InProcess::StoredSize i = 0; i < tuple->NumElements; i++) {
_swift_addRefCountStringForMetatype(writer, flags,
tuple->getElement(i).Type, fullOffset,
previousFieldOffset);
}
} else if (vwt == &VALUE_WITNESS_SYM(Bo)) {
auto tag = RefCountingKind::NativeStrong;
writer.writeBytes(((uint64_t)tag << 56) | offset);
previousFieldOffset = 0;
fullOffset += fieldType->vw_size();
} else if (vwt == &VALUE_WITNESS_SYM(BO)) {
#if SWIFT_OBJC_INTEROP
auto tag = RefCountingKind::ObjC;
#else
auto tag = RefCountingKind::Unknown;
#endif
writer.writeBytes(((uint64_t)tag << 56) | offset);
previousFieldOffset = 0;
fullOffset += fieldType->vw_size();
} else if (vwt == &VALUE_WITNESS_SYM(Bb)) {
auto tag = RefCountingKind::Bridge;
writer.writeBytes(((uint64_t)tag << 56) | offset);
previousFieldOffset = 0;
fullOffset += fieldType->vw_size();
} else if (auto *cls = fieldType->getClassObject()) {
RefCountingKind tag;
if (!cls->isTypeMetadata()) {
#if SWIFT_OBJC_INTEROP
tag = RefCountingKind::ObjC;
#else
tag = RefCountingKind::Unknown;
#endif
} else {
goto metadata;
}
writer.writeBytes(((uint64_t)tag << 56) | offset);
previousFieldOffset = 0;
fullOffset += fieldType->vw_size();
} else if (fieldType->hasLayoutString()) {
LayoutStringReader reader{fieldType->getLayoutString(), 0};
const auto fieldFlags = reader.readBytes<LayoutStringFlags>();
const auto fieldRefCountBytes = reader.readBytes<size_t>();
if (fieldRefCountBytes > 0) {
flags |= fieldFlags;
memcpy(writer.layoutStr + writer.offset,
reader.layoutStr + layoutStringHeaderSize, fieldRefCountBytes);
if (fieldFlags & LayoutStringFlags::HasRelativePointers) {
swift_resolve_resilientAccessors(writer.layoutStr, writer.offset,
reader.layoutStr + layoutStringHeaderSize, fieldType);
}
if (offset) {
LayoutStringReader tagReader {writer.layoutStr, writer.offset};
auto writerOffsetCopy = writer.offset;
auto firstTagAndOffset = tagReader.readBytes<uint64_t>();
firstTagAndOffset += offset;
writer.writeBytes(firstTagAndOffset);
writer.offset = writerOffsetCopy;
}
reader.offset = layoutStringHeaderSize + fieldRefCountBytes;
previousFieldOffset = reader.readBytes<uint64_t>();
writer.skip(fieldRefCountBytes);
} else {
previousFieldOffset += fieldType->vw_size();
}
fullOffset += fieldType->vw_size();
} else if (fieldType->isAnyExistentialType()) {
auto *existential = dyn_cast<ExistentialTypeMetadata>(fieldType);
assert(existential);
auto tag = existential->isClassBounded() ? RefCountingKind::Unknown
: RefCountingKind::Existential;
writer.writeBytes(((uint64_t)tag << 56) | offset);
previousFieldOffset = fieldType->vw_size() - (existential->isClassBounded() ? sizeof(uintptr_t) : (NumWords_ValueBuffer * sizeof(uintptr_t)));
fullOffset += fieldType->vw_size();
} else {
metadata:
writer.writeBytes(((uint64_t)RefCountingKind::Metatype << 56) | offset);
writer.writeBytes(fieldType);
previousFieldOffset = 0;
fullOffset += fieldType->vw_size();
}
}
/// Initialize the value witness table for a @_rawLayout struct.
SWIFT_RUNTIME_EXPORT
void swift::swift_initRawStructMetadata(StructMetadata *structType,
StructLayoutFlags layoutFlags,
const TypeLayout *likeTypeLayout,
int32_t count) {
auto vwtable = getMutableVWTableForInit(structType, layoutFlags);
// The existing vwt function entries are all fine to preserve, the only thing
// we need to initialize is the actual type layout.
auto size = likeTypeLayout->size;
auto stride = likeTypeLayout->stride;
auto alignMask = likeTypeLayout->flags.getAlignmentMask();
auto extraInhabitantCount = likeTypeLayout->extraInhabitantCount;
// If our count is greater than or equal 0, we're dealing an array like layout.
if (count >= 0) {
stride *= count;
size = stride;
}
vwtable->size = size;
vwtable->stride = stride;
vwtable->flags = ValueWitnessFlags()
.withAlignmentMask(alignMask)
.withCopyable(false);
vwtable->extraInhabitantCount = extraInhabitantCount;
}
/***************************************************************************/
/*** Classes ***************************************************************/
/***************************************************************************/
static MetadataAllocator &getResilientMetadataAllocator() {
// This should be constant-initialized, but this is safe.
static MetadataAllocator allocator(ResilientMetadataAllocatorTag);
return allocator;
}
ClassMetadata *
swift::swift_relocateClassMetadata(const ClassDescriptor *description,
const ResilientClassMetadataPattern *pattern) {
description = swift_auth_data_non_address(
description, SpecialPointerAuthDiscriminators::TypeDescriptor);
return _swift_relocateClassMetadata(description, pattern);
}
static ClassMetadata *
_swift_relocateClassMetadata(const ClassDescriptor *description,
const ResilientClassMetadataPattern *pattern) {
auto bounds = description->getMetadataBounds();
auto metadata = reinterpret_cast<ClassMetadata *>(
(char*) getResilientMetadataAllocator().Allocate(
bounds.getTotalSizeInBytes(), sizeof(void*)) +
bounds.getAddressPointInBytes());
auto fullMetadata = asFullMetadata(metadata);
char *rawMetadata = reinterpret_cast<char*>(metadata);
// Zero out the entire immediate-members section.
void **immediateMembers =
reinterpret_cast<void**>(rawMetadata + bounds.ImmediateMembersOffset);
memset(immediateMembers, 0, description->getImmediateMembersSize());
// Initialize the header:
// Heap destructor.
fullMetadata->destroy = pattern->Destroy.get();
// Value witness table.
#if SWIFT_OBJC_INTEROP
fullMetadata->ValueWitnesses =
(pattern->Flags & ClassFlags::UsesSwiftRefcounting)
? &VALUE_WITNESS_SYM(Bo)
: &VALUE_WITNESS_SYM(BO);
#else
fullMetadata->ValueWitnesses = &VALUE_WITNESS_SYM(Bo);
#endif
// MetadataKind / isa.
#if SWIFT_OBJC_INTEROP
metadata->setClassISA(pattern->Metaclass.get());
#else
metadata->setKind(MetadataKind::Class);
#endif
// Superclass.
metadata->Superclass = nullptr;
#if SWIFT_OBJC_INTEROP
// Cache data. Install the same initializer that the compiler is
// required to use. We don't need to do this in non-ObjC-interop modes.
metadata->CacheData[0] = &_objc_empty_cache;
metadata->CacheData[1] = nullptr;
#endif
// RO-data pointer.
#if SWIFT_OBJC_INTEROP
auto classRO = pattern->Data.get();
metadata->Data =
reinterpret_cast<uintptr_t>(classRO) | SWIFT_CLASS_IS_SWIFT_MASK;
#endif
// Class flags.
metadata->Flags = pattern->Flags;
// Instance layout.
metadata->InstanceAddressPoint = 0;
metadata->InstanceSize = 0;
metadata->InstanceAlignMask = 0;
// Reserved.
metadata->Reserved = 0;
// Class metadata layout.
metadata->ClassSize = bounds.getTotalSizeInBytes();
metadata->ClassAddressPoint = bounds.getAddressPointInBytes();
// Class descriptor.
metadata->setDescription(description);
// I-var destroyer.
metadata->IVarDestroyer = pattern->IVarDestroyer;
return metadata;
}
namespace {
/// The structure of ObjC class ivars as emitted by compilers.
struct ClassIvarEntry {
size_t *Offset;
const char *Name;
const char *Type;
uint32_t Log2Alignment;
uint32_t Size;
};
/// The structure of ObjC class ivar lists as emitted by compilers.
struct ClassIvarList {
uint32_t EntrySize;
uint32_t Count;
ClassIvarEntry *getIvars() {
return reinterpret_cast<ClassIvarEntry*>(this+1);
}
const ClassIvarEntry *getIvars() const {
return reinterpret_cast<const ClassIvarEntry*>(this+1);
}
};
/// The structure of ObjC class rodata as emitted by compilers.
struct ClassROData {
uint32_t Flags;
uint32_t InstanceStart;
uint32_t InstanceSize;
#if __POINTER_WIDTH__ == 64
uint32_t Reserved;
#endif
union {
const uint8_t *IvarLayout;
ClassMetadata *NonMetaClass;
};
const char *Name;
const void *MethodList;
const void *ProtocolList;
ClassIvarList *IvarList;
const uint8_t *WeakIvarLayout;
const void *PropertyList;
};
} // end anonymous namespace
#if SWIFT_OBJC_INTEROP
static uint32_t getLog2AlignmentFromMask(size_t alignMask) {
assert(((alignMask + 1) & alignMask) == 0 &&
"not an alignment mask!");
uint32_t log2 = 0;
while ((1 << log2) != (alignMask + 1))
++log2;
return log2;
}
static inline ClassROData *getROData(ClassMetadata *theClass) {
return (ClassROData*)(theClass->Data & ~uintptr_t(SWIFT_CLASS_IS_SWIFT_MASK));
}
// This gets called if we fail during copyGenericClassObjcName(). Its job is
// to generate a unique name, even though the name won't be very helpful if
// we end up looking at it in a debugger.
#define EMERGENCY_PREFIX "$SwiftEmergencyPlaceholderClassName"
static char *copyEmergencyName(ClassMetadata *theClass) {
char *nameBuf = nullptr;
asprintf(&nameBuf,
EMERGENCY_PREFIX "%016" PRIxPTR,
(uintptr_t)theClass);
return nameBuf;
}
static char *copyGenericClassObjCName(ClassMetadata *theClass) {
// Use the remangler to generate a mangled name from the type metadata.
Demangle::StackAllocatedDemangler<4096> Dem;
auto demangling = _swift_buildDemanglingForMetadata(theClass, Dem);
if (!demangling) {
return copyEmergencyName(theClass);
}
// Remangle that into a new type mangling string.
auto typeNode = Dem.createNode(Demangle::Node::Kind::TypeMangling);
typeNode->addChild(demangling, Dem);
auto globalNode = Dem.createNode(Demangle::Node::Kind::Global);
globalNode->addChild(typeNode, Dem);
auto mangling = Demangle::mangleNodeOld(globalNode, Dem);
if (!mangling.isSuccess()) {
return copyEmergencyName(theClass);
}
llvm::StringRef string = mangling.result();
// If the class is in the Swift module, add a $ to the end of the ObjC
// name. The old and new Swift libraries must be able to coexist in
// the same process, and this avoids warnings due to the ObjC names
// colliding.
bool addSuffix = string.starts_with("_TtGCs");
size_t allocationSize = string.size() + 1;
if (addSuffix)
allocationSize += 1;
auto fullNameBuf = (char*)swift_slowAlloc(allocationSize, 0);
memcpy(fullNameBuf, string.data(), string.size());
if (addSuffix) {
fullNameBuf[string.size()] = '$';
fullNameBuf[string.size() + 1] = '\0';
} else {
fullNameBuf[string.size()] = '\0';
}
return fullNameBuf;
}
static void initGenericClassObjCName(ClassMetadata *theClass) {
auto theMetaclass = (ClassMetadata *)object_getClass((id)theClass);
char *name = copyGenericClassObjCName(theClass);
getROData(theClass)->Name = name;
getROData(theMetaclass)->Name = name;
}
static bool installLazyClassNameHook() {
static objc_hook_lazyClassNamer oldHook;
auto myHook = [](Class theClass) -> const char * {
ClassMetadata *metadata = (ClassMetadata *)theClass;
if (metadata->isTypeMetadata())
return copyGenericClassObjCName(metadata);
return oldHook(theClass);
};
if (SWIFT_RUNTIME_WEAK_CHECK(objc_setHook_lazyClassNamer)) {
SWIFT_RUNTIME_WEAK_USE(objc_setHook_lazyClassNamer(myHook, &oldHook));
return true;
}
return false;
}
__attribute__((constructor)) SWIFT_RUNTIME_ATTRIBUTE_ALWAYS_INLINE static bool
supportsLazyObjcClassNames() {
return SWIFT_LAZY_CONSTANT(installLazyClassNameHook());
}
static void setUpGenericClassObjCName(ClassMetadata *theClass) {
if (supportsLazyObjcClassNames()) {
getROData(theClass)->Name = nullptr;
auto theMetaclass = (ClassMetadata *)object_getClass((id)theClass);
getROData(theMetaclass)->Name = nullptr;
getROData(theMetaclass)->NonMetaClass = theClass;
} else {
initGenericClassObjCName(theClass);
}
}
#endif
/// Initialize the invariant superclass components of a class metadata,
/// such as the generic type arguments, field offsets, and so on.
static void copySuperclassMetadataToSubclass(ClassMetadata *theClass,
ClassLayoutFlags layoutFlags) {
const ClassMetadata *theSuperclass = theClass->Superclass;
if (theSuperclass == nullptr)
return;
// If any ancestor classes have generic parameters, field offset vectors
// or virtual methods, inherit them.
//
// Note that the caller is responsible for installing overrides of
// superclass methods; here we just copy them verbatim.
auto ancestor = theSuperclass;
auto *classWords = reinterpret_cast<uintptr_t *>(theClass);
auto *superWords = reinterpret_cast<const uintptr_t *>(theSuperclass);
while (ancestor && ancestor->isTypeMetadata()) {
const auto *description = ancestor->getDescription();
// Copy the generic requirements.
if (description->isGeneric()
&& description->getGenericContextHeader().hasArguments()) {
// This should be okay even with variadic packs because we're
// copying from an existing metadata, so we've already uniqued.
auto genericOffset = description->getGenericArgumentOffset();
memcpy(classWords + genericOffset,
superWords + genericOffset,
description->getGenericContextHeader()
.getArgumentLayoutSizeInWords() * sizeof(uintptr_t));
}
// Copy the vtable entries.
if (description->hasVTable() && !hasStaticVTable(layoutFlags)) {
auto *vtable = description->getVTableDescriptor();
auto vtableOffset = vtable->getVTableOffset(description);
auto dest = classWords + vtableOffset;
auto src = superWords + vtableOffset;
#if SWIFT_PTRAUTH
auto descriptors = description->getMethodDescriptors();
for (size_t i = 0, e = vtable->VTableSize; i != e; ++i) {
swift_ptrauth_copy_code_or_data(
reinterpret_cast<void **>(&dest[i]),
reinterpret_cast<void *const *>(&src[i]),
descriptors[i].Flags.getExtraDiscriminator(),
!descriptors[i].Flags.isAsync(),
/*allowNull*/ true); // NULL allowed for VFE (methods in the vtable
// might be proven unused and null'ed)
}
#else
memcpy(dest, src, vtable->VTableSize * sizeof(uintptr_t));
#endif
}
// Copy the field offsets.
if (description->hasFieldOffsetVector()) {
unsigned fieldOffsetVector =
description->getFieldOffsetVectorOffset();
memcpy(classWords + fieldOffsetVector,
superWords + fieldOffsetVector,
description->NumFields * sizeof(uintptr_t));
}
ancestor = ancestor->Superclass;
}
#if SWIFT_OBJC_INTEROP
if (theClass->getDescription()->isGeneric() ||
(theSuperclass->isTypeMetadata() &&
theSuperclass->getDescription()->isGeneric())) {
// Set up the superclass of the metaclass, which is the metaclass of the
// superclass.
auto theMetaclass = (ClassMetadata *)object_getClass((id)theClass);
auto theSuperMetaclass
= (const ClassMetadata *)object_getClass(id_const_cast(theSuperclass));
theMetaclass->Superclass = theSuperMetaclass;
}
#endif
}
/// Using the information in the class context descriptor, fill in in the
/// immediate vtable entries for the class and install overrides of any
/// superclass vtable entries.
static void initClassVTable(ClassMetadata *self) {
const auto *description = self->getDescription();
auto *classWords = reinterpret_cast<void **>(self);
if (description->hasVTable()) {
auto *vtable = description->getVTableDescriptor();
auto vtableOffset = vtable->getVTableOffset(description);
auto descriptors = description->getMethodDescriptors();
for (unsigned i = 0, e = vtable->VTableSize; i < e; ++i) {
auto &methodDescription = descriptors[i];
swift_ptrauth_init_code_or_data(
&classWords[vtableOffset + i], methodDescription.getImpl(),
methodDescription.Flags.getExtraDiscriminator(),
!methodDescription.Flags.isAsync());
}
}
if (description->hasOverrideTable()) {
auto *overrideTable = description->getOverrideTable();
auto overrideDescriptors = description->getMethodOverrideDescriptors();
for (unsigned i = 0, e = overrideTable->NumEntries; i < e; ++i) {
auto &descriptor = overrideDescriptors[i];
// Get the base class and method.
auto *baseClass = cast_or_null<ClassDescriptor>(descriptor.Class.get());
auto *baseMethod = descriptor.Method.get();
// If the base method is null, it's an unavailable weak-linked
// symbol.
if (baseClass == nullptr || baseMethod == nullptr)
continue;
// Calculate the base method's vtable offset from the
// base method descriptor. The offset will be relative
// to the base class's vtable start offset.
auto baseClassMethods = baseClass->getMethodDescriptors();
// If the method descriptor doesn't land within the bounds of the
// method table, abort.
if (baseMethod < baseClassMethods.begin() ||
baseMethod >= baseClassMethods.end()) {
fatalError(0, "resilient vtable at %p contains out-of-bounds "
"method descriptor %p\n",
overrideTable, baseMethod);
}
// Install the method override in our vtable.
auto baseVTable = baseClass->getVTableDescriptor();
auto offset = (baseVTable->getVTableOffset(baseClass) +
(baseMethod - baseClassMethods.data()));
swift_ptrauth_init_code_or_data(&classWords[offset],
descriptor.getImpl(),
baseMethod->Flags.getExtraDiscriminator(),
!baseMethod->Flags.isAsync());
}
}
}
static void initClassFieldOffsetVector(ClassMetadata *self,
size_t numFields,
const TypeLayout * const *fieldTypes,
size_t *fieldOffsets) {
// Start layout by appending to a standard heap object header.
size_t size, alignMask;
#if SWIFT_OBJC_INTEROP
ClassROData *rodata = getROData(self);
#endif
// If we have a superclass, start from its size and alignment instead.
if (classHasSuperclass(self)) {
auto *super = self->Superclass;
// This is straightforward if the superclass is Swift.
#if SWIFT_OBJC_INTEROP
if (super->isTypeMetadata()) {
#endif
size = super->getInstanceSize();
alignMask = super->getInstanceAlignMask();
#if SWIFT_OBJC_INTEROP
// If it's Objective-C, start layout from our static notion of
// where the superclass starts. Objective-C expects us to have
// generated a correct ivar layout, which it will simply slide if
// it needs to.
} else {
size = rodata->InstanceStart;
alignMask = 0xF; // malloc alignment guarantee
}
#endif
// If we don't have a formal superclass, start with the basic heap header.
} else {
auto heapLayout = getInitialLayoutForHeapObject();
size = heapLayout.size;
alignMask = heapLayout.flags.getAlignmentMask();
}
#if SWIFT_OBJC_INTEROP
// Ensure that Objective-C does layout starting from the right
// offset. This needs to exactly match the superclass rodata's
// InstanceSize in cases where the compiler decided that we didn't
// really have a resilient ObjC superclass, because the compiler
// might hardcode offsets in that case, so we can't slide ivars.
// Fortunately, the cases where that happens are exactly the
// situations where our entire superclass hierarchy is defined
// in Swift. (But note that ObjC might think we have a superclass
// even if Swift doesn't, because of SwiftObject.)
//
// The rodata may be in read-only memory if the compiler knows that the size
// it generates is already definitely correct. Don't write to this value
// unless it's necessary. We'll grow the space for the superclass if needed,
// but not shrink it, as the compiler may write an unaligned size that's less
// than our aligned InstanceStart.
if (rodata->InstanceStart < size)
rodata->InstanceStart = size;
else
size = rodata->InstanceStart;
#endif
// Okay, now do layout.
for (unsigned i = 0; i != numFields; ++i) {
auto *eltLayout = fieldTypes[i];
// Skip empty fields.
if (fieldOffsets[i] == 0 && eltLayout->size == 0)
continue;
auto offset = roundUpToAlignMask(size,
eltLayout->flags.getAlignmentMask());
fieldOffsets[i] = offset;
size = offset + eltLayout->size;
alignMask = std::max(alignMask, eltLayout->flags.getAlignmentMask());
}
// Save the final size and alignment into the metadata record.
assert(self->isTypeMetadata());
self->setInstanceSize(size);
self->setInstanceAlignMask(alignMask);
#if SWIFT_OBJC_INTEROP
// Save the size into the Objective-C metadata as well.
if (rodata->InstanceSize != size)
rodata->InstanceSize = size;
#endif
}
#if SWIFT_OBJC_INTEROP
/// Non-generic classes only. Initialize the Objective-C ivar descriptors and
/// field offset globals. Does *not* register the class with the Objective-C
/// runtime; that must be done by the caller.
///
/// This function copies the ivar descriptors and updates each ivar global with
/// the corresponding offset in \p fieldOffsets, before asking the Objective-C
/// runtime to realize the class. The Objective-C runtime will then slide the
/// offsets stored in those globals.
///
/// Note that \p fieldOffsets remains unchanged in this case.
static void initObjCClass(ClassMetadata *self,
size_t numFields,
const TypeLayout * const *fieldTypes,
size_t *fieldOffsets) {
ClassROData *rodata = getROData(self);
ClassIvarList *ivars = rodata->IvarList;
if (!ivars) {
assert(numFields == 0);
return;
}
assert(ivars->Count == numFields);
assert(ivars->EntrySize == sizeof(ClassIvarEntry));
bool copiedIvarList = false;
for (unsigned i = 0; i != numFields; ++i) {
auto *eltLayout = fieldTypes[i];
ClassIvarEntry *ivar = &ivars->getIvars()[i];
// Fill in the field offset global, if this ivar has one.
if (ivar->Offset) {
if (*ivar->Offset != fieldOffsets[i])
*ivar->Offset = fieldOffsets[i];
}
// If the ivar's size doesn't match the field layout we
// computed, overwrite it and give it better type information.
if (ivar->Size != eltLayout->size) {
// If we're going to modify the ivar list, we need to copy it first.
if (!copiedIvarList) {
auto ivarListSize = sizeof(ClassIvarList) +
numFields * sizeof(ClassIvarEntry);
ivars = (ClassIvarList*) getResilientMetadataAllocator()
.Allocate(ivarListSize, alignof(ClassIvarList));
memcpy(ivars, rodata->IvarList, ivarListSize);
rodata->IvarList = ivars;
copiedIvarList = true;
// Update ivar to point to the newly copied list.
ivar = &ivars->getIvars()[i];
}
ivar->Size = eltLayout->size;
ivar->Type = nullptr;
ivar->Log2Alignment =
getLog2AlignmentFromMask(eltLayout->flags.getAlignmentMask());
}
}
}
/// Generic classes only. Initialize the Objective-C ivar descriptors and field
/// offset globals and register the class with the runtime.
///
/// This function copies the ivar descriptors and points each ivar offset at the
/// corresponding entry in \p fieldOffsets, before asking the Objective-C
/// runtime to realize the class. The Objective-C runtime will then slide the
/// offsets in \p fieldOffsets.
static MetadataDependency
initGenericObjCClass(ClassMetadata *self, size_t numFields,
const TypeLayout * const *fieldTypes,
size_t *fieldOffsets) {
// If the class is generic, we need to give it a name for Objective-C.
setUpGenericClassObjCName(self);
ClassROData *rodata = getROData(self);
// In ObjC interop mode, we have up to two places we need each correct
// ivar offset to end up:
//
// - the global ivar offset in the RO-data; this should only exist
// if the class layout (up to this ivar) is not actually dependent
//
// - the field offset vector (fieldOffsets)
//
// When we ask the ObjC runtime to lay out this class, we need the
// RO-data to point to the field offset vector, even if the layout
// is not dependent. The RO-data is not shared between
// instantiations, but the global ivar offset is (by definition).
// If the compiler didn't have the correct static size for the
// superclass (i.e. if rodata->InstanceStart is wrong), a previous
// instantiation might have already slid the global offset to the
// correct place; we need the ObjC runtime to see a pre-slid value,
// and it's not safe to briefly unslide it and let the runtime slide
// it back because there might already be concurrent code relying on
// the global ivar offset.
//
// So we need to the remember the addresses of the global ivar offsets.
// We use this lazily-filled array to do so.
const unsigned NumInlineGlobalIvarOffsets = 8;
size_t *_inlineGlobalIvarOffsets[NumInlineGlobalIvarOffsets];
size_t **_globalIvarOffsets = nullptr;
auto getGlobalIvarOffsets = [&]() -> size_t** {
if (!_globalIvarOffsets) {
if (numFields <= NumInlineGlobalIvarOffsets) {
_globalIvarOffsets = _inlineGlobalIvarOffsets;
// Make sure all the entries start out null.
memset(_globalIvarOffsets, 0, numFields * sizeof(size_t *));
} else {
_globalIvarOffsets =
static_cast<size_t **>(calloc(numFields, sizeof(size_t *)));
}
}
return _globalIvarOffsets;
};
// Always clone the ivar descriptors.
if (numFields) {
const ClassIvarList *dependentIvars = rodata->IvarList;
assert(dependentIvars->Count == numFields);
assert(dependentIvars->EntrySize == sizeof(ClassIvarEntry));
auto ivarListSize = sizeof(ClassIvarList) +
numFields * sizeof(ClassIvarEntry);
auto ivars = (ClassIvarList*) getResilientMetadataAllocator()
.Allocate(ivarListSize, alignof(ClassIvarList));
memcpy(ivars, dependentIvars, ivarListSize);
rodata->IvarList = ivars;
for (unsigned i = 0; i != numFields; ++i) {
auto *eltLayout = fieldTypes[i];
ClassIvarEntry &ivar = ivars->getIvars()[i];
// Remember the global ivar offset if present.
if (ivar.Offset) {
getGlobalIvarOffsets()[i] = ivar.Offset;
}
// Change the ivar offset to point to the respective entry of
// the field-offset vector, as discussed above.
ivar.Offset = &fieldOffsets[i];
// If the ivar's size doesn't match the field layout we
// computed, overwrite it and give it better type information.
if (ivar.Size != eltLayout->size) {
ivar.Size = eltLayout->size;
ivar.Type = nullptr;
ivar.Log2Alignment =
getLog2AlignmentFromMask(eltLayout->flags.getAlignmentMask());
}
}
}
// Register this class with the runtime. This will also cause the
// runtime to slide the entries in the field offset vector.
swift_instantiateObjCClass(self);
// If we saved any global ivar offsets, make sure we write back to them.
if (_globalIvarOffsets) {
for (unsigned i = 0; i != numFields; ++i) {
if (!_globalIvarOffsets[i]) continue;
// To avoid dirtying memory, only write to the global ivar
// offset if it's actually wrong.
if (*_globalIvarOffsets[i] != fieldOffsets[i])
*_globalIvarOffsets[i] = fieldOffsets[i];
}
// Free the out-of-line if we allocated one.
if (_globalIvarOffsets != _inlineGlobalIvarOffsets) {
free(_globalIvarOffsets);
}
}
return MetadataDependency();
}
#endif
SWIFT_CC(swift)
SWIFT_RUNTIME_STDLIB_INTERNAL MetadataResponse
getSuperclassMetadata(MetadataRequest request, const ClassMetadata *self) {
// If there is a mangled superclass name, demangle it to the superclass
// type.
if (auto superclassNameBase = self->getDescription()->SuperclassType.get()) {
StringRef superclassName =
Demangle::makeSymbolicMangledNameStringRef(superclassNameBase);
SubstGenericParametersFromMetadata substitutions(self);
auto result = swift_getTypeByMangledName(
request, superclassName, substitutions.getGenericArgs(),
[&substitutions](unsigned depth, unsigned index) {
return substitutions.getMetadata(depth, index).Ptr;
},
[&substitutions](const Metadata *type, unsigned index) {
return substitutions.getWitnessTable(type, index);
});
if (auto *error = result.getError()) {
fatalError(
0, "failed to demangle superclass of %s from mangled name '%s': %s\n",
self->getDescription()->Name.get(), superclassName.str().c_str(),
error->copyErrorString());
}
return result.getType().getResponse();
} else {
return MetadataResponse();
}
}
SWIFT_CC(swift)
static std::pair<MetadataDependency, const ClassMetadata *>
getSuperclassMetadata(ClassMetadata *self, bool allowDependency) {
MetadataRequest request(allowDependency ? MetadataState::NonTransitiveComplete
: /*FIXME*/ MetadataState::Abstract,
/*non-blocking*/ allowDependency);
auto response = getSuperclassMetadata(request, self);
auto *superclass = response.Value;
if (!superclass)
return {MetadataDependency(), nullptr};
const ClassMetadata *second;
#if SWIFT_OBJC_INTEROP
if (auto objcWrapper = dyn_cast<ObjCClassWrapperMetadata>(superclass)) {
second = objcWrapper->Class;
} else {
second = cast<ClassMetadata>(superclass);
}
#else
second = cast<ClassMetadata>(superclass);
#endif
// If the request isn't satisfied, we have a new dependency.
if (!request.isSatisfiedBy(response.State)) {
assert(allowDependency);
return {MetadataDependency(superclass, request.getState()), second};
}
return {MetadataDependency(), second};
}
static SWIFT_CC(swift) MetadataDependency
_swift_initClassMetadataImpl(ClassMetadata *self,
ClassLayoutFlags layoutFlags,
size_t numFields,
const TypeLayout * const *fieldTypes,
size_t *fieldOffsets,
bool allowDependency) {
// Try to install the superclass.
auto superDependencyAndSuper = getSuperclassMetadata(self, allowDependency);
if (superDependencyAndSuper.first)
return superDependencyAndSuper.first;
auto super = superDependencyAndSuper.second;
self->Superclass = super;
#if SWIFT_OBJC_INTEROP
// Set the superclass to SwiftObject if this is a root class.
if (!super)
self->Superclass = getRootSuperclass();
// Register our custom implementation of class_getImageName.
static swift::once_t onceToken;
swift::once(
onceToken,
[](void *unused) {
(void)unused;
setUpObjCRuntimeGetImageNameFromClass();
},
nullptr);
#endif
// Copy field offsets, generic arguments and (if necessary) vtable entries
// from our superclass.
copySuperclassMetadataToSubclass(self, layoutFlags);
// Copy the class's immediate methods from the nominal type descriptor
// to the class metadata.
if (!hasStaticVTable(layoutFlags))
initClassVTable(self);
initClassFieldOffsetVector(self, numFields, fieldTypes, fieldOffsets);
#if SWIFT_OBJC_INTEROP
auto *description = self->getDescription();
if (description->isGeneric()) {
assert(!description->hasObjCResilientClassStub());
initGenericObjCClass(self, numFields, fieldTypes, fieldOffsets);
} else {
initObjCClass(self, numFields, fieldTypes, fieldOffsets);
// Register this class with the runtime. This will also cause the
// runtime to slide the field offsets stored in the field offset
// globals. Note that the field offset vector is *not* updated;
// however we should not be using it for anything in a non-generic
// class.
auto *stub = description->getObjCResilientClassStub();
// On a new enough runtime, register the class as a replacement for
// its stub if we have one, which attaches any categories referencing
// the stub.
//
// On older runtimes, just register the class via the usual mechanism.
// The compiler enforces that @objc methods in extensions of classes
// with resilient ancestry have the correct availability, so it should
// be safe to ignore the stub in this case.
if (stub != nullptr && SWIFT_RUNTIME_WEAK_CHECK(_objc_realizeClassFromSwift)) {
SWIFT_RUNTIME_WEAK_USE(_objc_realizeClassFromSwift((Class) self, const_cast<void *>(stub)));
} else {
swift_instantiateObjCClass(self);
}
}
#else
assert(!self->getDescription()->hasObjCResilientClassStub());
#endif
return MetadataDependency();
}
void swift::swift_initClassMetadata(ClassMetadata *self,
ClassLayoutFlags layoutFlags,
size_t numFields,
const TypeLayout * const *fieldTypes,
size_t *fieldOffsets) {
(void) _swift_initClassMetadataImpl(self, layoutFlags, numFields,
fieldTypes, fieldOffsets,
/*allowDependency*/ false);
}
MetadataDependency
swift::swift_initClassMetadata2(ClassMetadata *self,
ClassLayoutFlags layoutFlags,
size_t numFields,
const TypeLayout * const *fieldTypes,
size_t *fieldOffsets) {
return _swift_initClassMetadataImpl(self, layoutFlags, numFields,
fieldTypes, fieldOffsets,
/*allowDependency*/ true);
}
#if SWIFT_OBJC_INTEROP
static SWIFT_CC(swift) MetadataDependency
_swift_updateClassMetadataImpl(ClassMetadata *self,
ClassLayoutFlags layoutFlags,
size_t numFields,
const TypeLayout * const *fieldTypes,
size_t *fieldOffsets,
bool allowDependency) {
bool requiresUpdate = SWIFT_RUNTIME_WEAK_CHECK(_objc_realizeClassFromSwift);
// If we're on a newer runtime, we're going to be initializing the
// field offset vector. Realize the superclass metadata first, even
// though our superclass field references it statically.
auto superDependencyAndSuper = getSuperclassMetadata(self, allowDependency);
if (superDependencyAndSuper.first)
return superDependencyAndSuper.first;
const ClassMetadata *super = superDependencyAndSuper.second;
// Check that it matches what's already in there.
if (!super)
assert(self->Superclass == getRootSuperclass());
else
assert(self->Superclass == super);
(void) super;
// If we're running on a older Objective-C runtime, just realize
// the class.
if (!requiresUpdate) {
// If we don't have a backward deployment layout, we cannot proceed here.
if (self->getInstanceSize() == 0 ||
self->getInstanceAlignMask() == 0) {
fatalError(0, "class %s does not have a fragile layout; "
"the deployment target was newer than this OS\n",
self->getDescription()->Name.get());
}
// Realize the class. This causes the runtime to slide the field offsets
// stored in the field offset globals.
//
// Note that the field offset vector is *not* updated; however in
// Objective-C interop mode, we don't actually use the field offset vector
// of non-generic classes.
//
// In particular, class mirrors always use the Objective-C ivar descriptors,
// which point at field offset globals and not the field offset vector.
swift_getInitializedObjCClass((Class)self);
} else {
// Update the field offset vector using runtime type information; the layout
// of resilient types might be different than the statically-emitted layout.
initClassFieldOffsetVector(self, numFields, fieldTypes, fieldOffsets);
// Copy field offset vector entries to the field offset globals.
initObjCClass(self, numFields, fieldTypes, fieldOffsets);
// See remark above about how this slides field offset globals.
SWIFT_RUNTIME_WEAK_USE(_objc_realizeClassFromSwift((Class)self, (Class)self));
}
return MetadataDependency();
}
void swift::swift_updateClassMetadata(ClassMetadata *self,
ClassLayoutFlags layoutFlags,
size_t numFields,
const TypeLayout * const *fieldTypes,
size_t *fieldOffsets) {
(void) _swift_updateClassMetadataImpl(self, layoutFlags, numFields,
fieldTypes, fieldOffsets,
/*allowDependency*/ false);
}
MetadataDependency
swift::swift_updateClassMetadata2(ClassMetadata *self,
ClassLayoutFlags layoutFlags,
size_t numFields,
const TypeLayout * const *fieldTypes,
size_t *fieldOffsets) {
return _swift_updateClassMetadataImpl(self, layoutFlags, numFields,
fieldTypes, fieldOffsets,
/*allowDependency*/ true);
}
#endif
#ifndef NDEBUG
static bool isAncestorOf(const ClassMetadata *metadata,
const ClassDescriptor *description) {
auto ancestor = metadata;
while (ancestor && ancestor->isTypeMetadata()) {
if (ancestor->getDescription() == description)
return true;
ancestor = ancestor->Superclass;
}
return false;
}
#endif
void *
swift::swift_lookUpClassMethod(const ClassMetadata *metadata,
const MethodDescriptor *method,
const ClassDescriptor *description) {
assert(metadata->isTypeMetadata());
#ifndef NDEBUG
assert(isAncestorOf(metadata, description));
#endif
auto *vtable = description->getVTableDescriptor();
assert(vtable != nullptr);
auto methods = description->getMethodDescriptors();
unsigned index = method - methods.data();
assert(index < methods.size());
auto vtableOffset = vtable->getVTableOffset(description) + index;
auto *words = reinterpret_cast<void * const *>(metadata);
auto *const *methodPtr = (words + vtableOffset);
#if SWIFT_PTRAUTH
// Re-sign the return value without the address.
unsigned extra = method->Flags.getExtraDiscriminator();
if (method->Flags.isAsync()) {
return ptrauth_auth_and_resign(
*methodPtr, ptrauth_key_process_independent_data,
ptrauth_blend_discriminator(methodPtr, extra),
ptrauth_key_process_independent_data, extra);
} else {
return ptrauth_auth_and_resign(
*methodPtr, ptrauth_key_function_pointer,
ptrauth_blend_discriminator(methodPtr, extra),
ptrauth_key_function_pointer, extra);
}
#else
return *methodPtr;
#endif
}
/***************************************************************************/
/*** Metatypes *************************************************************/
/***************************************************************************/
/// Find the appropriate value witness table for the given type.
static const ValueWitnessTable *
getMetatypeValueWitnesses(const Metadata *instanceType) {
// When metatypes are accessed opaquely, they always have a "thick"
// representation.
return &getUnmanagedPointerPointerValueWitnesses();
}
namespace {
class MetatypeCacheEntry {
public:
FullMetadata<MetatypeMetadata> Data;
MetatypeCacheEntry(const Metadata *instanceType) {
Data.setKind(MetadataKind::Metatype);
Data.ValueWitnesses = getMetatypeValueWitnesses(instanceType);
Data.InstanceType = instanceType;
}
intptr_t getKeyIntValueForDump() {
return reinterpret_cast<intptr_t>(Data.InstanceType);
}
bool matchesKey(const Metadata *instanceType) const {
return instanceType == Data.InstanceType;
}
friend llvm::hash_code hash_value(const MetatypeCacheEntry &value) {
return llvm::hash_value(value.Data.InstanceType);
}
static size_t getExtraAllocationSize(const Metadata *instanceType) {
return 0;
}
size_t getExtraAllocationSize() const {
return 0;
}
};
} // end anonymous namespace
/// The uniquing structure for metatype type metadata.
static SimpleGlobalCache<MetatypeCacheEntry, MetatypeTypesTag> MetatypeTypes;
/// Fetch a uniqued metadata for a metatype type.
SWIFT_RUNTIME_EXPORT
const MetatypeMetadata *
swift::swift_getMetatypeMetadata(const Metadata *instanceMetadata) {
return &MetatypeTypes.getOrInsert(instanceMetadata).first->Data;
}
/***************************************************************************/
/*** Existential Metatypes *************************************************/
/***************************************************************************/
namespace {
/// A cache entry for existential metatype witness tables.
class ExistentialMetatypeValueWitnessTableCacheEntry {
public:
ValueWitnessTable Data;
unsigned getNumWitnessTables() const {
return (Data.size - sizeof(ExistentialMetatypeContainer))
/ sizeof(const ValueWitnessTable*);
}
ExistentialMetatypeValueWitnessTableCacheEntry(unsigned numWitnessTables);
intptr_t getKeyIntValueForDump() {
return static_cast<intptr_t>(getNumWitnessTables());
}
bool matchesKey(unsigned key) const { return key == getNumWitnessTables(); }
friend llvm::hash_code
hash_value(const ExistentialMetatypeValueWitnessTableCacheEntry &value) {
return llvm::hash_value(value.getNumWitnessTables());
}
static size_t getExtraAllocationSize(unsigned numTables) {
return 0;
}
size_t getExtraAllocationSize() const {
return 0;
}
};
class ExistentialMetatypeCacheEntry {
public:
FullMetadata<ExistentialMetatypeMetadata> Data;
ExistentialMetatypeCacheEntry(const Metadata *instanceMetadata);
intptr_t getKeyIntValueForDump() {
return reinterpret_cast<intptr_t>(Data.InstanceType);
}
bool matchesKey(const Metadata *instanceType) const {
return instanceType == Data.InstanceType;
}
friend llvm::hash_code
hash_value(const ExistentialMetatypeCacheEntry &value) {
return llvm::hash_value(value.Data.InstanceType);
}
static size_t getExtraAllocationSize(const Metadata *key) {
return 0;
}
size_t getExtraAllocationSize() const {
return 0;
}
};
} // end anonymous namespace
/// The uniquing structure for existential metatype value witness tables.
static SimpleGlobalCache<ExistentialMetatypeValueWitnessTableCacheEntry,
ExistentialMetatypeValueWitnessTablesTag>
ExistentialMetatypeValueWitnessTables;
/// The uniquing structure for existential metatype type metadata.
static SimpleGlobalCache<ExistentialMetatypeCacheEntry,
ExistentialMetatypesTag> ExistentialMetatypes;
static const ValueWitnessTable
ExistentialMetatypeValueWitnesses_1 =
ValueWitnessTableForBox<ExistentialMetatypeBox<1>>::table;
static const ValueWitnessTable
ExistentialMetatypeValueWitnesses_2 =
ValueWitnessTableForBox<ExistentialMetatypeBox<2>>::table;
/// Instantiate a value witness table for an existential metatype
/// container with the given number of witness table pointers.
static const ValueWitnessTable *
getExistentialMetatypeValueWitnesses(unsigned numWitnessTables) {
if (numWitnessTables == 0)
return &getUnmanagedPointerPointerValueWitnesses();
if (numWitnessTables == 1)
return &ExistentialMetatypeValueWitnesses_1;
if (numWitnessTables == 2)
return &ExistentialMetatypeValueWitnesses_2;
static_assert(3 * sizeof(void*) >= sizeof(ValueBuffer),
"not handling all possible inline-storage class existentials!");
return &ExistentialMetatypeValueWitnessTables.getOrInsert(numWitnessTables)
.first->Data;
}
ExistentialMetatypeValueWitnessTableCacheEntry::
ExistentialMetatypeValueWitnessTableCacheEntry(unsigned numWitnessTables) {
using Box = NonFixedExistentialMetatypeBox;
using Witnesses = NonFixedValueWitnesses<Box, /*known allocated*/ true>;
#define WANT_REQUIRED_VALUE_WITNESSES 1
#define WANT_EXTRA_INHABITANT_VALUE_WITNESSES 1
#define WANT_ENUM_VALUE_WITNESSES 0
#define VALUE_WITNESS(LOWER_ID, UPPER_ID) \
Data.LOWER_ID = Witnesses::LOWER_ID;
#define DATA_VALUE_WITNESS(LOWER_ID, UPPER_ID, TYPE)
#include "swift/ABI/ValueWitness.def"
Data.size = Box::Container::getSize(numWitnessTables);
Data.flags = ValueWitnessFlags()
.withAlignment(Box::Container::getAlignment(numWitnessTables))
.withPOD(true)
.withBitwiseTakable(true)
.withInlineStorage(false);
Data.stride = Box::Container::getStride(numWitnessTables);
Data.extraInhabitantCount = Witnesses::numExtraInhabitants;
assert(getNumWitnessTables() == numWitnessTables);
}
/// Fetch a uniqued metadata for a metatype type.
SWIFT_RUNTIME_EXPORT
const ExistentialMetatypeMetadata *
swift::swift_getExistentialMetatypeMetadata(const Metadata *instanceMetadata) {
return &ExistentialMetatypes.getOrInsert(instanceMetadata).first->Data;
}
ExistentialMetatypeCacheEntry::ExistentialMetatypeCacheEntry(
const Metadata *instanceMetadata) {
ExistentialTypeFlags flags;
switch (instanceMetadata->getKind()) {
case MetadataKind::Existential:
flags = static_cast<const ExistentialTypeMetadata*>(instanceMetadata)
->Flags;
break;
case MetadataKind::ExistentialMetatype:
flags = static_cast<const ExistentialMetatypeMetadata*>(instanceMetadata)
->Flags;
break;
default:
assert(false && "expected existential metadata");
}
Data.setKind(MetadataKind::ExistentialMetatype);
Data.ValueWitnesses =
getExistentialMetatypeValueWitnesses(flags.getNumWitnessTables());
Data.InstanceType = instanceMetadata;
Data.Flags = flags;
}
/***************************************************************************/
/*** Existential types *****************************************************/
/***************************************************************************/
namespace {
class ExistentialCacheEntry {
public:
FullMetadata<ExistentialTypeMetadata> Data;
struct Key {
const Metadata *SuperclassConstraint;
ProtocolClassConstraint ClassConstraint : 1;
uint32_t NumProtocols : 31;
const ProtocolDescriptorRef *Protocols;
friend llvm::hash_code hash_value(const Key &key) {
auto hash = llvm::hash_combine(key.SuperclassConstraint,
key.ClassConstraint, key.NumProtocols);
for (size_t i = 0; i != key.NumProtocols; i++)
hash = llvm::hash_combine(hash, key.Protocols[i].getRawData());
return hash;
}
};
ExistentialCacheEntry(Key key);
intptr_t getKeyIntValueForDump() {
return 0;
}
bool matchesKey(Key key) const {
if (key.ClassConstraint != Data.Flags.getClassConstraint())
return false;
if (key.SuperclassConstraint != Data.getSuperclassConstraint())
return false;
if (key.NumProtocols != Data.NumProtocols)
return false;
auto dataProtocols = Data.getProtocols();
for (size_t i = 0; i != key.NumProtocols; ++i) {
if (key.Protocols[i].getRawData() != dataProtocols[i].getRawData())
return false;
}
return true;
}
friend llvm::hash_code hash_value(const ExistentialCacheEntry &value) {
Key key = {value.Data.getSuperclassConstraint(),
value.Data.Flags.getClassConstraint(), value.Data.NumProtocols,
value.Data.getProtocols().data()};
return hash_value(key);
}
static size_t getExtraAllocationSize(Key key) {
return ExistentialTypeMetadata::additionalSizeToAlloc<
const Metadata *, ProtocolDescriptorRef
>(key.SuperclassConstraint != nullptr, key.NumProtocols);
}
size_t getExtraAllocationSize() const {
return ExistentialTypeMetadata::additionalSizeToAlloc<
const Metadata *, ProtocolDescriptorRef
>(Data.Flags.hasSuperclassConstraint(), Data.NumProtocols);
}
};
class OpaqueExistentialValueWitnessTableCacheEntry {
public:
ValueWitnessTable Data;
OpaqueExistentialValueWitnessTableCacheEntry(unsigned numTables);
unsigned getNumWitnessTables() const {
return (Data.size - sizeof(OpaqueExistentialContainer))
/ sizeof(const WitnessTable *);
}
intptr_t getKeyIntValueForDump() {
return getNumWitnessTables();
}
bool matchesKey(unsigned key) const { return key == getNumWitnessTables(); }
friend llvm::hash_code
hash_value(const OpaqueExistentialValueWitnessTableCacheEntry &value) {
return llvm::hash_value(value.getNumWitnessTables());
}
static size_t getExtraAllocationSize(unsigned numTables) {
return 0;
}
size_t getExtraAllocationSize() const {
return 0;
}
};
class ClassExistentialValueWitnessTableCacheEntry {
public:
ValueWitnessTable Data;
ClassExistentialValueWitnessTableCacheEntry(unsigned numTables);
unsigned getNumWitnessTables() const {
return (Data.size - sizeof(ClassExistentialContainer))
/ sizeof(const WitnessTable *);
}
intptr_t getKeyIntValueForDump() {
return getNumWitnessTables();
}
bool matchesKey(unsigned key) const { return key == getNumWitnessTables(); }
friend llvm::hash_code
hash_value(const ClassExistentialValueWitnessTableCacheEntry &value) {
return llvm::hash_value(value.getNumWitnessTables());
}
static size_t getExtraAllocationSize(unsigned numTables) {
return 0;
}
size_t getExtraAllocationSize() const {
return 0;
}
};
} // end anonymous namespace
/// The uniquing structure for existential type metadata.
static SimpleGlobalCache<ExistentialCacheEntry, ExistentialTypesTag> ExistentialTypes;
static const ValueWitnessTable
OpaqueExistentialValueWitnesses_0 =
ValueWitnessTableForBox<OpaqueExistentialBox<0>>::table;
static const ValueWitnessTable
OpaqueExistentialValueWitnesses_1 =
ValueWitnessTableForBox<OpaqueExistentialBox<1>>::table;
/// The standard metadata for Any.
const FullMetadata<ExistentialTypeMetadata> swift::
METADATA_SYM(ANY_MANGLING) = {
{ &OpaqueExistentialValueWitnesses_0 }, // ValueWitnesses
ExistentialTypeMetadata(
ExistentialTypeFlags() // Flags
.withNumWitnessTables(0)
.withClassConstraint(ProtocolClassConstraint::Any)
.withHasSuperclass(false)
.withSpecialProtocol(SpecialProtocol::None)),
};
/// The standard metadata for AnyObject.
const FullMetadata<ExistentialTypeMetadata> swift::
METADATA_SYM(ANYOBJECT_MANGLING) = {
{
#if SWIFT_OBJC_INTEROP
&VALUE_WITNESS_SYM(BO)
#else
&VALUE_WITNESS_SYM(Bo)
#endif
},
ExistentialTypeMetadata(
ExistentialTypeFlags() // Flags
.withNumWitnessTables(0)
.withClassConstraint(ProtocolClassConstraint::Class)
.withHasSuperclass(false)
.withSpecialProtocol(SpecialProtocol::None)),
};
/// The uniquing structure for opaque existential value witness tables.
static SimpleGlobalCache<OpaqueExistentialValueWitnessTableCacheEntry,
OpaqueExistentialValueWitnessTablesTag>
OpaqueExistentialValueWitnessTables;
/// Instantiate a value witness table for an opaque existential container with
/// the given number of witness table pointers.
static const ValueWitnessTable *
getOpaqueExistentialValueWitnesses(unsigned numWitnessTables) {
// We pre-allocate a couple of important cases.
if (numWitnessTables == 0)
return &OpaqueExistentialValueWitnesses_0;
if (numWitnessTables == 1)
return &OpaqueExistentialValueWitnesses_1;
return &OpaqueExistentialValueWitnessTables.getOrInsert(numWitnessTables)
.first->Data;
}
OpaqueExistentialValueWitnessTableCacheEntry::
OpaqueExistentialValueWitnessTableCacheEntry(unsigned numWitnessTables) {
using Box = NonFixedOpaqueExistentialBox;
using Witnesses = NonFixedValueWitnesses<Box, /*known allocated*/ true>;
#define WANT_ONLY_REQUIRED_VALUE_WITNESSES
#define VALUE_WITNESS(LOWER_ID, UPPER_ID) \
Data.LOWER_ID = Witnesses::LOWER_ID;
#define DATA_VALUE_WITNESS(LOWER_ID, UPPER_ID, TYPE)
#include "swift/ABI/ValueWitness.def"
Data.size = Box::Container::getSize(numWitnessTables);
Data.flags = ValueWitnessFlags()
.withAlignment(Box::Container::getAlignment(numWitnessTables))
.withPOD(false)
.withBitwiseTakable(true)
.withInlineStorage(false);
Data.extraInhabitantCount = Witnesses::numExtraInhabitants;
Data.stride = Box::Container::getStride(numWitnessTables);
assert(getNumWitnessTables() == numWitnessTables);
}
static const ValueWitnessTable ClassExistentialValueWitnesses_1 =
ValueWitnessTableForBox<ClassExistentialBox<1>>::table;
static const ValueWitnessTable ClassExistentialValueWitnesses_2 =
ValueWitnessTableForBox<ClassExistentialBox<2>>::table;
/// The uniquing structure for class existential value witness tables.
static SimpleGlobalCache<ClassExistentialValueWitnessTableCacheEntry,
ClassExistentialValueWitnessTablesTag>
ClassExistentialValueWitnessTables;
/// Instantiate a value witness table for a class-constrained existential
/// container with the given number of witness table pointers.
static const ValueWitnessTable *
getClassExistentialValueWitnesses(const Metadata *superclass,
unsigned numWitnessTables) {
// FIXME: If the superclass is not @objc, use native reference counting.
if (numWitnessTables == 0) {
#if SWIFT_OBJC_INTEROP
return &VALUE_WITNESS_SYM(BO);
#else
return &VALUE_WITNESS_SYM(Bo);
#endif
}
if (numWitnessTables == 1)
return &ClassExistentialValueWitnesses_1;
if (numWitnessTables == 2)
return &ClassExistentialValueWitnesses_2;
static_assert(3 * sizeof(void*) >= sizeof(ValueBuffer),
"not handling all possible inline-storage class existentials!");
return &ClassExistentialValueWitnessTables.getOrInsert(numWitnessTables)
.first->Data;
}
ClassExistentialValueWitnessTableCacheEntry::
ClassExistentialValueWitnessTableCacheEntry(unsigned numWitnessTables) {
using Box = NonFixedClassExistentialBox;
using Witnesses = NonFixedValueWitnesses<Box, /*known allocated*/ true>;
#define WANT_REQUIRED_VALUE_WITNESSES 1
#define WANT_EXTRA_INHABITANT_VALUE_WITNESSES 1
#define WANT_ENUM_VALUE_WITNESSES 0
#define VALUE_WITNESS(LOWER_ID, UPPER_ID) \
Data.LOWER_ID = Witnesses::LOWER_ID;
#define DATA_VALUE_WITNESS(LOWER_ID, UPPER_ID, TYPE)
#include "swift/ABI/ValueWitness.def"
Data.size = Box::Container::getSize(numWitnessTables);
Data.flags = ValueWitnessFlags()
.withAlignment(Box::Container::getAlignment(numWitnessTables))
.withPOD(false)
.withBitwiseTakable(true)
.withInlineStorage(false);
Data.extraInhabitantCount = Witnesses::numExtraInhabitants;
Data.stride = Box::Container::getStride(numWitnessTables);
assert(getNumWitnessTables() == numWitnessTables);
}
/// Get the value witness table for an existential type, first trying to use a
/// shared specialized table for common cases.
static const ValueWitnessTable *
getExistentialValueWitnesses(ProtocolClassConstraint classConstraint,
const Metadata *superclassConstraint,
unsigned numWitnessTables,
SpecialProtocol special) {
// Use special representation for special protocols.
switch (special) {
case SpecialProtocol::Error:
#if SWIFT_OBJC_INTEROP
// Error always has a single-ObjC-refcounted representation.
return &VALUE_WITNESS_SYM(BO);
#else
// Without ObjC interop, Error is native-refcounted.
return &VALUE_WITNESS_SYM(Bo);
#endif
// Other existentials use standard representation.
case SpecialProtocol::None:
break;
}
switch (classConstraint) {
case ProtocolClassConstraint::Class:
return getClassExistentialValueWitnesses(superclassConstraint,
numWitnessTables);
case ProtocolClassConstraint::Any:
assert(superclassConstraint == nullptr);
return getOpaqueExistentialValueWitnesses(numWitnessTables);
}
swift_unreachable("Unhandled ProtocolClassConstraint in switch.");
}
template<> ExistentialTypeRepresentation
ExistentialTypeMetadata::getRepresentation() const {
// Some existentials use special containers.
switch (Flags.getSpecialProtocol()) {
case SpecialProtocol::Error:
return ExistentialTypeRepresentation::Error;
case SpecialProtocol::None:
break;
}
// The layout of standard containers depends on whether the existential is
// class-constrained.
if (isClassBounded())
return ExistentialTypeRepresentation::Class;
return ExistentialTypeRepresentation::Opaque;
}
template<> bool
ExistentialTypeMetadata::mayTakeValue(const OpaqueValue *container) const {
switch (getRepresentation()) {
// Owning a reference to a class existential is equivalent to owning a
// reference to the contained class instance.
case ExistentialTypeRepresentation::Class:
return true;
// Opaque existential containers uniquely own their contained value.
case ExistentialTypeRepresentation::Opaque: {
// We can't take from a shared existential box without checking uniqueness.
auto *opaque =
reinterpret_cast<const OpaqueExistentialContainer *>(container);
return opaque->isValueInline();
}
// References to boxed existential containers may be shared.
case ExistentialTypeRepresentation::Error: {
// We can only take the value if the box is a bridged NSError, in which case
// owning a reference to the box is owning a reference to the NSError.
// TODO: Or if the box is uniquely referenced. We don't have intimate
// enough knowledge of CF refcounting to check for that dynamically yet.
const SwiftError *errorBox
= *reinterpret_cast<const SwiftError * const *>(container);
return errorBox->isPureNSError();
}
}
swift_unreachable(
"Unhandled ExistentialTypeRepresentation in switch.");
}
template<> void
ExistentialTypeMetadata::deinitExistentialContainer(OpaqueValue *container)
const {
switch (getRepresentation()) {
case ExistentialTypeRepresentation::Class:
// Nothing to clean up after taking the class reference.
break;
case ExistentialTypeRepresentation::Opaque: {
auto *opaque = reinterpret_cast<OpaqueExistentialContainer *>(container);
opaque->deinit();
break;
}
case ExistentialTypeRepresentation::Error:
// TODO: If we were able to claim the value from a uniquely-owned
// existential box, we would want to deallocError here.
break;
}
}
template<> const OpaqueValue *
ExistentialTypeMetadata::projectValue(const OpaqueValue *container) const {
switch (getRepresentation()) {
case ExistentialTypeRepresentation::Class: {
auto classContainer =
reinterpret_cast<const ClassExistentialContainer*>(container);
return reinterpret_cast<const OpaqueValue *>(&classContainer->Value);
}
case ExistentialTypeRepresentation::Opaque: {
auto *opaqueContainer =
reinterpret_cast<const OpaqueExistentialContainer*>(container);
return opaqueContainer->projectValue();
}
case ExistentialTypeRepresentation::Error: {
const SwiftError *errorBox
= *reinterpret_cast<const SwiftError * const *>(container);
// If the error is a bridged NSError, then the "box" is in fact itself
// the value.
if (errorBox->isPureNSError())
return container;
return errorBox->getValue();
}
}
swift_unreachable(
"Unhandled ExistentialTypeRepresentation in switch.");
}
template<> const Metadata *
ExistentialTypeMetadata::getDynamicType(const OpaqueValue *container) const {
switch (getRepresentation()) {
case ExistentialTypeRepresentation::Class: {
auto classContainer =
reinterpret_cast<const ClassExistentialContainer*>(container);
void *obj = classContainer->Value;
return swift_getObjectType(reinterpret_cast<HeapObject*>(obj));
}
case ExistentialTypeRepresentation::Opaque: {
auto opaqueContainer =
reinterpret_cast<const OpaqueExistentialContainer*>(container);
return opaqueContainer->Type;
}
case ExistentialTypeRepresentation::Error: {
const SwiftError *errorBox
= *reinterpret_cast<const SwiftError * const *>(container);
return errorBox->getType();
}
}
swift_unreachable(
"Unhandled ExistentialTypeRepresentation in switch.");
}
template<> const WitnessTable *
ExistentialTypeMetadata::getWitnessTable(const OpaqueValue *container,
unsigned i) const {
assert(i < Flags.getNumWitnessTables());
// The layout of the container depends on whether it's class-constrained
// or a special protocol.
const WitnessTable * const *witnessTables;
switch (getRepresentation()) {
case ExistentialTypeRepresentation::Class: {
auto classContainer =
reinterpret_cast<const ClassExistentialContainer*>(container);
witnessTables = classContainer->getWitnessTables();
break;
}
case ExistentialTypeRepresentation::Opaque: {
auto opaqueContainer =
reinterpret_cast<const OpaqueExistentialContainer*>(container);
witnessTables = opaqueContainer->getWitnessTables();
break;
}
case ExistentialTypeRepresentation::Error: {
// Only one witness table we should be able to return, which is the
// Error.
assert(i == 0 && "only one witness table in an Error box");
const SwiftError *errorBox
= *reinterpret_cast<const SwiftError * const *>(container);
return errorBox->getErrorConformance();
}
}
// The return type here describes extra structure for the protocol
// witness table for some reason. We should probably have a nominal
// type for these, just for type safety reasons.
return witnessTables[i];
}
#ifndef NDEBUG
/// Determine whether any of the given protocols is class-bound.
static bool anyProtocolIsClassBound(
size_t numProtocols,
const ProtocolDescriptorRef *protocols) {
for (unsigned i = 0; i != numProtocols; ++i) {
if (protocols[i].getClassConstraint() == ProtocolClassConstraint::Class)
return true;
}
return false;
}
#endif
const Metadata *
swift::_getSimpleProtocolTypeMetadata(const ProtocolDescriptor *protocol) {
auto protocolRef = ProtocolDescriptorRef::forSwift(protocol);
auto constraint =
protocol->getProtocolContextDescriptorFlags().getClassConstraint();
return swift_getExistentialTypeMetadata(constraint,
/*superclass bound*/ nullptr,
/*num protocols*/ 1,
&protocolRef);
}
/// Fetch a uniqued metadata for an existential type. The array
/// referenced by \c protocols will be sorted in-place.
const ExistentialTypeMetadata *
swift::swift_getExistentialTypeMetadata(
ProtocolClassConstraint classConstraint,
const Metadata *superclassConstraint,
size_t numProtocols,
const ProtocolDescriptorRef *protocols) {
// The empty compositions Any and AnyObject have fixed metadata.
if (numProtocols == 0 && !superclassConstraint) {
switch (classConstraint) {
case ProtocolClassConstraint::Any:
return &METADATA_SYM(ANY_MANGLING);
case ProtocolClassConstraint::Class:
return &METADATA_SYM(ANYOBJECT_MANGLING);
}
}
// We entrust that the compiler emitting the call to
// swift_getExistentialTypeMetadata always sorts the `protocols` array using
// a globally stable ordering that's consistent across modules.
// Ensure that the "class constraint" bit is set whenever we have a
// superclass or a one of the protocols is class-bound.
#ifndef NDEBUG
assert(classConstraint == ProtocolClassConstraint::Class ||
(!superclassConstraint &&
!anyProtocolIsClassBound(numProtocols, protocols)));
#endif
ExistentialCacheEntry::Key key = {
superclassConstraint, classConstraint, (uint32_t)numProtocols, protocols
};
return &ExistentialTypes.getOrInsert(key).first->Data;
}
ExistentialCacheEntry::ExistentialCacheEntry(Key key) {
// Calculate the class constraint and number of witness tables for the
// protocol set.
unsigned numWitnessTables = 0;
for (auto p : make_range(key.Protocols, key.Protocols + key.NumProtocols)) {
if (p.needsWitnessTable())
++numWitnessTables;
}
// Get the special protocol kind for an uncomposed protocol existential.
// Protocol compositions are currently never special.
auto special = SpecialProtocol::None;
if (key.NumProtocols == 1)
special = key.Protocols[0].getSpecialProtocol();
Data.setKind(MetadataKind::Existential);
Data.ValueWitnesses = getExistentialValueWitnesses(key.ClassConstraint,
key.SuperclassConstraint,
numWitnessTables,
special);
Data.Flags = ExistentialTypeFlags()
.withNumWitnessTables(numWitnessTables)
.withClassConstraint(key.ClassConstraint)
.withSpecialProtocol(special);
if (key.SuperclassConstraint != nullptr) {
Data.Flags = Data.Flags.withHasSuperclass(true);
Data.setSuperclassConstraint(key.SuperclassConstraint);
}
Data.NumProtocols = key.NumProtocols;
auto dataProtocols = Data.getMutableProtocols();
for (size_t i = 0; i < key.NumProtocols; ++i) {
dataProtocols[i] = key.Protocols[i];
}
}
/// Perform a copy-assignment from one existential container to another.
/// Both containers must be of the same existential type representable with no
/// witness tables.
OpaqueValue *swift::swift_assignExistentialWithCopy0(OpaqueValue *dest,
const OpaqueValue *src,
const Metadata *type) {
using Witnesses = ValueWitnesses<OpaqueExistentialBox<0>>;
return Witnesses::assignWithCopy(dest, const_cast<OpaqueValue*>(src), type);
}
/// Perform a copy-assignment from one existential container to another.
/// Both containers must be of the same existential type representable with one
/// witness table.
OpaqueValue *swift::swift_assignExistentialWithCopy1(OpaqueValue *dest,
const OpaqueValue *src,
const Metadata *type) {
using Witnesses = ValueWitnesses<OpaqueExistentialBox<1>>;
return Witnesses::assignWithCopy(dest, const_cast<OpaqueValue*>(src), type);
}
/// Perform a copy-assignment from one existential container to another.
/// Both containers must be of the same existential type representable with the
/// same number of witness tables.
OpaqueValue *swift::swift_assignExistentialWithCopy(OpaqueValue *dest,
const OpaqueValue *src,
const Metadata *type) {
assert(!type->getValueWitnesses()->isValueInline());
using Witnesses = NonFixedValueWitnesses<NonFixedOpaqueExistentialBox,
/*known allocated*/ true>;
return Witnesses::assignWithCopy(dest, const_cast<OpaqueValue*>(src), type);
}
/***************************************************************************/
/*** Extended existential type descriptors *********************************/
/***************************************************************************/
namespace {
class ExtendedExistentialTypeShapeCacheEntry {
public:
const NonUniqueExtendedExistentialTypeShape *
__ptrauth_swift_nonunique_extended_existential_type_shape Data;
struct Key {
const NonUniqueExtendedExistentialTypeShape *Candidate;
llvm::StringRef TypeString;
Key(const NonUniqueExtendedExistentialTypeShape *candidate)
: Candidate(candidate),
TypeString(candidate->getExistentialTypeStringForUniquing()) {}
friend llvm::hash_code hash_value(const Key &key) {
return hash_value(key.TypeString);
}
};
ExtendedExistentialTypeShapeCacheEntry(Key key)
: Data(key.Candidate) {}
intptr_t getKeyIntValueForDump() {
return 0;
}
bool matchesKey(Key key) const {
auto self = Data;
auto other = key.Candidate;
if (self == other) return true;
return self->getExistentialTypeStringForUniquing() == key.TypeString;
}
friend llvm::hash_code hash_value(
const ExtendedExistentialTypeShapeCacheEntry &value) {
return hash_value(Key(value.Data));
}
static size_t getExtraAllocationSize(Key key) {
return 0;
}
};
}
/// The uniquing structure for extended existential type descriptors.
static SimpleGlobalCache<ExtendedExistentialTypeShapeCacheEntry,
ExtendedExistentialTypeShapesTag>
ExtendedExistentialTypeShapes;
const ExtendedExistentialTypeShape *
swift::swift_getExtendedExistentialTypeShape(
const NonUniqueExtendedExistentialTypeShape *nonUnique) {
#if SWIFT_PTRAUTH
// The description pointer is expected to be signed with an
// address-undiversified schema when passed in.
nonUnique = ptrauth_auth_data(nonUnique,
ptrauth_key_process_independent_data,
SpecialPointerAuthDiscriminators::NonUniqueExtendedExistentialTypeShape);
#endif
// Check the cache.
auto &cache = *nonUnique->UniqueCache.get();
if (auto ptr = cache.load(std::memory_order_acquire)) {
#if SWIFT_PTRAUTH
// Resign the returned pointer from an address-diversified to an
// undiversified schema.
ptr = ptrauth_auth_and_resign(ptr,
ptrauth_key_process_independent_data,
ptrauth_blend_discriminator(&cache,
SpecialPointerAuthDiscriminators::ExtendedExistentialTypeShape),
ptrauth_key_process_independent_data,
SpecialPointerAuthDiscriminators::ExtendedExistentialTypeShape);
#endif
return ptr;
}
// Find the unique entry.
auto uniqueEntry = ExtendedExistentialTypeShapes.getOrInsert(
ExtendedExistentialTypeShapeCacheEntry::Key(nonUnique));
const ExtendedExistentialTypeShape *unique =
&uniqueEntry.first->Data->LocalCopy;
// Cache the uniqued description, signing it with an
// address-diversified schema.
auto uniqueForCache = unique;
#if SWIFT_PTRAUTH
uniqueForCache = ptrauth_sign_unauthenticated(uniqueForCache,
ptrauth_key_process_independent_data,
ptrauth_blend_discriminator(&cache,
SpecialPointerAuthDiscriminators::ExtendedExistentialTypeShape));
#endif
cache.store(uniqueForCache, std::memory_order_release);
// Return the uniqued description, signing it with an
// address-undiversified schema.
#if SWIFT_PTRAUTH
unique = ptrauth_sign_unauthenticated(unique,
ptrauth_key_process_independent_data,
SpecialPointerAuthDiscriminators::ExtendedExistentialTypeShape);
#endif
return unique;
}
/***************************************************************************/
/*** Extended existential types ********************************************/
/***************************************************************************/
namespace {
class ExtendedExistentialTypeCacheEntry {
public:
FullMetadata<ExtendedExistentialTypeMetadata> Data;
struct Key {
MetadataCacheKey Arguments;
const ExtendedExistentialTypeShape *Shape;
Key(const ExtendedExistentialTypeShape *shape,
const void * const *arguments)
: Arguments(shape->getGeneralizationSignature(), arguments),
Shape(shape) {}
friend llvm::hash_code hash_value(const Key &key) {
return llvm::hash_combine(key.Shape, // by address
key.Arguments.hash());
}
bool operator==(const Key &other) const {
return Shape == other.Shape && Arguments == other.Arguments;
}
};
ExtendedExistentialTypeCacheEntry(Key key)
: Data{ TargetTypeMetadataHeader<InProcess>({getOrCreateTypeLayout(key)}, {getOrCreateVWT(key)}), key.Shape} {
key.Arguments.installInto(Data.getTrailingObjects<const void *>());
}
static const ValueWitnessTable *getOrCreateVWT(Key key);
static const uint8_t *getOrCreateTypeLayout(Key key);
intptr_t getKeyIntValueForDump() {
return 0;
}
Key getKey() const {
return Key{Data.Shape, Data.getGeneralizationArguments()};
}
bool matchesKey(Key key) const {
// Bypass the eager hashing done in the Key constructor in the most
// important negative case.
if (Data.Shape != key.Shape)
return false;
return (getKey() == key);
}
friend llvm::hash_code hash_value(const ExtendedExistentialTypeCacheEntry &value) {
return hash_value(value.getKey());
}
static size_t getExtraAllocationSize(Key key) {
return ExtendedExistentialTypeMetadata::additionalSizeToAlloc<
const void *
>(key.Shape->getGenSigArgumentLayoutSizeInWords());
}
size_t getExtraAllocationSize() const {
return ExtendedExistentialTypeMetadata::additionalSizeToAlloc<
const void *
>(Data.Shape->getGenSigArgumentLayoutSizeInWords());
}
};
} // end anonymous namespace
const ValueWitnessTable *
ExtendedExistentialTypeCacheEntry::getOrCreateVWT(Key key) {
auto shape = key.Shape;
if (auto witnesses = shape->getSuggestedValueWitnesses())
return witnesses;
// The type head must name all the type parameters, so we must not have
// multiple type parameters if we have an opaque type head.
auto sigSizeInWords = shape->ReqSigHeader.getArgumentLayoutSizeInWords();
#ifndef NDEBUG
auto layout =
GenericSignatureLayout<InProcess>(shape->getRequirementSignature());
assert(layout.NumKeyParameters == shape->ReqSigHeader.NumParams &&
"requirement signature for existential includes a "
"redundant parameter?");
assert(layout.NumWitnessTables
== sigSizeInWords - shape->ReqSigHeader.NumParams &&
"requirement signature for existential includes an "
"unexpected key argument?");
#endif
// We're lowering onto existing witnesses for existential types,
// which are parameterized only by the number of witness tables they
// need to copy around.
// TODO: variadic-parameter-packs? Or is a memcpy okay, because we
// can assume existentials store permanent packs, in the unlikely
// case that the requirement signature includes a pack parameter?
unsigned wtableStorageSizeInWords =
sigSizeInWords - shape->ReqSigHeader.NumParams;
using SpecialKind = ExtendedExistentialTypeShape::SpecialKind;
switch (shape->Flags.getSpecialKind()) {
case SpecialKind::None:
assert(shape->isTypeExpressionOpaque() &&
"shape with a non-opaque type expression has no suggested VWT");
// Use the standard opaque-existential representation.
return getExistentialValueWitnesses(ProtocolClassConstraint::Any,
/*superclass*/ nullptr,
wtableStorageSizeInWords,
SpecialProtocol::None);
case SpecialKind::ExplicitLayout:
swift_unreachable("shape with explicit layout but no suggested VWT");
case SpecialKind::Class:
// Class-constrained existentials don't store type metadata.
// TODO: pull out a superclass constraint if there is one so that
// we can use native reference counting.
return getExistentialValueWitnesses(ProtocolClassConstraint::Class,
/*superclass*/ nullptr,
wtableStorageSizeInWords,
SpecialProtocol::None);
case SpecialKind::Metatype:
// Existential metatypes don't store type metadata.
return getExistentialMetatypeValueWitnesses(wtableStorageSizeInWords);
}
// We can support back-deployment of new special kinds (at least here)
// if we just require them to provide suggested value witnesses.
swift_unreachable("shape with unknown special kind had no suggested VWT");
}
const uint8_t *
ExtendedExistentialTypeCacheEntry::getOrCreateTypeLayout(Key key) {
// TODO: implement
return nullptr;
}
/// The uniquing structure for extended existential type metadata.
static SimpleGlobalCache<ExtendedExistentialTypeCacheEntry,
ExtendedExistentialTypesTag>
ExtendedExistentialTypes;
const ExtendedExistentialTypeMetadata *
swift::swift_getExtendedExistentialTypeMetadata_unique(
const ExtendedExistentialTypeShape *shape,
const void * const *generalizationArguments) {
#if SWIFT_PTRAUTH
shape = ptrauth_auth_data(shape, ptrauth_key_process_independent_data,
SpecialPointerAuthDiscriminators::ExtendedExistentialTypeShape);
#endif
ExtendedExistentialTypeCacheEntry::Key key(shape, generalizationArguments);
auto entry = ExtendedExistentialTypes.getOrInsert(key);
return &entry.first->Data;
}
/// Fetch a unique existential shape descriptor for an extended
/// existential type.
SWIFT_RUNTIME_EXPORT
const ExtendedExistentialTypeMetadata *
swift_getExtendedExistentialTypeMetadata(
const NonUniqueExtendedExistentialTypeShape *nonUniqueShape,
const void * const *generalizationArguments) {
auto uniqueShape = swift_getExtendedExistentialTypeShape(nonUniqueShape);
return swift_getExtendedExistentialTypeMetadata_unique(uniqueShape,
generalizationArguments);
}
/***************************************************************************/
/*** Foreign types *********************************************************/
/***************************************************************************/
// We use a DenseMap over what are essentially StringRefs instead of a
// StringMap because we don't need to actually copy the string.
namespace {
static const TypeContextDescriptor *
getForeignTypeDescription(Metadata *metadata) {
if (auto foreignClass = dyn_cast<ForeignClassMetadata>(metadata))
return foreignClass->getDescription();
else if (auto foreignClass = dyn_cast<ForeignReferenceTypeMetadata>(metadata))
return foreignClass->getDescription();
return cast<ValueMetadata>(metadata)->getDescription();
}
class ForeignMetadataCacheEntry
: public MetadataCacheEntryBase<ForeignMetadataCacheEntry, /*spurious*/ int> {
Metadata *Value;
friend MetadataCacheEntryBase;
ValueType getValue() {
return Value;
}
void setValue(ValueType value) {
swift_unreachable("should never be called");
}
public:
struct Key {
const TypeContextDescriptor *Description;
friend llvm::hash_code hash_value(const Key &key) {
return hash_value(TypeContextIdentity(key.Description));
}
};
static const char *getName() { return "ForeignMetadataCache"; }
ForeignMetadataCacheEntry(Key key, MetadataWaitQueue::Worker &worker,
MetadataRequest request, Metadata *candidate)
: MetadataCacheEntryBase(worker, configureCandidate(key, candidate)),
Value(candidate) {
}
const TypeContextDescriptor *getDescription() const {
return getForeignTypeDescription(Value);
}
template <class... Args>
static size_t numTrailingObjects(OverloadToken<int>, Args &&...) {
return 0;
}
intptr_t getKeyIntValueForDump() const {
return reinterpret_cast<intptr_t>(getDescription()->Name.get());
}
friend llvm::hash_code hash_value(const ForeignMetadataCacheEntry &value) {
return hash_value(TypeContextIdentity(value.getDescription()));
}
bool matchesKey(Key key) {
// We can just compare unparented type-context identities because
// we assume that foreign types don't have interesting parenting
// structure.
return TypeContextIdentity(key.Description) == TypeContextIdentity(getDescription());
}
AllocationResult allocate(Metadata *candidate) {
swift_unreachable("allocation is short-circuited during construction");
}
MetadataStateWithDependency tryInitialize(Metadata *metadata,
PrivateMetadataState state,
PrivateMetadataCompletionContext *ctxt) {
assert(state != PrivateMetadataState::Complete);
// Finish the completion function.
auto &init = getDescription()->getForeignMetadataInitialization();
if (init.CompletionFunction) {
// Try to complete the metadata's instantiation.
auto dependency =
init.CompletionFunction(metadata, &ctxt->Public, nullptr);
// If this failed with a dependency, infer the current metadata state
// and return.
if (dependency) {
return { inferStateForMetadata(metadata), dependency };
}
}
// Check for transitive completeness.
if (auto dependency = checkTransitiveCompleteness(metadata)) {
return { PrivateMetadataState::NonTransitiveComplete, dependency };
}
// We're done.
return { PrivateMetadataState::Complete, MetadataDependency() };
}
private:
/// Do as much candidate initialization as we reasonably can during
/// construction. Remember, though, that this is just construction;
/// we won't have committed to this candidate as the metadata until
/// this entry is successfully installed in the concurrent map.
static PrivateMetadataState configureCandidate(Key key, Metadata *candidate) {
auto &init = key.Description->getForeignMetadataInitialization();
if (!init.CompletionFunction) {
if (areAllTransitiveMetadataComplete_cheap(candidate)) {
return PrivateMetadataState::Complete;
} else {
return PrivateMetadataState::NonTransitiveComplete;
}
}
if (candidate->getValueWitnesses() == nullptr) {
assert(isa<ForeignClassMetadata>(candidate) &&
"cannot set default value witnesses for non-class foreign types");
// Fill in the default VWT if it was not set in the candidate at build
// time.
#if SWIFT_OBJC_INTEROP
candidate->setValueWitnesses(&VALUE_WITNESS_SYM(BO));
#else
candidate->setValueWitnesses(&VALUE_WITNESS_SYM(Bo));
#endif
}
return inferStateForMetadata(candidate);
}
};
} // end anonymous namespace
static Lazy<MetadataCache<ForeignMetadataCacheEntry, ForeignMetadataCacheTag>> ForeignMetadata;
MetadataResponse
swift::swift_getForeignTypeMetadata(MetadataRequest request,
ForeignTypeMetadata *candidate) {
auto description = getForeignTypeDescription(candidate);
ForeignMetadataCacheEntry::Key key{description};
return ForeignMetadata->getOrInsert(key, request, candidate).second;
}
/// Unique-ing of foreign types' witness tables.
namespace {
class ForeignWitnessTableCacheEntry {
public:
struct Key {
const TypeContextDescriptor *type;
const ProtocolDescriptor *protocol;
friend llvm::hash_code hash_value(const Key &value) {
return llvm::hash_combine(value.protocol,
TypeContextIdentity(value.type));
}
};
const TypeContextDescriptor *type;
const ProtocolDescriptor *protocol;
const WitnessTable *data;
ForeignWitnessTableCacheEntry(const ForeignWitnessTableCacheEntry::Key k,
const WitnessTable *d)
: type(k.type), protocol(k.protocol), data(d) {}
intptr_t getKeyIntValueForDump() {
return reinterpret_cast<intptr_t>(type);
}
bool matchesKey(const Key other) const {
return other.protocol == protocol &&
TypeContextIdentity(other.type) == TypeContextIdentity(type);
}
friend llvm::hash_code
hash_value(const ForeignWitnessTableCacheEntry &value) {
Key key{value.type, value.protocol};
return hash_value(key);
}
static size_t getExtraAllocationSize(const Key,
const WitnessTable *) {
return 0;
}
size_t getExtraAllocationSize() const {
return 0;
}
};
}
static ConcurrentReadableHashMap<ForeignWitnessTableCacheEntry>
ForeignWitnessTables;
static const WitnessTable *_getForeignWitnessTable(
const WitnessTable *witnessTableCandidate,
const TypeContextDescriptor *contextDescriptor,
const ProtocolDescriptor *protocol) {
const WitnessTable *result = nullptr;
ForeignWitnessTableCacheEntry::Key key{contextDescriptor, protocol};
ForeignWitnessTables.getOrInsert(
key, [&](ForeignWitnessTableCacheEntry *entryPtr, bool created) {
if (created)
::new (entryPtr)
ForeignWitnessTableCacheEntry(key, witnessTableCandidate);
result = entryPtr->data;
return true;
});
return result;
}
/***************************************************************************/
/*** Other metadata routines ***********************************************/
/***************************************************************************/
template <> OpaqueValue *Metadata::allocateBoxForExistentialIn(ValueBuffer *buffer) const {
auto *vwt = getValueWitnesses();
if (vwt->isValueInline())
return reinterpret_cast<OpaqueValue *>(buffer);
// Allocate the box.
BoxPair refAndValueAddr(swift_allocBox(this));
buffer->PrivateData[0] = refAndValueAddr.object;
return refAndValueAddr.buffer;
}
template <> void Metadata::deallocateBoxForExistentialIn(ValueBuffer *buffer) const {
auto *vwt = getValueWitnesses();
if (vwt->isValueInline())
return;
swift_deallocBox(reinterpret_cast<HeapObject *>(buffer->PrivateData[0]));
}
template <> OpaqueValue *Metadata::allocateBufferIn(ValueBuffer *buffer) const {
auto *vwt = getValueWitnesses();
if (vwt->isValueInline())
return reinterpret_cast<OpaqueValue *>(buffer);
// Allocate temporary outline buffer.
auto size = vwt->getSize();
auto alignMask = vwt->getAlignmentMask();
auto *ptr = swift_slowAlloc(size, alignMask);
buffer->PrivateData[0] = ptr;
return reinterpret_cast<OpaqueValue *>(ptr);
}
template <> OpaqueValue *Metadata::projectBufferFrom(ValueBuffer *buffer) const{
auto *vwt = getValueWitnesses();
if (vwt->isValueInline())
return reinterpret_cast<OpaqueValue *>(buffer);
return reinterpret_cast<OpaqueValue *>(buffer->PrivateData[0]);
}
template <> void Metadata::deallocateBufferIn(ValueBuffer *buffer) const {
auto *vwt = getValueWitnesses();
if (vwt->isValueInline())
return;
auto size = vwt->getSize();
auto alignMask = vwt->getAlignmentMask();
swift_slowDealloc(buffer->PrivateData[0], size, alignMask);
}
#ifndef NDEBUG
SWIFT_RUNTIME_EXPORT
void _swift_debug_verifyTypeLayoutAttribute(Metadata *type,
const void *runtimeValue,
const void *staticValue,
size_t size,
const char *description) {
auto presentValue = [&](const void *value) {
if (size <= sizeof(uint64_t)) {
uint64_t intValue = 0;
auto ptr = reinterpret_cast<uint8_t *>(&intValue);
#if defined(__BIG_ENDIAN__)
ptr += sizeof(uint64_t) - size;
#endif
memcpy(ptr, value, size);
fprintf(stderr, "%" PRIu64 " (%#" PRIx64 ")\n", intValue, intValue);
fprintf(stderr, " ");
}
auto bytes = reinterpret_cast<const uint8_t *>(value);
for (unsigned i = 0; i < size; ++i) {
fprintf(stderr, "%02x ", bytes[i]);
}
fprintf(stderr, "\n");
};
if (memcmp(runtimeValue, staticValue, size) != 0) {
auto typeName = nameForMetadata(type);
fprintf(stderr, "*** Type verification of %s %s failed ***\n",
typeName.c_str(), description);
fprintf(stderr, " runtime value: ");
presentValue(runtimeValue);
fprintf(stderr, " compiler value: ");
presentValue(staticValue);
}
}
#endif
StringRef swift::getStringForMetadataKind(MetadataKind kind) {
switch (kind) {
#define METADATAKIND(NAME, VALUE) \
case MetadataKind::NAME: \
return #NAME;
#include "swift/ABI/MetadataKind.def"
default:
return "<unknown>";
}
}
/***************************************************************************/
/*** Debugging dump methods ************************************************/
/***************************************************************************/
#ifndef NDEBUG
template <> SWIFT_USED void Metadata::dump() const {
printf("TargetMetadata.\n");
printf("Kind: %s.\n", getStringForMetadataKind(getKind()).data());
printf("Value Witnesses: %p.\n", getValueWitnesses());
if (auto *contextDescriptor = getTypeContextDescriptor()) {
printf("Name: %s.\n", contextDescriptor->Name.get());
printf("Type Context Description: %p.\n", contextDescriptor);
if (contextDescriptor->isGeneric()) {
auto genericCount = contextDescriptor->getFullGenericContextHeader().Base.getNumArguments();
auto *args = getGenericArgs();
printf("Generic Args: %u: [", genericCount);
for (uint32_t i = 0; i < genericCount; ++i) {
if (i > 0)
printf(", ");
printf("%p", args[i]);
}
printf("]\n");
}
}
if (auto *tuple = dyn_cast<TupleTypeMetadata>(this)) {
printf("Labels: %s.\n", tuple->Labels);
}
if (auto *existential = dyn_cast<ExistentialTypeMetadata>(this)) {
printf("Is class bounded: %s.\n",
existential->isClassBounded() ? "true" : "false");
auto protocols = existential->getProtocols();
bool first = true;
printf("Protocols: ");
for (auto protocol : protocols) {
if (!first)
printf(" & ");
printf("%s", protocol.getName());
first = false;
}
if (auto *superclass = existential->getSuperclassConstraint())
if (auto *contextDescriptor = superclass->getTypeContextDescriptor())
printf("Superclass constraint: %s.\n", contextDescriptor->Name.get());
printf("\n");
}
#if SWIFT_OBJC_INTEROP
if (auto *classObject = getClassObject()) {
printf("ObjC Name: %s.\n", class_getName(
reinterpret_cast<Class>(const_cast<ClassMetadata *>(classObject))));
printf("Class Object: %p.\n", classObject);
}
#endif
}
template <> SWIFT_USED void ContextDescriptor::dump() const {
printf("TargetTypeContextDescriptor.\n");
printf("Flags: 0x%x.\n", this->Flags.getIntValue());
printf("Parent: %p.\n", this->Parent.get());
if (auto *typeDescriptor = dyn_cast<TypeContextDescriptor>(this)) {
printf("Name: %s.\n", typeDescriptor->Name.get());
printf("Fields: %p.\n", typeDescriptor->Fields.get());
printf("Access function: %p.\n",
static_cast<void *>(typeDescriptor->getAccessFunction()));
}
}
template <> SWIFT_USED void EnumDescriptor::dump() const {
printf("TargetEnumDescriptor.\n");
printf("Flags: 0x%x.\n", this->Flags.getIntValue());
printf("Parent: %p.\n", this->Parent.get());
printf("Name: %s.\n", Name.get());
printf("Access function: %p.\n", static_cast<void *>(getAccessFunction()));
printf("Fields: %p.\n", Fields.get());
printf("NumPayloadCasesAndPayloadSizeOffset: 0x%08x "
"(payload cases: %u - payload size offset: %zu).\n",
NumPayloadCasesAndPayloadSizeOffset,
getNumPayloadCases(), getPayloadSizeOffset());
printf("NumEmptyCases: %u\n", NumEmptyCases);
}
#endif
/***************************************************************************/
/*** Protocol witness tables ***********************************************/
/***************************************************************************/
namespace {
/// A cache-entry type suitable for use with LockingConcurrentMap.
class WitnessTableCacheEntry :
public SimpleLockingCacheEntryBase<WitnessTableCacheEntry, WitnessTable*> {
/// The type for which this table was instantiated.
const Metadata * const Type;
/// The protocol conformance descriptor. This is only kept around so that we
/// can compute the size of an entry correctly in case of a race to
/// allocate the entry.
const ProtocolConformanceDescriptor * const Conformance;
public:
/// Do the structural initialization necessary for this entry to appear
/// in a concurrent map.
WitnessTableCacheEntry(const Metadata *type,
WaitQueue::Worker &worker,
const ProtocolConformanceDescriptor *conformance,
const void * const *instantiationArgs)
: SimpleLockingCacheEntryBase(worker),
Type(type), Conformance(conformance) {}
intptr_t getKeyIntValueForDump() const {
return reinterpret_cast<intptr_t>(Type);
}
friend llvm::hash_code hash_value(const WitnessTableCacheEntry &value) {
return llvm::hash_value(value.Type);
}
/// The key value of the entry is just its type pointer.
bool matchesKey(const Metadata *type) {
return Type == type;
}
static size_t getExtraAllocationSize(
const Metadata *type,
WaitQueue::Worker &worker,
const ProtocolConformanceDescriptor *conformance,
const void * const *instantiationArgs) {
return getWitnessTableSize(conformance);
}
size_t getExtraAllocationSize() const {
return getWitnessTableSize(Conformance);
}
static size_t getWitnessTableSize(
const ProtocolConformanceDescriptor *conformance) {
auto protocol = conformance->getProtocol();
auto genericTable = conformance->getGenericWitnessTable();
size_t numPrivateWords = genericTable->getWitnessTablePrivateSizeInWords();
size_t numRequirementWords =
WitnessTableFirstRequirementOffset + protocol->NumRequirements;
return (numPrivateWords + numRequirementWords) * sizeof(void*);
}
WitnessTable *allocate(const ProtocolConformanceDescriptor *conformance,
const void * const *instantiationArgs);
};
using GenericWitnessTableCache =
MetadataCache<WitnessTableCacheEntry, GenericWitnessTableCacheTag>;
using LazyGenericWitnessTableCache = Lazy<GenericWitnessTableCache>;
class GlobalWitnessTableCacheEntry {
public:
const GenericWitnessTable *Gen;
GenericWitnessTableCache Cache;
GlobalWitnessTableCacheEntry(const GenericWitnessTable *gen)
: Gen(gen), Cache() {}
intptr_t getKeyIntValueForDump() {
return reinterpret_cast<intptr_t>(Gen);
}
bool matchesKey(const GenericWitnessTable *gen) const {
return gen == Gen;
}
friend llvm::hash_code hash_value(const GlobalWitnessTableCacheEntry &value) {
return llvm::hash_value(value.Gen);
}
static size_t
getExtraAllocationSize(const GenericWitnessTable *gen) {
return 0;
}
size_t getExtraAllocationSize() const { return 0; }
};
static SimpleGlobalCache<GlobalWitnessTableCacheEntry, GlobalWitnessTableCacheTag>
GlobalWitnessTableCache;
} // end anonymous namespace
/// Fetch the cache for a generic witness-table structure.
static GenericWitnessTableCache &getCache(const GenericWitnessTable *gen) {
// Keep this assert even if you change the representation above.
static_assert(sizeof(LazyGenericWitnessTableCache) <=
sizeof(GenericWitnessTable::PrivateDataType),
"metadata cache is larger than the allowed space");
if (gen->PrivateData == nullptr) {
return GlobalWitnessTableCache.getOrInsert(gen).first->Cache;
}
auto lazyCache =
reinterpret_cast<LazyGenericWitnessTableCache*>(gen->PrivateData.get());
return lazyCache->get();
}
/// If there's no initializer, no private storage, and all requirements
/// are present, we don't have to instantiate anything; just return the
/// witness table template.
static bool doesNotRequireInstantiation(
const ProtocolConformanceDescriptor *conformance,
const GenericWitnessTable *genericTable) {
// If the table says it requires instantiation, it does.
if (genericTable->requiresInstantiation()) {
return false;
}
// If we have resilient witnesses, we require instantiation.
if (!conformance->getResilientWitnesses().empty()) {
return false;
}
// If we don't have the exact number of witnesses expected, we require
// instantiation.
if (genericTable->WitnessTableSizeInWords !=
(conformance->getProtocol()->NumRequirements +
WitnessTableFirstRequirementOffset)) {
return false;
}
// If we have an instantiation function or private data, we require
// instantiation.
if (!genericTable->Instantiator.isNull() ||
genericTable->getWitnessTablePrivateSizeInWords() > 0) {
return false;
}
return true;
}
#if SWIFT_PTRAUTH
static const unsigned swift_ptrauth_key_associated_type =
ptrauth_key_process_independent_code;
/// Given an unsigned pointer to an associated-type protocol witness,
/// fill in the appropriate slot in the witness table we're building.
static void initAssociatedTypeProtocolWitness(const Metadata **slot,
const Metadata *witness,
const ProtocolRequirement &reqt) {
assert(reqt.Flags.getKind() ==
ProtocolRequirementFlags::Kind::AssociatedTypeAccessFunction);
// FIXME: this should use ptrauth_key_process_independent_data
// now that it no longer stores a function pointer.
swift_ptrauth_init(slot, witness, reqt.Flags.getExtraDiscriminator());
}
static const unsigned swift_ptrauth_key_associated_conformance =
ptrauth_key_process_independent_code;
/// Given an unsigned pointer to an associated-conformance protocol witness,
/// fill in the appropriate slot in the witness table we're building.
static void initAssociatedConformanceProtocolWitness(void **slot, void *witness,
const ProtocolRequirement &reqt) {
assert(reqt.Flags.getKind() ==
ProtocolRequirementFlags::Kind::AssociatedConformanceAccessFunction);
// FIXME: this should use ptrauth_key_process_independent_data
// now that it no longer stores a function pointer.
swift_ptrauth_init(slot, witness, reqt.Flags.getExtraDiscriminator());
}
#endif
/// Given an unsigned pointer to an arbitrary protocol witness, fill
/// in a slot in the witness table we're building.
static void initProtocolWitness(void **slot, void *witness,
const ProtocolRequirement &reqt) {
#if SWIFT_PTRAUTH
switch (reqt.Flags.getKind()) {
// Base protocols use no signing at all right now.
case ProtocolRequirementFlags::Kind::BaseProtocol:
*slot = witness;
return;
// Method requirements use address-discriminated signing with the
// function-pointer key.
case ProtocolRequirementFlags::Kind::Method:
case ProtocolRequirementFlags::Kind::Init:
case ProtocolRequirementFlags::Kind::Getter:
case ProtocolRequirementFlags::Kind::Setter:
case ProtocolRequirementFlags::Kind::ReadCoroutine:
case ProtocolRequirementFlags::Kind::ModifyCoroutine:
swift_ptrauth_init_code_or_data(slot, witness,
reqt.Flags.getExtraDiscriminator(),
!reqt.Flags.isAsync());
return;
case ProtocolRequirementFlags::Kind::AssociatedConformanceAccessFunction:
initAssociatedConformanceProtocolWitness(slot, witness, reqt);
return;
case ProtocolRequirementFlags::Kind::AssociatedTypeAccessFunction:
initAssociatedTypeProtocolWitness(reinterpret_cast<const Metadata **>(
const_cast<const void**>(slot)),
reinterpret_cast<const Metadata *>(
witness),
reqt);
return;
}
swift_unreachable("bad witness kind");
#else
*slot = witness;
#endif
}
/// Copy an arbitrary protocol witness from another table.
static void copyProtocolWitness(void **dest, void * const *src,
const ProtocolRequirement &reqt) {
#if SWIFT_PTRAUTH
switch (reqt.Flags.getKind()) {
// Base protocols use no signing at all right now.
case ProtocolRequirementFlags::Kind::BaseProtocol:
*dest = *src;
return;
// Method requirements use address-discriminated signing with the
// function-pointer key.
case ProtocolRequirementFlags::Kind::Method:
case ProtocolRequirementFlags::Kind::Init:
case ProtocolRequirementFlags::Kind::Getter:
case ProtocolRequirementFlags::Kind::Setter:
case ProtocolRequirementFlags::Kind::ReadCoroutine:
case ProtocolRequirementFlags::Kind::ModifyCoroutine:
swift_ptrauth_copy_code_or_data(
dest, src, reqt.Flags.getExtraDiscriminator(), !reqt.Flags.isAsync(),
/*allowNull*/ true); // NULL allowed for VFE (methods in the vtable
// might be proven unused and null'ed)
return;
// FIXME: these should both use ptrauth_key_process_independent_data now.
case ProtocolRequirementFlags::Kind::AssociatedConformanceAccessFunction:
case ProtocolRequirementFlags::Kind::AssociatedTypeAccessFunction:
swift_ptrauth_copy(
dest, src, reqt.Flags.getExtraDiscriminator(),
/*allowNull*/ true); // NULL allowed for VFE (methods in the vtable
// might be proven unused and null'ed)
return;
}
swift_unreachable("bad witness kind");
#else
*dest = *src;
#endif
}
/// Initialize witness table entries from order independent resilient
/// witnesses stored in the generic witness table structure itself.
static void initializeResilientWitnessTable(
const ProtocolConformanceDescriptor *conformance,
const Metadata *conformingType,
const GenericWitnessTable *genericTable,
void **table) {
auto protocol = conformance->getProtocol();
auto requirements = protocol->getRequirements();
auto witnesses = conformance->getResilientWitnesses();
// Loop over the provided witnesses, filling in appropriate entry.
for (const auto &witness : witnesses) {
// Retrieve the requirement descriptor.
auto reqDescriptor = witness.Requirement.get();
// The requirement descriptor may be NULL, in which case this is a
// requirement introduced in a later version of the protocol.
if (!reqDescriptor) continue;
// If the requirement descriptor doesn't land within the bounds of the
// requirements, abort.
if (reqDescriptor < requirements.begin() ||
reqDescriptor >= requirements.end()) {
fatalError(0, "generic witness table at %p contains out-of-bounds "
"requirement descriptor %p\n",
genericTable, reqDescriptor);
}
unsigned witnessIndex = (reqDescriptor - requirements.data()) +
WitnessTableFirstRequirementOffset;
auto &reqt = requirements[reqDescriptor - requirements.begin()];
// This is an unsigned pointer formed from a relative address.
void *impl = witness.getWitness(reqt.Flags);
initProtocolWitness(&table[witnessIndex], impl, reqt);
}
// Loop over the requirements, filling in default implementations where
// needed.
for (size_t i = 0, e = protocol->NumRequirements; i < e; ++i) {
unsigned witnessIndex = WitnessTableFirstRequirementOffset + i;
// If we don't have a witness, fill in the default implementation.
// If we already have a witness, there's nothing to do.
auto &reqt = requirements[i];
if (!table[witnessIndex]) {
// This is an unsigned pointer formed from a relative address.
void *impl = reqt.getDefaultImplementation();
initProtocolWitness(&table[witnessIndex], impl, reqt);
}
// Realize base protocol witnesses.
if (reqt.Flags.getKind() == ProtocolRequirementFlags::Kind::BaseProtocol &&
table[witnessIndex]) {
// Realize the base protocol witness table. We call the slow function
// because the fast function doesn't allow base protocol requirements.
auto baseReq = protocol->getRequirementBaseDescriptor();
(void)swift_getAssociatedConformanceWitnessSlow((WitnessTable *)table,
conformingType,
conformingType,
baseReq, &reqt);
}
}
}
// Instantiate a generic or resilient witness table into a `buffer`
// that has already been allocated of the appropriate size and zeroed out.
static WitnessTable *
instantiateWitnessTable(const Metadata *Type,
const ProtocolConformanceDescriptor *conformance,
const void * const *instantiationArgs,
void **fullTable) {
auto protocol = conformance->getProtocol();
auto genericTable = conformance->getGenericWitnessTable();
auto *genericArgs = Type->getGenericArgs();
// The number of witnesses provided by the table pattern.
size_t numPatternWitnesses = genericTable->WitnessTableSizeInWords;
// The total number of requirements.
size_t numRequirements =
protocol->NumRequirements + WitnessTableFirstRequirementOffset;
assert(numPatternWitnesses <= numRequirements);
(void)numRequirements;
// Number of bytes for any private storage used by the conformance itself.
size_t privateSizeInWords = genericTable->getWitnessTablePrivateSizeInWords();
// Advance the address point; the private storage area is accessed via
// negative offsets.
auto table = fullTable + privateSizeInWords;
if (auto pattern =
reinterpret_cast<void * const *>(
&*conformance->getWitnessTablePattern())) {
auto requirements = protocol->getRequirements();
// Fill in the provided part of the requirements from the pattern.
for (size_t i = 0, e = numPatternWitnesses; i < e; ++i) {
size_t requirementIndex = i - WitnessTableFirstRequirementOffset;
if (i < WitnessTableFirstRequirementOffset)
table[i] = pattern[i];
else
copyProtocolWitness(&table[i], &pattern[i],
requirements[requirementIndex]);
}
} else {
// Put the conformance descriptor in place. Instantiation will fill in the
// rest.
assert(numPatternWitnesses == 0);
table[0] = (void *)conformance;
}
// Copy any instantiation arguments that correspond to conditional
// requirements into the private area.
{
unsigned currentInstantiationArg = 0;
llvm::ArrayRef<GenericPackShapeDescriptor> packShapeDescriptors =
conformance->getConditionalPackShapeDescriptors();
unsigned packIdx = 0;
for (const auto &conditionalRequirement
: conformance->getConditionalRequirements()) {
if (!conditionalRequirement.Flags.hasKeyArgument())
continue;
assert(currentInstantiationArg < privateSizeInWords);
auto *instantiationArg = instantiationArgs[currentInstantiationArg];
// Heap-allocate witness tables for conditional pack conformance requirements.
if (conditionalRequirement.Flags.isPackRequirement()) {
auto packShapeDescriptor = packShapeDescriptors[packIdx];
assert(packShapeDescriptor.Kind == GenericPackKind::WitnessTable);
assert(packShapeDescriptor.Index == currentInstantiationArg);
size_t count = reinterpret_cast<const size_t>(
genericArgs[packShapeDescriptor.ShapeClass]);
auto *wtable = reinterpret_cast<const WitnessTable * const*>(instantiationArg);
wtable = swift_allocateWitnessTablePack(wtable, count);
instantiationArg = wtable;
++packIdx;
}
table[-1 - (int)currentInstantiationArg] = const_cast<void *>(instantiationArg);
++currentInstantiationArg;
}
}
// Fill in any default requirements.
initializeResilientWitnessTable(conformance, Type, genericTable, table);
auto castTable = reinterpret_cast<WitnessTable*>(table);
// Call the instantiation function if present.
if (!genericTable->Instantiator.isNull()) {
genericTable->Instantiator(castTable, Type, instantiationArgs);
}
return castTable;
}
/// Instantiate a brand new witness table for a resilient or generic
/// protocol conformance.
WitnessTable *
WitnessTableCacheEntry::allocate(
const ProtocolConformanceDescriptor *conformance,
const void * const *instantiationArgs) {
// Find the allocation.
void **fullTable = reinterpret_cast<void**>(this + 1);
// Zero out the witness table.
memset(fullTable, 0, getWitnessTableSize(conformance));
// Instantiate the table.
return instantiateWitnessTable(Type, Conformance, instantiationArgs, fullTable);
}
/// Instantiate the witness table for a nondependent conformance that only has
/// one possible instantiation.
static WitnessTable *
getNondependentWitnessTable(const ProtocolConformanceDescriptor *conformance,
const Metadata *type) {
assert(conformance->getGenericWitnessTable()->PrivateData != nullptr);
// Check whether the table has already been instantiated.
auto tablePtr = reinterpret_cast<std::atomic<WitnessTable*> *>(
conformance->getGenericWitnessTable()->PrivateData.get());
auto existingTable = tablePtr->load(SWIFT_MEMORY_ORDER_CONSUME);
if (existingTable) {
return existingTable;
}
// Allocate space for the table.
auto tableSize = WitnessTableCacheEntry::getWitnessTableSize(conformance);
TaggedMetadataAllocator<SingletonGenericWitnessTableCacheTag> allocator;
auto buffer = (void **)allocator.Allocate(tableSize, alignof(void*));
memset(buffer, 0, tableSize);
// Instantiate the table.
auto table = instantiateWitnessTable(type, conformance, nullptr, buffer);
// See whether we can claim to be the one true table.
WitnessTable *orig = nullptr;
if (!tablePtr->compare_exchange_strong(orig, table, std::memory_order_release,
SWIFT_MEMORY_ORDER_CONSUME)) {
// Someone beat us to the punch. Throw away our table and return the
// existing one.
allocator.Deallocate(buffer);
return orig;
}
return table;
}
const WitnessTable *
swift::swift_getWitnessTable(const ProtocolConformanceDescriptor *conformance,
const Metadata *type,
const void * const *instantiationArgs) {
/// Local function to unique a foreign witness table, if needed.
auto uniqueForeignWitnessTableRef =
[conformance](const WitnessTable *candidate) {
if (!candidate || !conformance->isSynthesizedNonUnique())
return candidate;
auto conformingType =
cast<TypeContextDescriptor>(conformance->getTypeDescriptor());
return _getForeignWitnessTable(candidate,
conformingType,
conformance->getProtocol());
};
// When there is no generic table, or it doesn't require instantiation,
// use the pattern directly.
auto genericTable = conformance->getGenericWitnessTable();
if (!genericTable || doesNotRequireInstantiation(conformance, genericTable)) {
return uniqueForeignWitnessTableRef(conformance->getWitnessTablePattern());
}
// If the conformance is not dependent on generic arguments in the conforming
// type, then there is only one instantiation possible, so we can try to
// allocate only the table without the concurrent map structure.
//
// TODO: There is no metadata flag that directly encodes the "nondependent"
// as of the Swift 5.3 ABI. However, we can check whether the conforming
// type is generic; a nongeneric type's conformance can never be dependent (at
// least, not today). However, a generic type conformance may also be
// nondependent if it
auto typeDescription = conformance->getTypeDescriptor();
if (typeDescription && !typeDescription->isGeneric() &&
genericTable->PrivateData != nullptr) {
return getNondependentWitnessTable(conformance, type);
}
auto &cache = getCache(genericTable);
auto result = cache.getOrInsert(type, conformance, instantiationArgs);
// Our returned 'status' is the witness table itself.
return uniqueForeignWitnessTableRef(result.second);
}
namespace {
/// A cache-entry type suitable for use with LockingConcurrentMap.
class RelativeWitnessTableCacheEntry :
public SimpleLockingCacheEntryBase<RelativeWitnessTableCacheEntry,
RelativeWitnessTable*> {
/// The type for which this table was instantiated.
const Metadata * const Type;
/// The protocol conformance descriptor. This is only kept around so that we
/// can compute the size of an entry correctly in case of a race to
/// allocate the entry.
const ProtocolConformanceDescriptor * const Conformance;
public:
/// Do the structural initialization necessary for this entry to appear
/// in a concurrent map.
RelativeWitnessTableCacheEntry(const Metadata *type,
WaitQueue::Worker &worker,
const ProtocolConformanceDescriptor *conformance,
const void * const *instantiationArgs)
: SimpleLockingCacheEntryBase(worker),
Type(type), Conformance(conformance) {}
intptr_t getKeyIntValueForDump() const {
return reinterpret_cast<intptr_t>(Type);
}
friend llvm::hash_code hash_value(const RelativeWitnessTableCacheEntry &value) {
return llvm::hash_value(value.Type);
}
/// The key value of the entry is just its type pointer.
bool matchesKey(const Metadata *type) {
return Type == type;
}
static size_t getExtraAllocationSize(
const Metadata *type,
WaitQueue::Worker &worker,
const ProtocolConformanceDescriptor *conformance,
const void * const *instantiationArgs) {
return getWitnessTableSize(conformance);
}
size_t getExtraAllocationSize() const {
return getWitnessTableSize(Conformance);
}
static size_t getNumBaseProtocolRequirements(
const ProtocolConformanceDescriptor *conformance) {
size_t result = 0;
size_t currIdx = 0;
auto protocol = conformance->getProtocol();
auto requirements = protocol->getRequirements();
for (auto &req : requirements) {
++currIdx;
if (req.Flags.getKind() ==
ProtocolRequirementFlags::Kind::BaseProtocol) {
++result;
// We currently assume that base protocol requirements preceed other
// requirements i.e we store the base protocol pointers sequentially in
// instantiateRelativeWitnessTable starting at index 1.
assert(currIdx == result &&
"base protocol requirements come before everything else");
(void)currIdx;
}
}
return result;
}
static size_t getWitnessTableSize(
const ProtocolConformanceDescriptor *conformance) {
auto genericTable = conformance->getGenericWitnessTable();
size_t numPrivateWords = genericTable->getWitnessTablePrivateSizeInWords();
size_t numRequirementWords =
WitnessTableFirstRequirementOffset +
getNumBaseProtocolRequirements(conformance);
return (numPrivateWords + numRequirementWords) * sizeof(void*);
}
RelativeWitnessTable *allocate(const ProtocolConformanceDescriptor *conformance,
const void * const *instantiationArgs);
};
using RelativeGenericWitnessTableCache =
MetadataCache<RelativeWitnessTableCacheEntry, GenericWitnessTableCacheTag>;
using LazyRelativeGenericWitnessTableCache = Lazy<RelativeGenericWitnessTableCache>;
class GlobalRelativeWitnessTableCacheEntry {
public:
const GenericWitnessTable *Gen;
RelativeGenericWitnessTableCache Cache;
GlobalRelativeWitnessTableCacheEntry(const GenericWitnessTable *gen)
: Gen(gen), Cache() {}
intptr_t getKeyIntValueForDump() {
return reinterpret_cast<intptr_t>(Gen);
}
bool matchesKey(const GenericWitnessTable *gen) const {
return gen == Gen;
}
friend llvm::hash_code hash_value(const GlobalRelativeWitnessTableCacheEntry &value) {
return llvm::hash_value(value.Gen);
}
static size_t
getExtraAllocationSize(const GenericWitnessTable *gen) {
return 0;
}
size_t getExtraAllocationSize() const { return 0; }
};
static SimpleGlobalCache<GlobalRelativeWitnessTableCacheEntry,
GlobalWitnessTableCacheTag>
GlobalRelativeWitnessTableCache;
} // end anonymous namespace
using RelativeBaseWitness = RelativeDirectPointer<void, true /*nullable*/>;
// Instantiate a relative witness table into a `buffer`
// that has already been allocated of the appropriate size and zeroed out.
//
// The layout of a dynamically allocated relative witness table is:
// [ conditional conformance n] ... private area
// [ conditional conformance 0] (negatively adressed)
// pointer -> [ pointer to relative witness table (pattern) ]
// [ base protocol witness table pointer 0 ] ... base protocol
// [ base protocol witness table pointer n ] pointers
static RelativeWitnessTable *
instantiateRelativeWitnessTable(const Metadata *Type,
const ProtocolConformanceDescriptor *conformance,
const void * const *instantiationArgs,
void **fullTable) {
auto genericTable = conformance->getGenericWitnessTable();
auto pattern = reinterpret_cast<uint32_t const *>(
&*conformance->getWitnessTablePattern());
assert(pattern);
auto numBaseProtocols =
RelativeWitnessTableCacheEntry::getNumBaseProtocolRequirements(conformance);
// The number of witnesses provided by the table pattern.
size_t numPatternWitnesses = genericTable->WitnessTableSizeInWords;
assert(numBaseProtocols <= numPatternWitnesses);
(void)numPatternWitnesses;
// Number of bytes for any private storage used by the conformance itself.
size_t privateSizeInWords = genericTable->getWitnessTablePrivateSizeInWords();
// Advance the address point; the private storage area is accessed via
// negative offsets.
auto table = fullTable + privateSizeInWords;
#if SWIFT_PTRAUTH
table[0] = ptrauth_sign_unauthenticated(
(void*)pattern,
ptrauth_key_process_independent_data,
SpecialPointerAuthDiscriminators::RelativeProtocolWitnessTable);
#else
table[0] = (void*)pattern;
#endif
assert(1 == WitnessTableFirstRequirementOffset);
// Fill in the base protocols of the requirements from the pattern.
for (size_t i = 0, e = numBaseProtocols; i < e; ++i) {
size_t index = i + WitnessTableFirstRequirementOffset;
#if SWIFT_PTRAUTH
auto rawValue = ((RelativeBaseWitness const *)pattern)[index].get();
table[index] = (rawValue == nullptr) ? rawValue :
ptrauth_sign_unauthenticated(
rawValue,
ptrauth_key_process_independent_data,
SpecialPointerAuthDiscriminators::RelativeProtocolWitnessTable);
#else
table[index] = ((RelativeBaseWitness const *)pattern)[index].get();
#endif
}
// Copy any instantiation arguments that correspond to conditional
// requirements into the private area.
{
unsigned currentInstantiationArg = 0;
auto copyNextInstantiationArg = [&] {
assert(currentInstantiationArg < privateSizeInWords);
table[-1 - (int)currentInstantiationArg] =
const_cast<void *>(instantiationArgs[currentInstantiationArg]);
++currentInstantiationArg;
};
for (const auto &conditionalRequirement
: conformance->getConditionalRequirements()) {
if (conditionalRequirement.Flags.hasKeyArgument())
copyNextInstantiationArg();
assert(!conditionalRequirement.Flags.isPackRequirement() &&
"Not supported yet");
}
}
// Call the instantiation function if present.
if (!genericTable->Instantiator.isNull()) {
auto castTable = reinterpret_cast<WitnessTable*>(table);
genericTable->Instantiator(castTable, Type, instantiationArgs);
}
return reinterpret_cast<RelativeWitnessTable*>(table);
}
/// Instantiate a brand new relative witness table for a generic protocol conformance.
RelativeWitnessTable *
RelativeWitnessTableCacheEntry::allocate(
const ProtocolConformanceDescriptor *conformance,
const void * const *instantiationArgs) {
// Find the allocation.
void **fullTable = reinterpret_cast<void**>(this + 1);
// Zero out the witness table.
memset(fullTable, 0, getWitnessTableSize(conformance));
// Instantiate the table.
return instantiateRelativeWitnessTable(Type, Conformance, instantiationArgs,
fullTable);
}
/// Fetch the cache for a generic witness-table structure.
static RelativeGenericWitnessTableCache &getCacheForRelativeWitness(
const GenericWitnessTable *gen) {
// Keep this assert even if you change the representation above.
static_assert(sizeof(LazyRelativeGenericWitnessTableCache) <=
sizeof(GenericWitnessTable::PrivateDataType),
"metadata cache is larger than the allowed space");
if (gen->PrivateData == nullptr) {
return GlobalRelativeWitnessTableCache.getOrInsert(gen).first->Cache;
}
auto lazyCache =
reinterpret_cast<LazyRelativeGenericWitnessTableCache*>(gen->PrivateData.get());
return lazyCache->get();
}
const RelativeWitnessTable *
swift::swift_getWitnessTableRelative(const ProtocolConformanceDescriptor *conformance,
const Metadata *type,
const void * const *instantiationArgs) {
/// Local function to unique a foreign witness table, if needed.
auto uniqueForeignWitnessTableRef =
[conformance](const WitnessTable *candidate) {
if (!candidate || !conformance->isSynthesizedNonUnique())
return candidate;
auto conformingType =
cast<TypeContextDescriptor>(conformance->getTypeDescriptor());
return _getForeignWitnessTable(candidate,
conformingType,
conformance->getProtocol());
};
auto genericTable = conformance->getGenericWitnessTable();
// When there is no generic table, or it doesn't require instantiation,
// use the pattern directly.
if (!genericTable || doesNotRequireInstantiation(conformance, genericTable)) {
assert(!conformance->isSynthesizedNonUnique());
auto pattern = conformance->getWitnessTablePattern();
auto table = uniqueForeignWitnessTableRef(pattern);
#if SWIFT_STDLIB_USE_RELATIVE_PROTOCOL_WITNESS_TABLES && SWIFT_PTRAUTH
table = ptrauth_sign_unauthenticated(table,
ptrauth_key_process_independent_data,
SpecialPointerAuthDiscriminators::RelativeProtocolWitnessTable);
#endif
return reinterpret_cast<const RelativeWitnessTable*>(table);
}
assert(genericTable &&
!doesNotRequireInstantiation(conformance, genericTable));
assert(!conformance->isSynthesizedNonUnique());
auto &cache = getCacheForRelativeWitness(genericTable);
auto result = cache.getOrInsert(type, conformance, instantiationArgs);
// Our returned 'status' is the witness table itself.
auto table = uniqueForeignWitnessTableRef(
(const WitnessTable*)result.second);
// Mark this as a dynamic (conditional conformance) protocol witness table.
return reinterpret_cast<RelativeWitnessTable*>(((uintptr_t)table) |
(uintptr_t)0x1);
}
/// Find the name of the associated type with the given descriptor.
static StringRef findAssociatedTypeName(const ProtocolDescriptor *protocol,
const ProtocolRequirement *assocType) {
// If we don't have associated type names, there's nothing to do.
const char *associatedTypeNamesPtr = protocol->AssociatedTypeNames.get();
if (!associatedTypeNamesPtr) return StringRef();
StringRef associatedTypeNames(associatedTypeNamesPtr);
for (const auto &req : protocol->getRequirements()) {
if (req.Flags.getKind() !=
ProtocolRequirementFlags::Kind::AssociatedTypeAccessFunction)
continue;
// If we've found the requirement, we're done.
auto splitIdx = associatedTypeNames.find(' ');
if (&req == assocType) {
return associatedTypeNames.substr(0, splitIdx);
}
// Skip this associated type name.
associatedTypeNames = associatedTypeNames.substr(splitIdx).substr(1);
}
return StringRef();
}
using AssociatedTypeWitness = std::atomic<const Metadata *>;
SWIFT_CC(swift)
static MetadataResponse
swift_getAssociatedTypeWitnessSlowImpl(
MetadataRequest request,
WitnessTable *wtable,
const Metadata *conformingType,
const ProtocolRequirement *reqBase,
const ProtocolRequirement *assocType) {
#ifndef NDEBUG
{
const ProtocolConformanceDescriptor *conformance = wtable->getDescription();
const ProtocolDescriptor *protocol = conformance->getProtocol();
auto requirements = protocol->getRequirements();
assert(assocType >= requirements.begin() &&
assocType < requirements.end());
assert(reqBase == requirements.data() - WitnessTableFirstRequirementOffset);
assert(assocType->Flags.getKind() ==
ProtocolRequirementFlags::Kind::AssociatedTypeAccessFunction);
}
#endif
// Retrieve the witness.
unsigned witnessIndex = assocType - reqBase;
auto *witnessAddr = &((AssociatedTypeWitness*)wtable)[witnessIndex];
auto witness = witnessAddr->load(std::memory_order_acquire);
#if SWIFT_PTRAUTH
uint16_t extraDiscriminator = assocType->Flags.getExtraDiscriminator();
witness = ptrauth_auth_data(witness, swift_ptrauth_key_associated_type,
ptrauth_blend_discriminator(witnessAddr,
extraDiscriminator));
#endif
// If the low bit of the witness is clear, it's already a metadata pointer.
if (SWIFT_LIKELY((reinterpret_cast<uintptr_t>(witness) &
ProtocolRequirementFlags::AssociatedTypeMangledNameBit) ==
0)) {
// Cached metadata pointers are always complete.
return MetadataResponse{(const Metadata *)witness, MetadataState::Complete};
}
// Find the mangled name.
const char *mangledNameBase =
(const char *)(uintptr_t(witness) &
~ProtocolRequirementFlags::AssociatedTypeMangledNameBit);
// Check whether the mangled name has the prefix byte indicating that
// the mangled name is relative to the protocol itself.
bool inProtocolContext = false;
if ((uint8_t)*mangledNameBase ==
ProtocolRequirementFlags::AssociatedTypeInProtocolContextByte) {
inProtocolContext = true;
++mangledNameBase;
}
// Dig out the protocol.
const ProtocolConformanceDescriptor *conformance = wtable->getDescription();
const ProtocolDescriptor *protocol = conformance->getProtocol();
// Extract the mangled name itself.
StringRef mangledName =
Demangle::makeSymbolicMangledNameStringRef(mangledNameBase);
// Demangle the associated type.
TypeLookupErrorOr<TypeInfo> result;
if (inProtocolContext) {
// The protocol's Self is the only generic parameter that can occur in the
// type.
result = swift_getTypeByMangledName(
request, mangledName, nullptr,
[conformingType](unsigned depth, unsigned index) -> const Metadata * {
if (depth == 0 && index == 0)
return conformingType;
return nullptr;
},
[&](const Metadata *type, unsigned index) -> const WitnessTable * {
auto requirements = protocol->getRequirements();
auto dependentDescriptor = requirements.data() + index;
if (dependentDescriptor < requirements.begin() ||
dependentDescriptor >= requirements.end())
return nullptr;
return swift_getAssociatedConformanceWitness(wtable, conformingType,
type, reqBase,
dependentDescriptor);
});
} else {
// The generic parameters in the associated type name are those of the
// conforming type.
// For a class, chase the superclass chain up until we hit the
// type that specified the conformance.
auto originalConformingType = findConformingSuperclass(conformingType,
conformance);
SubstGenericParametersFromMetadata substitutions(originalConformingType);
result = swift_getTypeByMangledName(
request, mangledName, substitutions.getGenericArgs(),
[&substitutions](unsigned depth, unsigned index) {
return substitutions.getMetadata(depth, index).Ptr;
},
[&substitutions](const Metadata *type, unsigned index) {
return substitutions.getWitnessTable(type, index);
});
}
auto *error = result.getError();
MetadataResponse response = result.getType().getResponse();
auto assocTypeMetadata = response.Value;
if (error || !assocTypeMetadata) {
const char *errStr = error ? error->copyErrorString()
: "NULL metadata but no error was provided";
auto conformingTypeNameInfo = swift_getTypeName(conformingType, true);
StringRef conformingTypeName(conformingTypeNameInfo.data,
conformingTypeNameInfo.length);
StringRef assocTypeName = findAssociatedTypeName(protocol, assocType);
fatalError(0,
"failed to demangle witness for associated type '%s' in "
"conformance '%s: %s' from mangled name '%s' - %s\n",
assocTypeName.str().c_str(), conformingTypeName.str().c_str(),
protocol->Name.get(), mangledName.str().c_str(), errStr);
}
assert((uintptr_t(assocTypeMetadata) &
ProtocolRequirementFlags::AssociatedTypeMangledNameBit) == 0);
// If the metadata was completed, record it in the witness table.
if (response.State == MetadataState::Complete) {
// We pass type metadata around as unsigned pointers, but we sign them
// in witness tables, which doesn't provide all that much extra security.
auto valueToStore = assocTypeMetadata;
#if SWIFT_PTRAUTH
valueToStore = ptrauth_sign_unauthenticated(valueToStore,
swift_ptrauth_key_associated_type,
ptrauth_blend_discriminator(witnessAddr,
extraDiscriminator));
#endif
witnessAddr->store(valueToStore, std::memory_order_release);
}
return response;
}
MetadataResponse
swift::swift_getAssociatedTypeWitness(MetadataRequest request,
WitnessTable *wtable,
const Metadata *conformingType,
const ProtocolRequirement *reqBase,
const ProtocolRequirement *assocType) {
assert(assocType->Flags.getKind() ==
ProtocolRequirementFlags::Kind::AssociatedTypeAccessFunction);
// If the low bit of the witness is clear, it's already a metadata pointer.
unsigned witnessIndex = assocType - reqBase;
auto *witnessAddr = &((const AssociatedTypeWitness *)wtable)[witnessIndex];
auto witness = witnessAddr->load(std::memory_order_acquire);
#if SWIFT_PTRAUTH
uint16_t extraDiscriminator = assocType->Flags.getExtraDiscriminator();
witness = ptrauth_auth_data(witness, swift_ptrauth_key_associated_type,
ptrauth_blend_discriminator(witnessAddr,
extraDiscriminator));
#endif
if (SWIFT_LIKELY((reinterpret_cast<uintptr_t>(witness) &
ProtocolRequirementFlags::AssociatedTypeMangledNameBit) ==
0)) {
// Cached metadata pointers are always complete.
return MetadataResponse{(const Metadata *)witness, MetadataState::Complete};
}
return swift_getAssociatedTypeWitnessSlow(request, wtable, conformingType,
reqBase, assocType);
}
RelativeWitnessTable *swift::lookThroughOptionalConditionalWitnessTable(
const RelativeWitnessTable *wtable) {
uintptr_t conditional_wtable = (uintptr_t)wtable;
if (conditional_wtable & 0x1) {
conditional_wtable = conditional_wtable & ~(uintptr_t)(0x1);
conditional_wtable = (uintptr_t)*(void**)conditional_wtable;
}
auto table = (RelativeWitnessTable*)conditional_wtable;
#if SWIFT_PTRAUTH
table = swift_auth_data_non_address(
table,
SpecialPointerAuthDiscriminators::RelativeProtocolWitnessTable);
#endif
return table;
}
SWIFT_CC(swift)
static MetadataResponse
swift_getAssociatedTypeWitnessRelativeSlowImpl(
MetadataRequest request,
RelativeWitnessTable *wtable,
const Metadata *conformingType,
const ProtocolRequirement *reqBase,
const ProtocolRequirement *assocType) {
wtable = lookThroughOptionalConditionalWitnessTable(wtable);
#ifndef NDEBUG
{
const ProtocolConformanceDescriptor *conformance = wtable->getDescription();
const ProtocolDescriptor *protocol = conformance->getProtocol();
auto requirements = protocol->getRequirements();
assert(assocType >= requirements.begin() &&
assocType < requirements.end());
assert(reqBase == requirements.data() - WitnessTableFirstRequirementOffset);
assert(assocType->Flags.getKind() ==
ProtocolRequirementFlags::Kind::AssociatedTypeAccessFunction);
}
#endif
// Retrieve the witness.
unsigned witnessIndex = assocType - reqBase;
auto *relativeDistanceAddr = &((int32_t*)wtable)[witnessIndex];
auto relativeDistance = *relativeDistanceAddr;
auto value = swift::detail::applyRelativeOffset(relativeDistanceAddr,
relativeDistance);
assert((value & 0x1) && "Expecting the bit to be set");
value = value & ~((uintptr_t)0x1);
const char *mangledNameBase = (const char*) value;
// Dig out the protocol.
const ProtocolConformanceDescriptor *conformance = wtable->getDescription();
const ProtocolDescriptor *protocol = conformance->getProtocol();
// Extract the mangled name itself.
StringRef mangledName =
Demangle::makeSymbolicMangledNameStringRef(mangledNameBase);
// The generic parameters in the associated type name are those of the
// conforming type.
// For a class, chase the superclass chain up until we hit the
// type that specified the conformance.
auto originalConformingType = findConformingSuperclass(conformingType,
conformance);
SubstGenericParametersFromMetadata substitutions(originalConformingType);
auto result = swift_getTypeByMangledName(
request, mangledName, substitutions.getGenericArgs(),
[&substitutions](unsigned depth, unsigned index) {
return substitutions.getMetadata(depth, index).Ptr;
},
[&substitutions](const Metadata *type, unsigned index) {
return substitutions.getWitnessTable(type, index);
});
auto *error = result.getError();
MetadataResponse response = result.getType().getResponse();
auto assocTypeMetadata = response.Value;
if (error || !assocTypeMetadata) {
const char *errStr = error ? error->copyErrorString()
: "NULL metadata but no error was provided";
auto conformingTypeNameInfo = swift_getTypeName(conformingType, true);
StringRef conformingTypeName(conformingTypeNameInfo.data,
conformingTypeNameInfo.length);
StringRef assocTypeName = findAssociatedTypeName(protocol, assocType);
fatalError(0,
"failed to demangle witness for associated type '%s' in "
"conformance '%s: %s' from mangled name '%s' - %s\n",
assocTypeName.str().c_str(), conformingTypeName.str().c_str(),
protocol->Name.get(), mangledName.str().c_str(), errStr);
}
assert((uintptr_t(assocTypeMetadata) &
ProtocolRequirementFlags::AssociatedTypeMangledNameBit) == 0);
return response;
}
MetadataResponse
swift::swift_getAssociatedTypeWitnessRelative(MetadataRequest request,
RelativeWitnessTable *wtable,
const Metadata *conformingType,
const ProtocolRequirement *reqBase,
const ProtocolRequirement *assocType) {
assert(assocType->Flags.getKind() ==
ProtocolRequirementFlags::Kind::AssociatedTypeAccessFunction);
return swift_getAssociatedTypeWitnessRelativeSlowImpl(request, wtable,
conformingType, reqBase,
assocType);
}
using AssociatedConformanceWitness = std::atomic<void *>;
SWIFT_CC(swift)
static const WitnessTable *swift_getAssociatedConformanceWitnessSlowImpl(
WitnessTable *wtable,
const Metadata *conformingType,
const Metadata *assocType,
const ProtocolRequirement *reqBase,
const ProtocolRequirement *assocConformance) {
#ifndef NDEBUG
{
const ProtocolConformanceDescriptor *conformance = wtable->getDescription();
const ProtocolDescriptor *protocol = conformance->getProtocol();
auto requirements = protocol->getRequirements();
assert(assocConformance >= requirements.begin() &&
assocConformance < requirements.end());
assert(reqBase == requirements.data() - WitnessTableFirstRequirementOffset);
assert(
assocConformance->Flags.getKind() ==
ProtocolRequirementFlags::Kind::AssociatedConformanceAccessFunction ||
assocConformance->Flags.getKind() ==
ProtocolRequirementFlags::Kind::BaseProtocol);
}
#endif
// Retrieve the witness.
unsigned witnessIndex = assocConformance - reqBase;
auto *witnessAddr = &((AssociatedConformanceWitness*)wtable)[witnessIndex];
auto witness = witnessAddr->load(std::memory_order_acquire);
#if SWIFT_PTRAUTH
// For associated protocols, the witness is signed with address
// discrimination.
// For base protocols, the witness isn't signed at all.
if (assocConformance->Flags.isSignedWithAddress()) {
uint16_t extraDiscriminator =
assocConformance->Flags.getExtraDiscriminator();
witness = ptrauth_auth_data(
witness, swift_ptrauth_key_associated_conformance,
ptrauth_blend_discriminator(witnessAddr, extraDiscriminator));
}
#endif
// Fast path: we've already resolved this to a witness table, so return it.
if (SWIFT_LIKELY((reinterpret_cast<uintptr_t>(witness) &
ProtocolRequirementFlags::AssociatedTypeMangledNameBit) ==
0)) {
return static_cast<const WitnessTable *>(witness);
}
// Find the mangled name.
const char *mangledNameBase =
(const char *)(uintptr_t(witness) &
~ProtocolRequirementFlags::AssociatedTypeMangledNameBit);
// Extract the mangled name itself.
if (*mangledNameBase == '\xFF')
++mangledNameBase;
StringRef mangledName =
Demangle::makeSymbolicMangledNameStringRef(mangledNameBase);
// Relative reference to an associate conformance witness function.
// FIXME: This is intended to be a temporary mangling, to be replaced
// by a real "protocol conformance" mangling.
if (mangledName.size() == 5 &&
(mangledName[0] == '\x07' || mangledName[0] == '\x08')) {
// Resolve the relative reference to the witness function.
int32_t offset;
memcpy(&offset, mangledName.data() + 1, 4);
void *ptr = TargetCompactFunctionPointer<InProcess, void>::resolve(mangledName.data() + 1, offset);
// Call the witness function.
AssociatedWitnessTableAccessFunction *witnessFn;
#if SWIFT_PTRAUTH
witnessFn =
(AssociatedWitnessTableAccessFunction *)ptrauth_sign_unauthenticated(
(void *)ptr, ptrauth_key_function_pointer, 0);
#else
witnessFn = (AssociatedWitnessTableAccessFunction *)ptr;
#endif
auto assocWitnessTable = witnessFn(assocType, conformingType, wtable);
assert((uintptr_t(assocWitnessTable) &
ProtocolRequirementFlags::AssociatedTypeMangledNameBit) == 0);
// The access function returns an unsigned pointer for now.
auto valueToStore = assocWitnessTable;
#if SWIFT_PTRAUTH
if (assocConformance->Flags.isSignedWithAddress()) {
uint16_t extraDiscriminator =
assocConformance->Flags.getExtraDiscriminator();
valueToStore = ptrauth_sign_unauthenticated(valueToStore,
swift_ptrauth_key_associated_conformance,
ptrauth_blend_discriminator(witnessAddr,
extraDiscriminator));
}
#endif
witnessAddr->store(valueToStore, std::memory_order_release);
return assocWitnessTable;
}
swift_unreachable("Invalid mangled associate conformance");
}
const WitnessTable *swift::swift_getAssociatedConformanceWitness(
WitnessTable *wtable,
const Metadata *conformingType,
const Metadata *assocType,
const ProtocolRequirement *reqBase,
const ProtocolRequirement *assocConformance) {
// We avoid using this function for initializing base protocol conformances
// so that we can have a better fast-path.
assert(assocConformance->Flags.getKind() ==
ProtocolRequirementFlags::Kind::AssociatedConformanceAccessFunction);
// Retrieve the witness.
unsigned witnessIndex = assocConformance - reqBase;
auto *witnessAddr = &((AssociatedConformanceWitness*)wtable)[witnessIndex];
auto witness = witnessAddr->load(std::memory_order_acquire);
#if SWIFT_PTRAUTH
uint16_t extraDiscriminator = assocConformance->Flags.getExtraDiscriminator();
witness = ptrauth_auth_data(witness, swift_ptrauth_key_associated_conformance,
ptrauth_blend_discriminator(witnessAddr,
extraDiscriminator));
#endif
// Fast path: we've already resolved this to a witness table, so return it.
if (SWIFT_LIKELY((reinterpret_cast<uintptr_t>(witness) &
ProtocolRequirementFlags::AssociatedTypeMangledNameBit) ==
0)) {
return static_cast<const WitnessTable *>(witness);
}
return swift_getAssociatedConformanceWitnessSlow(wtable, conformingType,
assocType, reqBase,
assocConformance);
}
SWIFT_CC(swift)
static const RelativeWitnessTable *swift_getAssociatedConformanceWitnessRelativeSlowImpl(
RelativeWitnessTable *wtable,
const Metadata *conformingType,
const Metadata *assocType,
const ProtocolRequirement *reqBase,
const ProtocolRequirement *assocConformance) {
auto origWTable = wtable;
wtable = lookThroughOptionalConditionalWitnessTable(wtable);
#ifndef NDEBUG
{
const ProtocolConformanceDescriptor *conformance = wtable->getDescription();
const ProtocolDescriptor *protocol = conformance->getProtocol();
auto requirements = protocol->getRequirements();
assert(assocConformance >= requirements.begin() &&
assocConformance < requirements.end());
assert(reqBase == requirements.data() - WitnessTableFirstRequirementOffset);
assert(
assocConformance->Flags.getKind() ==
ProtocolRequirementFlags::Kind::AssociatedConformanceAccessFunction ||
assocConformance->Flags.getKind() ==
ProtocolRequirementFlags::Kind::BaseProtocol);
}
#endif
// Retrieve the witness.
unsigned witnessIndex = assocConformance - reqBase;
auto *relativeDistanceAddr = &((int32_t*)wtable)[witnessIndex];
auto relativeDistance = *relativeDistanceAddr;
auto value = swift::detail::applyRelativeOffset(relativeDistanceAddr,
relativeDistance);
assert((value & 0x1) && "Expecting the bit to be set");
value = value & ~((uintptr_t)0x1);
const char *mangledNameBase = (const char*) value;
// Extract the mangled name itself.
if (*mangledNameBase == '\xFF')
++mangledNameBase;
StringRef mangledName =
Demangle::makeSymbolicMangledNameStringRef(mangledNameBase);
// Relative reference to an associate conformance witness function.
// FIXME: This is intended to be a temporary mangling, to be replaced
// by a real "protocol conformance" mangling.
if (mangledName.size() == 5 &&
(mangledName[0] == '\x07' || mangledName[0] == '\x08')) {
// Resolve the relative reference to the witness function.
int32_t offset;
memcpy(&offset, mangledName.data() + 1, 4);
void *ptr = TargetCompactFunctionPointer<InProcess, void>::resolve(mangledName.data() + 1, offset);
// Call the witness function.
AssociatedRelativeWitnessTableAccessFunction *witnessFn;
#if SWIFT_PTRAUTH
witnessFn =
(AssociatedRelativeWitnessTableAccessFunction *)ptrauth_sign_unauthenticated(
(void *)ptr, ptrauth_key_function_pointer, 0);
#else
witnessFn = (AssociatedRelativeWitnessTableAccessFunction *)ptr;
#endif
auto assocWitnessTable = witnessFn(assocType, conformingType, origWTable);
// The access function returns an signed pointer.
return assocWitnessTable;
}
swift_unreachable("Invalid mangled associate conformance");
}
const RelativeWitnessTable *swift::swift_getAssociatedConformanceWitnessRelative(
RelativeWitnessTable *wtable,
const Metadata *conformingType,
const Metadata *assocType,
const ProtocolRequirement *reqBase,
const ProtocolRequirement *assocConformance) {
// We avoid using this function for initializing base protocol conformances
// so that we can have a better fast-path.
assert(assocConformance->Flags.getKind() ==
ProtocolRequirementFlags::Kind::AssociatedConformanceAccessFunction);
return swift_getAssociatedConformanceWitnessRelativeSlowImpl(wtable, conformingType,
assocType, reqBase,
assocConformance);
}
bool swift::swift_compareWitnessTables(const WitnessTable *lhs,
const WitnessTable *rhs) {
return MetadataCacheKey::areWitnessTablesEqual(lhs, rhs);
}
bool swift::swift_compareProtocolConformanceDescriptors(
const ProtocolConformanceDescriptor *lhs,
const ProtocolConformanceDescriptor *rhs) {
lhs = swift_auth_data_non_address(
lhs, SpecialPointerAuthDiscriminators::ProtocolConformanceDescriptor);
rhs = swift_auth_data_non_address(
rhs, SpecialPointerAuthDiscriminators::ProtocolConformanceDescriptor);
return MetadataCacheKey::areConformanceDescriptorsEqual(lhs, rhs);
}
/***************************************************************************/
/*** Recursive metadata dependencies ***************************************/
/***************************************************************************/
template <class Result, class Callbacks>
static Result performOnMetadataCache(const Metadata *metadata,
Callbacks &&callbacks) {
// TODO: Once more than just structs have canonical statically specialized
// metadata, calling an updated
// isCanonicalStaticallySpecializedGenericMetadata would entail
// dyn_casting to the same type more than once. Avoid that by combining
// that function's implementation with the dyn_casts below.
if (metadata->isCanonicalStaticallySpecializedGenericMetadata())
return std::move(callbacks).forOtherMetadata(metadata);
// Handle different kinds of type that can delay their metadata.
const TypeContextDescriptor *description;
if (auto classMetadata = dyn_cast<ClassMetadata>(metadata)) {
description = classMetadata->getDescription();
} else if (auto valueMetadata = dyn_cast<ValueMetadata>(metadata)) {
description = valueMetadata->getDescription();
} else if (auto tupleMetadata = dyn_cast<TupleTypeMetadata>(metadata)) {
// The empty tuple is special and doesn't belong to a metadata cache.
if (tupleMetadata->NumElements == 0)
return std::move(callbacks).forOtherMetadata(tupleMetadata);
return std::move(callbacks).forTupleMetadata(tupleMetadata);
} else if (auto foreignClass = dyn_cast<ForeignClassMetadata>(metadata)) {
return std::move(callbacks).forForeignMetadata(foreignClass,
foreignClass->getDescription());
} else {
return std::move(callbacks).forOtherMetadata(metadata);
}
if (!description->isGeneric()) {
switch (description->getMetadataInitialization()) {
case TypeContextDescriptorFlags::NoMetadataInitialization:
return std::move(callbacks).forOtherMetadata(metadata);
case TypeContextDescriptorFlags::ForeignMetadataInitialization:
return std::move(callbacks).forForeignMetadata(metadata, description);
case TypeContextDescriptorFlags::SingletonMetadataInitialization:
return std::move(callbacks).forSingletonMetadata(description);
}
swift_unreachable("bad metadata initialization kind");
}
auto genericArgs =
reinterpret_cast<const void * const *>(
description->getGenericArguments(metadata));
auto &cache = getCache(*description);
assert(description->getFullGenericContextHeader().Base.NumKeyArguments == cache.SigLayout.sizeInWords());
auto key = MetadataCacheKey(cache.SigLayout, genericArgs);
return std::move(callbacks).forGenericMetadata(metadata, description,
cache, key);
}
MetadataResponse swift::swift_checkMetadataState(MetadataRequest request,
const Metadata *type) {
struct CheckStateCallbacks {
MetadataRequest Request;
/// Generic types just need to be awaited.
MetadataResponse forGenericMetadata(const Metadata *type,
const TypeContextDescriptor *description,
GenericMetadataCache &cache,
MetadataCacheKey key) && {
return cache.await(key, Request);
}
MetadataResponse forForeignMetadata(const Metadata *metadata,
const TypeContextDescriptor *description) {
ForeignMetadataCacheEntry::Key key{description};
return ForeignMetadata.get().await(key, Request);
}
MetadataResponse forSingletonMetadata(
const TypeContextDescriptor *description) && {
return SingletonMetadata.get().await(description, Request);
}
MetadataResponse forTupleMetadata(const TupleTypeMetadata *metadata) {
return TupleTypes.get().await(metadata, Request);
}
/// All other type metadata are always complete.
MetadataResponse forOtherMetadata(const Metadata *type) && {
return MetadataResponse{type, MetadataState::Complete};
}
} callbacks = { request };
return performOnMetadataCache<MetadataResponse>(type, std::move(callbacks));
}
/// Search all the metadata that the given type has transitive completeness
/// requirements on for something that matches the given predicate.
template <class T>
static bool findAnyTransitiveMetadata(const Metadata *type, T &&predicate) {
const TypeContextDescriptor *description;
// Classes require their superclass to be transitively complete,
// and they can be generic.
if (auto classType = dyn_cast<ClassMetadata>(type)) {
description = classType->getDescription();
if (auto super = classType->Superclass) {
if (super->isTypeMetadata() && predicate(super))
return true;
}
// Value types can be generic.
} else if (auto valueType = dyn_cast<ValueMetadata>(type)) {
description = valueType->getDescription();
// Tuples require their element types to be transitively complete.
} else if (auto tupleType = dyn_cast<TupleTypeMetadata>(type)) {
for (size_t i = 0, e = tupleType->NumElements; i != e; ++i)
if (predicate(tupleType->getElement(i).Type))
return true;
return false;
// Foreign classes require their superclass to be transitively complete.
} else if (auto foreignClassType = dyn_cast<ForeignClassMetadata>(type)) {
if (auto super = foreignClassType->Superclass) {
if (predicate(super))
return true;
}
return false;
// Other types do not have transitive completeness requirements.
} else {
return false;
}
// Generic types require their type arguments to be transitively complete.
if (description->isGeneric()) {
auto *genericContext = description->getGenericContext();
auto keyArguments = description->getGenericArguments(type);
// The generic argument area begins with a pack count for each
// shape class; skip them first.
auto header = genericContext->getGenericPackShapeHeader();
unsigned paramIdx = header.NumShapeClasses;
auto packs = genericContext->getGenericPackShapeDescriptors();
unsigned packIdx = 0;
for (auto ¶m : genericContext->getGenericParams()) {
// Ignore parameters that don't have a key argument.
if (!param.hasKeyArgument())
continue;
switch (param.getKind()) {
case GenericParamKind::Type:
if (predicate(keyArguments[paramIdx]))
return true;
break;
case GenericParamKind::TypePack: {
assert(packIdx < header.NumPacks);
assert(packs[packIdx].Kind == GenericPackKind::Metadata);
assert(packs[packIdx].Index == paramIdx);
assert(packs[packIdx].ShapeClass < header.NumShapeClasses);
MetadataPackPointer pack(keyArguments[paramIdx]);
assert(pack.getLifetime() == PackLifetime::OnHeap);
uintptr_t count = reinterpret_cast<uintptr_t>(
keyArguments[packs[packIdx].ShapeClass]);
for (uintptr_t j = 0; j < count; ++j) {
if (predicate(pack.getElements()[j]))
return true;
}
++packIdx;
break;
}
default:
llvm_unreachable("Unsupported generic parameter kind");
}
++paramIdx;
}
}
// Didn't find anything.
return false;
}
/// Do a quick check to see if all the transitive type metadata are complete.
static bool
areAllTransitiveMetadataComplete_cheap(const Metadata *type) {
// Look for any transitive metadata that's *incomplete*.
return !findAnyTransitiveMetadata(type, [](const Metadata *type) {
struct IsIncompleteCallbacks {
bool forGenericMetadata(const Metadata *type,
const TypeContextDescriptor *description,
GenericMetadataCache &cache,
MetadataCacheKey key) && {
// Metadata cache lookups aren't really cheap enough for this
// optimization.
return true;
}
bool forForeignMetadata(const Metadata *metadata,
const TypeContextDescriptor *description) {
// If the type doesn't have a completion function, we can assume
// it's transitively complete by construction.
if (!description->getForeignMetadataInitialization().CompletionFunction)
return false;
// TODO: it might be worth doing a quick check against the cache here.
return false;
}
bool forSingletonMetadata(const TypeContextDescriptor *description) && {
// TODO: this could be cheap enough.
return true;
}
bool forTupleMetadata(const TupleTypeMetadata *metadata) {
// TODO: this could be cheap enough.
return true;
}
bool forOtherMetadata(const Metadata *type) && {
return false;
}
} callbacks;
return performOnMetadataCache<bool>(type, std::move(callbacks));
});
}
/// Check for transitive completeness.
///
/// The key observation here is that all we really care about is whether
/// the transitively-observable types are *actually* all complete; we don't
/// need them to *think* they're transitively complete. So if we find
/// something that thinks it's still transitively incomplete, we can just
/// scan its transitive metadata and actually try to find something that's
/// incomplete. If we don't find anything, then we know all the transitive
/// dependencies actually hold, and we can keep going.
static MetadataDependency
checkTransitiveCompleteness(const Metadata *initialType) {
llvm::SmallVector<const Metadata *, 8> worklist;
// An efficient hash-set implementation in the spirit of llvm's SmallPtrSet:
// The first 8 elements are stored in an inline-allocated array to avoid
// malloc calls in the common case. Lookup is still reasonable fast because
// there are max 8 elements in the array.
const int InlineCapacity = 8;
const Metadata *inlinedPresumedCompleteTypes[InlineCapacity];
int numInlinedTypes = 0;
std::unordered_set<const Metadata *> overflowPresumedCompleteTypes;
MetadataDependency dependency;
auto isIncomplete = [&](const Metadata *type) -> bool {
// Add the type to the presumed-complete-types set. If this doesn't
// succeed, we've already inserted it, which means we must have already
// decided it was complete.
// First, try to find the type in the inline-storage of the set.
const Metadata **end = inlinedPresumedCompleteTypes + numInlinedTypes;
if (std::find(inlinedPresumedCompleteTypes, end, type) != end)
return false;
// We didn't find the type in the inline-storage.
if (numInlinedTypes < InlineCapacity) {
assert(overflowPresumedCompleteTypes.size() == 0);
inlinedPresumedCompleteTypes[numInlinedTypes++] = type;
} else {
// The inline-storage is full. So try to insert the type into the
// overflow set.
if (!overflowPresumedCompleteTypes.insert(type).second)
return false;
}
// Check the metadata's current state with a non-blocking request.
auto request = MetadataRequest(MetadataState::Complete,
/*non-blocking*/ true);
auto state =
MetadataResponse(swift_checkMetadataState(request, type)).State;
// If it's transitively complete, we're done.
// This is the most likely result.
if (state == MetadataState::Complete)
return false;
// Otherwise, if the state is actually incomplete, set a dependency
// and leave. We set the dependency at non-transitive completeness
// because we can potentially resolve ourselves if we find completeness.
if (!isAtLeast(state, MetadataState::NonTransitiveComplete)) {
dependency = MetadataDependency{type,
MetadataState::NonTransitiveComplete};
return true;
}
// Otherwise, we have to add it to the worklist.
worklist.push_back(type);
return false;
};
// Consider the type itself to be presumed-complete. We're looking for
// a greatest fixed point.
assert(numInlinedTypes == 0 && overflowPresumedCompleteTypes.size() == 0);
inlinedPresumedCompleteTypes[0] = initialType;
numInlinedTypes = 1;
if (findAnyTransitiveMetadata(initialType, isIncomplete))
return dependency;
// Drain the worklist. The order we do things in doesn't really matter,
// so optimize for locality and convenience by using a stack.
while (!worklist.empty()) {
auto type = worklist.back();
worklist.pop_back();
// Search for incomplete dependencies. This will set Dependency
// if it finds anything.
if (findAnyTransitiveMetadata(type, isIncomplete))
return dependency;
}
// Otherwise, we're transitively complete.
return MetadataDependency();
}
/// Diagnose a metadata dependency cycle.
SWIFT_NORETURN static void
diagnoseMetadataDependencyCycle(llvm::ArrayRef<MetadataDependency> links) {
assert(links.size() >= 2);
assert(links.front().Value == links.back().Value);
auto stringForRequirement = [](MetadataState req) -> const char * {
switch (req) {
case MetadataState::Complete:
return "transitive completion of ";
case MetadataState::NonTransitiveComplete:
return "completion of ";
case MetadataState::LayoutComplete:
return "layout of ";
case MetadataState::Abstract:
return "abstract metadata for ";
}
return "<corrupted requirement> for ";
};
std::string diagnostic =
"runtime error: unresolvable type metadata dependency cycle detected\n"
" Request for ";
diagnostic += stringForRequirement(links.front().Requirement);
diagnostic += nameForMetadata(links.front().Value);
for (auto &link : links.drop_front()) {
// If the diagnostic gets too large, just cut it short.
if (diagnostic.size() >= 128 * 1024) {
diagnostic += "\n (cycle too long, limiting diagnostic text)";
break;
}
diagnostic += "\n depends on ";
diagnostic += stringForRequirement(link.Requirement);
diagnostic += nameForMetadata(link.Value);
}
diagnostic += "\nAborting!\n";
if (_swift_shouldReportFatalErrorsToDebugger()) {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wc99-extensions"
RuntimeErrorDetails details = {
.version = RuntimeErrorDetails::currentVersion,
.errorType = "type-metadata-cycle",
.currentStackDescription = "fetching metadata", // TODO?
.framesToSkip = 1, // skip out to the check function
.memoryAddress = links.front().Value
// TODO: describe the cycle using notes instead of one huge message?
};
#pragma GCC diagnostic pop
_swift_reportToDebugger(RuntimeErrorFlagFatal, diagnostic.c_str(),
&details);
}
fatalError(0, "%s", diagnostic.c_str());
}
/// Check whether the given metadata dependency is satisfied, and if not,
/// return its current dependency, if one exists.
static MetadataStateWithDependency
checkMetadataDependency(MetadataDependency dependency) {
struct CheckDependencyResult {
MetadataState Requirement;
MetadataStateWithDependency
forGenericMetadata(const Metadata *type,
const TypeContextDescriptor *desc,
GenericMetadataCache &cache,
MetadataCacheKey key) && {
return cache.checkDependency(key, Requirement);
}
MetadataStateWithDependency
forForeignMetadata(const Metadata *metadata,
const TypeContextDescriptor *description) {
ForeignMetadataCacheEntry::Key key{description};
return ForeignMetadata.get().checkDependency(key, Requirement);
}
MetadataStateWithDependency
forSingletonMetadata(const TypeContextDescriptor *description) {
return SingletonMetadata.get().checkDependency(description, Requirement);
}
MetadataStateWithDependency
forTupleMetadata(const TupleTypeMetadata *metadata) {
return TupleTypes.get().checkDependency(metadata, Requirement);
}
MetadataStateWithDependency forOtherMetadata(const Metadata *type) {
return { PrivateMetadataState::Complete, MetadataDependency() };
}
} callbacks = { dependency.Requirement };
return performOnMetadataCache<MetadataStateWithDependency>(dependency.Value,
std::move(callbacks));
}
/// Check for an unbreakable metadata-dependency cycle.
void swift::blockOnMetadataDependency(MetadataDependency root,
MetadataDependency firstLink) {
std::vector<MetadataDependency> links;
auto checkNewLink = [&](MetadataDependency newLink) {
links.push_back(newLink);
for (auto i = links.begin(), e = links.end() - 1; i != e; ++i) {
if (i->Value == newLink.Value) {
diagnoseMetadataDependencyCycle(
llvm::makeArrayRef(&*i, links.end() - i));
}
}
};
links.push_back(root);
// Iteratively add each link, checking for a cycle, until we reach
// something without a known dependency.
checkNewLink(firstLink);
while (true) {
// Try to get a dependency for the metadata in the last link we added.
auto checkResult = checkMetadataDependency(links.back());
// If there isn't a known dependency, we can't do any more checking.
if (!checkResult.Dependency) {
// In the special case where it's the first link that doesn't have
// a known dependency and its current metadata state now satisfies
// the dependency leading to it, we can skip waiting.
if (links.size() == 2 &&
satisfies(checkResult.NewState, links.back().Requirement))
return;
// Otherwise, just make a blocking request for the first link in
// the chain.
auto request = MetadataRequest(firstLink.Requirement);
swift_checkMetadataState(request, firstLink.Value);
return;
}
// Check the new link.
checkNewLink(checkResult.Dependency);
}
}
/***************************************************************************/
/*** Allocator implementation **********************************************/
/***************************************************************************/
#if !SWIFT_STDLIB_PASSTHROUGH_METADATA_ALLOCATOR
namespace {
struct alignas(sizeof(uintptr_t) * 2) PoolRange {
static constexpr uintptr_t PageSize = 16 * 1024;
static constexpr uintptr_t MaxPoolAllocationSize = PageSize / 2;
/// The start of the allocation.
char *Begin;
/// The number of bytes remaining.
size_t Remaining;
};
/// The trailer placed at the end of each pool allocation, used when
/// SWIFT_DEBUG_ENABLE_METADATA_ALLOCATION_ITERATION is on.
struct PoolTrailer {
void *PrevTrailer;
size_t PoolSize;
};
static constexpr size_t InitialPoolSize = 64 * 1024;
/// The header placed before each allocation, used when
/// SWIFT_DEBUG_ENABLE_METADATA_ALLOCATION_ITERATION is on.
struct alignas(void *) AllocationHeader {
uint16_t Size;
uint16_t Tag;
};
} // end anonymous namespace
// A statically-allocated pool. It's zero-initialized, so this
// doesn't cost us anything in binary size.
alignas(void *) static struct {
char Pool[InitialPoolSize];
} InitialAllocationPool;
static swift::atomic<PoolRange>
AllocationPool{PoolRange{InitialAllocationPool.Pool,
sizeof(InitialAllocationPool.Pool)}};
std::tuple<const void *, size_t> MetadataAllocator::InitialPoolLocation() {
return {InitialAllocationPool.Pool, sizeof(InitialAllocationPool.Pool)};
}
bool swift::_swift_debug_metadataAllocationIterationEnabled = false;
const void * const swift::_swift_debug_allocationPoolPointer = &AllocationPool;
std::atomic<const void *> swift::_swift_debug_metadataAllocationBacktraceList;
static void recordBacktrace(void *allocation) {
withCurrentBacktrace([&](void **addrs, int count) {
MetadataAllocationBacktraceHeader<InProcess> *record =
(MetadataAllocationBacktraceHeader<InProcess> *)malloc(
sizeof(*record) + count * sizeof(void *));
record->Allocation = allocation;
record->Count = count;
memcpy(record + 1, addrs, count * sizeof(void *));
record->Next = _swift_debug_metadataAllocationBacktraceList.load(
std::memory_order_relaxed);
while (!_swift_debug_metadataAllocationBacktraceList.compare_exchange_weak(
record->Next, record, std::memory_order_release,
std::memory_order_relaxed))
; // empty
});
}
static inline bool scribbleEnabled() {
#ifndef NDEBUG
// When DEBUG is defined, always scribble.
return true;
#else
// When DEBUG is not defined, only scribble when the
// SWIFT_DEBUG_ENABLE_MALLOC_SCRIBBLE environment variable is set.
return SWIFT_UNLIKELY(
runtime::environment::SWIFT_DEBUG_ENABLE_MALLOC_SCRIBBLE());
#endif
}
static constexpr char scribbleByte = 0xAA;
template <typename Pointee>
static inline void memsetScribble(Pointee *bytes, size_t totalSize) {
if (scribbleEnabled())
memset(bytes, scribbleByte, totalSize);
}
/// When scribbling is enabled, check the specified region for the scribble
/// values to detect overflows. When scribbling is disabled, this is a no-op.
static inline void checkScribble(char *bytes, size_t totalSize) {
if (scribbleEnabled())
for (size_t i = 0; i < totalSize; i++)
if (bytes[i] != scribbleByte) {
const size_t maxToPrint = 16;
size_t remaining = totalSize - i;
size_t toPrint = std::min(remaining, maxToPrint);
std::string hex = toHex(llvm::StringRef{&bytes[i], toPrint});
swift::fatalError(
0, "corrupt metadata allocation arena detected at %p: %s%s",
&bytes[i], hex.c_str(), toPrint < remaining ? "..." : "");
}
}
static void checkAllocatorDebugEnvironmentVariables(void *context) {
memsetScribble(InitialAllocationPool.Pool, InitialPoolSize);
_swift_debug_metadataAllocationIterationEnabled =
runtime::environment::SWIFT_DEBUG_ENABLE_METADATA_ALLOCATION_ITERATION();
if (!_swift_debug_metadataAllocationIterationEnabled) {
if (runtime::environment::SWIFT_DEBUG_ENABLE_METADATA_BACKTRACE_LOGGING())
swift::warning(RuntimeErrorFlagNone,
"Warning: SWIFT_DEBUG_ENABLE_METADATA_BACKTRACE_LOGGING "
"without SWIFT_DEBUG_ENABLE_METADATA_ALLOCATION_ITERATION "
"has no effect.\n");
return;
}
// Write a PoolTrailer to the end of InitialAllocationPool and shrink
// the pool accordingly.
auto poolCopy = AllocationPool.load(std::memory_order_relaxed);
assert(poolCopy.Begin == InitialAllocationPool.Pool);
size_t newPoolSize = InitialPoolSize - sizeof(PoolTrailer);
PoolTrailer trailer = {nullptr, newPoolSize};
memcpy(InitialAllocationPool.Pool + newPoolSize, &trailer, sizeof(trailer));
poolCopy.Remaining = newPoolSize;
AllocationPool.store(poolCopy, std::memory_order_relaxed);
}
void *MetadataAllocator::Allocate(size_t size, size_t alignment) {
assert(Tag != 0);
assert(alignment <= alignof(void*));
assert(size % alignof(void*) == 0);
static swift::once_t getenvToken;
swift::once(getenvToken, checkAllocatorDebugEnvironmentVariables);
// If the size is larger than the maximum, just do a normal heap allocation.
if (size > PoolRange::MaxPoolAllocationSize) {
void *allocation = swift_slowAlloc(size, alignment - 1);
memsetScribble(allocation, size);
return allocation;
}
// Allocate out of the pool.
auto sizeWithHeader = size;
if (SWIFT_UNLIKELY(_swift_debug_metadataAllocationIterationEnabled))
sizeWithHeader += sizeof(AllocationHeader);
PoolRange curState = AllocationPool.load(std::memory_order_relaxed);
while (true) {
char *allocation;
PoolRange newState;
bool allocatedNewPage;
// Try to allocate out of the current page.
if (sizeWithHeader <= curState.Remaining) {
allocatedNewPage = false;
allocation = curState.Begin;
newState = PoolRange{curState.Begin + sizeWithHeader,
curState.Remaining - sizeWithHeader};
} else {
auto poolSize = PoolRange::PageSize;
if (SWIFT_UNLIKELY(_swift_debug_metadataAllocationIterationEnabled))
poolSize -= sizeof(PoolTrailer);
allocatedNewPage = true;
allocation = reinterpret_cast<char *>(swift_slowAlloc(PoolRange::PageSize,
alignof(char) - 1));
memsetScribble(allocation, PoolRange::PageSize);
if (SWIFT_UNLIKELY(_swift_debug_metadataAllocationIterationEnabled)) {
PoolTrailer *newTrailer = (PoolTrailer *)(allocation + poolSize);
char *prevTrailer = curState.Begin + curState.Remaining;
newTrailer->PrevTrailer = prevTrailer;
newTrailer->PoolSize = poolSize;
}
newState = PoolRange{allocation + sizeWithHeader,
poolSize - sizeWithHeader};
__asan_poison_memory_region(allocation, newState.Remaining);
}
// NULL should be impossible, but check anyway in case of bugs or corruption
if (SWIFT_UNLIKELY(!allocation)) {
PoolRange curStateReRead = AllocationPool.load(std::memory_order_relaxed);
swift::fatalError(
0,
"Metadata allocator corruption: allocation is NULL. "
"curState: {%p, %zu} - curStateReRead: {%p, %zu} - "
"newState: {%p, %zu} - allocatedNewPage: %s - requested size: %zu - "
"sizeWithHeader: %zu - alignment: %zu - Tag: %d\n",
curState.Begin, curState.Remaining, curStateReRead.Begin,
curStateReRead.Remaining, newState.Begin, newState.Remaining,
allocatedNewPage ? "true" : "false", size, sizeWithHeader, alignment,
Tag);
}
// Swap in the new state.
if (AllocationPool.compare_exchange_weak(curState, newState,
std::memory_order_relaxed,
std::memory_order_relaxed)) {
// If that succeeded, we've successfully allocated.
__msan_allocated_memory(allocation, sizeWithHeader);
__asan_unpoison_memory_region(allocation, sizeWithHeader);
if (SWIFT_UNLIKELY(_swift_debug_metadataAllocationIterationEnabled)) {
AllocationHeader *header = (AllocationHeader *)allocation;
header->Size = size;
header->Tag = Tag;
auto *returnedAllocation = allocation + sizeof(AllocationHeader);
if (runtime::environment ::
SWIFT_DEBUG_ENABLE_METADATA_BACKTRACE_LOGGING())
recordBacktrace(returnedAllocation);
checkScribble(returnedAllocation, size);
return returnedAllocation;
} else {
checkScribble(allocation, size);
return allocation;
}
}
// If it failed, go back to a neutral state and try again.
if (allocatedNewPage) {
swift_slowDealloc(allocation, PoolRange::PageSize, alignof(char) - 1);
}
}
}
void MetadataAllocator::Deallocate(const void *allocation, size_t size,
size_t Alignment) {
__asan_poison_memory_region(allocation, size);
if (size > PoolRange::MaxPoolAllocationSize) {
swift_slowDealloc(const_cast<void *>(allocation), size, Alignment - 1);
return;
}
// Check whether the allocation pool is still in the state it was in
// immediately after the given allocation.
PoolRange curState = AllocationPool.load(std::memory_order_relaxed);
if (reinterpret_cast<const char*>(allocation) + size != curState.Begin) {
return;
}
// If we're scribbling, re-scribble the allocation so that the next call to
// Allocate sees what it expects.
memsetScribble(const_cast<void *>(allocation), size);
// Try to swap back to the pre-allocation state. If this fails,
// don't bother trying again; we'll just leak the allocation.
PoolRange newState = { reinterpret_cast<char*>(const_cast<void*>(allocation)),
curState.Remaining + size };
AllocationPool.compare_exchange_weak(curState, newState,
std::memory_order_relaxed,
std::memory_order_relaxed);
}
#endif
void *swift::allocateMetadata(size_t size, size_t alignment) {
return MetadataAllocator(MetadataTag).Allocate(size, alignment);
}
template<>
bool Metadata::satisfiesClassConstraint() const {
// existential types marked with @objc satisfy class requirement.
if (auto *existential = dyn_cast<ExistentialTypeMetadata>(this))
return existential->isObjC();
// or it's a class.
return isAnyClass();
}
#if !NDEBUG
static bool referencesAnonymousContext(Demangle::Node *node) {
if (node->getKind() == Demangle::Node::Kind::AnonymousContext)
return true;
for (unsigned i = 0, e = node->getNumChildren(); i < e; ++i)
if (referencesAnonymousContext(node->getChild(i)))
return true;
return false;
}
void swift::verifyMangledNameRoundtrip(const Metadata *metadata) {
// Enable verification when a special environment variable is set. This helps
// us stress test the mangler/demangler and type lookup machinery.
if (!swift::runtime::environment::SWIFT_ENABLE_MANGLED_NAME_VERIFICATION())
return;
Demangle::StackAllocatedDemangler<1024> Dem;
auto node = _swift_buildDemanglingForMetadata(metadata, Dem);
// If the mangled node involves types in an AnonymousContext, then by design,
// it cannot be looked up by name.
if (referencesAnonymousContext(node))
return;
auto mangling = Demangle::mangleNode(node);
if (!mangling.isSuccess()) {
swift::warning(RuntimeErrorFlagNone,
"Metadata mangled name failed to roundtrip: %p couldn't be mangled\n",
metadata);
} else {
std::string mangledName = mangling.result();
auto result =
swift_getTypeByMangledName(MetadataState::Abstract,
mangledName,
nullptr,
[](unsigned, unsigned){ return nullptr; },
[](const Metadata *, unsigned) { return nullptr; })
.getType().getMetadata();
if (metadata != result)
swift::warning(RuntimeErrorFlagNone,
"Metadata mangled name failed to roundtrip: %p -> %s -> %p\n",
metadata, mangledName.c_str(), (const Metadata *)result);
}
}
#endif
const TypeContextDescriptor *swift::swift_getTypeContextDescriptor(const Metadata *type) {
return type->getTypeContextDescriptor();
}
// Emit compatibility override shims for keypath runtime functionality. The
// implementation of these functions is in the standard library in
// KeyPath.swift.
SWIFT_RUNTIME_STDLIB_SPI
const HeapObject *swift_getKeyPathImpl(const void *pattern,
const void *arguments);
#define OVERRIDE_KEYPATH COMPATIBILITY_OVERRIDE
#define OVERRIDE_WITNESSTABLE COMPATIBILITY_OVERRIDE
#include COMPATIBILITY_OVERRIDE_INCLUDE_PATH
// Autolink with libc++, for cases where libswiftCore is linked statically.
#if defined(__MACH__)
asm(".linker_option \"-lc++\"\n");
#endif // defined(__MACH__)
|