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
|
//===--- TransferNonSendable.cpp ------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2023 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
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "transfer-non-sendable"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/DiagnosticsSIL.h"
#include "swift/AST/Expr.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/SourceFile.h"
#include "swift/AST/Type.h"
#include "swift/Basic/FrozenMultiMap.h"
#include "swift/Basic/ImmutablePointerSet.h"
#include "swift/SIL/BasicBlockData.h"
#include "swift/SIL/BasicBlockDatastructures.h"
#include "swift/SIL/DynamicCasts.h"
#include "swift/SIL/MemAccessUtils.h"
#include "swift/SIL/NodeDatastructures.h"
#include "swift/SIL/OperandDatastructures.h"
#include "swift/SIL/OwnershipUtils.h"
#include "swift/SIL/PatternMatch.h"
#include "swift/SIL/SILBasicBlock.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/Test.h"
#include "swift/SILOptimizer/Analysis/RegionAnalysis.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/PartitionUtils.h"
#include "swift/SILOptimizer/Utils/VariableNameUtils.h"
#include "swift/Sema/Concurrency.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/Support/Debug.h"
using namespace swift;
using namespace swift::PartitionPrimitives;
using namespace swift::PatternMatch;
using namespace swift::regionanalysisimpl;
namespace {
using TransferringOperandSetFactory = Partition::TransferringOperandSetFactory;
using Element = PartitionPrimitives::Element;
using Region = PartitionPrimitives::Region;
} // namespace
//===----------------------------------------------------------------------===//
// MARK: Utilities
//===----------------------------------------------------------------------===//
static SILValue stripFunctionConversions(SILValue val) {
while (true) {
if (auto ti = dyn_cast<ThinToThickFunctionInst>(val)) {
val = ti->getOperand();
continue;
}
if (auto cfi = dyn_cast<ConvertFunctionInst>(val)) {
val = cfi->getOperand();
continue;
}
if (auto cvt = dyn_cast<ConvertEscapeToNoEscapeInst>(val)) {
val = cvt->getOperand();
continue;
}
break;
}
return val;
}
static std::optional<DiagnosticBehavior>
getDiagnosticBehaviorLimitForValue(SILValue value) {
auto *nom = value->getType().getNominalOrBoundGenericNominal();
if (!nom)
return {};
auto declRef = value->getFunction()->getDeclRef();
if (!declRef)
return {};
auto *fromDC = declRef.getInnermostDeclContext();
return getConcurrencyDiagnosticBehaviorLimit(nom, fromDC);
}
static std::optional<DiagnosticBehavior>
getDiagnosticBehaviorLimitForCapturedValue(CapturedValue value) {
ValueDecl *decl = value.getDecl();
auto *nom = decl->getInterfaceType()->getNominalOrBoundGenericNominal();
if (!nom)
return {};
auto *fromDC = decl->getInnermostDeclContext();
return getConcurrencyDiagnosticBehaviorLimit(nom, fromDC);
}
/// Find the most conservative diagnostic behavior by taking the max over all
/// DiagnosticBehavior for the captured values.
static std::optional<DiagnosticBehavior>
getDiagnosticBehaviorLimitForCapturedValues(
ArrayRef<CapturedValue> capturedValues) {
using UnderlyingType = std::underlying_type<DiagnosticBehavior>::type;
std::optional<DiagnosticBehavior> diagnosticBehavior;
for (auto value : capturedValues) {
auto lhs = UnderlyingType(
diagnosticBehavior.value_or(DiagnosticBehavior::Unspecified));
auto rhs = UnderlyingType(
getDiagnosticBehaviorLimitForCapturedValue(value).value_or(
DiagnosticBehavior::Unspecified));
auto result = DiagnosticBehavior(std::max(lhs, rhs));
if (result != DiagnosticBehavior::Unspecified)
diagnosticBehavior = result;
}
return diagnosticBehavior;
}
static std::optional<SILDeclRef> getDeclRefForCallee(SILInstruction *inst) {
auto fas = FullApplySite::isa(inst);
if (!fas)
return {};
SILValue calleeOrigin = fas.getCalleeOrigin();
while (true) {
// Intentionally don't lookup through dynamic_function_ref and
// previous_dynamic_function_ref as the target of those functions is not
// statically known.
if (auto *fri = dyn_cast<FunctionRefInst>(calleeOrigin)) {
if (auto *callee = fri->getReferencedFunctionOrNull()) {
if (auto declRef = callee->getDeclRef())
return declRef;
}
}
if (auto *mi = dyn_cast<MethodInst>(calleeOrigin)) {
return mi->getMember();
}
if (auto *pai = dyn_cast<PartialApplyInst>(calleeOrigin)) {
calleeOrigin = pai->getCalleeOrigin();
continue;
}
return {};
}
}
static std::optional<std::pair<DescriptiveDeclKind, DeclName>>
getTransferringApplyCalleeInfo(SILInstruction *inst) {
auto declRef = getDeclRefForCallee(inst);
if (!declRef)
return {};
auto *decl = declRef->getDecl();
if (!decl || !decl->hasName())
return {};
return {{decl->getDescriptiveKind(), decl->getName()}};
}
static Expr *inferArgumentExprFromApplyExpr(ApplyExpr *sourceApply,
FullApplySite fai,
const Operand *op) {
Expr *foundExpr = nullptr;
// If we have self, then infer it.
if (fai.hasSelfArgument() && op == &fai.getSelfArgumentOperand()) {
if (auto callExpr = dyn_cast<CallExpr>(sourceApply))
if (auto calledExpr =
dyn_cast<DotSyntaxCallExpr>(callExpr->getDirectCallee()))
foundExpr = calledExpr->getBase();
} else {
// Otherwise, try to infer using the operand of the ApplyExpr.
unsigned argNum = [&]() -> unsigned {
if (fai.isCalleeOperand(*op))
return op->getOperandNumber();
return fai.getAppliedArgIndexWithoutIndirectResults(*op);
}();
// Something happened that we do not understand.
if (argNum >= sourceApply->getArgs()->size()) {
return nullptr;
}
foundExpr = sourceApply->getArgs()->getExpr(argNum);
// If we have an erasure expression, lets use the original type. We do
// this since we are not saying the specific parameter that is the
// issue and we are using the type to explain it to the user.
if (auto *erasureExpr = dyn_cast<ErasureExpr>(foundExpr))
foundExpr = erasureExpr->getSubExpr();
}
return foundExpr;
}
//===----------------------------------------------------------------------===//
// MARK: Diagnostics
//===----------------------------------------------------------------------===//
template <typename... T, typename... U>
static InFlightDiagnostic diagnoseError(ASTContext &context, SourceLoc loc,
Diag<T...> diag, U &&...args) {
return std::move(context.Diags.diagnose(loc, diag, std::forward<U>(args)...)
.warnUntilSwiftVersion(6));
}
template <typename... T, typename... U>
static InFlightDiagnostic diagnoseError(ASTContext &context, SILLocation loc,
Diag<T...> diag, U &&...args) {
return ::diagnoseError(context, loc.getSourceLoc(), diag,
std::forward<U>(args)...);
}
template <typename... T, typename... U>
static InFlightDiagnostic diagnoseError(const PartitionOp &op, Diag<T...> diag,
U &&...args) {
return ::diagnoseError(op.getSourceInst()->getFunction()->getASTContext(),
op.getSourceLoc().getSourceLoc(), diag,
std::forward<U>(args)...);
}
template <typename... T, typename... U>
static InFlightDiagnostic diagnoseError(const Operand *op, Diag<T...> diag,
U &&...args) {
return ::diagnoseError(op->getUser()->getFunction()->getASTContext(),
op->getUser()->getLoc().getSourceLoc(), diag,
std::forward<U>(args)...);
}
template <typename... T, typename... U>
static InFlightDiagnostic diagnoseError(const SILInstruction *inst,
Diag<T...> diag, U &&...args) {
return ::diagnoseError(inst->getFunction()->getASTContext(),
inst->getLoc().getSourceLoc(), diag,
std::forward<U>(args)...);
}
template <typename... T, typename... U>
static InFlightDiagnostic diagnoseNote(ASTContext &context, SourceLoc loc,
Diag<T...> diag, U &&...args) {
return context.Diags.diagnose(loc, diag, std::forward<U>(args)...);
}
template <typename... T, typename... U>
static InFlightDiagnostic diagnoseNote(ASTContext &context, SILLocation loc,
Diag<T...> diag, U &&...args) {
return ::diagnoseNote(context, loc.getSourceLoc(), diag,
std::forward<U>(args)...);
}
template <typename... T, typename... U>
static InFlightDiagnostic diagnoseNote(const PartitionOp &op, Diag<T...> diag,
U &&...args) {
return ::diagnoseNote(op.getSourceInst()->getFunction()->getASTContext(),
op.getSourceLoc().getSourceLoc(), diag,
std::forward<U>(args)...);
}
template <typename... T, typename... U>
static InFlightDiagnostic diagnoseNote(const Operand *op, Diag<T...> diag,
U &&...args) {
return ::diagnoseNote(op->getUser()->getFunction()->getASTContext(),
op->getUser()->getLoc().getSourceLoc(), diag,
std::forward<U>(args)...);
}
template <typename... T, typename... U>
static InFlightDiagnostic diagnoseNote(const SILInstruction *inst,
Diag<T...> diag, U &&...args) {
return ::diagnoseNote(inst->getFunction()->getASTContext(),
inst->getLoc().getSourceLoc(), diag,
std::forward<U>(args)...);
}
//===----------------------------------------------------------------------===//
// MARK: Require Liveness
//===----------------------------------------------------------------------===//
namespace {
class BlockLivenessInfo {
// Generation counter so we do not need to reallocate.
unsigned generation = 0;
SILInstruction *firstRequireInst = nullptr;
void resetIfNew(unsigned newGeneration) {
if (generation == newGeneration)
return;
generation = newGeneration;
firstRequireInst = nullptr;
}
public:
SILInstruction *getInst(unsigned callerGeneration) {
resetIfNew(callerGeneration);
return firstRequireInst;
}
void setInst(unsigned callerGeneration, SILInstruction *newValue) {
resetIfNew(callerGeneration);
firstRequireInst = newValue;
}
};
/// We only want to emit errors for the first requires along a path from a
/// transfer instruction. We discover this by walking from user blocks to
struct RequireLiveness {
unsigned generation;
SILInstruction *transferInst;
BasicBlockData<BlockLivenessInfo> &blockLivenessInfo;
InstructionSet allRequires;
InstructionSetWithSize finalRequires;
/// If we have requires in the def block before our transfer, this is the
/// first require.
SILInstruction *firstRequireBeforeTransferInDefBlock = nullptr;
RequireLiveness(unsigned generation, Operand *transferOp,
BasicBlockData<BlockLivenessInfo> &blockLivenessInfo)
: generation(generation), transferInst(transferOp->getUser()),
blockLivenessInfo(blockLivenessInfo),
allRequires(transferOp->getParentFunction()),
finalRequires(transferOp->getParentFunction()) {}
template <typename Collection>
void process(Collection collection);
/// Attempt to process requireInst for our def block. Returns false if
/// requireInst was before our def and we need to do interprocedural
/// processing. Returns true if requireInst was after our transferInst and we
/// were able to appropriately determine if we should emit it or not.
void processDefBlock();
/// Process all requires in block, updating blockLivenessInfo.
void processNonDefBlock(SILBasicBlock *block);
};
} // namespace
void RequireLiveness::processDefBlock() {
LLVM_DEBUG(llvm::dbgs() << " Processing def block!\n");
// First walk from the beginning of the block to the transfer instruction to
// see if we have any requires before our def. Once we find one, we can skip
// the traversal and jump straight to the transfer.
for (auto ii = transferInst->getParent()->begin(),
ie = transferInst->getIterator();
ii != ie; ++ii) {
if (allRequires.contains(&*ii) && !firstRequireBeforeTransferInDefBlock) {
firstRequireBeforeTransferInDefBlock = &*ii;
LLVM_DEBUG(llvm::dbgs() << " Found transfer before def: "
<< *firstRequireBeforeTransferInDefBlock);
break;
}
}
// Then walk from our transferInst to the end of the block looking for the
// first require inst. Once we find it... return.
//
// NOTE: We start walking at the transferInst since the transferInst could use
// the requireInst as well.
for (auto ii = transferInst->getIterator(),
ie = transferInst->getParent()->end();
ii != ie; ++ii) {
if (!allRequires.contains(&*ii))
continue;
finalRequires.insert(&*ii);
LLVM_DEBUG(llvm::dbgs() << " Found transfer after def: " << *ii);
return;
}
}
void RequireLiveness::processNonDefBlock(SILBasicBlock *block) {
// Walk from the bottom to the top... assigning to our block state.
auto blockState = blockLivenessInfo.get(block);
for (auto &inst : llvm::make_range(block->rbegin(), block->rend())) {
if (!finalRequires.contains(&inst))
continue;
blockState.get()->setInst(generation, &inst);
}
}
template <typename Collection>
void RequireLiveness::process(Collection requireInstList) {
LLVM_DEBUG(llvm::dbgs() << "==> Performing Require Liveness for: "
<< *transferInst);
// Then put all of our requires into our allRequires set.
BasicBlockWorklist initializingWorklist(transferInst->getFunction());
for (auto require : requireInstList) {
LLVM_DEBUG(llvm::dbgs() << " Require Inst: " << **require);
allRequires.insert(*require);
initializingWorklist.pushIfNotVisited(require->getParent());
}
// Then process our def block to see if we have any requires before and after
// the transferInst...
processDefBlock();
// If we found /any/ requries after the transferInst, we can bail early since
// that is guaranteed to dominate all further requires.
if (!finalRequires.empty()) {
LLVM_DEBUG(
llvm::dbgs()
<< " Found transfer after def in def block! Exiting early!\n");
return;
}
LLVM_DEBUG(llvm::dbgs() << " Did not find transfer after def in def "
"block! Walking blocks!\n");
// If we found a transfer in the def block before our def, add it to the block
// state for the def.
if (firstRequireBeforeTransferInDefBlock) {
LLVM_DEBUG(
llvm::dbgs()
<< " Found a require before transfer! Adding to block state!\n");
auto blockState = blockLivenessInfo.get(transferInst->getParent());
blockState.get()->setInst(generation, firstRequireBeforeTransferInDefBlock);
}
// Then for each require block that isn't a def block transfer, find the
// earliest transfer inst.
while (auto *requireBlock = initializingWorklist.pop()) {
auto blockState = blockLivenessInfo.get(requireBlock);
for (auto &inst : *requireBlock) {
if (!allRequires.contains(&inst))
continue;
LLVM_DEBUG(llvm::dbgs() << " Mapping Block bb"
<< requireBlock->getDebugID() << " to: " << inst);
blockState.get()->setInst(generation, &inst);
break;
}
}
// Then walk from our def block looking for setInst blocks.
auto *transferBlock = transferInst->getParent();
BasicBlockWorklist worklist(transferInst->getFunction());
for (auto *succBlock : transferBlock->getSuccessorBlocks())
worklist.pushIfNotVisited(succBlock);
while (auto *next = worklist.pop()) {
// Check if we found an earliest requires... if so, add that to final
// requires and continue. We don't want to visit successors.
auto blockState = blockLivenessInfo.get(next);
if (auto *inst = blockState.get()->getInst(generation)) {
finalRequires.insert(inst);
continue;
}
// Do not look at successors of the transfer block.
if (next == transferBlock)
continue;
// Otherwise, we did not find a requires and need to search further
// successors.
for (auto *succBlock : next->getSuccessorBlocks())
worklist.pushIfNotVisited(succBlock);
}
}
//===----------------------------------------------------------------------===//
// MARK: Forward Declaration Of TransferNonSendableImpl
//===----------------------------------------------------------------------===//
namespace {
struct InOutSendingNotDisconnectedInfo {
/// The function exiting inst where the 'inout sending' parameter was actor
/// isolated.
TermInst *functionExitingInst;
/// The 'inout sending' param that we are emitting an error for.
SILValue inoutSendingParam;
/// The dynamic actor isolated region info of our 'inout sending' value's
/// region at the terminator inst.
SILDynamicMergedIsolationInfo actorIsolatedRegionInfo;
InOutSendingNotDisconnectedInfo(
SILInstruction *functionExitingInst, SILValue inoutSendingParam,
SILDynamicMergedIsolationInfo actorIsolatedRegionInfo)
: functionExitingInst(cast<TermInst>(functionExitingInst)),
inoutSendingParam(inoutSendingParam),
actorIsolatedRegionInfo(actorIsolatedRegionInfo) {}
};
struct TransferredNonTransferrableInfo {
/// The use that actually caused the transfer.
Operand *transferredOperand;
/// The non-transferrable value that is in the same region as \p
/// transferredOperand.get().
llvm::PointerUnion<SILValue, SILInstruction *> nonTransferrable;
/// The region info that describes the dynamic dataflow derived isolation
/// region info for the non-transferrable value.
///
/// This is equal to the merge of the IsolationRegionInfo from all elements in
/// nonTransferrable's region when the error was diagnosed.
SILDynamicMergedIsolationInfo isolationRegionInfo;
TransferredNonTransferrableInfo(
Operand *transferredOperand, SILValue nonTransferrableValue,
SILDynamicMergedIsolationInfo isolationRegionInfo)
: transferredOperand(transferredOperand),
nonTransferrable(nonTransferrableValue),
isolationRegionInfo(isolationRegionInfo) {}
TransferredNonTransferrableInfo(
Operand *transferredOperand, SILInstruction *nonTransferrableInst,
SILDynamicMergedIsolationInfo isolationRegionInfo)
: transferredOperand(transferredOperand),
nonTransferrable(nonTransferrableInst),
isolationRegionInfo(isolationRegionInfo) {}
};
struct AssignIsolatedIntoOutSendingParameterInfo {
/// The user that actually caused the transfer.
Operand *srcOperand;
/// The specific out sending result.
SILFunctionArgument *outSendingResult;
/// The non-transferrable value that is in the same region as \p
/// outSendingResult.
SILValue nonTransferrableValue;
/// The region info that describes the dynamic dataflow derived isolation
/// region info for the non-transferrable value.
///
/// This is equal to the merge of the IsolationRegionInfo from all elements in
/// nonTransferrable's region when the error was diagnosed.
SILDynamicMergedIsolationInfo isolatedValueIsolationRegionInfo;
AssignIsolatedIntoOutSendingParameterInfo(
Operand *transferringOperand, SILFunctionArgument *outSendingResult,
SILValue nonTransferrableValue,
SILDynamicMergedIsolationInfo isolationRegionInfo)
: srcOperand(transferringOperand), outSendingResult(outSendingResult),
nonTransferrableValue(nonTransferrableValue),
isolatedValueIsolationRegionInfo(isolationRegionInfo) {}
};
/// Wrapper around a SILInstruction that internally specifies whether we are
/// dealing with an inout reinitialization needed or if it is just a normal
/// use after transfer.
class RequireInst {
public:
enum Kind {
UseAfterTransfer,
InOutReinitializationNeeded,
};
private:
llvm::PointerIntPair<SILInstruction *, 1> instAndKind;
RequireInst(SILInstruction *inst, Kind kind) : instAndKind(inst, kind) {}
public:
static RequireInst forUseAfterTransfer(SILInstruction *inst) {
return {inst, Kind::UseAfterTransfer};
}
static RequireInst forInOutReinitializationNeeded(SILInstruction *inst) {
return {inst, Kind::InOutReinitializationNeeded};
}
SILInstruction *getInst() const { return instAndKind.getPointer(); }
Kind getKind() const { return Kind(instAndKind.getInt()); }
SILInstruction *operator*() const { return getInst(); }
SILInstruction *operator->() const { return getInst(); }
};
class TransferNonSendableImpl {
RegionAnalysisFunctionInfo *regionInfo;
SmallFrozenMultiMap<Operand *, RequireInst, 8>
transferOpToRequireInstMultiMap;
SmallVector<TransferredNonTransferrableInfo, 8>
transferredNonTransferrableInfoList;
SmallVector<InOutSendingNotDisconnectedInfo, 8>
inoutSendingNotDisconnectedInfoList;
SmallVector<AssignIsolatedIntoOutSendingParameterInfo, 8>
assignIsolatedIntoOutSendingParameterInfoList;
public:
TransferNonSendableImpl(RegionAnalysisFunctionInfo *regionInfo)
: regionInfo(regionInfo) {}
void emitDiagnostics();
private:
void runDiagnosticEvaluator();
void emitUseAfterTransferDiagnostics();
void emitTransferredNonTransferrableDiagnostics();
void emitInOutSendingNotDisconnectedInfoList();
void emitAssignIsolatedIntoSendingResultDiagnostics();
};
} // namespace
//===----------------------------------------------------------------------===//
// MARK: UseAfterTransfer Diagnostic Inference
//===----------------------------------------------------------------------===//
namespace {
class UseAfterTransferDiagnosticEmitter {
Operand *transferOp;
SmallVectorImpl<RequireInst> &requireInsts;
bool emittedErrorDiagnostic = false;
public:
UseAfterTransferDiagnosticEmitter(Operand *transferOp,
SmallVectorImpl<RequireInst> &requireInsts)
: transferOp(transferOp), requireInsts(requireInsts) {}
~UseAfterTransferDiagnosticEmitter() {
// If we were supposed to emit a diagnostic and didn't emit an unknown
// pattern error.
if (!emittedErrorDiagnostic)
emitUnknownPatternError();
}
std::optional<DiagnosticBehavior> getBehaviorLimit() const {
return getDiagnosticBehaviorLimitForValue(transferOp->get());
}
/// If we can find a callee decl name, return that. None otherwise.
std::optional<std::pair<DescriptiveDeclKind, DeclName>>
getTransferringCalleeInfo() const {
return getTransferringApplyCalleeInfo(transferOp->getUser());
}
void
emitNamedIsolationCrossingError(SILLocation loc, Identifier name,
SILIsolationInfo namedValuesIsolationInfo,
ApplyIsolationCrossing isolationCrossing) {
// Emit the short error.
diagnoseError(loc, diag::regionbasedisolation_named_transfer_yields_race,
name)
.highlight(loc.getSourceRange())
.limitBehaviorIf(getBehaviorLimit());
// Then emit the note with greater context.
SmallString<64> descriptiveKindStr;
{
if (!namedValuesIsolationInfo.isDisconnected()) {
llvm::raw_svector_ostream os(descriptiveKindStr);
namedValuesIsolationInfo.printForDiagnostics(os);
os << ' ';
}
}
if (auto calleeInfo = getTransferringCalleeInfo()) {
diagnoseNote(
loc,
diag::regionbasedisolation_named_info_transfer_yields_race_callee,
name, descriptiveKindStr, isolationCrossing.getCalleeIsolation(),
calleeInfo->first, calleeInfo->second,
isolationCrossing.getCallerIsolation());
} else {
diagnoseNote(
loc, diag::regionbasedisolation_named_info_transfer_yields_race, name,
descriptiveKindStr, isolationCrossing.getCalleeIsolation(),
isolationCrossing.getCallerIsolation());
}
emitRequireInstDiagnostics();
}
void
emitNamedIsolationCrossingError(SILLocation loc, Identifier name,
SILIsolationInfo namedValuesIsolationInfo,
ApplyIsolationCrossing isolationCrossing,
DeclName calleeDeclName,
DescriptiveDeclKind calleeDeclKind) {
// Emit the short error.
diagnoseError(loc, diag::regionbasedisolation_named_transfer_yields_race,
name)
.highlight(loc.getSourceRange())
.limitBehaviorIf(getBehaviorLimit());
// Then emit the note with greater context.
SmallString<64> descriptiveKindStr;
{
if (!namedValuesIsolationInfo.isDisconnected()) {
llvm::raw_svector_ostream os(descriptiveKindStr);
namedValuesIsolationInfo.printForDiagnostics(os);
os << ' ';
}
}
diagnoseNote(
loc, diag::regionbasedisolation_named_info_transfer_yields_race_callee,
name, descriptiveKindStr, isolationCrossing.getCalleeIsolation(),
calleeDeclKind, calleeDeclName, isolationCrossing.getCallerIsolation());
emitRequireInstDiagnostics();
}
void emitNamedAsyncLetNoIsolationCrossingError(SILLocation loc,
Identifier name) {
// Emit the short error.
diagnoseError(loc, diag::regionbasedisolation_named_transfer_yields_race,
name)
.highlight(loc.getSourceRange())
.limitBehaviorIf(getBehaviorLimit());
diagnoseNote(
loc, diag::regionbasedisolation_named_nonisolated_asynclet_name, name);
emitRequireInstDiagnostics();
}
void emitTypedIsolationCrossing(SILLocation loc, Type inferredType,
ApplyIsolationCrossing isolationCrossing) {
diagnoseError(
loc, diag::regionbasedisolation_transfer_yields_race_with_isolation,
inferredType, isolationCrossing.getCallerIsolation(),
isolationCrossing.getCalleeIsolation())
.highlight(loc.getSourceRange())
.limitBehaviorIf(getBehaviorLimit());
emitRequireInstDiagnostics();
}
void emitNamedUseOfStronglyTransferredValue(SILLocation loc,
Identifier name) {
// Emit the short error.
diagnoseError(loc, diag::regionbasedisolation_named_transfer_yields_race,
name)
.highlight(loc.getSourceRange())
.limitBehaviorIf(getBehaviorLimit());
// Then emit the note with greater context.
diagnoseNote(
loc, diag::regionbasedisolation_named_value_used_after_explicit_sending,
name)
.highlight(loc.getSourceRange());
// Finally the require points.
emitRequireInstDiagnostics();
}
void emitTypedUseOfStronglyTransferredValue(SILLocation loc,
Type inferredType) {
diagnoseError(
loc,
diag::
regionbasedisolation_transfer_yields_race_stronglytransferred_binding,
inferredType)
.highlight(loc.getSourceRange())
.limitBehaviorIf(getBehaviorLimit());
emitRequireInstDiagnostics();
}
void emitTypedRaceWithUnknownIsolationCrossing(SILLocation loc,
Type inferredType) {
diagnoseError(loc,
diag::regionbasedisolation_transfer_yields_race_no_isolation,
inferredType)
.highlight(loc.getSourceRange())
.limitBehaviorIf(getBehaviorLimit());
emitRequireInstDiagnostics();
}
void emitNamedIsolationCrossingDueToCapture(
SILLocation loc, Identifier name,
SILIsolationInfo namedValuesIsolationInfo,
ApplyIsolationCrossing isolationCrossing) {
// Emit the short error.
diagnoseError(loc, diag::regionbasedisolation_named_transfer_yields_race,
name)
.highlight(loc.getSourceRange())
.limitBehaviorIf(getBehaviorLimit());
SmallString<64> descriptiveKindStr;
{
if (!namedValuesIsolationInfo.isDisconnected()) {
llvm::raw_svector_ostream os(descriptiveKindStr);
namedValuesIsolationInfo.printForDiagnostics(os);
os << ' ';
}
}
diagnoseNote(
loc, diag::regionbasedisolation_named_isolated_closure_yields_race,
descriptiveKindStr, name, isolationCrossing.getCalleeIsolation(),
isolationCrossing.getCallerIsolation())
.highlight(loc.getSourceRange());
emitRequireInstDiagnostics();
}
void emitTypedIsolationCrossingDueToCapture(
SILLocation loc, Type inferredType,
ApplyIsolationCrossing isolationCrossing) {
diagnoseError(loc, diag::regionbasedisolation_isolated_capture_yields_race,
inferredType, isolationCrossing.getCalleeIsolation(),
isolationCrossing.getCallerIsolation())
.highlight(loc.getSourceRange())
.limitBehaviorIf(getBehaviorLimit());
emitRequireInstDiagnostics();
}
void emitUnknownPatternError() {
if (shouldAbortOnUnknownPatternMatchError()) {
llvm::report_fatal_error(
"RegionIsolation: Aborting on unknown pattern match error");
}
diagnoseError(transferOp->getUser(),
diag::regionbasedisolation_unknown_pattern)
.limitBehaviorIf(getBehaviorLimit());
}
private:
ASTContext &getASTContext() const {
return transferOp->getFunction()->getASTContext();
}
template <typename... T, typename... U>
InFlightDiagnostic diagnoseError(SourceLoc loc, Diag<T...> diag,
U &&...args) {
emittedErrorDiagnostic = true;
return std::move(getASTContext()
.Diags.diagnose(loc, diag, std::forward<U>(args)...)
.warnUntilSwiftVersion(6));
}
template <typename... T, typename... U>
InFlightDiagnostic diagnoseError(SILLocation loc, Diag<T...> diag,
U &&...args) {
return diagnoseError(loc.getSourceLoc(), diag, std::forward<U>(args)...);
}
template <typename... T, typename... U>
InFlightDiagnostic diagnoseError(SILInstruction *inst, Diag<T...> diag,
U &&...args) {
return diagnoseError(inst->getLoc(), diag, std::forward<U>(args)...);
}
template <typename... T, typename... U>
InFlightDiagnostic diagnoseNote(SourceLoc loc, Diag<T...> diag, U &&...args) {
return getASTContext().Diags.diagnose(loc, diag, std::forward<U>(args)...);
}
template <typename... T, typename... U>
InFlightDiagnostic diagnoseNote(SILLocation loc, Diag<T...> diag,
U &&...args) {
return diagnoseNote(loc.getSourceLoc(), diag, std::forward<U>(args)...);
}
template <typename... T, typename... U>
InFlightDiagnostic diagnoseNote(SILInstruction *inst, Diag<T...> diag,
U &&...args) {
return diagnoseNote(inst->getLoc(), diag, std::forward<U>(args)...);
}
void emitRequireInstDiagnostics() {
// Now actually emit the require notes.
while (!requireInsts.empty()) {
auto require = requireInsts.pop_back_val();
switch (require.getKind()) {
case RequireInst::UseAfterTransfer:
diagnoseNote(*require, diag::regionbasedisolation_maybe_race)
.highlight(require->getLoc().getSourceRange());
continue;
case RequireInst::InOutReinitializationNeeded:
diagnoseNote(
*require,
diag::regionbasedisolation_inout_sending_must_be_reinitialized)
.highlight(require->getLoc().getSourceRange());
continue;
}
llvm_unreachable("Covered switch isn't covered?!");
}
}
};
class UseAfterTransferDiagnosticInferrer {
Operand *transferOp;
UseAfterTransferDiagnosticEmitter diagnosticEmitter;
RegionAnalysisValueMap &valueMap;
TransferringOperandToStateMap &transferringOpToStateMap;
SILLocation baseLoc = SILLocation::invalid();
Type baseInferredType;
struct AutoClosureWalker;
public:
UseAfterTransferDiagnosticInferrer(
Operand *transferOp, SmallVectorImpl<RequireInst> &requireInsts,
RegionAnalysisValueMap &valueMap,
TransferringOperandToStateMap &transferringOpToStateMap)
: transferOp(transferOp), diagnosticEmitter(transferOp, requireInsts),
valueMap(valueMap), transferringOpToStateMap(transferringOpToStateMap),
baseLoc(transferOp->getUser()->getLoc()),
baseInferredType(transferOp->get()->getType().getASTType()) {}
void infer();
Operand *getTransferringOperand() const { return transferOp; }
private:
bool initForIsolatedPartialApply(Operand *op, AbstractClosureExpr *ace);
void initForApply(Operand *op, ApplyExpr *expr);
void initForAutoclosure(Operand *op, AutoClosureExpr *expr);
Expr *getFoundExprForSelf(ApplyExpr *sourceApply) {
if (auto callExpr = dyn_cast<CallExpr>(sourceApply))
if (auto calledExpr =
dyn_cast<DotSyntaxCallExpr>(callExpr->getDirectCallee()))
return calledExpr->getBase();
return nullptr;
}
Expr *getFoundExprForParam(ApplyExpr *sourceApply, unsigned argNum) {
auto *expr = sourceApply->getArgs()->getExpr(argNum);
// If we have an erasure expression, lets use the original type. We do
// this since we are not saying the specific parameter that is the
// issue and we are using the type to explain it to the user.
if (auto *erasureExpr = dyn_cast<ErasureExpr>(expr))
expr = erasureExpr->getSubExpr();
return expr;
}
};
} // namespace
bool UseAfterTransferDiagnosticInferrer::initForIsolatedPartialApply(
Operand *op, AbstractClosureExpr *ace) {
SmallVector<std::tuple<CapturedValue, unsigned, ApplyIsolationCrossing>, 8>
foundCapturedIsolationCrossing;
ace->getIsolationCrossing(foundCapturedIsolationCrossing);
if (foundCapturedIsolationCrossing.empty())
return false;
unsigned opIndex = ApplySite(op->getUser()).getAppliedArgIndex(*op);
bool emittedDiagnostic = false;
for (auto &p : foundCapturedIsolationCrossing) {
if (std::get<1>(p) != opIndex)
continue;
emittedDiagnostic = true;
auto &state = transferringOpToStateMap.get(transferOp);
if (auto rootValueAndName =
VariableNameInferrer::inferNameAndRoot(transferOp->get())) {
diagnosticEmitter.emitNamedIsolationCrossingDueToCapture(
RegularLocation(std::get<0>(p).getLoc()), rootValueAndName->first,
state.isolationInfo.getIsolationInfo(), std::get<2>(p));
continue;
}
diagnosticEmitter.emitTypedIsolationCrossingDueToCapture(
RegularLocation(std::get<0>(p).getLoc()), baseInferredType,
std::get<2>(p));
}
return emittedDiagnostic;
}
void UseAfterTransferDiagnosticInferrer::initForApply(Operand *op,
ApplyExpr *sourceApply) {
auto isolationCrossing = sourceApply->getIsolationCrossing().value();
// Grab out full apply site and see if we can find a better expr.
SILInstruction *i = const_cast<SILInstruction *>(op->getUser());
auto fai = FullApplySite::isa(i);
assert(!fai.getArgumentConvention(*op).isIndirectOutParameter() &&
"An indirect out parameter is never transferred");
auto *foundExpr = inferArgumentExprFromApplyExpr(sourceApply, fai, op);
auto inferredArgType =
foundExpr ? foundExpr->findOriginalType() : baseInferredType;
diagnosticEmitter.emitTypedIsolationCrossing(baseLoc, inferredArgType,
isolationCrossing);
}
/// This walker visits an AutoClosureExpr and looks for uses of a specific
/// captured value. We want to error on the uses in the autoclosure.
struct UseAfterTransferDiagnosticInferrer::AutoClosureWalker : ASTWalker {
UseAfterTransferDiagnosticInferrer &foundTypeInfo;
ValueDecl *targetDecl;
SILIsolationInfo targetDeclIsolationInfo;
SmallPtrSet<Expr *, 8> visitedCallExprDeclRefExprs;
AutoClosureWalker(UseAfterTransferDiagnosticInferrer &foundTypeInfo,
ValueDecl *targetDecl,
SILIsolationInfo targetDeclIsolationInfo)
: foundTypeInfo(foundTypeInfo), targetDecl(targetDecl),
targetDeclIsolationInfo(targetDeclIsolationInfo) {}
Expr *lookThroughArgExpr(Expr *expr) {
while (true) {
if (auto *memberRefExpr = dyn_cast<MemberRefExpr>(expr)) {
expr = memberRefExpr->getBase();
continue;
}
if (auto *cvt = dyn_cast<ImplicitConversionExpr>(expr)) {
expr = cvt->getSubExpr();
continue;
}
if (auto *e = dyn_cast<ForceValueExpr>(expr)) {
expr = e->getSubExpr();
continue;
}
if (auto *t = dyn_cast<TupleElementExpr>(expr)) {
expr = t->getBase();
continue;
}
return expr;
}
}
PreWalkResult<Expr *> walkToExprPre(Expr *expr) override {
if (auto *declRef = dyn_cast<DeclRefExpr>(expr)) {
// If this decl ref expr was not visited as part of a callExpr and is our
// target decl... emit a simple async let error.
if (!visitedCallExprDeclRefExprs.count(declRef)) {
if (declRef->getDecl() == targetDecl) {
foundTypeInfo.diagnosticEmitter
.emitNamedAsyncLetNoIsolationCrossingError(
foundTypeInfo.baseLoc, targetDecl->getBaseIdentifier());
return Action::Continue(expr);
}
}
}
// If we have a call expr, see if any of its arguments will cause our sent
// value to be transferred into another isolation domain.
if (auto *callExpr = dyn_cast<CallExpr>(expr)) {
// Search callExpr's arguments to see if we have our targetDecl.
auto *argList = callExpr->getArgs();
for (auto pair : llvm::enumerate(argList->getArgExprs())) {
auto *arg = lookThroughArgExpr(pair.value());
auto *declRef = dyn_cast<DeclRefExpr>(arg);
if (!declRef)
continue;
if (declRef->getDecl() != targetDecl)
continue;
// Found our target!
visitedCallExprDeclRefExprs.insert(declRef);
auto isolationCrossing = callExpr->getIsolationCrossing();
// If we do not have an isolation crossing, then we must be just sending
// a value in a nonisolated fashion into an async let. So emit the
// simple async let error.
if (!isolationCrossing) {
foundTypeInfo.diagnosticEmitter
.emitNamedAsyncLetNoIsolationCrossingError(
foundTypeInfo.baseLoc, targetDecl->getBaseIdentifier());
continue;
}
// Otherwise, we are calling an actor isolated function in the async
// let. Emit a better error.
// See if we can find a valueDecl/name for our callee so we can
// emit a nicer error.
ConcreteDeclRef concreteDecl =
callExpr->getDirectCallee()->getReferencedDecl();
// If we do not find a direct one, see if we are calling a method
// on a nominal type.
if (!concreteDecl) {
if (auto *dot =
dyn_cast<DotSyntaxCallExpr>(callExpr->getDirectCallee())) {
concreteDecl = dot->getSemanticFn()->getReferencedDecl();
}
}
if (!concreteDecl)
continue;
auto *valueDecl = concreteDecl.getDecl();
assert(valueDecl && "Should be non-null if concreteDecl is valid");
if (auto isolationCrossing = callExpr->getIsolationCrossing()) {
// If we have an isolation crossing, use that information.
if (valueDecl->hasName()) {
foundTypeInfo.diagnosticEmitter.emitNamedIsolationCrossingError(
foundTypeInfo.baseLoc, targetDecl->getBaseIdentifier(),
targetDeclIsolationInfo, *isolationCrossing,
valueDecl->getName(), valueDecl->getDescriptiveKind());
continue;
}
// Otherwise default back to the "callee" error.
foundTypeInfo.diagnosticEmitter.emitNamedIsolationCrossingError(
foundTypeInfo.baseLoc, targetDecl->getBaseIdentifier(),
targetDeclIsolationInfo, *isolationCrossing);
continue;
}
}
}
return Action::Continue(expr);
}
};
void UseAfterTransferDiagnosticInferrer::infer() {
// Otherwise, see if our operand's instruction is a transferring parameter.
if (auto fas = FullApplySite::isa(transferOp->getUser())) {
assert(!fas.getArgumentConvention(*transferOp).isIndirectOutParameter() &&
"We should never transfer an indirect out parameter");
if (fas.getArgumentParameterInfo(*transferOp)
.hasOption(SILParameterInfo::Sending)) {
// First try to do the named diagnostic if we can find a name.
if (auto rootValueAndName =
VariableNameInferrer::inferNameAndRoot(transferOp->get())) {
return diagnosticEmitter.emitNamedUseOfStronglyTransferredValue(
baseLoc, rootValueAndName->first);
}
// Otherwise, emit the typed diagnostic.
return diagnosticEmitter.emitTypedUseOfStronglyTransferredValue(
baseLoc, baseInferredType);
}
}
auto loc = transferOp->getUser()->getLoc();
// If we have a partial_apply that is actor isolated, see if we found a
// transfer error due to us transferring a value into it.
if (auto *ace = loc.getAsASTNode<AbstractClosureExpr>()) {
if (ace->getActorIsolation().isActorIsolated()) {
if (initForIsolatedPartialApply(transferOp, ace)) {
return;
}
}
}
if (auto *sourceApply = loc.getAsASTNode<ApplyExpr>()) {
// Before we do anything further, see if we can find a name and emit a name
// error.
if (auto rootValueAndName =
VariableNameInferrer::inferNameAndRoot(transferOp->get())) {
auto &state = transferringOpToStateMap.get(transferOp);
return diagnosticEmitter.emitNamedIsolationCrossingError(
baseLoc, rootValueAndName->first,
state.isolationInfo.getIsolationInfo(),
*sourceApply->getIsolationCrossing());
}
// Otherwise, try to infer from the ApplyExpr.
return initForApply(transferOp, sourceApply);
}
if (auto fas = FullApplySite::isa(transferOp->getUser())) {
if (auto isolationCrossing = fas.getIsolationCrossing()) {
return diagnosticEmitter.emitTypedIsolationCrossing(
baseLoc, baseInferredType, *isolationCrossing);
}
}
auto *autoClosureExpr = loc.getAsASTNode<AutoClosureExpr>();
if (!autoClosureExpr) {
return diagnosticEmitter.emitUnknownPatternError();
}
auto *i = transferOp->getUser();
auto pai = ApplySite::isa(i);
unsigned captureIndex = pai.getAppliedArgIndex(*transferOp);
auto &state = transferringOpToStateMap.get(transferOp);
auto captureInfo =
autoClosureExpr->getCaptureInfo().getCaptures()[captureIndex];
auto *captureDecl = captureInfo.getDecl();
AutoClosureWalker walker(*this, captureDecl,
state.isolationInfo.getIsolationInfo());
autoClosureExpr->walk(walker);
}
// Top level entrypoint for use after transfer diagnostics.
void TransferNonSendableImpl::emitUseAfterTransferDiagnostics() {
auto *function = regionInfo->getFunction();
BasicBlockData<BlockLivenessInfo> blockLivenessInfo(function);
// We use a generation counter so we can lazily reset blockLivenessInfo
// since we cannot clear it without iterating over it.
unsigned blockLivenessInfoGeneration = 0;
if (transferOpToRequireInstMultiMap.empty())
return;
LLVM_DEBUG(llvm::dbgs() << "Emitting use after transfer diagnostics.\n");
for (auto [transferOp, requireInsts] :
transferOpToRequireInstMultiMap.getRange()) {
LLVM_DEBUG(llvm::dbgs()
<< "Transfer Op. Number: " << transferOp->getOperandNumber()
<< ". User: " << *transferOp->getUser());
// Then look for our requires before we emit any error. We want to emit a
// single we don't understand error if we do not find the require.
bool didEmitRequireNote = false;
InstructionSet requireInstsUnique(function);
RequireLiveness liveness(blockLivenessInfoGeneration, transferOp,
blockLivenessInfo);
++blockLivenessInfoGeneration;
liveness.process(requireInsts);
SmallVector<RequireInst, 8> requireInstsForError;
for (auto require : requireInsts) {
// We can have multiple of the same require insts if we had a require
// and an assign from the same instruction. Our liveness checking
// above doesn't care about that, but we still need to make sure we do
// not emit twice.
if (!requireInstsUnique.insert(*require))
continue;
// If this was not a last require, do not emit an error.
if (!liveness.finalRequires.contains(*require))
continue;
requireInstsForError.push_back(require);
didEmitRequireNote = true;
}
// If we did not emit a require, emit an "unknown pattern" error that
// tells the user to file a bug. This importantly ensures that we can
// guarantee that we always find the require if we successfully compile.
if (!didEmitRequireNote) {
if (shouldAbortOnUnknownPatternMatchError()) {
llvm::report_fatal_error(
"RegionIsolation: Aborting on unknown pattern match error");
}
diagnoseError(transferOp, diag::regionbasedisolation_unknown_pattern);
continue;
}
UseAfterTransferDiagnosticInferrer diagnosticInferrer(
transferOp, requireInstsForError, regionInfo->getValueMap(),
regionInfo->getTransferringOpToStateMap());
diagnosticInferrer.infer();
}
}
//===----------------------------------------------------------------------===//
// MARK: Transfer NonTransferrable Diagnostic Inference
//===----------------------------------------------------------------------===//
namespace {
class TransferNonTransferrableDiagnosticEmitter {
TransferredNonTransferrableInfo info;
bool emittedErrorDiagnostic = false;
public:
TransferNonTransferrableDiagnosticEmitter(
TransferredNonTransferrableInfo info)
: info(info) {}
~TransferNonTransferrableDiagnosticEmitter() {
if (!emittedErrorDiagnostic) {
emitUnknownPatternError();
}
}
Operand *getOperand() const { return info.transferredOperand; }
SILValue getNonTransferrableValue() const {
return info.nonTransferrable.dyn_cast<SILValue>();
}
SILInstruction *getNonTransferringActorIntroducingInst() const {
return info.nonTransferrable.dyn_cast<SILInstruction *>();
}
std::optional<DiagnosticBehavior> getBehaviorLimit() const {
return getDiagnosticBehaviorLimitForValue(info.transferredOperand->get());
}
/// If we can find a callee decl name, return that. None otherwise.
std::optional<std::pair<DescriptiveDeclKind, DeclName>>
getTransferringCalleeInfo() const {
return getTransferringApplyCalleeInfo(info.transferredOperand->getUser());
}
SILLocation getLoc() const {
return info.transferredOperand->getUser()->getLoc();
}
/// Return the isolation region info for \p getNonTransferrableValue().
SILDynamicMergedIsolationInfo getIsolationRegionInfo() const {
return info.isolationRegionInfo;
}
void emitUnknownPatternError() {
if (shouldAbortOnUnknownPatternMatchError()) {
llvm::report_fatal_error(
"RegionIsolation: Aborting on unknown pattern match error");
}
diagnoseError(getOperand()->getUser(),
diag::regionbasedisolation_unknown_pattern)
.limitBehaviorIf(getBehaviorLimit());
}
void emitUnknownUse(SILLocation loc) {
// TODO: This will eventually be an unknown pattern error.
diagnoseError(loc,
diag::regionbasedisolation_task_or_actor_isolated_transferred)
.limitBehaviorIf(getBehaviorLimit());
}
void emitFunctionArgumentApply(SILLocation loc, Type type,
ApplyIsolationCrossing crossing) {
SmallString<64> descriptiveKindStr;
{
llvm::raw_svector_ostream os(descriptiveKindStr);
getIsolationRegionInfo().printForDiagnostics(os);
}
diagnoseError(loc, diag::regionbasedisolation_arg_transferred,
descriptiveKindStr, type, crossing.getCalleeIsolation())
.highlight(getOperand()->getUser()->getLoc().getSourceRange())
.limitBehaviorIf(getBehaviorLimit());
}
void emitNamedFunctionArgumentClosure(SILLocation loc, Identifier name,
ApplyIsolationCrossing crossing) {
emitNamedOnlyError(loc, name);
SmallString<64> descriptiveKindStr;
{
if (!getIsolationRegionInfo().isDisconnected()) {
llvm::raw_svector_ostream os(descriptiveKindStr);
getIsolationRegionInfo().printForDiagnostics(os);
os << ' ';
}
}
diagnoseNote(loc,
diag::regionbasedisolation_named_isolated_closure_yields_race,
descriptiveKindStr, name, crossing.getCalleeIsolation(),
crossing.getCallerIsolation())
.highlight(loc.getSourceRange());
}
void emitFunctionArgumentApplyStronglyTransferred(SILLocation loc,
Type type) {
SmallString<64> descriptiveKindStr;
{
llvm::raw_svector_ostream os(descriptiveKindStr);
getIsolationRegionInfo().printForDiagnostics(os);
}
auto diag =
diag::regionbasedisolation_arg_passed_to_strongly_transferred_param;
diagnoseError(loc, diag, descriptiveKindStr, type)
.highlight(getOperand()->getUser()->getLoc().getSourceRange())
.limitBehaviorIf(getBehaviorLimit());
}
/// Only use if we were able to find the actual isolated value.
void emitTypedSendingNeverSendableToSendingClosureParamDirectlyIsolated(
SILLocation loc, CapturedValue capturedValue) {
SmallString<64> descriptiveKindStr;
{
llvm::raw_svector_ostream os(descriptiveKindStr);
if (getIsolationRegionInfo().getIsolationInfo().isTaskIsolated()) {
os << "code in the current task";
} else {
getIsolationRegionInfo().printForDiagnostics(os);
os << " code";
}
}
diagnoseError(loc,
diag::regionbasedisolation_typed_tns_passed_sending_closure,
descriptiveKindStr)
.highlight(loc.getSourceRange())
.limitBehaviorIf(
getDiagnosticBehaviorLimitForCapturedValue(capturedValue));
auto capturedLoc = RegularLocation(capturedValue.getLoc());
if (getIsolationRegionInfo().getIsolationInfo().isTaskIsolated()) {
auto diag = diag::
regionbasedisolation_typed_tns_passed_to_sending_closure_helper_have_value_task_isolated;
diagnoseNote(capturedLoc, diag, capturedValue.getDecl()->getName());
return;
}
descriptiveKindStr.clear();
{
llvm::raw_svector_ostream os(descriptiveKindStr);
getIsolationRegionInfo().printForDiagnostics(os);
}
auto diag = diag::
regionbasedisolation_typed_tns_passed_to_sending_closure_helper_have_value;
diagnoseNote(capturedLoc, diag, descriptiveKindStr,
capturedValue.getDecl()->getName());
}
void emitTypedSendingNeverSendableToSendingClosureParam(
SILLocation loc, ArrayRef<CapturedValue> capturedValues) {
SmallString<64> descriptiveKindStr;
{
llvm::raw_svector_ostream os(descriptiveKindStr);
if (getIsolationRegionInfo().getIsolationInfo().isTaskIsolated()) {
os << "code in the current task";
} else {
getIsolationRegionInfo().printForDiagnostics(os);
os << " code";
}
}
auto behaviorLimit =
getDiagnosticBehaviorLimitForCapturedValues(capturedValues);
diagnoseError(loc,
diag::regionbasedisolation_typed_tns_passed_sending_closure,
descriptiveKindStr)
.highlight(loc.getSourceRange())
.limitBehaviorIf(behaviorLimit);
if (capturedValues.size() == 1) {
auto captured = capturedValues.front();
auto capturedLoc = RegularLocation(captured.getLoc());
if (getIsolationRegionInfo().getIsolationInfo().isTaskIsolated()) {
auto diag = diag::
regionbasedisolation_typed_tns_passed_to_sending_closure_helper_have_value_task_isolated;
diagnoseNote(capturedLoc, diag, captured.getDecl()->getName());
return;
}
descriptiveKindStr.clear();
{
llvm::raw_svector_ostream os(descriptiveKindStr);
getIsolationRegionInfo().printForDiagnostics(os);
}
auto diag = diag::
regionbasedisolation_typed_tns_passed_to_sending_closure_helper_have_value_region;
diagnoseNote(capturedLoc, diag, descriptiveKindStr,
captured.getDecl()->getName());
return;
}
for (auto captured : capturedValues) {
auto capturedLoc = RegularLocation(captured.getLoc());
auto diag = diag::
regionbasedisolation_typed_tns_passed_to_sending_closure_helper_multiple_value;
diagnoseNote(capturedLoc, diag, captured.getDecl()->getName());
}
}
void emitNamedOnlyError(SILLocation loc, Identifier name) {
diagnoseError(loc, diag::regionbasedisolation_named_transfer_yields_race,
name)
.highlight(getOperand()->getUser()->getLoc().getSourceRange())
.limitBehaviorIf(getBehaviorLimit());
}
void emitNamedAsyncLetCapture(SILLocation loc, Identifier name,
SILIsolationInfo transferredValueIsolation) {
assert(!getIsolationRegionInfo().isDisconnected() &&
"Should never be disconnected?!");
emitNamedOnlyError(loc, name);
SmallString<64> descriptiveKindStr;
{
llvm::raw_svector_ostream os(descriptiveKindStr);
getIsolationRegionInfo().printForDiagnostics(os);
}
diagnoseNote(loc,
diag::regionbasedisolation_named_transfer_nt_asynclet_capture,
name, descriptiveKindStr)
.limitBehaviorIf(getBehaviorLimit());
}
void emitNamedIsolation(SILLocation loc, Identifier name,
ApplyIsolationCrossing isolationCrossing) {
emitNamedOnlyError(loc, name);
SmallString<64> descriptiveKindStr;
SmallString<64> descriptiveKindStrWithSpace;
{
if (!getIsolationRegionInfo().isDisconnected()) {
{
llvm::raw_svector_ostream os(descriptiveKindStr);
getIsolationRegionInfo().printForDiagnostics(os);
}
descriptiveKindStrWithSpace = descriptiveKindStr;
descriptiveKindStrWithSpace.push_back(' ');
}
}
if (auto calleeInfo = getTransferringCalleeInfo()) {
diagnoseNote(
loc,
diag::regionbasedisolation_named_transfer_non_transferrable_callee,
name, descriptiveKindStrWithSpace,
isolationCrossing.getCalleeIsolation(), calleeInfo->first,
calleeInfo->second, descriptiveKindStr);
} else {
diagnoseNote(loc,
diag::regionbasedisolation_named_transfer_non_transferrable,
name, descriptiveKindStrWithSpace,
isolationCrossing.getCalleeIsolation(), descriptiveKindStr);
}
}
void emitNamedFunctionArgumentApplyStronglyTransferred(SILLocation loc,
Identifier varName) {
emitNamedOnlyError(loc, varName);
SmallString<64> descriptiveKindStr;
{
if (!getIsolationRegionInfo().isDisconnected()) {
llvm::raw_svector_ostream os(descriptiveKindStr);
getIsolationRegionInfo().printForDiagnostics(os);
os << ' ';
}
}
auto diag = diag::regionbasedisolation_named_transfer_into_sending_param;
diagnoseNote(loc, diag, descriptiveKindStr, varName);
}
void emitNamedTransferringReturn(SILLocation loc, Identifier varName) {
emitNamedOnlyError(loc, varName);
SmallString<64> descriptiveKindStr;
SmallString<64> descriptiveKindStrWithSpace;
{
if (!getIsolationRegionInfo().isDisconnected()) {
{
llvm::raw_svector_ostream os(descriptiveKindStr);
getIsolationRegionInfo().printForDiagnostics(os);
}
descriptiveKindStrWithSpace = descriptiveKindStr;
descriptiveKindStrWithSpace.push_back(' ');
}
}
auto diag =
diag::regionbasedisolation_named_notransfer_transfer_into_result;
diagnoseNote(loc, diag, descriptiveKindStrWithSpace, varName,
descriptiveKindStr);
}
private:
ASTContext &getASTContext() const {
return getOperand()->getFunction()->getASTContext();
}
template <typename... T, typename... U>
InFlightDiagnostic diagnoseError(SourceLoc loc, Diag<T...> diag,
U &&...args) {
emittedErrorDiagnostic = true;
return std::move(getASTContext()
.Diags.diagnose(loc, diag, std::forward<U>(args)...)
.warnUntilSwiftVersion(6));
}
template <typename... T, typename... U>
InFlightDiagnostic diagnoseError(SILLocation loc, Diag<T...> diag,
U &&...args) {
return diagnoseError(loc.getSourceLoc(), diag, std::forward<U>(args)...);
}
template <typename... T, typename... U>
InFlightDiagnostic diagnoseError(SILInstruction *inst, Diag<T...> diag,
U &&...args) {
return diagnoseError(inst->getLoc(), diag, std::forward<U>(args)...);
}
template <typename... T, typename... U>
InFlightDiagnostic diagnoseNote(SourceLoc loc, Diag<T...> diag, U &&...args) {
return getASTContext().Diags.diagnose(loc, diag, std::forward<U>(args)...);
}
template <typename... T, typename... U>
InFlightDiagnostic diagnoseNote(SILLocation loc, Diag<T...> diag,
U &&...args) {
return diagnoseNote(loc.getSourceLoc(), diag, std::forward<U>(args)...);
}
template <typename... T, typename... U>
InFlightDiagnostic diagnoseNote(SILInstruction *inst, Diag<T...> diag,
U &&...args) {
return diagnoseNote(inst->getLoc(), diag, std::forward<U>(args)...);
}
};
class TransferNonTransferrableDiagnosticInferrer {
struct AutoClosureWalker;
RegionAnalysisValueMap &valueMap;
TransferNonTransferrableDiagnosticEmitter diagnosticEmitter;
public:
TransferNonTransferrableDiagnosticInferrer(
RegionAnalysisValueMap &valueMap, TransferredNonTransferrableInfo info)
: valueMap(valueMap), diagnosticEmitter(info) {}
/// Gathers diagnostics. Returns false if we emitted a "I don't understand
/// error". If we emit such an error, we should bail without emitting any
/// further diagnostics, since we may not have any diagnostics or be in an
/// inconcistent state.
bool run();
private:
/// \p actualCallerIsolation is used to override the caller isolation we use
/// when emitting the error if the closure would have the incorrect one.
bool initForIsolatedPartialApply(
Operand *op, AbstractClosureExpr *ace,
std::optional<ActorIsolation> actualCallerIsolation = {});
bool initForSendingPartialApply(FullApplySite fas, Operand *pai);
std::optional<unsigned>
getIsolatedValuePartialApplyIndex(PartialApplyInst *pai,
SILValue isolatedValue) {
for (auto &paiOp : ApplySite(pai).getArgumentOperands()) {
if (valueMap.getTrackableValue(paiOp.get()).getRepresentative() ==
isolatedValue) {
// isolated_any causes all partial apply parameters to be shifted by 1
// due to the implicit isolated any parameter.
unsigned isIsolatedAny = pai->getFunctionType()->getIsolation() ==
SILFunctionTypeIsolation::Erased;
return ApplySite(pai).getAppliedArgIndex(paiOp) - isIsolatedAny;
}
}
return {};
}
};
} // namespace
bool TransferNonTransferrableDiagnosticInferrer::initForSendingPartialApply(
FullApplySite fas, Operand *paiOp) {
auto *pai =
dyn_cast<PartialApplyInst>(stripFunctionConversions(paiOp->get()));
if (!pai)
return false;
// For now we want this to be really narrow and to only apply to closure
// literals.
auto *ce = pai->getLoc().getAsASTNode<ClosureExpr>();
if (!ce)
return false;
// Ok, we now know we have a partial apply and it is a closure literal. Lets
// see if we can find the exact thing that caused the closure literal to be
// actor isolated.
auto isolationInfo = diagnosticEmitter.getIsolationRegionInfo();
if (isolationInfo->hasIsolatedValue()) {
// Now that we have the value, see if that value is one of our captured
// values.
auto isolatedValue = isolationInfo->getIsolatedValue();
auto matchingElt = getIsolatedValuePartialApplyIndex(pai, isolatedValue);
if (matchingElt) {
// Ok, we found the matching element. Lets emit our diagnostic!
auto capture = ce->getCaptureInfo().getCaptures()[*matchingElt];
diagnosticEmitter
.emitTypedSendingNeverSendableToSendingClosureParamDirectlyIsolated(
ce, capture);
return true;
}
}
// Ok, we are not tracking an actual isolated value or we do not capture the
// isolated value directly... we need to be smarter here. First lets gather up
// all non-Sendable values captured by the closure.
SmallVector<CapturedValue, 8> nonSendableCaptures;
for (auto capture : ce->getCaptureInfo().getCaptures()) {
auto *decl = capture.getDecl();
auto type = decl->getInterfaceType()->getCanonicalType();
auto silType = SILType::getPrimitiveObjectType(type);
if (!SILIsolationInfo::isNonSendableType(silType, pai->getFunction()))
continue;
auto *fromDC = decl->getInnermostDeclContext();
auto *nom = silType.getNominalOrBoundGenericNominal();
if (nom && fromDC) {
if (auto diagnosticBehavior =
getConcurrencyDiagnosticBehaviorLimit(nom, fromDC)) {
if (*diagnosticBehavior == DiagnosticBehavior::Ignore)
continue;
}
}
nonSendableCaptures.push_back(capture);
}
// If we do not have any non-Sendable captures... bail.
if (nonSendableCaptures.empty())
return false;
// Otherwise, emit the diagnostic.
diagnosticEmitter.emitTypedSendingNeverSendableToSendingClosureParam(
ce, nonSendableCaptures);
return true;
}
bool TransferNonTransferrableDiagnosticInferrer::initForIsolatedPartialApply(
Operand *op, AbstractClosureExpr *ace,
std::optional<ActorIsolation> actualCallerIsolation) {
SmallVector<std::tuple<CapturedValue, unsigned, ApplyIsolationCrossing>, 8>
foundCapturedIsolationCrossing;
ace->getIsolationCrossing(foundCapturedIsolationCrossing);
if (foundCapturedIsolationCrossing.empty())
return false;
unsigned opIndex = ApplySite(op->getUser()).getAppliedArgIndex(*op);
for (auto &p : foundCapturedIsolationCrossing) {
if (std::get<1>(p) == opIndex) {
auto loc = RegularLocation(std::get<0>(p).getLoc());
auto crossing = std::get<2>(p);
auto declIsolation = crossing.getCallerIsolation();
auto closureIsolation = crossing.getCalleeIsolation();
if (!bool(declIsolation) && actualCallerIsolation) {
declIsolation = *actualCallerIsolation;
}
diagnosticEmitter.emitNamedFunctionArgumentClosure(
loc, std::get<0>(p).getDecl()->getBaseIdentifier(),
ApplyIsolationCrossing(declIsolation, closureIsolation));
return true;
}
}
return false;
}
/// This walker visits an AutoClosureExpr and looks for uses of a specific
/// captured value. We want to error on the uses in the autoclosure.
struct TransferNonTransferrableDiagnosticInferrer::AutoClosureWalker
: ASTWalker {
TransferNonTransferrableDiagnosticEmitter &foundTypeInfo;
ValueDecl *targetDecl;
SILIsolationInfo targetDeclIsolationInfo;
SmallPtrSet<Expr *, 8> visitedCallExprDeclRefExprs;
SILLocation captureLoc;
bool isAsyncLet;
AutoClosureWalker(TransferNonTransferrableDiagnosticEmitter &foundTypeInfo,
ValueDecl *targetDecl,
SILIsolationInfo targetDeclIsolationInfo,
SILLocation captureLoc, bool isAsyncLet)
: foundTypeInfo(foundTypeInfo), targetDecl(targetDecl),
targetDeclIsolationInfo(targetDeclIsolationInfo),
captureLoc(captureLoc), isAsyncLet(isAsyncLet) {}
Expr *lookThroughArgExpr(Expr *expr) {
while (true) {
if (auto *memberRefExpr = dyn_cast<MemberRefExpr>(expr)) {
expr = memberRefExpr->getBase();
continue;
}
if (auto *cvt = dyn_cast<ImplicitConversionExpr>(expr)) {
expr = cvt->getSubExpr();
continue;
}
if (auto *e = dyn_cast<ForceValueExpr>(expr)) {
expr = e->getSubExpr();
continue;
}
if (auto *t = dyn_cast<TupleElementExpr>(expr)) {
expr = t->getBase();
continue;
}
return expr;
}
}
PreWalkResult<Expr *> walkToExprPre(Expr *expr) override {
if (auto *declRef = dyn_cast<DeclRefExpr>(expr)) {
// If this decl ref expr was not visited as part of a callExpr and is our
// target decl... emit a simple async let error.
//
// This occurs if we do:
//
// ```
// let x = ...
// async let y = x
// ```
if (declRef->getDecl() == targetDecl) {
foundTypeInfo.emitNamedAsyncLetCapture(captureLoc,
targetDecl->getBaseIdentifier(),
targetDeclIsolationInfo);
return Action::Continue(expr);
}
}
return Action::Continue(expr);
}
};
bool TransferNonTransferrableDiagnosticInferrer::run() {
// We need to find the isolation info.
auto *op = diagnosticEmitter.getOperand();
auto loc = op->getUser()->getLoc();
if (auto *sourceApply = loc.getAsASTNode<ApplyExpr>()) {
// First see if we have a transferring argument.
if (auto fas = FullApplySite::isa(op->getUser())) {
if (fas.getArgumentParameterInfo(*op).hasOption(
SILParameterInfo::Sending)) {
// Before we do anything, lets see if we are passing a sendable closure
// literal. If we do, we want to emit a special error that states which
// captured value caused the actual error.
if (initForSendingPartialApply(fas, op))
return true;
// See if we can infer a name from the value.
SmallString<64> resultingName;
if (auto varName = VariableNameInferrer::inferName(op->get())) {
diagnosticEmitter.emitNamedFunctionArgumentApplyStronglyTransferred(
loc, *varName);
return true;
}
Type type = op->get()->getType().getASTType();
if (auto *inferredArgExpr =
inferArgumentExprFromApplyExpr(sourceApply, fas, op)) {
type = inferredArgExpr->findOriginalType();
}
diagnosticEmitter.emitFunctionArgumentApplyStronglyTransferred(loc,
type);
return true;
}
}
// First try to get the apply from the isolation crossing.
auto isolation = sourceApply->getIsolationCrossing();
// If we could not infer an isolation...
if (!isolation) {
// Otherwise, emit a "we don't know error" that tells the user to file a
// bug.
diagnosticEmitter.emitUnknownPatternError();
return false;
}
assert(isolation && "Expected non-null");
// Then if we are calling a closure expr. If so, we should use the loc of
// the closure.
if (auto *closureExpr =
dyn_cast<AbstractClosureExpr>(sourceApply->getFn())) {
initForIsolatedPartialApply(op, closureExpr,
isolation->getCallerIsolation());
return true;
}
// See if we can infer a name from the value.
SmallString<64> resultingName;
if (auto name = VariableNameInferrer::inferName(op->get())) {
diagnosticEmitter.emitNamedIsolation(loc, *name, *isolation);
return true;
}
// Attempt to find the specific sugared ASTType if we can to emit a better
// diagnostic.
Type type = op->get()->getType().getASTType();
if (auto fas = FullApplySite::isa(op->getUser())) {
if (auto *inferredArgExpr =
inferArgumentExprFromApplyExpr(sourceApply, fas, op)) {
type = inferredArgExpr->findOriginalType();
}
}
diagnosticEmitter.emitFunctionArgumentApply(loc, type, *isolation);
return true;
}
if (auto *ace = loc.getAsASTNode<AbstractClosureExpr>()) {
if (ace->getActorIsolation().isActorIsolated()) {
if (initForIsolatedPartialApply(op, ace)) {
return true;
}
}
}
// See if we are in SIL and have an apply site specified isolation.
if (auto fas = FullApplySite::isa(op->getUser())) {
if (auto isolation = fas.getIsolationCrossing()) {
diagnosticEmitter.emitFunctionArgumentApply(
loc, op->get()->getType().getASTType(), *isolation);
return true;
}
}
if (auto *ri = dyn_cast<ReturnInst>(op->getUser())) {
auto fType = ri->getFunction()->getLoweredFunctionType();
if (fType->getNumResults() &&
fType->getResults()[0].hasOption(SILResultInfo::IsSending)) {
assert(llvm::all_of(fType->getResults(),
[](SILResultInfo resultInfo) {
return resultInfo.hasOption(
SILResultInfo::IsSending);
}) &&
"All result info must be the same... if that changes... update "
"this code!");
SmallString<64> resultingName;
if (auto name = VariableNameInferrer::inferName(op->get())) {
diagnosticEmitter.emitNamedTransferringReturn(loc, *name);
return true;
}
} else {
assert(llvm::none_of(fType->getResults(),
[](SILResultInfo resultInfo) {
return resultInfo.hasOption(
SILResultInfo::IsSending);
}) &&
"All result info must be the same... if that changes... update "
"this code!");
}
}
// If we are failing due to an autoclosure... see if we can find the captured
// value that is causing the issue.
if (auto *autoClosureExpr = loc.getAsASTNode<AutoClosureExpr>()) {
// To split up this work, we only do this for async let for now.
if (autoClosureExpr->getThunkKind() == AutoClosureExpr::Kind::AsyncLet) {
auto *i = op->getUser();
auto pai = ApplySite::isa(i);
unsigned captureIndex = pai.getAppliedArgIndex(*op);
auto captureInfo =
autoClosureExpr->getCaptureInfo().getCaptures()[captureIndex];
auto loc = RegularLocation(captureInfo.getLoc(), false /*implicit*/);
AutoClosureWalker walker(
diagnosticEmitter, captureInfo.getDecl(),
diagnosticEmitter.getIsolationRegionInfo().getIsolationInfo(), loc,
autoClosureExpr->getThunkKind() == AutoClosureExpr::Kind::AsyncLet);
autoClosureExpr->walk(walker);
return true;
}
}
diagnosticEmitter.emitUnknownUse(loc);
return true;
}
// Top level emission for transfer non transferable diagnostic.
void TransferNonSendableImpl::emitTransferredNonTransferrableDiagnostics() {
if (transferredNonTransferrableInfoList.empty())
return;
LLVM_DEBUG(
llvm::dbgs() << "Emitting transfer non transferrable diagnostics.\n");
for (auto info : transferredNonTransferrableInfoList) {
TransferNonTransferrableDiagnosticInferrer diagnosticInferrer(
regionInfo->getValueMap(), info);
diagnosticInferrer.run();
}
}
//===----------------------------------------------------------------------===//
// MARK: InOutSendingNotDisconnected Error Emitter
//===----------------------------------------------------------------------===//
namespace {
class InOutSendingNotDisconnectedDiagnosticEmitter {
InOutSendingNotDisconnectedInfo info;
bool emittedErrorDiagnostic = false;
public:
InOutSendingNotDisconnectedDiagnosticEmitter(
InOutSendingNotDisconnectedInfo info)
: info(info) {}
~InOutSendingNotDisconnectedDiagnosticEmitter() {
// If we were supposed to emit a diagnostic and didn't emit an unknown
// pattern error.
if (!emittedErrorDiagnostic)
emitUnknownPatternError();
}
std::optional<DiagnosticBehavior> getBehaviorLimit() const {
return getDiagnosticBehaviorLimitForValue(info.inoutSendingParam);
}
void emitUnknownPatternError() {
if (shouldAbortOnUnknownPatternMatchError()) {
llvm::report_fatal_error(
"RegionIsolation: Aborting on unknown pattern match error");
}
diagnoseError(info.functionExitingInst,
diag::regionbasedisolation_unknown_pattern)
.limitBehaviorIf(getBehaviorLimit());
}
void emit();
ASTContext &getASTContext() const {
return info.functionExitingInst->getFunction()->getASTContext();
}
template <typename... T, typename... U>
InFlightDiagnostic diagnoseError(SourceLoc loc, Diag<T...> diag,
U &&...args) {
emittedErrorDiagnostic = true;
return std::move(getASTContext()
.Diags.diagnose(loc, diag, std::forward<U>(args)...)
.warnUntilSwiftVersion(6));
}
template <typename... T, typename... U>
InFlightDiagnostic diagnoseError(SILLocation loc, Diag<T...> diag,
U &&...args) {
return diagnoseError(loc.getSourceLoc(), diag, std::forward<U>(args)...);
}
template <typename... T, typename... U>
InFlightDiagnostic diagnoseError(SILInstruction *inst, Diag<T...> diag,
U &&...args) {
return diagnoseError(inst->getLoc(), diag, std::forward<U>(args)...);
}
template <typename... T, typename... U>
InFlightDiagnostic diagnoseNote(SourceLoc loc, Diag<T...> diag, U &&...args) {
return getASTContext().Diags.diagnose(loc, diag, std::forward<U>(args)...);
}
template <typename... T, typename... U>
InFlightDiagnostic diagnoseNote(SILLocation loc, Diag<T...> diag,
U &&...args) {
return diagnoseNote(loc.getSourceLoc(), diag, std::forward<U>(args)...);
}
template <typename... T, typename... U>
InFlightDiagnostic diagnoseNote(SILInstruction *inst, Diag<T...> diag,
U &&...args) {
return diagnoseNote(inst->getLoc(), diag, std::forward<U>(args)...);
}
};
} // namespace
void InOutSendingNotDisconnectedDiagnosticEmitter::emit() {
// We should always be able to find a name for an inout sending param. If we
// do not, emit an unknown pattern error.
auto varName = VariableNameInferrer::inferName(info.inoutSendingParam);
if (!varName) {
return emitUnknownPatternError();
}
// Then emit the note with greater context.
SmallString<64> descriptiveKindStr;
{
llvm::raw_svector_ostream os(descriptiveKindStr);
info.actorIsolatedRegionInfo.printForDiagnostics(os);
os << ' ';
}
diagnoseError(
info.functionExitingInst,
diag::regionbasedisolation_inout_sending_cannot_be_actor_isolated,
*varName, descriptiveKindStr)
.limitBehaviorIf(getBehaviorLimit());
diagnoseNote(
info.functionExitingInst,
diag::regionbasedisolation_inout_sending_cannot_be_actor_isolated_note,
*varName, descriptiveKindStr);
}
void TransferNonSendableImpl::emitInOutSendingNotDisconnectedInfoList() {
for (auto &info : inoutSendingNotDisconnectedInfoList) {
InOutSendingNotDisconnectedDiagnosticEmitter emitter(info);
emitter.emit();
}
}
//===----------------------------------------------------------------------===//
// MARK: AssignTransferNonTransferrableIntoSendingResult
//===----------------------------------------------------------------------===//
namespace {
class AssignIsolatedIntoSendingResultDiagnosticEmitter {
AssignIsolatedIntoOutSendingParameterInfo info;
bool emittedErrorDiagnostic = false;
public:
AssignIsolatedIntoSendingResultDiagnosticEmitter(
AssignIsolatedIntoOutSendingParameterInfo info)
: info(info) {}
~AssignIsolatedIntoSendingResultDiagnosticEmitter() {
// If we were supposed to emit a diagnostic and didn't emit an unknown
// pattern error.
if (!emittedErrorDiagnostic)
emitUnknownPatternError();
}
std::optional<DiagnosticBehavior> getBehaviorLimit() const {
return getDiagnosticBehaviorLimitForValue(info.outSendingResult);
}
void emitUnknownPatternError() {
if (shouldAbortOnUnknownPatternMatchError()) {
llvm::report_fatal_error(
"RegionIsolation: Aborting on unknown pattern match error");
}
diagnoseError(info.srcOperand->getUser(),
diag::regionbasedisolation_unknown_pattern)
.limitBehaviorIf(getBehaviorLimit());
}
void emit();
ASTContext &getASTContext() const {
return info.srcOperand->getFunction()->getASTContext();
}
template <typename... T, typename... U>
InFlightDiagnostic diagnoseError(SourceLoc loc, Diag<T...> diag,
U &&...args) {
emittedErrorDiagnostic = true;
return std::move(getASTContext()
.Diags.diagnose(loc, diag, std::forward<U>(args)...)
.warnUntilSwiftVersion(6));
}
template <typename... T, typename... U>
InFlightDiagnostic diagnoseError(SILLocation loc, Diag<T...> diag,
U &&...args) {
return diagnoseError(loc.getSourceLoc(), diag, std::forward<U>(args)...);
}
template <typename... T, typename... U>
InFlightDiagnostic diagnoseError(SILInstruction *inst, Diag<T...> diag,
U &&...args) {
return diagnoseError(inst->getLoc(), diag, std::forward<U>(args)...);
}
template <typename... T, typename... U>
InFlightDiagnostic diagnoseError(Operand *op, Diag<T...> diag, U &&...args) {
return diagnoseError(op->getUser()->getLoc(), diag,
std::forward<U>(args)...);
}
template <typename... T, typename... U>
InFlightDiagnostic diagnoseNote(SourceLoc loc, Diag<T...> diag, U &&...args) {
return getASTContext().Diags.diagnose(loc, diag, std::forward<U>(args)...);
}
template <typename... T, typename... U>
InFlightDiagnostic diagnoseNote(SILLocation loc, Diag<T...> diag,
U &&...args) {
return diagnoseNote(loc.getSourceLoc(), diag, std::forward<U>(args)...);
}
template <typename... T, typename... U>
InFlightDiagnostic diagnoseNote(SILInstruction *inst, Diag<T...> diag,
U &&...args) {
return diagnoseNote(inst->getLoc(), diag, std::forward<U>(args)...);
}
template <typename... T, typename... U>
InFlightDiagnostic diagnoseNote(Operand *op, Diag<T...> diag, U &&...args) {
return diagnoseNote(op->getUser()->getLoc(), diag,
std::forward<U>(args)...);
}
};
} // namespace
/// Look through values looking for our out parameter. We want to tightly
/// control this to be conservative... so we handroll this.
static SILValue findOutParameter(SILValue v) {
while (true) {
SILValue temp = v;
if (auto *initOpt = dyn_cast<InitEnumDataAddrInst>(temp)) {
if (initOpt->getElement()->getParentEnum() ==
initOpt->getFunction()->getASTContext().getOptionalDecl()) {
temp = initOpt->getOperand();
}
}
if (temp == v) {
return v;
}
v = temp;
}
}
void AssignIsolatedIntoSendingResultDiagnosticEmitter::emit() {
// Then emit the note with greater context.
SmallString<64> descriptiveKindStr;
{
llvm::raw_svector_ostream os(descriptiveKindStr);
info.isolatedValueIsolationRegionInfo.printForDiagnostics(os);
}
// Grab the var name if we can find it.
if (auto varName = VariableNameInferrer::inferName(info.srcOperand->get())) {
// In general, when we do an assignment like this, we assume that srcOperand
// and our outSendingResult have the same type. This doesn't always happen
// though especially if our outSendingResult is used as an out parameter of
// a class_method. Check for such a case and if so, add to the end of our
// string a path component for that class_method.
if (info.srcOperand->get()->getType() != info.outSendingResult->getType()) {
if (auto fas = FullApplySite::isa(info.srcOperand->getUser())) {
if (fas.getSelfArgument() == info.srcOperand->get() &&
fas.getNumIndirectSILResults() == 1) {
// First check if our function argument is exactly our out parameter.
bool canEmit =
info.outSendingResult == fas.getIndirectSILResults()[0];
// If that fails, see if we are storing into a temporary
// alloc_stack. In such a case, find the root value that the temporary
// is initialized to and see if that is our target function
// argument. In such a case, we also want to add the decl name to our
// type.
if (!canEmit) {
canEmit = info.outSendingResult ==
findOutParameter(fas.getIndirectSILResults()[0]);
}
if (canEmit) {
if (auto *callee =
dyn_cast_or_null<MethodInst>(fas.getCalleeOrigin())) {
SmallString<64> resultingString;
resultingString.append(varName->str());
resultingString += '.';
resultingString += VariableNameInferrer::getNameFromDecl(
callee->getMember().getDecl());
varName = fas->getFunction()->getASTContext().getIdentifier(
resultingString);
}
}
}
}
}
diagnoseError(
info.srcOperand,
diag::regionbasedisolation_out_sending_cannot_be_actor_isolated_named,
*varName, descriptiveKindStr)
.limitBehaviorIf(getBehaviorLimit());
diagnoseNote(
info.srcOperand,
diag::
regionbasedisolation_out_sending_cannot_be_actor_isolated_note_named,
*varName, descriptiveKindStr);
return;
}
Type type = info.nonTransferrableValue->getType().getASTType();
diagnoseError(
info.srcOperand,
diag::regionbasedisolation_out_sending_cannot_be_actor_isolated_type,
type, descriptiveKindStr)
.limitBehaviorIf(getBehaviorLimit());
diagnoseNote(
info.srcOperand,
diag::regionbasedisolation_out_sending_cannot_be_actor_isolated_note_type,
type, descriptiveKindStr);
diagnoseNote(info.srcOperand, diag::regionbasedisolation_type_is_non_sendable,
type);
}
void TransferNonSendableImpl::emitAssignIsolatedIntoSendingResultDiagnostics() {
for (auto &info : assignIsolatedIntoOutSendingParameterInfoList) {
AssignIsolatedIntoSendingResultDiagnosticEmitter emitter(info);
emitter.emit();
}
}
//===----------------------------------------------------------------------===//
// MARK: Diagnostic Evaluator
//===----------------------------------------------------------------------===//
namespace {
struct DiagnosticEvaluator final
: PartitionOpEvaluatorBaseImpl<DiagnosticEvaluator> {
RegionAnalysisFunctionInfo *info;
SmallFrozenMultiMap<Operand *, RequireInst, 8>
&transferOpToRequireInstMultiMap;
/// First value is the operand that was transferred... second value is the
/// non-transferrable value in the same region as that value. The second value
/// is what is non-transferrable.
SmallVectorImpl<TransferredNonTransferrableInfo> &transferredNonTransferrable;
/// A list of state that tracks specific 'inout sending' parameters that were
/// actor isolated on function exit with the necessary state to emit the
/// error.
SmallVectorImpl<InOutSendingNotDisconnectedInfo>
&inoutSendingNotDisconnectedInfoList;
/// A list of state that tracks specific 'inout sending' parameters that were
/// actor isolated on function exit with the necessary state to emit the
/// error.
SmallVectorImpl<AssignIsolatedIntoOutSendingParameterInfo>
&assignIsolatedIntoOutSendingParameterInfoList;
DiagnosticEvaluator(Partition &workingPartition,
RegionAnalysisFunctionInfo *info,
SmallFrozenMultiMap<Operand *, RequireInst, 8>
&transferOpToRequireInstMultiMap,
SmallVectorImpl<TransferredNonTransferrableInfo>
&transferredNonTransferrable,
SmallVectorImpl<InOutSendingNotDisconnectedInfo>
&inoutSendingNotDisconnectedInfoList,
SmallVectorImpl<AssignIsolatedIntoOutSendingParameterInfo>
&assignIsolatedIntoOutSendingParameterInfo,
TransferringOperandToStateMap &operandToStateMap)
: PartitionOpEvaluatorBaseImpl(
workingPartition, info->getOperandSetFactory(), operandToStateMap),
info(info),
transferOpToRequireInstMultiMap(transferOpToRequireInstMultiMap),
transferredNonTransferrable(transferredNonTransferrable),
inoutSendingNotDisconnectedInfoList(
inoutSendingNotDisconnectedInfoList),
assignIsolatedIntoOutSendingParameterInfoList(
assignIsolatedIntoOutSendingParameterInfo) {}
void handleLocalUseAfterTransfer(const PartitionOp &partitionOp,
Element transferredVal,
Operand *transferringOp) const {
auto &operandState = operandToStateMap.get(transferringOp);
// Ignore this if we have a gep like instruction that is returning a
// sendable type and transferringOp was not set with closure
// capture.
if (auto *svi =
dyn_cast<SingleValueInstruction>(partitionOp.getSourceInst())) {
if (isa<TupleElementAddrInst, StructElementAddrInst>(svi) &&
!SILIsolationInfo::isNonSendableType(svi->getType(),
svi->getFunction())) {
bool isCapture = operandState.isClosureCaptured;
if (!isCapture) {
return;
}
}
}
auto rep = info->getValueMap().getRepresentative(transferredVal);
LLVM_DEBUG(llvm::dbgs()
<< " Emitting Use After Transfer Error!\n"
<< " Transferring Inst: " << *transferringOp->getUser()
<< " Transferring Op Value: " << transferringOp->get()
<< " Require Inst: " << *partitionOp.getSourceInst()
<< " ID: %%" << transferredVal << "\n"
<< " Rep: " << *rep << " Transferring Op Num: "
<< transferringOp->getOperandNumber() << '\n');
transferOpToRequireInstMultiMap.insert(
transferringOp,
RequireInst::forUseAfterTransfer(partitionOp.getSourceInst()));
}
void handleTransferNonTransferrable(
const PartitionOp &partitionOp, Element transferredVal,
SILDynamicMergedIsolationInfo isolationRegionInfo) const {
LLVM_DEBUG(llvm::dbgs()
<< " Emitting TransferNonTransferrable Error!\n"
<< " ID: %%" << transferredVal << "\n"
<< " Rep: "
<< *info->getValueMap().getRepresentative(transferredVal)
<< " Dynamic Isolation Region: ";
isolationRegionInfo.printForDiagnostics(llvm::dbgs());
llvm::dbgs() << '\n');
auto *self = const_cast<DiagnosticEvaluator *>(this);
auto nonTransferrableValue =
info->getValueMap().getRepresentative(transferredVal);
self->transferredNonTransferrable.emplace_back(
partitionOp.getSourceOp(), nonTransferrableValue, isolationRegionInfo);
}
void handleInOutSendingNotDisconnectedAtExitError(
const PartitionOp &partitionOp, Element inoutSendingVal,
SILDynamicMergedIsolationInfo isolationRegionInfo) const {
LLVM_DEBUG(llvm::dbgs()
<< " Emitting InOut Sending ActorIsolated at end of "
"Function Error!\n"
<< " ID: %%" << inoutSendingVal << "\n"
<< " Rep: "
<< *info->getValueMap().getRepresentative(inoutSendingVal)
<< " Dynamic Isolation Region: ";
isolationRegionInfo.printForDiagnostics(llvm::dbgs());
llvm::dbgs() << '\n');
auto *self = const_cast<DiagnosticEvaluator *>(this);
auto nonTransferrableValue =
info->getValueMap().getRepresentative(inoutSendingVal);
self->inoutSendingNotDisconnectedInfoList.emplace_back(
partitionOp.getSourceInst(), nonTransferrableValue,
isolationRegionInfo);
}
void handleTransferNonTransferrable(
const PartitionOp &partitionOp, Element transferredVal,
Element actualNonTransferrableValue,
SILDynamicMergedIsolationInfo isolationRegionInfo) const {
LLVM_DEBUG(llvm::dbgs()
<< " Emitting TransferNonTransferrable Error!\n"
<< " ID: %%" << transferredVal << "\n"
<< " Rep: "
<< *info->getValueMap().getRepresentative(transferredVal)
<< " Dynamic Isolation Region: ";
isolationRegionInfo.printForDiagnostics(llvm::dbgs());
llvm::dbgs() << '\n');
auto *self = const_cast<DiagnosticEvaluator *>(this);
// If we have a non-actor introducing fake representative value, just use
// the value that actually introduced the actor isolation.
if (auto nonTransferrableValue = info->getValueMap().maybeGetRepresentative(
actualNonTransferrableValue)) {
LLVM_DEBUG(llvm::dbgs()
<< " ActualTransfer: " << nonTransferrableValue);
self->transferredNonTransferrable.emplace_back(partitionOp.getSourceOp(),
nonTransferrableValue,
isolationRegionInfo);
} else if (auto *nonTransferrableInst =
info->getValueMap().maybeGetActorIntroducingInst(
actualNonTransferrableValue)) {
LLVM_DEBUG(llvm::dbgs()
<< " ActualTransfer: " << *nonTransferrableInst);
self->transferredNonTransferrable.emplace_back(
partitionOp.getSourceOp(), nonTransferrableInst, isolationRegionInfo);
} else {
// Otherwise, just use the actual value.
//
// TODO: We are eventually going to want to be able to say that it is b/c
// of the actor isolated parameter. Maybe we should put in the actual
// region isolation info here.
self->transferredNonTransferrable.emplace_back(
partitionOp.getSourceOp(),
info->getValueMap().getRepresentative(transferredVal),
isolationRegionInfo);
}
}
void handleAssignTransferNonTransferrableIntoSendingResult(
const PartitionOp &partitionOp, Element destElement,
SILFunctionArgument *destValue, Element srcElement, SILValue srcValue,
SILDynamicMergedIsolationInfo srcIsolationRegionInfo) const {
auto srcRep = info->getValueMap().getRepresentativeValue(srcElement);
LLVM_DEBUG(
llvm::dbgs()
<< " Emitting Error! Kind: Assign Isolated Into Sending Result!\n"
<< " Assign Inst: " << *partitionOp.getSourceInst()
<< " Dest Value: " << *destValue
<< " Dest Element: " << destElement << '\n'
<< " Src Value: " << srcValue
<< " Src Element: " << srcElement << '\n'
<< " Src Rep: " << srcRep
<< " Src Isolation: " << srcIsolationRegionInfo << '\n');
assignIsolatedIntoOutSendingParameterInfoList.emplace_back(
partitionOp.getSourceOp(), destValue, srcValue, srcIsolationRegionInfo);
}
void
handleInOutSendingNotInitializedAtExitError(const PartitionOp &partitionOp,
Element inoutSendingVal,
Operand *transferringOp) const {
auto rep = info->getValueMap().getRepresentative(inoutSendingVal);
LLVM_DEBUG(llvm::dbgs()
<< " Emitting InOut Not Reinitialized At End Of Function!\n"
<< " Transferring Inst: " << *transferringOp->getUser()
<< " Transferring Op Value: " << transferringOp->get()
<< " Require Inst: " << *partitionOp.getSourceInst()
<< " ID: %%" << inoutSendingVal << "\n"
<< " Rep: " << *rep << " Transferring Op Num: "
<< transferringOp->getOperandNumber() << '\n');
transferOpToRequireInstMultiMap.insert(
transferringOp, RequireInst::forInOutReinitializationNeeded(
partitionOp.getSourceInst()));
}
void handleUnknownCodePattern(const PartitionOp &op) const {
if (shouldAbortOnUnknownPatternMatchError()) {
llvm::report_fatal_error(
"RegionIsolation: Aborting on unknown pattern match error");
}
diagnoseError(op.getSourceInst(),
diag::regionbasedisolation_unknown_pattern);
}
bool isActorDerived(Element element) const {
return info->getValueMap().getIsolationRegion(element).isActorIsolated();
}
bool isTaskIsolatedDerived(Element element) const {
return info->getValueMap().getIsolationRegion(element).isTaskIsolated();
}
SILIsolationInfo::Kind hasSpecialDerivation(Element element) const {
return info->getValueMap().getIsolationRegion(element).getKind();
}
SILIsolationInfo getIsolationRegionInfo(Element element) const {
return info->getValueMap().getIsolationRegion(element);
}
std::optional<Element> getElement(SILValue value) const {
return info->getValueMap().getTrackableValue(value).getID();
}
SILValue getRepresentative(SILValue value) const {
return info->getValueMap()
.getTrackableValue(value)
.getRepresentative()
.maybeGetValue();
}
RepresentativeValue getRepresentativeValue(Element element) const {
return info->getValueMap().getRepresentativeValue(element);
}
bool isClosureCaptured(Element element, Operand *op) const {
auto value = info->getValueMap().maybeGetRepresentative(element);
if (!value)
return false;
return info->isClosureCaptured(value, op);
}
};
} // namespace
void TransferNonSendableImpl::runDiagnosticEvaluator() {
// Then for each block...
LLVM_DEBUG(llvm::dbgs() << "Walking blocks for diagnostics.\n");
for (auto [block, blockState] : regionInfo->getRange()) {
LLVM_DEBUG(llvm::dbgs() << "|--> Block bb" << block.getDebugID() << "\n");
if (!blockState.getLiveness()) {
LLVM_DEBUG(llvm::dbgs() << "Dead block... skipping!\n");
continue;
}
LLVM_DEBUG(llvm::dbgs() << "Entry Partition: ";
blockState.getEntryPartition().print(llvm::dbgs()));
// Grab its entry partition and setup an evaluator for the partition that
// has callbacks that emit diagnsotics...
Partition workingPartition = blockState.getEntryPartition();
DiagnosticEvaluator eval(workingPartition, regionInfo,
transferOpToRequireInstMultiMap,
transferredNonTransferrableInfoList,
inoutSendingNotDisconnectedInfoList,
assignIsolatedIntoOutSendingParameterInfoList,
regionInfo->getTransferringOpToStateMap());
// And then evaluate all of our partition ops on the entry partition.
for (auto &partitionOp : blockState.getPartitionOps()) {
eval.apply(partitionOp);
}
LLVM_DEBUG(llvm::dbgs() << "Exit Partition: ";
workingPartition.print(llvm::dbgs()));
}
LLVM_DEBUG(llvm::dbgs() << "Finished walking blocks for diagnostics.\n");
// Now that we have found all of our transferInsts/Requires emit errors.
transferOpToRequireInstMultiMap.setFrozen();
}
//===----------------------------------------------------------------------===//
// MARK: Top Level Entrypoint
//===----------------------------------------------------------------------===//
/// Once we have reached a fixpoint, this routine runs over all blocks again
/// reporting any failures by applying our ops to the converged dataflow
/// state.
void TransferNonSendableImpl::emitDiagnostics() {
auto *function = regionInfo->getFunction();
LLVM_DEBUG(llvm::dbgs() << "Emitting diagnostics for function "
<< function->getName() << "\n");
runDiagnosticEvaluator();
emitTransferredNonTransferrableDiagnostics();
emitUseAfterTransferDiagnostics();
emitInOutSendingNotDisconnectedInfoList();
emitAssignIsolatedIntoSendingResultDiagnostics();
}
namespace {
class TransferNonSendable : public SILFunctionTransform {
void run() override {
SILFunction *function = getFunction();
auto *functionInfo = getAnalysis<RegionAnalysis>()->get(function);
if (!functionInfo->isSupportedFunction()) {
LLVM_DEBUG(llvm::dbgs() << "===> SKIPPING UNSUPPORTED FUNCTION: "
<< function->getName() << '\n');
return;
}
LLVM_DEBUG(llvm::dbgs()
<< "===> PROCESSING: " << function->getName() << '\n');
TransferNonSendableImpl impl(functionInfo);
impl.emitDiagnostics();
}
};
} // end anonymous namespace
SILTransform *swift::createTransferNonSendable() {
return new TransferNonSendable();
}
|