1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715
|
/*========================== begin_copyright_notice ============================
Copyright (C) 2020-2021 Intel Corporation
SPDX-License-Identifier: MIT
============================= end_copyright_notice ===========================*/
#include "LinearScanRA.h"
#include "DebugInfo.h"
#include "LocalRA.h"
#include "PointsToAnalysis.h"
#include "SCCAnalysis.h"
#include "SpillManagerGMRF.h"
#include "common.h"
#include <optional>
using namespace vISA;
extern void getForbiddenGRFs(std::vector<unsigned int> ®Num,
G4_Kernel &kernel, unsigned stackCallRegSize,
unsigned reserveSpillSize,
unsigned reservedRegNum);
LinearScanRA::LinearScanRA(BankConflictPass &b, GlobalRA &g,
LivenessAnalysis &liveAnalysis)
: kernel(g.kernel), builder(g.builder), l(liveAnalysis), LSMem(4096), bc(b),
gra(g) {
stackCallArgLR = nullptr;
stackCallRetLR = nullptr;
}
void LinearScanRA::allocForbiddenVector(LSLiveRange *lr) {
unsigned size = kernel.getNumRegTotal();
bool *forbidden = (bool *)LSMem.alloc(sizeof(bool) * size);
memset(forbidden, false, size);
lr->setForbidden(forbidden);
if (!builder.canWriteR0())
lr->addForbidden(0);
if (builder.mustReserveR1())
lr->addForbidden(1);
}
void globalLinearScan::allocRetRegsVector(LSLiveRange *lr) {
auto size = builder.kernel.getNumRegTotal();
if (lr->getRetGRFs() == nullptr) {
bool *forbidden = (bool *)GLSMem->alloc(sizeof(bool) * size);
memset(forbidden, false, size);
lr->setRegGRFs(forbidden);
} else {
// If we are vector is preallocated, simply clear it
lr->clearRetGRF(size);
}
}
LSLiveRange *LinearScanRA::GetOrCreateLocalLiveRange(G4_Declare *topdcl) {
LSLiveRange *lr = gra.getSafeLSLR(topdcl);
// Check topdcl of operand and setup a new live range if required
if (!lr) {
lr = new (LSMem) LSLiveRange();
gra.setLSLR(topdcl, lr);
// Should we lazy-create forbidden vector instead? It seems they should be
// rare and we don't want to waste space on every live range.
allocForbiddenVector(lr);
}
return lr;
}
LSLiveRange *LinearScanRA::CreateLocalLiveRange(G4_Declare *topdcl) {
LSLiveRange *lr = new (LSMem) LSLiveRange();
gra.setLSLR(topdcl, lr);
allocForbiddenVector(lr);
return lr;
}
class isLifetimeOpCandidateForRemoval {
public:
isLifetimeOpCandidateForRemoval(GlobalRA &g) : gra(g) {}
GlobalRA &gra;
bool operator()(G4_INST *inst) {
if (inst->isPseudoKill() || inst->isLifeTimeEnd()) {
G4_Declare *topdcl = nullptr;
if (inst->isPseudoKill()) {
topdcl = GetTopDclFromRegRegion(inst->getDst());
} else {
topdcl = GetTopDclFromRegRegion(inst->getSrc(0));
}
if (topdcl) {
LSLiveRange *lr = gra.getSafeLSLR(topdcl);
if (lr && lr->getNumRefs() == 0 && (topdcl->getRegFile() == G4_GRF ||
topdcl->getRegFile() == G4_INPUT)) {
// Remove this lifetime op
return true;
}
}
}
return false;
}
};
void LinearScanRA::removeUnrequiredLifetimeOps() {
// Iterate over all instructions and inspect only
// pseudo_kills/lifetime.end instructions. Remove
// instructions that have no other useful instruction.
for (BB_LIST_ITER bb_it = kernel.fg.begin(); bb_it != kernel.fg.end();
bb_it++) {
G4_BB *bb = (*bb_it);
bb->erase(std::remove_if(bb->begin(), bb->end(),
isLifetimeOpCandidateForRemoval(this->gra)),
bb->end());
}
}
void LinearScanRA::setLexicalID() {
unsigned int id = 1;
for (auto bb : kernel.fg) {
for (auto curInst : *bb) {
if (curInst->isPseudoKill() || curInst->isLifeTimeEnd()) {
curInst->setLexicalId(id);
} else {
curInst->setLexicalId(id++);
}
}
}
lastInstLexID = id;
}
bool LinearScanRA::hasDstSrcOverlapPotential(G4_DstRegRegion *dst,
G4_SrcRegRegion *src) {
int dstOpndNumRows = 0;
if (dst->getBase()->isRegVar()) {
G4_Declare *dstDcl = dst->getBase()->asRegVar()->getDeclare();
if (dstDcl != nullptr) {
int dstOffset = (dstDcl->getOffsetFromBase() + dst->getLeftBound()) /
builder.numEltPerGRF<Type_UB>();
G4_DstRegRegion *dstRgn = dst;
dstOpndNumRows = dstRgn->getSubRegOff() * dstRgn->getTypeSize() +
dstRgn->getLinearizedEnd() -
dstRgn->getLinearizedStart() + 1 >
builder.numEltPerGRF<Type_UB>();
if (src != NULL && src->isSrcRegRegion() &&
src->asSrcRegRegion()->getBase()->isRegVar()) {
G4_SrcRegRegion *srcRgn = src->asSrcRegRegion();
G4_Declare *srcDcl = src->getBase()->asRegVar()->getDeclare();
int srcOffset = (srcDcl->getOffsetFromBase() + src->getLeftBound()) /
builder.numEltPerGRF<Type_UB>();
bool srcOpndNumRows = srcRgn->getSubRegOff() * dstRgn->getTypeSize() +
srcRgn->getLinearizedEnd() -
srcRgn->getLinearizedStart() + 1 >
builder.numEltPerGRF<Type_UB>();
if (dstOpndNumRows || srcOpndNumRows) {
if (!(gra.isEvenAligned(dstDcl) && gra.isEvenAligned(srcDcl) &&
srcOffset % 2 == dstOffset % 2 && dstOpndNumRows &&
srcOpndNumRows)) {
return true;
}
}
}
}
}
return false;
}
void LinearScanRA::getRowInfo(int size, int &nrows, int &lastRowSize,
const IR_Builder &builder) {
if (size <= (int)builder.numEltPerGRF<Type_UW>()) {
nrows = 1;
} else {
// nrows is total number of rows, including last row even if it is partial
nrows = size / builder.numEltPerGRF<Type_UW>();
// lastrowsize is number of words actually used in last row
lastRowSize = size % builder.numEltPerGRF<Type_UW>();
if (size % builder.numEltPerGRF<Type_UW>() != 0) {
nrows++;
}
if (lastRowSize == 0) {
lastRowSize = builder.numEltPerGRF<Type_UW>();
}
}
return;
}
unsigned int LinearScanRA::convertSubRegOffFromWords(G4_Declare *dcl,
int subregnuminwords) {
// Return subreg offset in units of dcl's element size.
// Input is subregnum in word units.
unsigned int subregnum;
subregnum = (subregnuminwords * 2) / dcl->getElemSize();
return subregnum;
}
void LSLiveRange::recordRef(G4_BB *bb, bool fromEntry) {
if (numRefsInFG < 2) {
if (fromEntry) {
numRefsInFG += 2;
} else if (bb != prevBBRef) {
numRefsInFG++;
prevBBRef = bb;
}
}
if (!fromEntry) {
numRefs++;
}
}
bool LSLiveRange::isGRFRegAssigned() {
vISA_ASSERT(topdcl != NULL, "Top dcl not set");
G4_RegVar *rvar = topdcl->getRegVar();
bool isPhyRegAssigned = false;
if (rvar) {
if (rvar->isPhyRegAssigned())
isPhyRegAssigned = true;
}
return isPhyRegAssigned;
}
unsigned int LSLiveRange::getSizeInWords(const IR_Builder &builder) {
int nrows = getTopDcl()->getNumRows();
int elemsize = getTopDcl()->getElemSize();
int nelems = getTopDcl()->getNumElems(); //elements per row
int words = 0;
if (nrows > 1) {
// If sizeInWords is set, use it otherwise consider entire row reserved
unsigned int sizeInWords = getTopDcl()->getWordSize();
if (sizeInWords > 0)
words = sizeInWords;
else
words = nrows * builder.numEltPerGRF<Type_UW>();
} else if (nrows == 1) {
int nbytesperword = 2;
words = (nelems * elemsize + 1) / nbytesperword;
}
return words;
}
// Mark physical register allocated to range lr as not busy
void globalLinearScan::freeAllocedRegs(LSLiveRange *lr, bool setInstID) {
int sregnum;
G4_VarBase *preg = lr->getPhyReg(sregnum);
vISA_ASSERT(
preg != NULL,
"Physical register not assigned to live range. Cannot free regs.");
unsigned int idx = 0;
if (setInstID) {
lr->getLastRef(idx);
}
if (!lr->isUseUnAvailableReg()) {
pregManager.freeRegs(preg->asGreg()->getRegNum(), sregnum,
lr->getSizeInWords(builder), idx);
}
}
void globalLinearScan::printActives() {
std::cout << "====================ACTIVATE START==================="
<< "\n";
for (auto lr : active) {
unsigned int start, end;
lr->getFirstRef(start);
lr->getLastRef(end);
int startregnum, endregnum, startsregnum = 0, endsregnum;
G4_VarBase *op;
op = lr->getPhyReg(startsregnum);
startregnum = endregnum = op->asGreg()->getRegNum();
endsregnum =
startsregnum +
(lr->getTopDcl()->getTotalElems() *
lr->getTopDcl()->getElemSize() / 2) -
1;
if (lr->getTopDcl()->getNumRows() > 1) {
endregnum = startregnum + lr->getTopDcl()->getNumRows() - 1;
if (lr->getTopDcl()->getWordSize() > 0) {
endsregnum =
lr->getTopDcl()->getWordSize() % builder.numEltPerGRF<Type_UW>() -
1;
if (endsregnum < 0)
endsregnum = 15;
} else
endsregnum = 15; // last word in GRF
}
if (lr->hasIndirectAccess()) {
std::cout << "INDIR: ";
} else {
std::cout << "DIR : ";
}
if (lr->getPreAssigned()) {
std::cout << "\tPRE: ";
} else {
std::cout << "\tNOT: ";
}
std::cout << lr->getTopDcl()->getName() << "(" << start << ", " << end
<< ", " << lr->getTopDcl()->getByteSize() << ")";
std::cout << " (r" << startregnum << "." << startsregnum << ":w - "
<< "r" << endregnum << "." << endsregnum << ":w)";
std::cout << "\n";
}
for (int i = 0; i < (int)(numRegLRA); i++) {
std::cout << "\nR" << i << ":";
if (activeGRF[i].activeInput.size()) {
for (auto lr : activeGRF[i].activeLV) {
int startregnum, endregnum, startsregnum = 0, endsregnum;
G4_VarBase *op;
op = lr->getPhyReg(startsregnum);
startregnum = endregnum = op->asGreg()->getRegNum();
endsregnum = startsregnum +
(lr->getTopDcl()->getTotalElems() *
lr->getTopDcl()->getElemSize() / 2) -
1;
if (lr->getTopDcl()->getNumRows() > 1) {
endregnum = startregnum + lr->getTopDcl()->getNumRows() - 1;
if (lr->getTopDcl()->getWordSize() > 0) {
endsregnum = lr->getTopDcl()->getWordSize() %
builder.numEltPerGRF<Type_UW>() -
1;
if (endsregnum < 0)
endsregnum = 15;
} else
endsregnum = 15; // last word in GRF
}
std::cout << "\tIN: " << lr->getTopDcl()->getName();
std::cout << "(r" << startregnum << "." << startsregnum << ":w - "
<< "r" << endregnum << "." << endsregnum << ":w)";
}
}
if (activeGRF[i].activeLV.size()) {
// There may be multiple variables take same register with different
// offsets
for (auto lr : activeGRF[i].activeLV) {
int startsregnum = 0;
G4_VarBase *op = lr->getPhyReg(startsregnum);
int startregnum = op->asGreg()->getRegNum();
int endregnum = startregnum;
int endsregnum = startsregnum +
(lr->getTopDcl()->getTotalElems() *
lr->getTopDcl()->getElemSize() / 2) -
1;
if (lr->getTopDcl()->getNumRows() > 1) {
endregnum = startregnum + lr->getTopDcl()->getNumRows() - 1;
if (lr->getTopDcl()->getWordSize() > 0) {
endsregnum = lr->getTopDcl()->getWordSize() %
builder.numEltPerGRF<Type_UW>() -
1;
if (endsregnum < 0)
endsregnum = 15;
} else
endsregnum = 15; // last word in GRF
}
std::cout << "\t" << lr->getTopDcl()->getName();
std::cout << "(r" << startregnum << "." << startsregnum << ":w - "
<< "r" << endregnum << "." << endsregnum << ":w)";
}
}
}
std::cout << "====================ACTIVATE END==================="
<< "\n";
}
void globalLinearScan::expireAllActive() {
if (active.size() > 0) {
// Expire any remaining ranges
LSLiveRange *lastActive = active.back();
unsigned int endIdx;
lastActive->getLastRef(endIdx);
expireGlobalRanges(endIdx);
}
}
void LinearScanRA::linearScanMarkReferencesInOpnd(G4_Operand *opnd, bool isEOT,
bool isCall) {
G4_Declare *topdcl = NULL;
if ((opnd->isSrcRegRegion() || opnd->isDstRegRegion())) {
topdcl = GetTopDclFromRegRegion(opnd);
if (topdcl &&
(topdcl->getRegFile() == G4_GRF || topdcl->getRegFile() == G4_INPUT)) {
// Handle GRF here
vISA_ASSERT(topdcl->getAliasDeclare() == NULL, "Not topdcl");
LSLiveRange *lr = GetOrCreateLocalLiveRange(topdcl);
lr->recordRef(curBB_, false);
if (isEOT && kernel.fg.builder->hasEOTGRFBinding()) {
lr->markEOT();
}
if (topdcl->getRegVar() && topdcl->getRegVar()->isPhyRegAssigned() &&
topdcl->getRegVar()->getPhyReg()->isGreg()) {
lr->setPreAssigned(true);
}
if (isCall) {
lr->setIsCall(true);
}
if (topdcl->getRegFile() == G4_INPUT) {
BBVector[curBB_->getId()].setRefInput(true);
}
}
} else if (opnd->isAddrExp()) {
G4_AddrExp *addrExp = opnd->asAddrExp();
topdcl = addrExp->getRegVar()->getDeclare();
while (topdcl->getAliasDeclare() != NULL)
topdcl = topdcl->getAliasDeclare();
vISA_ASSERT(topdcl != NULL, "Top dcl was null for addr exp opnd");
LSLiveRange *lr = GetOrCreateLocalLiveRange(topdcl);
lr->recordRef(curBB_, false);
lr->markIndirectRef(true);
if (topdcl->getRegVar() && topdcl->getRegVar()->isPhyRegAssigned() &&
topdcl->getRegVar()->getPhyReg()->isGreg()) {
lr->setPreAssigned(true);
}
if (topdcl->getRegFile() == G4_INPUT) {
BBVector[curBB_->getId()].setRefInput(true);
}
}
}
void LinearScanRA::linearScanMarkReferencesInInst(INST_LIST_ITER inst_it) {
auto inst = (*inst_it);
// Scan dst
G4_Operand *dst = inst->getDst();
if (dst) {
linearScanMarkReferencesInOpnd(dst, false, inst->isCall());
}
// Scan srcs
for (int i = 0, nSrcs = inst->getNumSrc(); i < nSrcs; i++) {
G4_Operand *src = inst->getSrc(i);
if (src) {
linearScanMarkReferencesInOpnd(src, inst->isEOT(), inst->isCall());
}
}
}
void LinearScanRA::linearScanMarkReferences(unsigned int &numRowsEOT) {
// Iterate over all BBs
for (auto curBB : kernel.fg) {
curBB_ = curBB;
// Iterate over all insts
for (INST_LIST_ITER inst_it = curBB->begin(), inst_end = curBB->end();
inst_it != inst_end; ++inst_it) {
G4_INST *curInst = (*inst_it);
if (curInst->isPseudoKill() || curInst->isLifeTimeEnd()) {
if (curInst->isLifeTimeEnd()) {
linearScanMarkReferencesInInst(inst_it);
}
continue;
}
if (curInst->isEOT() && kernel.fg.builder->hasEOTGRFBinding()) {
numRowsEOT += curInst->getSrc(0)->getTopDcl()->getNumRows();
if (curInst->isSplitSend() && !curInst->getSrc(1)->isNullReg()) {
// both src0 and src1 have to be >=r112
numRowsEOT += curInst->getSrc(1)->getTopDcl()->getNumRows();
}
}
linearScanMarkReferencesInInst(inst_it);
}
if (BBVector[curBB->getId()].hasBackEdgeIn() || curBB->getId() == 0) {
for (unsigned i = 0; i < kernel.Declares.size(); i++) {
G4_Declare *dcl = kernel.Declares[i];
if (dcl->getAliasDeclare() != NULL) {
continue;
}
if (dcl->getRegFile() != G4_GRF && dcl->getRegFile() != G4_INPUT) {
continue;
}
LSLiveRange *lr = gra.getSafeLSLR(dcl);
if (lr == nullptr) {
continue;
}
if (!l.isEmptyLiveness() &&
l.isLiveAtEntry(curBB, dcl->getRegVar()->getId())) {
lr->recordRef(curBB, true);
}
}
}
}
getGlobalDeclares();
}
bool LSLiveRange::isLiveRangeGlobal() const {
if (numRefsInFG > 1 || topdcl->isOutput() == true ||
(topdcl->getRegVar() && topdcl->getRegVar()->isPhyRegAssigned() &&
topdcl->getRegVar()->getPhyReg()->isGreg())) {
return true;
}
return false;
}
void LinearScanRA::getGlobalDeclares() {
for (G4_Declare *dcl : kernel.Declares) {
const LSLiveRange *lr = gra.getSafeLSLR(dcl);
if (lr && lr->isLiveRangeGlobal()) {
globalDeclares.push_back(dcl);
}
}
return;
}
void LinearScanRA::markBackEdges() {
unsigned numBBId = (unsigned)kernel.fg.size();
BBVector.resize(numBBId);
for (auto curBB : kernel.fg) {
for (auto succBB : curBB->Succs) {
if (curBB->getId() >= succBB->getId()) {
BBVector[succBB->getId()].setBackEdgeIn(true);
BBVector[curBB->getId()].setBackEdgeOut(true);
}
}
}
if (!kernel.fg.isReducible()) {
// Find exit BB of SCC and map it to the head BB of SCC
SCCAnalysis SCCFinder(kernel.fg);
SCCFinder.run();
for (auto iter = SCCFinder.SCC_begin(), iterEnd = SCCFinder.SCC_end();
iter != iterEnd; ++iter) {
auto &&anSCC = *iter;
std::unordered_set<G4_BB *> SCCSucc; // any successor BB of the SCC
G4_BB *headBB = anSCC.getEarliestBB();
for (auto BI = anSCC.body_begin(), BIEnd = anSCC.body_end(); BI != BIEnd;
++BI) {
G4_BB *bb = *BI;
for (auto succ : bb->Succs) {
if (!anSCC.isMember(succ)) {
SCCSucc.insert(succ);
}
}
}
for (auto exitBB : SCCSucc) // map the exitBB to the head of the SCC
{
loopHeadExitMap[headBB].push_back(exitBB);
}
}
} else {
// Find exit BB of loop and map it to the head BB of loop
for (auto &&iter : kernel.fg.getAllNaturalLoops()) {
auto &&backEdge = iter.first;
G4_BB *headBB = backEdge.second;
const std::set<G4_BB *> &loopBody = iter.second;
for (auto block : loopBody) {
for (auto succBB : block->Succs) {
if (loopBody.find(succBB) == loopBody.end()) {
G4_BB *exitBB = succBB;
unsigned latchBBId = (backEdge.first)->getId();
unsigned exitBBId = succBB->getId();
if (exitBBId < latchBBId && succBB->Succs.size() == 1) {
exitBB = succBB->Succs.front();
}
loopHeadExitMap[headBB].push_back(
exitBB); // map the exitBB to the head of the loop
}
}
}
}
}
}
void LinearScanRA::createLiveIntervals() {
for (auto dcl : gra.kernel.Declares) {
// Mark those physical registers busy that are declared with Output
// attribute The live interval will gurantee they are not reused.
if (dcl->isOutput() && dcl->isInput()) {
pregs->markPhyRegs(dcl);
}
if (dcl->getAliasDeclare() != NULL) {
continue;
}
LSLiveRange *lr = new (LSMem) LSLiveRange();
gra.setLSLR(dcl, lr);
allocForbiddenVector(lr);
}
}
void LinearScanRA::preRAAnalysis() {
int numGRF = kernel.getNumRegTotal();
// Clear LSLiveRange* computed preRA
gra.clearLocalLiveRanges();
createLiveIntervals();
markBackEdges();
// Mark references made to decls
linearScanMarkReferences(numRowsEOT);
// Check whether pseudo_kill/lifetime.end are only references
// for their respective variables. Remove them if so. Doing this
// helps reduce number of variables in symbol table increasing
// changes of skipping global RA.
removeUnrequiredLifetimeOps();
numRegLRA = numGRF;
unsigned int reservedGRFNum =
builder.getOptions()->getuInt32Option(vISA_ReservedGRFNum);
bool hasStackCall =
kernel.fg.getHasStackCalls() || kernel.fg.getIsStackCallFunc();
if (hasStackCall || reservedGRFNum || builder.getOption(vISA_Debug)) {
std::vector<unsigned int> forbiddenRegs;
unsigned int stackCallRegSize =
hasStackCall ? kernel.stackCall.numReservedABIGRF() : 0;
getForbiddenGRFs(forbiddenRegs, kernel, stackCallRegSize, 0,
reservedGRFNum);
for (unsigned int i = 0, size = forbiddenRegs.size(); i < size; i++) {
unsigned int regNum = forbiddenRegs[i];
pregs->setGRFUnavailable(
regNum); // un-available will always be there, if it's conflict with
// input or pre-assigned, it's still un-available.
}
} else {
pregs->setSimpleGRFAvailable(true);
if (kernel.getInt32KernelAttr(Attributes::ATTR_Target) != VISA_3D ||
!builder.canWriteR0()) {
pregs->setR0Forbidden();
}
if (builder.mustReserveR1()) {
pregs->setR1Forbidden();
}
}
return;
}
void LinearScanRA::getCalleeSaveRegisters() {
unsigned int callerSaveNumGRF = kernel.stackCall.getCallerSaveLastGRF() + 1;
unsigned int numCalleeSaveRegs = kernel.stackCall.getNumCalleeSaveRegs();
gra.calleeSaveRegs.resize(numCalleeSaveRegs, false);
gra.calleeSaveRegCount = 0;
G4_Declare *dcl = builder.kernel.fg.pseudoVCEDcl;
LSLiveRange *lr = gra.getLSLR(dcl);
const bool *forbidden = lr->getForbidden();
unsigned int startCalleeSave = kernel.stackCall.getCallerSaveLastGRF() + 1;
unsigned int endCalleeSave =
startCalleeSave + kernel.stackCall.getNumCalleeSaveRegs() - 1;
for (unsigned i = 0; i < kernel.getNumRegTotal(); i++) {
if (forbidden[i]) {
if (i >= startCalleeSave && i < endCalleeSave) {
gra.calleeSaveRegs[i - callerSaveNumGRF] = true;
gra.calleeSaveRegCount++;
}
}
}
}
void LinearScanRA::getCallerSaveRegisters() {
unsigned int callerSaveNumGRF = kernel.stackCall.getCallerSaveLastGRF() + 1;
for (BB_LIST_ITER it = builder.kernel.fg.begin();
it != builder.kernel.fg.end(); ++it) {
if ((*it)->isEndWithFCall()) {
gra.callerSaveRegsMap[(*it)].resize(callerSaveNumGRF, false);
gra.retRegsMap[(*it)].resize(callerSaveNumGRF, false);
unsigned callerSaveRegCount = 0;
G4_INST *callInst = (*it)->back();
vISA_ASSERT((*it)->Succs.size() == 1,
"fcall basic block cannot have more than 1 successor");
G4_Declare *dcl =
builder.kernel.fg.fcallToPseudoDclMap[callInst->asCFInst()]
.VCA->getRegVar()
->getDeclare();
LSLiveRange *lr = gra.getLSLR(dcl);
const bool *forbidden = lr->getForbidden();
unsigned int startCalleeSave = 1;
unsigned int endCalleeSave =
startCalleeSave + kernel.stackCall.getCallerSaveLastGRF();
for (unsigned i = 0; i < builder.kernel.getNumRegTotal(); i++) {
if (forbidden[i]) {
if (i >= startCalleeSave && i < endCalleeSave) {
gra.callerSaveRegsMap[(*it)][i] = true;
callerSaveRegCount++;
}
}
}
// ret
const bool *rRegs = lr->getRetGRFs();
if (rRegs != nullptr) {
for (unsigned i = 0; i < builder.kernel.getNumRegTotal(); i++) {
if (rRegs[i]) {
if (i >= startCalleeSave && i < endCalleeSave) {
gra.retRegsMap[(*it)][i] = true;
}
}
}
}
gra.callerSaveRegCountMap[(*it)] = callerSaveRegCount;
}
}
}
void LinearScanRA::getSaveRestoreRegister() {
if (!builder.getIsKernel()) {
getCalleeSaveRegisters();
}
getCallerSaveRegisters();
}
/*
* Calculate the last lexcial ID of executed instruction if the function is
* called
*/
void LinearScanRA::calculateFuncLastID() {
funcLastLexID.resize(kernel.fg.sortedFuncTable.size());
for (unsigned i = 0; i < kernel.fg.sortedFuncTable.size(); i++) {
funcLastLexID[i] = 0;
}
for (auto func : kernel.fg.sortedFuncTable) {
unsigned fid = func->getId();
if (fid == UINT_MAX) {
// entry kernel
continue;
}
funcLastLexID[fid] = func->getExitBB()->back()->getLexicalId() * 2;
for (auto &&callee : func->getCallees()) {
if (funcLastLexID[fid] < funcLastLexID[callee->getId()]) {
funcLastLexID[fid] = funcLastLexID[callee->getId()];
}
}
}
}
int LinearScanRA::linearScanRA() {
std::list<LSLiveRange *> spillLRs;
int iterator = 0;
uint32_t GRFSpillFillCount = 0;
bool hasStackCall =
kernel.fg.getHasStackCalls() || kernel.fg.getIsStackCallFunc();
int globalScratchOffset =
kernel.getInt32KernelAttr(Attributes::ATTR_SpillMemOffset);
// FXIME: This does not match GCRA's definition (it has an additional
// builder.suppportsLSC())
bool useScratchMsgForSpill =
!hasStackCall && (globalScratchOffset < (int)(SCRATCH_MSG_LIMIT * 0.6));
bool enableSpillSpaceCompression =
builder.getOption(vISA_SpillSpaceCompression);
do {
spillLRs.clear();
funcCnt = 0;
std::vector<LSLiveRange *> eotLiveIntervals;
inputIntervals.clear();
setLexicalID();
calculateFuncLastID();
#ifdef DEBUG_VERBOSE_ON
COUT_ERROR << "============= ITERATION: " << iterator << "============"
<< "\n";
#endif
// Input
PhyRegsLocalRA initPregs = (*pregs);
calculateInputIntervalsGlobal(initPregs);
#ifdef DEBUG_VERBOSE_ON
COUT_ERROR << "===== printInputLiveIntervalsGlobal============"
<< kernel.getName() << "\n";
printInputLiveIntervalsGlobal();
#endif
liveThroughIntervals.clear();
globalLiveIntervals.clear();
preAssignedLiveIntervals.clear();
eotLiveIntervals.clear();
unsigned latestLexID = 0;
// Some live through intervals are implicit
calculateLiveThroughIntervals();
for (auto bb : kernel.fg) {
calculateLiveIntervalsGlobal(bb, globalLiveIntervals, eotLiveIntervals);
latestLexID = bb->back()->getLexicalId() * 2;
}
if (liveThroughIntervals.size()) {
for (auto lr : liveThroughIntervals) {
globalLiveIntervals.insert(globalLiveIntervals.begin(), lr);
}
}
#ifdef DEBUG_VERBOSE_ON
COUT_ERROR << "===== globalLiveIntervals============"
<< "\n";
printLiveIntervals(globalLiveIntervals);
#endif
if (eotLiveIntervals.size()) {
assignEOTLiveRanges(builder, eotLiveIntervals);
for (auto lr : eotLiveIntervals) {
preAssignedLiveIntervals.push_back(lr);
}
}
#ifdef DEBUG_VERBOSE_ON
COUT_ERROR << "===== preAssignedLiveIntervals============"
<< "\n";
printLiveIntervals(preAssignedLiveIntervals);
#endif
// Copy over alignment for vars inserted by RA
gra.copyMissingAlignment();
PhyRegsManager pregManager(builder, initPregs, doBCR);
globalLinearScan ra(gra, &l, globalLiveIntervals, &preAssignedLiveIntervals,
inputIntervals, pregManager, numRegLRA, numRowsEOT,
latestLexID, doBCR, highInternalConflict, &LSMem);
// Run linear scan RA
bool success = ra.runLinearScan(builder, globalLiveIntervals, spillLRs);
auto underSpillThreshold = [this](int numSpill, int asmCount) {
int threshold = std::min(
builder.getOptions()->getuInt32Option(vISA_AbortOnSpillThreshold),
200u);
return (numSpill * 200) < (threshold * asmCount);
};
for (auto lr : spillLRs) {
GRFSpillFillCount += lr->getNumRefs();
}
int instNum = 0;
for (auto bb : kernel.fg) {
instNum += (int)bb->size();
}
if (GRFSpillFillCount && builder.getOption(vISA_AbortOnSpill) &&
!underSpillThreshold(GRFSpillFillCount, instNum)) {
// update jit metadata information
if (auto jitInfo = builder.getJitInfo()) {
jitInfo->stats.spillMemUsed = 0;
jitInfo->stats.numAsmCountUnweighted = instNum;
jitInfo->stats.numGRFSpillFillWeighted = GRFSpillFillCount;
}
// Early exit when -abortonspill is passed, instead of
// spending time inserting spill code and then aborting.
return VISA_SPILL;
}
// Try other graphcoloring
if (!success) {
undoLinearScanRAAssignments();
return VISA_FAILURE;
}
if (spillLRs.size()) {
if (iterator == 0 && enableSpillSpaceCompression &&
kernel.getInt32KernelAttr(Attributes::ATTR_Target) == VISA_3D &&
!hasStackCall) {
enableSpillSpaceCompression = gra.spillSpaceCompression(
gra.computeSpillSize(spillLRs), gra.nextSpillOffset);
}
SpillManagerGRF spillGRF(gra, gra.nextSpillOffset, &l, &spillLRs,
enableSpillSpaceCompression,
useScratchMsgForSpill);
spillGRF.spillLiveRanges(&kernel);
gra.nextSpillOffset = spillGRF.getNextOffset();
gra.scratchOffset = std::max(gra.scratchOffset, spillGRF.getNextScratchOffset());
#ifdef DEBUG_VERBOSE_ON
COUT_ERROR << "===== printSpillLiveIntervals============"
<< "\n";
printSpillLiveIntervals(spillLRs);
#endif
if (builder.hasScratchSurface() && !hasStackCall &&
(gra.nextSpillOffset + globalScratchOffset) > SCRATCH_MSG_LIMIT) {
// create temp variable to store old a0.2 - this is marked as live-in
// and live-out. because the variable is emitted only post RA to
// preserve old value of a0.2.
G4_Declare *a0Dcl = kernel.fg.builder->getOldA0Dot2Temp();
LSLiveRange *lr = gra.getSafeLSLR(a0Dcl);
if (!lr) {
lr = CreateLocalLiveRange(a0Dcl);
globalDeclares.push_back(a0Dcl);
}
} else if (gra.useLscForNonStackCallSpillFill ||
gra.useLscForScatterSpill) {
// Xe2+ LSC-based spill/fill needs the same as above
G4_Declare *a0Dcl = kernel.fg.builder->getOldA0Dot2Temp();
LSLiveRange *lr = gra.getSafeLSLR(a0Dcl);
if (!lr) {
lr = CreateLocalLiveRange(a0Dcl);
globalDeclares.push_back(a0Dcl);
}
}
// update jit metadata information for spill
if (auto jitInfo = builder.getJitInfo()) {
jitInfo->hasStackcalls = kernel.fg.getHasStackCalls();
if (builder.kernel.fg.frameSizeInOWord != 0) {
// jitInfo->spillMemUsed is the entire visa stack size. Consider the
// caller/callee save size if having caller/callee save
// globalScratchOffset in unit of byte, others in Oword
//
// FIXME: globalScratchOffset must be 0 when having stack call, or
// there is a problem at stack setup
// (see GlobalRA::addGenxMainStackSetupCode)
//
// vISA stack
// globalScratchOffset -> ---------------------
// | spill |
// calleeSaveAreaOffset -> ---------------------
// | callee save |
// callerSaveAreaOffset -> ---------------------
// | caller save |
// frameSizeInOWord -> ---------------------
jitInfo->stats.spillMemUsed = builder.kernel.fg.frameSizeInOWord * 16;
// reserve spillMemUsed #bytes before 8kb boundary
kernel.getGTPinData()->setScratchNextFree(
8 * 1024 - kernel.getGTPinData()->getNumBytesScratchUse());
} else {
jitInfo->stats.spillMemUsed = gra.nextSpillOffset;
kernel.getGTPinData()->setScratchNextFree(gra.nextSpillOffset);
}
jitInfo->stats.numGRFSpillFillWeighted = GRFSpillFillCount;
}
undoLinearScanRAAssignments();
}
RA_TRACE({
std::cout << "\titeration: " << iterator << "\n";
std::cout << "\t\tnextSpillOffset: " << gra.nextSpillOffset << "\n";
std::cout << "\t\tGRFSpillFillCount: " << GRFSpillFillCount << "\n";
});
if (spillLRs.size()) {
kernel.dumpToFile("after.Spill_GRF." + std::to_string(iterator));
}
iterator++;
} while (spillLRs.size() && iterator < MAXIMAL_ITERATIONS);
if (spillLRs.size()) {
std::stringstream spilledVars;
for (auto dcl : kernel.Declares) {
if (dcl->isSpilled() && dcl->getRegFile() == G4_GRF) {
spilledVars << dcl->getName() << "\t";
}
}
spillLRs.clear();
return VISA_FAILURE;
}
if (kernel.fg.getHasStackCalls() || kernel.fg.getIsStackCallFunc()) {
getSaveRestoreRegister();
unsigned localSpillAreaOwordSize = ROUND(gra.scratchOffset, 64) / 16;
gra.addSaveRestoreCode(localSpillAreaOwordSize);
}
return VISA_SUCCESS;
}
int LinearScanRA::doLinearScanRA() {
if (l.getNumSelectedVar() == 0) {
return VISA_SUCCESS;
}
RA_TRACE(std::cout << "--Global linear Scan RA--\n");
// Initial pregs which will be used in the preRAAnalysis
PhyRegsLocalRA phyRegs(builder, kernel.getNumRegTotal());
pregs = &phyRegs;
preRAAnalysis();
int success = linearScanRA();
if (success == VISA_SUCCESS) {
kernel.setRAType(RA_Type::GLOBAL_LINEAR_SCAN_RA);
}
return success;
}
void LinearScanRA::undoLinearScanRAAssignments() {
// Undo all assignments made by local RA
for (auto dcl : kernel.Declares) {
LSLiveRange *lr = gra.getSafeLSLR(dcl);
if (lr != NULL) {
if (lr->getAssigned() == true) {
// Undo the assignment
lr->setAssigned(false);
if (lr->getTopDcl()->getRegFile() != G4_INPUT &&
!lr->getPreAssigned()) {
lr->getTopDcl()->getRegVar()->resetPhyReg();
}
lr->resetPhyReg();
}
lr->setActiveLR(false);
lr->setFirstRef(NULL, 0);
lr->setLastRef(NULL, 0);
lr->clearForbiddenGRF(kernel.getNumRegTotal());
lr->setPushed(false);
if (kernel.getOption(vISA_GenerateDebugInfo)) {
auto lrInfo = kernel.getKernelDebugInfo()->getLiveIntervalInfo(
lr->getTopDcl(), false);
if (lrInfo)
lrInfo->clearLiveIntervals();
}
}
}
}
void LinearScanRA::setPreAssignedLR(
LSLiveRange *lr, std::vector<LSLiveRange *> &preAssignedLiveIntervals) {
int subreg = 0;
G4_VarBase *reg = lr->getPhyReg(subreg);
unsigned regnum =
lr->getTopDcl()->getRegVar()->getPhyReg()->asGreg()->getRegNum();
if (reg == nullptr) {
unsigned int subReg = lr->getTopDcl()->getRegVar()->getPhyRegOff();
unsigned int subRegInWord =
subReg * lr->getTopDcl()->getRegVar()->getDeclare()->getElemSize() / 2;
lr->setPhyReg(builder.phyregpool.getGreg(regnum), subRegInWord);
}
lr->setAssigned(true);
// Pre assigned registers may overlap the unavailable registers
lr->setUseUnAvailableReg(
isUseUnAvailableRegister(regnum, lr->getTopDcl()->getNumRows()));
// Insert into preAssgined live intervals
// If the pre-assigned register is marked as unavailable, not join the live
// range
// FIXME: What about partial overlap?
if (std::find(preAssignedLiveIntervals.begin(),
preAssignedLiveIntervals.end(),
lr) == preAssignedLiveIntervals.end()) {
preAssignedLiveIntervals.push_back(lr);
}
return;
}
void LinearScanRA::setDstReferences(
G4_BB *bb, INST_LIST_ITER inst_it, G4_Declare *dcl,
std::vector<LSLiveRange *> &liveIntervals,
std::vector<LSLiveRange *> &eotLiveIntervals) {
G4_INST *curInst = (*inst_it);
LSLiveRange *lr = gra.getSafeLSLR(dcl);
if (!lr &&
dcl->getRegFile() == G4_GRF) // The new variables generated by spill/fill,
// mark reference should handle it
{
lr = CreateLocalLiveRange(dcl);
}
if (!lr)
return;
if (dcl->isOutput() && !lr->isGRFRegAssigned()) {
lr->setLastRef(curInst, lastInstLexID * 2 + 1);
if (!lr->isPushedToIntervalList()) {
liveThroughIntervals.push_back(lr);
lr->setPushed(true);
}
return;
}
if ((dcl->getRegFile() == G4_INPUT &&
dcl != kernel.fg.builder->getStackCallArg() &&
dcl != kernel.fg.builder->getStackCallRet()) ||
(lr->isGRFRegAssigned() && (!dcl->getRegVar()->isGreg()))) // ARF
{
return;
}
if (dcl == kernel.fg.builder->getStackCallArg()) {
if (stackCallArgLR == nullptr) {
lr = new (LSMem) LSLiveRange();
stackCallArgLR = lr;
lr->setTopDcl(dcl);
allocForbiddenVector(lr);
} else {
lr = stackCallArgLR;
}
} else if (dcl == kernel.fg.builder->getStackCallRet()) {
if (stackCallRetLR == nullptr) {
lr = new (LSMem) LSLiveRange();
stackCallRetLR = lr;
lr->setTopDcl(dcl);
allocForbiddenVector(lr);
} else {
lr = stackCallRetLR;
}
}
// Check whether local LR is a candidate
if (lr->isGRFRegAssigned() == false) {
if (!lr->isPushedToIntervalList()) {
liveIntervals.push_back(lr);
lr->setPushed(true);
}
unsigned int startIdx;
if (lr->getFirstRef(startIdx) == NULL && startIdx == 0) {
lr->setFirstRef(curInst, curInst->getLexicalId() * 2);
}
// For dst, we set the last ref = lexcial_ID * 2 + 1.
// So that the dst will not be released immediately if it's defined only.
// This is to handle some special workload. Such as for LIT test
lr->setLastRef(curInst, curInst->getLexicalId() * 2 + 1);
} else if (dcl->getRegVar()
->getPhyReg()
->isGreg()) // Assigned already and is GRF
{ // Such as stack call varaibles
unsigned int startIdx;
if (!lr->isPushedToIntervalList()) {
if (!curInst->isFCall()) {
liveIntervals.push_back(lr);
}
lr->setPushed(true);
// Mark live range as assigned
setPreAssignedLR(lr, preAssignedLiveIntervals);
}
if (lr->getFirstRef(startIdx) == NULL && startIdx == 0) {
lr->setFirstRef(curInst, curInst->getLexicalId() * 2);
}
// For dst, we set the last ref = lexcial_ID * 2 + 1.
// So that the dst will not be released immediately if it's defined only.
lr->setLastRef(curInst, curInst->getLexicalId() * 2 + 1);
}
if (lr->isEOT() && std::find(eotLiveIntervals.begin(), eotLiveIntervals.end(),
lr) == eotLiveIntervals.end()) {
eotLiveIntervals.push_back(lr);
}
return;
}
void LinearScanRA::setSrcReferences(
G4_BB *bb, INST_LIST_ITER inst_it, int srcIdx, G4_Declare *dcl,
std::vector<LSLiveRange *> &liveIntervals,
std::vector<LSLiveRange *> &eotLiveIntervals) {
G4_INST *curInst = (*inst_it);
LSLiveRange *lr = gra.getSafeLSLR(dcl);
if (!lr && dcl->getRegFile() == G4_GRF) {
lr = CreateLocalLiveRange(dcl);
}
if (!lr)
return;
if (dcl->isOutput() && !lr->isGRFRegAssigned()) {
lr->setLastRef(curInst, lastInstLexID * 2 + 1);
if (!lr->isPushedToIntervalList()) {
liveThroughIntervals.push_back(lr);
lr->setPushed(true);
}
return;
}
if ((dcl->getRegFile() == G4_INPUT &&
dcl != kernel.fg.builder->getStackCallRet() &&
dcl != kernel.fg.builder->getStackCallArg()) ||
(lr->isGRFRegAssigned() && (!dcl->getRegVar()->isGreg()))) // ARF
{
return;
}
if (!lr->isPushedToIntervalList()) {
liveIntervals.push_back(lr);
lr->setPushed(true);
gra.addUndefinedDcl(dcl);
unsigned int startIdx;
if (lr->getFirstRef(startIdx) == NULL &&
startIdx == 0) { // Since we scan from front to end, not referenced
// before means not defined.
if (lr->isGRFRegAssigned() && dcl->getRegVar()->getPhyReg()->isGreg()) {
lr->setFirstRef(nullptr, 1);
lr->setValid(false);
setPreAssignedLR(lr, preAssignedLiveIntervals);
} else // Not pre-asssigned, temp
{
lr->setFirstRef(curInst, curInst->getLexicalId() * 2);
}
}
}
lr->setLastRef(curInst, curInst->getLexicalId() * 2);
unsigned firstIdx = 0;
if ((builder.WaDisableSendSrcDstOverlap() &&
((curInst->isSend() && srcIdx == 0) ||
(curInst->isSplitSend() && srcIdx == 1))) ||
(curInst->isDpas() &&
srcIdx == 1) || // For DPAS, as part of same instruction, src1 should not
// have overlap with dst.
(builder.avoidDstSrcOverlap() && curInst->getDst() != NULL &&
hasDstSrcOverlapPotential(curInst->getDst(),
curInst->getSrc(srcIdx)->asSrcRegRegion())) ||
lr->getFirstRef(firstIdx) == curInst) {
lr->setLastRef(curInst, curInst->getLexicalId() * 2 + 1);
}
if (lr->isEOT() && std::find(eotLiveIntervals.begin(), eotLiveIntervals.end(),
lr) == eotLiveIntervals.end()) {
eotLiveIntervals.push_back(lr);
}
return;
}
void LinearScanRA::generateInputIntervals(
G4_Declare *topdcl, G4_INST *inst, std::vector<uint32_t> &inputRegLastRef,
PhyRegsLocalRA &initPregs, bool avoidSameInstOverlap) {
unsigned int instID = inst->getLexicalId();
G4_RegVar *var = topdcl->getRegVar();
unsigned int regNum = var->getPhyReg()->asGreg()->getRegNum();
unsigned int regOff = var->getPhyRegOff();
unsigned int idx = regNum * builder.numEltPerGRF<Type_UW>() +
(regOff * topdcl->getElemSize()) / G4_WSIZE +
topdcl->getWordSize() - 1;
//Variable size may be larger than occupied GRF
if (idx > (kernel.getNumRegTotal() * builder.numEltPerGRF<Type_UW>() - 1)) {
idx = kernel.getNumRegTotal() * builder.numEltPerGRF<Type_UW>() - 1;
}
unsigned int numWords = topdcl->getWordSize();
for (int i = numWords - 1; i >= 0; --i, --idx) {
if ((inputRegLastRef[idx] == UINT_MAX || inputRegLastRef[idx] < instID) &&
initPregs.isGRFAvailable(idx / builder.numEltPerGRF<Type_UW>())) {
inputRegLastRef[idx] = instID;
if (avoidSameInstOverlap) {
inputIntervals.push_front(new (LSMem)
LSInputLiveRange(idx, instID * 2 + 1));
} else {
inputIntervals.push_front(new (LSMem)
LSInputLiveRange(idx, instID * 2));
}
if (kernel.getOptions()->getOption(vISA_GenerateDebugInfo)) {
updateDebugInfo(kernel, topdcl, 0, inst->getVISAId());
}
}
}
initPregs.markPhyRegs(topdcl);
return;
}
// Generate the input intervals for current BB.
// The input live ranges either live through current BB or killed by current BB.
// So, it's enough we check the live out of the BB and the BB it's self
void LinearScanRA::calculateInputIntervalsGlobal(PhyRegsLocalRA &initPregs) {
int numGRF = kernel.getNumRegTotal();
std::vector<uint32_t> inputRegLastRef(
numGRF * builder.numEltPerGRF<Type_UW>(), UINT_MAX);
G4_INST *lastInst = nullptr;
for (BB_LIST_RITER bb_it = kernel.fg.rbegin(), bb_rend = kernel.fg.rend();
bb_it != bb_rend; bb_it++) {
G4_BB *bb = (*bb_it);
//@ the end of BB
if (BBVector[bb->getId()].hasBackEdgeOut()) {
for (auto dcl : globalDeclares) {
if (dcl->getAliasDeclare() != NULL || dcl->isSpilled())
continue;
if (dcl->getRegFile() == G4_INPUT &&
dcl->getRegVar()
->isGreg() && // Filter out the architecture registers
dcl->isOutput() ==
false && // Input and out should be marked as unavailable
!builder.isPreDefArg(dcl) && // Not stack call associated variables
l.isLiveAtExit(bb, dcl->getRegVar()->getId())) {
vISA_ASSERT(dcl->getRegVar()->isPhyRegAssigned(),
"Input variable has no pre-assigned physical register");
generateInputIntervals(dcl, bb->getInstList().back(), inputRegLastRef,
initPregs, false);
}
}
}
//@BB
for (INST_LIST_RITER inst_it = bb->rbegin(), inst_rend = bb->rend();
inst_it != inst_rend; inst_it++) {
G4_INST *curInst = (*inst_it);
G4_Declare *topdcl = NULL;
if (lastInst == nullptr) {
lastInst = curInst;
}
// scan dst operand (may be unnecessary but added for safety)
if (curInst->getDst() != NULL) {
// Scan dst
G4_DstRegRegion *dst = curInst->getDst();
topdcl = GetTopDclFromRegRegion(dst);
if (topdcl && topdcl->getRegFile() == G4_INPUT &&
topdcl->getRegVar()->isGreg() && topdcl->isOutput() == false &&
!builder.isPreDefArg(topdcl)) {
generateInputIntervals(topdcl, curInst, inputRegLastRef, initPregs,
false);
}
}
// Scan src operands
for (int i = 0, nSrcs = curInst->getNumSrc(); i < nSrcs; i++) {
G4_Operand *src = curInst->getSrc(i);
if (src == nullptr || src->isNullReg()) {
continue;
}
if (src->getTopDcl()) {
topdcl = GetTopDclFromRegRegion(src);
if (topdcl && topdcl->getRegFile() == G4_INPUT &&
(topdcl->getRegVar()->isGreg()) && topdcl->isOutput() == false &&
!builder.isPreDefArg(topdcl)) {
// Check whether it is input
if (builder.avoidDstSrcOverlap() && curInst->getDst() != NULL &&
hasDstSrcOverlapPotential(curInst->getDst(),
src->asSrcRegRegion())) {
generateInputIntervals(topdcl, curInst, inputRegLastRef,
initPregs, true);
} else {
if (l.isLiveAtEntry(bb, topdcl->getRegVar()->getId())) {
generateInputIntervals(topdcl, curInst, inputRegLastRef,
initPregs, false);
} else // Not capture by liveness analysis
{
generateInputIntervals(topdcl, lastInst, inputRegLastRef,
initPregs, false);
}
}
}
} else if (src->isAddrExp()) {
G4_AddrExp *addrExp = src->asAddrExp();
topdcl = addrExp->getRegVar()->getDeclare();
while (topdcl->getAliasDeclare() != NULL)
topdcl = topdcl->getAliasDeclare();
vISA_ASSERT(topdcl != NULL, "Top dcl was null for addr exp opnd");
if (topdcl->getRegFile() == G4_INPUT &&
topdcl->getRegVar()->isGreg() && topdcl->isOutput() == false &&
!builder.isPreDefArg(topdcl)) {
generateInputIntervals(topdcl, curInst, inputRegLastRef, initPregs,
false);
}
}
}
}
}
return;
}
//
//@ the entry of BB
//
void LinearScanRA::calculateLiveInIntervals(
G4_BB *bb, std::vector<LSLiveRange *> &liveIntervals) {
// FIXME: The complexity is "block_num * declare_num"
std::vector<LSLiveRange *> preAssignedLiveIntervals;
for (auto dcl : globalDeclares) {
if (dcl->getAliasDeclare() != NULL || dcl->getRegFile() == G4_INPUT ||
dcl->isSpilled()) {
continue;
}
LSLiveRange *lr = gra.getSafeLSLR(dcl);
if (lr && !l.isEmptyLiveness() &&
l.isLiveAtEntry(bb, dcl->getRegVar()->getId())) // Live in current BB
{
if (!lr->isPushedToIntervalList()) {
if (lr->isGRFRegAssigned() && dcl->getRegVar()->isGreg()) {
setPreAssignedLR(lr, preAssignedLiveIntervals);
} else {
liveIntervals.push_back(lr);
}
lr->setPushed(true);
}
unsigned curIdx = 0;
if (lr->getFirstRef(curIdx) == NULL &&
curIdx == 0) // not referenced before, assigned or not assigned?
{
lr->setFirstRef((*bb->begin()), (*bb->begin())->getLexicalId() * 2);
}
} else // Live in the exist BB of a loop
{
// Extend the live ranges of live in variable of exit BB of the loop to
// the head of loop.
std::map<G4_BB *, std::vector<G4_BB *>>::iterator loopHEIt =
loopHeadExitMap.find(bb);
if (loopHEIt !=
loopHeadExitMap.end()) // If current BB is the head of a loop
{
for (auto exitBB : loopHeadExitMap[bb]) // for all exit BBs.
{
if (lr && !l.isEmptyLiveness() &&
l.isLiveAtEntry(exitBB, dcl->getRegVar()->getId())) {
if (!lr->isPushedToIntervalList()) // Is the interval pushed or not
{
if (lr->isGRFRegAssigned() && dcl->getRegVar()->isGreg()) {
setPreAssignedLR(lr, preAssignedLiveIntervals);
} else {
liveIntervals.push_back(lr);
}
lr->setPushed(true);
}
unsigned curIdx = 0;
if (lr->getFirstRef(curIdx) == NULL &&
curIdx == 0) // not referenced before
{
lr->setFirstRef((*bb->begin()),
(*bb->begin())->getLexicalId() * 2);
}
}
}
}
}
}
if (preAssignedLiveIntervals.size() &&
bb->getId() == 0) // Should happen in the entry BB
{
liveIntervals.insert(liveIntervals.begin(),
preAssignedLiveIntervals.begin(),
preAssignedLiveIntervals.end());
}
return;
}
void LinearScanRA::calculateCurrentBBLiveIntervals(
G4_BB *bb, std::vector<LSLiveRange *> &liveIntervals,
std::vector<LSLiveRange *> &eotLiveIntervals) {
for (INST_LIST_ITER inst_it = bb->begin(), bbend = bb->end();
inst_it != bbend; inst_it++) {
G4_INST *curInst = (*inst_it);
G4_Declare *topdcl = NULL;
if (curInst->isPseudoKill() || curInst->isLifeTimeEnd() ||
curInst->isLabel()) {
continue;
}
if (curInst->isCall() == true) {
const char *name =
kernel.fg.builder->getNameString(32, "SCALL_%d", funcCnt++);
G4_Declare *scallDcl =
kernel.fg.builder->createDeclare(name, G4_GRF, 1, 1, Type_UD);
LSLiveRange *lr = CreateLocalLiveRange(scallDcl);
liveIntervals.push_back(lr);
lr->setPushed(true);
lr->setFirstRef(curInst, curInst->getLexicalId() * 2);
FuncInfo *callee = bb->getCalleeInfo();
unsigned int funcId = callee->getId();
lr->setLastRef(curInst, funcLastLexID[funcId]);
lr->setIsCallSite(true);
}
if (curInst->isFCall()) {
auto fcall = kernel.fg.builder->getFcallInfo(curInst);
G4_Declare *arg = kernel.fg.builder->getStackCallArg();
G4_Declare *ret = kernel.fg.builder->getStackCallRet();
vISA_ASSERT(fcall != std::nullopt, "fcall info not found");
uint16_t retSize = fcall->getRetSize();
uint16_t argSize = fcall->getArgSize();
if (ret && retSize > 0 && ret->getRegVar()) {
LSLiveRange *stackCallRetLR = new (LSMem) LSLiveRange();
stackCallRetLR->setTopDcl(ret);
allocForbiddenVector(stackCallRetLR);
stackCallRetLR->setFirstRef(curInst, curInst->getLexicalId() * 2);
liveIntervals.push_back(stackCallRetLR);
stackCallRetLR->setPushed(true);
}
if (stackCallArgLR && arg && argSize > 0 && arg->getRegVar()) {
stackCallArgLR->setLastRef(
curInst, curInst->getLexicalId() * 2 -
1); // Minus one so that arguments will not be spilled
}
}
if (curInst->isFReturn()) {
uint16_t retSize = kernel.fg.builder->getRetVarSize();
if (retSize && stackCallRetLR) {
stackCallRetLR->setLastRef(curInst, curInst->getLexicalId() * 2);
stackCallRetLR = nullptr;
}
}
// Scan srcs
for (int i = 0, nSrcs = curInst->getNumSrc(); i < nSrcs; i++) {
G4_Operand *src = curInst->getSrc(i);
if (src == nullptr || src->isNullReg()) {
continue;
}
if (src && src->isSrcRegRegion()) {
if (src->asSrcRegRegion()->isIndirect()) {
auto pointsToSet = l.getPointsToAnalysis().getAllInPointsTo(
src->getBase()->asRegVar());
for (const auto& pt : *pointsToSet) {
G4_Declare *dcl = pt.var->getDeclare()->getRootDeclare();
setSrcReferences(bb, inst_it, i, dcl, liveIntervals,
eotLiveIntervals);
}
} else {
// Scan all srcs
topdcl = GetTopDclFromRegRegion(src);
if (topdcl) {
setSrcReferences(bb, inst_it, i, topdcl, liveIntervals,
eotLiveIntervals);
}
}
}
}
// Scan dst
G4_DstRegRegion *dst = curInst->getDst();
if (dst) {
if (dst->isIndirect()) {
auto pointsToSet = l.getPointsToAnalysis().getAllInPointsTo(
dst->getBase()->asRegVar());
for (const auto& pt : *pointsToSet) {
G4_Declare *dcl = pt.var->getDeclare()->getRootDeclare();
setDstReferences(bb, inst_it, dcl, liveIntervals, eotLiveIntervals);
}
} else {
topdcl = GetTopDclFromRegRegion(dst);
if (topdcl) {
setDstReferences(bb, inst_it, topdcl, liveIntervals,
eotLiveIntervals);
}
}
}
}
return;
}
void LinearScanRA::calculateLiveOutIntervals(
G4_BB *bb, std::vector<LSLiveRange *> &liveIntervals) {
for (auto dcl : globalDeclares) {
if (dcl->getAliasDeclare() != NULL || dcl->getRegFile() == G4_INPUT ||
dcl->isSpilled())
continue;
LSLiveRange *lr = gra.getSafeLSLR(dcl);
if (lr && l.isLiveAtExit(bb, dcl->getRegVar()->getId())) {
lr->setLastRef(bb->getInstList().back(),
bb->getInstList().back()->getLexicalId() * 2 + 1);
}
}
return;
}
void LinearScanRA::calculateLiveThroughIntervals() {
for (auto dcl : globalDeclares) {
if (dcl->getAliasDeclare() != NULL || dcl->getRegFile() == G4_INPUT ||
dcl->isSpilled())
continue;
LSLiveRange *lr = gra.getSafeLSLR(dcl);
if (lr && dcl->isInput() && dcl->isOutput() && !lr->isGRFRegAssigned()) {
lr->setFirstRef(nullptr, 0);
lr->setLastRef(nullptr, lastInstLexID * 2 + 1);
if (!lr->isPushedToIntervalList()) {
liveThroughIntervals.push_back(lr);
lr->setPushed(true);
}
}
}
return;
}
//
// Live intervals:
// 1. not input variables
// 2. variables without assigned value: normal Intervals.
// 3. variables without assigned value, without define: wired, added by front
// end. Such as cmp f1.0, v11, v11. @BB only
// 4. variables which are pre-defined with registers: such as stack call
// pre-defined varaibles. @BB only
// 5. variables which are pre-defined but will not be assigned with registers:
// such as %null. exclusive
// 6. variables which are assigned in previuos region (BB, BBs or function, ..).
// //@entry BB
// 7. live in of region: pre-assigned, or not.
// 8. live out of region: set the last reference.
//
void LinearScanRA::calculateLiveIntervalsGlobal(
G4_BB *bb, std::vector<LSLiveRange *> &liveIntervals,
std::vector<LSLiveRange *> &eotLiveIntervals) {
//@ the entry of BB
if (bb->getId() == 0 || BBVector[bb->getId()].hasBackEdgeIn()) {
calculateLiveInIntervals(bb, liveIntervals);
}
//@ BB
calculateCurrentBBLiveIntervals(bb, liveIntervals, eotLiveIntervals);
//@ the exit of BB
if (BBVector[bb->getId()].hasBackEdgeOut()) {
calculateLiveOutIntervals(bb, liveIntervals);
}
return;
}
void LinearScanRA::printLiveIntervals(
std::vector<LSLiveRange *> &liveIntervals) {
for (auto lr : liveIntervals) {
unsigned int start, end;
lr->getFirstRef(start);
lr->getLastRef(end);
std::cout << lr->getTopDcl()->getName() << "(" << start << ", " << end
<< ", " << lr->getTopDcl()->getByteSize() << ")";
std::cout << "\n";
}
std::cout << "\n";
}
void LinearScanRA::printSpillLiveIntervals(
std::list<LSLiveRange *> &liveIntervals) {
for (auto lr : liveIntervals) {
unsigned int start, end;
lr->getFirstRef(start);
lr->getLastRef(end);
std::cout << lr->getTopDcl()->getName() << "(" << start << ", " << end
<< ", " << lr->getTopDcl()->getByteSize() << ")";
std::cout << "\n";
}
std::cout << "\n";
}
void LinearScanRA::printInputLiveIntervalsGlobal() {
COUT_ERROR << "\n"
<< "Input Live intervals "
<< "\n";
for (std::list<LSInputLiveRange *>::iterator it = inputIntervals.begin();
it != inputIntervals.end(); it++) {
unsigned int regWordIdx, lrEndIdx, regNum, subRegInWord;
LSInputLiveRange *lr = (*it);
regWordIdx = lr->getRegWordIdx();
regNum = regWordIdx / builder.numEltPerGRF<Type_UW>();
subRegInWord = regWordIdx % builder.numEltPerGRF<Type_UW>();
lrEndIdx = lr->getLrEndIdx();
COUT_ERROR << "r" << regNum << "." << subRegInWord << " " << lrEndIdx;
COUT_ERROR << "\n";
}
COUT_ERROR << "\n";
}
static inline void printLiveInterval(LSLiveRange *lr, bool assign,
const IR_Builder &builder) {
int startregnum, endregnum, startsregnum = 0, endsregnum;
G4_VarBase *op;
op = lr->getPhyReg(startsregnum);
startregnum = endregnum = op->asGreg()->getRegNum();
endsregnum =
startsregnum +
(lr->getTopDcl()->getTotalElems() * lr->getTopDcl()->getElemSize() / 2) -
1;
if (lr->getTopDcl()->getNumRows() > 1) {
endregnum = startregnum + lr->getTopDcl()->getNumRows() - 1;
if (lr->getTopDcl()->getWordSize() > 0) {
endsregnum =
lr->getTopDcl()->getWordSize() % builder.numEltPerGRF<Type_UW>() - 1;
if (endsregnum < 0)
endsregnum = 15;
} else
endsregnum = 15; // last word in GRF
}
if (assign) {
COUT_ERROR << "Assigned physical register to ";
} else {
COUT_ERROR << "Free physical register of ";
}
COUT_ERROR << lr->getTopDcl()->getName() << " (r" << startregnum << "."
<< startsregnum << ":w - "
<< "r" << endregnum << "." << endsregnum << ":w)"
<< "\n";
return;
}
globalLinearScan::globalLinearScan(
GlobalRA &g, LivenessAnalysis *l, std::vector<LSLiveRange *> &lv,
std::vector<LSLiveRange *> *assignedLiveIntervals,
std::list<LSInputLiveRange *, std_arena_based_allocator<LSInputLiveRange *>>
&inputLivelIntervals,
PhyRegsManager &pregMgr, unsigned int numReg, unsigned int numEOT,
unsigned int lastLexID, bool bankConflict, bool internalConflict, Mem_Manager* GLSMem)
: gra(g), builder(g.builder), GLSMem(GLSMem), pregManager(pregMgr),
liveIntervals(lv), preAssignedIntervals(assignedLiveIntervals),
inputIntervals(inputLivelIntervals), numRegLRA(numReg), numRowsEOT(numEOT),
lastLexicalID(lastLexID), doBankConflict(bankConflict),
highInternalConflict(internalConflict) {
startGRFReg = 0;
activeGRF.resize(g.kernel.getNumRegTotal());
for (auto lr : inputLivelIntervals) {
unsigned int regnum = lr->getRegWordIdx() / builder.numEltPerGRF<Type_UW>();
activeGRF[regnum].activeInput.push_back(lr);
}
}
void globalLinearScan::getCalleeSaveGRF(std::vector<unsigned int> ®Num,
G4_Kernel *kernel) {
unsigned int startCallerSave = kernel->stackCall.calleeSaveStart();
unsigned int endCallerSave = startCallerSave + kernel->stackCall.getNumCalleeSaveRegs();
for (auto active_it = active.begin(); active_it != active.end();
active_it++) {
LSLiveRange *lr = (*active_it);
G4_VarBase *op;
int startsregnum = 0;
op = lr->getPhyReg(startsregnum);
unsigned startregnum = op->asGreg()->getRegNum();
unsigned endregnum = startregnum + lr->getTopDcl()->getNumRows() - 1;
for (unsigned i = startregnum; i <= endregnum; i++) {
if (i >= startCallerSave && i <= endCallerSave) {
regNum.push_back(i);
}
}
}
return;
}
void globalLinearScan::getCallerSaveGRF(std::vector<unsigned int> ®Num,
std::vector<unsigned int> &retRegNum,
G4_Kernel *kernel) {
unsigned int startCalleeSave = 1;
unsigned int endCalleeSave = startCalleeSave + kernel->stackCall.getCallerSaveLastGRF();
for (auto active_it = active.begin(); active_it != active.end();
active_it++) {
LSLiveRange *lr = (*active_it);
G4_Declare *dcl = lr->getTopDcl();
if (!builder.kernel.fg.isPseudoVCEDcl(dcl) && !builder.isPreDefArg(dcl)) {
G4_VarBase *op;
int startsregnum = 0;
op = lr->getPhyReg(startsregnum);
unsigned startregnum = op->asGreg()->getRegNum();
unsigned endregnum = startregnum + lr->getTopDcl()->getNumRows() - 1;
for (unsigned i = startregnum; i <= endregnum; i++) {
if (i >= startCalleeSave && i < endCalleeSave) {
if (builder.isPreDefRet(dcl)) {
retRegNum.push_back(i);
} else {
regNum.push_back(i);
}
}
}
}
}
for (auto inputlr : inputIntervals) {
unsigned int regnum =
inputlr->getRegWordIdx() / builder.numEltPerGRF<Type_UW>();
std::vector<unsigned int>::iterator it =
std::find(regNum.begin(), regNum.end(), regnum);
if (it == regNum.end()) {
if (regnum >= startCalleeSave && regnum < endCalleeSave) {
regNum.push_back(regnum);
}
}
}
}
bool LinearScanRA::isUseUnAvailableRegister(uint32_t startReg,
uint32_t regNum) {
for (uint32_t i = startReg; i < startReg + regNum; ++i) {
if (!pregs->isGRFAvailable(i)) {
return true;
}
}
return false;
}
bool LinearScanRA::assignEOTLiveRanges(
IR_Builder &builder, std::vector<LSLiveRange *> &liveIntervals) {
#ifdef DEBUG_VERBOSE_ON
COUT_ERROR << "--------------------------------- "
<< "\n";
#endif
uint32_t nextEOTGRF = numRegLRA - numRowsEOT;
for (auto lr : liveIntervals) {
vASSERT(lr->isEOT());
G4_Declare *dcl = lr->getTopDcl();
G4_Greg *phyReg = builder.phyregpool.getGreg(nextEOTGRF);
dcl->getRegVar()->setPhyReg(phyReg, 0);
lr->setPhyReg(phyReg, 0);
lr->setAssigned(true);
lr->setUseUnAvailableReg(
isUseUnAvailableRegister(nextEOTGRF, dcl->getNumRows()));
nextEOTGRF += dcl->getNumRows();
if (nextEOTGRF > numRegLRA) {
vASSERT(false);
}
#ifdef DEBUG_VERBOSE_ON
printLiveInterval(lr, true, builder);
#endif
}
return true;
}
void globalLinearScan::updateCallSiteLiveIntervals(LSLiveRange *callSiteLR) {
unsigned lastIdx = 0;
G4_INST *inst = callSiteLR->getLastRef(lastIdx);
for (auto lr : active) {
unsigned curLastIdx;
lr->getLastRef(curLastIdx);
if (curLastIdx < lastIdx) {
lr->setLastRef(inst, lastIdx);
}
}
for (auto inputlr : inputIntervals) {
unsigned curLastIdx = inputlr->getLrEndIdx();
if (curLastIdx < lastIdx) {
inputlr->setLrEndIdx(lastIdx);
}
}
return;
}
bool globalLinearScan::runLinearScan(IR_Builder &builder,
std::vector<LSLiveRange *> &liveIntervals,
std::list<LSLiveRange *> &spillLRs) {
unsigned int idx = 0;
bool allocateRegResult = false;
#ifdef DEBUG_VERBOSE_ON
COUT_ERROR << "--------------------------------- "
<< "\n";
#endif
for (auto lr : liveIntervals) {
G4_Declare *dcl = lr->getTopDcl();
lr->getFirstRef(idx);
if (!lr->isEOT() && !lr->getAssigned()) {
// Add forbidden for preAssigned registers
auto isTopDclPseudoVCA = builder.kernel.fg.isPseudoVCADcl(lr->getTopDcl());
for (auto preAssginedLI : *preAssignedIntervals) {
if (isTopDclPseudoVCA &&
(builder.isPreDefRet(preAssginedLI->getTopDcl()) ||
builder.isPreDefArg(preAssginedLI->getTopDcl()))) {
continue;
}
unsigned preFirstIdx, preLastIdx;
preAssginedLI->getFirstRef(preFirstIdx);
preAssginedLI->getLastRef(preLastIdx);
unsigned lastIdx = 0;
lr->getLastRef(lastIdx);
if (!(lastIdx < preFirstIdx || preLastIdx < idx)) {
G4_VarBase *preg;
int subregnumword;
preg = preAssginedLI->getPhyReg(subregnumword);
unsigned reg = preg->asGreg()->getRegNum();
unsigned rowNum = preAssginedLI->getTopDcl()->getNumRows();
for (unsigned k = 0; k < rowNum; k++) {
lr->addForbidden(reg + k);
}
}
}
}
#ifdef DEBUG_VERBOSE_ON
COUT_ERROR << "-------- IDX: " << idx << "---------"
<< "\n";
#endif
// Expire the live ranges ended befoe idx
expireGlobalRanges(idx);
expireInputRanges(idx);
if (lr->isCallSite()) {
updateCallSiteLiveIntervals(lr);
continue;
}
if (builder.kernel.fg.isPseudoVCADcl(dcl)) {
std::vector<unsigned int> callerSaveRegs;
std::vector<unsigned int> regRegs;
getCallerSaveGRF(callerSaveRegs, regRegs, &gra.kernel);
for (unsigned int i = 0; i < callerSaveRegs.size(); i++) {
unsigned int callerSaveReg = callerSaveRegs[i];
lr->addForbidden(callerSaveReg);
}
for (unsigned int i = 0; i < regRegs.size(); i++) {
unsigned int callerSaveReg = regRegs[i];
if (lr->getRetGRFs() == nullptr) {
allocRetRegsVector(lr);
}
lr->addRetRegs(callerSaveReg);
}
continue;
} else if (builder.kernel.fg.isPseudoVCEDcl(dcl)) {
calleeSaveLR = lr;
continue;
} else if (!lr->getAssigned()) {
if (dcl == gra.getOldFPDcl()) {
std::vector<unsigned int> callerSaveRegs;
std::vector<unsigned int> regRegs;
getCallerSaveGRF(callerSaveRegs, regRegs, &gra.kernel);
for (unsigned int i = 0; i < callerSaveRegs.size(); i++) {
unsigned int callerSaveReg = callerSaveRegs[i];
lr->addForbidden(callerSaveReg);
}
for (unsigned int i = 0; i < regRegs.size(); i++) {
unsigned int callerSaveReg = regRegs[i];
if (lr->getRetGRFs() == nullptr) {
allocRetRegsVector(lr);
}
lr->addRetRegs(callerSaveReg);
}
}
allocateRegResult = allocateRegsLinearScan(lr, builder);
#ifdef DEBUG_VERBOSE_ON
if (allocateRegResult) {
printLiveInterval(lr, true, builder);
}
#endif
} else {
allocateRegResult = true;
int startregnum, subregnum;
G4_VarBase *op;
op = lr->getPhyReg(subregnum);
startregnum = op->asGreg()->getRegNum();
int nrows = 0;
int lastRowSize = 0;
int size = lr->getSizeInWords(builder);
LinearScanRA::getRowInfo(size, nrows, lastRowSize, builder);
if (!lr->isUseUnAvailableReg()) {
if ((unsigned)size >= builder.numEltPerGRF<Type_UW>()) {
if (size % builder.numEltPerGRF<Type_UW>() == 0) {
pregManager.getAvailableRegs()->setGRFBusy(
startregnum, lr->getTopDcl()->getNumRows());
} else {
pregManager.getAvailableRegs()->setGRFBusy(
startregnum, lr->getTopDcl()->getNumRows() - 1);
pregManager.getAvailableRegs()->setWordBusy(
startregnum + lr->getTopDcl()->getNumRows() - 1, 0,
lastRowSize);
}
} else {
pregManager.getAvailableRegs()->setWordBusy(startregnum, subregnum,
size);
}
}
}
if (allocateRegResult) {
updateGlobalActiveList(lr);
} else // Spill
{
if (spillFromActiveList(lr, spillLRs)) {
// Fixme: get the start GRF already, can allocate immediately
allocateRegResult = allocateRegsLinearScan(lr, builder);
if (!allocateRegResult) {
#ifdef DEBUG_VERBOSE_ON
COUT_ERROR << "Failed assigned physical register to "
<< lr->getTopDcl()->getName()
<< ", rows :" << lr->getTopDcl()->getNumRows() << "\n";
printActives();
#endif
return false;
} else {
updateGlobalActiveList(lr);
#ifdef DEBUG_VERBOSE_ON
printLiveInterval(lr, true, builder);
#endif
}
} else {
#ifdef DEBUG_VERBOSE_ON
COUT_ERROR << "Failed to spill registers for "
<< lr->getTopDcl()->getName()
<< ", rows :" << lr->getTopDcl()->getNumRows() << "\n";
printActives();
#endif
return false;
}
}
}
int totalGRFNum = builder.kernel.getNumRegTotal();
for (int i = 0; i < totalGRFNum; i++) {
activeGRF[i].activeLV.clear();
activeGRF[i].activeInput.clear();
}
// Assign the registers for the live out ones
expireAllActive();
if (builder.kernel.getOptions()->getOption(vISA_GenerateDebugInfo)) {
updateDebugInfo(builder.kernel, liveIntervals);
}
return true;
}
void globalLinearScan::updateGlobalActiveList(LSLiveRange *lr) {
bool done = false;
unsigned int newlr_end;
lr->getLastRef(newlr_end);
for (auto active_it = active.begin(); active_it != active.end();
active_it++) {
unsigned int end_idx;
LSLiveRange *active_lr = (*active_it);
active_lr->getLastRef(end_idx);
if (end_idx > newlr_end) {
active.insert(active_it, lr);
done = true;
break;
}
}
if (done == false)
active.push_back(lr);
#ifdef DEBUG_VERBOSE_ON
COUT_ERROR << "Add active " << lr->getTopDcl()->getName() << "\n";
#endif
G4_VarBase *op;
int startsregnum = 0;
op = lr->getPhyReg(startsregnum);
unsigned startregnum = op->asGreg()->getRegNum();
unsigned endregnum = startregnum + lr->getTopDcl()->getNumRows() - 1;
for (unsigned i = startregnum; i <= endregnum; i++) {
activeGRF[i].activeLV.push_back(lr);
#ifdef DEBUG_VERBOSE_ON
COUT_ERROR << "Add activeGRF " << lr->getTopDcl()->getName()
<< " Reg: " << i << "\n";
#endif
}
}
bool globalLinearScan::insertLiveRange(std::list<LSLiveRange *> *liveIntervals,
LSLiveRange *lr) {
unsigned int idx = 0;
lr->getFirstRef(idx);
std::list<LSLiveRange *>::iterator it = liveIntervals->begin();
while (it != liveIntervals->end()) {
LSLiveRange *curLR = (*it);
unsigned curIdx = 0;
curLR->getFirstRef(curIdx);
if (curIdx > idx) {
liveIntervals->insert(it, lr);
return true;
}
it++;
}
return false;
}
bool globalLinearScan::canBeSpilledLR(LSLiveRange *lr) {
if (lr->isUseUnAvailableReg()) {
return false;
}
if (lr->isEOT()) {
return false;
}
if (lr->getTopDcl() == builder.getBuiltinR0()) {
return false;
}
if (lr->getTopDcl()->isDoNotSpill()) {
return false;
}
if (lr->isCall()) {
return false;
}
if (lr->isGRFRegAssigned()) {
return false;
}
if (lr->getTopDcl()->isSpilled()) {
return false;
}
if (lr->getTopDcl()->getRegFile() == G4_INPUT) {
return false;
}
if (lr->getTopDcl()->getRegVar()->getId() == UNDEFINED_VAL) {
return false;
}
if (lr->getTopDcl()->getRegVar()->isRegVarTransient() ||
lr->getTopDcl()->getRegVar()->isRegVarTmp()) {
return false;
}
// Stack call variables
if (lr->getTopDcl() == gra.getOldFPDcl()) {
return false;
}
if (builder.kernel.fg.isPseudoVCADcl(lr->getTopDcl()) ||
builder.kernel.fg.isPseudoVCEDcl(lr->getTopDcl())) {
return false;
}
return true;
}
int globalLinearScan::findSpillCandidate(LSLiveRange *tlr) {
unsigned short requiredRows = tlr->getTopDcl()->getNumRows();
int referenceCount = 0;
int startGRF = -1;
float spillCost = (float)(int)0x7FFFFFFF;
unsigned lastIdxs = 1;
unsigned tStartIdx = 0;
tlr->getFirstRef(tStartIdx);
BankAlign bankAlign = getBankAlign(tlr);
for (int i = 0; i < (int)(numRegLRA - requiredRows); i++) {
unsigned endIdx = 0;
bool canBeFree = true;
LSLiveRange *analyzedLV = nullptr;
pregManager.getAvailableRegs()->findRegisterCandiateWithAlignForward(
i, bankAlign, false);
// Check the following adjacent registers
for (int k = i; k < i + requiredRows; k++) {
if (activeGRF[k].activeInput.size() || tlr->getForbidden()[k]) {
i = k;
canBeFree = false;
break;
}
if (activeGRF[k].activeLV.size()) {
// There may be multiple variables take same register with different
// offsets
for (auto lr : activeGRF[k].activeLV) {
if (lr == analyzedLV) // one LV may occupy multiple registers
{
continue;
}
analyzedLV = lr;
if (!canBeSpilledLR(lr) || lr->getForbidden()[k]) {
int startsregnum = 0;
G4_VarBase *op = lr->getPhyReg(startsregnum);
unsigned startregnum = op->asGreg()->getRegNum();
canBeFree = false;
i = startregnum + lr->getTopDcl()->getNumRows() -
1; // Jump to k + rows - 1 to avoid unnecessory analysis.
break;
}
int startsregnum = 0;
G4_VarBase *op = lr->getPhyReg(startsregnum);
int startregnum = op->asGreg()->getRegNum();
unsigned effectGRFNum =
startregnum > i
? lr->getTopDcl()->getNumRows()
: lr->getTopDcl()->getNumRows() - (i - startregnum);
lr->getLastRef(endIdx);
lastIdxs += (endIdx - tStartIdx) * effectGRFNum;
referenceCount += lr->getNumRefs();
}
if (!canBeFree) {
break;
}
} else if (pregManager.getAvailableRegs()->isGRFAvailable(k) &&
!pregManager.getAvailableRegs()->isGRFBusy(k)) {
lastIdxs += lastLexicalID - tStartIdx;
} else // Reserved regsiters
{
i = k;
canBeFree = false;
break;
}
}
if (canBeFree) {
// Spill cost
float currentSpillCost = (float)referenceCount / lastIdxs;
if (currentSpillCost < spillCost) {
startGRF = i;
spillCost = currentSpillCost;
}
}
lastIdxs = 1;
referenceCount = 0;
}
return startGRF;
}
void globalLinearScan::freeSelectedRegistsers(
int startGRF, LSLiveRange *tlr, std::list<LSLiveRange *> &spillLRs) {
unsigned short requiredRows = tlr->getTopDcl()->getNumRows();
#ifdef DEBUG_VERBOSE_ON
COUT_ERROR << "Required GRF size for spill: " << requiredRows << "\n";
#endif
// Free registers.
for (int k = startGRF; k < startGRF + requiredRows; k++) {
#ifdef DEBUG_VERBOSE_ON
if (!activeGRF[k].activeLV.size()) {
COUT_ERROR << "Pick free GRF for spill: "
<< " GRF:" << k << "\n";
}
#endif
while (activeGRF[k].activeLV.size()) {
LSLiveRange *lr = activeGRF[k].activeLV.front();
G4_VarBase *op;
int startsregnum = 0;
op = lr->getPhyReg(startsregnum);
unsigned startregnum = op->asGreg()->getRegNum();
unsigned endregnum = startregnum + lr->getTopDcl()->getNumRows() - 1;
vASSERT(startregnum <= (unsigned)k);
vASSERT(lr->getTopDcl()->getRegFile() != G4_INPUT);
// Free from the register buckect array
for (unsigned s = startregnum; s <= endregnum; s++) {
std::vector<LSLiveRange *>::iterator it = std::find(
activeGRF[s].activeLV.begin(), activeGRF[s].activeLV.end(), lr);
if (it != activeGRF[s].activeLV.end()) {
#ifdef DEBUG_VERBOSE_ON
COUT_ERROR << "SPILL: Free activeGRF from : "
<< (lr)->getTopDcl()->getName() << " GRF:" << s << "\n";
#endif
activeGRF[s].activeLV.erase(it);
}
}
#ifdef DEBUG_VERBOSE_ON
printLiveInterval(lr, false, builder);
#endif
// Free the allocated register
freeAllocedRegs(lr, true);
// Record spilled live range
if (std::find(spillLRs.begin(), spillLRs.end(), lr) == spillLRs.end()) {
spillLRs.push_back(lr);
}
// Remove spilled live range from active list
std::list<LSLiveRange *>::iterator activeListIter = active.begin();
while (activeListIter != active.end()) {
std::list<LSLiveRange *>::iterator nextIt = activeListIter;
nextIt++;
if ((*activeListIter) == lr) {
#ifdef DEBUG_VERBOSE_ON
COUT_ERROR << "SPILL: Free active lr: "
<< (*activeListIter)->getTopDcl()->getName() << "\n";
#endif
active.erase(activeListIter);
break;
}
activeListIter = nextIt;
}
}
}
}
bool globalLinearScan::spillFromActiveList(LSLiveRange *tlr,
std::list<LSLiveRange *> &spillLRs) {
int startGRF = findSpillCandidate(tlr);
if (startGRF == -1) {
#ifdef DEBUG_VERBOSE_ON
printActives();
#endif
return false;
}
freeSelectedRegistsers(startGRF, tlr, spillLRs);
return true;
}
void globalLinearScan::expireGlobalRanges(unsigned int idx) {
// active list is sorted in ascending order of starting index
while (active.size() > 0) {
unsigned int endIdx;
LSLiveRange *lr = active.front();
lr->getLastRef(endIdx);
if (endIdx <= idx) {
G4_VarBase *preg;
int subregnumword, subregnum;
preg = lr->getPhyReg(subregnumword);
if (preg) {
subregnum = LinearScanRA::convertSubRegOffFromWords(lr->getTopDcl(),
subregnumword);
// Mark the RegVar object of dcl as assigned to physical register
lr->getTopDcl()->getRegVar()->setPhyReg(preg, subregnum);
lr->setAssigned(true);
}
#ifdef DEBUG_VERBOSE_ON
printLiveInterval(lr, false, builder);
#endif
if (preg) {
unsigned startregnum = preg->asGreg()->getRegNum();
unsigned endregnum = startregnum + lr->getTopDcl()->getNumRows() - 1;
for (unsigned i = startregnum; i <= endregnum; i++) {
std::vector<LSLiveRange *>::iterator activeListIter =
activeGRF[i].activeLV.begin();
while (activeListIter != activeGRF[i].activeLV.end()) {
std::vector<LSLiveRange *>::iterator nextIt = activeListIter;
nextIt++;
if ((*activeListIter) == lr) {
activeGRF[i].activeLV.erase(activeListIter);
#ifdef DEBUG_VERBOSE_ON
COUT_ERROR << "Remove range " << lr->getTopDcl()->getName()
<< " from activeGRF: " << i << "\n";
#endif
break;
}
activeListIter = nextIt;
}
}
if (calleeSaveLR) {
unsigned int startCallerSave =
builder.kernel.stackCall.calleeSaveStart();
unsigned int endCallerSave =
startCallerSave + builder.kernel.stackCall.getNumCalleeSaveRegs();
for (unsigned i = startregnum; i <= endregnum; i++) {
if (i >= startCallerSave && i <= endCallerSave) {
calleeSaveLR->addForbidden(i);
}
}
}
}
// Free physical regs marked for this range
freeAllocedRegs(lr, true);
// Remove range from active list
active.pop_front();
} else {
// As soon as we find first range that ends after ids break loop
break;
}
}
}
void globalLinearScan::expireInputRanges(unsigned int global_idx) {
while (inputIntervals.size() > 0) {
LSInputLiveRange *lr = inputIntervals.front();
unsigned int endIdx = lr->getLrEndIdx();
if (endIdx <= global_idx) {
unsigned int regnum =
lr->getRegWordIdx() / builder.numEltPerGRF<Type_UW>();
unsigned int subRegInWord =
lr->getRegWordIdx() % builder.numEltPerGRF<Type_UW>();
// Free physical regs marked for this range
pregManager.freeRegs(regnum, subRegInWord, 1, endIdx);
#ifdef DEBUG_VERBOSE_ON
COUT_ERROR << "Expiring input r" << regnum << "." << subRegInWord << "\n";
#endif
// Remove range from inputIntervals list
inputIntervals.pop_front();
vASSERT(lr == activeGRF[regnum].activeInput.front());
activeGRF[regnum].activeInput.erase(
activeGRF[regnum].activeInput.begin());
} else {
// As soon as we find first range that ends after ids break loop
break;
}
}
}
BankAlign globalLinearScan::getBankAlign(LSLiveRange *lr) {
G4_Declare *dcl = lr->getTopDcl();
BankAlign bankAlign =
gra.isEvenAligned(dcl) ? BankAlign::Even : BankAlign::Either;
return bankAlign;
}
bool globalLinearScan::allocateRegsLinearScan(LSLiveRange *lr,
IR_Builder &builder) {
int regnum, subregnum;
unsigned int localRABound = 0;
unsigned int instID;
lr->getFirstRef(instID);
// Let local RA allocate only those ranges that need < 10 GRFs
// Larger ranges are not many and are best left to global RA
// as it can make a better judgement by considering the
// spill cost.
int nrows = 0;
int size = lr->getSizeInWords(builder);
G4_Declare *dcl = lr->getTopDcl();
G4_SubReg_Align subalign = gra.getSubRegAlign(dcl);
localRABound = numRegLRA - 1;
BankAlign bankAlign = getBankAlign(lr);
nrows = pregManager.findFreeRegs(size, bankAlign, subalign, regnum, subregnum,
startGRFReg, localRABound, instID,
lr->getForbidden());
if (nrows) {
#ifdef DEBUG_VERBOSE_ON
COUT_ERROR << lr->getTopDcl()->getName() << ":r" << regnum
<< " BANK: " << (int)bankAlign << "\n";
#endif
lr->setPhyReg(builder.phyregpool.getGreg(regnum), subregnum);
if (!builder.getOptions()->getOption(vISA_LSFristFit)) {
startGRFReg = (startGRFReg + nrows) % localRABound;
} else {
vASSERT(startGRFReg == 0);
}
return true;
} else if (!builder.getOptions()->getOption(vISA_LSFristFit)) {
startGRFReg = 0;
nrows = pregManager.findFreeRegs(size, bankAlign, subalign, regnum,
subregnum, startGRFReg, localRABound,
instID, lr->getForbidden());
if (nrows) {
#ifdef DEBUG_VERBOSE_ON
COUT_ERROR << lr->getTopDcl()->getName() << ":r" << regnum
<< " BANK: " << (int)bankAlign << "\n";
#endif
lr->setPhyReg(builder.phyregpool.getGreg(regnum), subregnum);
startGRFReg = (startGRFReg + nrows) % localRABound;
return true;
}
}
#ifdef DEBUG_VERBOSE_ON
COUT_ERROR << lr->getTopDcl()->getName() << ": failed to allocate"
<< "\n";
#endif
return false;
}
bool PhyRegsLocalRA::findFreeMultipleRegsForward(int regIdx, BankAlign align,
int ®num, int nrows,
int lastRowSize, int endReg,
int instID,
const bool *forbidden) {
int foundItem = 0;
int startReg = 0;
int i = regIdx;
int grfRows = 0;
bool multiSteps = nrows > 1;
if (lastRowSize % builder.numEltPerGRF<Type_UW>() == 0) {
grfRows = nrows;
} else {
grfRows = nrows - 1;
}
findRegisterCandiateWithAlignForward(i, align, multiSteps);
startReg = i;
while (i <= endReg + nrows - 1) {
if (isGRFAvailable(i) && !forbidden[i] && regBusyVector[i] == 0) {
foundItem++;
} else if (foundItem < grfRows) {
foundItem = 0;
i++;
findRegisterCandiateWithAlignForward(i, align, multiSteps);
startReg = i;
continue;
}
if (foundItem == grfRows) {
if (lastRowSize % builder.numEltPerGRF<Type_UW>() == 0) {
regnum = startReg;
return true;
} else {
if (i + 1 <= endReg + nrows - 1 && isGRFAvailable(i + 1) &&
!forbidden[i + 1] && (isWordBusy(i + 1, 0, lastRowSize) == false)) {
regnum = startReg;
return true;
} else {
foundItem = 0;
i++;
findRegisterCandiateWithAlignForward(i, align, multiSteps);
startReg = i;
continue;
}
}
}
i++;
}
return false;
}
bool PhyRegsLocalRA::findFreeSingleReg(int regIdx, int size, BankAlign align,
G4_SubReg_Align subalign, int ®num,
int &subregnum, int endReg,
const bool *forbidden) {
int i = regIdx;
bool found = false;
while (!found) {
if (i > endReg) //<= works
break;
// Align GRF
if ((align == BankAlign::Even) && (i % 2 != 0)) {
i++;
continue;
} else if ((align == BankAlign::Odd) && (i % 2 == 0)) {
i++;
continue;
} else if ((align == BankAlign::Even2GRF) && ((i % 4 >= 2))) {
i++;
continue;
} else if ((align == BankAlign::Odd2GRF) && ((i % 4 < 2))) {
i++;
continue;
}
if (isGRFAvailable(i, 1) && !forbidden[i]) {
found = findFreeSingleReg(i, subalign, regnum, subregnum, size);
if (found) {
return true;
}
}
i++;
}
return false;
}
int PhyRegsManager::findFreeRegs(int size, BankAlign align,
G4_SubReg_Align subalign, int ®num,
int &subregnum, int startRegNum, int endRegNum,
unsigned int instID, const bool *forbidden) {
int nrows = 0;
int lastRowSize = 0;
LocalRA::getRowInfo(size, nrows, lastRowSize, builder);
int startReg = startRegNum;
int endReg = endRegNum - nrows + 1;
bool found = false;
if (size >= (int)builder.numEltPerGRF<Type_UW>()) {
found = availableRegs.findFreeMultipleRegsForward(
startReg, align, regnum, nrows, lastRowSize, endReg, instID, forbidden);
if (found) {
subregnum = 0;
if (size % builder.numEltPerGRF<Type_UW>() == 0) {
availableRegs.setGRFBusy(regnum, nrows);
} else {
availableRegs.setGRFBusy(regnum, nrows - 1);
availableRegs.setWordBusy(regnum + nrows - 1, 0, lastRowSize);
}
}
} else {
found = availableRegs.findFreeSingleReg(
startReg, size, align, subalign, regnum, subregnum, endReg, forbidden);
if (found) {
availableRegs.setWordBusy(regnum, subregnum, size);
}
}
if (found) {
return nrows;
}
return 0;
}
|