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
|
//===--- OwnershipUtils.cpp -----------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 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
//
//===----------------------------------------------------------------------===//
#include "swift/SIL/OwnershipUtils.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/GraphNodeWorklist.h"
#include "swift/Basic/SmallPtrSetVector.h"
#include "swift/SIL/InstructionUtils.h"
#include "swift/SIL/LinearLifetimeChecker.h"
#include "swift/SIL/MemAccessUtils.h"
#include "swift/SIL/Projection.h"
#include "swift/SIL/PrunedLiveness.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/Test.h"
using namespace swift;
bool swift::findPointerEscape(SILValue original) {
if (original->getOwnershipKind() != OwnershipKind::Owned &&
original->getOwnershipKind() != OwnershipKind::Guaranteed) {
return false;
}
ValueWorklist worklist(original->getFunction());
worklist.push(original);
if (auto *phi = SILArgument::asPhi(original)) {
phi->visitTransitiveIncomingPhiOperands([&](auto *phi, auto *operand) {
worklist.pushIfNotVisited(operand->get());
return true;
});
}
while (auto value = worklist.pop()) {
for (auto use : value->getUses()) {
switch (use->getOperandOwnership()) {
case OperandOwnership::PointerEscape:
case OperandOwnership::ForwardingUnowned:
return true;
case OperandOwnership::ForwardingConsume: {
auto *branch = dyn_cast<BranchInst>(use->getUser());
if (!branch) {
// Non-phi forwarding consumes end the lifetime of an owned value.
break;
}
auto *phi = branch->getDestBB()->getArgument(use->getOperandNumber());
worklist.pushIfNotVisited(phi);
break;
}
case OperandOwnership::Borrow: {
auto borrowOp = BorrowingOperand(use);
if (auto borrowValue = borrowOp.getBorrowIntroducingUserResult()) {
worklist.pushIfNotVisited(borrowValue.value);
}
break;
}
case OperandOwnership::Reborrow: {
SILArgument *phi = PhiOperand(use).getValue();
worklist.pushIfNotVisited(phi);
break;
}
case OperandOwnership::GuaranteedForwarding: {
// This may follow guaranteed phis.
ForwardingOperand(use).visitForwardedValues([&](SILValue result) {
// Do not include transitive uses with 'none' ownership
if (result->getOwnershipKind() == OwnershipKind::None)
return true;
worklist.pushIfNotVisited(result);
return true;
});
break;
}
case OperandOwnership::InteriorPointer: {
if (InteriorPointerOperand(use).findTransitiveUses() !=
AddressUseKind::NonEscaping) {
return true;
}
break;
}
default:
break;
}
}
}
return false;
}
namespace swift::test {
// Arguments:
// - value: the value to check for escaping
// Dumps:
// - the value
// - whether it has a pointer escape
static FunctionTest OwnershipUtilsHasPointerEscape(
"has-pointer-escape", [](auto &function, auto &arguments, auto &test) {
auto value = arguments.takeValue();
auto has = findPointerEscape(value);
value->print(llvm::outs());
auto *boolString = has ? "true" : "false";
llvm::outs() << boolString << "\n";
});
} // end namespace swift::test
bool swift::canOpcodeForwardInnerGuaranteedValues(SILValue value) {
if (auto *inst = value->getDefiningInstructionOrTerminator()) {
if (auto fwdOp = ForwardingOperation(inst)) {
return fwdOp.preservesOwnership() &&
!fwdOp.canForwardOwnedCompatibleValuesOnly();
}
}
return false;
}
bool swift::canOpcodeForwardInnerGuaranteedValues(Operand *use) {
if (auto fwdOp = ForwardingOperation(use->getUser()))
return fwdOp.preservesOwnership() &&
!fwdOp.canForwardOwnedCompatibleValuesOnly();
return false;
}
bool swift::canOpcodeForwardOwnedValues(SILValue value) {
if (auto *inst = value->getDefiningInstructionOrTerminator()) {
if (auto fwdOp = ForwardingOperation(inst)) {
return fwdOp.preservesOwnership() &&
!fwdOp.canForwardGuaranteedCompatibleValuesOnly();
}
}
return false;
}
bool swift::canOpcodeForwardOwnedValues(Operand *use) {
if (auto fwdOp = ForwardingOperation(use->getUser()))
return fwdOp.preservesOwnership() &&
!fwdOp.canForwardGuaranteedCompatibleValuesOnly();
return false;
}
bool swift::computeIsReborrow(SILArgument *arg) {
if (arg->getOwnershipKind() != OwnershipKind::Guaranteed) {
return false;
}
if (isa<SILFunctionArgument>(arg)) {
return false;
}
return !computeIsGuaranteedForwarding(arg);
}
bool swift::computeIsScoped(SILArgument *arg) {
if (arg->getOwnershipKind() == OwnershipKind::Owned) {
return true;
}
return computeIsReborrow(arg);
}
// This is the use-def equivalent of use->getOperandOwnership() ==
// OperandOwnership::GuaranteedForwarding.
bool swift::computeIsGuaranteedForwarding(SILValue value) {
if (value->getOwnershipKind() != OwnershipKind::Guaranteed) {
return false;
}
// NOTE: canOpcodeForwardInnerGuaranteedValues returns true for transformation
// terminator results.
if (canOpcodeForwardInnerGuaranteedValues(value) ||
isa<SILFunctionArgument>(value)) {
return true;
}
// If not a phi, return false
auto *phi = dyn_cast<SILPhiArgument>(value);
if (!phi || !phi->isPhi()) {
return false;
}
// For a phi, if we find GuaranteedForwarding phi operand on any incoming
// path, we return true. Additional verification is added to ensure
// GuaranteedForwarding phi operands are found on zero or all paths in the
// OwnershipVerifier.
bool isGuaranteedForwardingPhi = false;
phi->visitTransitiveIncomingPhiOperands([&](auto *, auto *op) -> bool {
auto opValue = op->get();
assert(opValue->getOwnershipKind().isCompatibleWith(
OwnershipKind::Guaranteed));
if (canOpcodeForwardInnerGuaranteedValues(opValue) ||
isa<SILFunctionArgument>(opValue)) {
isGuaranteedForwardingPhi = true;
return false;
}
auto *phi = dyn_cast<SILPhiArgument>(opValue);
if (!phi || !phi->isPhi()) {
return false;
}
return true;
});
return isGuaranteedForwardingPhi;
}
//===----------------------------------------------------------------------===//
// Guaranteed Use-Point (Lifetime) Discovery
//===----------------------------------------------------------------------===//
// Find all use points of \p guaranteedValue within its borrow scope. All uses
// are naturally dominated by \p guaranteedValue. If a PointerEscape is found,
// then no assumption can be made about \p guaranteedValue's lifetime. Therefore
// the use points are incomplete and this returns false. The escape point that
// was found must still be in \p usePoints to distinguish from dead addresses.
//
// Accumulate results in \p usePoints, ignoring existing elements.
//
// Skip over nested borrow scopes. Their scope-ending instructions are their use
// points. Transitively find all nested scope-ending instructions by looking
// through nested reborrows. Nested reborrows are not use points.
//
// FIXME: handle inner reborrows, which aren't dominated by
// guaranteedValue. Audit all users to handle reborrows.
//
// TODO: Replace this with OwnershipUseVisitor.
bool swift::findInnerTransitiveGuaranteedUses(
SILValue guaranteedValue, SmallVectorImpl<Operand *> *usePoints) {
bool foundPointerEscape = false;
auto leafUse = [&](Operand *use) {
if (usePoints && use->getOperandOwnership() != OperandOwnership::NonUse) {
usePoints->push_back(use);
}
return true;
};
// Push the value's immediate uses.
//
// TODO: The worklist can be a simple vector without any a membership check if
// destructures are changed to be represented as reborrows. Currently a
// destructure forwards multiple results! This means that the worklist could
// grow exponentially without the membership check. It's fine to do this
// membership check locally in this function (within a borrow scope) because
// it isn't needed for the immediate uses, only the transitive uses.
GraphNodeWorklist<Operand *, 8> worklist;
for (Operand *use : guaranteedValue->getUses()) {
if (use->getOperandOwnership() != OperandOwnership::NonUse)
worklist.insert(use);
}
// --- Transitively follow forwarded uses and look for escapes.
// usePoints grows in this loop.
while (Operand *use = worklist.pop()) {
switch (use->getOperandOwnership()) {
case OperandOwnership::NonUse:
case OperandOwnership::TrivialUse:
case OperandOwnership::ForwardingConsume:
case OperandOwnership::DestroyingConsume:
llvm_unreachable("this operand cannot handle an inner guaranteed use");
case OperandOwnership::ForwardingUnowned:
case OperandOwnership::PointerEscape:
leafUse(use);
foundPointerEscape = true;
break;
case OperandOwnership::InstantaneousUse:
case OperandOwnership::UnownedInstantaneousUse:
case OperandOwnership::BitwiseEscape:
// Reborrow only happens when this is called on a value that creates a
// borrow scope.
case OperandOwnership::Reborrow:
// EndBorrow either happens when this is called on a value that creates a
// borrow scope, or when it is pushed as a use when processing a nested
// borrow.
case OperandOwnership::EndBorrow:
leafUse(use);
break;
case OperandOwnership::InteriorPointer:
#if 0 // FIXME!!! Enable in a following commit that fixes RAUW
// If our base guaranteed value does not have any consuming uses
// (consider function arguments), we need to be sure to include interior
// pointer operands since we may not get a use from a end_scope
// instruction.
if (InteriorPointerOperand(use).findTransitiveUses(usePoints)
!= AddressUseKind::NonEscaping) {
foundPointerEscape = true;
}
#endif
leafUse(use);
foundPointerEscape = true;
break;
case OperandOwnership::GuaranteedForwarding: {
bool nonLeaf = false;
ForwardingOperand(use).visitForwardedValues([&](SILValue result) {
// Do not include transitive uses with 'none' ownership
if (result->getOwnershipKind() == OwnershipKind::None)
return true;
// Bailout on guaranteed phis because the caller may assume dominance.
if (SILArgument::asPhi(result)) {
leafUse(use);
foundPointerEscape = true;
return true;
}
for (auto *resultUse : result->getUses()) {
if (resultUse->getOperandOwnership() != OperandOwnership::NonUse) {
nonLeaf = true;
worklist.insert(resultUse);
}
}
return true;
});
// e.g. A dead forwarded value, e.g. a switch_enum with only trivial uses,
// must itself be a leaf use.
if (!nonLeaf) {
leafUse(use);
}
break;
}
case OperandOwnership::Borrow:
// FIXME: Use visitExtendedScopeEndingUses and audit all clients to handle
// reborrows.
//
// FIXME: visit[Extended]ScopeEndingUses can't return false here once dead
// borrows are disallowed.
if (!BorrowingOperand(use).visitScopeEndingUses(
[&](Operand *endUse) {
if (endUse->getOperandOwnership() == OperandOwnership::Reborrow) {
foundPointerEscape = true;
}
leafUse(endUse);
return true;
},
[&](Operand *unknownUse) {
foundPointerEscape = true;
leafUse(unknownUse);
return true;
})) {
// Special case for dead borrows. This is dangerous because clients
// don't expect a begin_borrow to be in the use list.
leafUse(use);
}
break;
}
}
return !foundPointerEscape;
}
/// Find all uses in the extended lifetime (i.e. including copies) of a simple
/// (i.e. not reborrowed) borrow scope and its transitive uses.
bool swift::findExtendedUsesOfSimpleBorrowedValue(
BorrowedValue borrowedValue, SmallVectorImpl<Operand *> *usePoints) {
auto recordUse = [&](Operand *use) {
if (usePoints && use->getOperandOwnership() != OperandOwnership::NonUse) {
usePoints->push_back(use);
}
};
// Push the value's immediate uses.
//
// TODO: The worklist can be a simple vector without any a membership check if
// destructures are changed to be represented as reborrows. Currently a
// destructure forwards multiple results! This means that the worklist could
// grow exponentially without the membership check. It's fine to do this
// membership check locally in this function (within a borrow scope) because
// it isn't needed for the immediate uses, only the transitive uses.
GraphNodeWorklist<Operand *, 8> worklist;
auto addUsesToWorklist = [&worklist](SILValue value) {
for (Operand *use : value->getUses()) {
if (use->getOperandOwnership() != OperandOwnership::NonUse)
worklist.insert(use);
}
};
addUsesToWorklist(borrowedValue.value);
// --- Transitively follow forwarded uses and look for escapes.
// usePoints grows in this loop.
while (Operand *use = worklist.pop()) {
if (auto *cvi = dyn_cast<CopyValueInst>(use->getUser())) {
addUsesToWorklist(cvi);
}
switch (use->getOperandOwnership()) {
case OperandOwnership::NonUse:
break;
case OperandOwnership::TrivialUse:
case OperandOwnership::ForwardingConsume:
case OperandOwnership::DestroyingConsume:
recordUse(use);
break;
case OperandOwnership::ForwardingUnowned:
case OperandOwnership::PointerEscape:
case OperandOwnership::Reborrow:
return false;
case OperandOwnership::InstantaneousUse:
case OperandOwnership::UnownedInstantaneousUse:
case OperandOwnership::BitwiseEscape:
// EndBorrow either happens when this is called on a value that creates a
// borrow scope, or when it is pushed as a use when processing a nested
// borrow.
case OperandOwnership::EndBorrow:
recordUse(use);
break;
case OperandOwnership::InteriorPointer:
if (InteriorPointerOperandKind::get(use) ==
InteriorPointerOperandKind::Invalid)
return false;
// If our base guaranteed value does not have any consuming uses (consider
// function arguments), we need to be sure to include interior pointer
// operands since we may not get a use from a end_scope instruction.
if (InteriorPointerOperand(use).findTransitiveUses(usePoints) !=
AddressUseKind::NonEscaping) {
return false;
}
recordUse(use);
break;
case OperandOwnership::GuaranteedForwarding: {
// Conservatively assume that a forwarding phi is not dominated by the
// initial borrowed value and bailout.
if (PhiOperand(use)) {
return false;
}
ForwardingOperand(use).visitForwardedValues([&](SILValue result) {
// Do not include transitive uses with 'none' ownership
if (result->getOwnershipKind() == OwnershipKind::None)
return true;
for (auto *resultUse : result->getUses()) {
if (resultUse->getOperandOwnership() != OperandOwnership::NonUse) {
worklist.insert(resultUse);
}
}
return true;
});
recordUse(use);
break;
}
case OperandOwnership::Borrow:
if (!BorrowingOperand(use).visitExtendedScopeEndingUses(
[&](Operand *endUse) {
recordUse(endUse);
return true;
})) {
return false;
}
break;
}
}
return true;
}
// TODO: refactor this with SSAPrunedLiveness::computeLiveness.
bool swift::findUsesOfSimpleValue(SILValue value,
SmallVectorImpl<Operand *> *usePoints) {
for (auto *use : value->getUses()) {
switch (use->getOperandOwnership()) {
case OperandOwnership::PointerEscape:
return false;
case OperandOwnership::Borrow:
if (!BorrowingOperand(use).visitScopeEndingUses([&](Operand *end) {
if (end->getOperandOwnership() == OperandOwnership::Reborrow) {
return false;
}
usePoints->push_back(end);
return true;
})) {
return false;
}
break;
default:
break;
}
usePoints->push_back(use);
}
return true;
}
bool swift::visitGuaranteedForwardingPhisForSSAValue(
SILValue value, function_ref<bool(Operand *)> visitor) {
assert(isa<BeginBorrowInst>(value) || isa<LoadBorrowInst>(value) ||
(isa<SILPhiArgument>(value) &&
value->getOwnershipKind() == OwnershipKind::Guaranteed));
// guaranteedForwardingOps is a collection of all transitive
// GuaranteedForwarding uses of \p value. It is a set, to avoid repeated
// processing of structs and tuples which are GuaranteedForwarding.
llvm::SmallSetVector<Operand *, 4> guaranteedForwardingOps;
// Collect first-level GuaranteedForwarding uses, and call the visitor on any
// GuaranteedForwardingPhi uses.
for (auto *use : value->getUses()) {
if (use->getOperandOwnership() == OperandOwnership::GuaranteedForwarding) {
if (PhiOperand(use)) {
if (!visitor(use)) {
return false;
}
}
guaranteedForwardingOps.insert(use);
}
}
// Transitively, collect GuaranteedForwarding uses.
for (unsigned i = 0; i < guaranteedForwardingOps.size(); i++) {
for (auto val : guaranteedForwardingOps[i]->getUser()->getResults()) {
for (auto *valUse : val->getUses()) {
if (valUse->getOperandOwnership() ==
OperandOwnership::GuaranteedForwarding) {
if (PhiOperand(valUse)) {
if (!visitor(valUse)) {
return false;
}
}
guaranteedForwardingOps.insert(valUse);
}
}
}
}
return true;
}
// Find all use points of \p guaranteedValue within its borrow scope. All use
// points will be dominated by \p guaranteedValue.
//
// Record (non-nested) reborrows as uses.
//
// BorrowedValues (which introduce a borrow scope) are fundamentally different
// than "inner" guaranteed values. Their only use points are their scope-ending
// uses. There is no need to transitively process uses. However, unlike inner
// guaranteed values, they can have reborrows. To transitively process
// reborrows, use findExtendedTransitiveBorrowedUses.
bool swift::findTransitiveGuaranteedUses(
SILValue guaranteedValue, SmallVectorImpl<Operand *> &usePoints,
function_ref<void(Operand *)> visitReborrow) {
// Handle local borrow introducers without following uses.
// SILFunctionArguments are *not* borrow introducers in this context--we're
// trying to find lifetime of values within a function.
if (auto borrowedValue = BorrowedValue(guaranteedValue)) {
if (borrowedValue.isLocalScope()) {
borrowedValue.visitLocalScopeEndingUses([&](Operand *scopeEnd) {
// Initially push the reborrow as a use point. visitReborrow may pop it
// if it only wants to compute the extended lifetime's use points.
usePoints.push_back(scopeEnd);
if (scopeEnd->getOperandOwnership() == OperandOwnership::Reborrow)
visitReborrow(scopeEnd);
return true;
});
}
return true;
}
return findInnerTransitiveGuaranteedUses(guaranteedValue, &usePoints);
}
// Find all use points of \p guaranteedValue within its borrow scope. If the
// guaranteed value introduces a borrow scope, then this includes the extended
// borrow scope by following reborrows.
bool swift::
findExtendedTransitiveGuaranteedUses(SILValue guaranteedValue,
SmallVectorImpl<Operand *> &usePoints) {
// Multiple paths may reach the same reborrows, and reborrow may even be
// recursive, so the working set requires a membership check.
SmallPtrSetVector<SILValue, 4> reborrows;
auto visitReborrow = [&](Operand *reborrow) {
// Pop the reborrow. It should not appear in the use points of the
// extend lifetime.
assert(reborrow == usePoints.back());
usePoints.pop_back();
auto borrowedPhi =
BorrowingOperand(reborrow).getBorrowIntroducingUserResult();
reborrows.insert(borrowedPhi.value);
};
if (!findTransitiveGuaranteedUses(guaranteedValue, usePoints, visitReborrow))
return false;
// For guaranteed values that do not introduce a borrow scope, reborrows will
// be empty at this point.
for (unsigned idx = 0; idx < reborrows.size(); ++idx) {
bool result =
findTransitiveGuaranteedUses(reborrows[idx], usePoints, visitReborrow);
// It is impossible to find a Pointer escape while traversing reborrows.
assert(result && "visiting reborrows always succeeds");
(void)result;
}
return true;
}
//===----------------------------------------------------------------------===//
// Borrowing Operand
//===----------------------------------------------------------------------===//
void BorrowingOperandKind::print(llvm::raw_ostream &os) const {
switch (value) {
case Kind::Invalid:
llvm_unreachable("Using an unreachable?!");
case Kind::BeginBorrow:
os << "BeginBorrow";
return;
case Kind::StoreBorrow:
os << "StoreBorrow";
return;
case Kind::BeginApply:
os << "BeginApply";
return;
case Kind::Branch:
os << "Branch";
return;
case Kind::Apply:
os << "Apply";
return;
case Kind::TryApply:
os << "TryApply";
return;
case Kind::Yield:
os << "Yield";
return;
case Kind::PartialApplyStack:
os << "PartialApply [stack]";
return;
case Kind::MarkDependenceNonEscaping:
os << "MarkDependence [nonescaping]";
return;
case Kind::BeginAsyncLet:
os << "BeginAsyncLet";
return;
}
llvm_unreachable("Covered switch isn't covered?!");
}
llvm::raw_ostream &swift::operator<<(llvm::raw_ostream &os,
BorrowingOperandKind kind) {
kind.print(os);
return os;
}
void BorrowingOperand::print(llvm::raw_ostream &os) const {
os << "BorrowScopeOperand:\n"
"Kind: " << kind << "\n"
"Value: " << op->get()
<< "User: " << *op->getUser();
}
llvm::raw_ostream &swift::operator<<(llvm::raw_ostream &os,
const BorrowingOperand &operand) {
operand.print(os);
return os;
}
bool BorrowingOperand::hasEmptyRequiredEndingUses() const {
switch (kind) {
case BorrowingOperandKind::Invalid:
llvm_unreachable("Using invalid case");
case BorrowingOperandKind::BeginBorrow:
case BorrowingOperandKind::StoreBorrow:
case BorrowingOperandKind::BeginApply:
case BorrowingOperandKind::BeginAsyncLet:
case BorrowingOperandKind::PartialApplyStack:
case BorrowingOperandKind::MarkDependenceNonEscaping: {
return op->getUser()->hasUsesOfAnyResult();
}
case BorrowingOperandKind::Branch: {
auto *br = cast<BranchInst>(op->getUser());
return br->getArgForOperand(op)->use_empty();
}
// These are instantaneous borrow scopes so there aren't any special end
// scope instructions.
case BorrowingOperandKind::Apply:
case BorrowingOperandKind::TryApply:
case BorrowingOperandKind::Yield:
return false;
}
llvm_unreachable("Covered switch isn't covered");
}
bool BorrowingOperand::visitScopeEndingUses(
function_ref<bool(Operand *)> visitScopeEnd,
function_ref<bool(Operand *)> visitUnknownUse) const {
switch (kind) {
case BorrowingOperandKind::Invalid:
llvm_unreachable("Using invalid case");
case BorrowingOperandKind::BeginBorrow: {
bool deadBorrow = true;
for (auto *use : cast<BeginBorrowInst>(op->getUser())->getUses()) {
if (use->isLifetimeEnding()) {
deadBorrow = false;
if (!visitScopeEnd(use))
return false;
}
}
// FIXME: special case for dead borrows. This is dangerous because clients
// only expect visitScopeEndingUses to return false if the visitor returned
// false.
return !deadBorrow;
}
case BorrowingOperandKind::StoreBorrow: {
bool deadBorrow = true;
for (auto *use : cast<StoreBorrowInst>(op->getUser())->getUses()) {
if (isa<EndBorrowInst>(use->getUser())) {
deadBorrow = false;
if (!visitScopeEnd(use))
return false;
}
}
// FIXME: special case for dead borrows. This is dangerous because clients
// only expect visitScopeEndingUses to return false if the visitor returned
// false.
return !deadBorrow;
}
case BorrowingOperandKind::BeginApply: {
bool deadApply = true;
auto *user = cast<BeginApplyInst>(op->getUser());
for (auto *use : user->getTokenResult()->getUses()) {
deadApply = false;
if (!visitScopeEnd(use))
return false;
}
return !deadApply;
}
case BorrowingOperandKind::PartialApplyStack: {
auto *user = cast<PartialApplyInst>(op->getUser());
assert(user->isOnStack() && "escaping closures can't borrow");
// The closure's borrow lifetimes end when the closure itself ends its
// lifetime. That may happen transitively through conversions that forward
// ownership of the closure.
return user->visitOnStackLifetimeEnds(visitScopeEnd);
}
case BorrowingOperandKind::MarkDependenceNonEscaping: {
auto *user = cast<MarkDependenceInst>(op->getUser());
assert(user->isNonEscaping() && "escaping dependencies don't borrow");
return user->visitNonEscapingLifetimeEnds(visitScopeEnd, visitUnknownUse);
}
case BorrowingOperandKind::BeginAsyncLet: {
auto user = cast<BuiltinInst>(op->getUser());
// The async let ends its borrow when the task is ended.
bool dead = true;
for (auto *use : user->getUses()) {
dead = false;
auto builtinUser = dyn_cast<BuiltinInst>(use->getUser());
if (!builtinUser
|| builtinUser->getBuiltinKind() != BuiltinValueKind::EndAsyncLetLifetime)
continue;
if (!visitScopeEnd(use)) {
return false;
}
}
return !dead;
}
// These are instantaneous borrow scopes so there aren't any special end
// scope instructions.
case BorrowingOperandKind::Apply:
case BorrowingOperandKind::TryApply:
case BorrowingOperandKind::Yield:
return true;
case BorrowingOperandKind::Branch: {
bool deadBranch = true;
auto *br = cast<BranchInst>(op->getUser());
for (auto *use : br->getArgForOperand(op)->getUses()) {
if (use->isLifetimeEnding()) {
deadBranch = false;
if (!visitScopeEnd(use))
return false;
}
}
return !deadBranch;
}
}
llvm_unreachable("Covered switch isn't covered");
}
bool BorrowingOperand::visitExtendedScopeEndingUses(
function_ref<bool(Operand *)> visitor,
function_ref<bool(Operand *)> visitUnknownUse) const {
if (hasBorrowIntroducingUser()) {
auto borrowedValue = getBorrowIntroducingUserResult();
return borrowedValue.visitExtendedScopeEndingUses(visitor);
}
return visitScopeEndingUses(visitor, visitUnknownUse);
}
BorrowedValue BorrowingOperand::getBorrowIntroducingUserResult() const {
switch (kind) {
case BorrowingOperandKind::Invalid:
case BorrowingOperandKind::Apply:
case BorrowingOperandKind::TryApply:
case BorrowingOperandKind::BeginApply:
case BorrowingOperandKind::Yield:
case BorrowingOperandKind::PartialApplyStack:
case BorrowingOperandKind::MarkDependenceNonEscaping:
case BorrowingOperandKind::BeginAsyncLet:
case BorrowingOperandKind::StoreBorrow:
return BorrowedValue();
case BorrowingOperandKind::BeginBorrow: {
auto value = BorrowedValue(cast<BeginBorrowInst>(op->getUser()));
assert(value);
return value;
}
case BorrowingOperandKind::Branch: {
auto *bi = cast<BranchInst>(op->getUser());
auto value =
BorrowedValue(bi->getDestBB()->getArgument(op->getOperandNumber()));
assert(value && "guaranteed-to-unowned conversion not allowed on branches");
return value;
}
}
llvm_unreachable("covered switch");
}
SILValue BorrowingOperand::getScopeIntroducingUserResult() {
switch (kind) {
case BorrowingOperandKind::Invalid:
case BorrowingOperandKind::Yield:
case BorrowingOperandKind::Apply:
case BorrowingOperandKind::TryApply:
return SILValue();
case BorrowingOperandKind::BeginAsyncLet:
case BorrowingOperandKind::PartialApplyStack:
case BorrowingOperandKind::MarkDependenceNonEscaping:
case BorrowingOperandKind::BeginBorrow:
case BorrowingOperandKind::StoreBorrow:
return cast<SingleValueInstruction>(op->getUser());
case BorrowingOperandKind::BeginApply:
return cast<BeginApplyInst>(op->getUser())->getTokenResult();
case BorrowingOperandKind::Branch: {
PhiOperand phiOp(op);
return phiOp.getValue();
}
}
llvm_unreachable("covered switch");
}
void BorrowingOperand::getImplicitUses(
SmallVectorImpl<Operand *> &foundUses) const {
// FIXME: this visitScopeEndingUses should never return false once dead
// borrows are disallowed.
auto handleUse = [&](Operand *endOp) {
foundUses.push_back(endOp);
return true;
};
if (!visitScopeEndingUses(handleUse, handleUse)) {
// Special-case for dead borrows.
foundUses.push_back(op);
}
}
//===----------------------------------------------------------------------===//
// Borrow Introducers
//===----------------------------------------------------------------------===//
void BorrowedValueKind::print(llvm::raw_ostream &os) const {
switch (value) {
case BorrowedValueKind::Invalid:
llvm_unreachable("Using invalid case?!");
case BorrowedValueKind::SILFunctionArgument:
os << "SILFunctionArgument";
return;
case BorrowedValueKind::BeginBorrow:
os << "BeginBorrowInst";
return;
case BorrowedValueKind::LoadBorrow:
os << "LoadBorrowInst";
return;
case BorrowedValueKind::Phi:
os << "Phi";
return;
}
llvm_unreachable("Covered switch isn't covered?!");
}
void BorrowedValue::print(llvm::raw_ostream &os) const {
os << "BorrowScopeIntroducingValue:\n"
"Kind: " << kind << "\n"
"Value: " << value;
}
void BorrowedValue::getLocalScopeEndingInstructions(
SmallVectorImpl<SILInstruction *> &scopeEndingInsts) const {
visitLocalScopeEndingUses([&](auto *use) {
scopeEndingInsts.push_back(use->getUser());
return true;
});
}
// Note: BorrowedLifetimeExtender assumes no intermediate values between a
// borrow introducer and its reborrow. The borrowed value must be an operand of
// the reborrow.
bool BorrowedValue::visitLocalScopeEndingUses(
function_ref<bool(Operand *)> visitor) const {
assert(isLocalScope() && "Should only call this given a local scope");
switch (kind) {
case BorrowedValueKind::Invalid:
llvm_unreachable("Using invalid case?!");
case BorrowedValueKind::SILFunctionArgument:
llvm_unreachable("Should only call this with a local scope");
case BorrowedValueKind::LoadBorrow:
case BorrowedValueKind::BeginBorrow:
case BorrowedValueKind::Phi:
for (auto *use : value->getUses()) {
if (use->isLifetimeEnding()) {
if (!visitor(use))
return false;
}
}
return true;
}
llvm_unreachable("Covered switch isn't covered?!");
}
llvm::raw_ostream &swift::operator<<(llvm::raw_ostream &os,
BorrowedValueKind kind) {
kind.print(os);
return os;
}
llvm::raw_ostream &swift::operator<<(llvm::raw_ostream &os,
const BorrowedValue &value) {
value.print(os);
return os;
}
/// Add this scopes live blocks into the PrunedLiveness result.
void BorrowedValue::
computeTransitiveLiveness(MultiDefPrunedLiveness &liveness) const {
liveness.initializeDef(value);
visitTransitiveLifetimeEndingUses([&](Operand *endOp) {
if (endOp->getOperandOwnership() == OperandOwnership::EndBorrow) {
liveness.updateForUse(endOp->getUser(), /*lifetimeEnding*/ true);
return true;
}
assert(endOp->getOperandOwnership() == OperandOwnership::Reborrow);
PhiOperand phiOper(endOp);
liveness.initializeDef(phiOper.getValue());
liveness.updateForUse(endOp->getUser(), /*lifetimeEnding*/ false);
return true;
});
}
bool BorrowedValue::areUsesWithinExtendedScope(
ArrayRef<Operand *> uses, DeadEndBlocks *deadEndBlocks) const {
// First make sure that we actually have a local scope. If we have a non-local
// scope, then we have something (like a SILFunctionArgument) where a larger
// semantic construct (in the case of SILFunctionArgument, the function
// itself) acts as the scope. So we already know that our passed in
// instructions must be in the same scope.
if (!isLocalScope())
return true;
// Compute the local scope's liveness.
MultiDefPrunedLiveness liveness(value->getFunction());
computeTransitiveLiveness(liveness);
return liveness.areUsesWithinBoundary(uses, deadEndBlocks);
}
// The visitor \p func is only called on final scope-ending uses, not reborrows.
bool BorrowedValue::visitExtendedScopeEndingUses(
function_ref<bool(Operand *)> visitor) const {
assert(isLocalScope());
SmallPtrSetVector<SILValue, 4> reborrows;
auto visitEnd = [&](Operand *scopeEndingUse) {
if (scopeEndingUse->getOperandOwnership() == OperandOwnership::Reborrow) {
auto borrowedValue =
BorrowingOperand(scopeEndingUse).getBorrowIntroducingUserResult();
reborrows.insert(borrowedValue.value);
return true;
}
return visitor(scopeEndingUse);
};
if (!visitLocalScopeEndingUses(visitEnd))
return false;
// reborrows grows in this loop.
for (unsigned idx = 0; idx < reborrows.size(); ++idx) {
if (!BorrowedValue(reborrows[idx]).visitLocalScopeEndingUses(visitEnd))
return false;
}
return true;
}
bool BorrowedValue::visitTransitiveLifetimeEndingUses(
function_ref<bool(Operand *)> visitor) const {
assert(isLocalScope());
SmallPtrSetVector<SILValue, 4> reborrows;
auto visitEnd = [&](Operand *scopeEndingUse) {
if (scopeEndingUse->getOperandOwnership() == OperandOwnership::Reborrow) {
auto borrowedValue =
BorrowingOperand(scopeEndingUse).getBorrowIntroducingUserResult();
reborrows.insert(borrowedValue.value);
// visitor on the reborrow
return visitor(scopeEndingUse);
}
// visitor on the end_borrow
return visitor(scopeEndingUse);
};
if (!visitLocalScopeEndingUses(visitEnd))
return false;
// reborrows grows in this loop.
for (unsigned idx = 0; idx < reborrows.size(); ++idx) {
if (!BorrowedValue(reborrows[idx]).visitLocalScopeEndingUses(visitEnd))
return false;
}
return true;
}
bool BorrowedValue::visitInteriorPointerOperandHelper(
function_ref<void(InteriorPointerOperand)> func,
BorrowedValue::InteriorPointerOperandVisitorKind kind) const {
using Kind = BorrowedValue::InteriorPointerOperandVisitorKind;
SmallVector<Operand *, 32> worklist(value->getUses());
while (!worklist.empty()) {
auto *op = worklist.pop_back_val();
if (auto interiorPointer = InteriorPointerOperand(op)) {
func(interiorPointer);
continue;
}
if (auto borrowingOperand = BorrowingOperand(op)) {
switch (kind) {
case Kind::NoNestedNoReborrows:
// We do not look through nested things and or reborrows, so just
// continue.
continue;
case Kind::YesNestedNoReborrows:
// We only look through nested borrowing operands, we never look through
// reborrows though.
if (borrowingOperand.isReborrow())
continue;
break;
case Kind::YesNestedYesReborrows:
// Look through everything!
break;
}
auto bv = borrowingOperand.getBorrowIntroducingUserResult();
for (auto *use : bv->getUses()) {
if (auto intPtrOperand = InteriorPointerOperand(use)) {
func(intPtrOperand);
continue;
}
worklist.push_back(use);
}
continue;
}
auto *user = op->getUser();
if (isa<DebugValueInst>(user) || isa<SuperMethodInst>(user) ||
isa<ClassMethodInst>(user) || isa<CopyValueInst>(user) ||
isa<EndBorrowInst>(user) || isa<ApplyInst>(user) ||
isa<StoreInst>(user) || isa<PartialApplyInst>(user) ||
isa<UnmanagedRetainValueInst>(user) ||
isa<UnmanagedReleaseValueInst>(user) ||
isa<UnmanagedAutoreleaseValueInst>(user)) {
continue;
}
// These are interior pointers that have not had support yet added for them.
if (isa<ProjectExistentialBoxInst>(user)) {
continue;
}
// Look through object.
if (auto *svi = dyn_cast<SingleValueInstruction>(user)) {
if (Projection::isObjectProjection(svi)) {
for (SILValue result : user->getResults()) {
llvm::copy(result->getUses(), std::back_inserter(worklist));
}
continue;
}
}
return false;
}
return true;
}
//===----------------------------------------------------------------------===//
// AddressOwnership
//===----------------------------------------------------------------------===//
bool AddressOwnership::areUsesWithinLifetime(
ArrayRef<Operand *> uses, DeadEndBlocks &deadEndBlocks) const {
if (!base.hasLocalOwnershipLifetime())
return true;
SILValue root = base.getOwnershipReferenceRoot();
BorrowedValue borrow(root);
if (borrow)
return borrow.areUsesWithinExtendedScope(uses, &deadEndBlocks);
// --- A reference with no borrow scope! Currently happens for project_box.
// Compute the reference value's liveness.
SSAPrunedLiveness liveness(root->getFunction());
liveness.initializeDef(root);
LiveRangeSummary summary = liveness.computeSimple();
// Conservatively ignore InnerBorrowKind::Reborrowed and
// AddressUseKind::PointerEscape and Reborrowed. The resulting liveness at
// least covers the known uses.
(void)summary;
// FIXME (implicit borrow): handle reborrows transitively just like above so
// we don't bail out if a uses is within the reborrowed scope.
return liveness.areUsesWithinBoundary(uses, &deadEndBlocks);
}
//===----------------------------------------------------------------------===//
// Owned Value Introducers
//===----------------------------------------------------------------------===//
void OwnedValueIntroducerKind::print(llvm::raw_ostream &os) const {
switch (value) {
case OwnedValueIntroducerKind::Invalid:
llvm_unreachable("Using invalid case?!");
case OwnedValueIntroducerKind::Apply:
os << "Apply";
return;
case OwnedValueIntroducerKind::BeginApply:
os << "BeginApply";
return;
case OwnedValueIntroducerKind::TryApply:
os << "TryApply";
return;
case OwnedValueIntroducerKind::Copy:
os << "Copy";
return;
case OwnedValueIntroducerKind::LoadCopy:
os << "LoadCopy";
return;
case OwnedValueIntroducerKind::LoadTake:
os << "LoadTake";
return;
case OwnedValueIntroducerKind::Move:
os << "Move";
return;
case OwnedValueIntroducerKind::Phi:
os << "Phi";
return;
case OwnedValueIntroducerKind::Struct:
os << "Struct";
return;
case OwnedValueIntroducerKind::Tuple:
os << "Tuple";
return;
case OwnedValueIntroducerKind::FunctionArgument:
os << "FunctionArgument";
return;
case OwnedValueIntroducerKind::PartialApplyInit:
os << "PartialApplyInit";
return;
case OwnedValueIntroducerKind::AllocBoxInit:
os << "AllocBoxInit";
return;
case OwnedValueIntroducerKind::AllocRefInit:
os << "AllocRefInit";
return;
}
llvm_unreachable("Covered switch isn't covered");
}
//===----------------------------------------------------------------------===//
// Introducer Searching Routines
//===----------------------------------------------------------------------===//
bool swift::getAllBorrowIntroducingValues(SILValue inputValue,
SmallVectorImpl<BorrowedValue> &out) {
if (inputValue->getOwnershipKind() != OwnershipKind::Guaranteed)
return false;
llvm::SmallSetVector<SILValue, 32> worklist;
worklist.insert(inputValue);
// worklist grows in this loop.
for (unsigned idx = 0; idx < worklist.size(); idx++) {
SILValue value = worklist[idx];
// First check if v is an introducer. If so, stash it and continue.
if (auto scopeIntroducer = BorrowedValue(value)) {
out.push_back(scopeIntroducer);
continue;
}
// If v produces .none ownership, then we can ignore it. It is important
// that we put this before checking for guaranteed forwarding instructions,
// since we want to ignore guaranteed forwarding instructions that in this
// specific case produce a .none value.
if (value->getOwnershipKind() == OwnershipKind::None)
continue;
// Otherwise if v is an ownership forwarding value, add its defining
// instruction
if (value->isGuaranteedForwarding()) {
if (auto *i = value->getDefiningInstruction()) {
for (SILValue opValue : i->getNonTypeDependentOperandValues()) {
worklist.insert(opValue);
}
continue;
}
// Otherwise, we should have a block argument that is defined by a single
// predecessor terminator.
auto *arg = cast<SILPhiArgument>(value);
if (arg->isTerminatorResult()) {
if (auto *forwardedOper = arg->forwardedTerminatorResultOperand()) {
worklist.insert(forwardedOper->get());
continue;
}
}
arg->visitIncomingPhiOperands([&](auto *operand) {
worklist.insert(operand->get());
return true;
});
}
// Otherwise, this is an introducer we do not understand. Bail and return
// false.
return false;
}
return true;
}
// FIXME: replace this logic with AccessBase::findOwnershipReferenceRoot.
BorrowedValue swift::getSingleBorrowIntroducingValue(SILValue inputValue) {
if (inputValue->getOwnershipKind() != OwnershipKind::Guaranteed)
return {};
SILValue currentValue = inputValue;
while (true) {
// First check if our initial value is an introducer. If we have one, just
// return it.
if (auto scopeIntroducer = BorrowedValue(currentValue)) {
return scopeIntroducer;
}
if (currentValue->getOwnershipKind() == OwnershipKind::None)
return {};
// Otherwise if v is an ownership forwarding value, add its defining
// instruction
if (currentValue->isGuaranteedForwarding()) {
if (auto *i = currentValue->getDefiningInstructionOrTerminator()) {
auto instOps = i->getNonTypeDependentOperandValues();
// If we have multiple incoming values, return .None. We can't handle
// this.
auto begin = instOps.begin();
if (std::next(begin) != instOps.end()) {
return {};
}
// Otherwise, set currentOp to the single operand and continue.
currentValue = *begin;
continue;
}
}
// Otherwise, this is an introducer we do not understand. Bail and return
// None.
return {};
}
llvm_unreachable("Should never hit this");
}
bool swift::getAllOwnedValueIntroducers(
SILValue inputValue, SmallVectorImpl<OwnedValueIntroducer> &out) {
if (inputValue->getOwnershipKind() != OwnershipKind::Owned)
return false;
SmallVector<SILValue, 32> worklist;
worklist.emplace_back(inputValue);
while (!worklist.empty()) {
SILValue value = worklist.pop_back_val();
// First check if v is an introducer. If so, stash it and continue.
if (auto introducer = OwnedValueIntroducer::get(value)) {
out.push_back(introducer);
continue;
}
// If v produces .none ownership, then we can ignore it. It is important
// that we put this before checking for guaranteed forwarding instructions,
// since we want to ignore guaranteed forwarding instructions that in this
// specific case produce a .none value.
if (value->getOwnershipKind() == OwnershipKind::None)
continue;
// Otherwise if v is an ownership forwarding value, add its defining
// instruction
if (isForwardingConsume(value)) {
if (auto *i = value->getDefiningInstructionOrTerminator()) {
llvm::copy(i->getNonTypeDependentOperandValues(),
std::back_inserter(worklist));
continue;
}
}
// Otherwise, this is an introducer we do not understand. Bail and return
// false.
return false;
}
return true;
}
OwnedValueIntroducer swift::getSingleOwnedValueIntroducer(SILValue inputValue) {
if (inputValue->getOwnershipKind() != OwnershipKind::Owned)
return {};
SILValue currentValue = inputValue;
while (true) {
// First check if our initial value is an introducer. If we have one, just
// return it.
if (auto introducer = OwnedValueIntroducer::get(currentValue)) {
return introducer;
}
// Otherwise if v is an ownership forwarding value, add its defining
// instruction
if (isForwardingConsume(currentValue)) {
if (auto *i = currentValue->getDefiningInstructionOrTerminator()) {
auto instOps = i->getNonTypeDependentOperandValues();
// If we have multiple incoming values, return .None. We can't handle
// this.
auto begin = instOps.begin();
if (std::next(begin) != instOps.end()) {
return {};
}
// Otherwise, set currentOp to the single operand and continue.
currentValue = *begin;
continue;
}
}
// Otherwise, this is an introducer we do not understand. Bail and return
// None.
return {};
}
llvm_unreachable("Should never hit this");
}
//===----------------------------------------------------------------------===//
// Forwarding Operand
//===----------------------------------------------------------------------===//
ForwardingOperand::ForwardingOperand(Operand *use) {
if (use->isTypeDependent())
return;
switch (use->getOperandOwnership()) {
case OperandOwnership::ForwardingUnowned:
case OperandOwnership::ForwardingConsume:
case OperandOwnership::GuaranteedForwarding:
this->use = use;
break;
default:
this->use = nullptr;
return;
}
}
ValueOwnershipKind ForwardingOperand::getForwardingOwnershipKind() const {
auto *user = use->getUser();
// NOTE: This if chain is meant to be a covered switch, so make sure to return
// in each if itself since we have an unreachable at the bottom to ensure if a
// new subclass of OwnershipForwardingInst is added
if (auto *ofsvi = dyn_cast<OwnershipForwardingSingleValueInstruction>(user))
return ofsvi->getForwardingOwnershipKind();
if (auto *ofmvi =
dyn_cast<OwnershipForwardingMultipleValueInstruction>(user)) {
assert(ofmvi->getNumOperands() == 1);
return ofmvi->getForwardingOwnershipKind();
}
if (auto *ofti = dyn_cast<OwnershipForwardingTermInst>(user)) {
assert(ofti->getNumOperands() == 1);
return ofti->getForwardingOwnershipKind();
}
llvm_unreachable("Unhandled forwarding inst?!");
}
void ForwardingOperand::setForwardingOwnershipKind(
ValueOwnershipKind newKind) const {
auto *user = use->getUser();
// NOTE: This if chain is meant to be a covered switch, so make sure to return
// in each if itself since we have an unreachable at the bottom to ensure if a
// new subclass of OwnershipForwardingInst is added
if (auto *ofsvi = dyn_cast<OwnershipForwardingSingleValueInstruction>(user))
return ofsvi->setForwardingOwnershipKind(newKind);
if (auto *ofmvi = dyn_cast<OwnershipForwardingMultipleValueInstruction>(user)) {
assert(ofmvi->getNumOperands() == 1);
if (!ofmvi->getOperand(0)->getType().isTrivial(*ofmvi->getFunction())) {
ofmvi->setForwardingOwnershipKind(newKind);
// TODO: Refactor this better.
if (auto *dsi = dyn_cast<DestructureStructInst>(ofmvi)) {
for (auto &result : dsi->getAllResultsBuffer()) {
if (result.getType().isTrivial(*dsi->getFunction()))
continue;
result.setOwnershipKind(newKind);
}
} else {
auto *dti = cast<DestructureTupleInst>(ofmvi);
for (auto &result : dti->getAllResultsBuffer()) {
if (result.getType().isTrivial(*dti->getFunction()))
continue;
result.setOwnershipKind(newKind);
}
}
}
return;
}
if (auto *ofti = dyn_cast<OwnershipForwardingTermInst>(user)) {
assert(ofti->getNumOperands() == 1);
if (!ofti->getOperand()->getType().isTrivial(*ofti->getFunction())) {
ofti->setForwardingOwnershipKind(newKind);
// Then convert all of its incoming values that are owned to be guaranteed.
for (auto &succ : ofti->getSuccessors()) {
auto *succBlock = succ.getBB();
// If we do not have any arguments, then continue.
if (succBlock->args_empty())
continue;
for (auto *succArg : succBlock->getSILPhiArguments()) {
// If we have an any value, just continue.
if (!succArg->getType().isTrivial(*ofti->getFunction()))
continue;
succArg->setOwnershipKind(newKind);
}
}
}
return;
}
assert(
!isa<MoveOnlyWrapperToCopyableValueInst>(user) &&
"MoveOnlyWrapperToCopyableValueInst can not have its ownership changed");
llvm_unreachable("Out of sync with OperandOwnership");
}
void ForwardingOperand::replaceOwnershipKind(ValueOwnershipKind oldKind,
ValueOwnershipKind newKind) const {
auto *user = use->getUser();
if (auto *fInst = dyn_cast<OwnershipForwardingSingleValueInstruction>(user))
if (fInst->getForwardingOwnershipKind() == oldKind)
return fInst->setForwardingOwnershipKind(newKind);
if (auto *ofmvi = dyn_cast<OwnershipForwardingMultipleValueInstruction>(user)) {
if (ofmvi->getForwardingOwnershipKind() == oldKind) {
ofmvi->setForwardingOwnershipKind(newKind);
}
// TODO: Refactor this better.
if (auto *dsi = dyn_cast<DestructureStructInst>(ofmvi)) {
for (auto &result : dsi->getAllResultsBuffer()) {
if (result.getOwnershipKind() != oldKind)
continue;
result.setOwnershipKind(newKind);
}
} else {
auto *dti = cast<DestructureTupleInst>(ofmvi);
for (auto &result : dti->getAllResultsBuffer()) {
if (result.getOwnershipKind() != oldKind)
continue;
result.setOwnershipKind(newKind);
}
}
return;
}
if (auto *ofti = dyn_cast<OwnershipForwardingTermInst>(user)) {
if (ofti->getForwardingOwnershipKind() == oldKind) {
ofti->setForwardingOwnershipKind(newKind);
// Then convert all of its incoming values that are owned to be guaranteed.
for (auto &succ : ofti->getSuccessors()) {
auto *succBlock = succ.getBB();
// If we do not have any arguments, then continue.
if (succBlock->args_empty())
continue;
for (auto *succArg : succBlock->getSILPhiArguments()) {
// If we have an any value, just continue.
if (succArg->getOwnershipKind() == oldKind) {
succArg->setOwnershipKind(newKind);
}
}
}
}
return;
}
assert(
!isa<MoveOnlyWrapperToCopyableValueInst>(user) &&
"MoveOnlyWrapperToCopyableValueInst can not have its ownership changed");
llvm_unreachable("Missing Case! Out of sync with OperandOwnership");
}
SILValue ForwardingOperand::getSingleForwardedValue() const {
if (auto *svi = dyn_cast<SingleValueInstruction>(use->getUser()))
return svi;
return SILValue();
}
bool ForwardingOperand::visitForwardedValues(
function_ref<bool(SILValue)> visitor) {
auto *user = use->getUser();
// See if we have a single value instruction... if we do that is always the
// transitive result.
if (auto *svi = dyn_cast<SingleValueInstruction>(user)) {
return visitor(svi);
}
if (auto *mvri = dyn_cast<MultipleValueInstruction>(user)) {
return llvm::all_of(mvri->getResults(), [&](SILValue value) {
if (value->getOwnershipKind() == OwnershipKind::None)
return true;
return visitor(value);
});
}
// This is an instruction like switch_enum and checked_cast_br that are
// "transforming terminators"... We know that this means that we should at
// most have a single phi argument.
auto *ti = cast<TermInst>(user);
if (ti->mayHaveTerminatorResult()) {
return llvm::all_of(
ti->getSuccessorBlocks(), [&](SILBasicBlock *succBlock) {
// If we do not have any arguments, then continue.
if (succBlock->args_empty())
return true;
auto args = succBlock->getSILPhiArguments();
assert(args.size() == 1 &&
"Transforming terminator with multiple args?!");
return visitor(args[0]);
});
}
// If our terminator is function exiting, we do not have a value to visit, so
// just return.
if (ti->isFunctionExiting())
return true;
auto *succArg = PhiOperand(use).getValue();
return visitor(succArg);
}
void swift::visitExtendedReborrowPhiBaseValuePairs(
BeginBorrowInst *borrowInst, function_ref<void(SILPhiArgument *, SILValue)>
visitReborrowPhiBaseValuePair) {
// A Reborrow can have different base values on different control flow
// paths.
// For that reason, worklist stores (reborrow, base value) pairs.
// We need a SetVector to make sure we don't revisit the same pair again.
llvm::SmallSetVector<std::tuple<PhiOperand, SILValue>, 4> worklist;
// Find all reborrows of value and insert the (reborrow, base value) pair into
// the worklist.
auto collectReborrows = [&](SILValue value, SILValue baseValue) {
BorrowedValue(value).visitLocalScopeEndingUses([&](Operand *op) {
if (op->getOperandOwnership() == OperandOwnership::Reborrow) {
worklist.insert(std::make_tuple(PhiOperand(op), baseValue));
}
return true;
});
};
// Initialize the worklist.
collectReborrows(borrowInst, borrowInst->getOperand());
// For every (reborrow, base value) pair in the worklist:
// - Find phi value and new base value
// - Call the visitor on the phi value and new base value pair
// - Populate the worklist with pairs of reborrows of phi value and the new
// base.
for (unsigned idx = 0; idx < worklist.size(); idx++) {
PhiOperand phiOp;
SILValue currentBaseValue;
std::tie(phiOp, currentBaseValue) = worklist[idx];
auto *phiValue = phiOp.getValue();
SILValue newBaseValue = currentBaseValue;
// If the previous base value was also passed as a phi operand along with
// the reborrow, its phi value will be the new base value.
for (auto &op : phiOp.getBranch()->getAllOperands()) {
PhiOperand otherPhiOp(&op);
if (otherPhiOp.getSource() != currentBaseValue) {
continue;
}
newBaseValue = otherPhiOp.getValue();
}
// Call the visitor function
visitReborrowPhiBaseValuePair(phiValue, newBaseValue);
collectReborrows(phiValue, newBaseValue);
}
}
void swift::visitExtendedGuaranteedForwardingPhiBaseValuePairs(
BorrowedValue borrow, function_ref<void(SILPhiArgument *, SILValue)>
visitGuaranteedForwardingPhiBaseValuePair) {
assert(borrow.kind == BorrowedValueKind::BeginBorrow ||
borrow.kind == BorrowedValueKind::LoadBorrow);
// A GuaranteedForwardingPhi can have different base values on different
// control flow paths.
// For that reason, worklist stores (GuaranteedForwardingPhi operand, base
// value) pairs. We need a SetVector to make sure we don't revisit the same
// pair again.
llvm::SmallSetVector<std::tuple<PhiOperand, SILValue>, 4> worklist;
auto collectGuaranteedForwardingPhis = [&](SILValue value,
SILValue baseValue) {
visitGuaranteedForwardingPhisForSSAValue(value, [&](Operand *op) {
worklist.insert(std::make_tuple(PhiOperand(op), baseValue));
return true;
});
};
// Collect all GuaranteedForwardingPhis
collectGuaranteedForwardingPhis(borrow.value, borrow.value);
borrow.visitTransitiveLifetimeEndingUses([&](Operand *endUse) {
if (endUse->getOperandOwnership() == OperandOwnership::Reborrow) {
auto *phiValue = PhiOperand(endUse).getValue();
collectGuaranteedForwardingPhis(phiValue, phiValue);
}
return true;
});
// For every (GuaranteedForwardingPhi operand, base value) pair in the
// worklist:
// - Find phi value and new base value
// - Call the visitor on the phi value and new base value pair
// - Populate the worklist with pairs of GuaranteedForwardingPhi ops of phi
// value and the new base.
for (unsigned idx = 0; idx < worklist.size(); idx++) {
PhiOperand phiOp;
SILValue currentBaseValue;
std::tie(phiOp, currentBaseValue) = worklist[idx];
auto *phiValue = phiOp.getValue();
SILValue newBaseValue = currentBaseValue;
// If an adjacent reborrow is found in the same block as the guaranteed phi,
// then set newBaseValue to the reborrow.
for (auto &op : phiOp.getBranch()->getAllOperands()) {
PhiOperand otherPhiOp(&op);
if (otherPhiOp.getSource() != currentBaseValue) {
continue;
}
newBaseValue = otherPhiOp.getValue();
}
// Call the visitor function
visitGuaranteedForwardingPhiBaseValuePair(phiValue, newBaseValue);
collectGuaranteedForwardingPhis(phiValue, newBaseValue);
}
}
/// If \p instruction forwards guaranteed values to its results, visit each
/// forwarded operand. The visitor must check whether the forwarded value is
/// guaranteed.
///
/// Return true \p visitOperand was called at least once.
///
/// \p visitOperand should always recheck for Guaranteed owernship if it
/// matters, in case a cast forwards a trivial type to a nontrivial type.
///
/// This intentionally does not handle phis, which require recursive traversal
/// to determine `isGuaranteedForwardingPhi`.
bool swift::visitForwardedGuaranteedOperands(
SILValue value, function_ref<void(Operand *)> visitOperand) {
assert(!SILArgument::asPhi(value) && "phis are handled separately");
if (auto *termResult = SILArgument::isTerminatorResult(value)) {
if (auto *oper = termResult->forwardedTerminatorResultOperand()) {
visitOperand(oper);
return true;
}
return false;
}
auto *inst = value->getDefiningInstruction();
if (!inst)
return false;
// Bypass conversions that produce a guarantee value out of thin air.
if (inst->getNumRealOperands() == 0) {
return false;
}
auto fwdOp = ForwardingOperation(inst);
if (!fwdOp) {
return false;
}
for (auto &operand : fwdOp.getForwardedOperands()) {
visitOperand(&operand);
}
return true;
}
namespace {
// Find the definitions of the scopes that enclose guaranteed values, handling
// all combinations of aggregation, guaranteed forwarding phis, and reborrows.
class FindEnclosingDefs {
// A separately allocated set-vector is used for each level of recursion
// across block boundaries (NodeSet cannot be used recursively).
using LocalValueSetVector = SmallPtrSetVector<SILValue, 8>;
SILFunction *function;
ValueSet visitedPhis;
public:
FindEnclosingDefs(SILFunction *function) : function(function),
visitedPhis(function) {}
// Visit each definition of a scope that immediately encloses a guaranteed
// value. The guaranteed value effectively keeps these scopes alive.
//
// This means something different depending on whether \p value is itself a
// borrow introducer vs. a forwarded guaranteed value. If \p value is an
// introducer, then this disovers the enclosing borrow scope and visits all
// introducers of that scope. If \p value is a forwarded value, then this
// visits the introducers of the current borrow scope.
bool visitEnclosingDefs(SILValue value,
function_ref<bool(SILValue)> visitor) && {
if (value->getOwnershipKind() != OwnershipKind::Guaranteed)
return true;
if (auto borrowedValue = BorrowedValue(value)) {
switch (borrowedValue.kind) {
case BorrowedValueKind::Invalid:
llvm_unreachable("checked above");
case BorrowedValueKind::Phi: {
StackList<SILValue> enclosingDefs(function);
recursivelyFindDefsOfReborrow(SILArgument::asPhi(value), enclosingDefs);
for (SILValue def : enclosingDefs) {
if (!visitor(def))
return false;
}
return true;
}
case BorrowedValueKind::BeginBorrow:
return std::move(*this).visitBorrowIntroducers(
cast<BeginBorrowInst>(value)->getOperand(), visitor);
case BorrowedValueKind::LoadBorrow:
case BorrowedValueKind::SILFunctionArgument:
// There is no enclosing def on this path.
return true;
}
}
// Handle forwarded guaranteed values.
return std::move(*this).visitBorrowIntroducers(value, visitor);
}
// Visit the values that introduce the borrow scopes that includes \p
// value. If value is owned, or introduces a borrow scope, then this only
// visits \p value.
bool visitBorrowIntroducers(SILValue value,
function_ref<bool(SILValue)> visitor) && {
StackList<SILValue> introducers(function);
LocalValueSetVector visitedValues;
recursivelyFindBorrowIntroducers(value, introducers, visitedValues);
for (SILValue introducer : introducers) {
if (!visitor(introducer))
return false;
}
return true;
}
protected:
// This is the identity function (i.e. just adds \p value to \p introducers)
// when:
// - \p value is owned
// - \p value introduces a borrow scope (begin_borrow, load_borrow, reborrow)
//
// Otherwise recurse up the use-def chain to find all introducers.
//
// Returns false if \p forwardingPhi was already encountered, either because
// of a phi cycle or because of reconvergent control flow. Similarly, return
// false if all incoming values were encountered.
bool recursivelyFindBorrowIntroducers(SILValue value,
StackList<SILValue> &introducers,
LocalValueSetVector &visitedValues) {
// Check if this value's introducers have already been added to
// 'introducers' to avoid duplicates and avoid exponential recursion on
// aggregates.
if (!visitedValues.insert(value))
return false;
switch (value->getOwnershipKind()) {
case OwnershipKind::Any:
case OwnershipKind::None:
case OwnershipKind::Unowned:
return false;
case OwnershipKind::Owned:
introducers.push_back(value);
return true;
case OwnershipKind::Guaranteed:
break;
}
// BorrowedValue handles the initial scope introducers: begin_borrow,
// load_borrow, & reborrow.
if (BorrowedValue(value)) {
introducers.push_back(value);
return true;
}
bool foundNewIntroducer = false;
// Handle forwarding phis.
if (auto *phi = SILArgument::asPhi(value)) {
foundNewIntroducer = recursivelyFindForwardingPhiIntroducers(
phi, introducers, visitedValues);
} else {
// Recurse through guaranteed forwarding instructions.
visitForwardedGuaranteedOperands(value, [&](Operand *operand) {
SILValue forwardedVal = operand->get();
if (forwardedVal->getOwnershipKind() == OwnershipKind::Guaranteed) {
foundNewIntroducer |=
recursivelyFindBorrowIntroducers(forwardedVal, introducers,
visitedValues);
}
});
}
return foundNewIntroducer;
}
// Given the enclosing definition on a predecessor path, identify the
// enclosing definitions on the successor block. Each enclosing predecessor
// def is either used by an outer-adjacent phi in the successor block, or it
// must dominate the successor block.
static SILValue findSuccessorDefFromPredDef(SILBasicBlock *predecessor,
SILValue enclosingPredDef) {
SILBasicBlock *successor = predecessor->getSingleSuccessorBlock();
assert(successor && "phi predecessor must have a single successor in OSSA");
for (auto *candidatePhi : successor->getArguments()) {
SILValue candidateValue =
candidatePhi->getIncomingPhiValue(predecessor);
// Find the outer adjacent phi in the successor block.
// the 'enclosingDef' from the 'pred' block.
if (candidateValue == enclosingPredDef)
return candidatePhi;
}
// No candidates phi are outer-adjacent phis. The incoming enclosingDef
// must dominate the current guaranteed phi. So it remains the enclosing
// scope.
return enclosingPredDef;
}
// Given the enclosing definitions on a predecessor path, identify the
// enclosing definitions on the successor block.
void findSuccessorDefsFromPredDefs(
SILBasicBlock *predecessor, const StackList<SILValue> &predDefs,
StackList<SILValue> &successorDefs,
LocalValueSetVector &visitedSuccessorValues) {
// Gather the new introducers for the successor block.
for (SILValue predDef : predDefs) {
SILValue succDef = findSuccessorDefFromPredDef(predecessor, predDef);
if (visitedSuccessorValues.insert(succDef))
successorDefs.push_back(succDef);
}
}
// Find the introducers of a forwarding phi's borrow scope. The introducers
// are either dominating values, or reborrows in the same block as the
// forwarding phi.
//
// Recurse along the use-def phi web until a begin_borrow is reached. At each
// level, find the outer-adjacent phi, if one exists, otherwise return the
// dominating definition.
//
// Returns false if \p forwardingPhi was already encountered, either because
// of a phi cycle or because of reconvergent control flow. Similarly, returns
// false if all incoming values were encountered.
//
// one(%reborrow_1 : @guaranteed)
// %field = struct_extract %reborrow_1
// br two(%reborrow_1, %field)
// two(%reborrow_2 : @guaranteed, %forward_2 : @guaranteed)
// end_borrow %reborrow_2
//
// Calling recursivelyFindForwardingPhiIntroducers(%forward_2)
// recursively computes these introducers:
//
// %field is the only value incoming to %forward_2.
//
// %field is introduced by %reborrow_1 via
// recursivelyFindBorrowIntroducers(%field).
//
// %reborrow_1 is introduced by %reborrow_2 in block "two" via
// findSuccessorDefsFromPredDefs(%reborrow_1)).
//
// %reborrow_2 is returned.
//
bool
recursivelyFindForwardingPhiIntroducers(SILPhiArgument *forwardingPhi,
StackList<SILValue> &introducers,
LocalValueSetVector &visitedValues) {
// Phi cycles are skipped. They cannot contribute any new enclosing defs.
if (!visitedPhis.insert(forwardingPhi))
return false;
bool foundIntroducer = false;
SILBasicBlock *block = forwardingPhi->getParent();
for (auto *pred : block->getPredecessorBlocks()) {
SILValue incomingValue = forwardingPhi->getIncomingPhiValue(pred);
// Each phi operand requires a new introducer list and visited values
// set. These values will be remapped to successor phis before adding them
// to the caller's introducer list. It may be necessary to revisit a value
// that was already visited by the caller before remapping to phis.
StackList<SILValue> incomingIntroducers(function);
LocalValueSetVector incomingVisitedValues;
if (!recursivelyFindBorrowIntroducers(incomingValue, incomingIntroducers,
incomingVisitedValues))
continue;
foundIntroducer = true;
findSuccessorDefsFromPredDefs(pred, incomingIntroducers, introducers,
visitedValues);
}
return foundIntroducer;
}
// Given a reborrow operand's incoming value, find the enclosing definition.
void recursivelyFindDefsOfReborrowOperand(
SILValue incomingValue,
StackList<SILValue> &enclosingDefs) {
if (incomingValue->getOwnershipKind() == OwnershipKind::None)
return;
assert(incomingValue->getOwnershipKind() == OwnershipKind::Guaranteed);
// Avoid repeatedly constructing BorrowedValue during use-def
// traversal. That would be quadratic if it checks all uses for reborrows.
if (auto *predPhi = dyn_cast<SILPhiArgument>(incomingValue)) {
recursivelyFindDefsOfReborrow(predPhi, enclosingDefs);
return;
}
// Handle non-phi borrow introducers.
BorrowedValue borrowedValue(incomingValue);
switch (borrowedValue.kind) {
case BorrowedValueKind::Phi:
llvm_unreachable("phis are short-curcuited above");
case BorrowedValueKind::Invalid:
llvm_unreachable("A reborrow immediate operand must be a BorrowedValue.");
case BorrowedValueKind::BeginBorrow: {
LocalValueSetVector visitedValues;
recursivelyFindBorrowIntroducers(
cast<BeginBorrowInst>(incomingValue)->getOperand(), enclosingDefs,
visitedValues);
break;
}
case BorrowedValueKind::LoadBorrow:
case BorrowedValueKind::SILFunctionArgument:
// There is no enclosing def on this path.
break;
}
}
// Given a reborrow, find the definitions of the enclosing borrow scopes. Each
// enclosing borrow scope is represented by one of the following cases, which
// refer to the example below:
//
// dominating owned value -> %value encloses %reborrow_1
// owned outer-adjacent phi -> %phi_3 encloses %reborrow_3
// dominating outer borrow introducer -> %outerBorrowB encloses %reborrow
// outer-adjacent reborrow -> %outerReborrow encloses %reborrow
//
// Recurse along the use-def phi web until a begin_borrow is reached. Then
// find all introducers of the begin_borrow's operand. At each level, find
// the outer adjacent phi, if one exists, otherwise return the most recently
// found dominating definition.
//
// If \p reborrow was already encountered because of a phi cycle, then no
// enclosingDefs are added.
//
// Example:
//
// %value = ...
// %borrow = begin_borrow %value
// br one(%borrow)
// one(%reborrow_1 : @guaranteed)
// br two(%value, %reborrow_1)
// two(%phi_2 : @owned, %reborrow_2 : @guaranteed)
// br three(%value, %reborrow_1)
// three(%phi_3 : @owned, %reborrow_3 : @guaranteed)
// end_borrow %reborrow_3
// destroy_value %phi_3
//
// recursivelyFindDefsOfReborrow(%reborrow_3) returns %phi_3 by
// computing enclosing defs (inner -> outer) in this order:
//
// %reborrow_1 -> %value
// %reborrow_2 -> %phi_2
// %reborrow_3 -> %phi_3
//
// Example:
//
// %outerBorrowA = begin_borrow
// %outerBorrowB = begin_borrow
// %struct = struct (%outerBorrowA, outerBorrowB)
// %borrow = begin_borrow %struct
// br one(%outerBorrowA, %borrow)
// one(%outerReborrow : @guaranteed, %reborrow : @guaranteed)
//
// recursivelyFindDefsOfReborrow(%reborrow) returns
// (%outerReborrow, %outerBorrowB).
//
void recursivelyFindDefsOfReborrow(SILPhiArgument *reborrow,
StackList<SILValue> &enclosingDefs) {
assert(enclosingDefs.empty());
LocalValueSetVector visitedDefs;
// phi cycles can be skipped. They cannot contribute any new enclosing defs.
if (!visitedPhis.insert(reborrow))
return;
SILBasicBlock *block = reborrow->getParent();
for (auto *pred : block->getPredecessorBlocks()) {
SILValue incomingValue = reborrow->getIncomingPhiValue(pred);
// Each phi operand requires a new enclosing def list. These values will
// be remapped to successor phis before adding them to the caller's
// enclosing def list. It may be necessary to revisit a value that was
// already visited by the caller before remapping to phis.
StackList<SILValue> enclosingPredDefs(function);
recursivelyFindDefsOfReborrowOperand(incomingValue, enclosingPredDefs);
findSuccessorDefsFromPredDefs(pred, enclosingPredDefs, enclosingDefs,
visitedDefs);
}
}
};
} // end namespace
bool swift::visitEnclosingDefs(SILValue value,
function_ref<bool(SILValue)> visitor) {
if (isa<SILUndef>(value))
return true;
return FindEnclosingDefs(value->getFunction())
.visitEnclosingDefs(value, visitor);
}
namespace swift::test {
// Arguments:
// - SILValue: value
// Dumps:
// - function
// - the enclosing defs
static FunctionTest FindEnclosingDefsTest(
"find-enclosing-defs", [](auto &function, auto &arguments, auto &test) {
function.print(llvm::outs());
llvm::outs() << "Enclosing Defs:\n";
visitEnclosingDefs(arguments.takeValue(), [](SILValue def) {
def->print(llvm::outs());
return true;
});
});
} // end namespace swift::test
bool swift::visitBorrowIntroducers(SILValue value,
function_ref<bool(SILValue)> visitor) {
if (isa<SILUndef>(value))
return true;
return FindEnclosingDefs(value->getFunction())
.visitBorrowIntroducers(value, visitor);
}
namespace swift::test {
// Arguments:
// - SILValue: value
// Dumps:
// - function
// - the borrow introducers
static FunctionTest FindBorrowIntroducers(
"find-borrow-introducers", [](auto &function, auto &arguments, auto &test) {
function.print(llvm::outs());
llvm::outs() << "Introducers:\n";
visitBorrowIntroducers(arguments.takeValue(), [](SILValue def) {
def->print(llvm::outs());
return true;
});
});
} // end namespace swift::test
/// Return true of the lifetime of \p innerPhiVal depends on \p outerPhiVal.
///
/// This handles SIL values with nested lifetimes that cross a control flow
/// merge.
///
/// When an owned value is passed to a phi, it is consumed. So any
/// "inner" scope borrowing that owned value must end no later than that
/// branch instruction. Either such a borrow scope ends before the branch that
/// represents the owned phi operand:
/// %lifetime = begin_borrow %value
/// ...
/// end_borrow %lifetime <-- borrow scope ends here
/// br block(%value) <-- owned value consumed here
/// or the borrow scope ends in another phi in the same block as (adjacent to)
/// the owned phi:
/// %lifetime = begin_borrow %value
/// ...
/// end_borrow %lifetime
/// br block(%value, %lifetime) <-- borrow scope ends here
/// <-- adjacent to the consume
/// A phi corresponding to a value nested within another phi's lifetime is an
/// "inner adjacent phi".
///
/// A guaranteed phi that ends a borrow scope is a special kind of phi called a
/// "reborrow". In the above example, the reborrow is an inner adjacent to the
/// owned phi and the owned phi is outer adjacent to the reborrow.
///
/// Note that an inner lifetime cannot extend beyond the outer lifetime's scope,
/// even of the outer value is forwarded. In particular, the following is
/// invalid:
/// %lifetime = begin_borrow %value
/// ...
/// br block(%value)
/// block(%value_2 : @owned):
/// end_borrow %lifetime
/// destroy_value %value_2
/// because %lifetime depends on %value but %value is consumed at `br two`.
///
/// Similarly, a reborrow ends its borrow scope and begins a new borrow
/// scope. So any open nested borrow of the original outer borrow must end no
/// later than in that branch instruction.
///
/// This extends to guaranteed forwarding phis, whose lifetimes are nested
/// within a borrow scope.
///
/// Currently, an owned phi's inner adjacent phi must be a reborrow. A
/// reborrow's adjacent phi may be either a nested reborrow, or a guaranteed
/// forwarding phi. In the future, we remove the requirement that all guaranteed
/// values have borrow scopes; then an owned phi's inner adjacent phi may be a
/// guaranteed forwarding phi.
///
/// Given a phi, 'outerPhi', it can be determined to have an inner adjacent phi,
/// 'innerPhi' if and only if: on any path, the operand of 'outerPhi' is the
/// enclosing definition of the operand of 'innerPhi' on the same path.
///
bool swift::isInnerAdjacentPhi(SILArgument *innerPhiVal,
SILArgument *outerPhiVal) {
auto innerPhi = PhiValue(innerPhiVal);
auto outerPhi = PhiValue(outerPhiVal);
assert(innerPhi.phiBlock == outerPhi.phiBlock && "precondition");
for (SILBasicBlock *predBlock : innerPhi.phiBlock->getPredecessorBlocks()) {
SILValue innerValue = innerPhi.getOperand(predBlock)->get();
SILValue outerValue = outerPhi.getOperand(predBlock)->get();
// Visitor returns false to stop visiting when a match is found.
if (!visitEnclosingDefs(innerValue, [&](SILValue def) {
// If innerValue's enclosing 'def' is 'outerValue', then we found an inner
// adjacent phi.
return def != outerValue;
})) {
// outerPhi ends the lifetime of an enclosing def for this predecessor.
return true;
}
}
return false;
}
/// Visit the phis in the same block as \p phi whose lifetime depends on \p
/// phi.
///
/// See isInnerAdjacentPhi() comments.
///
/// If the visitor returns false, stops visiting and returns false. Otherwise,
/// returns true.
bool swift::visitInnerAdjacentPhis(SILArgument *phi,
function_ref<bool(SILArgument *)> visitor) {
SILBasicBlock *block = phi->getParentBlock();
if (block->pred_empty())
return true;
for (auto *adjacentPhi : block->getArguments()) {
if (adjacentPhi == phi)
continue;
if (isInnerAdjacentPhi(adjacentPhi, phi)) {
if (!visitor(adjacentPhi))
return false;
}
}
return true;
}
namespace swift::test {
// Arguments:
// - SILValue: phi
// Dumps:
// - function
// - the adjacent phis
static FunctionTest VisitInnerAdjacentPhisTest(
"visit-inner-adjacent-phis",
[](auto &function, auto &arguments, auto &test) {
function.print(llvm::outs());
visitInnerAdjacentPhis(cast<SILPhiArgument>(arguments.takeValue()),
[](auto *argument) -> bool {
argument->print(llvm::outs());
return true;
});
});
} // end namespace swift::test
void swift::visitTransitiveEndBorrows(
SILValue value,
function_ref<void(EndBorrowInst *)> visitEndBorrow) {
GraphNodeWorklist<SILValue, 4> worklist;
worklist.insert(value);
while (!worklist.empty()) {
auto val = worklist.pop();
for (auto *consumingUse : val->getConsumingUses()) {
auto *consumingUser = consumingUse->getUser();
if (auto *branch = dyn_cast<BranchInst>(consumingUser)) {
auto *succBlock = branch->getSingleSuccessorBlock();
auto *phiArg = cast<SILPhiArgument>(
succBlock->getArgument(consumingUse->getOperandNumber()));
worklist.insert(phiArg);
} else {
visitEndBorrow(cast<EndBorrowInst>(consumingUser));
}
}
}
}
/// Whether the specified lexical begin_borrow instruction is nested.
///
/// A begin_borrow [lexical] is nested if the borrowed value's lifetime is
/// guaranteed by another lexical scope. That happens if:
/// - the non-guaranteed borrowee's value is lexical
/// - the guaranteed borrowee's value's reference roots are lexical
/// - for example, the borrowee is itself a begin_borrow [lexical]
bool swift::isNestedLexicalBeginBorrow(BeginBorrowInst *bbi) {
assert(bbi->isLexical());
auto value = bbi->getOperand();
if (value->getOwnershipKind() != OwnershipKind::Guaranteed) {
return value->isLexical();
}
SmallVector<SILValue, 8> roots;
findGuaranteedReferenceRoots(value, /*lookThroughNestedBorrows=*/false,
roots);
return llvm::all_of(roots, [](auto root) {
if (auto *outerBBI = dyn_cast<BeginBorrowInst>(root)) {
return (bool)outerBBI->isLexical();
}
if (auto *arg = dyn_cast<SILFunctionArgument>(root)) {
return arg->getOwnershipKind() == OwnershipKind::Guaranteed;
}
return false;
});
}
bool swift::isRedundantMoveValue(MoveValueInst *mvi) {
// Given: %moved_to_value = move_value %original_value
//
// Check whether the original value's lifetime and the moved-to value's
// lifetime have the same (1) ownership, (2) lexicality, and (3) escaping.
//
// Along the way, also check for cases where they have different values for
// those characteristics but it doesn't matter because of how limited the uses
// of the original value are (for now, whether the move is the only consuming
// use).
auto original = mvi->getOperand();
// (1) Ownership matches?
// (The new value always has owned ownership.)
if (original->getOwnershipKind() != OwnershipKind::Owned) {
return false;
}
// (2) Lexicality matches?
if (mvi->isLexical() != original->isLexical()) {
return false;
}
// The move doesn't alter constraints: ownership and lexicality match.
// Before checking whether escaping matches, check whether the move_value is
// redundant regardless on account of how its uses are limited.
//
// At this point, ownership and lexicality are known to match. If the
// original value doesn't escape, then merging the two lifetimes won't make
// it harder to optimize the portion of the merged lifetime corresponding to
// the moved-to value. If the original's only consuming use is the
// move_value, then the original value's lifetime couldn't be shortened
// anyway.
//
// Summary: !escaping(original)
// && singleConsumingUser(original) == move
// => redundant(mvi)
//
// Check this in two ways, one cheaper than the other.
// First, avoid calling findPointerEscape(original).
//
// If the original value is not a phi (a phi's incoming values might have
// escaping uses) and its only user is the move, then it doesn't escape. Also
// if its only user is the move, then its only _consuming_ user is the move.
auto *singleUser =
original->getSingleUse() ? original->getSingleUse()->getUser() : nullptr;
if (mvi == singleUser && !SILArgument::asPhi(original)) {
assert(!findPointerEscape(original));
assert(original->getSingleConsumingUse()->getUser() == mvi);
// - !escaping(original)
// - singleConsumingUser(original) == move
return true;
}
// Second, call findPointerEscape(original).
//
// Explicitly check both
// - !escaping(original)
// - singleConsumingUser(original) == move
auto originalHasEscape = findPointerEscape(original);
auto *singleConsumingUser = original->getSingleConsumingUse()
? original->getSingleConsumingUse()->getUser()
: nullptr;
if (mvi == singleConsumingUser && !originalHasEscape) {
return true;
}
// (3) Escaping matches? (Expensive check, saved for last.)
auto moveHasEscape = findPointerEscape(mvi);
return moveHasEscape == originalHasEscape;
}
|