1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808
|
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ART_COMPILER_OPTIMIZING_NODES_H_
#define ART_COMPILER_OPTIMIZING_NODES_H_
#include <algorithm>
#include <array>
#include <type_traits>
#include "art_method.h"
#include "base/arena_allocator.h"
#include "base/arena_bit_vector.h"
#include "base/arena_containers.h"
#include "base/arena_object.h"
#include "base/array_ref.h"
#include "base/intrusive_forward_list.h"
#include "base/iteration_range.h"
#include "base/macros.h"
#include "base/mutex.h"
#include "base/quasi_atomic.h"
#include "base/stl_util.h"
#include "base/transform_array_ref.h"
#include "block_namer.h"
#include "class_root.h"
#include "compilation_kind.h"
#include "data_type.h"
#include "deoptimization_kind.h"
#include "dex/dex_file.h"
#include "dex/dex_file_types.h"
#include "dex/invoke_type.h"
#include "dex/method_reference.h"
#include "entrypoints/quick/quick_entrypoints_enum.h"
#include "handle.h"
#include "handle_scope.h"
#include "intrinsics_enum.h"
#include "locations.h"
#include "mirror/class.h"
#include "mirror/method_type.h"
#include "offsets.h"
namespace art HIDDEN {
class ArenaStack;
class CodeGenerator;
class GraphChecker;
class HBasicBlock;
class HConstructorFence;
class HCurrentMethod;
class HDoubleConstant;
class HEnvironment;
class HFloatConstant;
class HGraphBuilder;
class HGraphVisitor;
class HInstruction;
class HIntConstant;
class HInvoke;
class HLongConstant;
class HNullConstant;
class HParameterValue;
class HPhi;
class HSuspendCheck;
class HTryBoundary;
class FieldInfo;
class LiveInterval;
class LocationSummary;
class ProfilingInfo;
class SlowPathCode;
class SsaBuilder;
namespace mirror {
class DexCache;
} // namespace mirror
static const int kDefaultNumberOfBlocks = 8;
static const int kDefaultNumberOfSuccessors = 2;
static const int kDefaultNumberOfPredecessors = 2;
static const int kDefaultNumberOfExceptionalPredecessors = 0;
static const int kDefaultNumberOfDominatedBlocks = 1;
static const int kDefaultNumberOfBackEdges = 1;
// The maximum (meaningful) distance (31) that can be used in an integer shift/rotate operation.
static constexpr int32_t kMaxIntShiftDistance = 0x1f;
// The maximum (meaningful) distance (63) that can be used in a long shift/rotate operation.
static constexpr int32_t kMaxLongShiftDistance = 0x3f;
static constexpr uint32_t kUnknownFieldIndex = static_cast<uint32_t>(-1);
static constexpr uint16_t kUnknownClassDefIndex = static_cast<uint16_t>(-1);
static constexpr InvokeType kInvalidInvokeType = static_cast<InvokeType>(-1);
static constexpr uint32_t kNoDexPc = -1;
inline bool IsSameDexFile(const DexFile& lhs, const DexFile& rhs) {
// For the purposes of the compiler, the dex files must actually be the same object
// if we want to safely treat them as the same. This is especially important for JIT
// as custom class loaders can open the same underlying file (or memory) multiple
// times and provide different class resolution but no two class loaders should ever
// use the same DexFile object - doing so is an unsupported hack that can lead to
// all sorts of weird failures.
return &lhs == &rhs;
}
enum IfCondition {
// All types.
kCondEQ, // ==
kCondNE, // !=
// Signed integers and floating-point numbers.
kCondLT, // <
kCondLE, // <=
kCondGT, // >
kCondGE, // >=
// Unsigned integers.
kCondB, // <
kCondBE, // <=
kCondA, // >
kCondAE, // >=
// First and last aliases.
kCondFirst = kCondEQ,
kCondLast = kCondAE,
};
enum GraphAnalysisResult {
kAnalysisSkipped,
kAnalysisInvalidBytecode,
kAnalysisFailThrowCatchLoop,
kAnalysisFailAmbiguousArrayOp,
kAnalysisFailIrreducibleLoopAndStringInit,
kAnalysisFailPhiEquivalentInOsr,
kAnalysisSuccess,
};
template <typename T>
static inline typename std::make_unsigned<T>::type MakeUnsigned(T x) {
return static_cast<typename std::make_unsigned<T>::type>(x);
}
class HInstructionList : public ValueObject {
public:
HInstructionList() : first_instruction_(nullptr), last_instruction_(nullptr) {}
void AddInstruction(HInstruction* instruction);
void RemoveInstruction(HInstruction* instruction);
// Insert `instruction` before/after an existing instruction `cursor`.
void InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor);
void InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor);
// Return true if this list contains `instruction`.
bool Contains(HInstruction* instruction) const;
// Return true if `instruction1` is found before `instruction2` in
// this instruction list and false otherwise. Abort if none
// of these instructions is found.
bool FoundBefore(const HInstruction* instruction1,
const HInstruction* instruction2) const;
bool IsEmpty() const { return first_instruction_ == nullptr; }
void Clear() { first_instruction_ = last_instruction_ = nullptr; }
// Update the block of all instructions to be `block`.
void SetBlockOfInstructions(HBasicBlock* block) const;
void AddAfter(HInstruction* cursor, const HInstructionList& instruction_list);
void AddBefore(HInstruction* cursor, const HInstructionList& instruction_list);
void Add(const HInstructionList& instruction_list);
// Return the number of instructions in the list. This is an expensive operation.
size_t CountSize() const;
private:
HInstruction* first_instruction_;
HInstruction* last_instruction_;
friend class HBasicBlock;
friend class HGraph;
friend class HInstruction;
friend class HInstructionIterator;
friend class HInstructionIteratorHandleChanges;
friend class HBackwardInstructionIterator;
DISALLOW_COPY_AND_ASSIGN(HInstructionList);
};
class ReferenceTypeInfo : ValueObject {
public:
using TypeHandle = Handle<mirror::Class>;
static ReferenceTypeInfo Create(TypeHandle type_handle, bool is_exact);
static ReferenceTypeInfo Create(TypeHandle type_handle) REQUIRES_SHARED(Locks::mutator_lock_) {
return Create(type_handle, type_handle->CannotBeAssignedFromOtherTypes());
}
static ReferenceTypeInfo CreateUnchecked(TypeHandle type_handle, bool is_exact) {
return ReferenceTypeInfo(type_handle, is_exact);
}
static ReferenceTypeInfo CreateInvalid() { return ReferenceTypeInfo(); }
static bool IsValidHandle(TypeHandle handle) {
return handle.GetReference() != nullptr;
}
bool IsValid() const {
return IsValidHandle(type_handle_);
}
bool IsExact() const { return is_exact_; }
bool IsObjectClass() const REQUIRES_SHARED(Locks::mutator_lock_) {
DCHECK(IsValid());
return GetTypeHandle()->IsObjectClass();
}
bool IsStringClass() const REQUIRES_SHARED(Locks::mutator_lock_) {
DCHECK(IsValid());
return GetTypeHandle()->IsStringClass();
}
bool IsObjectArray() const REQUIRES_SHARED(Locks::mutator_lock_) {
DCHECK(IsValid());
return IsArrayClass() && GetTypeHandle()->GetComponentType()->IsObjectClass();
}
bool IsInterface() const REQUIRES_SHARED(Locks::mutator_lock_) {
DCHECK(IsValid());
return GetTypeHandle()->IsInterface();
}
bool IsArrayClass() const REQUIRES_SHARED(Locks::mutator_lock_) {
DCHECK(IsValid());
return GetTypeHandle()->IsArrayClass();
}
bool IsPrimitiveArrayClass() const REQUIRES_SHARED(Locks::mutator_lock_) {
DCHECK(IsValid());
return GetTypeHandle()->IsPrimitiveArray();
}
bool IsNonPrimitiveArrayClass() const REQUIRES_SHARED(Locks::mutator_lock_) {
DCHECK(IsValid());
return GetTypeHandle()->IsArrayClass() && !GetTypeHandle()->IsPrimitiveArray();
}
bool CanArrayHold(ReferenceTypeInfo rti) const REQUIRES_SHARED(Locks::mutator_lock_) {
DCHECK(IsValid());
if (!IsExact()) return false;
if (!IsArrayClass()) return false;
return GetTypeHandle()->GetComponentType()->IsAssignableFrom(rti.GetTypeHandle().Get());
}
bool CanArrayHoldValuesOf(ReferenceTypeInfo rti) const REQUIRES_SHARED(Locks::mutator_lock_) {
DCHECK(IsValid());
if (!IsExact()) return false;
if (!IsArrayClass()) return false;
if (!rti.IsArrayClass()) return false;
return GetTypeHandle()->GetComponentType()->IsAssignableFrom(
rti.GetTypeHandle()->GetComponentType());
}
Handle<mirror::Class> GetTypeHandle() const { return type_handle_; }
bool IsSupertypeOf(ReferenceTypeInfo rti) const REQUIRES_SHARED(Locks::mutator_lock_) {
DCHECK(IsValid());
DCHECK(rti.IsValid());
return GetTypeHandle()->IsAssignableFrom(rti.GetTypeHandle().Get());
}
// Returns true if the type information provide the same amount of details.
// Note that it does not mean that the instructions have the same actual type
// (because the type can be the result of a merge).
bool IsEqual(ReferenceTypeInfo rti) const REQUIRES_SHARED(Locks::mutator_lock_) {
if (!IsValid() && !rti.IsValid()) {
// Invalid types are equal.
return true;
}
if (!IsValid() || !rti.IsValid()) {
// One is valid, the other not.
return false;
}
return IsExact() == rti.IsExact()
&& GetTypeHandle().Get() == rti.GetTypeHandle().Get();
}
private:
ReferenceTypeInfo() : type_handle_(TypeHandle()), is_exact_(false) {}
ReferenceTypeInfo(TypeHandle type_handle, bool is_exact)
: type_handle_(type_handle), is_exact_(is_exact) { }
// The class of the object.
TypeHandle type_handle_;
// Whether or not the type is exact or a superclass of the actual type.
// Whether or not we have any information about this type.
bool is_exact_;
};
std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs);
class HandleCache {
public:
explicit HandleCache(VariableSizedHandleScope* handles) : handles_(handles) { }
VariableSizedHandleScope* GetHandles() { return handles_; }
template <typename T>
MutableHandle<T> NewHandle(T* object) REQUIRES_SHARED(Locks::mutator_lock_) {
return handles_->NewHandle(object);
}
template <typename T>
MutableHandle<T> NewHandle(ObjPtr<T> object) REQUIRES_SHARED(Locks::mutator_lock_) {
return handles_->NewHandle(object);
}
ReferenceTypeInfo::TypeHandle GetObjectClassHandle() {
return GetRootHandle(ClassRoot::kJavaLangObject, &object_class_handle_);
}
ReferenceTypeInfo::TypeHandle GetClassClassHandle() {
return GetRootHandle(ClassRoot::kJavaLangClass, &class_class_handle_);
}
ReferenceTypeInfo::TypeHandle GetMethodHandleClassHandle() {
return GetRootHandle(ClassRoot::kJavaLangInvokeMethodHandleImpl, &method_handle_class_handle_);
}
ReferenceTypeInfo::TypeHandle GetMethodTypeClassHandle() {
return GetRootHandle(ClassRoot::kJavaLangInvokeMethodType, &method_type_class_handle_);
}
ReferenceTypeInfo::TypeHandle GetStringClassHandle() {
return GetRootHandle(ClassRoot::kJavaLangString, &string_class_handle_);
}
ReferenceTypeInfo::TypeHandle GetThrowableClassHandle() {
return GetRootHandle(ClassRoot::kJavaLangThrowable, &throwable_class_handle_);
}
private:
inline ReferenceTypeInfo::TypeHandle GetRootHandle(ClassRoot class_root,
ReferenceTypeInfo::TypeHandle* cache) {
if (UNLIKELY(!ReferenceTypeInfo::IsValidHandle(*cache))) {
*cache = CreateRootHandle(handles_, class_root);
}
return *cache;
}
static ReferenceTypeInfo::TypeHandle CreateRootHandle(VariableSizedHandleScope* handles,
ClassRoot class_root);
VariableSizedHandleScope* handles_;
ReferenceTypeInfo::TypeHandle object_class_handle_;
ReferenceTypeInfo::TypeHandle class_class_handle_;
ReferenceTypeInfo::TypeHandle method_handle_class_handle_;
ReferenceTypeInfo::TypeHandle method_type_class_handle_;
ReferenceTypeInfo::TypeHandle string_class_handle_;
ReferenceTypeInfo::TypeHandle throwable_class_handle_;
};
// Control-flow graph of a method. Contains a list of basic blocks.
class HGraph : public ArenaObject<kArenaAllocGraph> {
public:
HGraph(ArenaAllocator* allocator,
ArenaStack* arena_stack,
VariableSizedHandleScope* handles,
const DexFile& dex_file,
uint32_t method_idx,
InstructionSet instruction_set,
InvokeType invoke_type = kInvalidInvokeType,
bool dead_reference_safe = false,
bool debuggable = false,
CompilationKind compilation_kind = CompilationKind::kOptimized,
int start_instruction_id = 0)
: allocator_(allocator),
arena_stack_(arena_stack),
handle_cache_(handles),
blocks_(allocator->Adapter(kArenaAllocBlockList)),
reverse_post_order_(allocator->Adapter(kArenaAllocReversePostOrder)),
linear_order_(allocator->Adapter(kArenaAllocLinearOrder)),
reachability_graph_(allocator, 0, 0, true, kArenaAllocReachabilityGraph),
entry_block_(nullptr),
exit_block_(nullptr),
maximum_number_of_out_vregs_(0),
number_of_vregs_(0),
number_of_in_vregs_(0),
temporaries_vreg_slots_(0),
has_bounds_checks_(false),
has_try_catch_(false),
has_monitor_operations_(false),
has_simd_(false),
has_loops_(false),
has_irreducible_loops_(false),
has_direct_critical_native_call_(false),
has_always_throwing_invokes_(false),
dead_reference_safe_(dead_reference_safe),
debuggable_(debuggable),
current_instruction_id_(start_instruction_id),
dex_file_(dex_file),
method_idx_(method_idx),
invoke_type_(invoke_type),
in_ssa_form_(false),
number_of_cha_guards_(0),
instruction_set_(instruction_set),
cached_null_constant_(nullptr),
cached_int_constants_(std::less<int32_t>(), allocator->Adapter(kArenaAllocConstantsMap)),
cached_float_constants_(std::less<int32_t>(), allocator->Adapter(kArenaAllocConstantsMap)),
cached_long_constants_(std::less<int64_t>(), allocator->Adapter(kArenaAllocConstantsMap)),
cached_double_constants_(std::less<int64_t>(), allocator->Adapter(kArenaAllocConstantsMap)),
cached_current_method_(nullptr),
art_method_(nullptr),
compilation_kind_(compilation_kind),
cha_single_implementation_list_(allocator->Adapter(kArenaAllocCHA)) {
blocks_.reserve(kDefaultNumberOfBlocks);
}
std::ostream& Dump(std::ostream& os,
CodeGenerator* codegen,
std::optional<std::reference_wrapper<const BlockNamer>> namer = std::nullopt);
ArenaAllocator* GetAllocator() const { return allocator_; }
ArenaStack* GetArenaStack() const { return arena_stack_; }
HandleCache* GetHandleCache() { return &handle_cache_; }
const ArenaVector<HBasicBlock*>& GetBlocks() const { return blocks_; }
// An iterator to only blocks that are still actually in the graph (when
// blocks are removed they are replaced with 'nullptr' in GetBlocks to
// simplify block-id assignment and avoid memmoves in the block-list).
IterationRange<FilterNull<ArenaVector<HBasicBlock*>::const_iterator>> GetActiveBlocks() const {
return FilterOutNull(MakeIterationRange(GetBlocks()));
}
bool IsInSsaForm() const { return in_ssa_form_; }
void SetInSsaForm() { in_ssa_form_ = true; }
HBasicBlock* GetEntryBlock() const { return entry_block_; }
HBasicBlock* GetExitBlock() const { return exit_block_; }
bool HasExitBlock() const { return exit_block_ != nullptr; }
void SetEntryBlock(HBasicBlock* block) { entry_block_ = block; }
void SetExitBlock(HBasicBlock* block) { exit_block_ = block; }
void AddBlock(HBasicBlock* block);
void ComputeDominanceInformation();
void ClearDominanceInformation();
void ComputeReachabilityInformation();
void ClearReachabilityInformation();
void ClearLoopInformation();
void FindBackEdges(ArenaBitVector* visited);
GraphAnalysisResult BuildDominatorTree();
void SimplifyCFG();
void SimplifyCatchBlocks();
// Analyze all natural loops in this graph. Returns a code specifying that it
// was successful or the reason for failure. The method will fail if a loop
// is a throw-catch loop, i.e. the header is a catch block.
GraphAnalysisResult AnalyzeLoops() const;
// Iterate over blocks to compute try block membership. Needs reverse post
// order and loop information.
void ComputeTryBlockInformation();
// Inline this graph in `outer_graph`, replacing the given `invoke` instruction.
// Returns the instruction to replace the invoke expression or null if the
// invoke is for a void method. Note that the caller is responsible for replacing
// and removing the invoke instruction.
HInstruction* InlineInto(HGraph* outer_graph, HInvoke* invoke);
// Update the loop and try membership of `block`, which was spawned from `reference`.
// In case `reference` is a back edge, `replace_if_back_edge` notifies whether `block`
// should be the new back edge.
// `has_more_specific_try_catch_info` will be set to true when inlining a try catch.
void UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
HBasicBlock* reference,
bool replace_if_back_edge,
bool has_more_specific_try_catch_info = false);
// Need to add a couple of blocks to test if the loop body is entered and
// put deoptimization instructions, etc.
void TransformLoopHeaderForBCE(HBasicBlock* header);
// Adds a new loop directly after the loop with the given header and exit.
// Returns the new preheader.
HBasicBlock* TransformLoopForVectorization(HBasicBlock* header,
HBasicBlock* body,
HBasicBlock* exit);
// Removes `block` from the graph. Assumes `block` has been disconnected from
// other blocks and has no instructions or phis.
void DeleteDeadEmptyBlock(HBasicBlock* block);
// Splits the edge between `block` and `successor` while preserving the
// indices in the predecessor/successor lists. If there are multiple edges
// between the blocks, the lowest indices are used.
// Returns the new block which is empty and has the same dex pc as `successor`.
HBasicBlock* SplitEdge(HBasicBlock* block, HBasicBlock* successor);
void SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor);
// Splits the edge between `block` and `successor` and then updates the graph's RPO to keep
// consistency without recomputing the whole graph.
HBasicBlock* SplitEdgeAndUpdateRPO(HBasicBlock* block, HBasicBlock* successor);
void OrderLoopHeaderPredecessors(HBasicBlock* header);
// Transform a loop into a format with a single preheader.
//
// Each phi in the header should be split: original one in the header should only hold
// inputs reachable from the back edges and a single input from the preheader. The newly created
// phi in the preheader should collate the inputs from the original multiple incoming blocks.
//
// Loops in the graph typically have a single preheader, so this method is used to "repair" loops
// that no longer have this property.
void TransformLoopToSinglePreheaderFormat(HBasicBlock* header);
void SimplifyLoop(HBasicBlock* header);
int32_t GetNextInstructionId() {
CHECK_NE(current_instruction_id_, INT32_MAX);
return current_instruction_id_++;
}
int32_t GetCurrentInstructionId() const {
return current_instruction_id_;
}
void SetCurrentInstructionId(int32_t id) {
CHECK_GE(id, current_instruction_id_);
current_instruction_id_ = id;
}
uint16_t GetMaximumNumberOfOutVRegs() const {
return maximum_number_of_out_vregs_;
}
void SetMaximumNumberOfOutVRegs(uint16_t new_value) {
maximum_number_of_out_vregs_ = new_value;
}
void UpdateMaximumNumberOfOutVRegs(uint16_t other_value) {
maximum_number_of_out_vregs_ = std::max(maximum_number_of_out_vregs_, other_value);
}
void UpdateTemporariesVRegSlots(size_t slots) {
temporaries_vreg_slots_ = std::max(slots, temporaries_vreg_slots_);
}
size_t GetTemporariesVRegSlots() const {
DCHECK(!in_ssa_form_);
return temporaries_vreg_slots_;
}
void SetNumberOfVRegs(uint16_t number_of_vregs) {
number_of_vregs_ = number_of_vregs;
}
uint16_t GetNumberOfVRegs() const {
return number_of_vregs_;
}
void SetNumberOfInVRegs(uint16_t value) {
number_of_in_vregs_ = value;
}
uint16_t GetNumberOfInVRegs() const {
return number_of_in_vregs_;
}
uint16_t GetNumberOfLocalVRegs() const {
DCHECK(!in_ssa_form_);
return number_of_vregs_ - number_of_in_vregs_;
}
const ArenaVector<HBasicBlock*>& GetReversePostOrder() const {
return reverse_post_order_;
}
ArrayRef<HBasicBlock* const> GetReversePostOrderSkipEntryBlock() const {
DCHECK(GetReversePostOrder()[0] == entry_block_);
return ArrayRef<HBasicBlock* const>(GetReversePostOrder()).SubArray(1);
}
IterationRange<ArenaVector<HBasicBlock*>::const_reverse_iterator> GetPostOrder() const {
return ReverseRange(GetReversePostOrder());
}
const ArenaVector<HBasicBlock*>& GetLinearOrder() const {
return linear_order_;
}
IterationRange<ArenaVector<HBasicBlock*>::const_reverse_iterator> GetLinearPostOrder() const {
return ReverseRange(GetLinearOrder());
}
bool HasBoundsChecks() const {
return has_bounds_checks_;
}
void SetHasBoundsChecks(bool value) {
has_bounds_checks_ = value;
}
// Returns true if dest is reachable from source, using either blocks or block-ids.
bool PathBetween(const HBasicBlock* source, const HBasicBlock* dest) const;
bool PathBetween(uint32_t source_id, uint32_t dest_id) const;
// Is the code known to be robust against eliminating dead references
// and the effects of early finalization?
bool IsDeadReferenceSafe() const { return dead_reference_safe_; }
void MarkDeadReferenceUnsafe() { dead_reference_safe_ = false; }
bool IsDebuggable() const { return debuggable_; }
// Returns a constant of the given type and value. If it does not exist
// already, it is created and inserted into the graph. This method is only for
// integral types.
HConstant* GetConstant(DataType::Type type, int64_t value, uint32_t dex_pc = kNoDexPc);
// TODO: This is problematic for the consistency of reference type propagation
// because it can be created anytime after the pass and thus it will be left
// with an invalid type.
HNullConstant* GetNullConstant(uint32_t dex_pc = kNoDexPc);
HIntConstant* GetIntConstant(int32_t value, uint32_t dex_pc = kNoDexPc) {
return CreateConstant(value, &cached_int_constants_, dex_pc);
}
HLongConstant* GetLongConstant(int64_t value, uint32_t dex_pc = kNoDexPc) {
return CreateConstant(value, &cached_long_constants_, dex_pc);
}
HFloatConstant* GetFloatConstant(float value, uint32_t dex_pc = kNoDexPc) {
return CreateConstant(bit_cast<int32_t, float>(value), &cached_float_constants_, dex_pc);
}
HDoubleConstant* GetDoubleConstant(double value, uint32_t dex_pc = kNoDexPc) {
return CreateConstant(bit_cast<int64_t, double>(value), &cached_double_constants_, dex_pc);
}
HCurrentMethod* GetCurrentMethod();
const DexFile& GetDexFile() const {
return dex_file_;
}
uint32_t GetMethodIdx() const {
return method_idx_;
}
// Get the method name (without the signature), e.g. "<init>"
const char* GetMethodName() const;
// Get the pretty method name (class + name + optionally signature).
std::string PrettyMethod(bool with_signature = true) const;
InvokeType GetInvokeType() const {
return invoke_type_;
}
InstructionSet GetInstructionSet() const {
return instruction_set_;
}
bool IsCompilingOsr() const { return compilation_kind_ == CompilationKind::kOsr; }
bool IsCompilingBaseline() const { return compilation_kind_ == CompilationKind::kBaseline; }
CompilationKind GetCompilationKind() const { return compilation_kind_; }
ArenaSet<ArtMethod*>& GetCHASingleImplementationList() {
return cha_single_implementation_list_;
}
// In case of OSR we intend to use SuspendChecks as an entry point to the
// function; for debuggable graphs we might deoptimize to interpreter from
// SuspendChecks. In these cases we should always generate code for them.
bool SuspendChecksAreAllowedToNoOp() const {
return !IsDebuggable() && !IsCompilingOsr();
}
void AddCHASingleImplementationDependency(ArtMethod* method) {
cha_single_implementation_list_.insert(method);
}
bool HasShouldDeoptimizeFlag() const {
return number_of_cha_guards_ != 0 || debuggable_;
}
bool HasTryCatch() const { return has_try_catch_; }
void SetHasTryCatch(bool value) { has_try_catch_ = value; }
bool HasMonitorOperations() const { return has_monitor_operations_; }
void SetHasMonitorOperations(bool value) { has_monitor_operations_ = value; }
bool HasSIMD() const { return has_simd_; }
void SetHasSIMD(bool value) { has_simd_ = value; }
bool HasLoops() const { return has_loops_; }
void SetHasLoops(bool value) { has_loops_ = value; }
bool HasIrreducibleLoops() const { return has_irreducible_loops_; }
void SetHasIrreducibleLoops(bool value) { has_irreducible_loops_ = value; }
bool HasDirectCriticalNativeCall() const { return has_direct_critical_native_call_; }
void SetHasDirectCriticalNativeCall(bool value) { has_direct_critical_native_call_ = value; }
bool HasAlwaysThrowingInvokes() const { return has_always_throwing_invokes_; }
void SetHasAlwaysThrowingInvokes(bool value) { has_always_throwing_invokes_ = value; }
ArtMethod* GetArtMethod() const { return art_method_; }
void SetArtMethod(ArtMethod* method) { art_method_ = method; }
void SetProfilingInfo(ProfilingInfo* info) { profiling_info_ = info; }
ProfilingInfo* GetProfilingInfo() const { return profiling_info_; }
// Returns an instruction with the opposite Boolean value from 'cond'.
// The instruction has been inserted into the graph, either as a constant, or
// before cursor.
HInstruction* InsertOppositeCondition(HInstruction* cond, HInstruction* cursor);
ReferenceTypeInfo GetInexactObjectRti() {
return ReferenceTypeInfo::Create(handle_cache_.GetObjectClassHandle(), /* is_exact= */ false);
}
uint32_t GetNumberOfCHAGuards() const { return number_of_cha_guards_; }
void SetNumberOfCHAGuards(uint32_t num) { number_of_cha_guards_ = num; }
void IncrementNumberOfCHAGuards() { number_of_cha_guards_++; }
private:
void RemoveDeadBlocksInstructionsAsUsersAndDisconnect(const ArenaBitVector& visited) const;
void RemoveDeadBlocks(const ArenaBitVector& visited);
template <class InstructionType, typename ValueType>
InstructionType* CreateConstant(ValueType value,
ArenaSafeMap<ValueType, InstructionType*>* cache,
uint32_t dex_pc = kNoDexPc) {
// Try to find an existing constant of the given value.
InstructionType* constant = nullptr;
auto cached_constant = cache->find(value);
if (cached_constant != cache->end()) {
constant = cached_constant->second;
}
// If not found or previously deleted, create and cache a new instruction.
// Don't bother reviving a previously deleted instruction, for simplicity.
if (constant == nullptr || constant->GetBlock() == nullptr) {
constant = new (allocator_) InstructionType(value, dex_pc);
cache->Overwrite(value, constant);
InsertConstant(constant);
}
return constant;
}
void InsertConstant(HConstant* instruction);
// Cache a float constant into the graph. This method should only be
// called by the SsaBuilder when creating "equivalent" instructions.
void CacheFloatConstant(HFloatConstant* constant);
// See CacheFloatConstant comment.
void CacheDoubleConstant(HDoubleConstant* constant);
ArenaAllocator* const allocator_;
ArenaStack* const arena_stack_;
HandleCache handle_cache_;
// List of blocks in insertion order.
ArenaVector<HBasicBlock*> blocks_;
// List of blocks to perform a reverse post order tree traversal.
ArenaVector<HBasicBlock*> reverse_post_order_;
// List of blocks to perform a linear order tree traversal. Unlike the reverse
// post order, this order is not incrementally kept up-to-date.
ArenaVector<HBasicBlock*> linear_order_;
// Reachability graph for checking connectedness between nodes. Acts as a partitioned vector where
// each RoundUp(blocks_.size(), BitVector::kWordBits) is the reachability of each node.
ArenaBitVectorArray reachability_graph_;
HBasicBlock* entry_block_;
HBasicBlock* exit_block_;
// The maximum number of virtual registers arguments passed to a HInvoke in this graph.
uint16_t maximum_number_of_out_vregs_;
// The number of virtual registers in this method. Contains the parameters.
uint16_t number_of_vregs_;
// The number of virtual registers used by parameters of this method.
uint16_t number_of_in_vregs_;
// Number of vreg size slots that the temporaries use (used in baseline compiler).
size_t temporaries_vreg_slots_;
// Flag whether there are bounds checks in the graph. We can skip
// BCE if it's false.
bool has_bounds_checks_;
// Flag whether there are try/catch blocks in the graph. We will skip
// try/catch-related passes if it's false.
bool has_try_catch_;
// Flag whether there are any HMonitorOperation in the graph. If yes this will mandate
// DexRegisterMap to be present to allow deadlock analysis for non-debuggable code.
bool has_monitor_operations_;
// Flag whether SIMD instructions appear in the graph. If true, the
// code generators may have to be more careful spilling the wider
// contents of SIMD registers.
bool has_simd_;
// Flag whether there are any loops in the graph. We can skip loop
// optimization if it's false.
bool has_loops_;
// Flag whether there are any irreducible loops in the graph.
bool has_irreducible_loops_;
// Flag whether there are any direct calls to native code registered
// for @CriticalNative methods.
bool has_direct_critical_native_call_;
// Flag whether the graph contains invokes that always throw.
bool has_always_throwing_invokes_;
// Is the code known to be robust against eliminating dead references
// and the effects of early finalization? If false, dead reference variables
// are kept if they might be visible to the garbage collector.
// Currently this means that the class was declared to be dead-reference-safe,
// the method accesses no reachability-sensitive fields or data, and the same
// is true for any methods that were inlined into the current one.
bool dead_reference_safe_;
// Indicates whether the graph should be compiled in a way that
// ensures full debuggability. If false, we can apply more
// aggressive optimizations that may limit the level of debugging.
const bool debuggable_;
// The current id to assign to a newly added instruction. See HInstruction.id_.
int32_t current_instruction_id_;
// The dex file from which the method is from.
const DexFile& dex_file_;
// The method index in the dex file.
const uint32_t method_idx_;
// If inlined, this encodes how the callee is being invoked.
const InvokeType invoke_type_;
// Whether the graph has been transformed to SSA form. Only used
// in debug mode to ensure we are not using properties only valid
// for non-SSA form (like the number of temporaries).
bool in_ssa_form_;
// Number of CHA guards in the graph. Used to short-circuit the
// CHA guard optimization pass when there is no CHA guard left.
uint32_t number_of_cha_guards_;
const InstructionSet instruction_set_;
// Cached constants.
HNullConstant* cached_null_constant_;
ArenaSafeMap<int32_t, HIntConstant*> cached_int_constants_;
ArenaSafeMap<int32_t, HFloatConstant*> cached_float_constants_;
ArenaSafeMap<int64_t, HLongConstant*> cached_long_constants_;
ArenaSafeMap<int64_t, HDoubleConstant*> cached_double_constants_;
HCurrentMethod* cached_current_method_;
// The ArtMethod this graph is for. Note that for AOT, it may be null,
// for example for methods whose declaring class could not be resolved
// (such as when the superclass could not be found).
ArtMethod* art_method_;
// The `ProfilingInfo` associated with the method being compiled.
ProfilingInfo* profiling_info_;
// How we are compiling the graph: either optimized, osr, or baseline.
// For osr, we will make all loops seen as irreducible and emit special
// stack maps to mark compiled code entries which the interpreter can
// directly jump to.
const CompilationKind compilation_kind_;
// List of methods that are assumed to have single implementation.
ArenaSet<ArtMethod*> cha_single_implementation_list_;
friend class SsaBuilder; // For caching constants.
friend class SsaLivenessAnalysis; // For the linear order.
friend class HInliner; // For the reverse post order.
ART_FRIEND_TEST(GraphTest, IfSuccessorSimpleJoinBlock1);
DISALLOW_COPY_AND_ASSIGN(HGraph);
};
class HLoopInformation : public ArenaObject<kArenaAllocLoopInfo> {
public:
HLoopInformation(HBasicBlock* header, HGraph* graph)
: header_(header),
suspend_check_(nullptr),
irreducible_(false),
contains_irreducible_loop_(false),
back_edges_(graph->GetAllocator()->Adapter(kArenaAllocLoopInfoBackEdges)),
// Make bit vector growable, as the number of blocks may change.
blocks_(graph->GetAllocator(),
graph->GetBlocks().size(),
true,
kArenaAllocLoopInfoBackEdges) {
back_edges_.reserve(kDefaultNumberOfBackEdges);
}
bool IsIrreducible() const { return irreducible_; }
bool ContainsIrreducibleLoop() const { return contains_irreducible_loop_; }
void Dump(std::ostream& os);
HBasicBlock* GetHeader() const {
return header_;
}
void SetHeader(HBasicBlock* block) {
header_ = block;
}
HSuspendCheck* GetSuspendCheck() const { return suspend_check_; }
void SetSuspendCheck(HSuspendCheck* check) { suspend_check_ = check; }
bool HasSuspendCheck() const { return suspend_check_ != nullptr; }
void AddBackEdge(HBasicBlock* back_edge) {
back_edges_.push_back(back_edge);
}
void RemoveBackEdge(HBasicBlock* back_edge) {
RemoveElement(back_edges_, back_edge);
}
bool IsBackEdge(const HBasicBlock& block) const {
return ContainsElement(back_edges_, &block);
}
size_t NumberOfBackEdges() const {
return back_edges_.size();
}
HBasicBlock* GetPreHeader() const;
const ArenaVector<HBasicBlock*>& GetBackEdges() const {
return back_edges_;
}
// Returns the lifetime position of the back edge that has the
// greatest lifetime position.
size_t GetLifetimeEnd() const;
void ReplaceBackEdge(HBasicBlock* existing, HBasicBlock* new_back_edge) {
ReplaceElement(back_edges_, existing, new_back_edge);
}
// Finds blocks that are part of this loop.
void Populate();
// Updates blocks population of the loop and all of its outer' ones recursively after the
// population of the inner loop is updated.
void PopulateInnerLoopUpwards(HLoopInformation* inner_loop);
// Returns whether this loop information contains `block`.
// Note that this loop information *must* be populated before entering this function.
bool Contains(const HBasicBlock& block) const;
// Returns whether this loop information is an inner loop of `other`.
// Note that `other` *must* be populated before entering this function.
bool IsIn(const HLoopInformation& other) const;
// Returns true if instruction is not defined within this loop.
bool IsDefinedOutOfTheLoop(HInstruction* instruction) const;
const ArenaBitVector& GetBlocks() const { return blocks_; }
void Add(HBasicBlock* block);
void Remove(HBasicBlock* block);
void ClearAllBlocks() {
blocks_.ClearAllBits();
}
bool HasBackEdgeNotDominatedByHeader() const;
bool IsPopulated() const {
return blocks_.GetHighestBitSet() != -1;
}
bool DominatesAllBackEdges(HBasicBlock* block);
bool HasExitEdge() const;
// Resets back edge and blocks-in-loop data.
void ResetBasicBlockData() {
back_edges_.clear();
ClearAllBlocks();
}
private:
// Internal recursive implementation of `Populate`.
void PopulateRecursive(HBasicBlock* block);
void PopulateIrreducibleRecursive(HBasicBlock* block, ArenaBitVector* finalized);
HBasicBlock* header_;
HSuspendCheck* suspend_check_;
bool irreducible_;
bool contains_irreducible_loop_;
ArenaVector<HBasicBlock*> back_edges_;
ArenaBitVector blocks_;
DISALLOW_COPY_AND_ASSIGN(HLoopInformation);
};
// Stores try/catch information for basic blocks.
// Note that HGraph is constructed so that catch blocks cannot simultaneously
// be try blocks.
class TryCatchInformation : public ArenaObject<kArenaAllocTryCatchInfo> {
public:
// Try block information constructor.
explicit TryCatchInformation(const HTryBoundary& try_entry)
: try_entry_(&try_entry),
catch_dex_file_(nullptr),
catch_type_index_(dex::TypeIndex::Invalid()) {
DCHECK(try_entry_ != nullptr);
}
// Catch block information constructor.
TryCatchInformation(dex::TypeIndex catch_type_index, const DexFile& dex_file)
: try_entry_(nullptr),
catch_dex_file_(&dex_file),
catch_type_index_(catch_type_index) {}
bool IsTryBlock() const { return try_entry_ != nullptr; }
const HTryBoundary& GetTryEntry() const {
DCHECK(IsTryBlock());
return *try_entry_;
}
bool IsCatchBlock() const { return catch_dex_file_ != nullptr; }
bool IsValidTypeIndex() const {
DCHECK(IsCatchBlock());
return catch_type_index_.IsValid();
}
dex::TypeIndex GetCatchTypeIndex() const {
DCHECK(IsCatchBlock());
return catch_type_index_;
}
const DexFile& GetCatchDexFile() const {
DCHECK(IsCatchBlock());
return *catch_dex_file_;
}
void SetInvalidTypeIndex() {
catch_type_index_ = dex::TypeIndex::Invalid();
}
private:
// One of possibly several TryBoundary instructions entering the block's try.
// Only set for try blocks.
const HTryBoundary* try_entry_;
// Exception type information. Only set for catch blocks.
const DexFile* catch_dex_file_;
dex::TypeIndex catch_type_index_;
};
static constexpr size_t kNoLifetime = -1;
static constexpr uint32_t kInvalidBlockId = static_cast<uint32_t>(-1);
// A block in a method. Contains the list of instructions represented
// as a double linked list. Each block knows its predecessors and
// successors.
class HBasicBlock : public ArenaObject<kArenaAllocBasicBlock> {
public:
explicit HBasicBlock(HGraph* graph, uint32_t dex_pc = kNoDexPc)
: graph_(graph),
predecessors_(graph->GetAllocator()->Adapter(kArenaAllocPredecessors)),
successors_(graph->GetAllocator()->Adapter(kArenaAllocSuccessors)),
loop_information_(nullptr),
dominator_(nullptr),
dominated_blocks_(graph->GetAllocator()->Adapter(kArenaAllocDominated)),
block_id_(kInvalidBlockId),
dex_pc_(dex_pc),
lifetime_start_(kNoLifetime),
lifetime_end_(kNoLifetime),
try_catch_information_(nullptr) {
predecessors_.reserve(kDefaultNumberOfPredecessors);
successors_.reserve(kDefaultNumberOfSuccessors);
dominated_blocks_.reserve(kDefaultNumberOfDominatedBlocks);
}
const ArenaVector<HBasicBlock*>& GetPredecessors() const {
return predecessors_;
}
size_t GetNumberOfPredecessors() const {
return GetPredecessors().size();
}
const ArenaVector<HBasicBlock*>& GetSuccessors() const {
return successors_;
}
ArrayRef<HBasicBlock* const> GetNormalSuccessors() const;
ArrayRef<HBasicBlock* const> GetExceptionalSuccessors() const;
bool HasSuccessor(const HBasicBlock* block, size_t start_from = 0u) {
return ContainsElement(successors_, block, start_from);
}
const ArenaVector<HBasicBlock*>& GetDominatedBlocks() const {
return dominated_blocks_;
}
bool IsEntryBlock() const {
return graph_->GetEntryBlock() == this;
}
bool IsExitBlock() const {
return graph_->GetExitBlock() == this;
}
bool IsSingleGoto() const;
bool IsSingleReturn() const;
bool IsSingleReturnOrReturnVoidAllowingPhis() const;
bool IsSingleTryBoundary() const;
// Returns true if this block emits nothing but a jump.
bool IsSingleJump() const {
HLoopInformation* loop_info = GetLoopInformation();
return (IsSingleGoto() || IsSingleTryBoundary())
// Back edges generate a suspend check.
&& (loop_info == nullptr || !loop_info->IsBackEdge(*this));
}
void AddBackEdge(HBasicBlock* back_edge) {
if (loop_information_ == nullptr) {
loop_information_ = new (graph_->GetAllocator()) HLoopInformation(this, graph_);
}
DCHECK_EQ(loop_information_->GetHeader(), this);
loop_information_->AddBackEdge(back_edge);
}
// Registers a back edge; if the block was not a loop header before the call associates a newly
// created loop info with it.
//
// Used in SuperblockCloner to preserve LoopInformation object instead of reseting loop
// info for all blocks during back edges recalculation.
void AddBackEdgeWhileUpdating(HBasicBlock* back_edge) {
if (loop_information_ == nullptr || loop_information_->GetHeader() != this) {
loop_information_ = new (graph_->GetAllocator()) HLoopInformation(this, graph_);
}
loop_information_->AddBackEdge(back_edge);
}
HGraph* GetGraph() const { return graph_; }
void SetGraph(HGraph* graph) { graph_ = graph; }
uint32_t GetBlockId() const { return block_id_; }
void SetBlockId(int id) { block_id_ = id; }
uint32_t GetDexPc() const { return dex_pc_; }
HBasicBlock* GetDominator() const { return dominator_; }
void SetDominator(HBasicBlock* dominator) { dominator_ = dominator; }
void AddDominatedBlock(HBasicBlock* block) { dominated_blocks_.push_back(block); }
void RemoveDominatedBlock(HBasicBlock* block) {
RemoveElement(dominated_blocks_, block);
}
void ReplaceDominatedBlock(HBasicBlock* existing, HBasicBlock* new_block) {
ReplaceElement(dominated_blocks_, existing, new_block);
}
void ClearDominanceInformation();
int NumberOfBackEdges() const {
return IsLoopHeader() ? loop_information_->NumberOfBackEdges() : 0;
}
HInstruction* GetFirstInstruction() const { return instructions_.first_instruction_; }
HInstruction* GetLastInstruction() const { return instructions_.last_instruction_; }
const HInstructionList& GetInstructions() const { return instructions_; }
HInstruction* GetFirstPhi() const { return phis_.first_instruction_; }
HInstruction* GetLastPhi() const { return phis_.last_instruction_; }
const HInstructionList& GetPhis() const { return phis_; }
HInstruction* GetFirstInstructionDisregardMoves() const;
void AddSuccessor(HBasicBlock* block) {
successors_.push_back(block);
block->predecessors_.push_back(this);
}
void ReplaceSuccessor(HBasicBlock* existing, HBasicBlock* new_block) {
size_t successor_index = GetSuccessorIndexOf(existing);
existing->RemovePredecessor(this);
new_block->predecessors_.push_back(this);
successors_[successor_index] = new_block;
}
void ReplacePredecessor(HBasicBlock* existing, HBasicBlock* new_block) {
size_t predecessor_index = GetPredecessorIndexOf(existing);
existing->RemoveSuccessor(this);
new_block->successors_.push_back(this);
predecessors_[predecessor_index] = new_block;
}
// Insert `this` between `predecessor` and `successor. This method
// preserves the indices, and will update the first edge found between
// `predecessor` and `successor`.
void InsertBetween(HBasicBlock* predecessor, HBasicBlock* successor) {
size_t predecessor_index = successor->GetPredecessorIndexOf(predecessor);
size_t successor_index = predecessor->GetSuccessorIndexOf(successor);
successor->predecessors_[predecessor_index] = this;
predecessor->successors_[successor_index] = this;
successors_.push_back(successor);
predecessors_.push_back(predecessor);
}
void RemovePredecessor(HBasicBlock* block) {
predecessors_.erase(predecessors_.begin() + GetPredecessorIndexOf(block));
}
void RemoveSuccessor(HBasicBlock* block) {
successors_.erase(successors_.begin() + GetSuccessorIndexOf(block));
}
void ClearAllPredecessors() {
predecessors_.clear();
}
void AddPredecessor(HBasicBlock* block) {
predecessors_.push_back(block);
block->successors_.push_back(this);
}
void SwapPredecessors() {
DCHECK_EQ(predecessors_.size(), 2u);
std::swap(predecessors_[0], predecessors_[1]);
}
void SwapSuccessors() {
DCHECK_EQ(successors_.size(), 2u);
std::swap(successors_[0], successors_[1]);
}
size_t GetPredecessorIndexOf(HBasicBlock* predecessor) const {
return IndexOfElement(predecessors_, predecessor);
}
size_t GetSuccessorIndexOf(HBasicBlock* successor) const {
return IndexOfElement(successors_, successor);
}
HBasicBlock* GetSinglePredecessor() const {
DCHECK_EQ(GetPredecessors().size(), 1u);
return GetPredecessors()[0];
}
HBasicBlock* GetSingleSuccessor() const {
DCHECK_EQ(GetSuccessors().size(), 1u);
return GetSuccessors()[0];
}
// Returns whether the first occurrence of `predecessor` in the list of
// predecessors is at index `idx`.
bool IsFirstIndexOfPredecessor(HBasicBlock* predecessor, size_t idx) const {
DCHECK_EQ(GetPredecessors()[idx], predecessor);
return GetPredecessorIndexOf(predecessor) == idx;
}
// Create a new block between this block and its predecessors. The new block
// is added to the graph, all predecessor edges are relinked to it and an edge
// is created to `this`. Returns the new empty block. Reverse post order or
// loop and try/catch information are not updated.
HBasicBlock* CreateImmediateDominator();
// Split the block into two blocks just before `cursor`. Returns the newly
// created, latter block. Note that this method will add the block to the
// graph, create a Goto at the end of the former block and will create an edge
// between the blocks. It will not, however, update the reverse post order or
// loop and try/catch information.
HBasicBlock* SplitBefore(HInstruction* cursor, bool require_graph_not_in_ssa_form = true);
// Split the block into two blocks just before `cursor`. Returns the newly
// created block. Note that this method just updates raw block information,
// like predecessors, successors, dominators, and instruction list. It does not
// update the graph, reverse post order, loop information, nor make sure the
// blocks are consistent (for example ending with a control flow instruction).
HBasicBlock* SplitBeforeForInlining(HInstruction* cursor);
// Similar to `SplitBeforeForInlining` but does it after `cursor`.
HBasicBlock* SplitAfterForInlining(HInstruction* cursor);
// Merge `other` at the end of `this`. Successors and dominated blocks of
// `other` are changed to be successors and dominated blocks of `this`. Note
// that this method does not update the graph, reverse post order, loop
// information, nor make sure the blocks are consistent (for example ending
// with a control flow instruction).
void MergeWithInlined(HBasicBlock* other);
// Replace `this` with `other`. Predecessors, successors, and dominated blocks
// of `this` are moved to `other`.
// Note that this method does not update the graph, reverse post order, loop
// information, nor make sure the blocks are consistent (for example ending
// with a control flow instruction).
void ReplaceWith(HBasicBlock* other);
// Merges the instructions of `other` at the end of `this`.
void MergeInstructionsWith(HBasicBlock* other);
// Merge `other` at the end of `this`. This method updates loops, reverse post
// order, links to predecessors, successors, dominators and deletes the block
// from the graph. The two blocks must be successive, i.e. `this` the only
// predecessor of `other` and vice versa.
void MergeWith(HBasicBlock* other);
// Disconnects `this` from all its predecessors, successors and dominator,
// removes it from all loops it is included in and eventually from the graph.
// The block must not dominate any other block. Predecessors and successors
// are safely updated.
void DisconnectAndDelete();
// Disconnects `this` from all its successors and updates their phis, if the successors have them.
// If `visited` is provided, it will use the information to know if a successor is reachable and
// skip updating those phis.
void DisconnectFromSuccessors(const ArenaBitVector* visited = nullptr);
// Removes the catch phi uses of the instructions in `this`, and then remove the instruction
// itself. If `building_dominator_tree` is true, it will not remove the instruction as user, since
// we do it in a previous step. This is a special case for building up the dominator tree: we want
// to eliminate uses before inputs but we don't have domination information, so we remove all
// connections from input/uses first before removing any instruction.
// This method assumes the instructions have been removed from all users with the exception of
// catch phis because of missing exceptional edges in the graph.
void RemoveCatchPhiUsesAndInstruction(bool building_dominator_tree);
void AddInstruction(HInstruction* instruction);
// Insert `instruction` before/after an existing instruction `cursor`.
void InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor);
void InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor);
// Replace phi `initial` with `replacement` within this block.
void ReplaceAndRemovePhiWith(HPhi* initial, HPhi* replacement);
// Replace instruction `initial` with `replacement` within this block.
void ReplaceAndRemoveInstructionWith(HInstruction* initial,
HInstruction* replacement);
void AddPhi(HPhi* phi);
void InsertPhiAfter(HPhi* instruction, HPhi* cursor);
// RemoveInstruction and RemovePhi delete a given instruction from the respective
// instruction list. With 'ensure_safety' set to true, it verifies that the
// instruction is not in use and removes it from the use lists of its inputs.
void RemoveInstruction(HInstruction* instruction, bool ensure_safety = true);
void RemovePhi(HPhi* phi, bool ensure_safety = true);
void RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety = true);
bool IsLoopHeader() const {
return IsInLoop() && (loop_information_->GetHeader() == this);
}
bool IsLoopPreHeaderFirstPredecessor() const {
DCHECK(IsLoopHeader());
return GetPredecessors()[0] == GetLoopInformation()->GetPreHeader();
}
bool IsFirstPredecessorBackEdge() const {
DCHECK(IsLoopHeader());
return GetLoopInformation()->IsBackEdge(*GetPredecessors()[0]);
}
HLoopInformation* GetLoopInformation() const {
return loop_information_;
}
// Set the loop_information_ on this block. Overrides the current
// loop_information if it is an outer loop of the passed loop information.
// Note that this method is called while creating the loop information.
void SetInLoop(HLoopInformation* info) {
if (IsLoopHeader()) {
// Nothing to do. This just means `info` is an outer loop.
} else if (!IsInLoop()) {
loop_information_ = info;
} else if (loop_information_->Contains(*info->GetHeader())) {
// Block is currently part of an outer loop. Make it part of this inner loop.
// Note that a non loop header having a loop information means this loop information
// has already been populated
loop_information_ = info;
} else {
// Block is part of an inner loop. Do not update the loop information.
// Note that we cannot do the check `info->Contains(loop_information_)->GetHeader()`
// at this point, because this method is being called while populating `info`.
}
}
// Raw update of the loop information.
void SetLoopInformation(HLoopInformation* info) {
loop_information_ = info;
}
bool IsInLoop() const { return loop_information_ != nullptr; }
TryCatchInformation* GetTryCatchInformation() const { return try_catch_information_; }
void SetTryCatchInformation(TryCatchInformation* try_catch_information) {
try_catch_information_ = try_catch_information;
}
bool IsTryBlock() const {
return try_catch_information_ != nullptr && try_catch_information_->IsTryBlock();
}
bool IsCatchBlock() const {
return try_catch_information_ != nullptr && try_catch_information_->IsCatchBlock();
}
// Returns the try entry that this block's successors should have. They will
// be in the same try, unless the block ends in a try boundary. In that case,
// the appropriate try entry will be returned.
const HTryBoundary* ComputeTryEntryOfSuccessors() const;
bool HasThrowingInstructions() const;
// Returns whether this block dominates the blocked passed as parameter.
bool Dominates(const HBasicBlock* block) const;
size_t GetLifetimeStart() const { return lifetime_start_; }
size_t GetLifetimeEnd() const { return lifetime_end_; }
void SetLifetimeStart(size_t start) { lifetime_start_ = start; }
void SetLifetimeEnd(size_t end) { lifetime_end_ = end; }
bool EndsWithControlFlowInstruction() const;
bool EndsWithReturn() const;
bool EndsWithIf() const;
bool EndsWithTryBoundary() const;
bool HasSinglePhi() const;
private:
HGraph* graph_;
ArenaVector<HBasicBlock*> predecessors_;
ArenaVector<HBasicBlock*> successors_;
HInstructionList instructions_;
HInstructionList phis_;
HLoopInformation* loop_information_;
HBasicBlock* dominator_;
ArenaVector<HBasicBlock*> dominated_blocks_;
uint32_t block_id_;
// The dex program counter of the first instruction of this block.
const uint32_t dex_pc_;
size_t lifetime_start_;
size_t lifetime_end_;
TryCatchInformation* try_catch_information_;
friend class HGraph;
friend class HInstruction;
// Allow manual control of the ordering of predecessors/successors
friend class OptimizingUnitTestHelper;
DISALLOW_COPY_AND_ASSIGN(HBasicBlock);
};
// Iterates over the LoopInformation of all loops which contain 'block'
// from the innermost to the outermost.
class HLoopInformationOutwardIterator : public ValueObject {
public:
explicit HLoopInformationOutwardIterator(const HBasicBlock& block)
: current_(block.GetLoopInformation()) {}
bool Done() const { return current_ == nullptr; }
void Advance() {
DCHECK(!Done());
current_ = current_->GetPreHeader()->GetLoopInformation();
}
HLoopInformation* Current() const {
DCHECK(!Done());
return current_;
}
private:
HLoopInformation* current_;
DISALLOW_COPY_AND_ASSIGN(HLoopInformationOutwardIterator);
};
#define FOR_EACH_CONCRETE_INSTRUCTION_SCALAR_COMMON(M) \
M(Above, Condition) \
M(AboveOrEqual, Condition) \
M(Abs, UnaryOperation) \
M(Add, BinaryOperation) \
M(And, BinaryOperation) \
M(ArrayGet, Instruction) \
M(ArrayLength, Instruction) \
M(ArraySet, Instruction) \
M(Below, Condition) \
M(BelowOrEqual, Condition) \
M(BooleanNot, UnaryOperation) \
M(BoundsCheck, Instruction) \
M(BoundType, Instruction) \
M(CheckCast, Instruction) \
M(ClassTableGet, Instruction) \
M(ClearException, Instruction) \
M(ClinitCheck, Instruction) \
M(Compare, BinaryOperation) \
M(ConstructorFence, Instruction) \
M(CurrentMethod, Instruction) \
M(ShouldDeoptimizeFlag, Instruction) \
M(Deoptimize, Instruction) \
M(Div, BinaryOperation) \
M(DivZeroCheck, Instruction) \
M(DoubleConstant, Constant) \
M(Equal, Condition) \
M(Exit, Instruction) \
M(FloatConstant, Constant) \
M(Goto, Instruction) \
M(GreaterThan, Condition) \
M(GreaterThanOrEqual, Condition) \
M(If, Instruction) \
M(InstanceFieldGet, Instruction) \
M(InstanceFieldSet, Instruction) \
M(PredicatedInstanceFieldGet, Instruction) \
M(InstanceOf, Instruction) \
M(IntConstant, Constant) \
M(IntermediateAddress, Instruction) \
M(InvokeUnresolved, Invoke) \
M(InvokeInterface, Invoke) \
M(InvokeStaticOrDirect, Invoke) \
M(InvokeVirtual, Invoke) \
M(InvokePolymorphic, Invoke) \
M(InvokeCustom, Invoke) \
M(LessThan, Condition) \
M(LessThanOrEqual, Condition) \
M(LoadClass, Instruction) \
M(LoadException, Instruction) \
M(LoadMethodHandle, Instruction) \
M(LoadMethodType, Instruction) \
M(LoadString, Instruction) \
M(LongConstant, Constant) \
M(Max, Instruction) \
M(MemoryBarrier, Instruction) \
M(MethodEntryHook, Instruction) \
M(MethodExitHook, Instruction) \
M(Min, BinaryOperation) \
M(MonitorOperation, Instruction) \
M(Mul, BinaryOperation) \
M(Neg, UnaryOperation) \
M(NewArray, Instruction) \
M(NewInstance, Instruction) \
M(Nop, Instruction) \
M(Not, UnaryOperation) \
M(NotEqual, Condition) \
M(NullConstant, Instruction) \
M(NullCheck, Instruction) \
M(Or, BinaryOperation) \
M(PackedSwitch, Instruction) \
M(ParallelMove, Instruction) \
M(ParameterValue, Instruction) \
M(Phi, Instruction) \
M(Rem, BinaryOperation) \
M(Return, Instruction) \
M(ReturnVoid, Instruction) \
M(Ror, BinaryOperation) \
M(Shl, BinaryOperation) \
M(Shr, BinaryOperation) \
M(StaticFieldGet, Instruction) \
M(StaticFieldSet, Instruction) \
M(StringBuilderAppend, Instruction) \
M(UnresolvedInstanceFieldGet, Instruction) \
M(UnresolvedInstanceFieldSet, Instruction) \
M(UnresolvedStaticFieldGet, Instruction) \
M(UnresolvedStaticFieldSet, Instruction) \
M(Select, Instruction) \
M(Sub, BinaryOperation) \
M(SuspendCheck, Instruction) \
M(Throw, Instruction) \
M(TryBoundary, Instruction) \
M(TypeConversion, Instruction) \
M(UShr, BinaryOperation) \
M(Xor, BinaryOperation)
#define FOR_EACH_CONCRETE_INSTRUCTION_VECTOR_COMMON(M) \
M(VecReplicateScalar, VecUnaryOperation) \
M(VecExtractScalar, VecUnaryOperation) \
M(VecReduce, VecUnaryOperation) \
M(VecCnv, VecUnaryOperation) \
M(VecNeg, VecUnaryOperation) \
M(VecAbs, VecUnaryOperation) \
M(VecNot, VecUnaryOperation) \
M(VecAdd, VecBinaryOperation) \
M(VecHalvingAdd, VecBinaryOperation) \
M(VecSub, VecBinaryOperation) \
M(VecMul, VecBinaryOperation) \
M(VecDiv, VecBinaryOperation) \
M(VecMin, VecBinaryOperation) \
M(VecMax, VecBinaryOperation) \
M(VecAnd, VecBinaryOperation) \
M(VecAndNot, VecBinaryOperation) \
M(VecOr, VecBinaryOperation) \
M(VecXor, VecBinaryOperation) \
M(VecSaturationAdd, VecBinaryOperation) \
M(VecSaturationSub, VecBinaryOperation) \
M(VecShl, VecBinaryOperation) \
M(VecShr, VecBinaryOperation) \
M(VecUShr, VecBinaryOperation) \
M(VecSetScalars, VecOperation) \
M(VecMultiplyAccumulate, VecOperation) \
M(VecSADAccumulate, VecOperation) \
M(VecDotProd, VecOperation) \
M(VecLoad, VecMemoryOperation) \
M(VecStore, VecMemoryOperation) \
M(VecPredSetAll, VecPredSetOperation) \
M(VecPredWhile, VecPredSetOperation) \
M(VecPredCondition, VecOperation) \
#define FOR_EACH_CONCRETE_INSTRUCTION_COMMON(M) \
FOR_EACH_CONCRETE_INSTRUCTION_SCALAR_COMMON(M) \
FOR_EACH_CONCRETE_INSTRUCTION_VECTOR_COMMON(M)
/*
* Instructions, shared across several (not all) architectures.
*/
#if !defined(ART_ENABLE_CODEGEN_arm) && !defined(ART_ENABLE_CODEGEN_arm64)
#define FOR_EACH_CONCRETE_INSTRUCTION_SHARED(M)
#else
#define FOR_EACH_CONCRETE_INSTRUCTION_SHARED(M) \
M(BitwiseNegatedRight, Instruction) \
M(DataProcWithShifterOp, Instruction) \
M(MultiplyAccumulate, Instruction) \
M(IntermediateAddressIndex, Instruction)
#endif
#define FOR_EACH_CONCRETE_INSTRUCTION_ARM(M)
#define FOR_EACH_CONCRETE_INSTRUCTION_ARM64(M)
#ifndef ART_ENABLE_CODEGEN_x86
#define FOR_EACH_CONCRETE_INSTRUCTION_X86(M)
#else
#define FOR_EACH_CONCRETE_INSTRUCTION_X86(M) \
M(X86ComputeBaseMethodAddress, Instruction) \
M(X86LoadFromConstantTable, Instruction) \
M(X86FPNeg, Instruction) \
M(X86PackedSwitch, Instruction)
#endif
#if defined(ART_ENABLE_CODEGEN_x86) || defined(ART_ENABLE_CODEGEN_x86_64)
#define FOR_EACH_CONCRETE_INSTRUCTION_X86_COMMON(M) \
M(X86AndNot, Instruction) \
M(X86MaskOrResetLeastSetBit, Instruction)
#else
#define FOR_EACH_CONCRETE_INSTRUCTION_X86_COMMON(M)
#endif
#define FOR_EACH_CONCRETE_INSTRUCTION_X86_64(M)
#define FOR_EACH_CONCRETE_INSTRUCTION(M) \
FOR_EACH_CONCRETE_INSTRUCTION_COMMON(M) \
FOR_EACH_CONCRETE_INSTRUCTION_SHARED(M) \
FOR_EACH_CONCRETE_INSTRUCTION_ARM(M) \
FOR_EACH_CONCRETE_INSTRUCTION_ARM64(M) \
FOR_EACH_CONCRETE_INSTRUCTION_X86(M) \
FOR_EACH_CONCRETE_INSTRUCTION_X86_64(M) \
FOR_EACH_CONCRETE_INSTRUCTION_X86_COMMON(M)
#define FOR_EACH_ABSTRACT_INSTRUCTION(M) \
M(Condition, BinaryOperation) \
M(Constant, Instruction) \
M(UnaryOperation, Instruction) \
M(BinaryOperation, Instruction) \
M(Invoke, Instruction) \
M(VecOperation, Instruction) \
M(VecUnaryOperation, VecOperation) \
M(VecBinaryOperation, VecOperation) \
M(VecMemoryOperation, VecOperation) \
M(VecPredSetOperation, VecOperation)
#define FOR_EACH_INSTRUCTION(M) \
FOR_EACH_CONCRETE_INSTRUCTION(M) \
FOR_EACH_ABSTRACT_INSTRUCTION(M)
#define FORWARD_DECLARATION(type, super) class H##type;
FOR_EACH_INSTRUCTION(FORWARD_DECLARATION)
#undef FORWARD_DECLARATION
#define DECLARE_INSTRUCTION(type) \
private: \
H##type& operator=(const H##type&) = delete; \
public: \
const char* DebugName() const override { return #type; } \
HInstruction* Clone(ArenaAllocator* arena) const override { \
DCHECK(IsClonable()); \
return new (arena) H##type(*this->As##type()); \
} \
void Accept(HGraphVisitor* visitor) override
#define DECLARE_ABSTRACT_INSTRUCTION(type) \
private: \
H##type& operator=(const H##type&) = delete; \
public:
#define DEFAULT_COPY_CONSTRUCTOR(type) H##type(const H##type& other) = default;
template <typename T>
class HUseListNode : public ArenaObject<kArenaAllocUseListNode>,
public IntrusiveForwardListNode<HUseListNode<T>> {
public:
// Get the instruction which has this use as one of the inputs.
T GetUser() const { return user_; }
// Get the position of the input record that this use corresponds to.
size_t GetIndex() const { return index_; }
// Set the position of the input record that this use corresponds to.
void SetIndex(size_t index) { index_ = index; }
private:
HUseListNode(T user, size_t index)
: user_(user), index_(index) {}
T const user_;
size_t index_;
friend class HInstruction;
DISALLOW_COPY_AND_ASSIGN(HUseListNode);
};
template <typename T>
using HUseList = IntrusiveForwardList<HUseListNode<T>>;
// This class is used by HEnvironment and HInstruction classes to record the
// instructions they use and pointers to the corresponding HUseListNodes kept
// by the used instructions.
template <typename T>
class HUserRecord : public ValueObject {
public:
HUserRecord() : instruction_(nullptr), before_use_node_() {}
explicit HUserRecord(HInstruction* instruction) : instruction_(instruction), before_use_node_() {}
HUserRecord(const HUserRecord<T>& old_record, typename HUseList<T>::iterator before_use_node)
: HUserRecord(old_record.instruction_, before_use_node) {}
HUserRecord(HInstruction* instruction, typename HUseList<T>::iterator before_use_node)
: instruction_(instruction), before_use_node_(before_use_node) {
DCHECK(instruction_ != nullptr);
}
HInstruction* GetInstruction() const { return instruction_; }
typename HUseList<T>::iterator GetBeforeUseNode() const { return before_use_node_; }
typename HUseList<T>::iterator GetUseNode() const { return ++GetBeforeUseNode(); }
private:
// Instruction used by the user.
HInstruction* instruction_;
// Iterator before the corresponding entry in the use list kept by 'instruction_'.
typename HUseList<T>::iterator before_use_node_;
};
// Helper class that extracts the input instruction from HUserRecord<HInstruction*>.
// This is used for HInstruction::GetInputs() to return a container wrapper providing
// HInstruction* values even though the underlying container has HUserRecord<>s.
struct HInputExtractor {
HInstruction* operator()(HUserRecord<HInstruction*>& record) const {
return record.GetInstruction();
}
const HInstruction* operator()(const HUserRecord<HInstruction*>& record) const {
return record.GetInstruction();
}
};
using HInputsRef = TransformArrayRef<HUserRecord<HInstruction*>, HInputExtractor>;
using HConstInputsRef = TransformArrayRef<const HUserRecord<HInstruction*>, HInputExtractor>;
/**
* Side-effects representation.
*
* For write/read dependences on fields/arrays, the dependence analysis uses
* type disambiguation (e.g. a float field write cannot modify the value of an
* integer field read) and the access type (e.g. a reference array write cannot
* modify the value of a reference field read [although it may modify the
* reference fetch prior to reading the field, which is represented by its own
* write/read dependence]). The analysis makes conservative points-to
* assumptions on reference types (e.g. two same typed arrays are assumed to be
* the same, and any reference read depends on any reference read without
* further regard of its type).
*
* kDependsOnGCBit is defined in the following way: instructions with kDependsOnGCBit must not be
* alive across the point where garbage collection might happen.
*
* Note: Instructions with kCanTriggerGCBit do not depend on each other.
*
* kCanTriggerGCBit must be used for instructions for which GC might happen on the path across
* those instructions from the compiler perspective (between this instruction and the next one
* in the IR).
*
* Note: Instructions which can cause GC only on a fatal slow path do not need
* kCanTriggerGCBit as the execution never returns to the instruction next to the exceptional
* one. However the execution may return to compiled code if there is a catch block in the
* current method; for this purpose the TryBoundary exit instruction has kCanTriggerGCBit
* set.
*
* The internal representation uses 38-bit and is described in the table below.
* The first line indicates the side effect, and for field/array accesses the
* second line indicates the type of the access (in the order of the
* DataType::Type enum).
* The two numbered lines below indicate the bit position in the bitfield (read
* vertically).
*
* |Depends on GC|ARRAY-R |FIELD-R |Can trigger GC|ARRAY-W |FIELD-W |
* +-------------+---------+---------+--------------+---------+---------+
* | |DFJISCBZL|DFJISCBZL| |DFJISCBZL|DFJISCBZL|
* | 3 |333333322|222222221| 1 |111111110|000000000|
* | 7 |654321098|765432109| 8 |765432109|876543210|
*
* Note that, to ease the implementation, 'changes' bits are least significant
* bits, while 'dependency' bits are most significant bits.
*/
class SideEffects : public ValueObject {
public:
SideEffects() : flags_(0) {}
static SideEffects None() {
return SideEffects(0);
}
static SideEffects All() {
return SideEffects(kAllChangeBits | kAllDependOnBits);
}
static SideEffects AllChanges() {
return SideEffects(kAllChangeBits);
}
static SideEffects AllDependencies() {
return SideEffects(kAllDependOnBits);
}
static SideEffects AllExceptGCDependency() {
return AllWritesAndReads().Union(SideEffects::CanTriggerGC());
}
static SideEffects AllWritesAndReads() {
return SideEffects(kAllWrites | kAllReads);
}
static SideEffects AllWrites() {
return SideEffects(kAllWrites);
}
static SideEffects AllReads() {
return SideEffects(kAllReads);
}
static SideEffects FieldWriteOfType(DataType::Type type, bool is_volatile) {
return is_volatile
? AllWritesAndReads()
: SideEffects(TypeFlag(type, kFieldWriteOffset));
}
static SideEffects ArrayWriteOfType(DataType::Type type) {
return SideEffects(TypeFlag(type, kArrayWriteOffset));
}
static SideEffects FieldReadOfType(DataType::Type type, bool is_volatile) {
return is_volatile
? AllWritesAndReads()
: SideEffects(TypeFlag(type, kFieldReadOffset));
}
static SideEffects ArrayReadOfType(DataType::Type type) {
return SideEffects(TypeFlag(type, kArrayReadOffset));
}
// Returns whether GC might happen across this instruction from the compiler perspective so
// the next instruction in the IR would see that.
//
// See the SideEffect class comments.
static SideEffects CanTriggerGC() {
return SideEffects(1ULL << kCanTriggerGCBit);
}
// Returns whether the instruction must not be alive across a GC point.
//
// See the SideEffect class comments.
static SideEffects DependsOnGC() {
return SideEffects(1ULL << kDependsOnGCBit);
}
// Combines the side-effects of this and the other.
SideEffects Union(SideEffects other) const {
return SideEffects(flags_ | other.flags_);
}
SideEffects Exclusion(SideEffects other) const {
return SideEffects(flags_ & ~other.flags_);
}
void Add(SideEffects other) {
flags_ |= other.flags_;
}
bool Includes(SideEffects other) const {
return (other.flags_ & flags_) == other.flags_;
}
bool HasSideEffects() const {
return (flags_ & kAllChangeBits);
}
bool HasDependencies() const {
return (flags_ & kAllDependOnBits);
}
// Returns true if there are no side effects or dependencies.
bool DoesNothing() const {
return flags_ == 0;
}
// Returns true if something is written.
bool DoesAnyWrite() const {
return (flags_ & kAllWrites);
}
// Returns true if something is read.
bool DoesAnyRead() const {
return (flags_ & kAllReads);
}
// Returns true if potentially everything is written and read
// (every type and every kind of access).
bool DoesAllReadWrite() const {
return (flags_ & (kAllWrites | kAllReads)) == (kAllWrites | kAllReads);
}
bool DoesAll() const {
return flags_ == (kAllChangeBits | kAllDependOnBits);
}
// Returns true if `this` may read something written by `other`.
bool MayDependOn(SideEffects other) const {
const uint64_t depends_on_flags = (flags_ & kAllDependOnBits) >> kChangeBits;
return (other.flags_ & depends_on_flags);
}
// Returns string representation of flags (for debugging only).
// Format: |x|DFJISCBZL|DFJISCBZL|y|DFJISCBZL|DFJISCBZL|
std::string ToString() const {
std::string flags = "|";
for (int s = kLastBit; s >= 0; s--) {
bool current_bit_is_set = ((flags_ >> s) & 1) != 0;
if ((s == kDependsOnGCBit) || (s == kCanTriggerGCBit)) {
// This is a bit for the GC side effect.
if (current_bit_is_set) {
flags += "GC";
}
flags += "|";
} else {
// This is a bit for the array/field analysis.
// The underscore character stands for the 'can trigger GC' bit.
static const char *kDebug = "LZBCSIJFDLZBCSIJFD_LZBCSIJFDLZBCSIJFD";
if (current_bit_is_set) {
flags += kDebug[s];
}
if ((s == kFieldWriteOffset) || (s == kArrayWriteOffset) ||
(s == kFieldReadOffset) || (s == kArrayReadOffset)) {
flags += "|";
}
}
}
return flags;
}
bool Equals(const SideEffects& other) const { return flags_ == other.flags_; }
private:
static constexpr int kFieldArrayAnalysisBits = 9;
static constexpr int kFieldWriteOffset = 0;
static constexpr int kArrayWriteOffset = kFieldWriteOffset + kFieldArrayAnalysisBits;
static constexpr int kLastBitForWrites = kArrayWriteOffset + kFieldArrayAnalysisBits - 1;
static constexpr int kCanTriggerGCBit = kLastBitForWrites + 1;
static constexpr int kChangeBits = kCanTriggerGCBit + 1;
static constexpr int kFieldReadOffset = kCanTriggerGCBit + 1;
static constexpr int kArrayReadOffset = kFieldReadOffset + kFieldArrayAnalysisBits;
static constexpr int kLastBitForReads = kArrayReadOffset + kFieldArrayAnalysisBits - 1;
static constexpr int kDependsOnGCBit = kLastBitForReads + 1;
static constexpr int kLastBit = kDependsOnGCBit;
static constexpr int kDependOnBits = kLastBit + 1 - kChangeBits;
// Aliases.
static_assert(kChangeBits == kDependOnBits,
"the 'change' bits should match the 'depend on' bits.");
static constexpr uint64_t kAllChangeBits = ((1ULL << kChangeBits) - 1);
static constexpr uint64_t kAllDependOnBits = ((1ULL << kDependOnBits) - 1) << kChangeBits;
static constexpr uint64_t kAllWrites =
((1ULL << (kLastBitForWrites + 1 - kFieldWriteOffset)) - 1) << kFieldWriteOffset;
static constexpr uint64_t kAllReads =
((1ULL << (kLastBitForReads + 1 - kFieldReadOffset)) - 1) << kFieldReadOffset;
// Translates type to bit flag. The type must correspond to a Java type.
static uint64_t TypeFlag(DataType::Type type, int offset) {
int shift;
switch (type) {
case DataType::Type::kReference: shift = 0; break;
case DataType::Type::kBool: shift = 1; break;
case DataType::Type::kInt8: shift = 2; break;
case DataType::Type::kUint16: shift = 3; break;
case DataType::Type::kInt16: shift = 4; break;
case DataType::Type::kInt32: shift = 5; break;
case DataType::Type::kInt64: shift = 6; break;
case DataType::Type::kFloat32: shift = 7; break;
case DataType::Type::kFloat64: shift = 8; break;
default:
LOG(FATAL) << "Unexpected data type " << type;
UNREACHABLE();
}
DCHECK_LE(kFieldWriteOffset, shift);
DCHECK_LT(shift, kArrayWriteOffset);
return UINT64_C(1) << (shift + offset);
}
// Private constructor on direct flags value.
explicit SideEffects(uint64_t flags) : flags_(flags) {}
uint64_t flags_;
};
// A HEnvironment object contains the values of virtual registers at a given location.
class HEnvironment : public ArenaObject<kArenaAllocEnvironment> {
public:
ALWAYS_INLINE HEnvironment(ArenaAllocator* allocator,
size_t number_of_vregs,
ArtMethod* method,
uint32_t dex_pc,
HInstruction* holder)
: vregs_(number_of_vregs, allocator->Adapter(kArenaAllocEnvironmentVRegs)),
locations_(allocator->Adapter(kArenaAllocEnvironmentLocations)),
parent_(nullptr),
method_(method),
dex_pc_(dex_pc),
holder_(holder) {
}
ALWAYS_INLINE HEnvironment(ArenaAllocator* allocator,
const HEnvironment& to_copy,
HInstruction* holder)
: HEnvironment(allocator,
to_copy.Size(),
to_copy.GetMethod(),
to_copy.GetDexPc(),
holder) {}
void AllocateLocations() {
DCHECK(locations_.empty());
locations_.resize(vregs_.size());
}
void SetAndCopyParentChain(ArenaAllocator* allocator, HEnvironment* parent) {
if (parent_ != nullptr) {
parent_->SetAndCopyParentChain(allocator, parent);
} else {
parent_ = new (allocator) HEnvironment(allocator, *parent, holder_);
parent_->CopyFrom(parent);
if (parent->GetParent() != nullptr) {
parent_->SetAndCopyParentChain(allocator, parent->GetParent());
}
}
}
void CopyFrom(ArrayRef<HInstruction* const> locals);
void CopyFrom(HEnvironment* environment);
// Copy from `env`. If it's a loop phi for `loop_header`, copy the first
// input to the loop phi instead. This is for inserting instructions that
// require an environment (like HDeoptimization) in the loop pre-header.
void CopyFromWithLoopPhiAdjustment(HEnvironment* env, HBasicBlock* loop_header);
void SetRawEnvAt(size_t index, HInstruction* instruction) {
vregs_[index] = HUserRecord<HEnvironment*>(instruction);
}
HInstruction* GetInstructionAt(size_t index) const {
return vregs_[index].GetInstruction();
}
void RemoveAsUserOfInput(size_t index) const;
// Replaces the input at the position 'index' with the replacement; the replacement and old
// input instructions' env_uses_ lists are adjusted. The function works similar to
// HInstruction::ReplaceInput.
void ReplaceInput(HInstruction* replacement, size_t index);
size_t Size() const { return vregs_.size(); }
HEnvironment* GetParent() const { return parent_; }
void SetLocationAt(size_t index, Location location) {
locations_[index] = location;
}
Location GetLocationAt(size_t index) const {
return locations_[index];
}
uint32_t GetDexPc() const {
return dex_pc_;
}
ArtMethod* GetMethod() const {
return method_;
}
HInstruction* GetHolder() const {
return holder_;
}
bool IsFromInlinedInvoke() const {
return GetParent() != nullptr;
}
class EnvInputSelector {
public:
explicit EnvInputSelector(const HEnvironment* e) : env_(e) {}
HInstruction* operator()(size_t s) const {
return env_->GetInstructionAt(s);
}
private:
const HEnvironment* env_;
};
using HConstEnvInputRef = TransformIterator<CountIter, EnvInputSelector>;
IterationRange<HConstEnvInputRef> GetEnvInputs() const {
IterationRange<CountIter> range(Range(Size()));
return MakeIterationRange(MakeTransformIterator(range.begin(), EnvInputSelector(this)),
MakeTransformIterator(range.end(), EnvInputSelector(this)));
}
private:
ArenaVector<HUserRecord<HEnvironment*>> vregs_;
ArenaVector<Location> locations_;
HEnvironment* parent_;
ArtMethod* method_;
const uint32_t dex_pc_;
// The instruction that holds this environment.
HInstruction* const holder_;
friend class HInstruction;
DISALLOW_COPY_AND_ASSIGN(HEnvironment);
};
std::ostream& operator<<(std::ostream& os, const HInstruction& rhs);
// Iterates over the Environments
class HEnvironmentIterator : public ValueObject,
public std::iterator<std::forward_iterator_tag, HEnvironment*> {
public:
explicit HEnvironmentIterator(HEnvironment* cur) : cur_(cur) {}
HEnvironment* operator*() const {
return cur_;
}
HEnvironmentIterator& operator++() {
DCHECK(cur_ != nullptr);
cur_ = cur_->GetParent();
return *this;
}
HEnvironmentIterator operator++(int) {
HEnvironmentIterator prev(*this);
++(*this);
return prev;
}
bool operator==(const HEnvironmentIterator& other) const {
return other.cur_ == cur_;
}
bool operator!=(const HEnvironmentIterator& other) const {
return !(*this == other);
}
private:
HEnvironment* cur_;
};
class HInstruction : public ArenaObject<kArenaAllocInstruction> {
public:
#define DECLARE_KIND(type, super) k##type,
enum InstructionKind { // private marker to avoid generate-operator-out.py from processing.
FOR_EACH_CONCRETE_INSTRUCTION(DECLARE_KIND)
kLastInstructionKind
};
#undef DECLARE_KIND
HInstruction(InstructionKind kind, SideEffects side_effects, uint32_t dex_pc)
: HInstruction(kind, DataType::Type::kVoid, side_effects, dex_pc) {}
HInstruction(InstructionKind kind, DataType::Type type, SideEffects side_effects, uint32_t dex_pc)
: previous_(nullptr),
next_(nullptr),
block_(nullptr),
dex_pc_(dex_pc),
id_(-1),
ssa_index_(-1),
packed_fields_(0u),
environment_(nullptr),
locations_(nullptr),
live_interval_(nullptr),
lifetime_position_(kNoLifetime),
side_effects_(side_effects),
reference_type_handle_(ReferenceTypeInfo::CreateInvalid().GetTypeHandle()) {
SetPackedField<InstructionKindField>(kind);
SetPackedField<TypeField>(type);
SetPackedFlag<kFlagReferenceTypeIsExact>(ReferenceTypeInfo::CreateInvalid().IsExact());
}
virtual ~HInstruction() {}
std::ostream& Dump(std::ostream& os, bool dump_args = false);
// Helper for dumping without argument information using operator<<
struct NoArgsDump {
const HInstruction* ins;
};
NoArgsDump DumpWithoutArgs() const {
return NoArgsDump{this};
}
// Helper for dumping with argument information using operator<<
struct ArgsDump {
const HInstruction* ins;
};
ArgsDump DumpWithArgs() const {
return ArgsDump{this};
}
HInstruction* GetNext() const { return next_; }
HInstruction* GetPrevious() const { return previous_; }
HInstruction* GetNextDisregardingMoves() const;
HInstruction* GetPreviousDisregardingMoves() const;
HBasicBlock* GetBlock() const { return block_; }
ArenaAllocator* GetAllocator() const { return block_->GetGraph()->GetAllocator(); }
void SetBlock(HBasicBlock* block) { block_ = block; }
bool IsInBlock() const { return block_ != nullptr; }
bool IsInLoop() const { return block_->IsInLoop(); }
bool IsLoopHeaderPhi() const { return IsPhi() && block_->IsLoopHeader(); }
bool IsIrreducibleLoopHeaderPhi() const {
return IsLoopHeaderPhi() && GetBlock()->GetLoopInformation()->IsIrreducible();
}
virtual ArrayRef<HUserRecord<HInstruction*>> GetInputRecords() = 0;
ArrayRef<const HUserRecord<HInstruction*>> GetInputRecords() const {
// One virtual method is enough, just const_cast<> and then re-add the const.
return ArrayRef<const HUserRecord<HInstruction*>>(
const_cast<HInstruction*>(this)->GetInputRecords());
}
HInputsRef GetInputs() {
return MakeTransformArrayRef(GetInputRecords(), HInputExtractor());
}
HConstInputsRef GetInputs() const {
return MakeTransformArrayRef(GetInputRecords(), HInputExtractor());
}
size_t InputCount() const { return GetInputRecords().size(); }
HInstruction* InputAt(size_t i) const { return InputRecordAt(i).GetInstruction(); }
bool HasInput(HInstruction* input) const {
for (const HInstruction* i : GetInputs()) {
if (i == input) {
return true;
}
}
return false;
}
void SetRawInputAt(size_t index, HInstruction* input) {
SetRawInputRecordAt(index, HUserRecord<HInstruction*>(input));
}
virtual void Accept(HGraphVisitor* visitor) = 0;
virtual const char* DebugName() const = 0;
DataType::Type GetType() const {
return TypeField::Decode(GetPackedFields());
}
virtual bool NeedsEnvironment() const { return false; }
virtual bool NeedsBss() const {
return false;
}
uint32_t GetDexPc() const { return dex_pc_; }
virtual bool IsControlFlow() const { return false; }
// Can the instruction throw?
// TODO: We should rename to CanVisiblyThrow, as some instructions (like HNewInstance),
// could throw OOME, but it is still OK to remove them if they are unused.
virtual bool CanThrow() const { return false; }
// Does the instruction always throw an exception unconditionally?
virtual bool AlwaysThrows() const { return false; }
// Will this instruction only cause async exceptions if it causes any at all?
virtual bool OnlyThrowsAsyncExceptions() const {
return false;
}
bool CanThrowIntoCatchBlock() const { return CanThrow() && block_->IsTryBlock(); }
bool HasSideEffects() const { return side_effects_.HasSideEffects(); }
bool DoesAnyWrite() const { return side_effects_.DoesAnyWrite(); }
// Does not apply for all instructions, but having this at top level greatly
// simplifies the null check elimination.
// TODO: Consider merging can_be_null into ReferenceTypeInfo.
virtual bool CanBeNull() const {
DCHECK_EQ(GetType(), DataType::Type::kReference) << "CanBeNull only applies to reference types";
return true;
}
virtual bool CanDoImplicitNullCheckOn(HInstruction* obj ATTRIBUTE_UNUSED) const {
return false;
}
// If this instruction will do an implicit null check, return the `HNullCheck` associated
// with it. Otherwise return null.
HNullCheck* GetImplicitNullCheck() const {
// Go over previous non-move instructions that are emitted at use site.
HInstruction* prev_not_move = GetPreviousDisregardingMoves();
while (prev_not_move != nullptr && prev_not_move->IsEmittedAtUseSite()) {
if (prev_not_move->IsNullCheck()) {
return prev_not_move->AsNullCheck();
}
prev_not_move = prev_not_move->GetPreviousDisregardingMoves();
}
return nullptr;
}
virtual bool IsActualObject() const {
return GetType() == DataType::Type::kReference;
}
// Sets the ReferenceTypeInfo. The RTI must be valid.
void SetReferenceTypeInfo(ReferenceTypeInfo rti);
// Same as above, but we only set it if it's valid. Otherwise, we don't change the current RTI.
void SetReferenceTypeInfoIfValid(ReferenceTypeInfo rti);
ReferenceTypeInfo GetReferenceTypeInfo() const {
DCHECK_EQ(GetType(), DataType::Type::kReference);
return ReferenceTypeInfo::CreateUnchecked(reference_type_handle_,
GetPackedFlag<kFlagReferenceTypeIsExact>());
}
void AddUseAt(HInstruction* user, size_t index) {
DCHECK(user != nullptr);
// Note: fixup_end remains valid across push_front().
auto fixup_end = uses_.empty() ? uses_.begin() : ++uses_.begin();
ArenaAllocator* allocator = user->GetBlock()->GetGraph()->GetAllocator();
HUseListNode<HInstruction*>* new_node =
new (allocator) HUseListNode<HInstruction*>(user, index);
uses_.push_front(*new_node);
FixUpUserRecordsAfterUseInsertion(fixup_end);
}
void AddEnvUseAt(HEnvironment* user, size_t index) {
DCHECK(user != nullptr);
// Note: env_fixup_end remains valid across push_front().
auto env_fixup_end = env_uses_.empty() ? env_uses_.begin() : ++env_uses_.begin();
HUseListNode<HEnvironment*>* new_node =
new (GetBlock()->GetGraph()->GetAllocator()) HUseListNode<HEnvironment*>(user, index);
env_uses_.push_front(*new_node);
FixUpUserRecordsAfterEnvUseInsertion(env_fixup_end);
}
void RemoveAsUserOfInput(size_t input) {
HUserRecord<HInstruction*> input_use = InputRecordAt(input);
HUseList<HInstruction*>::iterator before_use_node = input_use.GetBeforeUseNode();
input_use.GetInstruction()->uses_.erase_after(before_use_node);
input_use.GetInstruction()->FixUpUserRecordsAfterUseRemoval(before_use_node);
}
void RemoveAsUserOfAllInputs() {
for (const HUserRecord<HInstruction*>& input_use : GetInputRecords()) {
HUseList<HInstruction*>::iterator before_use_node = input_use.GetBeforeUseNode();
input_use.GetInstruction()->uses_.erase_after(before_use_node);
input_use.GetInstruction()->FixUpUserRecordsAfterUseRemoval(before_use_node);
}
}
const HUseList<HInstruction*>& GetUses() const { return uses_; }
const HUseList<HEnvironment*>& GetEnvUses() const { return env_uses_; }
bool HasUses() const { return !uses_.empty() || !env_uses_.empty(); }
bool HasEnvironmentUses() const { return !env_uses_.empty(); }
bool HasNonEnvironmentUses() const { return !uses_.empty(); }
bool HasOnlyOneNonEnvironmentUse() const {
return !HasEnvironmentUses() && GetUses().HasExactlyOneElement();
}
bool IsRemovable() const {
return
!DoesAnyWrite() &&
!CanThrow() &&
!IsSuspendCheck() &&
!IsControlFlow() &&
!IsNop() &&
!IsParameterValue() &&
// If we added an explicit barrier then we should keep it.
!IsMemoryBarrier() &&
!IsConstructorFence();
}
bool IsDeadAndRemovable() const {
return IsRemovable() && !HasUses();
}
// Does this instruction dominate `other_instruction`?
// Aborts if this instruction and `other_instruction` are different phis.
bool Dominates(HInstruction* other_instruction) const;
// Same but with `strictly dominates` i.e. returns false if this instruction and
// `other_instruction` are the same.
bool StrictlyDominates(HInstruction* other_instruction) const;
int GetId() const { return id_; }
void SetId(int id) { id_ = id; }
int GetSsaIndex() const { return ssa_index_; }
void SetSsaIndex(int ssa_index) { ssa_index_ = ssa_index; }
bool HasSsaIndex() const { return ssa_index_ != -1; }
bool HasEnvironment() const { return environment_ != nullptr; }
HEnvironment* GetEnvironment() const { return environment_; }
IterationRange<HEnvironmentIterator> GetAllEnvironments() const {
return MakeIterationRange(HEnvironmentIterator(GetEnvironment()),
HEnvironmentIterator(nullptr));
}
// Set the `environment_` field. Raw because this method does not
// update the uses lists.
void SetRawEnvironment(HEnvironment* environment) {
DCHECK(environment_ == nullptr);
DCHECK_EQ(environment->GetHolder(), this);
environment_ = environment;
}
void InsertRawEnvironment(HEnvironment* environment) {
DCHECK(environment_ != nullptr);
DCHECK_EQ(environment->GetHolder(), this);
DCHECK(environment->GetParent() == nullptr);
environment->parent_ = environment_;
environment_ = environment;
}
void RemoveEnvironment();
// Set the environment of this instruction, copying it from `environment`. While
// copying, the uses lists are being updated.
void CopyEnvironmentFrom(HEnvironment* environment) {
DCHECK(environment_ == nullptr);
ArenaAllocator* allocator = GetBlock()->GetGraph()->GetAllocator();
environment_ = new (allocator) HEnvironment(allocator, *environment, this);
environment_->CopyFrom(environment);
if (environment->GetParent() != nullptr) {
environment_->SetAndCopyParentChain(allocator, environment->GetParent());
}
}
void CopyEnvironmentFromWithLoopPhiAdjustment(HEnvironment* environment,
HBasicBlock* block) {
DCHECK(environment_ == nullptr);
ArenaAllocator* allocator = GetBlock()->GetGraph()->GetAllocator();
environment_ = new (allocator) HEnvironment(allocator, *environment, this);
environment_->CopyFromWithLoopPhiAdjustment(environment, block);
if (environment->GetParent() != nullptr) {
environment_->SetAndCopyParentChain(allocator, environment->GetParent());
}
}
// Returns the number of entries in the environment. Typically, that is the
// number of dex registers in a method. It could be more in case of inlining.
size_t EnvironmentSize() const;
LocationSummary* GetLocations() const { return locations_; }
void SetLocations(LocationSummary* locations) { locations_ = locations; }
void ReplaceWith(HInstruction* instruction);
void ReplaceUsesDominatedBy(HInstruction* dominator,
HInstruction* replacement,
bool strictly_dominated = true);
void ReplaceEnvUsesDominatedBy(HInstruction* dominator, HInstruction* replacement);
void ReplaceInput(HInstruction* replacement, size_t index);
// This is almost the same as doing `ReplaceWith()`. But in this helper, the
// uses of this instruction by `other` are *not* updated.
void ReplaceWithExceptInReplacementAtIndex(HInstruction* other, size_t use_index) {
ReplaceWith(other);
other->ReplaceInput(this, use_index);
}
// Move `this` instruction before `cursor`
void MoveBefore(HInstruction* cursor, bool do_checks = true);
// Move `this` before its first user and out of any loops. If there is no
// out-of-loop user that dominates all other users, move the instruction
// to the end of the out-of-loop common dominator of the user's blocks.
//
// This can be used only on non-throwing instructions with no side effects that
// have at least one use but no environment uses.
void MoveBeforeFirstUserAndOutOfLoops();
#define INSTRUCTION_TYPE_CHECK(type, super) \
bool Is##type() const;
FOR_EACH_INSTRUCTION(INSTRUCTION_TYPE_CHECK)
#undef INSTRUCTION_TYPE_CHECK
#define INSTRUCTION_TYPE_CAST(type, super) \
const H##type* As##type() const; \
H##type* As##type();
FOR_EACH_INSTRUCTION(INSTRUCTION_TYPE_CAST)
#undef INSTRUCTION_TYPE_CAST
// Return a clone of the instruction if it is clonable (shallow copy by default, custom copy
// if a custom copy-constructor is provided for a particular type). If IsClonable() is false for
// the instruction then the behaviour of this function is undefined.
//
// Note: It is semantically valid to create a clone of the instruction only until
// prepare_for_register_allocator phase as lifetime, intervals and codegen info are not
// copied.
//
// Note: HEnvironment and some other fields are not copied and are set to default values, see
// 'explicit HInstruction(const HInstruction& other)' for details.
virtual HInstruction* Clone(ArenaAllocator* arena ATTRIBUTE_UNUSED) const {
LOG(FATAL) << "Cloning is not implemented for the instruction " <<
DebugName() << " " << GetId();
UNREACHABLE();
}
virtual bool IsFieldAccess() const {
return false;
}
virtual const FieldInfo& GetFieldInfo() const {
CHECK(IsFieldAccess()) << "Only callable on field accessors not " << DebugName() << " "
<< *this;
LOG(FATAL) << "Must be overridden by field accessors. Not implemented by " << *this;
UNREACHABLE();
}
// Return whether instruction can be cloned (copied).
virtual bool IsClonable() const { return false; }
// Returns whether the instruction can be moved within the graph.
// TODO: this method is used by LICM and GVN with possibly different
// meanings? split and rename?
virtual bool CanBeMoved() const { return false; }
// Returns whether any data encoded in the two instructions is equal.
// This method does not look at the inputs. Both instructions must be
// of the same type, otherwise the method has undefined behavior.
virtual bool InstructionDataEquals(const HInstruction* other ATTRIBUTE_UNUSED) const {
return false;
}
// Returns whether two instructions are equal, that is:
// 1) They have the same type and contain the same data (InstructionDataEquals).
// 2) Their inputs are identical.
bool Equals(const HInstruction* other) const;
InstructionKind GetKind() const { return GetPackedField<InstructionKindField>(); }
virtual size_t ComputeHashCode() const {
size_t result = GetKind();
for (const HInstruction* input : GetInputs()) {
result = (result * 31) + input->GetId();
}
return result;
}
SideEffects GetSideEffects() const { return side_effects_; }
void SetSideEffects(SideEffects other) { side_effects_ = other; }
void AddSideEffects(SideEffects other) { side_effects_.Add(other); }
size_t GetLifetimePosition() const { return lifetime_position_; }
void SetLifetimePosition(size_t position) { lifetime_position_ = position; }
LiveInterval* GetLiveInterval() const { return live_interval_; }
void SetLiveInterval(LiveInterval* interval) { live_interval_ = interval; }
bool HasLiveInterval() const { return live_interval_ != nullptr; }
bool IsSuspendCheckEntry() const { return IsSuspendCheck() && GetBlock()->IsEntryBlock(); }
// Returns whether the code generation of the instruction will require to have access
// to the current method. Such instructions are:
// (1): Instructions that require an environment, as calling the runtime requires
// to walk the stack and have the current method stored at a specific stack address.
// (2): HCurrentMethod, potentially used by HInvokeStaticOrDirect, HLoadString, or HLoadClass
// to access the dex cache.
bool NeedsCurrentMethod() const {
return NeedsEnvironment() || IsCurrentMethod();
}
// Does this instruction have any use in an environment before
// control flow hits 'other'?
bool HasAnyEnvironmentUseBefore(HInstruction* other);
// Remove all references to environment uses of this instruction.
// The caller must ensure that this is safe to do.
void RemoveEnvironmentUsers();
bool IsEmittedAtUseSite() const { return GetPackedFlag<kFlagEmittedAtUseSite>(); }
void MarkEmittedAtUseSite() { SetPackedFlag<kFlagEmittedAtUseSite>(true); }
protected:
// If set, the machine code for this instruction is assumed to be generated by
// its users. Used by liveness analysis to compute use positions accordingly.
static constexpr size_t kFlagEmittedAtUseSite = 0u;
static constexpr size_t kFlagReferenceTypeIsExact = kFlagEmittedAtUseSite + 1;
static constexpr size_t kFieldInstructionKind = kFlagReferenceTypeIsExact + 1;
static constexpr size_t kFieldInstructionKindSize =
MinimumBitsToStore(static_cast<size_t>(InstructionKind::kLastInstructionKind - 1));
static constexpr size_t kFieldType =
kFieldInstructionKind + kFieldInstructionKindSize;
static constexpr size_t kFieldTypeSize =
MinimumBitsToStore(static_cast<size_t>(DataType::Type::kLast));
static constexpr size_t kNumberOfGenericPackedBits = kFieldType + kFieldTypeSize;
static constexpr size_t kMaxNumberOfPackedBits = sizeof(uint32_t) * kBitsPerByte;
static_assert(kNumberOfGenericPackedBits <= kMaxNumberOfPackedBits,
"Too many generic packed fields");
using TypeField = BitField<DataType::Type, kFieldType, kFieldTypeSize>;
const HUserRecord<HInstruction*> InputRecordAt(size_t i) const {
return GetInputRecords()[i];
}
void SetRawInputRecordAt(size_t index, const HUserRecord<HInstruction*>& input) {
ArrayRef<HUserRecord<HInstruction*>> input_records = GetInputRecords();
input_records[index] = input;
}
uint32_t GetPackedFields() const {
return packed_fields_;
}
template <size_t flag>
bool GetPackedFlag() const {
return (packed_fields_ & (1u << flag)) != 0u;
}
template <size_t flag>
void SetPackedFlag(bool value = true) {
packed_fields_ = (packed_fields_ & ~(1u << flag)) | ((value ? 1u : 0u) << flag);
}
template <typename BitFieldType>
typename BitFieldType::value_type GetPackedField() const {
return BitFieldType::Decode(packed_fields_);
}
template <typename BitFieldType>
void SetPackedField(typename BitFieldType::value_type value) {
DCHECK(IsUint<BitFieldType::size>(static_cast<uintptr_t>(value)));
packed_fields_ = BitFieldType::Update(value, packed_fields_);
}
// Copy construction for the instruction (used for Clone function).
//
// Fields (e.g. lifetime, intervals and codegen info) associated with phases starting from
// prepare_for_register_allocator are not copied (set to default values).
//
// Copy constructors must be provided for every HInstruction type; default copy constructor is
// fine for most of them. However for some of the instructions a custom copy constructor must be
// specified (when instruction has non-trivially copyable fields and must have a special behaviour
// for copying them).
explicit HInstruction(const HInstruction& other)
: previous_(nullptr),
next_(nullptr),
block_(nullptr),
dex_pc_(other.dex_pc_),
id_(-1),
ssa_index_(-1),
packed_fields_(other.packed_fields_),
environment_(nullptr),
locations_(nullptr),
live_interval_(nullptr),
lifetime_position_(kNoLifetime),
side_effects_(other.side_effects_),
reference_type_handle_(other.reference_type_handle_) {
}
private:
using InstructionKindField =
BitField<InstructionKind, kFieldInstructionKind, kFieldInstructionKindSize>;
void FixUpUserRecordsAfterUseInsertion(HUseList<HInstruction*>::iterator fixup_end) {
auto before_use_node = uses_.before_begin();
for (auto use_node = uses_.begin(); use_node != fixup_end; ++use_node) {
HInstruction* user = use_node->GetUser();
size_t input_index = use_node->GetIndex();
user->SetRawInputRecordAt(input_index, HUserRecord<HInstruction*>(this, before_use_node));
before_use_node = use_node;
}
}
void FixUpUserRecordsAfterUseRemoval(HUseList<HInstruction*>::iterator before_use_node) {
auto next = ++HUseList<HInstruction*>::iterator(before_use_node);
if (next != uses_.end()) {
HInstruction* next_user = next->GetUser();
size_t next_index = next->GetIndex();
DCHECK(next_user->InputRecordAt(next_index).GetInstruction() == this);
next_user->SetRawInputRecordAt(next_index, HUserRecord<HInstruction*>(this, before_use_node));
}
}
void FixUpUserRecordsAfterEnvUseInsertion(HUseList<HEnvironment*>::iterator env_fixup_end) {
auto before_env_use_node = env_uses_.before_begin();
for (auto env_use_node = env_uses_.begin(); env_use_node != env_fixup_end; ++env_use_node) {
HEnvironment* user = env_use_node->GetUser();
size_t input_index = env_use_node->GetIndex();
user->vregs_[input_index] = HUserRecord<HEnvironment*>(this, before_env_use_node);
before_env_use_node = env_use_node;
}
}
void FixUpUserRecordsAfterEnvUseRemoval(HUseList<HEnvironment*>::iterator before_env_use_node) {
auto next = ++HUseList<HEnvironment*>::iterator(before_env_use_node);
if (next != env_uses_.end()) {
HEnvironment* next_user = next->GetUser();
size_t next_index = next->GetIndex();
DCHECK(next_user->vregs_[next_index].GetInstruction() == this);
next_user->vregs_[next_index] = HUserRecord<HEnvironment*>(this, before_env_use_node);
}
}
HInstruction* previous_;
HInstruction* next_;
HBasicBlock* block_;
const uint32_t dex_pc_;
// An instruction gets an id when it is added to the graph.
// It reflects creation order. A negative id means the instruction
// has not been added to the graph.
int id_;
// When doing liveness analysis, instructions that have uses get an SSA index.
int ssa_index_;
// Packed fields.
uint32_t packed_fields_;
// List of instructions that have this instruction as input.
HUseList<HInstruction*> uses_;
// List of environments that contain this instruction.
HUseList<HEnvironment*> env_uses_;
// The environment associated with this instruction. Not null if the instruction
// might jump out of the method.
HEnvironment* environment_;
// Set by the code generator.
LocationSummary* locations_;
// Set by the liveness analysis.
LiveInterval* live_interval_;
// Set by the liveness analysis, this is the position in a linear
// order of blocks where this instruction's live interval start.
size_t lifetime_position_;
SideEffects side_effects_;
// The reference handle part of the reference type info.
// The IsExact() flag is stored in packed fields.
// TODO: for primitive types this should be marked as invalid.
ReferenceTypeInfo::TypeHandle reference_type_handle_;
friend class GraphChecker;
friend class HBasicBlock;
friend class HEnvironment;
friend class HGraph;
friend class HInstructionList;
};
std::ostream& operator<<(std::ostream& os, HInstruction::InstructionKind rhs);
std::ostream& operator<<(std::ostream& os, const HInstruction::NoArgsDump rhs);
std::ostream& operator<<(std::ostream& os, const HInstruction::ArgsDump rhs);
std::ostream& operator<<(std::ostream& os, const HUseList<HInstruction*>& lst);
std::ostream& operator<<(std::ostream& os, const HUseList<HEnvironment*>& lst);
// Forward declarations for friends
template <typename InnerIter> struct HSTLInstructionIterator;
// Iterates over the instructions, while preserving the next instruction
// in case the current instruction gets removed from the list by the user
// of this iterator.
class HInstructionIterator : public ValueObject {
public:
explicit HInstructionIterator(const HInstructionList& instructions)
: instruction_(instructions.first_instruction_) {
next_ = Done() ? nullptr : instruction_->GetNext();
}
bool Done() const { return instruction_ == nullptr; }
HInstruction* Current() const { return instruction_; }
void Advance() {
instruction_ = next_;
next_ = Done() ? nullptr : instruction_->GetNext();
}
private:
HInstructionIterator() : instruction_(nullptr), next_(nullptr) {}
HInstruction* instruction_;
HInstruction* next_;
friend struct HSTLInstructionIterator<HInstructionIterator>;
};
// Iterates over the instructions without saving the next instruction,
// therefore handling changes in the graph potentially made by the user
// of this iterator.
class HInstructionIteratorHandleChanges : public ValueObject {
public:
explicit HInstructionIteratorHandleChanges(const HInstructionList& instructions)
: instruction_(instructions.first_instruction_) {
}
bool Done() const { return instruction_ == nullptr; }
HInstruction* Current() const { return instruction_; }
void Advance() {
instruction_ = instruction_->GetNext();
}
private:
HInstructionIteratorHandleChanges() : instruction_(nullptr) {}
HInstruction* instruction_;
friend struct HSTLInstructionIterator<HInstructionIteratorHandleChanges>;
};
class HBackwardInstructionIterator : public ValueObject {
public:
explicit HBackwardInstructionIterator(const HInstructionList& instructions)
: instruction_(instructions.last_instruction_) {
next_ = Done() ? nullptr : instruction_->GetPrevious();
}
bool Done() const { return instruction_ == nullptr; }
HInstruction* Current() const { return instruction_; }
void Advance() {
instruction_ = next_;
next_ = Done() ? nullptr : instruction_->GetPrevious();
}
private:
HBackwardInstructionIterator() : instruction_(nullptr), next_(nullptr) {}
HInstruction* instruction_;
HInstruction* next_;
friend struct HSTLInstructionIterator<HBackwardInstructionIterator>;
};
template <typename InnerIter>
struct HSTLInstructionIterator : public ValueObject,
public std::iterator<std::forward_iterator_tag, HInstruction*> {
public:
static_assert(std::is_same_v<InnerIter, HBackwardInstructionIterator> ||
std::is_same_v<InnerIter, HInstructionIterator> ||
std::is_same_v<InnerIter, HInstructionIteratorHandleChanges>,
"Unknown wrapped iterator!");
explicit HSTLInstructionIterator(InnerIter inner) : inner_(inner) {}
HInstruction* operator*() const {
DCHECK(inner_.Current() != nullptr);
return inner_.Current();
}
HSTLInstructionIterator<InnerIter>& operator++() {
DCHECK(*this != HSTLInstructionIterator<InnerIter>::EndIter());
inner_.Advance();
return *this;
}
HSTLInstructionIterator<InnerIter> operator++(int) {
HSTLInstructionIterator<InnerIter> prev(*this);
++(*this);
return prev;
}
bool operator==(const HSTLInstructionIterator<InnerIter>& other) const {
return inner_.Current() == other.inner_.Current();
}
bool operator!=(const HSTLInstructionIterator<InnerIter>& other) const {
return !(*this == other);
}
static HSTLInstructionIterator<InnerIter> EndIter() {
return HSTLInstructionIterator<InnerIter>(InnerIter());
}
private:
InnerIter inner_;
};
template <typename InnerIter>
IterationRange<HSTLInstructionIterator<InnerIter>> MakeSTLInstructionIteratorRange(InnerIter iter) {
return MakeIterationRange(HSTLInstructionIterator<InnerIter>(iter),
HSTLInstructionIterator<InnerIter>::EndIter());
}
class HVariableInputSizeInstruction : public HInstruction {
public:
using HInstruction::GetInputRecords; // Keep the const version visible.
ArrayRef<HUserRecord<HInstruction*>> GetInputRecords() override {
return ArrayRef<HUserRecord<HInstruction*>>(inputs_);
}
void AddInput(HInstruction* input);
void InsertInputAt(size_t index, HInstruction* input);
void RemoveInputAt(size_t index);
// Removes all the inputs.
// Also removes this instructions from each input's use list
// (for non-environment uses only).
void RemoveAllInputs();
protected:
HVariableInputSizeInstruction(InstructionKind inst_kind,
SideEffects side_effects,
uint32_t dex_pc,
ArenaAllocator* allocator,
size_t number_of_inputs,
ArenaAllocKind kind)
: HInstruction(inst_kind, side_effects, dex_pc),
inputs_(number_of_inputs, allocator->Adapter(kind)) {}
HVariableInputSizeInstruction(InstructionKind inst_kind,
DataType::Type type,
SideEffects side_effects,
uint32_t dex_pc,
ArenaAllocator* allocator,
size_t number_of_inputs,
ArenaAllocKind kind)
: HInstruction(inst_kind, type, side_effects, dex_pc),
inputs_(number_of_inputs, allocator->Adapter(kind)) {}
DEFAULT_COPY_CONSTRUCTOR(VariableInputSizeInstruction);
ArenaVector<HUserRecord<HInstruction*>> inputs_;
};
template<size_t N>
class HExpression : public HInstruction {
public:
HExpression<N>(InstructionKind kind, SideEffects side_effects, uint32_t dex_pc)
: HInstruction(kind, side_effects, dex_pc), inputs_() {}
HExpression<N>(InstructionKind kind,
DataType::Type type,
SideEffects side_effects,
uint32_t dex_pc)
: HInstruction(kind, type, side_effects, dex_pc), inputs_() {}
virtual ~HExpression() {}
using HInstruction::GetInputRecords; // Keep the const version visible.
ArrayRef<HUserRecord<HInstruction*>> GetInputRecords() final {
return ArrayRef<HUserRecord<HInstruction*>>(inputs_);
}
protected:
DEFAULT_COPY_CONSTRUCTOR(Expression<N>);
private:
std::array<HUserRecord<HInstruction*>, N> inputs_;
friend class SsaBuilder;
};
// HExpression specialization for N=0.
template<>
class HExpression<0> : public HInstruction {
public:
using HInstruction::HInstruction;
virtual ~HExpression() {}
using HInstruction::GetInputRecords; // Keep the const version visible.
ArrayRef<HUserRecord<HInstruction*>> GetInputRecords() final {
return ArrayRef<HUserRecord<HInstruction*>>();
}
protected:
DEFAULT_COPY_CONSTRUCTOR(Expression<0>);
private:
friend class SsaBuilder;
};
class HMethodEntryHook : public HExpression<0> {
public:
explicit HMethodEntryHook(uint32_t dex_pc)
: HExpression(kMethodEntryHook, SideEffects::All(), dex_pc) {}
bool NeedsEnvironment() const override {
return true;
}
bool CanThrow() const override { return true; }
DECLARE_INSTRUCTION(MethodEntryHook);
protected:
DEFAULT_COPY_CONSTRUCTOR(MethodEntryHook);
};
class HMethodExitHook : public HExpression<1> {
public:
HMethodExitHook(HInstruction* value, uint32_t dex_pc)
: HExpression(kMethodExitHook, SideEffects::All(), dex_pc) {
SetRawInputAt(0, value);
}
bool NeedsEnvironment() const override {
return true;
}
bool CanThrow() const override { return true; }
DECLARE_INSTRUCTION(MethodExitHook);
protected:
DEFAULT_COPY_CONSTRUCTOR(MethodExitHook);
};
// Represents dex's RETURN_VOID opcode. A HReturnVoid is a control flow
// instruction that branches to the exit block.
class HReturnVoid final : public HExpression<0> {
public:
explicit HReturnVoid(uint32_t dex_pc = kNoDexPc)
: HExpression(kReturnVoid, SideEffects::None(), dex_pc) {
}
bool IsControlFlow() const override { return true; }
DECLARE_INSTRUCTION(ReturnVoid);
protected:
DEFAULT_COPY_CONSTRUCTOR(ReturnVoid);
};
// Represents dex's RETURN opcodes. A HReturn is a control flow
// instruction that branches to the exit block.
class HReturn final : public HExpression<1> {
public:
explicit HReturn(HInstruction* value, uint32_t dex_pc = kNoDexPc)
: HExpression(kReturn, SideEffects::None(), dex_pc) {
SetRawInputAt(0, value);
}
bool IsControlFlow() const override { return true; }
DECLARE_INSTRUCTION(Return);
protected:
DEFAULT_COPY_CONSTRUCTOR(Return);
};
class HPhi final : public HVariableInputSizeInstruction {
public:
HPhi(ArenaAllocator* allocator,
uint32_t reg_number,
size_t number_of_inputs,
DataType::Type type,
uint32_t dex_pc = kNoDexPc)
: HVariableInputSizeInstruction(
kPhi,
ToPhiType(type),
SideEffects::None(),
dex_pc,
allocator,
number_of_inputs,
kArenaAllocPhiInputs),
reg_number_(reg_number) {
DCHECK_NE(GetType(), DataType::Type::kVoid);
// Phis are constructed live and marked dead if conflicting or unused.
// Individual steps of SsaBuilder should assume that if a phi has been
// marked dead, it can be ignored and will be removed by SsaPhiElimination.
SetPackedFlag<kFlagIsLive>(true);
SetPackedFlag<kFlagCanBeNull>(true);
}
bool IsClonable() const override { return true; }
// Returns a type equivalent to the given `type`, but that a `HPhi` can hold.
static DataType::Type ToPhiType(DataType::Type type) {
return DataType::Kind(type);
}
bool IsCatchPhi() const { return GetBlock()->IsCatchBlock(); }
void SetType(DataType::Type new_type) {
// Make sure that only valid type changes occur. The following are allowed:
// (1) int -> float/ref (primitive type propagation),
// (2) long -> double (primitive type propagation).
DCHECK(GetType() == new_type ||
(GetType() == DataType::Type::kInt32 && new_type == DataType::Type::kFloat32) ||
(GetType() == DataType::Type::kInt32 && new_type == DataType::Type::kReference) ||
(GetType() == DataType::Type::kInt64 && new_type == DataType::Type::kFloat64));
SetPackedField<TypeField>(new_type);
}
bool CanBeNull() const override { return GetPackedFlag<kFlagCanBeNull>(); }
void SetCanBeNull(bool can_be_null) { SetPackedFlag<kFlagCanBeNull>(can_be_null); }
uint32_t GetRegNumber() const { return reg_number_; }
void SetDead() { SetPackedFlag<kFlagIsLive>(false); }
void SetLive() { SetPackedFlag<kFlagIsLive>(true); }
bool IsDead() const { return !IsLive(); }
bool IsLive() const { return GetPackedFlag<kFlagIsLive>(); }
bool IsVRegEquivalentOf(const HInstruction* other) const {
return other != nullptr
&& other->IsPhi()
&& other->AsPhi()->GetBlock() == GetBlock()
&& other->AsPhi()->GetRegNumber() == GetRegNumber();
}
bool HasEquivalentPhi() const {
if (GetPrevious() != nullptr && GetPrevious()->AsPhi()->GetRegNumber() == GetRegNumber()) {
return true;
}
if (GetNext() != nullptr && GetNext()->AsPhi()->GetRegNumber() == GetRegNumber()) {
return true;
}
return false;
}
// Returns the next equivalent phi (starting from the current one) or null if there is none.
// An equivalent phi is a phi having the same dex register and type.
// It assumes that phis with the same dex register are adjacent.
HPhi* GetNextEquivalentPhiWithSameType() {
HInstruction* next = GetNext();
while (next != nullptr && next->AsPhi()->GetRegNumber() == reg_number_) {
if (next->GetType() == GetType()) {
return next->AsPhi();
}
next = next->GetNext();
}
return nullptr;
}
DECLARE_INSTRUCTION(Phi);
protected:
DEFAULT_COPY_CONSTRUCTOR(Phi);
private:
static constexpr size_t kFlagIsLive = HInstruction::kNumberOfGenericPackedBits;
static constexpr size_t kFlagCanBeNull = kFlagIsLive + 1;
static constexpr size_t kNumberOfPhiPackedBits = kFlagCanBeNull + 1;
static_assert(kNumberOfPhiPackedBits <= kMaxNumberOfPackedBits, "Too many packed fields.");
const uint32_t reg_number_;
};
// The exit instruction is the only instruction of the exit block.
// Instructions aborting the method (HThrow and HReturn) must branch to the
// exit block.
class HExit final : public HExpression<0> {
public:
explicit HExit(uint32_t dex_pc = kNoDexPc)
: HExpression(kExit, SideEffects::None(), dex_pc) {
}
bool IsControlFlow() const override { return true; }
DECLARE_INSTRUCTION(Exit);
protected:
DEFAULT_COPY_CONSTRUCTOR(Exit);
};
// Jumps from one block to another.
class HGoto final : public HExpression<0> {
public:
explicit HGoto(uint32_t dex_pc = kNoDexPc)
: HExpression(kGoto, SideEffects::None(), dex_pc) {
}
bool IsClonable() const override { return true; }
bool IsControlFlow() const override { return true; }
HBasicBlock* GetSuccessor() const {
return GetBlock()->GetSingleSuccessor();
}
DECLARE_INSTRUCTION(Goto);
protected:
DEFAULT_COPY_CONSTRUCTOR(Goto);
};
class HConstant : public HExpression<0> {
public:
explicit HConstant(InstructionKind kind, DataType::Type type, uint32_t dex_pc = kNoDexPc)
: HExpression(kind, type, SideEffects::None(), dex_pc) {
}
bool CanBeMoved() const override { return true; }
// Is this constant -1 in the arithmetic sense?
virtual bool IsMinusOne() const { return false; }
// Is this constant 0 in the arithmetic sense?
virtual bool IsArithmeticZero() const { return false; }
// Is this constant a 0-bit pattern?
virtual bool IsZeroBitPattern() const { return false; }
// Is this constant 1 in the arithmetic sense?
virtual bool IsOne() const { return false; }
virtual uint64_t GetValueAsUint64() const = 0;
DECLARE_ABSTRACT_INSTRUCTION(Constant);
protected:
DEFAULT_COPY_CONSTRUCTOR(Constant);
};
class HNullConstant final : public HConstant {
public:
bool InstructionDataEquals(const HInstruction* other ATTRIBUTE_UNUSED) const override {
return true;
}
uint64_t GetValueAsUint64() const override { return 0; }
size_t ComputeHashCode() const override { return 0; }
// The null constant representation is a 0-bit pattern.
bool IsZeroBitPattern() const override { return true; }
DECLARE_INSTRUCTION(NullConstant);
protected:
DEFAULT_COPY_CONSTRUCTOR(NullConstant);
private:
explicit HNullConstant(uint32_t dex_pc = kNoDexPc)
: HConstant(kNullConstant, DataType::Type::kReference, dex_pc) {
}
friend class HGraph;
};
// Constants of the type int. Those can be from Dex instructions, or
// synthesized (for example with the if-eqz instruction).
class HIntConstant final : public HConstant {
public:
int32_t GetValue() const { return value_; }
uint64_t GetValueAsUint64() const override {
return static_cast<uint64_t>(static_cast<uint32_t>(value_));
}
bool InstructionDataEquals(const HInstruction* other) const override {
DCHECK(other->IsIntConstant()) << other->DebugName();
return other->AsIntConstant()->value_ == value_;
}
size_t ComputeHashCode() const override { return GetValue(); }
bool IsMinusOne() const override { return GetValue() == -1; }
bool IsArithmeticZero() const override { return GetValue() == 0; }
bool IsZeroBitPattern() const override { return GetValue() == 0; }
bool IsOne() const override { return GetValue() == 1; }
// Integer constants are used to encode Boolean values as well,
// where 1 means true and 0 means false.
bool IsTrue() const { return GetValue() == 1; }
bool IsFalse() const { return GetValue() == 0; }
DECLARE_INSTRUCTION(IntConstant);
protected:
DEFAULT_COPY_CONSTRUCTOR(IntConstant);
private:
explicit HIntConstant(int32_t value, uint32_t dex_pc = kNoDexPc)
: HConstant(kIntConstant, DataType::Type::kInt32, dex_pc), value_(value) {
}
explicit HIntConstant(bool value, uint32_t dex_pc = kNoDexPc)
: HConstant(kIntConstant, DataType::Type::kInt32, dex_pc),
value_(value ? 1 : 0) {
}
const int32_t value_;
friend class HGraph;
ART_FRIEND_TEST(GraphTest, InsertInstructionBefore);
ART_FRIEND_TYPED_TEST(ParallelMoveTest, ConstantLast);
};
class HLongConstant final : public HConstant {
public:
int64_t GetValue() const { return value_; }
uint64_t GetValueAsUint64() const override { return value_; }
bool InstructionDataEquals(const HInstruction* other) const override {
DCHECK(other->IsLongConstant()) << other->DebugName();
return other->AsLongConstant()->value_ == value_;
}
size_t ComputeHashCode() const override { return static_cast<size_t>(GetValue()); }
bool IsMinusOne() const override { return GetValue() == -1; }
bool IsArithmeticZero() const override { return GetValue() == 0; }
bool IsZeroBitPattern() const override { return GetValue() == 0; }
bool IsOne() const override { return GetValue() == 1; }
DECLARE_INSTRUCTION(LongConstant);
protected:
DEFAULT_COPY_CONSTRUCTOR(LongConstant);
private:
explicit HLongConstant(int64_t value, uint32_t dex_pc = kNoDexPc)
: HConstant(kLongConstant, DataType::Type::kInt64, dex_pc),
value_(value) {
}
const int64_t value_;
friend class HGraph;
};
class HFloatConstant final : public HConstant {
public:
float GetValue() const { return value_; }
uint64_t GetValueAsUint64() const override {
return static_cast<uint64_t>(bit_cast<uint32_t, float>(value_));
}
bool InstructionDataEquals(const HInstruction* other) const override {
DCHECK(other->IsFloatConstant()) << other->DebugName();
return other->AsFloatConstant()->GetValueAsUint64() == GetValueAsUint64();
}
size_t ComputeHashCode() const override { return static_cast<size_t>(GetValue()); }
bool IsMinusOne() const override {
return bit_cast<uint32_t, float>(value_) == bit_cast<uint32_t, float>((-1.0f));
}
bool IsArithmeticZero() const override {
return std::fpclassify(value_) == FP_ZERO;
}
bool IsArithmeticPositiveZero() const {
return IsArithmeticZero() && !std::signbit(value_);
}
bool IsArithmeticNegativeZero() const {
return IsArithmeticZero() && std::signbit(value_);
}
bool IsZeroBitPattern() const override {
return bit_cast<uint32_t, float>(value_) == bit_cast<uint32_t, float>(0.0f);
}
bool IsOne() const override {
return bit_cast<uint32_t, float>(value_) == bit_cast<uint32_t, float>(1.0f);
}
bool IsNaN() const {
return std::isnan(value_);
}
DECLARE_INSTRUCTION(FloatConstant);
protected:
DEFAULT_COPY_CONSTRUCTOR(FloatConstant);
private:
explicit HFloatConstant(float value, uint32_t dex_pc = kNoDexPc)
: HConstant(kFloatConstant, DataType::Type::kFloat32, dex_pc),
value_(value) {
}
explicit HFloatConstant(int32_t value, uint32_t dex_pc = kNoDexPc)
: HConstant(kFloatConstant, DataType::Type::kFloat32, dex_pc),
value_(bit_cast<float, int32_t>(value)) {
}
const float value_;
// Only the SsaBuilder and HGraph can create floating-point constants.
friend class SsaBuilder;
friend class HGraph;
};
class HDoubleConstant final : public HConstant {
public:
double GetValue() const { return value_; }
uint64_t GetValueAsUint64() const override { return bit_cast<uint64_t, double>(value_); }
bool InstructionDataEquals(const HInstruction* other) const override {
DCHECK(other->IsDoubleConstant()) << other->DebugName();
return other->AsDoubleConstant()->GetValueAsUint64() == GetValueAsUint64();
}
size_t ComputeHashCode() const override { return static_cast<size_t>(GetValue()); }
bool IsMinusOne() const override {
return bit_cast<uint64_t, double>(value_) == bit_cast<uint64_t, double>((-1.0));
}
bool IsArithmeticZero() const override {
return std::fpclassify(value_) == FP_ZERO;
}
bool IsArithmeticPositiveZero() const {
return IsArithmeticZero() && !std::signbit(value_);
}
bool IsArithmeticNegativeZero() const {
return IsArithmeticZero() && std::signbit(value_);
}
bool IsZeroBitPattern() const override {
return bit_cast<uint64_t, double>(value_) == bit_cast<uint64_t, double>((0.0));
}
bool IsOne() const override {
return bit_cast<uint64_t, double>(value_) == bit_cast<uint64_t, double>(1.0);
}
bool IsNaN() const {
return std::isnan(value_);
}
DECLARE_INSTRUCTION(DoubleConstant);
protected:
DEFAULT_COPY_CONSTRUCTOR(DoubleConstant);
private:
explicit HDoubleConstant(double value, uint32_t dex_pc = kNoDexPc)
: HConstant(kDoubleConstant, DataType::Type::kFloat64, dex_pc),
value_(value) {
}
explicit HDoubleConstant(int64_t value, uint32_t dex_pc = kNoDexPc)
: HConstant(kDoubleConstant, DataType::Type::kFloat64, dex_pc),
value_(bit_cast<double, int64_t>(value)) {
}
const double value_;
// Only the SsaBuilder and HGraph can create floating-point constants.
friend class SsaBuilder;
friend class HGraph;
};
// Conditional branch. A block ending with an HIf instruction must have
// two successors.
class HIf final : public HExpression<1> {
public:
explicit HIf(HInstruction* input, uint32_t dex_pc = kNoDexPc)
: HExpression(kIf, SideEffects::None(), dex_pc) {
SetRawInputAt(0, input);
}
bool IsClonable() const override { return true; }
bool IsControlFlow() const override { return true; }
HBasicBlock* IfTrueSuccessor() const {
return GetBlock()->GetSuccessors()[0];
}
HBasicBlock* IfFalseSuccessor() const {
return GetBlock()->GetSuccessors()[1];
}
DECLARE_INSTRUCTION(If);
protected:
DEFAULT_COPY_CONSTRUCTOR(If);
};
// Abstract instruction which marks the beginning and/or end of a try block and
// links it to the respective exception handlers. Behaves the same as a Goto in
// non-exceptional control flow.
// Normal-flow successor is stored at index zero, exception handlers under
// higher indices in no particular order.
class HTryBoundary final : public HExpression<0> {
public:
enum class BoundaryKind {
kEntry,
kExit,
kLast = kExit
};
// SideEffects::CanTriggerGC prevents instructions with SideEffects::DependOnGC to be alive
// across the catch block entering edges as GC might happen during throwing an exception.
// TryBoundary with BoundaryKind::kExit is conservatively used for that as there is no
// HInstruction which a catch block must start from.
explicit HTryBoundary(BoundaryKind kind, uint32_t dex_pc = kNoDexPc)
: HExpression(kTryBoundary,
(kind == BoundaryKind::kExit) ? SideEffects::CanTriggerGC()
: SideEffects::None(),
dex_pc) {
SetPackedField<BoundaryKindField>(kind);
}
bool IsControlFlow() const override { return true; }
// Returns the block's non-exceptional successor (index zero).
HBasicBlock* GetNormalFlowSuccessor() const { return GetBlock()->GetSuccessors()[0]; }
ArrayRef<HBasicBlock* const> GetExceptionHandlers() const {
return ArrayRef<HBasicBlock* const>(GetBlock()->GetSuccessors()).SubArray(1u);
}
// Returns whether `handler` is among its exception handlers (non-zero index
// successors).
bool HasExceptionHandler(const HBasicBlock& handler) const {
DCHECK(handler.IsCatchBlock());
return GetBlock()->HasSuccessor(&handler, 1u /* Skip first successor. */);
}
// If not present already, adds `handler` to its block's list of exception
// handlers.
void AddExceptionHandler(HBasicBlock* handler) {
if (!HasExceptionHandler(*handler)) {
GetBlock()->AddSuccessor(handler);
}
}
BoundaryKind GetBoundaryKind() const { return GetPackedField<BoundaryKindField>(); }
bool IsEntry() const { return GetBoundaryKind() == BoundaryKind::kEntry; }
bool HasSameExceptionHandlersAs(const HTryBoundary& other) const;
DECLARE_INSTRUCTION(TryBoundary);
protected:
DEFAULT_COPY_CONSTRUCTOR(TryBoundary);
private:
static constexpr size_t kFieldBoundaryKind = kNumberOfGenericPackedBits;
static constexpr size_t kFieldBoundaryKindSize =
MinimumBitsToStore(static_cast<size_t>(BoundaryKind::kLast));
static constexpr size_t kNumberOfTryBoundaryPackedBits =
kFieldBoundaryKind + kFieldBoundaryKindSize;
static_assert(kNumberOfTryBoundaryPackedBits <= kMaxNumberOfPackedBits,
"Too many packed fields.");
using BoundaryKindField = BitField<BoundaryKind, kFieldBoundaryKind, kFieldBoundaryKindSize>;
};
// Deoptimize to interpreter, upon checking a condition.
class HDeoptimize final : public HVariableInputSizeInstruction {
public:
// Use this constructor when the `HDeoptimize` acts as a barrier, where no code can move
// across.
HDeoptimize(ArenaAllocator* allocator,
HInstruction* cond,
DeoptimizationKind kind,
uint32_t dex_pc)
: HVariableInputSizeInstruction(
kDeoptimize,
SideEffects::All(),
dex_pc,
allocator,
/* number_of_inputs= */ 1,
kArenaAllocMisc) {
SetPackedFlag<kFieldCanBeMoved>(false);
SetPackedField<DeoptimizeKindField>(kind);
SetRawInputAt(0, cond);
}
bool IsClonable() const override { return true; }
// Use this constructor when the `HDeoptimize` guards an instruction, and any user
// that relies on the deoptimization to pass should have its input be the `HDeoptimize`
// instead of `guard`.
// We set CanTriggerGC to prevent any intermediate address to be live
// at the point of the `HDeoptimize`.
HDeoptimize(ArenaAllocator* allocator,
HInstruction* cond,
HInstruction* guard,
DeoptimizationKind kind,
uint32_t dex_pc)
: HVariableInputSizeInstruction(
kDeoptimize,
guard->GetType(),
SideEffects::CanTriggerGC(),
dex_pc,
allocator,
/* number_of_inputs= */ 2,
kArenaAllocMisc) {
SetPackedFlag<kFieldCanBeMoved>(true);
SetPackedField<DeoptimizeKindField>(kind);
SetRawInputAt(0, cond);
SetRawInputAt(1, guard);
}
bool CanBeMoved() const override { return GetPackedFlag<kFieldCanBeMoved>(); }
bool InstructionDataEquals(const HInstruction* other) const override {
return (other->CanBeMoved() == CanBeMoved()) && (other->AsDeoptimize()->GetKind() == GetKind());
}
bool NeedsEnvironment() const override { return true; }
bool CanThrow() const override { return true; }
DeoptimizationKind GetDeoptimizationKind() const { return GetPackedField<DeoptimizeKindField>(); }
bool GuardsAnInput() const {
return InputCount() == 2;
}
HInstruction* GuardedInput() const {
DCHECK(GuardsAnInput());
return InputAt(1);
}
void RemoveGuard() {
RemoveInputAt(1);
}
DECLARE_INSTRUCTION(Deoptimize);
protected:
DEFAULT_COPY_CONSTRUCTOR(Deoptimize);
private:
static constexpr size_t kFieldCanBeMoved = kNumberOfGenericPackedBits;
static constexpr size_t kFieldDeoptimizeKind = kNumberOfGenericPackedBits + 1;
static constexpr size_t kFieldDeoptimizeKindSize =
MinimumBitsToStore(static_cast<size_t>(DeoptimizationKind::kLast));
static constexpr size_t kNumberOfDeoptimizePackedBits =
kFieldDeoptimizeKind + kFieldDeoptimizeKindSize;
static_assert(kNumberOfDeoptimizePackedBits <= kMaxNumberOfPackedBits,
"Too many packed fields.");
using DeoptimizeKindField =
BitField<DeoptimizationKind, kFieldDeoptimizeKind, kFieldDeoptimizeKindSize>;
};
// Represents a should_deoptimize flag. Currently used for CHA-based devirtualization.
// The compiled code checks this flag value in a guard before devirtualized call and
// if it's true, starts to do deoptimization.
// It has a 4-byte slot on stack.
// TODO: allocate a register for this flag.
class HShouldDeoptimizeFlag final : public HVariableInputSizeInstruction {
public:
// CHA guards are only optimized in a separate pass and it has no side effects
// with regard to other passes.
HShouldDeoptimizeFlag(ArenaAllocator* allocator, uint32_t dex_pc)
: HVariableInputSizeInstruction(kShouldDeoptimizeFlag,
DataType::Type::kInt32,
SideEffects::None(),
dex_pc,
allocator,
0,
kArenaAllocCHA) {
}
// We do all CHA guard elimination/motion in a single pass, after which there is no
// further guard elimination/motion since a guard might have been used for justification
// of the elimination of another guard. Therefore, we pretend this guard cannot be moved
// to avoid other optimizations trying to move it.
bool CanBeMoved() const override { return false; }
DECLARE_INSTRUCTION(ShouldDeoptimizeFlag);
protected:
DEFAULT_COPY_CONSTRUCTOR(ShouldDeoptimizeFlag);
};
// Represents the ArtMethod that was passed as a first argument to
// the method. It is used by instructions that depend on it, like
// instructions that work with the dex cache.
class HCurrentMethod final : public HExpression<0> {
public:
explicit HCurrentMethod(DataType::Type type, uint32_t dex_pc = kNoDexPc)
: HExpression(kCurrentMethod, type, SideEffects::None(), dex_pc) {
}
DECLARE_INSTRUCTION(CurrentMethod);
protected:
DEFAULT_COPY_CONSTRUCTOR(CurrentMethod);
};
// Fetches an ArtMethod from the virtual table or the interface method table
// of a class.
class HClassTableGet final : public HExpression<1> {
public:
enum class TableKind {
kVTable,
kIMTable,
kLast = kIMTable
};
HClassTableGet(HInstruction* cls,
DataType::Type type,
TableKind kind,
size_t index,
uint32_t dex_pc)
: HExpression(kClassTableGet, type, SideEffects::None(), dex_pc),
index_(index) {
SetPackedField<TableKindField>(kind);
SetRawInputAt(0, cls);
}
bool IsClonable() const override { return true; }
bool CanBeMoved() const override { return true; }
bool InstructionDataEquals(const HInstruction* other) const override {
return other->AsClassTableGet()->GetIndex() == index_ &&
other->AsClassTableGet()->GetPackedFields() == GetPackedFields();
}
TableKind GetTableKind() const { return GetPackedField<TableKindField>(); }
size_t GetIndex() const { return index_; }
DECLARE_INSTRUCTION(ClassTableGet);
protected:
DEFAULT_COPY_CONSTRUCTOR(ClassTableGet);
private:
static constexpr size_t kFieldTableKind = kNumberOfGenericPackedBits;
static constexpr size_t kFieldTableKindSize =
MinimumBitsToStore(static_cast<size_t>(TableKind::kLast));
static constexpr size_t kNumberOfClassTableGetPackedBits = kFieldTableKind + kFieldTableKindSize;
static_assert(kNumberOfClassTableGetPackedBits <= kMaxNumberOfPackedBits,
"Too many packed fields.");
using TableKindField = BitField<TableKind, kFieldTableKind, kFieldTableKindSize>;
// The index of the ArtMethod in the table.
const size_t index_;
};
// PackedSwitch (jump table). A block ending with a PackedSwitch instruction will
// have one successor for each entry in the switch table, and the final successor
// will be the block containing the next Dex opcode.
class HPackedSwitch final : public HExpression<1> {
public:
HPackedSwitch(int32_t start_value,
uint32_t num_entries,
HInstruction* input,
uint32_t dex_pc = kNoDexPc)
: HExpression(kPackedSwitch, SideEffects::None(), dex_pc),
start_value_(start_value),
num_entries_(num_entries) {
SetRawInputAt(0, input);
}
bool IsClonable() const override { return true; }
bool IsControlFlow() const override { return true; }
int32_t GetStartValue() const { return start_value_; }
uint32_t GetNumEntries() const { return num_entries_; }
HBasicBlock* GetDefaultBlock() const {
// Last entry is the default block.
return GetBlock()->GetSuccessors()[num_entries_];
}
DECLARE_INSTRUCTION(PackedSwitch);
protected:
DEFAULT_COPY_CONSTRUCTOR(PackedSwitch);
private:
const int32_t start_value_;
const uint32_t num_entries_;
};
class HUnaryOperation : public HExpression<1> {
public:
HUnaryOperation(InstructionKind kind,
DataType::Type result_type,
HInstruction* input,
uint32_t dex_pc = kNoDexPc)
: HExpression(kind, result_type, SideEffects::None(), dex_pc) {
SetRawInputAt(0, input);
}
// All of the UnaryOperation instructions are clonable.
bool IsClonable() const override { return true; }
HInstruction* GetInput() const { return InputAt(0); }
DataType::Type GetResultType() const { return GetType(); }
bool CanBeMoved() const override { return true; }
bool InstructionDataEquals(const HInstruction* other ATTRIBUTE_UNUSED) const override {
return true;
}
// Try to statically evaluate `this` and return a HConstant
// containing the result of this evaluation. If `this` cannot
// be evaluated as a constant, return null.
HConstant* TryStaticEvaluation() const;
// Apply this operation to `x`.
virtual HConstant* Evaluate(HIntConstant* x) const = 0;
virtual HConstant* Evaluate(HLongConstant* x) const = 0;
virtual HConstant* Evaluate(HFloatConstant* x) const = 0;
virtual HConstant* Evaluate(HDoubleConstant* x) const = 0;
DECLARE_ABSTRACT_INSTRUCTION(UnaryOperation);
protected:
DEFAULT_COPY_CONSTRUCTOR(UnaryOperation);
};
class HBinaryOperation : public HExpression<2> {
public:
HBinaryOperation(InstructionKind kind,
DataType::Type result_type,
HInstruction* left,
HInstruction* right,
SideEffects side_effects = SideEffects::None(),
uint32_t dex_pc = kNoDexPc)
: HExpression(kind, result_type, side_effects, dex_pc) {
SetRawInputAt(0, left);
SetRawInputAt(1, right);
}
// All of the BinaryOperation instructions are clonable.
bool IsClonable() const override { return true; }
HInstruction* GetLeft() const { return InputAt(0); }
HInstruction* GetRight() const { return InputAt(1); }
DataType::Type GetResultType() const { return GetType(); }
virtual bool IsCommutative() const { return false; }
// Put constant on the right.
// Returns whether order is changed.
bool OrderInputsWithConstantOnTheRight() {
HInstruction* left = InputAt(0);
HInstruction* right = InputAt(1);
if (left->IsConstant() && !right->IsConstant()) {
ReplaceInput(right, 0);
ReplaceInput(left, 1);
return true;
}
return false;
}
// Order inputs by instruction id, but favor constant on the right side.
// This helps GVN for commutative ops.
void OrderInputs() {
DCHECK(IsCommutative());
HInstruction* left = InputAt(0);
HInstruction* right = InputAt(1);
if (left == right || (!left->IsConstant() && right->IsConstant())) {
return;
}
if (OrderInputsWithConstantOnTheRight()) {
return;
}
// Order according to instruction id.
if (left->GetId() > right->GetId()) {
ReplaceInput(right, 0);
ReplaceInput(left, 1);
}
}
bool CanBeMoved() const override { return true; }
bool InstructionDataEquals(const HInstruction* other ATTRIBUTE_UNUSED) const override {
return true;
}
// Try to statically evaluate `this` and return a HConstant
// containing the result of this evaluation. If `this` cannot
// be evaluated as a constant, return null.
HConstant* TryStaticEvaluation() const;
// Apply this operation to `x` and `y`.
virtual HConstant* Evaluate(HNullConstant* x ATTRIBUTE_UNUSED,
HNullConstant* y ATTRIBUTE_UNUSED) const {
LOG(FATAL) << DebugName() << " is not defined for the (null, null) case.";
UNREACHABLE();
}
virtual HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const = 0;
virtual HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const = 0;
virtual HConstant* Evaluate(HLongConstant* x ATTRIBUTE_UNUSED,
HIntConstant* y ATTRIBUTE_UNUSED) const {
LOG(FATAL) << DebugName() << " is not defined for the (long, int) case.";
UNREACHABLE();
}
virtual HConstant* Evaluate(HFloatConstant* x, HFloatConstant* y) const = 0;
virtual HConstant* Evaluate(HDoubleConstant* x, HDoubleConstant* y) const = 0;
// Returns an input that can legally be used as the right input and is
// constant, or null.
HConstant* GetConstantRight() const;
// If `GetConstantRight()` returns one of the input, this returns the other
// one. Otherwise it returns null.
HInstruction* GetLeastConstantLeft() const;
DECLARE_ABSTRACT_INSTRUCTION(BinaryOperation);
protected:
DEFAULT_COPY_CONSTRUCTOR(BinaryOperation);
};
// The comparison bias applies for floating point operations and indicates how NaN
// comparisons are treated:
enum class ComparisonBias { // private marker to avoid generate-operator-out.py from processing.
kNoBias, // bias is not applicable (i.e. for long operation)
kGtBias, // return 1 for NaN comparisons
kLtBias, // return -1 for NaN comparisons
kLast = kLtBias
};
std::ostream& operator<<(std::ostream& os, ComparisonBias rhs);
class HCondition : public HBinaryOperation {
public:
HCondition(InstructionKind kind,
HInstruction* first,
HInstruction* second,
uint32_t dex_pc = kNoDexPc)
: HBinaryOperation(kind,
DataType::Type::kBool,
first,
second,
SideEffects::None(),
dex_pc) {
SetPackedField<ComparisonBiasField>(ComparisonBias::kNoBias);
}
// For code generation purposes, returns whether this instruction is just before
// `instruction`, and disregard moves in between.
bool IsBeforeWhenDisregardMoves(HInstruction* instruction) const;
DECLARE_ABSTRACT_INSTRUCTION(Condition);
virtual IfCondition GetCondition() const = 0;
virtual IfCondition GetOppositeCondition() const = 0;
bool IsGtBias() const { return GetBias() == ComparisonBias::kGtBias; }
bool IsLtBias() const { return GetBias() == ComparisonBias::kLtBias; }
ComparisonBias GetBias() const { return GetPackedField<ComparisonBiasField>(); }
void SetBias(ComparisonBias bias) { SetPackedField<ComparisonBiasField>(bias); }
bool InstructionDataEquals(const HInstruction* other) const override {
return GetPackedFields() == other->AsCondition()->GetPackedFields();
}
bool IsFPConditionTrueIfNaN() const {
DCHECK(DataType::IsFloatingPointType(InputAt(0)->GetType())) << InputAt(0)->GetType();
IfCondition if_cond = GetCondition();
if (if_cond == kCondNE) {
return true;
} else if (if_cond == kCondEQ) {
return false;
}
return ((if_cond == kCondGT) || (if_cond == kCondGE)) && IsGtBias();
}
bool IsFPConditionFalseIfNaN() const {
DCHECK(DataType::IsFloatingPointType(InputAt(0)->GetType())) << InputAt(0)->GetType();
IfCondition if_cond = GetCondition();
if (if_cond == kCondEQ) {
return true;
} else if (if_cond == kCondNE) {
return false;
}
return ((if_cond == kCondLT) || (if_cond == kCondLE)) && IsGtBias();
}
protected:
// Needed if we merge a HCompare into a HCondition.
static constexpr size_t kFieldComparisonBias = kNumberOfGenericPackedBits;
static constexpr size_t kFieldComparisonBiasSize =
MinimumBitsToStore(static_cast<size_t>(ComparisonBias::kLast));
static constexpr size_t kNumberOfConditionPackedBits =
kFieldComparisonBias + kFieldComparisonBiasSize;
static_assert(kNumberOfConditionPackedBits <= kMaxNumberOfPackedBits, "Too many packed fields.");
using ComparisonBiasField =
BitField<ComparisonBias, kFieldComparisonBias, kFieldComparisonBiasSize>;
template <typename T>
int32_t Compare(T x, T y) const { return x > y ? 1 : (x < y ? -1 : 0); }
template <typename T>
int32_t CompareFP(T x, T y) const {
DCHECK(DataType::IsFloatingPointType(InputAt(0)->GetType())) << InputAt(0)->GetType();
DCHECK_NE(GetBias(), ComparisonBias::kNoBias);
// Handle the bias.
return std::isunordered(x, y) ? (IsGtBias() ? 1 : -1) : Compare(x, y);
}
// Return an integer constant containing the result of a condition evaluated at compile time.
HIntConstant* MakeConstantCondition(bool value, uint32_t dex_pc) const {
return GetBlock()->GetGraph()->GetIntConstant(value, dex_pc);
}
DEFAULT_COPY_CONSTRUCTOR(Condition);
};
// Instruction to check if two inputs are equal to each other.
class HEqual final : public HCondition {
public:
HEqual(HInstruction* first, HInstruction* second, uint32_t dex_pc = kNoDexPc)
: HCondition(kEqual, first, second, dex_pc) {
}
bool IsCommutative() const override { return true; }
HConstant* Evaluate(HNullConstant* x ATTRIBUTE_UNUSED,
HNullConstant* y ATTRIBUTE_UNUSED) const override {
return MakeConstantCondition(true, GetDexPc());
}
HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
return MakeConstantCondition(Compute(x->GetValue(), y->GetValue()), GetDexPc());
}
// In the following Evaluate methods, a HCompare instruction has
// been merged into this HEqual instruction; evaluate it as
// `Compare(x, y) == 0`.
HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
return MakeConstantCondition(Compute(Compare(x->GetValue(), y->GetValue()), 0),
GetDexPc());
}
HConstant* Evaluate(HFloatConstant* x, HFloatConstant* y) const override {
return MakeConstantCondition(Compute(CompareFP(x->GetValue(), y->GetValue()), 0), GetDexPc());
}
HConstant* Evaluate(HDoubleConstant* x, HDoubleConstant* y) const override {
return MakeConstantCondition(Compute(CompareFP(x->GetValue(), y->GetValue()), 0), GetDexPc());
}
DECLARE_INSTRUCTION(Equal);
IfCondition GetCondition() const override {
return kCondEQ;
}
IfCondition GetOppositeCondition() const override {
return kCondNE;
}
protected:
DEFAULT_COPY_CONSTRUCTOR(Equal);
private:
template <typename T> static bool Compute(T x, T y) { return x == y; }
};
class HNotEqual final : public HCondition {
public:
HNotEqual(HInstruction* first, HInstruction* second,
uint32_t dex_pc = kNoDexPc)
: HCondition(kNotEqual, first, second, dex_pc) {
}
bool IsCommutative() const override { return true; }
HConstant* Evaluate(HNullConstant* x ATTRIBUTE_UNUSED,
HNullConstant* y ATTRIBUTE_UNUSED) const override {
return MakeConstantCondition(false, GetDexPc());
}
HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
return MakeConstantCondition(Compute(x->GetValue(), y->GetValue()), GetDexPc());
}
// In the following Evaluate methods, a HCompare instruction has
// been merged into this HNotEqual instruction; evaluate it as
// `Compare(x, y) != 0`.
HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
return MakeConstantCondition(Compute(Compare(x->GetValue(), y->GetValue()), 0), GetDexPc());
}
HConstant* Evaluate(HFloatConstant* x, HFloatConstant* y) const override {
return MakeConstantCondition(Compute(CompareFP(x->GetValue(), y->GetValue()), 0), GetDexPc());
}
HConstant* Evaluate(HDoubleConstant* x, HDoubleConstant* y) const override {
return MakeConstantCondition(Compute(CompareFP(x->GetValue(), y->GetValue()), 0), GetDexPc());
}
DECLARE_INSTRUCTION(NotEqual);
IfCondition GetCondition() const override {
return kCondNE;
}
IfCondition GetOppositeCondition() const override {
return kCondEQ;
}
protected:
DEFAULT_COPY_CONSTRUCTOR(NotEqual);
private:
template <typename T> static bool Compute(T x, T y) { return x != y; }
};
class HLessThan final : public HCondition {
public:
HLessThan(HInstruction* first, HInstruction* second,
uint32_t dex_pc = kNoDexPc)
: HCondition(kLessThan, first, second, dex_pc) {
}
HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
return MakeConstantCondition(Compute(x->GetValue(), y->GetValue()), GetDexPc());
}
// In the following Evaluate methods, a HCompare instruction has
// been merged into this HLessThan instruction; evaluate it as
// `Compare(x, y) < 0`.
HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
return MakeConstantCondition(Compute(Compare(x->GetValue(), y->GetValue()), 0), GetDexPc());
}
HConstant* Evaluate(HFloatConstant* x, HFloatConstant* y) const override {
return MakeConstantCondition(Compute(CompareFP(x->GetValue(), y->GetValue()), 0), GetDexPc());
}
HConstant* Evaluate(HDoubleConstant* x, HDoubleConstant* y) const override {
return MakeConstantCondition(Compute(CompareFP(x->GetValue(), y->GetValue()), 0), GetDexPc());
}
DECLARE_INSTRUCTION(LessThan);
IfCondition GetCondition() const override {
return kCondLT;
}
IfCondition GetOppositeCondition() const override {
return kCondGE;
}
protected:
DEFAULT_COPY_CONSTRUCTOR(LessThan);
private:
template <typename T> static bool Compute(T x, T y) { return x < y; }
};
class HLessThanOrEqual final : public HCondition {
public:
HLessThanOrEqual(HInstruction* first, HInstruction* second,
uint32_t dex_pc = kNoDexPc)
: HCondition(kLessThanOrEqual, first, second, dex_pc) {
}
HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
return MakeConstantCondition(Compute(x->GetValue(), y->GetValue()), GetDexPc());
}
// In the following Evaluate methods, a HCompare instruction has
// been merged into this HLessThanOrEqual instruction; evaluate it as
// `Compare(x, y) <= 0`.
HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
return MakeConstantCondition(Compute(Compare(x->GetValue(), y->GetValue()), 0), GetDexPc());
}
HConstant* Evaluate(HFloatConstant* x, HFloatConstant* y) const override {
return MakeConstantCondition(Compute(CompareFP(x->GetValue(), y->GetValue()), 0), GetDexPc());
}
HConstant* Evaluate(HDoubleConstant* x, HDoubleConstant* y) const override {
return MakeConstantCondition(Compute(CompareFP(x->GetValue(), y->GetValue()), 0), GetDexPc());
}
DECLARE_INSTRUCTION(LessThanOrEqual);
IfCondition GetCondition() const override {
return kCondLE;
}
IfCondition GetOppositeCondition() const override {
return kCondGT;
}
protected:
DEFAULT_COPY_CONSTRUCTOR(LessThanOrEqual);
private:
template <typename T> static bool Compute(T x, T y) { return x <= y; }
};
class HGreaterThan final : public HCondition {
public:
HGreaterThan(HInstruction* first, HInstruction* second, uint32_t dex_pc = kNoDexPc)
: HCondition(kGreaterThan, first, second, dex_pc) {
}
HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
return MakeConstantCondition(Compute(x->GetValue(), y->GetValue()), GetDexPc());
}
// In the following Evaluate methods, a HCompare instruction has
// been merged into this HGreaterThan instruction; evaluate it as
// `Compare(x, y) > 0`.
HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
return MakeConstantCondition(Compute(Compare(x->GetValue(), y->GetValue()), 0), GetDexPc());
}
HConstant* Evaluate(HFloatConstant* x, HFloatConstant* y) const override {
return MakeConstantCondition(Compute(CompareFP(x->GetValue(), y->GetValue()), 0), GetDexPc());
}
HConstant* Evaluate(HDoubleConstant* x, HDoubleConstant* y) const override {
return MakeConstantCondition(Compute(CompareFP(x->GetValue(), y->GetValue()), 0), GetDexPc());
}
DECLARE_INSTRUCTION(GreaterThan);
IfCondition GetCondition() const override {
return kCondGT;
}
IfCondition GetOppositeCondition() const override {
return kCondLE;
}
protected:
DEFAULT_COPY_CONSTRUCTOR(GreaterThan);
private:
template <typename T> static bool Compute(T x, T y) { return x > y; }
};
class HGreaterThanOrEqual final : public HCondition {
public:
HGreaterThanOrEqual(HInstruction* first, HInstruction* second, uint32_t dex_pc = kNoDexPc)
: HCondition(kGreaterThanOrEqual, first, second, dex_pc) {
}
HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
return MakeConstantCondition(Compute(x->GetValue(), y->GetValue()), GetDexPc());
}
// In the following Evaluate methods, a HCompare instruction has
// been merged into this HGreaterThanOrEqual instruction; evaluate it as
// `Compare(x, y) >= 0`.
HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
return MakeConstantCondition(Compute(Compare(x->GetValue(), y->GetValue()), 0), GetDexPc());
}
HConstant* Evaluate(HFloatConstant* x, HFloatConstant* y) const override {
return MakeConstantCondition(Compute(CompareFP(x->GetValue(), y->GetValue()), 0), GetDexPc());
}
HConstant* Evaluate(HDoubleConstant* x, HDoubleConstant* y) const override {
return MakeConstantCondition(Compute(CompareFP(x->GetValue(), y->GetValue()), 0), GetDexPc());
}
DECLARE_INSTRUCTION(GreaterThanOrEqual);
IfCondition GetCondition() const override {
return kCondGE;
}
IfCondition GetOppositeCondition() const override {
return kCondLT;
}
protected:
DEFAULT_COPY_CONSTRUCTOR(GreaterThanOrEqual);
private:
template <typename T> static bool Compute(T x, T y) { return x >= y; }
};
class HBelow final : public HCondition {
public:
HBelow(HInstruction* first, HInstruction* second, uint32_t dex_pc = kNoDexPc)
: HCondition(kBelow, first, second, dex_pc) {
}
HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
return MakeConstantCondition(Compute(x->GetValue(), y->GetValue()), GetDexPc());
}
HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
return MakeConstantCondition(Compute(x->GetValue(), y->GetValue()), GetDexPc());
}
HConstant* Evaluate(HFloatConstant* x ATTRIBUTE_UNUSED,
HFloatConstant* y ATTRIBUTE_UNUSED) const override {
LOG(FATAL) << DebugName() << " is not defined for float values";
UNREACHABLE();
}
HConstant* Evaluate(HDoubleConstant* x ATTRIBUTE_UNUSED,
HDoubleConstant* y ATTRIBUTE_UNUSED) const override {
LOG(FATAL) << DebugName() << " is not defined for double values";
UNREACHABLE();
}
DECLARE_INSTRUCTION(Below);
IfCondition GetCondition() const override {
return kCondB;
}
IfCondition GetOppositeCondition() const override {
return kCondAE;
}
protected:
DEFAULT_COPY_CONSTRUCTOR(Below);
private:
template <typename T> static bool Compute(T x, T y) {
return MakeUnsigned(x) < MakeUnsigned(y);
}
};
class HBelowOrEqual final : public HCondition {
public:
HBelowOrEqual(HInstruction* first, HInstruction* second, uint32_t dex_pc = kNoDexPc)
: HCondition(kBelowOrEqual, first, second, dex_pc) {
}
HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
return MakeConstantCondition(Compute(x->GetValue(), y->GetValue()), GetDexPc());
}
HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
return MakeConstantCondition(Compute(x->GetValue(), y->GetValue()), GetDexPc());
}
HConstant* Evaluate(HFloatConstant* x ATTRIBUTE_UNUSED,
HFloatConstant* y ATTRIBUTE_UNUSED) const override {
LOG(FATAL) << DebugName() << " is not defined for float values";
UNREACHABLE();
}
HConstant* Evaluate(HDoubleConstant* x ATTRIBUTE_UNUSED,
HDoubleConstant* y ATTRIBUTE_UNUSED) const override {
LOG(FATAL) << DebugName() << " is not defined for double values";
UNREACHABLE();
}
DECLARE_INSTRUCTION(BelowOrEqual);
IfCondition GetCondition() const override {
return kCondBE;
}
IfCondition GetOppositeCondition() const override {
return kCondA;
}
protected:
DEFAULT_COPY_CONSTRUCTOR(BelowOrEqual);
private:
template <typename T> static bool Compute(T x, T y) {
return MakeUnsigned(x) <= MakeUnsigned(y);
}
};
class HAbove final : public HCondition {
public:
HAbove(HInstruction* first, HInstruction* second, uint32_t dex_pc = kNoDexPc)
: HCondition(kAbove, first, second, dex_pc) {
}
HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
return MakeConstantCondition(Compute(x->GetValue(), y->GetValue()), GetDexPc());
}
HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
return MakeConstantCondition(Compute(x->GetValue(), y->GetValue()), GetDexPc());
}
HConstant* Evaluate(HFloatConstant* x ATTRIBUTE_UNUSED,
HFloatConstant* y ATTRIBUTE_UNUSED) const override {
LOG(FATAL) << DebugName() << " is not defined for float values";
UNREACHABLE();
}
HConstant* Evaluate(HDoubleConstant* x ATTRIBUTE_UNUSED,
HDoubleConstant* y ATTRIBUTE_UNUSED) const override {
LOG(FATAL) << DebugName() << " is not defined for double values";
UNREACHABLE();
}
DECLARE_INSTRUCTION(Above);
IfCondition GetCondition() const override {
return kCondA;
}
IfCondition GetOppositeCondition() const override {
return kCondBE;
}
protected:
DEFAULT_COPY_CONSTRUCTOR(Above);
private:
template <typename T> static bool Compute(T x, T y) {
return MakeUnsigned(x) > MakeUnsigned(y);
}
};
class HAboveOrEqual final : public HCondition {
public:
HAboveOrEqual(HInstruction* first, HInstruction* second, uint32_t dex_pc = kNoDexPc)
: HCondition(kAboveOrEqual, first, second, dex_pc) {
}
HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
return MakeConstantCondition(Compute(x->GetValue(), y->GetValue()), GetDexPc());
}
HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
return MakeConstantCondition(Compute(x->GetValue(), y->GetValue()), GetDexPc());
}
HConstant* Evaluate(HFloatConstant* x ATTRIBUTE_UNUSED,
HFloatConstant* y ATTRIBUTE_UNUSED) const override {
LOG(FATAL) << DebugName() << " is not defined for float values";
UNREACHABLE();
}
HConstant* Evaluate(HDoubleConstant* x ATTRIBUTE_UNUSED,
HDoubleConstant* y ATTRIBUTE_UNUSED) const override {
LOG(FATAL) << DebugName() << " is not defined for double values";
UNREACHABLE();
}
DECLARE_INSTRUCTION(AboveOrEqual);
IfCondition GetCondition() const override {
return kCondAE;
}
IfCondition GetOppositeCondition() const override {
return kCondB;
}
protected:
DEFAULT_COPY_CONSTRUCTOR(AboveOrEqual);
private:
template <typename T> static bool Compute(T x, T y) {
return MakeUnsigned(x) >= MakeUnsigned(y);
}
};
// Instruction to check how two inputs compare to each other.
// Result is 0 if input0 == input1, 1 if input0 > input1, or -1 if input0 < input1.
class HCompare final : public HBinaryOperation {
public:
// Note that `comparison_type` is the type of comparison performed
// between the comparison's inputs, not the type of the instantiated
// HCompare instruction (which is always DataType::Type::kInt).
HCompare(DataType::Type comparison_type,
HInstruction* first,
HInstruction* second,
ComparisonBias bias,
uint32_t dex_pc)
: HBinaryOperation(kCompare,
DataType::Type::kInt32,
first,
second,
SideEffectsForArchRuntimeCalls(comparison_type),
dex_pc) {
SetPackedField<ComparisonBiasField>(bias);
}
template <typename T>
int32_t Compute(T x, T y) const { return x > y ? 1 : (x < y ? -1 : 0); }
template <typename T>
int32_t ComputeFP(T x, T y) const {
DCHECK(DataType::IsFloatingPointType(InputAt(0)->GetType())) << InputAt(0)->GetType();
DCHECK_NE(GetBias(), ComparisonBias::kNoBias);
// Handle the bias.
return std::isunordered(x, y) ? (IsGtBias() ? 1 : -1) : Compute(x, y);
}
HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
// Note that there is no "cmp-int" Dex instruction so we shouldn't
// reach this code path when processing a freshly built HIR
// graph. However HCompare integer instructions can be synthesized
// by the instruction simplifier to implement IntegerCompare and
// IntegerSignum intrinsics, so we have to handle this case.
return MakeConstantComparison(Compute(x->GetValue(), y->GetValue()), GetDexPc());
}
HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
return MakeConstantComparison(Compute(x->GetValue(), y->GetValue()), GetDexPc());
}
HConstant* Evaluate(HFloatConstant* x, HFloatConstant* y) const override {
return MakeConstantComparison(ComputeFP(x->GetValue(), y->GetValue()), GetDexPc());
}
HConstant* Evaluate(HDoubleConstant* x, HDoubleConstant* y) const override {
return MakeConstantComparison(ComputeFP(x->GetValue(), y->GetValue()), GetDexPc());
}
bool InstructionDataEquals(const HInstruction* other) const override {
return GetPackedFields() == other->AsCompare()->GetPackedFields();
}
ComparisonBias GetBias() const { return GetPackedField<ComparisonBiasField>(); }
// Does this compare instruction have a "gt bias" (vs an "lt bias")?
// Only meaningful for floating-point comparisons.
bool IsGtBias() const {
DCHECK(DataType::IsFloatingPointType(InputAt(0)->GetType())) << InputAt(0)->GetType();
return GetBias() == ComparisonBias::kGtBias;
}
static SideEffects SideEffectsForArchRuntimeCalls(DataType::Type type ATTRIBUTE_UNUSED) {
// Comparisons do not require a runtime call in any back end.
return SideEffects::None();
}
DECLARE_INSTRUCTION(Compare);
protected:
static constexpr size_t kFieldComparisonBias = kNumberOfGenericPackedBits;
static constexpr size_t kFieldComparisonBiasSize =
MinimumBitsToStore(static_cast<size_t>(ComparisonBias::kLast));
static constexpr size_t kNumberOfComparePackedBits =
kFieldComparisonBias + kFieldComparisonBiasSize;
static_assert(kNumberOfComparePackedBits <= kMaxNumberOfPackedBits, "Too many packed fields.");
using ComparisonBiasField =
BitField<ComparisonBias, kFieldComparisonBias, kFieldComparisonBiasSize>;
// Return an integer constant containing the result of a comparison evaluated at compile time.
HIntConstant* MakeConstantComparison(int32_t value, uint32_t dex_pc) const {
DCHECK(value == -1 || value == 0 || value == 1) << value;
return GetBlock()->GetGraph()->GetIntConstant(value, dex_pc);
}
DEFAULT_COPY_CONSTRUCTOR(Compare);
};
class HNewInstance final : public HExpression<1> {
public:
HNewInstance(HInstruction* cls,
uint32_t dex_pc,
dex::TypeIndex type_index,
const DexFile& dex_file,
bool finalizable,
QuickEntrypointEnum entrypoint)
: HExpression(kNewInstance,
DataType::Type::kReference,
SideEffects::CanTriggerGC(),
dex_pc),
type_index_(type_index),
dex_file_(dex_file),
entrypoint_(entrypoint) {
SetPackedFlag<kFlagFinalizable>(finalizable);
SetPackedFlag<kFlagPartialMaterialization>(false);
SetRawInputAt(0, cls);
}
bool IsClonable() const override { return true; }
void SetPartialMaterialization() {
SetPackedFlag<kFlagPartialMaterialization>(true);
}
dex::TypeIndex GetTypeIndex() const { return type_index_; }
const DexFile& GetDexFile() const { return dex_file_; }
// Calls runtime so needs an environment.
bool NeedsEnvironment() const override { return true; }
// Can throw errors when out-of-memory or if it's not instantiable/accessible.
bool CanThrow() const override { return true; }
bool OnlyThrowsAsyncExceptions() const override {
return !IsFinalizable() && !NeedsChecks();
}
bool NeedsChecks() const {
return entrypoint_ == kQuickAllocObjectWithChecks;
}
bool IsFinalizable() const { return GetPackedFlag<kFlagFinalizable>(); }
bool CanBeNull() const override { return false; }
bool IsPartialMaterialization() const {
return GetPackedFlag<kFlagPartialMaterialization>();
}
QuickEntrypointEnum GetEntrypoint() const { return entrypoint_; }
void SetEntrypoint(QuickEntrypointEnum entrypoint) {
entrypoint_ = entrypoint;
}
HLoadClass* GetLoadClass() const {
HInstruction* input = InputAt(0);
if (input->IsClinitCheck()) {
input = input->InputAt(0);
}
DCHECK(input->IsLoadClass());
return input->AsLoadClass();
}
bool IsStringAlloc() const;
DECLARE_INSTRUCTION(NewInstance);
protected:
DEFAULT_COPY_CONSTRUCTOR(NewInstance);
private:
static constexpr size_t kFlagFinalizable = kNumberOfGenericPackedBits;
static constexpr size_t kFlagPartialMaterialization = kFlagFinalizable + 1;
static constexpr size_t kNumberOfNewInstancePackedBits = kFlagPartialMaterialization + 1;
static_assert(kNumberOfNewInstancePackedBits <= kMaxNumberOfPackedBits,
"Too many packed fields.");
const dex::TypeIndex type_index_;
const DexFile& dex_file_;
QuickEntrypointEnum entrypoint_;
};
enum IntrinsicNeedsEnvironment {
kNoEnvironment, // Intrinsic does not require an environment.
kNeedsEnvironment // Intrinsic requires an environment.
};
enum IntrinsicSideEffects {
kNoSideEffects, // Intrinsic does not have any heap memory side effects.
kReadSideEffects, // Intrinsic may read heap memory.
kWriteSideEffects, // Intrinsic may write heap memory.
kAllSideEffects // Intrinsic may read or write heap memory, or trigger GC.
};
enum IntrinsicExceptions {
kNoThrow, // Intrinsic does not throw any exceptions.
kCanThrow // Intrinsic may throw exceptions.
};
// Determines how to load an ArtMethod*.
enum class MethodLoadKind {
// Use a String init ArtMethod* loaded from Thread entrypoints.
kStringInit,
// Use the method's own ArtMethod* loaded by the register allocator.
kRecursive,
// Use PC-relative boot image ArtMethod* address that will be known at link time.
// Used for boot image methods referenced by boot image code.
kBootImageLinkTimePcRelative,
// Load from an entry in the .data.bimg.rel.ro using a PC-relative load.
// Used for app->boot calls with relocatable image.
kBootImageRelRo,
// Load from an entry in the .bss section using a PC-relative load.
// Used for methods outside boot image referenced by AOT-compiled app and boot image code.
kBssEntry,
// Use ArtMethod* at a known address, embed the direct address in the code.
// Used for for JIT-compiled calls.
kJitDirectAddress,
// Make a runtime call to resolve and call the method. This is the last-resort-kind
// used when other kinds are unimplemented on a particular architecture.
kRuntimeCall,
};
// Determines the location of the code pointer of an invoke.
enum class CodePtrLocation {
// Recursive call, use local PC-relative call instruction.
kCallSelf,
// Use native pointer from the Artmethod*.
// Used for @CriticalNative to avoid going through the compiled stub. This call goes through
// a special resolution stub if the class is not initialized or no native code is registered.
kCallCriticalNative,
// Use code pointer from the ArtMethod*.
// Used when we don't know the target code. This is also the last-resort-kind used when
// other kinds are unimplemented or impractical (i.e. slow) on a particular architecture.
kCallArtMethod,
};
static inline bool IsPcRelativeMethodLoadKind(MethodLoadKind load_kind) {
return load_kind == MethodLoadKind::kBootImageLinkTimePcRelative ||
load_kind == MethodLoadKind::kBootImageRelRo ||
load_kind == MethodLoadKind::kBssEntry;
}
class HInvoke : public HVariableInputSizeInstruction {
public:
bool NeedsEnvironment() const override;
void SetArgumentAt(size_t index, HInstruction* argument) {
SetRawInputAt(index, argument);
}
// Return the number of arguments. This number can be lower than
// the number of inputs returned by InputCount(), as some invoke
// instructions (e.g. HInvokeStaticOrDirect) can have non-argument
// inputs at the end of their list of inputs.
uint32_t GetNumberOfArguments() const { return number_of_arguments_; }
InvokeType GetInvokeType() const {
return GetPackedField<InvokeTypeField>();
}
Intrinsics GetIntrinsic() const {
return intrinsic_;
}
void SetIntrinsic(Intrinsics intrinsic,
IntrinsicNeedsEnvironment needs_env,
IntrinsicSideEffects side_effects,
IntrinsicExceptions exceptions);
bool IsFromInlinedInvoke() const {
return GetEnvironment()->IsFromInlinedInvoke();
}
void SetCanThrow(bool can_throw) { SetPackedFlag<kFlagCanThrow>(can_throw); }
bool CanThrow() const override { return GetPackedFlag<kFlagCanThrow>(); }
void SetAlwaysThrows(bool always_throws) { SetPackedFlag<kFlagAlwaysThrows>(always_throws); }
bool AlwaysThrows() const override final { return GetPackedFlag<kFlagAlwaysThrows>(); }
bool CanBeMoved() const override { return IsIntrinsic() && !DoesAnyWrite(); }
bool InstructionDataEquals(const HInstruction* other) const override {
return intrinsic_ != Intrinsics::kNone && intrinsic_ == other->AsInvoke()->intrinsic_;
}
uint32_t* GetIntrinsicOptimizations() {
return &intrinsic_optimizations_;
}
const uint32_t* GetIntrinsicOptimizations() const {
return &intrinsic_optimizations_;
}
bool IsIntrinsic() const { return intrinsic_ != Intrinsics::kNone; }
ArtMethod* GetResolvedMethod() const { return resolved_method_; }
void SetResolvedMethod(ArtMethod* method, bool enable_intrinsic_opt);
MethodReference GetMethodReference() const { return method_reference_; }
const MethodReference GetResolvedMethodReference() const {
return resolved_method_reference_;
}
DECLARE_ABSTRACT_INSTRUCTION(Invoke);
protected:
static constexpr size_t kFieldInvokeType = kNumberOfGenericPackedBits;
static constexpr size_t kFieldInvokeTypeSize =
MinimumBitsToStore(static_cast<size_t>(kMaxInvokeType));
static constexpr size_t kFlagCanThrow = kFieldInvokeType + kFieldInvokeTypeSize;
static constexpr size_t kFlagAlwaysThrows = kFlagCanThrow + 1;
static constexpr size_t kNumberOfInvokePackedBits = kFlagAlwaysThrows + 1;
static_assert(kNumberOfInvokePackedBits <= kMaxNumberOfPackedBits, "Too many packed fields.");
using InvokeTypeField = BitField<InvokeType, kFieldInvokeType, kFieldInvokeTypeSize>;
HInvoke(InstructionKind kind,
ArenaAllocator* allocator,
uint32_t number_of_arguments,
uint32_t number_of_other_inputs,
DataType::Type return_type,
uint32_t dex_pc,
MethodReference method_reference,
ArtMethod* resolved_method,
MethodReference resolved_method_reference,
InvokeType invoke_type,
bool enable_intrinsic_opt)
: HVariableInputSizeInstruction(
kind,
return_type,
SideEffects::AllExceptGCDependency(), // Assume write/read on all fields/arrays.
dex_pc,
allocator,
number_of_arguments + number_of_other_inputs,
kArenaAllocInvokeInputs),
number_of_arguments_(number_of_arguments),
method_reference_(method_reference),
resolved_method_reference_(resolved_method_reference),
intrinsic_(Intrinsics::kNone),
intrinsic_optimizations_(0) {
SetPackedField<InvokeTypeField>(invoke_type);
SetPackedFlag<kFlagCanThrow>(true);
SetResolvedMethod(resolved_method, enable_intrinsic_opt);
}
DEFAULT_COPY_CONSTRUCTOR(Invoke);
uint32_t number_of_arguments_;
ArtMethod* resolved_method_;
const MethodReference method_reference_;
// Cached values of the resolved method, to avoid needing the mutator lock.
const MethodReference resolved_method_reference_;
Intrinsics intrinsic_;
// A magic word holding optimizations for intrinsics. See intrinsics.h.
uint32_t intrinsic_optimizations_;
};
class HInvokeUnresolved final : public HInvoke {
public:
HInvokeUnresolved(ArenaAllocator* allocator,
uint32_t number_of_arguments,
DataType::Type return_type,
uint32_t dex_pc,
MethodReference method_reference,
InvokeType invoke_type)
: HInvoke(kInvokeUnresolved,
allocator,
number_of_arguments,
/* number_of_other_inputs= */ 0u,
return_type,
dex_pc,
method_reference,
nullptr,
MethodReference(nullptr, 0u),
invoke_type,
/* enable_intrinsic_opt= */ false) {
}
bool IsClonable() const override { return true; }
DECLARE_INSTRUCTION(InvokeUnresolved);
protected:
DEFAULT_COPY_CONSTRUCTOR(InvokeUnresolved);
};
class HInvokePolymorphic final : public HInvoke {
public:
HInvokePolymorphic(ArenaAllocator* allocator,
uint32_t number_of_arguments,
DataType::Type return_type,
uint32_t dex_pc,
MethodReference method_reference,
// resolved_method is the ArtMethod object corresponding to the polymorphic
// method (e.g. VarHandle.get), resolved using the class linker. It is needed
// to pass intrinsic information to the HInvokePolymorphic node.
ArtMethod* resolved_method,
MethodReference resolved_method_reference,
dex::ProtoIndex proto_idx,
bool enable_intrinsic_opt)
: HInvoke(kInvokePolymorphic,
allocator,
number_of_arguments,
/* number_of_other_inputs= */ 0u,
return_type,
dex_pc,
method_reference,
resolved_method,
resolved_method_reference,
kPolymorphic,
enable_intrinsic_opt),
proto_idx_(proto_idx) {
}
bool IsClonable() const override { return true; }
dex::ProtoIndex GetProtoIndex() { return proto_idx_; }
DECLARE_INSTRUCTION(InvokePolymorphic);
protected:
dex::ProtoIndex proto_idx_;
DEFAULT_COPY_CONSTRUCTOR(InvokePolymorphic);
};
class HInvokeCustom final : public HInvoke {
public:
HInvokeCustom(ArenaAllocator* allocator,
uint32_t number_of_arguments,
uint32_t call_site_index,
DataType::Type return_type,
uint32_t dex_pc,
MethodReference method_reference,
bool enable_intrinsic_opt)
: HInvoke(kInvokeCustom,
allocator,
number_of_arguments,
/* number_of_other_inputs= */ 0u,
return_type,
dex_pc,
method_reference,
/* resolved_method= */ nullptr,
MethodReference(nullptr, 0u),
kStatic,
enable_intrinsic_opt),
call_site_index_(call_site_index) {
}
uint32_t GetCallSiteIndex() const { return call_site_index_; }
bool IsClonable() const override { return true; }
DECLARE_INSTRUCTION(InvokeCustom);
protected:
DEFAULT_COPY_CONSTRUCTOR(InvokeCustom);
private:
uint32_t call_site_index_;
};
class HInvokeStaticOrDirect final : public HInvoke {
public:
// Requirements of this method call regarding the class
// initialization (clinit) check of its declaring class.
enum class ClinitCheckRequirement { // private marker to avoid generate-operator-out.py from processing.
kNone, // Class already initialized.
kExplicit, // Static call having explicit clinit check as last input.
kImplicit, // Static call implicitly requiring a clinit check.
kLast = kImplicit
};
struct DispatchInfo {
MethodLoadKind method_load_kind;
CodePtrLocation code_ptr_location;
// The method load data holds
// - thread entrypoint offset for kStringInit method if this is a string init invoke.
// Note that there are multiple string init methods, each having its own offset.
// - the method address for kDirectAddress
uint64_t method_load_data;
};
HInvokeStaticOrDirect(ArenaAllocator* allocator,
uint32_t number_of_arguments,
DataType::Type return_type,
uint32_t dex_pc,
MethodReference method_reference,
ArtMethod* resolved_method,
DispatchInfo dispatch_info,
InvokeType invoke_type,
MethodReference resolved_method_reference,
ClinitCheckRequirement clinit_check_requirement,
bool enable_intrinsic_opt)
: HInvoke(kInvokeStaticOrDirect,
allocator,
number_of_arguments,
// There is potentially one extra argument for the HCurrentMethod input,
// and one other if the clinit check is explicit. These can be removed later.
(NeedsCurrentMethodInput(dispatch_info) ? 1u : 0u) +
(clinit_check_requirement == ClinitCheckRequirement::kExplicit ? 1u : 0u),
return_type,
dex_pc,
method_reference,
resolved_method,
resolved_method_reference,
invoke_type,
enable_intrinsic_opt),
dispatch_info_(dispatch_info) {
SetPackedField<ClinitCheckRequirementField>(clinit_check_requirement);
}
bool IsClonable() const override { return true; }
bool NeedsBss() const override {
return GetMethodLoadKind() == MethodLoadKind::kBssEntry;
}
void SetDispatchInfo(DispatchInfo dispatch_info) {
bool had_current_method_input = HasCurrentMethodInput();
bool needs_current_method_input = NeedsCurrentMethodInput(dispatch_info);
// Using the current method is the default and once we find a better
// method load kind, we should not go back to using the current method.
DCHECK(had_current_method_input || !needs_current_method_input);
if (had_current_method_input && !needs_current_method_input) {
DCHECK_EQ(InputAt(GetCurrentMethodIndex()), GetBlock()->GetGraph()->GetCurrentMethod());
RemoveInputAt(GetCurrentMethodIndex());
}
dispatch_info_ = dispatch_info;
}
DispatchInfo GetDispatchInfo() const {
return dispatch_info_;
}
using HInstruction::GetInputRecords; // Keep the const version visible.
ArrayRef<HUserRecord<HInstruction*>> GetInputRecords() override {
ArrayRef<HUserRecord<HInstruction*>> input_records = HInvoke::GetInputRecords();
if (kIsDebugBuild && IsStaticWithExplicitClinitCheck()) {
DCHECK(!input_records.empty());
DCHECK_GT(input_records.size(), GetNumberOfArguments());
HInstruction* last_input = input_records.back().GetInstruction();
// Note: `last_input` may be null during arguments setup.
if (last_input != nullptr) {
// `last_input` is the last input of a static invoke marked as having
// an explicit clinit check. It must either be:
// - an art::HClinitCheck instruction, set by art::HGraphBuilder; or
// - an art::HLoadClass instruction, set by art::PrepareForRegisterAllocation.
DCHECK(last_input->IsClinitCheck() || last_input->IsLoadClass()) << last_input->DebugName();
}
}
return input_records;
}
bool CanDoImplicitNullCheckOn(HInstruction* obj ATTRIBUTE_UNUSED) const override {
// We do not access the method via object reference, so we cannot do an implicit null check.
// TODO: for intrinsics we can generate implicit null checks.
return false;
}
bool CanBeNull() const override {
return GetType() == DataType::Type::kReference && !IsStringInit();
}
MethodLoadKind GetMethodLoadKind() const { return dispatch_info_.method_load_kind; }
CodePtrLocation GetCodePtrLocation() const {
// We do CHA analysis after sharpening. When a method has CHA inlining, it
// cannot call itself, as if the CHA optmization is invalid we want to make
// sure the method is never executed again. So, while sharpening can return
// kCallSelf, we bypass it here if there is a CHA optimization.
if (dispatch_info_.code_ptr_location == CodePtrLocation::kCallSelf &&
GetBlock()->GetGraph()->HasShouldDeoptimizeFlag()) {
return CodePtrLocation::kCallArtMethod;
} else {
return dispatch_info_.code_ptr_location;
}
}
bool IsRecursive() const { return GetMethodLoadKind() == MethodLoadKind::kRecursive; }
bool IsStringInit() const { return GetMethodLoadKind() == MethodLoadKind::kStringInit; }
bool HasMethodAddress() const { return GetMethodLoadKind() == MethodLoadKind::kJitDirectAddress; }
bool HasPcRelativeMethodLoadKind() const {
return IsPcRelativeMethodLoadKind(GetMethodLoadKind());
}
QuickEntrypointEnum GetStringInitEntryPoint() const {
DCHECK(IsStringInit());
return static_cast<QuickEntrypointEnum>(dispatch_info_.method_load_data);
}
uint64_t GetMethodAddress() const {
DCHECK(HasMethodAddress());
return dispatch_info_.method_load_data;
}
const DexFile& GetDexFileForPcRelativeDexCache() const;
ClinitCheckRequirement GetClinitCheckRequirement() const {
return GetPackedField<ClinitCheckRequirementField>();
}
// Is this instruction a call to a static method?
bool IsStatic() const {
return GetInvokeType() == kStatic;
}
// Does this method load kind need the current method as an input?
static bool NeedsCurrentMethodInput(DispatchInfo dispatch_info) {
return dispatch_info.method_load_kind == MethodLoadKind::kRecursive ||
dispatch_info.method_load_kind == MethodLoadKind::kRuntimeCall ||
dispatch_info.code_ptr_location == CodePtrLocation::kCallCriticalNative;
}
// Get the index of the current method input.
size_t GetCurrentMethodIndex() const {
DCHECK(HasCurrentMethodInput());
return GetCurrentMethodIndexUnchecked();
}
size_t GetCurrentMethodIndexUnchecked() const {
return GetNumberOfArguments();
}
// Check if the method has a current method input.
bool HasCurrentMethodInput() const {
if (NeedsCurrentMethodInput(GetDispatchInfo())) {
DCHECK(InputAt(GetCurrentMethodIndexUnchecked()) == nullptr || // During argument setup.
InputAt(GetCurrentMethodIndexUnchecked())->IsCurrentMethod());
return true;
} else {
DCHECK(InputCount() == GetCurrentMethodIndexUnchecked() ||
InputAt(GetCurrentMethodIndexUnchecked()) == nullptr || // During argument setup.
!InputAt(GetCurrentMethodIndexUnchecked())->IsCurrentMethod());
return false;
}
}
// Get the index of the special input.
size_t GetSpecialInputIndex() const {
DCHECK(HasSpecialInput());
return GetSpecialInputIndexUnchecked();
}
size_t GetSpecialInputIndexUnchecked() const {
return GetNumberOfArguments() + (HasCurrentMethodInput() ? 1u : 0u);
}
// Check if the method has a special input.
bool HasSpecialInput() const {
size_t other_inputs =
GetSpecialInputIndexUnchecked() + (IsStaticWithExplicitClinitCheck() ? 1u : 0u);
size_t input_count = InputCount();
DCHECK_LE(input_count - other_inputs, 1u) << other_inputs << " " << input_count;
return other_inputs != input_count;
}
void AddSpecialInput(HInstruction* input) {
// We allow only one special input.
DCHECK(!HasSpecialInput());
InsertInputAt(GetSpecialInputIndexUnchecked(), input);
}
// Remove the HClinitCheck or the replacement HLoadClass (set as last input by
// PrepareForRegisterAllocation::VisitClinitCheck() in lieu of the initial HClinitCheck)
// instruction; only relevant for static calls with explicit clinit check.
void RemoveExplicitClinitCheck(ClinitCheckRequirement new_requirement) {
DCHECK(IsStaticWithExplicitClinitCheck());
size_t last_input_index = inputs_.size() - 1u;
HInstruction* last_input = inputs_.back().GetInstruction();
DCHECK(last_input != nullptr);
DCHECK(last_input->IsLoadClass() || last_input->IsClinitCheck()) << last_input->DebugName();
RemoveAsUserOfInput(last_input_index);
inputs_.pop_back();
SetPackedField<ClinitCheckRequirementField>(new_requirement);
DCHECK(!IsStaticWithExplicitClinitCheck());
}
// Is this a call to a static method whose declaring class has an
// explicit initialization check in the graph?
bool IsStaticWithExplicitClinitCheck() const {
return IsStatic() && (GetClinitCheckRequirement() == ClinitCheckRequirement::kExplicit);
}
// Is this a call to a static method whose declaring class has an
// implicit intialization check requirement?
bool IsStaticWithImplicitClinitCheck() const {
return IsStatic() && (GetClinitCheckRequirement() == ClinitCheckRequirement::kImplicit);
}
DECLARE_INSTRUCTION(InvokeStaticOrDirect);
protected:
DEFAULT_COPY_CONSTRUCTOR(InvokeStaticOrDirect);
private:
static constexpr size_t kFieldClinitCheckRequirement = kNumberOfInvokePackedBits;
static constexpr size_t kFieldClinitCheckRequirementSize =
MinimumBitsToStore(static_cast<size_t>(ClinitCheckRequirement::kLast));
static constexpr size_t kNumberOfInvokeStaticOrDirectPackedBits =
kFieldClinitCheckRequirement + kFieldClinitCheckRequirementSize;
static_assert(kNumberOfInvokeStaticOrDirectPackedBits <= kMaxNumberOfPackedBits,
"Too many packed fields.");
using ClinitCheckRequirementField = BitField<ClinitCheckRequirement,
kFieldClinitCheckRequirement,
kFieldClinitCheckRequirementSize>;
DispatchInfo dispatch_info_;
};
std::ostream& operator<<(std::ostream& os, MethodLoadKind rhs);
std::ostream& operator<<(std::ostream& os, CodePtrLocation rhs);
std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs);
class HInvokeVirtual final : public HInvoke {
public:
HInvokeVirtual(ArenaAllocator* allocator,
uint32_t number_of_arguments,
DataType::Type return_type,
uint32_t dex_pc,
MethodReference method_reference,
ArtMethod* resolved_method,
MethodReference resolved_method_reference,
uint32_t vtable_index,
bool enable_intrinsic_opt)
: HInvoke(kInvokeVirtual,
allocator,
number_of_arguments,
0u,
return_type,
dex_pc,
method_reference,
resolved_method,
resolved_method_reference,
kVirtual,
enable_intrinsic_opt),
vtable_index_(vtable_index) {
}
bool IsClonable() const override { return true; }
bool CanBeNull() const override {
switch (GetIntrinsic()) {
case Intrinsics::kThreadCurrentThread:
case Intrinsics::kStringBufferAppend:
case Intrinsics::kStringBufferToString:
case Intrinsics::kStringBuilderAppendObject:
case Intrinsics::kStringBuilderAppendString:
case Intrinsics::kStringBuilderAppendCharSequence:
case Intrinsics::kStringBuilderAppendCharArray:
case Intrinsics::kStringBuilderAppendBoolean:
case Intrinsics::kStringBuilderAppendChar:
case Intrinsics::kStringBuilderAppendInt:
case Intrinsics::kStringBuilderAppendLong:
case Intrinsics::kStringBuilderAppendFloat:
case Intrinsics::kStringBuilderAppendDouble:
case Intrinsics::kStringBuilderToString:
return false;
default:
return HInvoke::CanBeNull();
}
}
bool CanDoImplicitNullCheckOn(HInstruction* obj) const override;
uint32_t GetVTableIndex() const { return vtable_index_; }
DECLARE_INSTRUCTION(InvokeVirtual);
protected:
DEFAULT_COPY_CONSTRUCTOR(InvokeVirtual);
private:
// Cached value of the resolved method, to avoid needing the mutator lock.
const uint32_t vtable_index_;
};
class HInvokeInterface final : public HInvoke {
public:
HInvokeInterface(ArenaAllocator* allocator,
uint32_t number_of_arguments,
DataType::Type return_type,
uint32_t dex_pc,
MethodReference method_reference,
ArtMethod* resolved_method,
MethodReference resolved_method_reference,
uint32_t imt_index,
MethodLoadKind load_kind,
bool enable_intrinsic_opt)
: HInvoke(kInvokeInterface,
allocator,
number_of_arguments + (NeedsCurrentMethod(load_kind) ? 1 : 0),
0u,
return_type,
dex_pc,
method_reference,
resolved_method,
resolved_method_reference,
kInterface,
enable_intrinsic_opt),
imt_index_(imt_index),
hidden_argument_load_kind_(load_kind) {
}
static bool NeedsCurrentMethod(MethodLoadKind load_kind) {
return load_kind == MethodLoadKind::kRecursive;
}
bool IsClonable() const override { return true; }
bool NeedsBss() const override {
return GetHiddenArgumentLoadKind() == MethodLoadKind::kBssEntry;
}
bool CanDoImplicitNullCheckOn(HInstruction* obj) const override {
// TODO: Add implicit null checks in intrinsics.
return (obj == InputAt(0)) && !IsIntrinsic();
}
size_t GetSpecialInputIndex() const {
return GetNumberOfArguments();
}
void AddSpecialInput(HInstruction* input) {
InsertInputAt(GetSpecialInputIndex(), input);
}
uint32_t GetImtIndex() const { return imt_index_; }
MethodLoadKind GetHiddenArgumentLoadKind() const { return hidden_argument_load_kind_; }
DECLARE_INSTRUCTION(InvokeInterface);
protected:
DEFAULT_COPY_CONSTRUCTOR(InvokeInterface);
private:
// Cached value of the resolved method, to avoid needing the mutator lock.
const uint32_t imt_index_;
// How the hidden argument (the interface method) is being loaded.
const MethodLoadKind hidden_argument_load_kind_;
};
class HNeg final : public HUnaryOperation {
public:
HNeg(DataType::Type result_type, HInstruction* input, uint32_t dex_pc = kNoDexPc)
: HUnaryOperation(kNeg, result_type, input, dex_pc) {
DCHECK_EQ(result_type, DataType::Kind(input->GetType()));
}
template <typename T> static T Compute(T x) { return -x; }
HConstant* Evaluate(HIntConstant* x) const override {
return GetBlock()->GetGraph()->GetIntConstant(Compute(x->GetValue()), GetDexPc());
}
HConstant* Evaluate(HLongConstant* x) const override {
return GetBlock()->GetGraph()->GetLongConstant(Compute(x->GetValue()), GetDexPc());
}
HConstant* Evaluate(HFloatConstant* x) const override {
return GetBlock()->GetGraph()->GetFloatConstant(Compute(x->GetValue()), GetDexPc());
}
HConstant* Evaluate(HDoubleConstant* x) const override {
return GetBlock()->GetGraph()->GetDoubleConstant(Compute(x->GetValue()), GetDexPc());
}
DECLARE_INSTRUCTION(Neg);
protected:
DEFAULT_COPY_CONSTRUCTOR(Neg);
};
class HNewArray final : public HExpression<2> {
public:
HNewArray(HInstruction* cls, HInstruction* length, uint32_t dex_pc, size_t component_size_shift)
: HExpression(kNewArray, DataType::Type::kReference, SideEffects::CanTriggerGC(), dex_pc) {
SetRawInputAt(0, cls);
SetRawInputAt(1, length);
SetPackedField<ComponentSizeShiftField>(component_size_shift);
}
bool IsClonable() const override { return true; }
// Calls runtime so needs an environment.
bool NeedsEnvironment() const override { return true; }
// May throw NegativeArraySizeException, OutOfMemoryError, etc.
bool CanThrow() const override { return true; }
bool CanBeNull() const override { return false; }
HLoadClass* GetLoadClass() const {
DCHECK(InputAt(0)->IsLoadClass());
return InputAt(0)->AsLoadClass();
}
HInstruction* GetLength() const {
return InputAt(1);
}
size_t GetComponentSizeShift() {
return GetPackedField<ComponentSizeShiftField>();
}
DECLARE_INSTRUCTION(NewArray);
protected:
DEFAULT_COPY_CONSTRUCTOR(NewArray);
private:
static constexpr size_t kFieldComponentSizeShift = kNumberOfGenericPackedBits;
static constexpr size_t kFieldComponentSizeShiftSize = MinimumBitsToStore(3u);
static constexpr size_t kNumberOfNewArrayPackedBits =
kFieldComponentSizeShift + kFieldComponentSizeShiftSize;
static_assert(kNumberOfNewArrayPackedBits <= kMaxNumberOfPackedBits, "Too many packed fields.");
using ComponentSizeShiftField =
BitField<size_t, kFieldComponentSizeShift, kFieldComponentSizeShiftSize>;
};
class HAdd final : public HBinaryOperation {
public:
HAdd(DataType::Type result_type,
HInstruction* left,
HInstruction* right,
uint32_t dex_pc = kNoDexPc)
: HBinaryOperation(kAdd, result_type, left, right, SideEffects::None(), dex_pc) {
}
bool IsCommutative() const override { return true; }
template <typename T> static T Compute(T x, T y) { return x + y; }
HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
return GetBlock()->GetGraph()->GetIntConstant(
Compute(x->GetValue(), y->GetValue()), GetDexPc());
}
HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
return GetBlock()->GetGraph()->GetLongConstant(
Compute(x->GetValue(), y->GetValue()), GetDexPc());
}
HConstant* Evaluate(HFloatConstant* x, HFloatConstant* y) const override {
return GetBlock()->GetGraph()->GetFloatConstant(
Compute(x->GetValue(), y->GetValue()), GetDexPc());
}
HConstant* Evaluate(HDoubleConstant* x, HDoubleConstant* y) const override {
return GetBlock()->GetGraph()->GetDoubleConstant(
Compute(x->GetValue(), y->GetValue()), GetDexPc());
}
DECLARE_INSTRUCTION(Add);
protected:
DEFAULT_COPY_CONSTRUCTOR(Add);
};
class HSub final : public HBinaryOperation {
public:
HSub(DataType::Type result_type,
HInstruction* left,
HInstruction* right,
uint32_t dex_pc = kNoDexPc)
: HBinaryOperation(kSub, result_type, left, right, SideEffects::None(), dex_pc) {
}
template <typename T> static T Compute(T x, T y) { return x - y; }
HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
return GetBlock()->GetGraph()->GetIntConstant(
Compute(x->GetValue(), y->GetValue()), GetDexPc());
}
HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
return GetBlock()->GetGraph()->GetLongConstant(
Compute(x->GetValue(), y->GetValue()), GetDexPc());
}
HConstant* Evaluate(HFloatConstant* x, HFloatConstant* y) const override {
return GetBlock()->GetGraph()->GetFloatConstant(
Compute(x->GetValue(), y->GetValue()), GetDexPc());
}
HConstant* Evaluate(HDoubleConstant* x, HDoubleConstant* y) const override {
return GetBlock()->GetGraph()->GetDoubleConstant(
Compute(x->GetValue(), y->GetValue()), GetDexPc());
}
DECLARE_INSTRUCTION(Sub);
protected:
DEFAULT_COPY_CONSTRUCTOR(Sub);
};
class HMul final : public HBinaryOperation {
public:
HMul(DataType::Type result_type,
HInstruction* left,
HInstruction* right,
uint32_t dex_pc = kNoDexPc)
: HBinaryOperation(kMul, result_type, left, right, SideEffects::None(), dex_pc) {
}
bool IsCommutative() const override { return true; }
template <typename T> static T Compute(T x, T y) { return x * y; }
HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
return GetBlock()->GetGraph()->GetIntConstant(
Compute(x->GetValue(), y->GetValue()), GetDexPc());
}
HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
return GetBlock()->GetGraph()->GetLongConstant(
Compute(x->GetValue(), y->GetValue()), GetDexPc());
}
HConstant* Evaluate(HFloatConstant* x, HFloatConstant* y) const override {
return GetBlock()->GetGraph()->GetFloatConstant(
Compute(x->GetValue(), y->GetValue()), GetDexPc());
}
HConstant* Evaluate(HDoubleConstant* x, HDoubleConstant* y) const override {
return GetBlock()->GetGraph()->GetDoubleConstant(
Compute(x->GetValue(), y->GetValue()), GetDexPc());
}
DECLARE_INSTRUCTION(Mul);
protected:
DEFAULT_COPY_CONSTRUCTOR(Mul);
};
class HDiv final : public HBinaryOperation {
public:
HDiv(DataType::Type result_type,
HInstruction* left,
HInstruction* right,
uint32_t dex_pc)
: HBinaryOperation(kDiv, result_type, left, right, SideEffects::None(), dex_pc) {
}
template <typename T>
T ComputeIntegral(T x, T y) const {
DCHECK(!DataType::IsFloatingPointType(GetType())) << GetType();
// Our graph structure ensures we never have 0 for `y` during
// constant folding.
DCHECK_NE(y, 0);
// Special case -1 to avoid getting a SIGFPE on x86(_64).
return (y == -1) ? -x : x / y;
}
template <typename T>
T ComputeFP(T x, T y) const {
DCHECK(DataType::IsFloatingPointType(GetType())) << GetType();
return x / y;
}
HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
return GetBlock()->GetGraph()->GetIntConstant(
ComputeIntegral(x->GetValue(), y->GetValue()), GetDexPc());
}
HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
return GetBlock()->GetGraph()->GetLongConstant(
ComputeIntegral(x->GetValue(), y->GetValue()), GetDexPc());
}
HConstant* Evaluate(HFloatConstant* x, HFloatConstant* y) const override {
return GetBlock()->GetGraph()->GetFloatConstant(
ComputeFP(x->GetValue(), y->GetValue()), GetDexPc());
}
HConstant* Evaluate(HDoubleConstant* x, HDoubleConstant* y) const override {
return GetBlock()->GetGraph()->GetDoubleConstant(
ComputeFP(x->GetValue(), y->GetValue()), GetDexPc());
}
DECLARE_INSTRUCTION(Div);
protected:
DEFAULT_COPY_CONSTRUCTOR(Div);
};
class HRem final : public HBinaryOperation {
public:
HRem(DataType::Type result_type,
HInstruction* left,
HInstruction* right,
uint32_t dex_pc)
: HBinaryOperation(kRem, result_type, left, right, SideEffects::None(), dex_pc) {
}
template <typename T>
T ComputeIntegral(T x, T y) const {
DCHECK(!DataType::IsFloatingPointType(GetType())) << GetType();
// Our graph structure ensures we never have 0 for `y` during
// constant folding.
DCHECK_NE(y, 0);
// Special case -1 to avoid getting a SIGFPE on x86(_64).
return (y == -1) ? 0 : x % y;
}
template <typename T>
T ComputeFP(T x, T y) const {
DCHECK(DataType::IsFloatingPointType(GetType())) << GetType();
return std::fmod(x, y);
}
HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
return GetBlock()->GetGraph()->GetIntConstant(
ComputeIntegral(x->GetValue(), y->GetValue()), GetDexPc());
}
HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
return GetBlock()->GetGraph()->GetLongConstant(
ComputeIntegral(x->GetValue(), y->GetValue()), GetDexPc());
}
HConstant* Evaluate(HFloatConstant* x, HFloatConstant* y) const override {
return GetBlock()->GetGraph()->GetFloatConstant(
ComputeFP(x->GetValue(), y->GetValue()), GetDexPc());
}
HConstant* Evaluate(HDoubleConstant* x, HDoubleConstant* y) const override {
return GetBlock()->GetGraph()->GetDoubleConstant(
ComputeFP(x->GetValue(), y->GetValue()), GetDexPc());
}
DECLARE_INSTRUCTION(Rem);
protected:
DEFAULT_COPY_CONSTRUCTOR(Rem);
};
class HMin final : public HBinaryOperation {
public:
HMin(DataType::Type result_type,
HInstruction* left,
HInstruction* right,
uint32_t dex_pc)
: HBinaryOperation(kMin, result_type, left, right, SideEffects::None(), dex_pc) {}
bool IsCommutative() const override { return true; }
// Evaluation for integral values.
template <typename T> static T ComputeIntegral(T x, T y) {
return (x <= y) ? x : y;
}
HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
return GetBlock()->GetGraph()->GetIntConstant(
ComputeIntegral(x->GetValue(), y->GetValue()), GetDexPc());
}
HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
return GetBlock()->GetGraph()->GetLongConstant(
ComputeIntegral(x->GetValue(), y->GetValue()), GetDexPc());
}
// TODO: Evaluation for floating-point values.
HConstant* Evaluate(HFloatConstant* x ATTRIBUTE_UNUSED,
HFloatConstant* y ATTRIBUTE_UNUSED) const override { return nullptr; }
HConstant* Evaluate(HDoubleConstant* x ATTRIBUTE_UNUSED,
HDoubleConstant* y ATTRIBUTE_UNUSED) const override { return nullptr; }
DECLARE_INSTRUCTION(Min);
protected:
DEFAULT_COPY_CONSTRUCTOR(Min);
};
class HMax final : public HBinaryOperation {
public:
HMax(DataType::Type result_type,
HInstruction* left,
HInstruction* right,
uint32_t dex_pc)
: HBinaryOperation(kMax, result_type, left, right, SideEffects::None(), dex_pc) {}
bool IsCommutative() const override { return true; }
// Evaluation for integral values.
template <typename T> static T ComputeIntegral(T x, T y) {
return (x >= y) ? x : y;
}
HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
return GetBlock()->GetGraph()->GetIntConstant(
ComputeIntegral(x->GetValue(), y->GetValue()), GetDexPc());
}
HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
return GetBlock()->GetGraph()->GetLongConstant(
ComputeIntegral(x->GetValue(), y->GetValue()), GetDexPc());
}
// TODO: Evaluation for floating-point values.
HConstant* Evaluate(HFloatConstant* x ATTRIBUTE_UNUSED,
HFloatConstant* y ATTRIBUTE_UNUSED) const override { return nullptr; }
HConstant* Evaluate(HDoubleConstant* x ATTRIBUTE_UNUSED,
HDoubleConstant* y ATTRIBUTE_UNUSED) const override { return nullptr; }
DECLARE_INSTRUCTION(Max);
protected:
DEFAULT_COPY_CONSTRUCTOR(Max);
};
class HAbs final : public HUnaryOperation {
public:
HAbs(DataType::Type result_type, HInstruction* input, uint32_t dex_pc = kNoDexPc)
: HUnaryOperation(kAbs, result_type, input, dex_pc) {}
// Evaluation for integral values.
template <typename T> static T ComputeIntegral(T x) {
return x < 0 ? -x : x;
}
// Evaluation for floating-point values.
// Note, as a "quality of implementation", rather than pure "spec compliance",
// we require that Math.abs() clears the sign bit (but changes nothing else)
// for all floating-point numbers, including NaN (signaling NaN may become quiet though).
// http://b/30758343
template <typename T, typename S> static T ComputeFP(T x) {
S bits = bit_cast<S, T>(x);
return bit_cast<T, S>(bits & std::numeric_limits<S>::max());
}
HConstant* Evaluate(HIntConstant* x) const override {
return GetBlock()->GetGraph()->GetIntConstant(ComputeIntegral(x->GetValue()), GetDexPc());
}
HConstant* Evaluate(HLongConstant* x) const override {
return GetBlock()->GetGraph()->GetLongConstant(ComputeIntegral(x->GetValue()), GetDexPc());
}
HConstant* Evaluate(HFloatConstant* x) const override {
return GetBlock()->GetGraph()->GetFloatConstant(
ComputeFP<float, int32_t>(x->GetValue()), GetDexPc());
}
HConstant* Evaluate(HDoubleConstant* x) const override {
return GetBlock()->GetGraph()->GetDoubleConstant(
ComputeFP<double, int64_t>(x->GetValue()), GetDexPc());
}
DECLARE_INSTRUCTION(Abs);
protected:
DEFAULT_COPY_CONSTRUCTOR(Abs);
};
class HDivZeroCheck final : public HExpression<1> {
public:
// `HDivZeroCheck` can trigger GC, as it may call the `ArithmeticException`
// constructor. However it can only do it on a fatal slow path so execution never returns to the
// instruction following the current one; thus 'SideEffects::None()' is used.
HDivZeroCheck(HInstruction* value, uint32_t dex_pc)
: HExpression(kDivZeroCheck, value->GetType(), SideEffects::None(), dex_pc) {
SetRawInputAt(0, value);
}
bool IsClonable() const override { return true; }
bool CanBeMoved() const override { return true; }
bool InstructionDataEquals(const HInstruction* other ATTRIBUTE_UNUSED) const override {
return true;
}
bool NeedsEnvironment() const override { return true; }
bool CanThrow() const override { return true; }
DECLARE_INSTRUCTION(DivZeroCheck);
protected:
DEFAULT_COPY_CONSTRUCTOR(DivZeroCheck);
};
class HShl final : public HBinaryOperation {
public:
HShl(DataType::Type result_type,
HInstruction* value,
HInstruction* distance,
uint32_t dex_pc = kNoDexPc)
: HBinaryOperation(kShl, result_type, value, distance, SideEffects::None(), dex_pc) {
DCHECK_EQ(result_type, DataType::Kind(value->GetType()));
DCHECK_EQ(DataType::Type::kInt32, DataType::Kind(distance->GetType()));
}
template <typename T>
static T Compute(T value, int32_t distance, int32_t max_shift_distance) {
return value << (distance & max_shift_distance);
}
HConstant* Evaluate(HIntConstant* value, HIntConstant* distance) const override {
return GetBlock()->GetGraph()->GetIntConstant(
Compute(value->GetValue(), distance->GetValue(), kMaxIntShiftDistance), GetDexPc());
}
HConstant* Evaluate(HLongConstant* value, HIntConstant* distance) const override {
return GetBlock()->GetGraph()->GetLongConstant(
Compute(value->GetValue(), distance->GetValue(), kMaxLongShiftDistance), GetDexPc());
}
HConstant* Evaluate(HLongConstant* value ATTRIBUTE_UNUSED,
HLongConstant* distance ATTRIBUTE_UNUSED) const override {
LOG(FATAL) << DebugName() << " is not defined for the (long, long) case.";
UNREACHABLE();
}
HConstant* Evaluate(HFloatConstant* value ATTRIBUTE_UNUSED,
HFloatConstant* distance ATTRIBUTE_UNUSED) const override {
LOG(FATAL) << DebugName() << " is not defined for float values";
UNREACHABLE();
}
HConstant* Evaluate(HDoubleConstant* value ATTRIBUTE_UNUSED,
HDoubleConstant* distance ATTRIBUTE_UNUSED) const override {
LOG(FATAL) << DebugName() << " is not defined for double values";
UNREACHABLE();
}
DECLARE_INSTRUCTION(Shl);
protected:
DEFAULT_COPY_CONSTRUCTOR(Shl);
};
class HShr final : public HBinaryOperation {
public:
HShr(DataType::Type result_type,
HInstruction* value,
HInstruction* distance,
uint32_t dex_pc = kNoDexPc)
: HBinaryOperation(kShr, result_type, value, distance, SideEffects::None(), dex_pc) {
DCHECK_EQ(result_type, DataType::Kind(value->GetType()));
DCHECK_EQ(DataType::Type::kInt32, DataType::Kind(distance->GetType()));
}
template <typename T>
static T Compute(T value, int32_t distance, int32_t max_shift_distance) {
return value >> (distance & max_shift_distance);
}
HConstant* Evaluate(HIntConstant* value, HIntConstant* distance) const override {
return GetBlock()->GetGraph()->GetIntConstant(
Compute(value->GetValue(), distance->GetValue(), kMaxIntShiftDistance), GetDexPc());
}
HConstant* Evaluate(HLongConstant* value, HIntConstant* distance) const override {
return GetBlock()->GetGraph()->GetLongConstant(
Compute(value->GetValue(), distance->GetValue(), kMaxLongShiftDistance), GetDexPc());
}
HConstant* Evaluate(HLongConstant* value ATTRIBUTE_UNUSED,
HLongConstant* distance ATTRIBUTE_UNUSED) const override {
LOG(FATAL) << DebugName() << " is not defined for the (long, long) case.";
UNREACHABLE();
}
HConstant* Evaluate(HFloatConstant* value ATTRIBUTE_UNUSED,
HFloatConstant* distance ATTRIBUTE_UNUSED) const override {
LOG(FATAL) << DebugName() << " is not defined for float values";
UNREACHABLE();
}
HConstant* Evaluate(HDoubleConstant* value ATTRIBUTE_UNUSED,
HDoubleConstant* distance ATTRIBUTE_UNUSED) const override {
LOG(FATAL) << DebugName() << " is not defined for double values";
UNREACHABLE();
}
DECLARE_INSTRUCTION(Shr);
protected:
DEFAULT_COPY_CONSTRUCTOR(Shr);
};
class HUShr final : public HBinaryOperation {
public:
HUShr(DataType::Type result_type,
HInstruction* value,
HInstruction* distance,
uint32_t dex_pc = kNoDexPc)
: HBinaryOperation(kUShr, result_type, value, distance, SideEffects::None(), dex_pc) {
DCHECK_EQ(result_type, DataType::Kind(value->GetType()));
DCHECK_EQ(DataType::Type::kInt32, DataType::Kind(distance->GetType()));
}
template <typename T>
static T Compute(T value, int32_t distance, int32_t max_shift_distance) {
using V = std::make_unsigned_t<T>;
V ux = static_cast<V>(value);
return static_cast<T>(ux >> (distance & max_shift_distance));
}
HConstant* Evaluate(HIntConstant* value, HIntConstant* distance) const override {
return GetBlock()->GetGraph()->GetIntConstant(
Compute(value->GetValue(), distance->GetValue(), kMaxIntShiftDistance), GetDexPc());
}
HConstant* Evaluate(HLongConstant* value, HIntConstant* distance) const override {
return GetBlock()->GetGraph()->GetLongConstant(
Compute(value->GetValue(), distance->GetValue(), kMaxLongShiftDistance), GetDexPc());
}
HConstant* Evaluate(HLongConstant* value ATTRIBUTE_UNUSED,
HLongConstant* distance ATTRIBUTE_UNUSED) const override {
LOG(FATAL) << DebugName() << " is not defined for the (long, long) case.";
UNREACHABLE();
}
HConstant* Evaluate(HFloatConstant* value ATTRIBUTE_UNUSED,
HFloatConstant* distance ATTRIBUTE_UNUSED) const override {
LOG(FATAL) << DebugName() << " is not defined for float values";
UNREACHABLE();
}
HConstant* Evaluate(HDoubleConstant* value ATTRIBUTE_UNUSED,
HDoubleConstant* distance ATTRIBUTE_UNUSED) const override {
LOG(FATAL) << DebugName() << " is not defined for double values";
UNREACHABLE();
}
DECLARE_INSTRUCTION(UShr);
protected:
DEFAULT_COPY_CONSTRUCTOR(UShr);
};
class HAnd final : public HBinaryOperation {
public:
HAnd(DataType::Type result_type,
HInstruction* left,
HInstruction* right,
uint32_t dex_pc = kNoDexPc)
: HBinaryOperation(kAnd, result_type, left, right, SideEffects::None(), dex_pc) {
}
bool IsCommutative() const override { return true; }
template <typename T> static T Compute(T x, T y) { return x & y; }
HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
return GetBlock()->GetGraph()->GetIntConstant(
Compute(x->GetValue(), y->GetValue()), GetDexPc());
}
HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
return GetBlock()->GetGraph()->GetLongConstant(
Compute(x->GetValue(), y->GetValue()), GetDexPc());
}
HConstant* Evaluate(HFloatConstant* x ATTRIBUTE_UNUSED,
HFloatConstant* y ATTRIBUTE_UNUSED) const override {
LOG(FATAL) << DebugName() << " is not defined for float values";
UNREACHABLE();
}
HConstant* Evaluate(HDoubleConstant* x ATTRIBUTE_UNUSED,
HDoubleConstant* y ATTRIBUTE_UNUSED) const override {
LOG(FATAL) << DebugName() << " is not defined for double values";
UNREACHABLE();
}
DECLARE_INSTRUCTION(And);
protected:
DEFAULT_COPY_CONSTRUCTOR(And);
};
class HOr final : public HBinaryOperation {
public:
HOr(DataType::Type result_type,
HInstruction* left,
HInstruction* right,
uint32_t dex_pc = kNoDexPc)
: HBinaryOperation(kOr, result_type, left, right, SideEffects::None(), dex_pc) {
}
bool IsCommutative() const override { return true; }
template <typename T> static T Compute(T x, T y) { return x | y; }
HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
return GetBlock()->GetGraph()->GetIntConstant(
Compute(x->GetValue(), y->GetValue()), GetDexPc());
}
HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
return GetBlock()->GetGraph()->GetLongConstant(
Compute(x->GetValue(), y->GetValue()), GetDexPc());
}
HConstant* Evaluate(HFloatConstant* x ATTRIBUTE_UNUSED,
HFloatConstant* y ATTRIBUTE_UNUSED) const override {
LOG(FATAL) << DebugName() << " is not defined for float values";
UNREACHABLE();
}
HConstant* Evaluate(HDoubleConstant* x ATTRIBUTE_UNUSED,
HDoubleConstant* y ATTRIBUTE_UNUSED) const override {
LOG(FATAL) << DebugName() << " is not defined for double values";
UNREACHABLE();
}
DECLARE_INSTRUCTION(Or);
protected:
DEFAULT_COPY_CONSTRUCTOR(Or);
};
class HXor final : public HBinaryOperation {
public:
HXor(DataType::Type result_type,
HInstruction* left,
HInstruction* right,
uint32_t dex_pc = kNoDexPc)
: HBinaryOperation(kXor, result_type, left, right, SideEffects::None(), dex_pc) {
}
bool IsCommutative() const override { return true; }
template <typename T> static T Compute(T x, T y) { return x ^ y; }
HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
return GetBlock()->GetGraph()->GetIntConstant(
Compute(x->GetValue(), y->GetValue()), GetDexPc());
}
HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
return GetBlock()->GetGraph()->GetLongConstant(
Compute(x->GetValue(), y->GetValue()), GetDexPc());
}
HConstant* Evaluate(HFloatConstant* x ATTRIBUTE_UNUSED,
HFloatConstant* y ATTRIBUTE_UNUSED) const override {
LOG(FATAL) << DebugName() << " is not defined for float values";
UNREACHABLE();
}
HConstant* Evaluate(HDoubleConstant* x ATTRIBUTE_UNUSED,
HDoubleConstant* y ATTRIBUTE_UNUSED) const override {
LOG(FATAL) << DebugName() << " is not defined for double values";
UNREACHABLE();
}
DECLARE_INSTRUCTION(Xor);
protected:
DEFAULT_COPY_CONSTRUCTOR(Xor);
};
class HRor final : public HBinaryOperation {
public:
HRor(DataType::Type result_type, HInstruction* value, HInstruction* distance)
: HBinaryOperation(kRor, result_type, value, distance) {
}
template <typename T>
static T Compute(T value, int32_t distance, int32_t max_shift_value) {
using V = std::make_unsigned_t<T>;
V ux = static_cast<V>(value);
if ((distance & max_shift_value) == 0) {
return static_cast<T>(ux);
} else {
const V reg_bits = sizeof(T) * 8;
return static_cast<T>(ux >> (distance & max_shift_value)) |
(value << (reg_bits - (distance & max_shift_value)));
}
}
HConstant* Evaluate(HIntConstant* value, HIntConstant* distance) const override {
return GetBlock()->GetGraph()->GetIntConstant(
Compute(value->GetValue(), distance->GetValue(), kMaxIntShiftDistance), GetDexPc());
}
HConstant* Evaluate(HLongConstant* value, HIntConstant* distance) const override {
return GetBlock()->GetGraph()->GetLongConstant(
Compute(value->GetValue(), distance->GetValue(), kMaxLongShiftDistance), GetDexPc());
}
HConstant* Evaluate(HLongConstant* value ATTRIBUTE_UNUSED,
HLongConstant* distance ATTRIBUTE_UNUSED) const override {
LOG(FATAL) << DebugName() << " is not defined for the (long, long) case.";
UNREACHABLE();
}
HConstant* Evaluate(HFloatConstant* value ATTRIBUTE_UNUSED,
HFloatConstant* distance ATTRIBUTE_UNUSED) const override {
LOG(FATAL) << DebugName() << " is not defined for float values";
UNREACHABLE();
}
HConstant* Evaluate(HDoubleConstant* value ATTRIBUTE_UNUSED,
HDoubleConstant* distance ATTRIBUTE_UNUSED) const override {
LOG(FATAL) << DebugName() << " is not defined for double values";
UNREACHABLE();
}
DECLARE_INSTRUCTION(Ror);
protected:
DEFAULT_COPY_CONSTRUCTOR(Ror);
};
// The value of a parameter in this method. Its location depends on
// the calling convention.
class HParameterValue final : public HExpression<0> {
public:
HParameterValue(const DexFile& dex_file,
dex::TypeIndex type_index,
uint8_t index,
DataType::Type parameter_type,
bool is_this = false)
: HExpression(kParameterValue, parameter_type, SideEffects::None(), kNoDexPc),
dex_file_(dex_file),
type_index_(type_index),
index_(index) {
SetPackedFlag<kFlagIsThis>(is_this);
SetPackedFlag<kFlagCanBeNull>(!is_this);
}
const DexFile& GetDexFile() const { return dex_file_; }
dex::TypeIndex GetTypeIndex() const { return type_index_; }
uint8_t GetIndex() const { return index_; }
bool IsThis() const { return GetPackedFlag<kFlagIsThis>(); }
bool CanBeNull() const override { return GetPackedFlag<kFlagCanBeNull>(); }
void SetCanBeNull(bool can_be_null) { SetPackedFlag<kFlagCanBeNull>(can_be_null); }
DECLARE_INSTRUCTION(ParameterValue);
protected:
DEFAULT_COPY_CONSTRUCTOR(ParameterValue);
private:
// Whether or not the parameter value corresponds to 'this' argument.
static constexpr size_t kFlagIsThis = kNumberOfGenericPackedBits;
static constexpr size_t kFlagCanBeNull = kFlagIsThis + 1;
static constexpr size_t kNumberOfParameterValuePackedBits = kFlagCanBeNull + 1;
static_assert(kNumberOfParameterValuePackedBits <= kMaxNumberOfPackedBits,
"Too many packed fields.");
const DexFile& dex_file_;
const dex::TypeIndex type_index_;
// The index of this parameter in the parameters list. Must be less
// than HGraph::number_of_in_vregs_.
const uint8_t index_;
};
class HNot final : public HUnaryOperation {
public:
HNot(DataType::Type result_type, HInstruction* input, uint32_t dex_pc = kNoDexPc)
: HUnaryOperation(kNot, result_type, input, dex_pc) {
}
bool CanBeMoved() const override { return true; }
bool InstructionDataEquals(const HInstruction* other ATTRIBUTE_UNUSED) const override {
return true;
}
template <typename T> static T Compute(T x) { return ~x; }
HConstant* Evaluate(HIntConstant* x) const override {
return GetBlock()->GetGraph()->GetIntConstant(Compute(x->GetValue()), GetDexPc());
}
HConstant* Evaluate(HLongConstant* x) const override {
return GetBlock()->GetGraph()->GetLongConstant(Compute(x->GetValue()), GetDexPc());
}
HConstant* Evaluate(HFloatConstant* x ATTRIBUTE_UNUSED) const override {
LOG(FATAL) << DebugName() << " is not defined for float values";
UNREACHABLE();
}
HConstant* Evaluate(HDoubleConstant* x ATTRIBUTE_UNUSED) const override {
LOG(FATAL) << DebugName() << " is not defined for double values";
UNREACHABLE();
}
DECLARE_INSTRUCTION(Not);
protected:
DEFAULT_COPY_CONSTRUCTOR(Not);
};
class HBooleanNot final : public HUnaryOperation {
public:
explicit HBooleanNot(HInstruction* input, uint32_t dex_pc = kNoDexPc)
: HUnaryOperation(kBooleanNot, DataType::Type::kBool, input, dex_pc) {
}
bool CanBeMoved() const override { return true; }
bool InstructionDataEquals(const HInstruction* other ATTRIBUTE_UNUSED) const override {
return true;
}
template <typename T> static bool Compute(T x) {
DCHECK(IsUint<1>(x)) << x;
return !x;
}
HConstant* Evaluate(HIntConstant* x) const override {
return GetBlock()->GetGraph()->GetIntConstant(Compute(x->GetValue()), GetDexPc());
}
HConstant* Evaluate(HLongConstant* x ATTRIBUTE_UNUSED) const override {
LOG(FATAL) << DebugName() << " is not defined for long values";
UNREACHABLE();
}
HConstant* Evaluate(HFloatConstant* x ATTRIBUTE_UNUSED) const override {
LOG(FATAL) << DebugName() << " is not defined for float values";
UNREACHABLE();
}
HConstant* Evaluate(HDoubleConstant* x ATTRIBUTE_UNUSED) const override {
LOG(FATAL) << DebugName() << " is not defined for double values";
UNREACHABLE();
}
DECLARE_INSTRUCTION(BooleanNot);
protected:
DEFAULT_COPY_CONSTRUCTOR(BooleanNot);
};
class HTypeConversion final : public HExpression<1> {
public:
// Instantiate a type conversion of `input` to `result_type`.
HTypeConversion(DataType::Type result_type, HInstruction* input, uint32_t dex_pc = kNoDexPc)
: HExpression(kTypeConversion, result_type, SideEffects::None(), dex_pc) {
SetRawInputAt(0, input);
// Invariant: We should never generate a conversion to a Boolean value.
DCHECK_NE(DataType::Type::kBool, result_type);
}
HInstruction* GetInput() const { return InputAt(0); }
DataType::Type GetInputType() const { return GetInput()->GetType(); }
DataType::Type GetResultType() const { return GetType(); }
bool IsClonable() const override { return true; }
bool CanBeMoved() const override { return true; }
bool InstructionDataEquals(const HInstruction* other ATTRIBUTE_UNUSED) const override {
return true;
}
// Return whether the conversion is implicit. This includes conversion to the same type.
bool IsImplicitConversion() const {
return DataType::IsTypeConversionImplicit(GetInputType(), GetResultType());
}
// Try to statically evaluate the conversion and return a HConstant
// containing the result. If the input cannot be converted, return nullptr.
HConstant* TryStaticEvaluation() const;
DECLARE_INSTRUCTION(TypeConversion);
protected:
DEFAULT_COPY_CONSTRUCTOR(TypeConversion);
};
static constexpr uint32_t kNoRegNumber = -1;
class HNullCheck final : public HExpression<1> {
public:
// `HNullCheck` can trigger GC, as it may call the `NullPointerException`
// constructor. However it can only do it on a fatal slow path so execution never returns to the
// instruction following the current one; thus 'SideEffects::None()' is used.
HNullCheck(HInstruction* value, uint32_t dex_pc)
: HExpression(kNullCheck, value->GetType(), SideEffects::None(), dex_pc) {
SetRawInputAt(0, value);
}
bool IsClonable() const override { return true; }
bool CanBeMoved() const override { return true; }
bool InstructionDataEquals(const HInstruction* other ATTRIBUTE_UNUSED) const override {
return true;
}
bool NeedsEnvironment() const override { return true; }
bool CanThrow() const override { return true; }
bool CanBeNull() const override { return false; }
DECLARE_INSTRUCTION(NullCheck);
protected:
DEFAULT_COPY_CONSTRUCTOR(NullCheck);
};
// Embeds an ArtField and all the information required by the compiler. We cache
// that information to avoid requiring the mutator lock every time we need it.
class FieldInfo : public ValueObject {
public:
FieldInfo(ArtField* field,
MemberOffset field_offset,
DataType::Type field_type,
bool is_volatile,
uint32_t index,
uint16_t declaring_class_def_index,
const DexFile& dex_file)
: field_(field),
field_offset_(field_offset),
field_type_(field_type),
is_volatile_(is_volatile),
index_(index),
declaring_class_def_index_(declaring_class_def_index),
dex_file_(dex_file) {}
ArtField* GetField() const { return field_; }
MemberOffset GetFieldOffset() const { return field_offset_; }
DataType::Type GetFieldType() const { return field_type_; }
uint32_t GetFieldIndex() const { return index_; }
uint16_t GetDeclaringClassDefIndex() const { return declaring_class_def_index_;}
const DexFile& GetDexFile() const { return dex_file_; }
bool IsVolatile() const { return is_volatile_; }
bool Equals(const FieldInfo& other) const {
return field_ == other.field_ &&
field_offset_ == other.field_offset_ &&
field_type_ == other.field_type_ &&
is_volatile_ == other.is_volatile_ &&
index_ == other.index_ &&
declaring_class_def_index_ == other.declaring_class_def_index_ &&
&dex_file_ == &other.dex_file_;
}
std::ostream& Dump(std::ostream& os) const {
os << field_ << ", off: " << field_offset_ << ", type: " << field_type_
<< ", volatile: " << std::boolalpha << is_volatile_ << ", index_: " << std::dec << index_
<< ", declaring_class: " << declaring_class_def_index_ << ", dex: " << dex_file_;
return os;
}
private:
ArtField* const field_;
const MemberOffset field_offset_;
const DataType::Type field_type_;
const bool is_volatile_;
const uint32_t index_;
const uint16_t declaring_class_def_index_;
const DexFile& dex_file_;
};
inline bool operator==(const FieldInfo& a, const FieldInfo& b) {
return a.Equals(b);
}
inline std::ostream& operator<<(std::ostream& os, const FieldInfo& a) {
return a.Dump(os);
}
class HInstanceFieldGet final : public HExpression<1> {
public:
HInstanceFieldGet(HInstruction* value,
ArtField* field,
DataType::Type field_type,
MemberOffset field_offset,
bool is_volatile,
uint32_t field_idx,
uint16_t declaring_class_def_index,
const DexFile& dex_file,
uint32_t dex_pc)
: HExpression(kInstanceFieldGet,
field_type,
SideEffects::FieldReadOfType(field_type, is_volatile),
dex_pc),
field_info_(field,
field_offset,
field_type,
is_volatile,
field_idx,
declaring_class_def_index,
dex_file) {
SetRawInputAt(0, value);
}
bool IsClonable() const override { return true; }
bool CanBeMoved() const override { return !IsVolatile(); }
bool InstructionDataEquals(const HInstruction* other) const override {
const HInstanceFieldGet* other_get = other->AsInstanceFieldGet();
return GetFieldOffset().SizeValue() == other_get->GetFieldOffset().SizeValue();
}
bool CanDoImplicitNullCheckOn(HInstruction* obj) const override {
return (obj == InputAt(0)) && art::CanDoImplicitNullCheckOn(GetFieldOffset().Uint32Value());
}
size_t ComputeHashCode() const override {
return (HInstruction::ComputeHashCode() << 7) | GetFieldOffset().SizeValue();
}
bool IsFieldAccess() const override { return true; }
const FieldInfo& GetFieldInfo() const override { return field_info_; }
MemberOffset GetFieldOffset() const { return field_info_.GetFieldOffset(); }
DataType::Type GetFieldType() const { return field_info_.GetFieldType(); }
bool IsVolatile() const { return field_info_.IsVolatile(); }
void SetType(DataType::Type new_type) {
DCHECK(DataType::IsIntegralType(GetType()));
DCHECK(DataType::IsIntegralType(new_type));
DCHECK_EQ(DataType::Size(GetType()), DataType::Size(new_type));
SetPackedField<TypeField>(new_type);
}
DECLARE_INSTRUCTION(InstanceFieldGet);
protected:
DEFAULT_COPY_CONSTRUCTOR(InstanceFieldGet);
private:
const FieldInfo field_info_;
};
class HPredicatedInstanceFieldGet final : public HExpression<2> {
public:
HPredicatedInstanceFieldGet(HInstanceFieldGet* orig,
HInstruction* target,
HInstruction* default_val)
: HExpression(kPredicatedInstanceFieldGet,
orig->GetFieldType(),
orig->GetSideEffects(),
orig->GetDexPc()),
field_info_(orig->GetFieldInfo()) {
// NB Default-val is at 0 so we can avoid doing a move.
SetRawInputAt(1, target);
SetRawInputAt(0, default_val);
}
HPredicatedInstanceFieldGet(HInstruction* value,
ArtField* field,
HInstruction* default_value,
DataType::Type field_type,
MemberOffset field_offset,
bool is_volatile,
uint32_t field_idx,
uint16_t declaring_class_def_index,
const DexFile& dex_file,
uint32_t dex_pc)
: HExpression(kPredicatedInstanceFieldGet,
field_type,
SideEffects::FieldReadOfType(field_type, is_volatile),
dex_pc),
field_info_(field,
field_offset,
field_type,
is_volatile,
field_idx,
declaring_class_def_index,
dex_file) {
SetRawInputAt(1, value);
SetRawInputAt(0, default_value);
}
bool IsClonable() const override {
return true;
}
bool CanBeMoved() const override {
return !IsVolatile();
}
HInstruction* GetDefaultValue() const {
return InputAt(0);
}
HInstruction* GetTarget() const {
return InputAt(1);
}
bool InstructionDataEquals(const HInstruction* other) const override {
const HPredicatedInstanceFieldGet* other_get = other->AsPredicatedInstanceFieldGet();
return GetFieldOffset().SizeValue() == other_get->GetFieldOffset().SizeValue() &&
GetDefaultValue() == other_get->GetDefaultValue();
}
bool CanDoImplicitNullCheckOn(HInstruction* obj) const override {
return (obj == InputAt(0)) && art::CanDoImplicitNullCheckOn(GetFieldOffset().Uint32Value());
}
size_t ComputeHashCode() const override {
return (HInstruction::ComputeHashCode() << 7) | GetFieldOffset().SizeValue();
}
bool IsFieldAccess() const override { return true; }
const FieldInfo& GetFieldInfo() const override { return field_info_; }
MemberOffset GetFieldOffset() const { return field_info_.GetFieldOffset(); }
DataType::Type GetFieldType() const { return field_info_.GetFieldType(); }
bool IsVolatile() const { return field_info_.IsVolatile(); }
void SetType(DataType::Type new_type) {
DCHECK(DataType::IsIntegralType(GetType()));
DCHECK(DataType::IsIntegralType(new_type));
DCHECK_EQ(DataType::Size(GetType()), DataType::Size(new_type));
SetPackedField<TypeField>(new_type);
}
DECLARE_INSTRUCTION(PredicatedInstanceFieldGet);
protected:
DEFAULT_COPY_CONSTRUCTOR(PredicatedInstanceFieldGet);
private:
const FieldInfo field_info_;
};
enum class WriteBarrierKind {
// Emit the write barrier, with a runtime optimization which checks if the value that it is being
// set is null.
kEmitWithNullCheck,
// Emit the write barrier, without the runtime null check optimization. This could be set because:
// A) It is a write barrier for an ArraySet (which does the optimization with the type check, so
// it never does the optimization at the write barrier stage)
// B) We know that the input can't be null
// C) This write barrier is actually several write barriers coalesced into one. Potentially we
// could ask if every value is null for a runtime optimization at the cost of compile time / code
// size. At the time of writing it was deemed not worth the effort.
kEmitNoNullCheck,
// Skip emitting the write barrier. This could be set because:
// A) The write barrier is not needed (e.g. it is not a reference, or the value is the null
// constant)
// B) This write barrier was coalesced into another one so there's no need to emit it.
kDontEmit,
kLast = kDontEmit
};
std::ostream& operator<<(std::ostream& os, WriteBarrierKind rhs);
class HInstanceFieldSet final : public HExpression<2> {
public:
HInstanceFieldSet(HInstruction* object,
HInstruction* value,
ArtField* field,
DataType::Type field_type,
MemberOffset field_offset,
bool is_volatile,
uint32_t field_idx,
uint16_t declaring_class_def_index,
const DexFile& dex_file,
uint32_t dex_pc)
: HExpression(kInstanceFieldSet,
SideEffects::FieldWriteOfType(field_type, is_volatile),
dex_pc),
field_info_(field,
field_offset,
field_type,
is_volatile,
field_idx,
declaring_class_def_index,
dex_file) {
SetPackedFlag<kFlagValueCanBeNull>(true);
SetPackedFlag<kFlagIsPredicatedSet>(false);
SetPackedField<WriteBarrierKindField>(WriteBarrierKind::kEmitWithNullCheck);
SetRawInputAt(0, object);
SetRawInputAt(1, value);
}
bool IsClonable() const override { return true; }
bool CanDoImplicitNullCheckOn(HInstruction* obj) const override {
return (obj == InputAt(0)) && art::CanDoImplicitNullCheckOn(GetFieldOffset().Uint32Value());
}
bool IsFieldAccess() const override { return true; }
const FieldInfo& GetFieldInfo() const override { return field_info_; }
MemberOffset GetFieldOffset() const { return field_info_.GetFieldOffset(); }
DataType::Type GetFieldType() const { return field_info_.GetFieldType(); }
bool IsVolatile() const { return field_info_.IsVolatile(); }
HInstruction* GetValue() const { return InputAt(1); }
bool GetValueCanBeNull() const { return GetPackedFlag<kFlagValueCanBeNull>(); }
void ClearValueCanBeNull() { SetPackedFlag<kFlagValueCanBeNull>(false); }
bool GetIsPredicatedSet() const { return GetPackedFlag<kFlagIsPredicatedSet>(); }
void SetIsPredicatedSet(bool value = true) { SetPackedFlag<kFlagIsPredicatedSet>(value); }
WriteBarrierKind GetWriteBarrierKind() { return GetPackedField<WriteBarrierKindField>(); }
void SetWriteBarrierKind(WriteBarrierKind kind) {
DCHECK(kind != WriteBarrierKind::kEmitWithNullCheck)
<< "We shouldn't go back to the original value.";
SetPackedField<WriteBarrierKindField>(kind);
}
DECLARE_INSTRUCTION(InstanceFieldSet);
protected:
DEFAULT_COPY_CONSTRUCTOR(InstanceFieldSet);
private:
static constexpr size_t kFlagValueCanBeNull = kNumberOfGenericPackedBits;
static constexpr size_t kFlagIsPredicatedSet = kFlagValueCanBeNull + 1;
static constexpr size_t kWriteBarrierKind = kFlagIsPredicatedSet + 1;
static constexpr size_t kWriteBarrierKindSize =
MinimumBitsToStore(static_cast<size_t>(WriteBarrierKind::kLast));
static constexpr size_t kNumberOfInstanceFieldSetPackedBits =
kWriteBarrierKind + kWriteBarrierKindSize;
static_assert(kNumberOfInstanceFieldSetPackedBits <= kMaxNumberOfPackedBits,
"Too many packed fields.");
const FieldInfo field_info_;
using WriteBarrierKindField =
BitField<WriteBarrierKind, kWriteBarrierKind, kWriteBarrierKindSize>;
};
class HArrayGet final : public HExpression<2> {
public:
HArrayGet(HInstruction* array,
HInstruction* index,
DataType::Type type,
uint32_t dex_pc)
: HArrayGet(array,
index,
type,
SideEffects::ArrayReadOfType(type),
dex_pc,
/* is_string_char_at= */ false) {
}
HArrayGet(HInstruction* array,
HInstruction* index,
DataType::Type type,
SideEffects side_effects,
uint32_t dex_pc,
bool is_string_char_at)
: HExpression(kArrayGet, type, side_effects, dex_pc) {
SetPackedFlag<kFlagIsStringCharAt>(is_string_char_at);
SetRawInputAt(0, array);
SetRawInputAt(1, index);
}
bool IsClonable() const override { return true; }
bool CanBeMoved() const override { return true; }
bool InstructionDataEquals(const HInstruction* other ATTRIBUTE_UNUSED) const override {
return true;
}
bool CanDoImplicitNullCheckOn(HInstruction* obj ATTRIBUTE_UNUSED) const override {
// TODO: We can be smarter here.
// Currently, unless the array is the result of NewArray, the array access is always
// preceded by some form of null NullCheck necessary for the bounds check, usually
// implicit null check on the ArrayLength input to BoundsCheck or Deoptimize for
// dynamic BCE. There are cases when these could be removed to produce better code.
// If we ever add optimizations to do so we should allow an implicit check here
// (as long as the address falls in the first page).
//
// As an example of such fancy optimization, we could eliminate BoundsCheck for
// a = cond ? new int[1] : null;
// a[0]; // The Phi does not need bounds check for either input.
return false;
}
bool IsEquivalentOf(HArrayGet* other) const {
bool result = (GetDexPc() == other->GetDexPc());
if (kIsDebugBuild && result) {
DCHECK_EQ(GetBlock(), other->GetBlock());
DCHECK_EQ(GetArray(), other->GetArray());
DCHECK_EQ(GetIndex(), other->GetIndex());
if (DataType::IsIntOrLongType(GetType())) {
DCHECK(DataType::IsFloatingPointType(other->GetType())) << other->GetType();
} else {
DCHECK(DataType::IsFloatingPointType(GetType())) << GetType();
DCHECK(DataType::IsIntOrLongType(other->GetType())) << other->GetType();
}
}
return result;
}
bool IsStringCharAt() const { return GetPackedFlag<kFlagIsStringCharAt>(); }
HInstruction* GetArray() const { return InputAt(0); }
HInstruction* GetIndex() const { return InputAt(1); }
void SetType(DataType::Type new_type) {
DCHECK(DataType::IsIntegralType(GetType()));
DCHECK(DataType::IsIntegralType(new_type));
DCHECK_EQ(DataType::Size(GetType()), DataType::Size(new_type));
SetPackedField<TypeField>(new_type);
}
DECLARE_INSTRUCTION(ArrayGet);
protected:
DEFAULT_COPY_CONSTRUCTOR(ArrayGet);
private:
// We treat a String as an array, creating the HArrayGet from String.charAt()
// intrinsic in the instruction simplifier. We can always determine whether
// a particular HArrayGet is actually a String.charAt() by looking at the type
// of the input but that requires holding the mutator lock, so we prefer to use
// a flag, so that code generators don't need to do the locking.
static constexpr size_t kFlagIsStringCharAt = kNumberOfGenericPackedBits;
static constexpr size_t kNumberOfArrayGetPackedBits = kFlagIsStringCharAt + 1;
static_assert(kNumberOfArrayGetPackedBits <= HInstruction::kMaxNumberOfPackedBits,
"Too many packed fields.");
};
class HArraySet final : public HExpression<3> {
public:
HArraySet(HInstruction* array,
HInstruction* index,
HInstruction* value,
DataType::Type expected_component_type,
uint32_t dex_pc)
: HArraySet(array,
index,
value,
expected_component_type,
// Make a best guess for side effects now, may be refined during SSA building.
ComputeSideEffects(GetComponentType(value->GetType(), expected_component_type)),
dex_pc) {
}
HArraySet(HInstruction* array,
HInstruction* index,
HInstruction* value,
DataType::Type expected_component_type,
SideEffects side_effects,
uint32_t dex_pc)
: HExpression(kArraySet, side_effects, dex_pc) {
SetPackedField<ExpectedComponentTypeField>(expected_component_type);
SetPackedFlag<kFlagNeedsTypeCheck>(value->GetType() == DataType::Type::kReference);
SetPackedFlag<kFlagValueCanBeNull>(true);
SetPackedFlag<kFlagStaticTypeOfArrayIsObjectArray>(false);
// ArraySets never do the null check optimization at the write barrier stage.
SetPackedField<WriteBarrierKindField>(WriteBarrierKind::kEmitNoNullCheck);
SetRawInputAt(0, array);
SetRawInputAt(1, index);
SetRawInputAt(2, value);
}
bool IsClonable() const override { return true; }
bool NeedsEnvironment() const override {
// We call a runtime method to throw ArrayStoreException.
return NeedsTypeCheck();
}
// Can throw ArrayStoreException.
bool CanThrow() const override { return NeedsTypeCheck(); }
bool CanDoImplicitNullCheckOn(HInstruction* obj ATTRIBUTE_UNUSED) const override {
// TODO: Same as for ArrayGet.
return false;
}
void ClearTypeCheck() {
SetPackedFlag<kFlagNeedsTypeCheck>(false);
// Clear the `CanTriggerGC` flag too as we can only trigger a GC when doing a type check.
SetSideEffects(GetSideEffects().Exclusion(SideEffects::CanTriggerGC()));
}
void ClearValueCanBeNull() {
SetPackedFlag<kFlagValueCanBeNull>(false);
}
void SetStaticTypeOfArrayIsObjectArray() {
SetPackedFlag<kFlagStaticTypeOfArrayIsObjectArray>(true);
}
bool GetValueCanBeNull() const { return GetPackedFlag<kFlagValueCanBeNull>(); }
bool NeedsTypeCheck() const { return GetPackedFlag<kFlagNeedsTypeCheck>(); }
bool StaticTypeOfArrayIsObjectArray() const {
return GetPackedFlag<kFlagStaticTypeOfArrayIsObjectArray>();
}
HInstruction* GetArray() const { return InputAt(0); }
HInstruction* GetIndex() const { return InputAt(1); }
HInstruction* GetValue() const { return InputAt(2); }
DataType::Type GetComponentType() const {
return GetComponentType(GetValue()->GetType(), GetRawExpectedComponentType());
}
static DataType::Type GetComponentType(DataType::Type value_type,
DataType::Type expected_component_type) {
// The Dex format does not type floating point index operations. Since the
// `expected_component_type` comes from SSA building and can therefore not
// be correct, we also check what is the value type. If it is a floating
// point type, we must use that type.
return ((value_type == DataType::Type::kFloat32) || (value_type == DataType::Type::kFloat64))
? value_type
: expected_component_type;
}
DataType::Type GetRawExpectedComponentType() const {
return GetPackedField<ExpectedComponentTypeField>();
}
static SideEffects ComputeSideEffects(DataType::Type type) {
return SideEffects::ArrayWriteOfType(type).Union(SideEffectsForArchRuntimeCalls(type));
}
static SideEffects SideEffectsForArchRuntimeCalls(DataType::Type value_type) {
return (value_type == DataType::Type::kReference) ? SideEffects::CanTriggerGC()
: SideEffects::None();
}
WriteBarrierKind GetWriteBarrierKind() { return GetPackedField<WriteBarrierKindField>(); }
void SetWriteBarrierKind(WriteBarrierKind kind) {
DCHECK(kind != WriteBarrierKind::kEmitNoNullCheck)
<< "We shouldn't go back to the original value.";
DCHECK(kind != WriteBarrierKind::kEmitWithNullCheck)
<< "We never do the null check optimization for ArraySets.";
SetPackedField<WriteBarrierKindField>(kind);
}
DECLARE_INSTRUCTION(ArraySet);
protected:
DEFAULT_COPY_CONSTRUCTOR(ArraySet);
private:
static constexpr size_t kFieldExpectedComponentType = kNumberOfGenericPackedBits;
static constexpr size_t kFieldExpectedComponentTypeSize =
MinimumBitsToStore(static_cast<size_t>(DataType::Type::kLast));
static constexpr size_t kFlagNeedsTypeCheck =
kFieldExpectedComponentType + kFieldExpectedComponentTypeSize;
static constexpr size_t kFlagValueCanBeNull = kFlagNeedsTypeCheck + 1;
// Cached information for the reference_type_info_ so that codegen
// does not need to inspect the static type.
static constexpr size_t kFlagStaticTypeOfArrayIsObjectArray = kFlagValueCanBeNull + 1;
static constexpr size_t kWriteBarrierKind = kFlagStaticTypeOfArrayIsObjectArray + 1;
static constexpr size_t kWriteBarrierKindSize =
MinimumBitsToStore(static_cast<size_t>(WriteBarrierKind::kLast));
static constexpr size_t kNumberOfArraySetPackedBits = kWriteBarrierKind + kWriteBarrierKindSize;
static_assert(kNumberOfArraySetPackedBits <= kMaxNumberOfPackedBits, "Too many packed fields.");
using ExpectedComponentTypeField =
BitField<DataType::Type, kFieldExpectedComponentType, kFieldExpectedComponentTypeSize>;
using WriteBarrierKindField =
BitField<WriteBarrierKind, kWriteBarrierKind, kWriteBarrierKindSize>;
};
class HArrayLength final : public HExpression<1> {
public:
HArrayLength(HInstruction* array, uint32_t dex_pc, bool is_string_length = false)
: HExpression(kArrayLength, DataType::Type::kInt32, SideEffects::None(), dex_pc) {
SetPackedFlag<kFlagIsStringLength>(is_string_length);
// Note that arrays do not change length, so the instruction does not
// depend on any write.
SetRawInputAt(0, array);
}
bool IsClonable() const override { return true; }
bool CanBeMoved() const override { return true; }
bool InstructionDataEquals(const HInstruction* other ATTRIBUTE_UNUSED) const override {
return true;
}
bool CanDoImplicitNullCheckOn(HInstruction* obj) const override {
return obj == InputAt(0);
}
bool IsStringLength() const { return GetPackedFlag<kFlagIsStringLength>(); }
DECLARE_INSTRUCTION(ArrayLength);
protected:
DEFAULT_COPY_CONSTRUCTOR(ArrayLength);
private:
// We treat a String as an array, creating the HArrayLength from String.length()
// or String.isEmpty() intrinsic in the instruction simplifier. We can always
// determine whether a particular HArrayLength is actually a String.length() by
// looking at the type of the input but that requires holding the mutator lock, so
// we prefer to use a flag, so that code generators don't need to do the locking.
static constexpr size_t kFlagIsStringLength = kNumberOfGenericPackedBits;
static constexpr size_t kNumberOfArrayLengthPackedBits = kFlagIsStringLength + 1;
static_assert(kNumberOfArrayLengthPackedBits <= HInstruction::kMaxNumberOfPackedBits,
"Too many packed fields.");
};
class HBoundsCheck final : public HExpression<2> {
public:
// `HBoundsCheck` can trigger GC, as it may call the `IndexOutOfBoundsException`
// constructor. However it can only do it on a fatal slow path so execution never returns to the
// instruction following the current one; thus 'SideEffects::None()' is used.
HBoundsCheck(HInstruction* index,
HInstruction* length,
uint32_t dex_pc,
bool is_string_char_at = false)
: HExpression(kBoundsCheck, index->GetType(), SideEffects::None(), dex_pc) {
DCHECK_EQ(DataType::Type::kInt32, DataType::Kind(index->GetType()));
SetPackedFlag<kFlagIsStringCharAt>(is_string_char_at);
SetRawInputAt(0, index);
SetRawInputAt(1, length);
}
bool IsClonable() const override { return true; }
bool CanBeMoved() const override { return true; }
bool InstructionDataEquals(const HInstruction* other ATTRIBUTE_UNUSED) const override {
return true;
}
bool NeedsEnvironment() const override { return true; }
bool CanThrow() const override { return true; }
bool IsStringCharAt() const { return GetPackedFlag<kFlagIsStringCharAt>(); }
HInstruction* GetIndex() const { return InputAt(0); }
DECLARE_INSTRUCTION(BoundsCheck);
protected:
DEFAULT_COPY_CONSTRUCTOR(BoundsCheck);
private:
static constexpr size_t kFlagIsStringCharAt = kNumberOfGenericPackedBits;
static constexpr size_t kNumberOfBoundsCheckPackedBits = kFlagIsStringCharAt + 1;
static_assert(kNumberOfBoundsCheckPackedBits <= HInstruction::kMaxNumberOfPackedBits,
"Too many packed fields.");
};
class HSuspendCheck final : public HExpression<0> {
public:
explicit HSuspendCheck(uint32_t dex_pc = kNoDexPc, bool is_no_op = false)
: HExpression(kSuspendCheck, SideEffects::CanTriggerGC(), dex_pc),
slow_path_(nullptr) {
SetPackedFlag<kFlagIsNoOp>(is_no_op);
}
bool IsClonable() const override { return true; }
bool NeedsEnvironment() const override {
return true;
}
void SetIsNoOp(bool is_no_op) { SetPackedFlag<kFlagIsNoOp>(is_no_op); }
bool IsNoOp() const { return GetPackedFlag<kFlagIsNoOp>(); }
void SetSlowPath(SlowPathCode* slow_path) { slow_path_ = slow_path; }
SlowPathCode* GetSlowPath() const { return slow_path_; }
DECLARE_INSTRUCTION(SuspendCheck);
protected:
DEFAULT_COPY_CONSTRUCTOR(SuspendCheck);
// True if the HSuspendCheck should not emit any code during codegen. It is
// not possible to simply remove this instruction to disable codegen, as
// other optimizations (e.g: CHAGuardVisitor::HoistGuard) depend on
// HSuspendCheck being present in every loop.
static constexpr size_t kFlagIsNoOp = kNumberOfGenericPackedBits;
static constexpr size_t kNumberOfSuspendCheckPackedBits = kFlagIsNoOp + 1;
static_assert(kNumberOfSuspendCheckPackedBits <= HInstruction::kMaxNumberOfPackedBits,
"Too many packed fields.");
private:
// Only used for code generation, in order to share the same slow path between back edges
// of a same loop.
SlowPathCode* slow_path_;
};
// Pseudo-instruction which doesn't generate any code.
// If `emit_environment` is true, it can be used to generate an environment. It is used, for
// example, to provide the native debugger with mapping information. It ensures that we can generate
// line number and local variables at this point.
class HNop : public HExpression<0> {
public:
explicit HNop(uint32_t dex_pc, bool needs_environment)
: HExpression<0>(kNop, SideEffects::None(), dex_pc), needs_environment_(needs_environment) {
}
bool NeedsEnvironment() const override {
return needs_environment_;
}
DECLARE_INSTRUCTION(Nop);
protected:
DEFAULT_COPY_CONSTRUCTOR(Nop);
private:
bool needs_environment_;
};
/**
* Instruction to load a Class object.
*/
class HLoadClass final : public HInstruction {
public:
// Determines how to load the Class.
enum class LoadKind {
// We cannot load this class. See HSharpening::SharpenLoadClass.
kInvalid = -1,
// Use the Class* from the method's own ArtMethod*.
kReferrersClass,
// Use PC-relative boot image Class* address that will be known at link time.
// Used for boot image classes referenced by boot image code.
kBootImageLinkTimePcRelative,
// Load from an entry in the .data.bimg.rel.ro using a PC-relative load.
// Used for boot image classes referenced by apps in AOT-compiled code.
kBootImageRelRo,
// Load from an entry in the .bss section using a PC-relative load.
// Used for classes outside boot image referenced by AOT-compiled app and boot image code.
kBssEntry,
// Load from an entry for public class in the .bss section using a PC-relative load.
// Used for classes that were unresolved during AOT-compilation outside the literal
// package of the compiling class. Such classes are accessible only if they are public
// and the .bss entry shall therefore be filled only if the resolved class is public.
kBssEntryPublic,
// Load from an entry for package class in the .bss section using a PC-relative load.
// Used for classes that were unresolved during AOT-compilation but within the literal
// package of the compiling class. Such classes are accessible if they are public or
// in the same package which, given the literal package match, requires only matching
// defining class loader and the .bss entry shall therefore be filled only if at least
// one of those conditions holds. Note that all code in an oat file belongs to classes
// with the same defining class loader.
kBssEntryPackage,
// Use a known boot image Class* address, embedded in the code by the codegen.
// Used for boot image classes referenced by apps in JIT-compiled code.
kJitBootImageAddress,
// Load from the root table associated with the JIT compiled method.
kJitTableAddress,
// Load using a simple runtime call. This is the fall-back load kind when
// the codegen is unable to use another appropriate kind.
kRuntimeCall,
kLast = kRuntimeCall
};
HLoadClass(HCurrentMethod* current_method,
dex::TypeIndex type_index,
const DexFile& dex_file,
Handle<mirror::Class> klass,
bool is_referrers_class,
uint32_t dex_pc,
bool needs_access_check)
: HInstruction(kLoadClass,
DataType::Type::kReference,
SideEffectsForArchRuntimeCalls(),
dex_pc),
special_input_(HUserRecord<HInstruction*>(current_method)),
type_index_(type_index),
dex_file_(dex_file),
klass_(klass) {
// Referrers class should not need access check. We never inline unverified
// methods so we can't possibly end up in this situation.
DCHECK_IMPLIES(is_referrers_class, !needs_access_check);
SetPackedField<LoadKindField>(
is_referrers_class ? LoadKind::kReferrersClass : LoadKind::kRuntimeCall);
SetPackedFlag<kFlagNeedsAccessCheck>(needs_access_check);
SetPackedFlag<kFlagIsInBootImage>(false);
SetPackedFlag<kFlagGenerateClInitCheck>(false);
SetPackedFlag<kFlagValidLoadedClassRTI>(false);
}
bool IsClonable() const override { return true; }
void SetLoadKind(LoadKind load_kind);
LoadKind GetLoadKind() const {
return GetPackedField<LoadKindField>();
}
bool HasPcRelativeLoadKind() const {
return GetLoadKind() == LoadKind::kBootImageLinkTimePcRelative ||
GetLoadKind() == LoadKind::kBootImageRelRo ||
GetLoadKind() == LoadKind::kBssEntry ||
GetLoadKind() == LoadKind::kBssEntryPublic ||
GetLoadKind() == LoadKind::kBssEntryPackage;
}
bool CanBeMoved() const override { return true; }
bool InstructionDataEquals(const HInstruction* other) const override;
size_t ComputeHashCode() const override { return type_index_.index_; }
bool CanBeNull() const override { return false; }
bool NeedsEnvironment() const override {
return CanCallRuntime();
}
bool NeedsBss() const override {
LoadKind load_kind = GetLoadKind();
return load_kind == LoadKind::kBssEntry ||
load_kind == LoadKind::kBssEntryPublic ||
load_kind == LoadKind::kBssEntryPackage;
}
void SetMustGenerateClinitCheck(bool generate_clinit_check) {
SetPackedFlag<kFlagGenerateClInitCheck>(generate_clinit_check);
}
bool CanCallRuntime() const {
return NeedsAccessCheck() ||
MustGenerateClinitCheck() ||
GetLoadKind() == LoadKind::kRuntimeCall ||
GetLoadKind() == LoadKind::kBssEntry;
}
bool CanThrow() const override {
return NeedsAccessCheck() ||
MustGenerateClinitCheck() ||
// If the class is in the boot image, the lookup in the runtime call cannot throw.
((GetLoadKind() == LoadKind::kRuntimeCall ||
GetLoadKind() == LoadKind::kBssEntry) &&
!IsInBootImage());
}
ReferenceTypeInfo GetLoadedClassRTI() {
if (GetPackedFlag<kFlagValidLoadedClassRTI>()) {
// Note: The is_exact flag from the return value should not be used.
return ReferenceTypeInfo::CreateUnchecked(klass_, /* is_exact= */ true);
} else {
return ReferenceTypeInfo::CreateInvalid();
}
}
// Loaded class RTI is marked as valid by RTP if the klass_ is admissible.
void SetValidLoadedClassRTI() {
DCHECK(klass_ != nullptr);
SetPackedFlag<kFlagValidLoadedClassRTI>(true);
}
dex::TypeIndex GetTypeIndex() const { return type_index_; }
const DexFile& GetDexFile() const { return dex_file_; }
static SideEffects SideEffectsForArchRuntimeCalls() {
return SideEffects::CanTriggerGC();
}
bool IsReferrersClass() const { return GetLoadKind() == LoadKind::kReferrersClass; }
bool NeedsAccessCheck() const { return GetPackedFlag<kFlagNeedsAccessCheck>(); }
bool IsInBootImage() const { return GetPackedFlag<kFlagIsInBootImage>(); }
bool MustGenerateClinitCheck() const { return GetPackedFlag<kFlagGenerateClInitCheck>(); }
bool MustResolveTypeOnSlowPath() const {
// Check that this instruction has a slow path.
LoadKind load_kind = GetLoadKind();
DCHECK(load_kind != LoadKind::kRuntimeCall); // kRuntimeCall calls on main path.
bool must_resolve_type_on_slow_path =
load_kind == LoadKind::kBssEntry ||
load_kind == LoadKind::kBssEntryPublic ||
load_kind == LoadKind::kBssEntryPackage;
DCHECK(must_resolve_type_on_slow_path || MustGenerateClinitCheck());
return must_resolve_type_on_slow_path;
}
void MarkInBootImage() {
SetPackedFlag<kFlagIsInBootImage>(true);
}
void AddSpecialInput(HInstruction* special_input);
using HInstruction::GetInputRecords; // Keep the const version visible.
ArrayRef<HUserRecord<HInstruction*>> GetInputRecords() final {
return ArrayRef<HUserRecord<HInstruction*>>(
&special_input_, (special_input_.GetInstruction() != nullptr) ? 1u : 0u);
}
Handle<mirror::Class> GetClass() const {
return klass_;
}
DECLARE_INSTRUCTION(LoadClass);
protected:
DEFAULT_COPY_CONSTRUCTOR(LoadClass);
private:
static constexpr size_t kFlagNeedsAccessCheck = kNumberOfGenericPackedBits;
static constexpr size_t kFlagIsInBootImage = kFlagNeedsAccessCheck + 1;
// Whether this instruction must generate the initialization check.
// Used for code generation.
static constexpr size_t kFlagGenerateClInitCheck = kFlagIsInBootImage + 1;
static constexpr size_t kFieldLoadKind = kFlagGenerateClInitCheck + 1;
static constexpr size_t kFieldLoadKindSize =
MinimumBitsToStore(static_cast<size_t>(LoadKind::kLast));
static constexpr size_t kFlagValidLoadedClassRTI = kFieldLoadKind + kFieldLoadKindSize;
static constexpr size_t kNumberOfLoadClassPackedBits = kFlagValidLoadedClassRTI + 1;
static_assert(kNumberOfLoadClassPackedBits < kMaxNumberOfPackedBits, "Too many packed fields.");
using LoadKindField = BitField<LoadKind, kFieldLoadKind, kFieldLoadKindSize>;
static bool HasTypeReference(LoadKind load_kind) {
return load_kind == LoadKind::kReferrersClass ||
load_kind == LoadKind::kBootImageLinkTimePcRelative ||
load_kind == LoadKind::kBssEntry ||
load_kind == LoadKind::kBssEntryPublic ||
load_kind == LoadKind::kBssEntryPackage ||
load_kind == LoadKind::kRuntimeCall;
}
void SetLoadKindInternal(LoadKind load_kind);
// The special input is the HCurrentMethod for kRuntimeCall or kReferrersClass.
// For other load kinds it's empty or possibly some architecture-specific instruction
// for PC-relative loads, i.e. kBssEntry* or kBootImageLinkTimePcRelative.
HUserRecord<HInstruction*> special_input_;
// A type index and dex file where the class can be accessed. The dex file can be:
// - The compiling method's dex file if the class is defined there too.
// - The compiling method's dex file if the class is referenced there.
// - The dex file where the class is defined. When the load kind can only be
// kBssEntry* or kRuntimeCall, we cannot emit code for this `HLoadClass`.
const dex::TypeIndex type_index_;
const DexFile& dex_file_;
Handle<mirror::Class> klass_;
};
std::ostream& operator<<(std::ostream& os, HLoadClass::LoadKind rhs);
// Note: defined outside class to see operator<<(., HLoadClass::LoadKind).
inline void HLoadClass::SetLoadKind(LoadKind load_kind) {
// The load kind should be determined before inserting the instruction to the graph.
DCHECK(GetBlock() == nullptr);
DCHECK(GetEnvironment() == nullptr);
SetPackedField<LoadKindField>(load_kind);
if (load_kind != LoadKind::kRuntimeCall && load_kind != LoadKind::kReferrersClass) {
special_input_ = HUserRecord<HInstruction*>(nullptr);
}
if (!NeedsEnvironment()) {
SetSideEffects(SideEffects::None());
}
}
// Note: defined outside class to see operator<<(., HLoadClass::LoadKind).
inline void HLoadClass::AddSpecialInput(HInstruction* special_input) {
// The special input is used for PC-relative loads on some architectures,
// including literal pool loads, which are PC-relative too.
DCHECK(GetLoadKind() == LoadKind::kBootImageLinkTimePcRelative ||
GetLoadKind() == LoadKind::kBootImageRelRo ||
GetLoadKind() == LoadKind::kBssEntry ||
GetLoadKind() == LoadKind::kBssEntryPublic ||
GetLoadKind() == LoadKind::kBssEntryPackage ||
GetLoadKind() == LoadKind::kJitBootImageAddress) << GetLoadKind();
DCHECK(special_input_.GetInstruction() == nullptr);
special_input_ = HUserRecord<HInstruction*>(special_input);
special_input->AddUseAt(this, 0);
}
class HLoadString final : public HInstruction {
public:
// Determines how to load the String.
enum class LoadKind {
// Use PC-relative boot image String* address that will be known at link time.
// Used for boot image strings referenced by boot image code.
kBootImageLinkTimePcRelative,
// Load from an entry in the .data.bimg.rel.ro using a PC-relative load.
// Used for boot image strings referenced by apps in AOT-compiled code.
kBootImageRelRo,
// Load from an entry in the .bss section using a PC-relative load.
// Used for strings outside boot image referenced by AOT-compiled app and boot image code.
kBssEntry,
// Use a known boot image String* address, embedded in the code by the codegen.
// Used for boot image strings referenced by apps in JIT-compiled code.
kJitBootImageAddress,
// Load from the root table associated with the JIT compiled method.
kJitTableAddress,
// Load using a simple runtime call. This is the fall-back load kind when
// the codegen is unable to use another appropriate kind.
kRuntimeCall,
kLast = kRuntimeCall,
};
HLoadString(HCurrentMethod* current_method,
dex::StringIndex string_index,
const DexFile& dex_file,
uint32_t dex_pc)
: HInstruction(kLoadString,
DataType::Type::kReference,
SideEffectsForArchRuntimeCalls(),
dex_pc),
special_input_(HUserRecord<HInstruction*>(current_method)),
string_index_(string_index),
dex_file_(dex_file) {
SetPackedField<LoadKindField>(LoadKind::kRuntimeCall);
}
bool IsClonable() const override { return true; }
bool NeedsBss() const override {
return GetLoadKind() == LoadKind::kBssEntry;
}
void SetLoadKind(LoadKind load_kind);
LoadKind GetLoadKind() const {
return GetPackedField<LoadKindField>();
}
bool HasPcRelativeLoadKind() const {
return GetLoadKind() == LoadKind::kBootImageLinkTimePcRelative ||
GetLoadKind() == LoadKind::kBootImageRelRo ||
GetLoadKind() == LoadKind::kBssEntry;
}
const DexFile& GetDexFile() const {
return dex_file_;
}
dex::StringIndex GetStringIndex() const {
return string_index_;
}
Handle<mirror::String> GetString() const {
return string_;
}
void SetString(Handle<mirror::String> str) {
string_ = str;
}
bool CanBeMoved() const override { return true; }
bool InstructionDataEquals(const HInstruction* other) const override;
size_t ComputeHashCode() const override { return string_index_.index_; }
// Will call the runtime if we need to load the string through
// the dex cache and the string is not guaranteed to be there yet.
bool NeedsEnvironment() const override {
LoadKind load_kind = GetLoadKind();
if (load_kind == LoadKind::kBootImageLinkTimePcRelative ||
load_kind == LoadKind::kBootImageRelRo ||
load_kind == LoadKind::kJitBootImageAddress ||
load_kind == LoadKind::kJitTableAddress) {
return false;
}
return true;
}
bool CanBeNull() const override { return false; }
bool CanThrow() const override { return NeedsEnvironment(); }
static SideEffects SideEffectsForArchRuntimeCalls() {
return SideEffects::CanTriggerGC();
}
void AddSpecialInput(HInstruction* special_input);
using HInstruction::GetInputRecords; // Keep the const version visible.
ArrayRef<HUserRecord<HInstruction*>> GetInputRecords() final {
return ArrayRef<HUserRecord<HInstruction*>>(
&special_input_, (special_input_.GetInstruction() != nullptr) ? 1u : 0u);
}
DECLARE_INSTRUCTION(LoadString);
protected:
DEFAULT_COPY_CONSTRUCTOR(LoadString);
private:
static constexpr size_t kFieldLoadKind = kNumberOfGenericPackedBits;
static constexpr size_t kFieldLoadKindSize =
MinimumBitsToStore(static_cast<size_t>(LoadKind::kLast));
static constexpr size_t kNumberOfLoadStringPackedBits = kFieldLoadKind + kFieldLoadKindSize;
static_assert(kNumberOfLoadStringPackedBits <= kMaxNumberOfPackedBits, "Too many packed fields.");
using LoadKindField = BitField<LoadKind, kFieldLoadKind, kFieldLoadKindSize>;
void SetLoadKindInternal(LoadKind load_kind);
// The special input is the HCurrentMethod for kRuntimeCall.
// For other load kinds it's empty or possibly some architecture-specific instruction
// for PC-relative loads, i.e. kBssEntry or kBootImageLinkTimePcRelative.
HUserRecord<HInstruction*> special_input_;
dex::StringIndex string_index_;
const DexFile& dex_file_;
Handle<mirror::String> string_;
};
std::ostream& operator<<(std::ostream& os, HLoadString::LoadKind rhs);
// Note: defined outside class to see operator<<(., HLoadString::LoadKind).
inline void HLoadString::SetLoadKind(LoadKind load_kind) {
// The load kind should be determined before inserting the instruction to the graph.
DCHECK(GetBlock() == nullptr);
DCHECK(GetEnvironment() == nullptr);
DCHECK_EQ(GetLoadKind(), LoadKind::kRuntimeCall);
SetPackedField<LoadKindField>(load_kind);
if (load_kind != LoadKind::kRuntimeCall) {
special_input_ = HUserRecord<HInstruction*>(nullptr);
}
if (!NeedsEnvironment()) {
SetSideEffects(SideEffects::None());
}
}
// Note: defined outside class to see operator<<(., HLoadString::LoadKind).
inline void HLoadString::AddSpecialInput(HInstruction* special_input) {
// The special input is used for PC-relative loads on some architectures,
// including literal pool loads, which are PC-relative too.
DCHECK(GetLoadKind() == LoadKind::kBootImageLinkTimePcRelative ||
GetLoadKind() == LoadKind::kBootImageRelRo ||
GetLoadKind() == LoadKind::kBssEntry ||
GetLoadKind() == LoadKind::kJitBootImageAddress) << GetLoadKind();
// HLoadString::GetInputRecords() returns an empty array at this point,
// so use the GetInputRecords() from the base class to set the input record.
DCHECK(special_input_.GetInstruction() == nullptr);
special_input_ = HUserRecord<HInstruction*>(special_input);
special_input->AddUseAt(this, 0);
}
class HLoadMethodHandle final : public HInstruction {
public:
HLoadMethodHandle(HCurrentMethod* current_method,
uint16_t method_handle_idx,
const DexFile& dex_file,
uint32_t dex_pc)
: HInstruction(kLoadMethodHandle,
DataType::Type::kReference,
SideEffectsForArchRuntimeCalls(),
dex_pc),
special_input_(HUserRecord<HInstruction*>(current_method)),
method_handle_idx_(method_handle_idx),
dex_file_(dex_file) {
}
using HInstruction::GetInputRecords; // Keep the const version visible.
ArrayRef<HUserRecord<HInstruction*>> GetInputRecords() final {
return ArrayRef<HUserRecord<HInstruction*>>(
&special_input_, (special_input_.GetInstruction() != nullptr) ? 1u : 0u);
}
bool IsClonable() const override { return true; }
uint16_t GetMethodHandleIndex() const { return method_handle_idx_; }
const DexFile& GetDexFile() const { return dex_file_; }
static SideEffects SideEffectsForArchRuntimeCalls() {
return SideEffects::CanTriggerGC();
}
bool CanThrow() const override { return true; }
bool NeedsEnvironment() const override { return true; }
DECLARE_INSTRUCTION(LoadMethodHandle);
protected:
DEFAULT_COPY_CONSTRUCTOR(LoadMethodHandle);
private:
// The special input is the HCurrentMethod for kRuntimeCall.
HUserRecord<HInstruction*> special_input_;
const uint16_t method_handle_idx_;
const DexFile& dex_file_;
};
class HLoadMethodType final : public HInstruction {
public:
HLoadMethodType(HCurrentMethod* current_method,
dex::ProtoIndex proto_index,
const DexFile& dex_file,
uint32_t dex_pc)
: HInstruction(kLoadMethodType,
DataType::Type::kReference,
SideEffectsForArchRuntimeCalls(),
dex_pc),
special_input_(HUserRecord<HInstruction*>(current_method)),
proto_index_(proto_index),
dex_file_(dex_file) {
}
using HInstruction::GetInputRecords; // Keep the const version visible.
ArrayRef<HUserRecord<HInstruction*>> GetInputRecords() final {
return ArrayRef<HUserRecord<HInstruction*>>(
&special_input_, (special_input_.GetInstruction() != nullptr) ? 1u : 0u);
}
bool IsClonable() const override { return true; }
dex::ProtoIndex GetProtoIndex() const { return proto_index_; }
const DexFile& GetDexFile() const { return dex_file_; }
static SideEffects SideEffectsForArchRuntimeCalls() {
return SideEffects::CanTriggerGC();
}
bool CanThrow() const override { return true; }
bool NeedsEnvironment() const override { return true; }
DECLARE_INSTRUCTION(LoadMethodType);
protected:
DEFAULT_COPY_CONSTRUCTOR(LoadMethodType);
private:
// The special input is the HCurrentMethod for kRuntimeCall.
HUserRecord<HInstruction*> special_input_;
const dex::ProtoIndex proto_index_;
const DexFile& dex_file_;
};
/**
* Performs an initialization check on its Class object input.
*/
class HClinitCheck final : public HExpression<1> {
public:
HClinitCheck(HLoadClass* constant, uint32_t dex_pc)
: HExpression(
kClinitCheck,
DataType::Type::kReference,
SideEffects::AllExceptGCDependency(), // Assume write/read on all fields/arrays.
dex_pc) {
SetRawInputAt(0, constant);
}
// TODO: Make ClinitCheck clonable.
bool CanBeMoved() const override { return true; }
bool InstructionDataEquals(const HInstruction* other ATTRIBUTE_UNUSED) const override {
return true;
}
bool NeedsEnvironment() const override {
// May call runtime to initialize the class.
return true;
}
bool CanThrow() const override { return true; }
HLoadClass* GetLoadClass() const {
DCHECK(InputAt(0)->IsLoadClass());
return InputAt(0)->AsLoadClass();
}
DECLARE_INSTRUCTION(ClinitCheck);
protected:
DEFAULT_COPY_CONSTRUCTOR(ClinitCheck);
};
class HStaticFieldGet final : public HExpression<1> {
public:
HStaticFieldGet(HInstruction* cls,
ArtField* field,
DataType::Type field_type,
MemberOffset field_offset,
bool is_volatile,
uint32_t field_idx,
uint16_t declaring_class_def_index,
const DexFile& dex_file,
uint32_t dex_pc)
: HExpression(kStaticFieldGet,
field_type,
SideEffects::FieldReadOfType(field_type, is_volatile),
dex_pc),
field_info_(field,
field_offset,
field_type,
is_volatile,
field_idx,
declaring_class_def_index,
dex_file) {
SetRawInputAt(0, cls);
}
bool IsClonable() const override { return true; }
bool CanBeMoved() const override { return !IsVolatile(); }
bool InstructionDataEquals(const HInstruction* other) const override {
const HStaticFieldGet* other_get = other->AsStaticFieldGet();
return GetFieldOffset().SizeValue() == other_get->GetFieldOffset().SizeValue();
}
size_t ComputeHashCode() const override {
return (HInstruction::ComputeHashCode() << 7) | GetFieldOffset().SizeValue();
}
bool IsFieldAccess() const override { return true; }
const FieldInfo& GetFieldInfo() const override { return field_info_; }
MemberOffset GetFieldOffset() const { return field_info_.GetFieldOffset(); }
DataType::Type GetFieldType() const { return field_info_.GetFieldType(); }
bool IsVolatile() const { return field_info_.IsVolatile(); }
void SetType(DataType::Type new_type) {
DCHECK(DataType::IsIntegralType(GetType()));
DCHECK(DataType::IsIntegralType(new_type));
DCHECK_EQ(DataType::Size(GetType()), DataType::Size(new_type));
SetPackedField<TypeField>(new_type);
}
DECLARE_INSTRUCTION(StaticFieldGet);
protected:
DEFAULT_COPY_CONSTRUCTOR(StaticFieldGet);
private:
const FieldInfo field_info_;
};
class HStaticFieldSet final : public HExpression<2> {
public:
HStaticFieldSet(HInstruction* cls,
HInstruction* value,
ArtField* field,
DataType::Type field_type,
MemberOffset field_offset,
bool is_volatile,
uint32_t field_idx,
uint16_t declaring_class_def_index,
const DexFile& dex_file,
uint32_t dex_pc)
: HExpression(kStaticFieldSet,
SideEffects::FieldWriteOfType(field_type, is_volatile),
dex_pc),
field_info_(field,
field_offset,
field_type,
is_volatile,
field_idx,
declaring_class_def_index,
dex_file) {
SetPackedFlag<kFlagValueCanBeNull>(true);
SetPackedField<WriteBarrierKindField>(WriteBarrierKind::kEmitWithNullCheck);
SetRawInputAt(0, cls);
SetRawInputAt(1, value);
}
bool IsClonable() const override { return true; }
bool IsFieldAccess() const override { return true; }
const FieldInfo& GetFieldInfo() const override { return field_info_; }
MemberOffset GetFieldOffset() const { return field_info_.GetFieldOffset(); }
DataType::Type GetFieldType() const { return field_info_.GetFieldType(); }
bool IsVolatile() const { return field_info_.IsVolatile(); }
HInstruction* GetValue() const { return InputAt(1); }
bool GetValueCanBeNull() const { return GetPackedFlag<kFlagValueCanBeNull>(); }
void ClearValueCanBeNull() { SetPackedFlag<kFlagValueCanBeNull>(false); }
WriteBarrierKind GetWriteBarrierKind() { return GetPackedField<WriteBarrierKindField>(); }
void SetWriteBarrierKind(WriteBarrierKind kind) {
DCHECK(kind != WriteBarrierKind::kEmitWithNullCheck)
<< "We shouldn't go back to the original value.";
SetPackedField<WriteBarrierKindField>(kind);
}
DECLARE_INSTRUCTION(StaticFieldSet);
protected:
DEFAULT_COPY_CONSTRUCTOR(StaticFieldSet);
private:
static constexpr size_t kFlagValueCanBeNull = kNumberOfGenericPackedBits;
static constexpr size_t kWriteBarrierKind = kFlagValueCanBeNull + 1;
static constexpr size_t kWriteBarrierKindSize =
MinimumBitsToStore(static_cast<size_t>(WriteBarrierKind::kLast));
static constexpr size_t kNumberOfStaticFieldSetPackedBits =
kWriteBarrierKind + kWriteBarrierKindSize;
static_assert(kNumberOfStaticFieldSetPackedBits <= kMaxNumberOfPackedBits,
"Too many packed fields.");
const FieldInfo field_info_;
using WriteBarrierKindField =
BitField<WriteBarrierKind, kWriteBarrierKind, kWriteBarrierKindSize>;
};
class HStringBuilderAppend final : public HVariableInputSizeInstruction {
public:
HStringBuilderAppend(HIntConstant* format,
uint32_t number_of_arguments,
bool has_fp_args,
ArenaAllocator* allocator,
uint32_t dex_pc)
: HVariableInputSizeInstruction(
kStringBuilderAppend,
DataType::Type::kReference,
SideEffects::CanTriggerGC().Union(
// The runtime call may read memory from inputs. It never writes outside
// of the newly allocated result object or newly allocated helper objects,
// except for float/double arguments where we reuse thread-local helper objects.
has_fp_args ? SideEffects::AllWritesAndReads() : SideEffects::AllReads()),
dex_pc,
allocator,
number_of_arguments + /* format */ 1u,
kArenaAllocInvokeInputs) {
DCHECK_GE(number_of_arguments, 1u); // There must be something to append.
SetRawInputAt(FormatIndex(), format);
}
void SetArgumentAt(size_t index, HInstruction* argument) {
DCHECK_LE(index, GetNumberOfArguments());
SetRawInputAt(index, argument);
}
// Return the number of arguments, excluding the format.
size_t GetNumberOfArguments() const {
DCHECK_GE(InputCount(), 1u);
return InputCount() - 1u;
}
size_t FormatIndex() const {
return GetNumberOfArguments();
}
HIntConstant* GetFormat() {
return InputAt(FormatIndex())->AsIntConstant();
}
bool NeedsEnvironment() const override { return true; }
bool CanThrow() const override { return true; }
bool CanBeNull() const override { return false; }
DECLARE_INSTRUCTION(StringBuilderAppend);
protected:
DEFAULT_COPY_CONSTRUCTOR(StringBuilderAppend);
};
class HUnresolvedInstanceFieldGet final : public HExpression<1> {
public:
HUnresolvedInstanceFieldGet(HInstruction* obj,
DataType::Type field_type,
uint32_t field_index,
uint32_t dex_pc)
: HExpression(kUnresolvedInstanceFieldGet,
field_type,
SideEffects::AllExceptGCDependency(),
dex_pc),
field_index_(field_index) {
SetRawInputAt(0, obj);
}
bool IsClonable() const override { return true; }
bool NeedsEnvironment() const override { return true; }
bool CanThrow() const override { return true; }
DataType::Type GetFieldType() const { return GetType(); }
uint32_t GetFieldIndex() const { return field_index_; }
DECLARE_INSTRUCTION(UnresolvedInstanceFieldGet);
protected:
DEFAULT_COPY_CONSTRUCTOR(UnresolvedInstanceFieldGet);
private:
const uint32_t field_index_;
};
class HUnresolvedInstanceFieldSet final : public HExpression<2> {
public:
HUnresolvedInstanceFieldSet(HInstruction* obj,
HInstruction* value,
DataType::Type field_type,
uint32_t field_index,
uint32_t dex_pc)
: HExpression(kUnresolvedInstanceFieldSet, SideEffects::AllExceptGCDependency(), dex_pc),
field_index_(field_index) {
SetPackedField<FieldTypeField>(field_type);
DCHECK_EQ(DataType::Kind(field_type), DataType::Kind(value->GetType()));
SetRawInputAt(0, obj);
SetRawInputAt(1, value);
}
bool IsClonable() const override { return true; }
bool NeedsEnvironment() const override { return true; }
bool CanThrow() const override { return true; }
DataType::Type GetFieldType() const { return GetPackedField<FieldTypeField>(); }
uint32_t GetFieldIndex() const { return field_index_; }
DECLARE_INSTRUCTION(UnresolvedInstanceFieldSet);
protected:
DEFAULT_COPY_CONSTRUCTOR(UnresolvedInstanceFieldSet);
private:
static constexpr size_t kFieldFieldType = HInstruction::kNumberOfGenericPackedBits;
static constexpr size_t kFieldFieldTypeSize =
MinimumBitsToStore(static_cast<size_t>(DataType::Type::kLast));
static constexpr size_t kNumberOfUnresolvedStaticFieldSetPackedBits =
kFieldFieldType + kFieldFieldTypeSize;
static_assert(kNumberOfUnresolvedStaticFieldSetPackedBits <= HInstruction::kMaxNumberOfPackedBits,
"Too many packed fields.");
using FieldTypeField = BitField<DataType::Type, kFieldFieldType, kFieldFieldTypeSize>;
const uint32_t field_index_;
};
class HUnresolvedStaticFieldGet final : public HExpression<0> {
public:
HUnresolvedStaticFieldGet(DataType::Type field_type,
uint32_t field_index,
uint32_t dex_pc)
: HExpression(kUnresolvedStaticFieldGet,
field_type,
SideEffects::AllExceptGCDependency(),
dex_pc),
field_index_(field_index) {
}
bool IsClonable() const override { return true; }
bool NeedsEnvironment() const override { return true; }
bool CanThrow() const override { return true; }
DataType::Type GetFieldType() const { return GetType(); }
uint32_t GetFieldIndex() const { return field_index_; }
DECLARE_INSTRUCTION(UnresolvedStaticFieldGet);
protected:
DEFAULT_COPY_CONSTRUCTOR(UnresolvedStaticFieldGet);
private:
const uint32_t field_index_;
};
class HUnresolvedStaticFieldSet final : public HExpression<1> {
public:
HUnresolvedStaticFieldSet(HInstruction* value,
DataType::Type field_type,
uint32_t field_index,
uint32_t dex_pc)
: HExpression(kUnresolvedStaticFieldSet, SideEffects::AllExceptGCDependency(), dex_pc),
field_index_(field_index) {
SetPackedField<FieldTypeField>(field_type);
DCHECK_EQ(DataType::Kind(field_type), DataType::Kind(value->GetType()));
SetRawInputAt(0, value);
}
bool IsClonable() const override { return true; }
bool NeedsEnvironment() const override { return true; }
bool CanThrow() const override { return true; }
DataType::Type GetFieldType() const { return GetPackedField<FieldTypeField>(); }
uint32_t GetFieldIndex() const { return field_index_; }
DECLARE_INSTRUCTION(UnresolvedStaticFieldSet);
protected:
DEFAULT_COPY_CONSTRUCTOR(UnresolvedStaticFieldSet);
private:
static constexpr size_t kFieldFieldType = HInstruction::kNumberOfGenericPackedBits;
static constexpr size_t kFieldFieldTypeSize =
MinimumBitsToStore(static_cast<size_t>(DataType::Type::kLast));
static constexpr size_t kNumberOfUnresolvedStaticFieldSetPackedBits =
kFieldFieldType + kFieldFieldTypeSize;
static_assert(kNumberOfUnresolvedStaticFieldSetPackedBits <= HInstruction::kMaxNumberOfPackedBits,
"Too many packed fields.");
using FieldTypeField = BitField<DataType::Type, kFieldFieldType, kFieldFieldTypeSize>;
const uint32_t field_index_;
};
// Implement the move-exception DEX instruction.
class HLoadException final : public HExpression<0> {
public:
explicit HLoadException(uint32_t dex_pc = kNoDexPc)
: HExpression(kLoadException, DataType::Type::kReference, SideEffects::None(), dex_pc) {
}
bool CanBeNull() const override { return false; }
DECLARE_INSTRUCTION(LoadException);
protected:
DEFAULT_COPY_CONSTRUCTOR(LoadException);
};
// Implicit part of move-exception which clears thread-local exception storage.
// Must not be removed because the runtime expects the TLS to get cleared.
class HClearException final : public HExpression<0> {
public:
explicit HClearException(uint32_t dex_pc = kNoDexPc)
: HExpression(kClearException, SideEffects::AllWrites(), dex_pc) {
}
DECLARE_INSTRUCTION(ClearException);
protected:
DEFAULT_COPY_CONSTRUCTOR(ClearException);
};
class HThrow final : public HExpression<1> {
public:
HThrow(HInstruction* exception, uint32_t dex_pc)
: HExpression(kThrow, SideEffects::CanTriggerGC(), dex_pc) {
SetRawInputAt(0, exception);
}
bool IsControlFlow() const override { return true; }
bool NeedsEnvironment() const override { return true; }
bool CanThrow() const override { return true; }
bool AlwaysThrows() const override { return true; }
DECLARE_INSTRUCTION(Throw);
protected:
DEFAULT_COPY_CONSTRUCTOR(Throw);
};
/**
* Implementation strategies for the code generator of a HInstanceOf
* or `HCheckCast`.
*/
enum class TypeCheckKind { // private marker to avoid generate-operator-out.py from processing.
kUnresolvedCheck, // Check against an unresolved type.
kExactCheck, // Can do a single class compare.
kClassHierarchyCheck, // Can just walk the super class chain.
kAbstractClassCheck, // Can just walk the super class chain, starting one up.
kInterfaceCheck, // No optimization yet when checking against an interface.
kArrayObjectCheck, // Can just check if the array is not primitive.
kArrayCheck, // No optimization yet when checking against a generic array.
kBitstringCheck, // Compare the type check bitstring.
kLast = kArrayCheck
};
std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs);
// Note: HTypeCheckInstruction is just a helper class, not an abstract instruction with an
// `IsTypeCheckInstruction()`. (New virtual methods in the HInstruction class have a high cost.)
class HTypeCheckInstruction : public HVariableInputSizeInstruction {
public:
HTypeCheckInstruction(InstructionKind kind,
DataType::Type type,
HInstruction* object,
HInstruction* target_class_or_null,
TypeCheckKind check_kind,
Handle<mirror::Class> klass,
uint32_t dex_pc,
ArenaAllocator* allocator,
HIntConstant* bitstring_path_to_root,
HIntConstant* bitstring_mask,
SideEffects side_effects)
: HVariableInputSizeInstruction(
kind,
type,
side_effects,
dex_pc,
allocator,
/* number_of_inputs= */ check_kind == TypeCheckKind::kBitstringCheck ? 4u : 2u,
kArenaAllocTypeCheckInputs),
klass_(klass) {
SetPackedField<TypeCheckKindField>(check_kind);
SetPackedFlag<kFlagMustDoNullCheck>(true);
SetPackedFlag<kFlagValidTargetClassRTI>(false);
SetRawInputAt(0, object);
SetRawInputAt(1, target_class_or_null);
DCHECK_EQ(check_kind == TypeCheckKind::kBitstringCheck, bitstring_path_to_root != nullptr);
DCHECK_EQ(check_kind == TypeCheckKind::kBitstringCheck, bitstring_mask != nullptr);
if (check_kind == TypeCheckKind::kBitstringCheck) {
DCHECK(target_class_or_null->IsNullConstant());
SetRawInputAt(2, bitstring_path_to_root);
SetRawInputAt(3, bitstring_mask);
} else {
DCHECK(target_class_or_null->IsLoadClass());
}
}
HLoadClass* GetTargetClass() const {
DCHECK_NE(GetTypeCheckKind(), TypeCheckKind::kBitstringCheck);
HInstruction* load_class = InputAt(1);
DCHECK(load_class->IsLoadClass());
return load_class->AsLoadClass();
}
uint32_t GetBitstringPathToRoot() const {
DCHECK_EQ(GetTypeCheckKind(), TypeCheckKind::kBitstringCheck);
HInstruction* path_to_root = InputAt(2);
DCHECK(path_to_root->IsIntConstant());
return static_cast<uint32_t>(path_to_root->AsIntConstant()->GetValue());
}
uint32_t GetBitstringMask() const {
DCHECK_EQ(GetTypeCheckKind(), TypeCheckKind::kBitstringCheck);
HInstruction* mask = InputAt(3);
DCHECK(mask->IsIntConstant());
return static_cast<uint32_t>(mask->AsIntConstant()->GetValue());
}
bool IsClonable() const override { return true; }
bool CanBeMoved() const override { return true; }
bool InstructionDataEquals(const HInstruction* other) const override {
DCHECK(other->IsInstanceOf() || other->IsCheckCast()) << other->DebugName();
return GetPackedFields() == down_cast<const HTypeCheckInstruction*>(other)->GetPackedFields();
}
bool MustDoNullCheck() const { return GetPackedFlag<kFlagMustDoNullCheck>(); }
void ClearMustDoNullCheck() { SetPackedFlag<kFlagMustDoNullCheck>(false); }
TypeCheckKind GetTypeCheckKind() const { return GetPackedField<TypeCheckKindField>(); }
bool IsExactCheck() const { return GetTypeCheckKind() == TypeCheckKind::kExactCheck; }
ReferenceTypeInfo GetTargetClassRTI() {
if (GetPackedFlag<kFlagValidTargetClassRTI>()) {
// Note: The is_exact flag from the return value should not be used.
return ReferenceTypeInfo::CreateUnchecked(klass_, /* is_exact= */ true);
} else {
return ReferenceTypeInfo::CreateInvalid();
}
}
// Target class RTI is marked as valid by RTP if the klass_ is admissible.
void SetValidTargetClassRTI() {
DCHECK(klass_ != nullptr);
SetPackedFlag<kFlagValidTargetClassRTI>(true);
}
Handle<mirror::Class> GetClass() const {
return klass_;
}
protected:
DEFAULT_COPY_CONSTRUCTOR(TypeCheckInstruction);
private:
static constexpr size_t kFieldTypeCheckKind = kNumberOfGenericPackedBits;
static constexpr size_t kFieldTypeCheckKindSize =
MinimumBitsToStore(static_cast<size_t>(TypeCheckKind::kLast));
static constexpr size_t kFlagMustDoNullCheck = kFieldTypeCheckKind + kFieldTypeCheckKindSize;
static constexpr size_t kFlagValidTargetClassRTI = kFlagMustDoNullCheck + 1;
static constexpr size_t kNumberOfInstanceOfPackedBits = kFlagValidTargetClassRTI + 1;
static_assert(kNumberOfInstanceOfPackedBits <= kMaxNumberOfPackedBits, "Too many packed fields.");
using TypeCheckKindField = BitField<TypeCheckKind, kFieldTypeCheckKind, kFieldTypeCheckKindSize>;
Handle<mirror::Class> klass_;
};
class HInstanceOf final : public HTypeCheckInstruction {
public:
HInstanceOf(HInstruction* object,
HInstruction* target_class_or_null,
TypeCheckKind check_kind,
Handle<mirror::Class> klass,
uint32_t dex_pc,
ArenaAllocator* allocator,
HIntConstant* bitstring_path_to_root,
HIntConstant* bitstring_mask)
: HTypeCheckInstruction(kInstanceOf,
DataType::Type::kBool,
object,
target_class_or_null,
check_kind,
klass,
dex_pc,
allocator,
bitstring_path_to_root,
bitstring_mask,
SideEffectsForArchRuntimeCalls(check_kind)) {}
bool IsClonable() const override { return true; }
bool NeedsEnvironment() const override {
return CanCallRuntime(GetTypeCheckKind());
}
static bool CanCallRuntime(TypeCheckKind check_kind) {
// TODO: Re-evaluate now that mips codegen has been removed.
return check_kind != TypeCheckKind::kExactCheck;
}
static SideEffects SideEffectsForArchRuntimeCalls(TypeCheckKind check_kind) {
return CanCallRuntime(check_kind) ? SideEffects::CanTriggerGC() : SideEffects::None();
}
DECLARE_INSTRUCTION(InstanceOf);
protected:
DEFAULT_COPY_CONSTRUCTOR(InstanceOf);
};
class HBoundType final : public HExpression<1> {
public:
explicit HBoundType(HInstruction* input, uint32_t dex_pc = kNoDexPc)
: HExpression(kBoundType, DataType::Type::kReference, SideEffects::None(), dex_pc),
upper_bound_(ReferenceTypeInfo::CreateInvalid()) {
SetPackedFlag<kFlagUpperCanBeNull>(true);
SetPackedFlag<kFlagCanBeNull>(true);
DCHECK_EQ(input->GetType(), DataType::Type::kReference);
SetRawInputAt(0, input);
}
bool InstructionDataEquals(const HInstruction* other) const override;
bool IsClonable() const override { return true; }
// {Get,Set}Upper* should only be used in reference type propagation.
const ReferenceTypeInfo& GetUpperBound() const { return upper_bound_; }
bool GetUpperCanBeNull() const { return GetPackedFlag<kFlagUpperCanBeNull>(); }
void SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null);
void SetCanBeNull(bool can_be_null) {
DCHECK(GetUpperCanBeNull() || !can_be_null);
SetPackedFlag<kFlagCanBeNull>(can_be_null);
}
bool CanBeNull() const override { return GetPackedFlag<kFlagCanBeNull>(); }
DECLARE_INSTRUCTION(BoundType);
protected:
DEFAULT_COPY_CONSTRUCTOR(BoundType);
private:
// Represents the top constraint that can_be_null_ cannot exceed (i.e. if this
// is false then CanBeNull() cannot be true).
static constexpr size_t kFlagUpperCanBeNull = kNumberOfGenericPackedBits;
static constexpr size_t kFlagCanBeNull = kFlagUpperCanBeNull + 1;
static constexpr size_t kNumberOfBoundTypePackedBits = kFlagCanBeNull + 1;
static_assert(kNumberOfBoundTypePackedBits <= kMaxNumberOfPackedBits, "Too many packed fields.");
// Encodes the most upper class that this instruction can have. In other words
// it is always the case that GetUpperBound().IsSupertypeOf(GetReferenceType()).
// It is used to bound the type in cases like:
// if (x instanceof ClassX) {
// // uper_bound_ will be ClassX
// }
ReferenceTypeInfo upper_bound_;
};
class HCheckCast final : public HTypeCheckInstruction {
public:
HCheckCast(HInstruction* object,
HInstruction* target_class_or_null,
TypeCheckKind check_kind,
Handle<mirror::Class> klass,
uint32_t dex_pc,
ArenaAllocator* allocator,
HIntConstant* bitstring_path_to_root,
HIntConstant* bitstring_mask)
: HTypeCheckInstruction(kCheckCast,
DataType::Type::kVoid,
object,
target_class_or_null,
check_kind,
klass,
dex_pc,
allocator,
bitstring_path_to_root,
bitstring_mask,
SideEffects::CanTriggerGC()) {}
bool IsClonable() const override { return true; }
bool NeedsEnvironment() const override {
// Instruction may throw a CheckCastError.
return true;
}
bool CanThrow() const override { return true; }
DECLARE_INSTRUCTION(CheckCast);
protected:
DEFAULT_COPY_CONSTRUCTOR(CheckCast);
};
/**
* @brief Memory barrier types (see "The JSR-133 Cookbook for Compiler Writers").
* @details We define the combined barrier types that are actually required
* by the Java Memory Model, rather than using exactly the terminology from
* the JSR-133 cookbook. These should, in many cases, be replaced by acquire/release
* primitives. Note that the JSR-133 cookbook generally does not deal with
* store atomicity issues, and the recipes there are not always entirely sufficient.
* The current recipe is as follows:
* -# Use AnyStore ~= (LoadStore | StoreStore) ~= release barrier before volatile store.
* -# Use AnyAny barrier after volatile store. (StoreLoad is as expensive.)
* -# Use LoadAny barrier ~= (LoadLoad | LoadStore) ~= acquire barrier after each volatile load.
* -# Use StoreStore barrier after all stores but before return from any constructor whose
* class has final fields.
* -# Use NTStoreStore to order non-temporal stores with respect to all later
* store-to-memory instructions. Only generated together with non-temporal stores.
*/
enum MemBarrierKind {
kAnyStore,
kLoadAny,
kStoreStore,
kAnyAny,
kNTStoreStore,
kLastBarrierKind = kNTStoreStore
};
std::ostream& operator<<(std::ostream& os, MemBarrierKind kind);
class HMemoryBarrier final : public HExpression<0> {
public:
explicit HMemoryBarrier(MemBarrierKind barrier_kind, uint32_t dex_pc = kNoDexPc)
: HExpression(kMemoryBarrier,
SideEffects::AllWritesAndReads(), // Assume write/read on all fields/arrays.
dex_pc) {
SetPackedField<BarrierKindField>(barrier_kind);
}
bool IsClonable() const override { return true; }
MemBarrierKind GetBarrierKind() { return GetPackedField<BarrierKindField>(); }
DECLARE_INSTRUCTION(MemoryBarrier);
protected:
DEFAULT_COPY_CONSTRUCTOR(MemoryBarrier);
private:
static constexpr size_t kFieldBarrierKind = HInstruction::kNumberOfGenericPackedBits;
static constexpr size_t kFieldBarrierKindSize =
MinimumBitsToStore(static_cast<size_t>(kLastBarrierKind));
static constexpr size_t kNumberOfMemoryBarrierPackedBits =
kFieldBarrierKind + kFieldBarrierKindSize;
static_assert(kNumberOfMemoryBarrierPackedBits <= kMaxNumberOfPackedBits,
"Too many packed fields.");
using BarrierKindField = BitField<MemBarrierKind, kFieldBarrierKind, kFieldBarrierKindSize>;
};
// A constructor fence orders all prior stores to fields that could be accessed via a final field of
// the specified object(s), with respect to any subsequent store that might "publish"
// (i.e. make visible) the specified object to another thread.
//
// JLS 17.5.1 "Semantics of final fields" states that a freeze action happens
// for all final fields (that were set) at the end of the invoked constructor.
//
// The constructor fence models the freeze actions for the final fields of an object
// being constructed (semantically at the end of the constructor). Constructor fences
// have a per-object affinity; two separate objects being constructed get two separate
// constructor fences.
//
// (Note: that if calling a super-constructor or forwarding to another constructor,
// the freezes would happen at the end of *that* constructor being invoked).
//
// The memory model guarantees that when the object being constructed is "published" after
// constructor completion (i.e. escapes the current thread via a store), then any final field
// writes must be observable on other threads (once they observe that publication).
//
// Further, anything written before the freeze, and read by dereferencing through the final field,
// must also be visible (so final object field could itself have an object with non-final fields;
// yet the freeze must also extend to them).
//
// Constructor example:
//
// class HasFinal {
// final int field; Optimizing IR for <init>()V:
// HasFinal() {
// field = 123; HInstanceFieldSet(this, HasFinal.field, 123)
// // freeze(this.field); HConstructorFence(this)
// } HReturn
// }
//
// HConstructorFence can serve double duty as a fence for new-instance/new-array allocations of
// already-initialized classes; in that case the allocation must act as a "default-initializer"
// of the object which effectively writes the class pointer "final field".
//
// For example, we can model default-initialiation as roughly the equivalent of the following:
//
// class Object {
// private final Class header;
// }
//
// Java code: Optimizing IR:
//
// T new_instance<T>() {
// Object obj = allocate_memory(T.class.size); obj = HInvoke(art_quick_alloc_object, T)
// obj.header = T.class; // header write is done by above call.
// // freeze(obj.header) HConstructorFence(obj)
// return (T)obj;
// }
//
// See also:
// * DexCompilationUnit::RequiresConstructorBarrier
// * QuasiAtomic::ThreadFenceForConstructor
//
class HConstructorFence final : public HVariableInputSizeInstruction {
// A fence has variable inputs because the inputs can be removed
// after prepare_for_register_allocation phase.
// (TODO: In the future a fence could freeze multiple objects
// after merging two fences together.)
public:
// `fence_object` is the reference that needs to be protected for correct publication.
//
// It makes sense in the following situations:
// * <init> constructors, it's the "this" parameter (i.e. HParameterValue, s.t. IsThis() == true).
// * new-instance-like instructions, it's the return value (i.e. HNewInstance).
//
// After construction the `fence_object` becomes the 0th input.
// This is not an input in a real sense, but just a convenient place to stash the information
// about the associated object.
HConstructorFence(HInstruction* fence_object,
uint32_t dex_pc,
ArenaAllocator* allocator)
// We strongly suspect there is not a more accurate way to describe the fine-grained reordering
// constraints described in the class header. We claim that these SideEffects constraints
// enforce a superset of the real constraints.
//
// The ordering described above is conservatively modeled with SideEffects as follows:
//
// * To prevent reordering of the publication stores:
// ----> "Reads of objects" is the initial SideEffect.
// * For every primitive final field store in the constructor:
// ----> Union that field's type as a read (e.g. "Read of T") into the SideEffect.
// * If there are any stores to reference final fields in the constructor:
// ----> Use a more conservative "AllReads" SideEffect because any stores to any references
// that are reachable from `fence_object` also need to be prevented for reordering
// (and we do not want to do alias analysis to figure out what those stores are).
//
// In the implementation, this initially starts out as an "all reads" side effect; this is an
// even more conservative approach than the one described above, and prevents all of the
// above reordering without analyzing any of the instructions in the constructor.
//
// If in a later phase we discover that there are no writes to reference final fields,
// we can refine the side effect to a smaller set of type reads (see above constraints).
: HVariableInputSizeInstruction(kConstructorFence,
SideEffects::AllReads(),
dex_pc,
allocator,
/* number_of_inputs= */ 1,
kArenaAllocConstructorFenceInputs) {
DCHECK(fence_object != nullptr);
SetRawInputAt(0, fence_object);
}
// The object associated with this constructor fence.
//
// (Note: This will be null after the prepare_for_register_allocation phase,
// as all constructor fence inputs are removed there).
HInstruction* GetFenceObject() const {
return InputAt(0);
}
// Find all the HConstructorFence uses (`fence_use`) for `this` and:
// - Delete `fence_use` from `this`'s use list.
// - Delete `this` from `fence_use`'s inputs list.
// - If the `fence_use` is dead, remove it from the graph.
//
// A fence is considered dead once it no longer has any uses
// and all of the inputs are dead.
//
// This must *not* be called during/after prepare_for_register_allocation,
// because that removes all the inputs to the fences but the fence is actually
// still considered live.
//
// Returns how many HConstructorFence instructions were removed from graph.
static size_t RemoveConstructorFences(HInstruction* instruction);
// Combine all inputs of `this` and `other` instruction and remove
// `other` from the graph.
//
// Inputs are unique after the merge.
//
// Requirement: `this` must not be the same as `other.
void Merge(HConstructorFence* other);
// Check if this constructor fence is protecting
// an HNewInstance or HNewArray that is also the immediate
// predecessor of `this`.
//
// If `ignore_inputs` is true, then the immediate predecessor doesn't need
// to be one of the inputs of `this`.
//
// Returns the associated HNewArray or HNewInstance,
// or null otherwise.
HInstruction* GetAssociatedAllocation(bool ignore_inputs = false);
DECLARE_INSTRUCTION(ConstructorFence);
protected:
DEFAULT_COPY_CONSTRUCTOR(ConstructorFence);
};
class HMonitorOperation final : public HExpression<1> {
public:
enum class OperationKind {
kEnter,
kExit,
kLast = kExit
};
HMonitorOperation(HInstruction* object, OperationKind kind, uint32_t dex_pc)
: HExpression(kMonitorOperation,
SideEffects::AllExceptGCDependency(), // Assume write/read on all fields/arrays.
dex_pc) {
SetPackedField<OperationKindField>(kind);
SetRawInputAt(0, object);
}
// Instruction may go into runtime, so we need an environment.
bool NeedsEnvironment() const override { return true; }
bool CanThrow() const override {
// Verifier guarantees that monitor-exit cannot throw.
// This is important because it allows the HGraphBuilder to remove
// a dead throw-catch loop generated for `synchronized` blocks/methods.
return IsEnter();
}
OperationKind GetOperationKind() const { return GetPackedField<OperationKindField>(); }
bool IsEnter() const { return GetOperationKind() == OperationKind::kEnter; }
DECLARE_INSTRUCTION(MonitorOperation);
protected:
DEFAULT_COPY_CONSTRUCTOR(MonitorOperation);
private:
static constexpr size_t kFieldOperationKind = HInstruction::kNumberOfGenericPackedBits;
static constexpr size_t kFieldOperationKindSize =
MinimumBitsToStore(static_cast<size_t>(OperationKind::kLast));
static constexpr size_t kNumberOfMonitorOperationPackedBits =
kFieldOperationKind + kFieldOperationKindSize;
static_assert(kNumberOfMonitorOperationPackedBits <= HInstruction::kMaxNumberOfPackedBits,
"Too many packed fields.");
using OperationKindField = BitField<OperationKind, kFieldOperationKind, kFieldOperationKindSize>;
};
class HSelect final : public HExpression<3> {
public:
HSelect(HInstruction* condition,
HInstruction* true_value,
HInstruction* false_value,
uint32_t dex_pc)
: HExpression(kSelect, HPhi::ToPhiType(true_value->GetType()), SideEffects::None(), dex_pc) {
DCHECK_EQ(HPhi::ToPhiType(true_value->GetType()), HPhi::ToPhiType(false_value->GetType()));
// First input must be `true_value` or `false_value` to allow codegens to
// use the SameAsFirstInput allocation policy. We make it `false_value`, so
// that architectures which implement HSelect as a conditional move also
// will not need to invert the condition.
SetRawInputAt(0, false_value);
SetRawInputAt(1, true_value);
SetRawInputAt(2, condition);
}
bool IsClonable() const override { return true; }
HInstruction* GetFalseValue() const { return InputAt(0); }
HInstruction* GetTrueValue() const { return InputAt(1); }
HInstruction* GetCondition() const { return InputAt(2); }
bool CanBeMoved() const override { return true; }
bool InstructionDataEquals(const HInstruction* other ATTRIBUTE_UNUSED) const override {
return true;
}
bool CanBeNull() const override {
return GetTrueValue()->CanBeNull() || GetFalseValue()->CanBeNull();
}
DECLARE_INSTRUCTION(Select);
protected:
DEFAULT_COPY_CONSTRUCTOR(Select);
};
class MoveOperands : public ArenaObject<kArenaAllocMoveOperands> {
public:
MoveOperands(Location source,
Location destination,
DataType::Type type,
HInstruction* instruction)
: source_(source), destination_(destination), type_(type), instruction_(instruction) {}
Location GetSource() const { return source_; }
Location GetDestination() const { return destination_; }
void SetSource(Location value) { source_ = value; }
void SetDestination(Location value) { destination_ = value; }
// The parallel move resolver marks moves as "in-progress" by clearing the
// destination (but not the source).
Location MarkPending() {
DCHECK(!IsPending());
Location dest = destination_;
destination_ = Location::NoLocation();
return dest;
}
void ClearPending(Location dest) {
DCHECK(IsPending());
destination_ = dest;
}
bool IsPending() const {
DCHECK(source_.IsValid() || destination_.IsInvalid());
return destination_.IsInvalid() && source_.IsValid();
}
// True if this blocks a move from the given location.
bool Blocks(Location loc) const {
return !IsEliminated() && source_.OverlapsWith(loc);
}
// A move is redundant if it's been eliminated, if its source and
// destination are the same, or if its destination is unneeded.
bool IsRedundant() const {
return IsEliminated() || destination_.IsInvalid() || source_.Equals(destination_);
}
// We clear both operands to indicate move that's been eliminated.
void Eliminate() {
source_ = destination_ = Location::NoLocation();
}
bool IsEliminated() const {
DCHECK_IMPLIES(source_.IsInvalid(), destination_.IsInvalid());
return source_.IsInvalid();
}
DataType::Type GetType() const { return type_; }
bool Is64BitMove() const {
return DataType::Is64BitType(type_);
}
HInstruction* GetInstruction() const { return instruction_; }
private:
Location source_;
Location destination_;
// The type this move is for.
DataType::Type type_;
// The instruction this move is assocatied with. Null when this move is
// for moving an input in the expected locations of user (including a phi user).
// This is only used in debug mode, to ensure we do not connect interval siblings
// in the same parallel move.
HInstruction* instruction_;
};
std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs);
static constexpr size_t kDefaultNumberOfMoves = 4;
class HParallelMove final : public HExpression<0> {
public:
explicit HParallelMove(ArenaAllocator* allocator, uint32_t dex_pc = kNoDexPc)
: HExpression(kParallelMove, SideEffects::None(), dex_pc),
moves_(allocator->Adapter(kArenaAllocMoveOperands)) {
moves_.reserve(kDefaultNumberOfMoves);
}
void AddMove(Location source,
Location destination,
DataType::Type type,
HInstruction* instruction) {
DCHECK(source.IsValid());
DCHECK(destination.IsValid());
if (kIsDebugBuild) {
if (instruction != nullptr) {
for (const MoveOperands& move : moves_) {
if (move.GetInstruction() == instruction) {
// Special case the situation where the move is for the spill slot
// of the instruction.
if ((GetPrevious() == instruction)
|| ((GetPrevious() == nullptr)
&& instruction->IsPhi()
&& instruction->GetBlock() == GetBlock())) {
DCHECK_NE(destination.GetKind(), move.GetDestination().GetKind())
<< "Doing parallel moves for the same instruction.";
} else {
DCHECK(false) << "Doing parallel moves for the same instruction.";
}
}
}
}
for (const MoveOperands& move : moves_) {
DCHECK(!destination.OverlapsWith(move.GetDestination()))
<< "Overlapped destination for two moves in a parallel move: "
<< move.GetSource() << " ==> " << move.GetDestination() << " and "
<< source << " ==> " << destination << " for " << SafePrint(instruction);
}
}
moves_.emplace_back(source, destination, type, instruction);
}
MoveOperands* MoveOperandsAt(size_t index) {
return &moves_[index];
}
size_t NumMoves() const { return moves_.size(); }
DECLARE_INSTRUCTION(ParallelMove);
protected:
DEFAULT_COPY_CONSTRUCTOR(ParallelMove);
private:
ArenaVector<MoveOperands> moves_;
};
// This instruction computes an intermediate address pointing in the 'middle' of an object. The
// result pointer cannot be handled by GC, so extra care is taken to make sure that this value is
// never used across anything that can trigger GC.
// The result of this instruction is not a pointer in the sense of `DataType::Type::kreference`.
// So we represent it by the type `DataType::Type::kInt`.
class HIntermediateAddress final : public HExpression<2> {
public:
HIntermediateAddress(HInstruction* base_address, HInstruction* offset, uint32_t dex_pc)
: HExpression(kIntermediateAddress,
DataType::Type::kInt32,
SideEffects::DependsOnGC(),
dex_pc) {
DCHECK_EQ(DataType::Size(DataType::Type::kInt32),
DataType::Size(DataType::Type::kReference))
<< "kPrimInt and kPrimNot have different sizes.";
SetRawInputAt(0, base_address);
SetRawInputAt(1, offset);
}
bool IsClonable() const override { return true; }
bool CanBeMoved() const override { return true; }
bool InstructionDataEquals(const HInstruction* other ATTRIBUTE_UNUSED) const override {
return true;
}
bool IsActualObject() const override { return false; }
HInstruction* GetBaseAddress() const { return InputAt(0); }
HInstruction* GetOffset() const { return InputAt(1); }
DECLARE_INSTRUCTION(IntermediateAddress);
protected:
DEFAULT_COPY_CONSTRUCTOR(IntermediateAddress);
};
} // namespace art
#include "nodes_vector.h"
#if defined(ART_ENABLE_CODEGEN_arm) || defined(ART_ENABLE_CODEGEN_arm64)
#include "nodes_shared.h"
#endif
#if defined(ART_ENABLE_CODEGEN_x86) || defined(ART_ENABLE_CODEGEN_x86_64)
#include "nodes_x86.h"
#endif
namespace art HIDDEN {
class OptimizingCompilerStats;
class HGraphVisitor : public ValueObject {
public:
explicit HGraphVisitor(HGraph* graph, OptimizingCompilerStats* stats = nullptr)
: stats_(stats),
graph_(graph) {}
virtual ~HGraphVisitor() {}
virtual void VisitInstruction(HInstruction* instruction ATTRIBUTE_UNUSED) {}
virtual void VisitBasicBlock(HBasicBlock* block);
// Visit the graph following basic block insertion order.
void VisitInsertionOrder();
// Visit the graph following dominator tree reverse post-order.
void VisitReversePostOrder();
HGraph* GetGraph() const { return graph_; }
// Visit functions for instruction classes.
#define DECLARE_VISIT_INSTRUCTION(name, super) \
virtual void Visit##name(H##name* instr) { VisitInstruction(instr); }
FOR_EACH_INSTRUCTION(DECLARE_VISIT_INSTRUCTION)
#undef DECLARE_VISIT_INSTRUCTION
protected:
OptimizingCompilerStats* stats_;
private:
HGraph* const graph_;
DISALLOW_COPY_AND_ASSIGN(HGraphVisitor);
};
class HGraphDelegateVisitor : public HGraphVisitor {
public:
explicit HGraphDelegateVisitor(HGraph* graph, OptimizingCompilerStats* stats = nullptr)
: HGraphVisitor(graph, stats) {}
virtual ~HGraphDelegateVisitor() {}
// Visit functions that delegate to to super class.
#define DECLARE_VISIT_INSTRUCTION(name, super) \
void Visit##name(H##name* instr) override { Visit##super(instr); }
FOR_EACH_INSTRUCTION(DECLARE_VISIT_INSTRUCTION)
#undef DECLARE_VISIT_INSTRUCTION
private:
DISALLOW_COPY_AND_ASSIGN(HGraphDelegateVisitor);
};
// Create a clone of the instruction, insert it into the graph; replace the old one with a new
// and remove the old instruction.
HInstruction* ReplaceInstrOrPhiByClone(HInstruction* instr);
// Create a clone for each clonable instructions/phis and replace the original with the clone.
//
// Used for testing individual instruction cloner.
class CloneAndReplaceInstructionVisitor final : public HGraphDelegateVisitor {
public:
explicit CloneAndReplaceInstructionVisitor(HGraph* graph)
: HGraphDelegateVisitor(graph), instr_replaced_by_clones_count_(0) {}
void VisitInstruction(HInstruction* instruction) override {
if (instruction->IsClonable()) {
ReplaceInstrOrPhiByClone(instruction);
instr_replaced_by_clones_count_++;
}
}
size_t GetInstrReplacedByClonesCount() const { return instr_replaced_by_clones_count_; }
private:
size_t instr_replaced_by_clones_count_;
DISALLOW_COPY_AND_ASSIGN(CloneAndReplaceInstructionVisitor);
};
// Iterator over the blocks that art part of the loop. Includes blocks part
// of an inner loop. The order in which the blocks are iterated is on their
// block id.
class HBlocksInLoopIterator : public ValueObject {
public:
explicit HBlocksInLoopIterator(const HLoopInformation& info)
: blocks_in_loop_(info.GetBlocks()),
blocks_(info.GetHeader()->GetGraph()->GetBlocks()),
index_(0) {
if (!blocks_in_loop_.IsBitSet(index_)) {
Advance();
}
}
bool Done() const { return index_ == blocks_.size(); }
HBasicBlock* Current() const { return blocks_[index_]; }
void Advance() {
++index_;
for (size_t e = blocks_.size(); index_ < e; ++index_) {
if (blocks_in_loop_.IsBitSet(index_)) {
break;
}
}
}
private:
const BitVector& blocks_in_loop_;
const ArenaVector<HBasicBlock*>& blocks_;
size_t index_;
DISALLOW_COPY_AND_ASSIGN(HBlocksInLoopIterator);
};
// Iterator over the blocks that art part of the loop. Includes blocks part
// of an inner loop. The order in which the blocks are iterated is reverse
// post order.
class HBlocksInLoopReversePostOrderIterator : public ValueObject {
public:
explicit HBlocksInLoopReversePostOrderIterator(const HLoopInformation& info)
: blocks_in_loop_(info.GetBlocks()),
blocks_(info.GetHeader()->GetGraph()->GetReversePostOrder()),
index_(0) {
if (!blocks_in_loop_.IsBitSet(blocks_[index_]->GetBlockId())) {
Advance();
}
}
bool Done() const { return index_ == blocks_.size(); }
HBasicBlock* Current() const { return blocks_[index_]; }
void Advance() {
++index_;
for (size_t e = blocks_.size(); index_ < e; ++index_) {
if (blocks_in_loop_.IsBitSet(blocks_[index_]->GetBlockId())) {
break;
}
}
}
private:
const BitVector& blocks_in_loop_;
const ArenaVector<HBasicBlock*>& blocks_;
size_t index_;
DISALLOW_COPY_AND_ASSIGN(HBlocksInLoopReversePostOrderIterator);
};
// Returns int64_t value of a properly typed constant.
inline int64_t Int64FromConstant(HConstant* constant) {
if (constant->IsIntConstant()) {
return constant->AsIntConstant()->GetValue();
} else if (constant->IsLongConstant()) {
return constant->AsLongConstant()->GetValue();
} else {
DCHECK(constant->IsNullConstant()) << constant->DebugName();
return 0;
}
}
// Returns true iff instruction is an integral constant (and sets value on success).
inline bool IsInt64AndGet(HInstruction* instruction, /*out*/ int64_t* value) {
if (instruction->IsIntConstant()) {
*value = instruction->AsIntConstant()->GetValue();
return true;
} else if (instruction->IsLongConstant()) {
*value = instruction->AsLongConstant()->GetValue();
return true;
} else if (instruction->IsNullConstant()) {
*value = 0;
return true;
}
return false;
}
// Returns true iff instruction is the given integral constant.
inline bool IsInt64Value(HInstruction* instruction, int64_t value) {
int64_t val = 0;
return IsInt64AndGet(instruction, &val) && val == value;
}
// Returns true iff instruction is a zero bit pattern.
inline bool IsZeroBitPattern(HInstruction* instruction) {
return instruction->IsConstant() && instruction->AsConstant()->IsZeroBitPattern();
}
// Implement HInstruction::Is##type() for concrete instructions.
#define INSTRUCTION_TYPE_CHECK(type, super) \
inline bool HInstruction::Is##type() const { return GetKind() == k##type; }
FOR_EACH_CONCRETE_INSTRUCTION(INSTRUCTION_TYPE_CHECK)
#undef INSTRUCTION_TYPE_CHECK
// Implement HInstruction::Is##type() for abstract instructions.
#define INSTRUCTION_TYPE_CHECK_RESULT(type, super) \
std::is_base_of<BaseType, H##type>::value,
#define INSTRUCTION_TYPE_CHECK(type, super) \
inline bool HInstruction::Is##type() const { \
DCHECK_LT(GetKind(), kLastInstructionKind); \
using BaseType = H##type; \
static constexpr bool results[] = { \
FOR_EACH_CONCRETE_INSTRUCTION(INSTRUCTION_TYPE_CHECK_RESULT) \
}; \
return results[static_cast<size_t>(GetKind())]; \
}
FOR_EACH_ABSTRACT_INSTRUCTION(INSTRUCTION_TYPE_CHECK)
#undef INSTRUCTION_TYPE_CHECK
#undef INSTRUCTION_TYPE_CHECK_RESULT
#define INSTRUCTION_TYPE_CAST(type, super) \
inline const H##type* HInstruction::As##type() const { \
return Is##type() ? down_cast<const H##type*>(this) : nullptr; \
} \
inline H##type* HInstruction::As##type() { \
return Is##type() ? static_cast<H##type*>(this) : nullptr; \
}
FOR_EACH_INSTRUCTION(INSTRUCTION_TYPE_CAST)
#undef INSTRUCTION_TYPE_CAST
// Create space in `blocks` for adding `number_of_new_blocks` entries
// starting at location `at`. Blocks after `at` are moved accordingly.
inline void MakeRoomFor(ArenaVector<HBasicBlock*>* blocks,
size_t number_of_new_blocks,
size_t after) {
DCHECK_LT(after, blocks->size());
size_t old_size = blocks->size();
size_t new_size = old_size + number_of_new_blocks;
blocks->resize(new_size);
std::copy_backward(blocks->begin() + after + 1u, blocks->begin() + old_size, blocks->end());
}
/*
* Hunt "under the hood" of array lengths (leading to array references),
* null checks (also leading to array references), and new arrays
* (leading to the actual length). This makes it more likely related
* instructions become actually comparable.
*/
inline HInstruction* HuntForDeclaration(HInstruction* instruction) {
while (instruction->IsArrayLength() ||
instruction->IsNullCheck() ||
instruction->IsNewArray()) {
instruction = instruction->IsNewArray()
? instruction->AsNewArray()->GetLength()
: instruction->InputAt(0);
}
return instruction;
}
inline bool IsAddOrSub(const HInstruction* instruction) {
return instruction->IsAdd() || instruction->IsSub();
}
void RemoveEnvironmentUses(HInstruction* instruction);
bool HasEnvironmentUsedByOthers(HInstruction* instruction);
void ResetEnvironmentInputRecords(HInstruction* instruction);
// Detects an instruction that is >= 0. As long as the value is carried by
// a single instruction, arithmetic wrap-around cannot occur.
bool IsGEZero(HInstruction* instruction);
} // namespace art
#endif // ART_COMPILER_OPTIMIZING_NODES_H_
|