DXR will be turned off on Tuesday, December 29th. It will redirect to Searchfox.
See the announcement on Discourse.

DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Mercurial (c68fe15a81fc)

VCS Links

Line Code
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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 * vim: set ts=8 sts=2 et sw=2 tw=80:
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */


#include "mozilla/ScopeExit.h"

#include "debugger/DebugAPI.h"
#include "jit/arm/Simulator-arm.h"
#include "jit/BaselineFrame.h"
#include "jit/BaselineFrame.h"
#include "jit/BaselineIC.h"
#include "jit/BaselineJIT.h"
#include "jit/CompileInfo.h"
#include "jit/Ion.h"
#include "jit/IonScript.h"
#include "jit/IonScript.h"
#include "jit/JitSpewer.h"
#include "jit/mips32/Simulator-mips32.h"
#include "jit/mips64/Simulator-mips64.h"
#include "jit/Recover.h"
#include "jit/RematerializedFrame.h"
#include "jit/RematerializedFrame.h"
#include "js/Utility.h"
#include "util/Memory.h"
#include "vm/ArgumentsObject.h"
#include "vm/BytecodeUtil.h"
#include "vm/TraceLogging.h"
#include "vm/TraceLogging.h"

#include "jit/JitFrames-inl.h"
#include "vm/JSScript-inl.h"


using namespace js;
using namespace js::jit;


// BaselineStackBuilder may reallocate its buffer if the current one is too
// BaselineStackBuilder may reallocate its buffer if the current one is too
// small. To avoid dangling pointers, BufferPointer represents a pointer into
// this buffer as a pointer to the header and a fixed offset.
template <typename T>
template <typename T>
class BufferPointer {
  const UniquePtr<BaselineBailoutInfo>& header_;
  size_t offset_;
  bool heap_;


 public:
  BufferPointer(const UniquePtr<BaselineBailoutInfo>& header, size_t offset,
                bool heap)
      : header_(header), offset_(offset), heap_(heap) {}


  T* get() const {
    BaselineBailoutInfo* header = header_.get();
    if (!heap_) {
      return (T*)(header->incomingStack + offset_);
    }
    }

    uint8_t* p = header->copyStackTop - offset_;
    MOZ_ASSERT(p >= header->copyStackBottom && p < header->copyStackTop);
    return (T*)p;
  }
  }

  void set(const T& value) { *get() = value; }

  // Note: we return a copy instead of a reference, to avoid potential memory
  // Note: we return a copy instead of a reference, to avoid potential memory
  // safety hazards when the underlying buffer gets resized.
  const T operator*() const { return *get(); }
  T* operator->() const { return get(); }
};

/**
 * BaselineStackBuilder helps abstract the process of rebuilding the C stack on
 * the heap. It takes a bailout iterator and keeps track of the point on the C
 * the heap. It takes a bailout iterator and keeps track of the point on the C
 * stack from which the reconstructed frames will be written.
 *
 * It exposes methods to write data into the heap memory storing the
 * reconstructed stack.  It also exposes method to easily calculate addresses.
 * This includes both the virtual address that a particular value will be at
 * This includes both the virtual address that a particular value will be at
 * when it's eventually copied onto the stack, as well as the current actual
 * address of that value (whether on the heap allocated portion being
 * constructed or the existing stack).
 *
 *
 * The abstraction handles transparent re-allocation of the heap memory when it
 * needs to be enlarged to accommodate new data.  Similarly to the C stack, the
 * data that's written to the reconstructed stack grows from high to low in
 * memory.
 *
 *
 * The lowest region of the allocated memory contains a BaselineBailoutInfo
 * structure that points to the start and end of the written data.
 */
struct BaselineStackBuilder {
  JSContext* cx_;
  JSContext* cx_;
  const JSJitFrameIter& iter_;
  JitFrameLayout* frame_ = nullptr;

  size_t bufferTotal_ = 0;
  size_t bufferAvail_ = 0;
  size_t bufferAvail_ = 0;
  size_t bufferUsed_ = 0;
  size_t framePushed_ = 0;

  UniquePtr<BaselineBailoutInfo> header_;


  BaselineStackBuilder(JSContext* cx, const JSJitFrameIter& iter,
                       size_t initialSize)
      : cx_(cx),
        iter_(iter),
        frame_(static_cast<JitFrameLayout*>(iter.current())),
        frame_(static_cast<JitFrameLayout*>(iter.current())),
        bufferTotal_(initialSize) {
    MOZ_ASSERT(bufferTotal_ >= sizeof(BaselineBailoutInfo));
    MOZ_ASSERT(iter.isBailoutJS());
  }


  MOZ_MUST_USE bool init() {
    MOZ_ASSERT(!header_);
    MOZ_ASSERT(bufferUsed_ == 0);

    uint8_t* bufferRaw = cx_->pod_calloc<uint8_t>(bufferTotal_);
    uint8_t* bufferRaw = cx_->pod_calloc<uint8_t>(bufferTotal_);
    if (!bufferRaw) {
      return false;
    }
    bufferAvail_ = bufferTotal_ - sizeof(BaselineBailoutInfo);


    header_.reset(new (bufferRaw) BaselineBailoutInfo());
    header_->incomingStack = reinterpret_cast<uint8_t*>(frame_);
    header_->copyStackTop = bufferRaw + bufferTotal_;
    header_->copyStackBottom = header_->copyStackTop;
    return true;
    return true;
  }

  MOZ_MUST_USE bool enlarge() {
  MOZ_MUST_USE bool enlarge() {
    MOZ_ASSERT(header_ != nullptr);
    MOZ_ASSERT(header_ != nullptr);
    if (bufferTotal_ & mozilla::tl::MulOverflowMask<2>::value) {
      ReportOutOfMemory(cx_);
      return false;
      return false;
    }

    size_t newSize = bufferTotal_ * 2;
    uint8_t* newBufferRaw = cx_->pod_calloc<uint8_t>(newSize);
    if (!newBufferRaw) {
    if (!newBufferRaw) {
      return false;
    }

    // Initialize the new buffer.
    //
    //
    //   Before:
    //
    //     [ Header | .. | Payload ]
    //
    //   After:
    //
    //
    //     [ Header | ............... | Payload ]
    //
    // Size of Payload is |bufferUsed_|.
    //
    // We need to copy from the old buffer and header to the new buffer before
    // We need to copy from the old buffer and header to the new buffer before
    // we set header_ (this deletes the old buffer).
    //
    // We also need to update |copyStackBottom| and |copyStackTop| because these
    // fields point to the Payload's start and end, respectively.
    using BailoutInfoPtr = UniquePtr<BaselineBailoutInfo>;
    using BailoutInfoPtr = UniquePtr<BaselineBailoutInfo>;
    BailoutInfoPtr newHeader(new (newBufferRaw) BaselineBailoutInfo(*header_));
    newHeader->copyStackTop = newBufferRaw + newSize;
    newHeader->copyStackBottom = newHeader->copyStackTop - bufferUsed_;
    memcpy(newHeader->copyStackBottom, header_->copyStackBottom, bufferUsed_);
    bufferTotal_ = newSize;
    bufferTotal_ = newSize;
    bufferAvail_ = newSize - (sizeof(BaselineBailoutInfo) + bufferUsed_);
    header_ = std::move(newHeader);
    return true;
  }


  BaselineBailoutInfo* info() {
    MOZ_ASSERT(header_);
    return header_.get();
  }


  BaselineBailoutInfo* takeBuffer() {
    MOZ_ASSERT(header_);
    return header_.release();
  }
  }

  void resetFramePushed() { framePushed_ = 0; }

  size_t framePushed() const { return framePushed_; }


  MOZ_MUST_USE bool subtract(size_t size, const char* info = nullptr) {
    // enlarge the buffer if need be.
    while (size > bufferAvail_) {
    while (size > bufferAvail_) {
      if (!enlarge()) {
        return false;
      }
    }
    }

    // write out element.
    header_->copyStackBottom -= size;
    bufferAvail_ -= size;
    bufferUsed_ += size;
    bufferUsed_ += size;
    framePushed_ += size;
    if (info) {
      JitSpew(JitSpew_BaselineBailouts, "      SUB_%03d   %p/%p %-15s",
              (int)size, header_->copyStackBottom,
              virtualPointerAtStackOffset(0), info);
              virtualPointerAtStackOffset(0), info);
    }
    return true;
  }

  template <typename T>
  template <typename T>
  MOZ_MUST_USE bool write(const T& t) {
    MOZ_ASSERT(!(uintptr_t(&t) >= uintptr_t(header_->copyStackBottom) &&
                 uintptr_t(&t) < uintptr_t(header_->copyStackTop)),
               "Should not reference memory that can be freed");
    if (!subtract(sizeof(T))) {
    if (!subtract(sizeof(T))) {
      return false;
    }
    memcpy(header_->copyStackBottom, &t, sizeof(T));
    return true;
  }
  }

  template <typename T>
  MOZ_MUST_USE bool writePtr(T* t, const char* info) {
    if (!write<T*>(t)) {
      return false;
    }
    if (info) {
      JitSpew(JitSpew_BaselineBailouts, "      WRITE_PTR %p/%p %-15s %p",
              header_->copyStackBottom, virtualPointerAtStackOffset(0), info,
              header_->copyStackBottom, virtualPointerAtStackOffset(0), info,
              t);
    }
    return true;
  }


  MOZ_MUST_USE bool writeWord(size_t w, const char* info) {
    if (!write<size_t>(w)) {
      return false;
    }
    if (info) {
    if (info) {
      if (sizeof(size_t) == 4) {
        JitSpew(JitSpew_BaselineBailouts, "      WRITE_WRD %p/%p %-15s %08zx",
                header_->copyStackBottom, virtualPointerAtStackOffset(0), info,
                header_->copyStackBottom, virtualPointerAtStackOffset(0), info,
                w);
                w);
      } else {
        JitSpew(JitSpew_BaselineBailouts, "      WRITE_WRD %p/%p %-15s %016zx",
                header_->copyStackBottom, virtualPointerAtStackOffset(0), info,
                header_->copyStackBottom, virtualPointerAtStackOffset(0), info,
                w);
      }
    }
    return true;
  }
  }

  MOZ_MUST_USE bool writeValue(const Value& val, const char* info) {
    if (!write<Value>(val)) {
      return false;
    }
    }
    if (info) {
      JitSpew(JitSpew_BaselineBailouts,
              "      WRITE_VAL %p/%p %-15s %016" PRIx64,
              header_->copyStackBottom, virtualPointerAtStackOffset(0), info,
              *((uint64_t*)&val));
    }
    return true;
  }


  MOZ_MUST_USE bool maybeWritePadding(size_t alignment, size_t after,
                                      const char* info) {
    MOZ_ASSERT(framePushed_ % sizeof(Value) == 0);
    MOZ_ASSERT(after % sizeof(Value) == 0);
    size_t offset = ComputeByteAlignment(after, alignment);
    size_t offset = ComputeByteAlignment(after, alignment);
    while (framePushed_ % alignment != offset) {
      if (!writeValue(MagicValue(JS_ARG_POISON), info)) {
        return false;
      }
    }
    }

    return true;
  }

  Value popValue() {
  Value popValue() {
    MOZ_ASSERT(bufferUsed_ >= sizeof(Value));
    MOZ_ASSERT(framePushed_ >= sizeof(Value));
    bufferAvail_ += sizeof(Value);
    bufferUsed_ -= sizeof(Value);
    bufferUsed_ -= sizeof(Value);
    framePushed_ -= sizeof(Value);
    Value result = *((Value*)header_->copyStackBottom);
    header_->copyStackBottom += sizeof(Value);
    return result;
  }
  }

  void setResumeFramePtr(void* resumeFramePtr) {
    header_->resumeFramePtr = resumeFramePtr;
  }


  void setResumeAddr(void* resumeAddr) { header_->resumeAddr = resumeAddr; }

  void setMonitorPC(jsbytecode* pc) { header_->monitorPC = pc; }

  void setFrameSizeOfInnerMostFrame(uint32_t size) {
    header_->frameSizeOfInnerMostFrame = size;
    header_->frameSizeOfInnerMostFrame = size;
  }

  template <typename T>
  BufferPointer<T> pointerAtStackOffset(size_t offset) {
    if (offset < bufferUsed_) {
    if (offset < bufferUsed_) {
      // Calculate offset from copyStackTop.
      offset = header_->copyStackTop - (header_->copyStackBottom + offset);
      return BufferPointer<T>(header_, offset, /* heap = */ true);
    }


    return BufferPointer<T>(header_, offset - bufferUsed_, /* heap = */ false);
  }

  BufferPointer<Value> valuePointerAtStackOffset(size_t offset) {
    return pointerAtStackOffset<Value>(offset);
    return pointerAtStackOffset<Value>(offset);
  }

  inline uint8_t* virtualPointerAtStackOffset(size_t offset) {
    if (offset < bufferUsed_) {
      return reinterpret_cast<uint8_t*>(frame_) - (bufferUsed_ - offset);
      return reinterpret_cast<uint8_t*>(frame_) - (bufferUsed_ - offset);
    }
    return reinterpret_cast<uint8_t*>(frame_) + (offset - bufferUsed_);
  }

  inline JitFrameLayout* startFrame() { return frame_; }
  inline JitFrameLayout* startFrame() { return frame_; }

  BufferPointer<JitFrameLayout> topFrameAddress() {
    return pointerAtStackOffset<JitFrameLayout>(0);
  }


  //
  // This method should only be called when the builder is in a state where it
  // is starting to construct the stack frame for the next callee.  This means
  // that the lowest value on the constructed stack is the return address for
  // the previous caller frame.
  // the previous caller frame.
  //
  // This method is used to compute the value of the frame pointer (e.g. ebp on
  // x86) that would have been saved by the baseline jitcode when it was
  // entered.  In some cases, this value can be bogus since we can ensure that
  // the caller would have saved it anyway.
  // the caller would have saved it anyway.
  //
  void* calculatePrevFramePtr() {
    // Get the incoming frame.
    BufferPointer<JitFrameLayout> topFrame = topFrameAddress();
    FrameType type = topFrame->prevType();
    FrameType type = topFrame->prevType();

    // For IonJS, IonICCall and Entry frames, the "saved" frame pointer
    // in the baseline frame is meaningless, since Ion saves all registers
    // before calling other ion frames, and the entry frame saves all
    // before calling other ion frames, and the entry frame saves all
    // registers too.
    if (JSJitFrameIter::isEntry(type) || type == FrameType::IonJS ||
        type == FrameType::IonICCall) {
      return nullptr;
    }
    }

    // BaselineStub - Baseline calling into Ion.
    //  PrevFramePtr needs to point to the BaselineStubFrame's saved frame
    //  pointer.
    //      STACK_START_ADDR
    //      STACK_START_ADDR
    //          + JitFrameLayout::Size()
    //          + PREV_FRAME_SIZE
    //          - BaselineStubFrameLayout::reverseOffsetOfSavedFramePtr()
    if (type == FrameType::BaselineStub) {
      size_t offset = JitFrameLayout::Size() + topFrame->prevFrameLocalSize() +
      size_t offset = JitFrameLayout::Size() + topFrame->prevFrameLocalSize() +
                      BaselineStubFrameLayout::reverseOffsetOfSavedFramePtr();
      return virtualPointerAtStackOffset(offset);
    }

    MOZ_ASSERT(type == FrameType::Rectifier);
    MOZ_ASSERT(type == FrameType::Rectifier);
    // Rectifier - behaviour depends on the frame preceding the rectifier frame,
    // and whether the arch is x86 or not.  The x86 rectifier frame saves the
    // frame pointer, so we can calculate it directly.  For other archs, the
    // previous frame pointer is stored on the stack in the frame that precedes
    // the rectifier frame.
    size_t priorOffset =
        JitFrameLayout::Size() + topFrame->prevFrameLocalSize();
        JitFrameLayout::Size() + topFrame->prevFrameLocalSize();
#if defined(JS_CODEGEN_X86)
    // On X86, the FramePointer is pushed as the first value in the Rectifier
    // frame.
    static_assert(BaselineFrameReg == FramePointer);
    priorOffset -= sizeof(void*);
    priorOffset -= sizeof(void*);
    return virtualPointerAtStackOffset(priorOffset);
#elif defined(JS_CODEGEN_ARM) || defined(JS_CODEGEN_ARM64) ||   \
    defined(JS_CODEGEN_MIPS32) || defined(JS_CODEGEN_MIPS64) || \
    defined(JS_CODEGEN_X64)
    // On X64, ARM, ARM64, and MIPS, the frame pointer save location depends on
    // On X64, ARM, ARM64, and MIPS, the frame pointer save location depends on
    // the caller of the rectifier frame.
    BufferPointer<RectifierFrameLayout> priorFrame =
        pointerAtStackOffset<RectifierFrameLayout>(priorOffset);
    FrameType priorType = priorFrame->prevType();
    MOZ_ASSERT(JSJitFrameIter::isEntry(priorType) ||
    MOZ_ASSERT(JSJitFrameIter::isEntry(priorType) ||
               priorType == FrameType::IonJS ||
               priorType == FrameType::BaselineStub);

    // If the frame preceding the rectifier is an IonJS or entry frame,
    // then once again the frame pointer does not matter.
    // then once again the frame pointer does not matter.
    if (priorType == FrameType::IonJS || JSJitFrameIter::isEntry(priorType)) {
      return nullptr;
    }


    // Otherwise, the frame preceding the rectifier is a BaselineStub frame.
    //  let X = STACK_START_ADDR + JitFrameLayout::Size() + PREV_FRAME_SIZE
    //      X + RectifierFrameLayout::Size()
    //        + ((RectifierFrameLayout*) X)->prevFrameLocalSize()
    //        - BaselineStubFrameLayout::reverseOffsetOfSavedFramePtr()
    //        - BaselineStubFrameLayout::reverseOffsetOfSavedFramePtr()
    size_t extraOffset =
        RectifierFrameLayout::Size() + priorFrame->prevFrameLocalSize() +
        BaselineStubFrameLayout::reverseOffsetOfSavedFramePtr();
    return virtualPointerAtStackOffset(priorOffset + extraOffset);
    return virtualPointerAtStackOffset(priorOffset + extraOffset);
#elif defined(JS_CODEGEN_NONE)
    (void)priorOffset;
    MOZ_CRASH();
#else
#  error "Bad architecture!"
#  error "Bad architecture!"
#endif
  }
};

#ifdef DEBUG
#ifdef DEBUG
static inline bool IsInlinableFallback(ICFallbackStub* icEntry) {
  return icEntry->isCall_Fallback() || icEntry->isGetProp_Fallback() ||
         icEntry->isSetProp_Fallback() || icEntry->isGetElem_Fallback();
}
}
#endif

static inline void* GetStubReturnAddress(JSContext* cx, JSOp op) {
  const BaselineICFallbackCode& code =
      cx->runtime()->jitRuntime()->baselineICFallbackCode();
      cx->runtime()->jitRuntime()->baselineICFallbackCode();

  if (IsGetPropOp(op)) {
    return code.bailoutReturnAddr(BailoutReturnKind::GetProp);
  }
  if (IsSetPropOp(op)) {
  if (IsSetPropOp(op)) {
    return code.bailoutReturnAddr(BailoutReturnKind::SetProp);
  }
  if (IsGetElemOp(op)) {
    return code.bailoutReturnAddr(BailoutReturnKind::GetElem);
  }
  }

  // This should be a call op of some kind, now.
  MOZ_ASSERT(IsInvokeOp(op) && !IsSpreadOp(op));
  if (IsConstructOp(op)) {
    return code.bailoutReturnAddr(BailoutReturnKind::New);
  }
  return code.bailoutReturnAddr(BailoutReturnKind::Call);
  return code.bailoutReturnAddr(BailoutReturnKind::Call);
}

static inline jsbytecode* GetNextNonLoopHeadPc(jsbytecode* pc,
                                               jsbytecode** skippedLoopHead) {
  JSOp op = JSOp(*pc);
  JSOp op = JSOp(*pc);
  switch (op) {
    case JSOp::Goto:
      return pc + GET_JUMP_OFFSET(pc);

    case JSOp::LoopHead:
    case JSOp::LoopHead:
      *skippedLoopHead = pc;
      return GetNextPc(pc);

    case JSOp::Nop:
    case JSOp::Nop:
      return GetNextPc(pc);

    default:
      return pc;
  }
  }
}

// Returns the pc to resume execution at in Baseline after a bailout.
static jsbytecode* GetResumePC(JSScript* script, jsbytecode* pc,
                               bool resumeAfter) {
                               bool resumeAfter) {
  if (resumeAfter) {
    return GetNextPc(pc);
  }

  // If we are resuming at a LoopHead op, resume at the next op to avoid
  // If we are resuming at a LoopHead op, resume at the next op to avoid
  // a bailout -> enter Ion -> bailout loop with --ion-eager.
  //
  // The algorithm below is the "tortoise and the hare" algorithm. See bug
  // 994444 for more explanation.
  jsbytecode* skippedLoopHead = nullptr;
  jsbytecode* skippedLoopHead = nullptr;
  jsbytecode* fasterPc = pc;
  while (true) {
    pc = GetNextNonLoopHeadPc(pc, &skippedLoopHead);
    fasterPc = GetNextNonLoopHeadPc(fasterPc, &skippedLoopHead);
    fasterPc = GetNextNonLoopHeadPc(fasterPc, &skippedLoopHead);
    fasterPc = GetNextNonLoopHeadPc(fasterPc, &skippedLoopHead);
    if (fasterPc == pc) {
      break;
    }
  }

  return pc;
}


static bool HasLiveStackValueAtDepth(HandleScript script, jsbytecode* pc,
                                     uint32_t stackSlotIndex,
                                     uint32_t stackDepth) {
  // Return true iff stackSlotIndex is a stack value that's part of an active
  // iterator loop instead of a normal expression stack slot.
  // iterator loop instead of a normal expression stack slot.

  MOZ_ASSERT(stackSlotIndex < stackDepth);

  for (TryNoteIterAllNoGC tni(script, pc); !tni.done(); ++tni) {
    const TryNote& tn = **tni;
    const TryNote& tn = **tni;

    switch (tn.kind()) {
      case TryNoteKind::ForIn:
      case TryNoteKind::ForOf:
      case TryNoteKind::Destructuring:
      case TryNoteKind::Destructuring:
        MOZ_ASSERT(tn.stackDepth <= stackDepth);
        if (stackSlotIndex < tn.stackDepth) {
          return true;
        }
        break;
        break;

      default:
        break;
    }
  }
  }

  return false;
}

static bool IsPrologueBailout(const SnapshotIterator& iter,
                              const ExceptionBailoutInfo* excInfo) {
                              const ExceptionBailoutInfo* excInfo) {
  // If we are propagating an exception for debug mode, we will not resume
  // into baseline code, but instead into HandleExceptionBaseline (i.e.,
  // never before the prologue).
  return iter.pcOffset() == 0 && !iter.resumeAfter() &&
         (!excInfo || !excInfo->propagatingIonExceptionForDebugMode());
         (!excInfo || !excInfo->propagatingIonExceptionForDebugMode());
}

/* clang-format off */
// For every inline frame, we write out the following data:
//
//
//                      |      ...      |
//                      +---------------+
//                      |  Descr(???)   |  --- Descr size here is (PREV_FRAME_SIZE)
//                      +---------------+
//                      |  ReturnAddr   |
//                      |  ReturnAddr   |
//             --       +===============+  --- OVERWRITE STARTS HERE  (START_STACK_ADDR)
//             |        | PrevFramePtr  |
//             |    +-> +---------------+
//             |    |   |   Baseline    |
//             |    |   |    Frame      |
//             |    |   |    Frame      |
//             |    |   +---------------+
//             |    |   |    Fixed0     |
//             |    |   +---------------+
//         +--<     |   |     ...       |
//         |   |    |   +---------------+
//         |   |    |   +---------------+
//         |   |    |   |    FixedF     |
//         |   |    |   +---------------+
//         |   |    |   |    Stack0     |
//         |   |    |   +---------------+
//         |   |    |   +---------------+
//         |   |    |   |     ...       |
//         |   |    |   +---------------+
//         |   |    |   |    StackS     |
//         |   --   |   +---------------+  --- IF NOT LAST INLINE FRAME,
//         +------------|  Descr(BLJS)  |  --- CALLING INFO STARTS HERE
//         +------------|  Descr(BLJS)  |  --- CALLING INFO STARTS HERE
//                  |   +---------------+
//                  |   |  ReturnAddr   | <-- return into main jitcode after IC
//             --   |   +===============+
//             |    |   |    StubPtr    |
//             |    |   +---------------+
//             |    |   +---------------+
//             |    +---|   FramePtr    |
//             |        +---------------+  --- The inlined frame might OSR in Ion
//             |        |   Padding?    |  --- Thus the return address should be aligned.
//             |        +---------------+
//         +--<         |     ArgA      |
//         +--<         |     ArgA      |
//         |   |        +---------------+
//         |   |        |     ...       |
//         |   |        +---------------+
//         |   |        |     Arg0      |
//         |   |        +---------------+
//         |   |        +---------------+
//         |   |        |     ThisV     |
//         |   --       +---------------+
//         |            |  ActualArgC   |
//         |            +---------------+
//         |            |  CalleeToken  |
//         |            |  CalleeToken  |
//         |            +---------------+
//         +------------| Descr(BLStub) |
//                      +---------------+
//                      |  ReturnAddr   | <-- return into ICCall_Scripted IC
//             --       +===============+ --- IF CALLEE FORMAL ARGS > ActualArgC
//             --       +===============+ --- IF CALLEE FORMAL ARGS > ActualArgC
//             |        |   Padding?    |
//             |        +---------------+
//             |        |  UndefinedU   |
//             |        +---------------+
//             |        |     ...       |
//             |        |     ...       |
//             |        +---------------+
//             |        |  Undefined0   |
//             |        |  Undefined0   |
//         +--<         +---------------+
//         |   |        |     ArgA      |
//         |   |        +---------------+
//         |   |        |     ...       |
//         |   |        +---------------+
//         |   |        +---------------+
//         |   |        |     Arg0      |
//         |   |        +---------------+
//         |   |        |     ThisV     |
//         |   --       +---------------+
//         |            |  ActualArgC   |
//         |            |  ActualArgC   |
//         |            +---------------+
//         |            |  CalleeToken  |
//         |            +---------------+
//         +------------|  Descr(Rect)  |
//                      +---------------+
//                      +---------------+
//                      |  ReturnAddr   | <-- return into ArgumentsRectifier after call
//                      +===============+
/* clang-format on */
static bool InitFromBailout(JSContext* cx, size_t frameNo, HandleFunction fun,
                            HandleScript script, SnapshotIterator& iter,
                            HandleScript script, SnapshotIterator& iter,
                            bool invalidate, BaselineStackBuilder& builder,
                            MutableHandleValueVector startFrameFormals,
                            MutableHandleFunction nextCallee,
                            const ExceptionBailoutInfo* excInfo) {
  // The Baseline frames we will reconstruct on the heap are not rooted, so GC
  // The Baseline frames we will reconstruct on the heap are not rooted, so GC
  // must be suppressed here.
  MOZ_ASSERT(cx->suppressGC);

  MOZ_ASSERT(script->hasBaselineScript());


  // Are we catching an exception?
  bool catchingException = excInfo && excInfo->catchingException();


  // If we are catching an exception, we are bailing out to a catch or
  // If we are catching an exception, we are bailing out to a catch or
  // finally block and this is the frame where we will resume. Usually the
  // expression stack should be empty in this case but there can be
  // expression stack should be empty in this case but there can be
  // iterators on the stack.
  uint32_t exprStackSlots;
  if (catchingException) {
    exprStackSlots = excInfo->numExprSlots();
  } else {
  } else {
    exprStackSlots =
        iter.numAllocations() - (script->nfixed() + CountArgSlots(script, fun));
  }

  builder.resetFramePushed();
  builder.resetFramePushed();

  // Build first baseline frame:
  // +===============+
  // | PrevFramePtr  |
  // +---------------+
  // +---------------+
  // |   Baseline    |
  // |    Frame      |
  // +---------------+
  // |    Fixed0     |
  // +---------------+
  // +---------------+
  // |     ...       |
  // +---------------+
  // |    FixedF     |
  // +---------------+
  // |    Stack0     |
  // |    Stack0     |
  // +---------------+
  // |     ...       |
  // +---------------+
  // |    StackS     |
  // +---------------+  --- IF NOT LAST INLINE FRAME,
  // |  Descr(BLJS)  |  --- CALLING INFO STARTS HERE
  // +---------------+
  // +---------------+
  // |  ReturnAddr   | <-- return into main jitcode after IC
  // +===============+

  JitSpew(JitSpew_BaselineBailouts, "      Unpacking %s:%u:%u",
  JitSpew(JitSpew_BaselineBailouts, "      Unpacking %s:%u:%u",
          script->filename(), script->lineno(), script->column());
  JitSpew(JitSpew_BaselineBailouts, "      [BASELINE-JS FRAME]");

  // Calculate and write the previous frame pointer value.
  // Record the virtual stack offset at this location.  Later on, if we end up
  // Record the virtual stack offset at this location.  Later on, if we end up
  // writing out a BaselineStub frame for the next callee, we'll need to save
  // the address.
  void* prevFramePtr = builder.calculatePrevFramePtr();
  if (!builder.writePtr(prevFramePtr, "PrevFramePtr")) {
    return false;
    return false;
  }
  prevFramePtr = builder.virtualPointerAtStackOffset(0);

  // Write struct BaselineFrame.
  if (!builder.subtract(BaselineFrame::Size(), "BaselineFrame")) {
  if (!builder.subtract(BaselineFrame::Size(), "BaselineFrame")) {
    return false;
  }
  BufferPointer<BaselineFrame> blFrame =
      builder.pointerAtStackOffset<BaselineFrame>(0);


  uint32_t flags = BaselineFrame::RUNNING_IN_INTERPRETER;

  // If we are bailing to a script whose execution is observed, mark the
  // baseline frame as a debuggee frame. This is to cover the case where we
  // don't rematerialize the Ion frame via the Debugger.
  // don't rematerialize the Ion frame via the Debugger.
  if (script->isDebuggee()) {
    flags |= BaselineFrame::DEBUGGEE;
  }

  // Initialize BaselineFrame's envChain and argsObj
  // Initialize BaselineFrame's envChain and argsObj
  JSObject* envChain = nullptr;
  Value returnValue = UndefinedValue();
  ArgumentsObject* argsObj = nullptr;
  BailoutKind bailoutKind = iter.bailoutKind();
  if (bailoutKind == Bailout_ArgumentCheck) {
  if (bailoutKind == Bailout_ArgumentCheck) {
    // Skip the (unused) envChain, because it could be bogus (we can fail before
    // Skip the (unused) envChain, because it could be bogus (we can fail before
    // the env chain slot is set) and use the function's initial environment.
    // This will be fixed up later if needed in |FinishBailoutToBaseline|, which
    // calls |EnsureHasEnvironmentObjects|.
    JitSpew(JitSpew_BaselineBailouts,
            "      Bailout_ArgumentCheck! (using function's environment)");
            "      Bailout_ArgumentCheck! (using function's environment)");
    iter.skip();
    envChain = fun->environment();

    // skip |return value|
    iter.skip();
    iter.skip();

    // Scripts with |argumentsHasVarBinding| have an extra slot.
    if (script->argumentsHasVarBinding()) {
      JitSpew(
          JitSpew_BaselineBailouts,
          JitSpew_BaselineBailouts,
          "      Bailout_ArgumentCheck for script with argumentsHasVarBinding!"
          "Using empty arguments object");
      iter.skip();
    }
  } else {
  } else {
    Value v = iter.read();
    if (v.isObject()) {
      envChain = &v.toObject();

      // If Ion has updated env slot from UndefinedValue, it will be the
      // If Ion has updated env slot from UndefinedValue, it will be the
      // complete initial environment, so we can set the HAS_INITIAL_ENV
      // flag if needed.
      if (fun && fun->needsFunctionEnvironmentObjects()) {
        MOZ_ASSERT(fun->nonLazyScript()->initialEnvironmentShape());
        MOZ_ASSERT(!fun->needsExtraBodyVarEnvironment());
        MOZ_ASSERT(!fun->needsExtraBodyVarEnvironment());
        flags |= BaselineFrame::HAS_INITIAL_ENV;
      }
    } else {
      MOZ_ASSERT(v.isUndefined() || v.isMagic(JS_OPTIMIZED_OUT));

#ifdef DEBUG
      // The |envChain| slot must not be optimized out if the currently
      // active scope requires any EnvironmentObjects beyond what is
      // available at body scope. This checks that scope chain does not
      // available at body scope. This checks that scope chain does not
      // require any such EnvironmentObjects.
      // See also: |CompileInfo::isObservableFrameSlot|
      jsbytecode* pc = script->offsetToPC(iter.pcOffset());
      Scope* scopeIter = script->innermostScope(pc);
      while (scopeIter != script->bodyScope()) {
      while (scopeIter != script->bodyScope()) {
        MOZ_ASSERT(scopeIter);
        MOZ_ASSERT(!scopeIter->hasEnvironment());
        scopeIter = scopeIter->enclosing();
      }
#endif
#endif

      // Get env chain from function or script.
      if (fun) {
        envChain = fun->environment();
      } else if (script->module()) {
      } else if (script->module()) {
        envChain = script->module()->environment();
      } else {
        // For global scripts without a non-syntactic env the env
        // chain is the script's global lexical environment (Ion does
        // chain is the script's global lexical environment (Ion does
        // not compile scripts with a non-syntactic global scope).
        // Also note that it's invalid to resume into the prologue in
        // this case because the prologue expects the env chain in R1
        // for eval and global scripts.
        MOZ_ASSERT(!script->isForEval());
        MOZ_ASSERT(!script->isForEval());
        MOZ_ASSERT(!script->hasNonSyntacticScope());
        envChain = &(script->global().lexicalEnvironment());
      }
    }


    if (script->noScriptRval()) {
      // Don't use the return value (likely a JS_OPTIMIZED_OUT MagicValue) to
      // not confuse Baseline.
      iter.skip();
    } else {
    } else {
      // Make sure to add HAS_RVAL to |flags| and not blFrame->flags because
      // blFrame->setFlags(flags) below clobbers all frame flags.
      // blFrame->setFlags(flags) below clobbers all frame flags.
      flags |= BaselineFrame::HAS_RVAL;
      returnValue = iter.read();
    }

    // If script maybe has an arguments object, the third slot will hold it.
    // If script maybe has an arguments object, the third slot will hold it.
    if (script->argumentsHasVarBinding()) {
      v = iter.read();
      MOZ_ASSERT(v.isObject() || v.isUndefined() ||
                 v.isMagic(JS_OPTIMIZED_OUT));
                 v.isMagic(JS_OPTIMIZED_OUT));
      if (v.isObject()) {
        argsObj = &v.toObject().as<ArgumentsObject>();
      }
    }
  }
  }

  MOZ_ASSERT(envChain);

  JitSpew(JitSpew_BaselineBailouts, "      EnvChain=%p", envChain);
  blFrame->setEnvironmentChain(envChain);
  blFrame->setEnvironmentChain(envChain);
  JitSpew(JitSpew_BaselineBailouts, "      ReturnValue=%016" PRIx64,
          *((uint64_t*)&returnValue));
  blFrame->setReturnValue(returnValue);

  // Do not need to initialize scratchValue field in BaselineFrame.
  // Do not need to initialize scratchValue field in BaselineFrame.
  blFrame->setFlags(flags);

  // initArgsObjUnchecked modifies the frame's flags, so call it after setFlags.
  if (argsObj) {
    blFrame->initArgsObjUnchecked(*argsObj);
    blFrame->initArgsObjUnchecked(*argsObj);
  }

  if (fun) {
    // The unpacked thisv and arguments should overwrite the pushed args present
    // in the calling frame.
    // in the calling frame.
    Value thisv = iter.read();
    JitSpew(JitSpew_BaselineBailouts, "      Is function!");
    JitSpew(JitSpew_BaselineBailouts, "      thisv=%016" PRIx64,
            *((uint64_t*)&thisv));

    size_t thisvOffset = builder.framePushed() + JitFrameLayout::offsetOfThis();
    builder.valuePointerAtStackOffset(thisvOffset).set(thisv);
    builder.valuePointerAtStackOffset(thisvOffset).set(thisv);

    MOZ_ASSERT(iter.numAllocations() >= CountArgSlots(script, fun));
    JitSpew(JitSpew_BaselineBailouts,
            "      frame slots %u, nargs %zu, nfixed %zu",
            iter.numAllocations(), fun->nargs(), script->nfixed());
            iter.numAllocations(), fun->nargs(), script->nfixed());

    bool argsObjAliasesFormals = script->argsObjAliasesFormals();
    if (frameNo == 0 && !argsObjAliasesFormals) {
      // This is the first (outermost) frame and we don't have an
      // arguments object aliasing the formals. Store the formals in a
      // arguments object aliasing the formals. Store the formals in a
      // Vector until we are done. Due to UCE and phi elimination, we
      // could store an UndefinedValue() here for formals we think are
      // unused, but locals may still reference the original argument slot
      // (MParameter/LArgument) and expect the original Value.
      MOZ_ASSERT(startFrameFormals.empty());
      MOZ_ASSERT(startFrameFormals.empty());
      if (!startFrameFormals.resize(fun->nargs())) {
        return false;
      }
    }


    for (uint32_t i = 0; i < fun->nargs(); i++) {
      Value arg = iter.read();
      JitSpew(JitSpew_BaselineBailouts, "      arg %d = %016" PRIx64, (int)i,
              *((uint64_t*)&arg));
      if (frameNo > 0) {
      if (frameNo > 0) {
        size_t argOffset =
            builder.framePushed() + JitFrameLayout::offsetOfActualArg(i);
        builder.valuePointerAtStackOffset(argOffset).set(arg);
      } else if (argsObjAliasesFormals) {
        // When the arguments object aliases the formal arguments, then
        // JSOp::SetArg mutates the argument object. In such cases, the
        // list of arguments reported by the snapshot are only aliases
        // list of arguments reported by the snapshot are only aliases
        // of argument object slots which are optimized to only store
        // differences compared to arguments which are on the stack.
      } else {
        startFrameFormals[i].set(arg);
      }
      }
    }
  }

  for (uint32_t i = 0; i < script->nfixed(); i++) {
    Value slot = iter.read();
    Value slot = iter.read();
    if (!builder.writeValue(slot, "FixedValue")) {
      return false;
    }
  }


  // Get the pc. If we are handling an exception, resume at the pc of the
  // catch or finally block.
  jsbytecode* const pc = catchingException
                             ? excInfo->resumePC()
                             : script->offsetToPC(iter.pcOffset());
                             : script->offsetToPC(iter.pcOffset());
  const bool resumeAfter = catchingException ? false : iter.resumeAfter();

  // When pgo is enabled, increment the counter of the block in which we
  // resume, as Ion does not keep track of the code coverage.
  //
  //
  // We need to do that when pgo is enabled, as after a specific number of
  // FirstExecution bailouts, we invalidate and recompile the script with
  // IonMonkey. Failing to increment the counter of the current basic block
  // might lead to repeated bailouts and invalidations.
  if (!JitOptions.disablePgo && script->hasScriptCounts()) {
  if (!JitOptions.disablePgo && script->hasScriptCounts()) {
    script->incHitCount(pc);
  }


  const JSOp op = JSOp(*pc);
  const JSOp op = JSOp(*pc);

  // Inlining of SpreadCall-like frames not currently supported.
  MOZ_ASSERT_IF(IsSpreadOp(op), !iter.moreFrames());

  // Fixup inlined JSOp::FunCall, JSOp::FunApply, and accessors on the caller
  // side. On the caller side this must represent like the function wasn't
  // side. On the caller side this must represent like the function wasn't
  // inlined.
  uint32_t pushedSlots = 0;
  RootedValueVector savedCallerArgs(cx);
  bool needToSaveArgs =
      op == JSOp::FunApply || IsIonInlinableGetterOrSetterOp(op);
      op == JSOp::FunApply || IsIonInlinableGetterOrSetterOp(op);
  if (iter.moreFrames() && (op == JSOp::FunCall || needToSaveArgs)) {
    uint32_t inlined_args = 0;
    if (op == JSOp::FunCall) {
      inlined_args = 2 + GET_ARGC(pc) - 1;
    } else if (op == JSOp::FunApply) {
    } else if (op == JSOp::FunApply) {
      inlined_args = 2 + blFrame->numActualArgs();
    } else {
      MOZ_ASSERT(IsIonInlinableGetterOrSetterOp(op));
      inlined_args = 2 + IsSetPropOp(op);
    }
    }

    MOZ_ASSERT(exprStackSlots >= inlined_args);
    pushedSlots = exprStackSlots - inlined_args;

    JitSpew(JitSpew_BaselineBailouts,
    JitSpew(JitSpew_BaselineBailouts,
            "      pushing %u expression stack slots before fixup",
            pushedSlots);
    for (uint32_t i = 0; i < pushedSlots; i++) {
      Value v = iter.read();
      if (!builder.writeValue(v, "StackValue")) {
      if (!builder.writeValue(v, "StackValue")) {
        return false;
      }
    }

    if (op == JSOp::FunCall) {
    if (op == JSOp::FunCall) {
      // When funcall got inlined and the native js_fun_call was bypassed,
      // the stack state is incorrect. To restore correctly it must look like
      // js_fun_call was actually called. This means transforming the stack
      // js_fun_call was actually called. This means transforming the stack
      // from |target, this, args| to |js_fun_call, target, this, args|
      // The js_fun_call is never read, so just pushing undefined now.
      JitSpew(JitSpew_BaselineBailouts,
              "      pushing undefined to fixup funcall");
      if (!builder.writeValue(UndefinedValue(), "StackValue")) {
      if (!builder.writeValue(UndefinedValue(), "StackValue")) {
        return false;
      }
    }

    if (needToSaveArgs) {
    if (needToSaveArgs) {
      // When an accessor is inlined, the whole thing is a lie. There
      // should never have been a call there. Fix the caller's stack to
      // forget it ever happened.

      // When funapply gets inlined we take all arguments out of the
      // When funapply gets inlined we take all arguments out of the
      // arguments array. So the stack state is incorrect. To restore
      // correctly it must look like js_fun_apply was actually called.
      // This means transforming the stack from |target, this, arg1, ...|
      // to |js_fun_apply, target, this, argObject|.
      // to |js_fun_apply, target, this, argObject|.
      // Since the information is never read, we can just push undefined
      // for all values.
      if (op == JSOp::FunApply) {
        JitSpew(JitSpew_BaselineBailouts,
                "      pushing 4x undefined to fixup funapply");
                "      pushing 4x undefined to fixup funapply");
        if (!builder.writeValue(UndefinedValue(), "StackValue")) {
          return false;
        }
        if (!builder.writeValue(UndefinedValue(), "StackValue")) {
          return false;
          return false;
        }
        if (!builder.writeValue(UndefinedValue(), "StackValue")) {
          return false;
        }
        }
        if (!builder.writeValue(UndefinedValue(), "StackValue")) {
          return false;
        }
      }
      // Save the actual arguments. They are needed on the callee side
      // Save the actual arguments. They are needed on the callee side
      // as the arguments. Else we can't recover them.
      if (!savedCallerArgs.resize(inlined_args)) {
        return false;
      }
      for (uint32_t i = 0; i < inlined_args; i++) {
      for (uint32_t i = 0; i < inlined_args; i++) {
        savedCallerArgs[i].set(iter.read());
      }

      if (IsSetPropOp(op)) {
        // We would love to just save all the arguments and leave them
        // We would love to just save all the arguments and leave them
        // in the stub frame pushed below, but we will lose the inital
        // argument which the function was called with, which we must
        // leave on the stack. It's pushed as the result of the SetProp.
        Value initialArg = savedCallerArgs[inlined_args - 1];
        JitSpew(JitSpew_BaselineBailouts,
        JitSpew(JitSpew_BaselineBailouts,
                "     pushing setter's initial argument");
        if (!builder.writeValue(initialArg, "StackValue")) {
          return false;
        }
        }
      }
      pushedSlots = exprStackSlots;
    }
  }


  JitSpew(JitSpew_BaselineBailouts, "      pushing %u expression stack slots",
          exprStackSlots - pushedSlots);
  for (uint32_t i = pushedSlots; i < exprStackSlots; i++) {
    Value v;


    if (!iter.moreFrames() && i == exprStackSlots - 1 &&
        cx->hasIonReturnOverride()) {
        cx->hasIonReturnOverride()) {
      // If coming from an invalidation bailout, and this is the topmost
      // value, and a value override has been specified, don't read from the
      // iterator. Otherwise, we risk using a garbage value.
      MOZ_ASSERT(invalidate);
      iter.skip();
      iter.skip();
      JitSpew(JitSpew_BaselineBailouts, "      [Return Override]");
      v = cx->takeIonReturnOverride();
    } else if (excInfo && excInfo->propagatingIonExceptionForDebugMode()) {
      // If we are in the middle of propagating an exception from Ion by
      // bailing to baseline due to debug mode, we might not have all
      // bailing to baseline due to debug mode, we might not have all
      // the stack if we are at the newest frame.
      //
      // For instance, if calling |f()| pushed an Ion frame which threw,
      // the snapshot expects the return value to be pushed, but it's
      // possible nothing was pushed before we threw. We can't drop
      // possible nothing was pushed before we threw. We can't drop
      // iterators, however, so read them out. They will be closed by
      // HandleExceptionBaseline.
      MOZ_ASSERT(cx->realm()->isDebuggee() || cx->isPropagatingForcedReturn());
      if (iter.moreFrames() ||
          HasLiveStackValueAtDepth(script, pc, i, exprStackSlots)) {
          HasLiveStackValueAtDepth(script, pc, i, exprStackSlots)) {
        v = iter.read();
      } else {
        iter.skip();
        v = MagicValue(JS_OPTIMIZED_OUT);
      }
    } else {
    } else {
      v = iter.read();
    }
    if (!builder.writeValue(v, "StackValue")) {
      return false;
    }
    }
  }

  // BaselineFrame::frameSize is the size of everything pushed since
  // the builder.resetFramePushed() call.
  const uint32_t frameSize = builder.framePushed();
#ifdef DEBUG
#ifdef DEBUG
  blFrame->setDebugFrameSize(frameSize);
#endif
  JitSpew(JitSpew_BaselineBailouts, "      FrameSize=%u", frameSize);

  // debugNumValueSlots() is based on the frame size, do some sanity checks.
  // debugNumValueSlots() is based on the frame size, do some sanity checks.
  MOZ_ASSERT(blFrame->debugNumValueSlots() >= script->nfixed());
  MOZ_ASSERT(blFrame->debugNumValueSlots() <= script->nslots());

  const uint32_t pcOff = script->pcToOffset(pc);
  JitScript* jitScript = script->jitScript();
  JitScript* jitScript = script->jitScript();

#ifdef DEBUG
  uint32_t expectedDepth;
  bool reachablePC;
  if (!ReconstructStackDepth(cx, script, resumeAfter ? GetNextPc(pc) : pc,
                             &expectedDepth, &reachablePC)) {
                             &expectedDepth, &reachablePC)) {
    return false;
  }

  if (reachablePC) {
    if (op != JSOp::FunApply || !iter.moreFrames() || resumeAfter) {
    if (op != JSOp::FunApply || !iter.moreFrames() || resumeAfter) {
      if (op == JSOp::FunCall) {
        // For fun.call(this, ...); the reconstructStackDepth will
        // include the this. When inlining that is not included.
        // So the exprStackSlots will be one less.
        MOZ_ASSERT(expectedDepth - exprStackSlots <= 1);
        MOZ_ASSERT(expectedDepth - exprStackSlots <= 1);
      } else if (iter.moreFrames() && IsIonInlinableGetterOrSetterOp(op)) {
        // Accessors coming out of ion are inlined via a complete
        // lie perpetrated by the compiler internally. Ion just rearranges
        // the stack, and pretends that it looked like a call all along.
        // This means that the depth is actually one *more* than expected
        // This means that the depth is actually one *more* than expected
        // by the interpreter, as there is now a JSFunction, |this| and [arg],
        // rather than the expected |this| and [arg].
        // If the inlined accessor is a getelem operation, the numbers do match,
        // but that's just because getelem expects one more item on the stack.
        // Note that none of that was pushed, but it's still reflected
        // in exprStackSlots.
        // in exprStackSlots.
        MOZ_ASSERT(exprStackSlots - expectedDepth == (IsGetElemOp(op) ? 0 : 1));
      } else {
        // For fun.apply({}, arguments) the reconstructStackDepth will
        // have stackdepth 4, but it could be that we inlined the
        // have stackdepth 4, but it could be that we inlined the
        // funapply. In that case exprStackSlots, will have the real
        // arguments in the slots and not be 4.
        MOZ_ASSERT(exprStackSlots == expectedDepth);
      }
    }
    }
  }
#endif

#ifdef JS_JITSPEW
  JitSpew(JitSpew_BaselineBailouts,
  JitSpew(JitSpew_BaselineBailouts,
          "      Resuming %s pc offset %d (op %s) (line %u) of %s:%u:%u",
          resumeAfter ? "after" : "at", (int)pcOff, CodeName(op),
          PCToLineNumber(script, pc), script->filename(), script->lineno(),
          script->column());
  JitSpew(JitSpew_BaselineBailouts, "      Bailout kind: %s",
  JitSpew(JitSpew_BaselineBailouts, "      Bailout kind: %s",
          BailoutKindString(bailoutKind));
#endif

  const BaselineInterpreter& baselineInterp =
      cx->runtime()->jitRuntime()->baselineInterpreter();
      cx->runtime()->jitRuntime()->baselineInterpreter();

  // If this was the last inline frame, or we are bailing out to a catch or
  // finally block in this frame, then unpacking is almost done.
  if (!iter.moreFrames() || catchingException) {
    builder.setResumeFramePtr(prevFramePtr);
    builder.setResumeFramePtr(prevFramePtr);
    builder.setFrameSizeOfInnerMostFrame(frameSize);

    // Compute the native address (within the Baseline Interpreter) that we will
    // resume at and initialize the frame's interpreter fields.
    uint8_t* resumeAddr;
    uint8_t* resumeAddr;
    if (IsPrologueBailout(iter, excInfo)) {
      JitSpew(JitSpew_BaselineBailouts, "      Resuming into prologue.");
      MOZ_ASSERT(pc == script->code());
      blFrame->setInterpreterFieldsForPrologue(script);
      resumeAddr = baselineInterp.bailoutPrologueEntryAddr();
      resumeAddr = baselineInterp.bailoutPrologueEntryAddr();
    } else if (excInfo && excInfo->propagatingIonExceptionForDebugMode()) {
      // When propagating an exception for debug mode, set the
      // resume pc to the throwing pc, so that Debugger hooks report
      // the correct pc offset of the throwing op instead of its
      // successor.
      // successor.
      jsbytecode* throwPC = script->offsetToPC(iter.pcOffset());
      blFrame->setInterpreterFields(script, throwPC);
      resumeAddr = baselineInterp.interpretOpAddr().value;
    } else {
      // If the opcode is monitored we should monitor the top stack value when
      // If the opcode is monitored we should monitor the top stack value when
      // we finish the bailout in FinishBailoutToBaseline.
      if (resumeAfter && BytecodeOpHasTypeSet(op)) {
        builder.setMonitorPC(pc);
      }
      }
      jsbytecode* resumePC = GetResumePC(script, pc, resumeAfter);
      blFrame->setInterpreterFields(script, resumePC);
      resumeAddr = baselineInterp.interpretOpAddr().value;
    }
    builder.setResumeAddr(resumeAddr);
    builder.setResumeAddr(resumeAddr);
    JitSpew(JitSpew_BaselineBailouts, "      Set resumeAddr=%p", resumeAddr);

    if (cx->runtime()->geckoProfiler().enabled()) {
      // Register bailout with profiler.
      const char* filename = script->filename();
      const char* filename = script->filename();
      if (filename == nullptr) {
        filename = "<unknown>";
      }
      unsigned len = strlen(filename) + 200;
      UniqueChars buf(js_pod_malloc<char>(len));
      if (buf == nullptr) {
      if (buf == nullptr) {
        ReportOutOfMemory(cx);
        return false;
      }
      snprintf(buf.get(), len, "%s %s %s on line %u of %s:%u",
               BailoutKindString(bailoutKind), resumeAfter ? "after" : "at",
               BailoutKindString(bailoutKind), resumeAfter ? "after" : "at",
               CodeName(op), PCToLineNumber(script, pc), filename,
               script->lineno());
      cx->runtime()->geckoProfiler().markEvent(buf.get());
    }


    return true;
  }

  // This is an outer frame for an inlined getter/setter/call.


  blFrame->setInterpreterFields(script, pc);

  // Write out descriptor of BaselineJS frame.
  size_t baselineFrameDescr = MakeFrameDescriptor(
  size_t baselineFrameDescr = MakeFrameDescriptor(
      (uint32_t)builder.framePushed(), FrameType::BaselineJS,
      BaselineStubFrameLayout::Size());
  if (!builder.writeWord(baselineFrameDescr, "Descriptor")) {
    return false;
  }
  }

  // Calculate and write out return address.
  // The icEntry in question MUST have an inlinable fallback stub.
  ICEntry& icEntry = jitScript->icEntryFromPCOffset(pcOff);
  MOZ_ASSERT(IsInlinableFallback(icEntry.fallbackStub()));
  MOZ_ASSERT(IsInlinableFallback(icEntry.fallbackStub()));

  uint8_t* retAddr = baselineInterp.retAddrForIC(JSOp(*pc));
  if (!builder.writePtr(retAddr, "ReturnAddr")) {
  if (!builder.writePtr(retAddr, "ReturnAddr")) {
    return false;
  }

  // Build baseline stub frame:
  // +===============+
  // +===============+
  // |    StubPtr    |
  // +---------------+
  // |   FramePtr    |
  // +---------------+
  // |   Padding?    |
  // |   Padding?    |
  // +---------------+
  // |     ArgA      |
  // +---------------+
  // |     ...       |
  // +---------------+
  // +---------------+
  // |     Arg0      |
  // +---------------+
  // |     ThisV     |
  // +---------------+
  // |  ActualArgC   |
  // +---------------+
  // |  CalleeToken  |
  // |  CalleeToken  |
  // +---------------+
  // | Descr(BLStub) |
  // +---------------+
  // |  ReturnAddr   |
  // +===============+
  // +===============+

  JitSpew(JitSpew_BaselineBailouts, "      [BASELINE-STUB FRAME]");

  size_t startOfBaselineStubFrame = builder.framePushed();


  // Write stub pointer.
  MOZ_ASSERT(IsInlinableFallback(icEntry.fallbackStub()));
  if (!builder.writePtr(icEntry.fallbackStub(), "StubPtr")) {
    return false;
  }

  // Write previous frame pointer (saved earlier).
  if (!builder.writePtr(prevFramePtr, "PrevFramePtr")) {
  if (!builder.writePtr(prevFramePtr, "PrevFramePtr")) {
    return false;
  }
  prevFramePtr = builder.virtualPointerAtStackOffset(0);

  // Write out actual arguments (and thisv), copied from unpacked stack of
  // Write out actual arguments (and thisv), copied from unpacked stack of
  // BaselineJS frame. Arguments are reversed on the BaselineJS frame's stack
  // values.
  MOZ_ASSERT(IsIonInlinableOp(op));
  bool pushedNewTarget = IsConstructPC(pc);
  unsigned actualArgc;
  unsigned actualArgc;
  Value callee;
  if (needToSaveArgs) {
    // For FunApply or an accessor, the arguments are not on the stack anymore,
    // but they are copied in a vector and are written here.
    if (op == JSOp::FunApply) {
    if (op == JSOp::FunApply) {
      actualArgc = blFrame->numActualArgs();
    } else {
      actualArgc = IsSetPropOp(op);
    }
    callee = savedCallerArgs[0];

    // Align the stack based on the number of arguments.
    // Align the stack based on the number of arguments.
    size_t afterFrameSize =
        (actualArgc + 1) * sizeof(Value) + JitFrameLayout::Size();
    if (!builder.maybeWritePadding(JitStackAlignment, afterFrameSize,
                                   "Padding")) {
      return false;
      return false;
    }

    // Push arguments.
    MOZ_ASSERT(actualArgc + 2 <= exprStackSlots);
    MOZ_ASSERT(savedCallerArgs.length() == actualArgc + 2);
    MOZ_ASSERT(savedCallerArgs.length() == actualArgc + 2);
    for (unsigned i = 0; i < actualArgc + 1; i++) {
    for (unsigned i = 0; i < actualArgc + 1; i++) {
      size_t arg = savedCallerArgs.length() - (i + 1);
      if (!builder.writeValue(savedCallerArgs[arg], "ArgVal")) {
        return false;
      }
    }
    }
  } else {
    actualArgc = GET_ARGC(pc);
    if (op == JSOp::FunCall) {
      MOZ_ASSERT(actualArgc > 0);
      actualArgc--;
      actualArgc--;
    }

    // Align the stack based on the number of arguments.
    size_t afterFrameSize = (actualArgc + 1 + pushedNewTarget) * sizeof(Value) +
                            JitFrameLayout::Size();
    if (!builder.maybeWritePadding(JitStackAlignment, afterFrameSize,
                                   "Padding")) {
                                   "Padding")) {
      return false;
    }

    // Copy the arguments and |this| from the BaselineFrame, in reverse order.
    size_t valueSlot = blFrame->numValueSlots(frameSize) - 1;
    size_t valueSlot = blFrame->numValueSlots(frameSize) - 1;
    size_t calleeSlot = valueSlot - actualArgc - 1 - pushedNewTarget;

    for (size_t i = valueSlot; i > calleeSlot; i--) {
      Value v = *blFrame->valueSlot(i);
      if (!builder.writeValue(v, "ArgVal")) {
      if (!builder.writeValue(v, "ArgVal")) {
        return false;
      }
    }

    callee = *blFrame->valueSlot(calleeSlot);
    callee = *blFrame->valueSlot(calleeSlot);
  }

  // In case these arguments need to be copied on the stack again for a
  // rectifier frame, save the framePushed values here for later use.
  size_t endOfBaselineStubArgs = builder.framePushed();

  // Calculate frame size for descriptor.
  // Calculate frame size for descriptor.
  size_t baselineStubFrameSize =
      builder.framePushed() - startOfBaselineStubFrame;
  size_t baselineStubFrameDescr =
      MakeFrameDescriptor((uint32_t)baselineStubFrameSize,
                          FrameType::BaselineStub, JitFrameLayout::Size());

  // Push actual argc
  // Push actual argc
  if (!builder.writeWord(actualArgc, "ActualArgc")) {
    return false;
  }

  // Push callee token (must be a JS Function)
  // Push callee token (must be a JS Function)
  JitSpew(JitSpew_BaselineBailouts, "      Callee = %016" PRIx64,
          callee.asRawBits());

  JSFunction* calleeFun = &callee.toObject().as<JSFunction>();
  if (!builder.writePtr(CalleeToToken(calleeFun, pushedNewTarget),
  if (!builder.writePtr(CalleeToToken(calleeFun, pushedNewTarget),
                        "CalleeToken")) {
    return false;
  }
  nextCallee.set(calleeFun);


  // Push BaselineStub frame descriptor
  if (!builder.writeWord(baselineStubFrameDescr, "Descriptor")) {
    return false;
  }


  // Ensure we have a TypeMonitor fallback stub so we don't crash in JIT code
  // when we try to enter it. See callers of offsetOfFallbackMonitorStub.
  if (BytecodeOpHasTypeSet(JSOp(*pc))) {
    ICFallbackStub* fallbackStub = icEntry.fallbackStub();
    ICFallbackStub* fallbackStub = icEntry.fallbackStub();
    if (!fallbackStub->toMonitoredFallbackStub()->getFallbackMonitorStub(
            cx, script)) {
      return false;
    }
  }
  }

  // Push return address into ICCall_Scripted stub, immediately after the call.
  void* baselineCallReturnAddr = GetStubReturnAddress(cx, op);
  MOZ_ASSERT(baselineCallReturnAddr);
  if (!builder.writePtr(baselineCallReturnAddr, "ReturnAddr")) {
  if (!builder.writePtr(baselineCallReturnAddr, "ReturnAddr")) {
    return false;
  }
  MOZ_ASSERT(builder.framePushed() % JitStackAlignment == 0);

  // If actualArgc >= fun->nargs, then we are done.  Otherwise, we need to push
  // If actualArgc >= fun->nargs, then we are done.  Otherwise, we need to push
  // on a reconstructed rectifier frame.
  if (actualArgc >= calleeFun->nargs()) {
    return true;
  }


  // Push a reconstructed rectifier frame.
  // +===============+
  // |   Padding?    |
  // +---------------+
  // |  UndefinedU   |
  // |  UndefinedU   |
  // +---------------+
  // |     ...       |
  // +---------------+
  // |  Undefined0   |
  // +---------------+
  // +---------------+
  // |     ArgA      |
  // +---------------+
  // |     ...       |
  // |     ...       |
  // +---------------+
  // +---------------+
  // |     Arg0      |
  // +---------------+
  // |     ThisV     |
  // |     ThisV     |
  // +---------------+
  // |  ActualArgC   |
  // +---------------+
  // |  CalleeToken  |
  // +---------------+
  // |  Descr(Rect)  |
  // +---------------+
  // +---------------+
  // |  ReturnAddr   |
  // +===============+

  JitSpew(JitSpew_BaselineBailouts, "      [RECTIFIER FRAME]");


  size_t startOfRectifierFrame = builder.framePushed();

  // On x86-only, the frame pointer is saved again in the rectifier frame.
#if defined(JS_CODEGEN_X86)
  if (!builder.writePtr(prevFramePtr, "PrevFramePtr-X86Only")) {
  if (!builder.writePtr(prevFramePtr, "PrevFramePtr-X86Only")) {
    return false;
  }
  // Follow the same logic as in JitRuntime::generateArgumentsRectifier.
  prevFramePtr = builder.virtualPointerAtStackOffset(0);
  if (!builder.writePtr(prevFramePtr, "Padding-X86Only")) {
  if (!builder.writePtr(prevFramePtr, "Padding-X86Only")) {
    return false;
  }
#endif

  // Align the stack based on the number of arguments.
  // Align the stack based on the number of arguments.
  size_t afterFrameSize =
      (calleeFun->nargs() + 1 + pushedNewTarget) * sizeof(Value) +
      RectifierFrameLayout::Size();
  if (!builder.maybeWritePadding(JitStackAlignment, afterFrameSize,
  if (!builder.maybeWritePadding(JitStackAlignment, afterFrameSize,
                                 "Padding")) {
    return false;
  }

  // Copy new.target, if necessary.
  // Copy new.target, if necessary.
  if (pushedNewTarget) {
    size_t newTargetOffset = (builder.framePushed() - endOfBaselineStubArgs) +
                             (actualArgc + 1) * sizeof(Value);
    Value newTargetValue = *builder.valuePointerAtStackOffset(newTargetOffset);
    if (!builder.writeValue(newTargetValue, "CopiedNewTarget")) {
      return false;
      return false;
    }
  }

  // Push undefined for missing arguments.
  for (unsigned i = 0; i < (calleeFun->nargs() - actualArgc); i++) {
  for (unsigned i = 0; i < (calleeFun->nargs() - actualArgc); i++) {
    if (!builder.writeValue(UndefinedValue(), "FillerVal")) {
      return false;
    }
  }


  // Copy arguments + thisv from BaselineStub frame.
  if (!builder.subtract((actualArgc + 1) * sizeof(Value), "CopiedArgs")) {
    return false;
  }
  BufferPointer<uint8_t> stubArgsEnd = builder.pointerAtStackOffset<uint8_t>(
      builder.framePushed() - endOfBaselineStubArgs);
  JitSpew(JitSpew_BaselineBailouts, "      MemCpy from %p", stubArgsEnd.get());
  JitSpew(JitSpew_BaselineBailouts, "      MemCpy from %p", stubArgsEnd.get());
  memcpy(builder.pointerAtStackOffset<uint8_t>(0).get(), stubArgsEnd.get(),
         (actualArgc + 1) * sizeof(Value));

  // Calculate frame size for descriptor.
  size_t rectifierFrameSize = builder.framePushed() - startOfRectifierFrame;
  size_t rectifierFrameSize = builder.framePushed() - startOfRectifierFrame;
  size_t rectifierFrameDescr =
      MakeFrameDescriptor((uint32_t)rectifierFrameSize, FrameType::Rectifier,
                          JitFrameLayout::Size());

  // Push actualArgc
  // Push actualArgc
  if (!builder.writeWord(actualArgc, "ActualArgc")) {
    return false;
  }


  // Push calleeToken again.
  if (!builder.writePtr(CalleeToToken(calleeFun, pushedNewTarget),
                        "CalleeToken")) {
    return false;
  }
  }

  // Push rectifier frame descriptor
  if (!builder.writeWord(rectifierFrameDescr, "Descriptor")) {
    return false;
    return false;
  }

  // Push return address into the ArgumentsRectifier code, immediately after the
  // ioncode call.
  void* rectReturnAddr =
  void* rectReturnAddr =
      cx->runtime()->jitRuntime()->getArgumentsRectifierReturnAddr().value;
  MOZ_ASSERT(rectReturnAddr);
  if (!builder.writePtr(rectReturnAddr, "ReturnAddr")) {
    return false;
  }
  }
  MOZ_ASSERT(builder.framePushed() % JitStackAlignment == 0);

  return true;
}


bool jit::BailoutIonToBaseline(JSContext* cx, JitActivation* activation,
                               const JSJitFrameIter& iter, bool invalidate,
                               BaselineBailoutInfo** bailoutInfo,
                               const ExceptionBailoutInfo* excInfo) {
  MOZ_ASSERT(bailoutInfo != nullptr);
  MOZ_ASSERT(bailoutInfo != nullptr);
  MOZ_ASSERT(*bailoutInfo == nullptr);
  MOZ_ASSERT(iter.isBailoutJS());

  TraceLoggerThread* logger = TraceLoggerForCurrentThread(cx);
  TraceLogStopEvent(logger, TraceLogger_IonMonkey);
  TraceLogStopEvent(logger, TraceLogger_IonMonkey);
  TraceLogStartEvent(logger, TraceLogger_Baseline);

  // Ion bailout can fail due to overrecursion and OOM. In such cases we
  // cannot honor any further Debugger hooks on the frame, and need to
  // ensure that its Debugger.Frame entry is cleaned up.
  // ensure that its Debugger.Frame entry is cleaned up.
  auto guardRemoveRematerializedFramesFromDebugger =
      mozilla::MakeScopeExit([&] {
        activation->removeRematerializedFramesFromDebugger(cx, iter.fp());
      });


  // Always remove the RInstructionResults from the JitActivation, even in
  // case of failures as the stack frame is going away after the bailout.
  auto removeIonFrameRecovery = mozilla::MakeScopeExit(
      [&] { activation->removeIonFrameRecovery(iter.jsFrame()); });
      [&] { activation->removeIonFrameRecovery(iter.jsFrame()); });

  // The caller of the top frame must be one of the following:
  //      IonJS - Ion calling into Ion.
  //      BaselineStub - Baseline calling into Ion.
  //      Entry / WasmToJSJit - Interpreter or other (wasm) calling into Ion.
  //      Entry / WasmToJSJit - Interpreter or other (wasm) calling into Ion.
  //      Rectifier - Arguments rectifier calling into Ion.
  MOZ_ASSERT(iter.isBailoutJS());
#if defined(DEBUG) || defined(JS_JITSPEW)
  FrameType prevFrameType = iter.prevType();
  MOZ_ASSERT(JSJitFrameIter::isEntry(prevFrameType) ||
  MOZ_ASSERT(JSJitFrameIter::isEntry(prevFrameType) ||
             prevFrameType == FrameType::IonJS ||
             prevFrameType == FrameType::BaselineStub ||
             prevFrameType == FrameType::Rectifier ||
             prevFrameType == FrameType::IonICCall);
#endif
#endif

  // All incoming frames are going to look like this:
  //
  //      +---------------+
  //      |     ...       |
  //      |     ...       |
  //      +---------------+
  //      |     Args      |
  //      |     ...       |
  //      +---------------+
  //      |    ThisV      |
  //      +---------------+
  //      +---------------+
  //      |  ActualArgC   |
  //      +---------------+
  //      |  CalleeToken  |
  //      +---------------+
  //      +---------------+
  //      |  Descriptor   |
  //      +---------------+
  //      |  ReturnAddr   |
  //      +---------------+
  //      |    |||||      | <---- Overwrite starting here.
  //      |    |||||      | <---- Overwrite starting here.
  //      |    |||||      |
  //      |    |||||      |
  //      +---------------+

  JitSpew(JitSpew_BaselineBailouts,
  JitSpew(JitSpew_BaselineBailouts,
          "Bailing to baseline %s:%u:%u (IonScript=%p) (FrameType=%d)",
          iter.script()->filename(), iter.script()->lineno(),
          iter.script()->column(), (void*)iter.ionScript(), (int)prevFrameType);

  bool catchingException;
  bool catchingException;
  bool propagatingExceptionForDebugMode;
  if (excInfo) {
    catchingException = excInfo->catchingException();
    propagatingExceptionForDebugMode =
        excInfo->propagatingIonExceptionForDebugMode();
        excInfo->propagatingIonExceptionForDebugMode();

    if (catchingException) {
      JitSpew(JitSpew_BaselineBailouts, "Resuming in catch or finally block");
    }


    if (propagatingExceptionForDebugMode) {
      JitSpew(JitSpew_BaselineBailouts, "Resuming in-place for debug mode");
    }
  } else {
    catchingException = false;
    catchingException = false;
    propagatingExceptionForDebugMode = false;
  }

  JitSpew(JitSpew_BaselineBailouts,
  JitSpew(JitSpew_BaselineBailouts,
          "  Reading from snapshot offset %u size %zu", iter.snapshotOffset(),
          iter.ionScript()->snapshotsListSize());

  if (!excInfo) {
    iter.ionScript()->incNumBailouts();
    iter.ionScript()->incNumBailouts();
  }
  iter.script()->updateJitCodeRaw(cx->runtime());

  // Allocate buffer to hold stack replacement data.
  BaselineStackBuilder builder(cx, iter, 1024);
  BaselineStackBuilder builder(cx, iter, 1024);
  if (!builder.init()) {
    return false;
  }
  JitSpew(JitSpew_BaselineBailouts, "  Incoming frame ptr = %p",
          builder.startFrame());
          builder.startFrame());

  // Under a bailout, there is no need to invalidate the frame after
  // evaluating the recover instruction, as the invalidation is only needed in
  // cases where the frame is introspected ahead of the bailout.
  MaybeReadFallback recoverBailout(cx, activation, &iter,
  MaybeReadFallback recoverBailout(cx, activation, &iter,
                                   MaybeReadFallback::Fallback_DoNothing);

  // Ensure that all value locations are readable from the SnapshotIterator.
  // Get the RInstructionResults from the JitActivation if the frame got
  // recovered ahead of the bailout.
  // recovered ahead of the bailout.
  SnapshotIterator snapIter(iter, activation->bailoutData()->machineState());
  if (!snapIter.initInstructionResults(recoverBailout)) {
    ReportOutOfMemory(cx);
    return false;
    return false;
  }

#ifdef TRACK_SNAPSHOTS
  snapIter.spewBailingFrom();
#endif
#endif

  RootedFunction callee(cx, iter.maybeCallee());
  RootedFunction callee(cx, iter.maybeCallee());
  RootedScript scr(cx, iter.script());
  if (callee) {
    JitSpew(JitSpew_BaselineBailouts, "  Callee function (%s:%u:%u)",
            scr->filename(), scr->lineno(), scr->column());
  } else {
  } else {
    JitSpew(JitSpew_BaselineBailouts, "  No callee!");
  }

  if (iter.isConstructing()) {
    JitSpew(JitSpew_BaselineBailouts, "  Constructing!");
    JitSpew(JitSpew_BaselineBailouts, "  Constructing!");
  } else {
    JitSpew(JitSpew_BaselineBailouts, "  Not constructing!");
  }

  JitSpew(JitSpew_BaselineBailouts, "  Restoring frames:");
  JitSpew(JitSpew_BaselineBailouts, "  Restoring frames:");
  size_t frameNo = 0;

  // Reconstruct baseline frames using the builder.
  RootedFunction fun(cx, callee);
  RootedValueVector startFrameFormals(cx);
  RootedValueVector startFrameFormals(cx);

  gc::AutoSuppressGC suppress(cx);

  while (true) {
    // Skip recover instructions as they are already recovered by
    // Skip recover instructions as they are already recovered by
    // |initInstructionResults|.
    snapIter.settleOnFrame();

    if (frameNo > 0) {
      // TraceLogger doesn't create entries for inlined frames. But we
      // see them in Baseline. Here we create the start events of those
      // entries. So they correspond to what we will see in Baseline.
      // entries. So they correspond to what we will see in Baseline.
      TraceLoggerEvent scriptEvent(TraceLogger_Scripts, scr);
      TraceLogStartEvent(logger, scriptEvent);
      TraceLogStartEvent(logger, TraceLogger_Baseline);
    }

    JitSpew(JitSpew_BaselineBailouts, "    FrameNo %zu", frameNo);


    // If we are bailing out to a catch or finally block in this frame,
    // pass excInfo to InitFromBailout and don't unpack any other frames.
    bool handleException = (catchingException && excInfo->frameNo() == frameNo);

    // We also need to pass excInfo if we're bailing out in place for
    // We also need to pass excInfo if we're bailing out in place for
    // debug mode.
    bool passExcInfo = handleException || propagatingExceptionForDebugMode;

    RootedFunction nextCallee(cx, nullptr);
    if (!InitFromBailout(cx, frameNo, fun, scr, snapIter, invalidate, builder,
    if (!InitFromBailout(cx, frameNo, fun, scr, snapIter, invalidate, builder,
                         &startFrameFormals, &nextCallee,
                         passExcInfo ? excInfo : nullptr)) {
      MOZ_ASSERT(cx->isExceptionPending());
      return false;
    }
    }

    if (!snapIter.moreFrames()) {
      MOZ_ASSERT(!nextCallee);
      break;
      break;
    }

    if (handleException) {
      break;
    }
    }

    MOZ_ASSERT(nextCallee);
    fun = nextCallee;
    scr = fun->nonLazyScript();


    frameNo++;

    snapIter.nextInstruction();
  }
  JitSpew(JitSpew_BaselineBailouts, "  Done restoring frames");
  JitSpew(JitSpew_BaselineBailouts, "  Done restoring frames");

  BailoutKind bailoutKind = snapIter.bailoutKind();

  if (!startFrameFormals.empty()) {
    // Set the first frame's formals, see the comment in InitFromBailout.
    // Set the first frame's formals, see the comment in InitFromBailout.
    Value* argv = builder.startFrame()->argv() + 1;  // +1 to skip |this|.
    mozilla::PodCopy(argv, startFrameFormals.begin(),
                     startFrameFormals.length());
  }


  // Do stack check.
  bool overRecursed = false;
  BaselineBailoutInfo* info = builder.info();
  uint8_t* newsp =
      info->incomingStack - (info->copyStackTop - info->copyStackBottom);
      info->incomingStack - (info->copyStackTop - info->copyStackBottom);
#ifdef JS_SIMULATOR
  if (Simulator::Current()->overRecursed(uintptr_t(newsp))) {
    overRecursed = true;
  }
#else
  if (!CheckRecursionLimitWithStackPointerDontReport(cx, newsp)) {
    overRecursed = true;
    overRecursed = true;
  }
#endif
  if (overRecursed) {
    JitSpew(JitSpew_BaselineBailouts, "  Overrecursion check failed!");
    ReportOverRecursed(cx);
    ReportOverRecursed(cx);
    return false;
  }

  // Take the reconstructed baseline stack so it doesn't get freed when builder
  // destructs.
  // destructs.
  info = builder.takeBuffer();
  info->numFrames = frameNo + 1;
  info->bailoutKind.emplace(bailoutKind);
  *bailoutInfo = info;
  guardRemoveRematerializedFramesFromDebugger.release();
  guardRemoveRematerializedFramesFromDebugger.release();
  return true;
}

static void InvalidateAfterBailout(JSContext* cx, HandleScript outerScript,
                                   const char* reason) {
  // In some cases, the computation of recover instruction can invalidate the
  // In some cases, the computation of recover instruction can invalidate the
  // Ion script before we reach the end of the bailout. Thus, if the outer
  // script no longer have any Ion script attached, then we just skip the
  // invalidation.
  //
  // For example, such case can happen if the template object for an unboxed
  // For example, such case can happen if the template object for an unboxed
  // objects no longer match the content of its properties (see Bug 1174547)
  if (!outerScript->hasIonScript()) {
    JitSpew(JitSpew_BaselineBailouts, "Ion script is already invalidated");
    return;
    return;
  }

  MOZ_ASSERT(!outerScript->ionScript()->invalidated());

  JitSpew(JitSpew_BaselineBailouts, "Invalidating due to %s", reason);
  JitSpew(JitSpew_BaselineBailouts, "Invalidating due to %s", reason);
  Invalidate(cx, outerScript);
}

static void HandleBoundsCheckFailure(JSContext* cx, HandleScript outerScript,
                                     HandleScript innerScript) {
                                     HandleScript innerScript) {
  JitSpew(JitSpew_IonBailouts,
          "Bounds check failure %s:%u:%u, inlined into %s:%u:%u",
          innerScript->filename(), innerScript->lineno(), innerScript->column(),
          outerScript->filename(), outerScript->lineno(),
          outerScript->column());
          outerScript->column());

  if (!innerScript->failedBoundsCheck()) {
    innerScript->setFailedBoundsCheck();
  }


  InvalidateAfterBailout(cx, outerScript, "bounds check failure");
  if (innerScript->hasIonScript()) {
    Invalidate(cx, innerScript);
  }
}
}

static void HandleShapeGuardFailure(JSContext* cx, HandleScript outerScript,
                                    HandleScript innerScript) {
                                    HandleScript innerScript) {
  JitSpew(JitSpew_IonBailouts,
          "Shape guard failure %s:%u:%u, inlined into %s:%u:%u",
          innerScript->filename(), innerScript->lineno(), innerScript->column(),
          outerScript->filename(), outerScript->lineno(),
          outerScript->column());
          outerScript->column());

  // TODO: Currently this mimic's Ion's handling of this case.  Investigate
  // setting the flag on innerScript as opposed to outerScript, and maybe
  // invalidating both inner and outer scripts, instead of just the outer one.
  outerScript->setFailedShapeGuard();

  InvalidateAfterBailout(cx, outerScript, "shape guard failure");
  InvalidateAfterBailout(cx, outerScript, "shape guard failure");
}

static void HandleBaselineInfoBailout(JSContext* cx, HandleScript outerScript,
                                      HandleScript innerScript) {
  JitSpew(JitSpew_IonBailouts,
  JitSpew(JitSpew_IonBailouts,
          "Baseline info failure %s:%u:%u, inlined into %s:%u:%u",
          innerScript->filename(), innerScript->lineno(), innerScript->column(),
          outerScript->filename(), outerScript->lineno(),
          outerScript->column());


  InvalidateAfterBailout(cx, outerScript, "invalid baseline info");
}

static void HandleLexicalCheckFailure(JSContext* cx, HandleScript outerScript,
                                      HandleScript innerScript) {
                                      HandleScript innerScript) {
  JitSpew(JitSpew_IonBailouts,
          "Lexical check failure %s:%u:%u, inlined into %s:%u:%u",
          innerScript->filename(), innerScript->lineno(), innerScript->column(),
          outerScript->filename(), outerScript->lineno(),
          outerScript->column());
          outerScript->column());

  if (!innerScript->failedLexicalCheck()) {
  if (!innerScript->failedLexicalCheck()) {
    innerScript->setFailedLexicalCheck();
  }

  InvalidateAfterBailout(cx, outerScript, "lexical check failure");
  if (innerScript->hasIonScript()) {
    Invalidate(cx, innerScript);
  }
}


static bool CopyFromRematerializedFrame(JSContext* cx, JitActivation* act,
                                        uint8_t* fp, size_t inlineDepth,
                                        BaselineFrame* frame) {
  RematerializedFrame* rematFrame =
      act->lookupRematerializedFrame(fp, inlineDepth);
      act->lookupRematerializedFrame(fp, inlineDepth);

  // We might not have rematerialized a frame if the user never requested a
  // Debugger.Frame for it.
  if (!rematFrame) {
    return true;
    return true;
  }

  MOZ_ASSERT(rematFrame->script() == frame->script());
  MOZ_ASSERT(rematFrame->numActualArgs() == frame->numActualArgs());


  frame->setEnvironmentChain(rematFrame->environmentChain());

  if (frame->isFunctionFrame()) {
    frame->thisArgument() = rematFrame->thisArgument();
  }
  }

  for (unsigned i = 0; i < frame->numActualArgs(); i++) {
    frame->argv()[i] = rematFrame->argv()[i];
  }


  for (size_t i = 0; i < frame->script()->nfixed(); i++) {
    *frame->valueSlot(i) = rematFrame->locals()[i];
  }

  frame->setReturnValue(rematFrame->returnValue());
  frame->setReturnValue(rematFrame->returnValue());

  // Don't copy over the hasCachedSavedFrame bit. The new BaselineFrame we're
  // Don't copy over the hasCachedSavedFrame bit. The new BaselineFrame we're
  // building has a different AbstractFramePtr, so it won't be found in the
  // LiveSavedFrameCache if we look there.

  JitSpew(JitSpew_BaselineBailouts,
          "  Copied from rematerialized frame at (%p,%zu)", fp, inlineDepth);
          "  Copied from rematerialized frame at (%p,%zu)", fp, inlineDepth);

  // Propagate the debuggee frame flag. For the case where the Debugger did
  // not rematerialize an Ion frame, the baseline frame has its debuggee
  // flag set iff its script is considered a debuggee. See the debuggee case
  // in InitFromBailout.
  if (rematFrame->isDebuggee()) {
    frame->setIsDebuggee();
    frame->setIsDebuggee();
    return DebugAPI::handleIonBailout(cx, rematFrame, frame);
  }

  return true;
}
}

bool jit::FinishBailoutToBaseline(BaselineBailoutInfo* bailoutInfoArg) {
  JitSpew(JitSpew_BaselineBailouts, "  Done restoring frames");

  // Use UniquePtr to free the bailoutInfo before we return.
  // Use UniquePtr to free the bailoutInfo before we return.
  UniquePtr<BaselineBailoutInfo> bailoutInfo(bailoutInfoArg);
  bailoutInfoArg = nullptr;

  JSContext* cx = TlsContext.get();
  BaselineFrame* topFrame = GetTopBaselineFrame(cx);
  BaselineFrame* topFrame = GetTopBaselineFrame(cx);

  // We have to get rid of the rematerialized frame, whether it is
  // restored or unwound.
  uint8_t* incomingStack = bailoutInfo->incomingStack;
  auto guardRemoveRematerializedFramesFromDebugger =
  auto guardRemoveRematerializedFramesFromDebugger =
      mozilla::MakeScopeExit([&] {
        JitActivation* act = cx->activation()->asJit();
        act->removeRematerializedFramesFromDebugger(cx, incomingStack);
      });
      });

  // Ensure the frame has a call object if it needs one.
  // Ensure the frame has a call object if it needs one.
  if (!EnsureHasEnvironmentObjects(cx, topFrame)) {
    return false;
  }


  // Monitor the top stack value if we are resuming after a JOF_TYPESET op.
  if (jsbytecode* monitorPC = bailoutInfo->monitorPC) {
    MOZ_ASSERT(BytecodeOpHasTypeSet(JSOp(*monitorPC)));
    MOZ_ASSERT(GetNextPc(monitorPC) == topFrame->interpreterPC());


    RootedScript script(cx, topFrame->script());
    uint32_t monitorOffset = script->pcToOffset(monitorPC);
    ICEntry& icEntry = script->jitScript()->icEntryFromPCOffset(monitorOffset);
    ICFallbackStub* fallbackStub = icEntry.fallbackStub();


    // Not every monitored op has a monitored fallback stub, e.g.
    // JSOp::NewObject, which always returns the same type for a
    // particular script/pc location.
    if (fallbackStub->isMonitoredFallback()) {
      ICMonitoredFallbackStub* stub = fallbackStub->toMonitoredFallbackStub();
      ICMonitoredFallbackStub* stub = fallbackStub->toMonitoredFallbackStub();
      uint32_t frameSize = bailoutInfo->frameSizeOfInnerMostFrame;
      RootedValue val(cx, topFrame->topStackValue(frameSize));
      if (!TypeMonitorResult(cx, stub, topFrame, script, monitorPC, val)) {
        return false;
      }
      }
    }
  }

  // Create arguments objects for bailed out frames, to maintain the invariant
  // that script->needsArgsObj() implies frame->hasArgsObj().
  // that script->needsArgsObj() implies frame->hasArgsObj().
  RootedScript innerScript(cx, nullptr);
  RootedScript outerScript(cx, nullptr);

  MOZ_ASSERT(cx->currentlyRunningInJit());
  JSJitFrameIter iter(cx->activation()->asJit());
  JSJitFrameIter iter(cx->activation()->asJit());
  uint8_t* outerFp = nullptr;

  // Iter currently points at the exit frame.  Get the previous frame
  // (which must be a baseline frame), and set it as the last profiling
  // frame.
  // frame.
  if (cx->runtime()->jitRuntime()->isProfilerInstrumentationEnabled(
          cx->runtime())) {
    cx->jitActivation->setLastProfilingFrame(iter.prevFp());
  }
  }

  uint32_t numFrames = bailoutInfo->numFrames;
  MOZ_ASSERT(numFrames > 0);

  uint32_t frameno = 0;
  uint32_t frameno = 0;
  while (frameno < numFrames) {
    MOZ_ASSERT(!iter.isIonJS());

    if (iter.isBaselineJS()) {
      BaselineFrame* frame = iter.baselineFrame();
      BaselineFrame* frame = iter.baselineFrame();
      MOZ_ASSERT(frame->script()->hasBaselineScript());

      // If the frame doesn't even have a env chain set yet, then it's resuming
      // into the the prologue before the env chain is initialized.  Any
      // necessary args object will also be initialized there.
      // necessary args object will also be initialized there.
      if (frame->environmentChain() && frame->script()->needsArgsObj()) {
        ArgumentsObject* argsObj;
        if (frame->hasArgsObj()) {
          argsObj = &frame->argsObj();
        } else {
        } else {
          argsObj = ArgumentsObject::createExpected(cx, frame);
          if (!argsObj) {
            return false;
          }
        }
        }

        // The arguments is a local binding and needsArgsObj does not
        // check if it is clobbered. Ensure that the local binding
        // restored during bailout before storing the arguments object
        // to the slot.
        // to the slot.
        RootedScript script(cx, frame->script());
        SetFrameArgumentsObject(cx, frame, script, argsObj);
      }


      if (frameno == 0) {
        innerScript = frame->script();
      }

      if (frameno == numFrames - 1) {
      if (frameno == numFrames - 1) {
        outerScript = frame->script();
        outerFp = iter.fp();
        MOZ_ASSERT(outerFp == incomingStack);
      }


      frameno++;
    }

    ++iter;
  }
  }

  MOZ_ASSERT(innerScript);
  MOZ_ASSERT(outerScript);
  MOZ_ASSERT(outerFp);


  // If we rematerialized Ion frames due to debug mode toggling, copy their
  // values into the baseline frame. We need to do this even when debug mode
  // is off, as we should respect the mutations made while debug mode was
  // on.
  JitActivation* act = cx->activation()->asJit();
  JitActivation* act = cx->activation()->asJit();
  if (act->hasRematerializedFrame(outerFp)) {
    JSJitFrameIter iter(act);
    size_t inlineDepth = numFrames;
    bool ok = true;
    while (inlineDepth > 0) {
    while (inlineDepth > 0) {
      if (iter.isBaselineJS()) {
        // We must attempt to copy all rematerialized frames over,
        // even if earlier ones failed, to invoke the proper frame
        // cleanup in the Debugger.
        if (!CopyFromRematerializedFrame(cx, act, outerFp, --inlineDepth,
                                         iter.baselineFrame())) {
          ok = false;
          ok = false;
        }
      }
      ++iter;
    }


    if (!ok) {
      return false;
    }

    // After copying from all the rematerialized frames, remove them from
    // After copying from all the rematerialized frames, remove them from
    // the table to keep the table up to date.
    guardRemoveRematerializedFramesFromDebugger.release();
    act->removeRematerializedFrame(outerFp);
  }


  // If we are catching an exception, we need to unwind scopes.
  // See |SettleOnTryNote|
  if (cx->isExceptionPending() && bailoutInfo->faultPC) {
    EnvironmentIter ei(cx, topFrame, bailoutInfo->faultPC);
    UnwindEnvironment(cx, ei, bailoutInfo->tryPC);
    UnwindEnvironment(cx, ei, bailoutInfo->tryPC);
  }

  // Check for interrupts now because we might miss an interrupt check in JIT
  // code when resuming in the prologue, after the stack/interrupt check.
  if (!cx->isExceptionPending()) {
  if (!cx->isExceptionPending()) {
    if (!CheckForInterrupt(cx)) {
      return false;
    }
  }

  BailoutKind bailoutKind = *bailoutInfo->bailoutKind;
  JitSpew(JitSpew_BaselineBailouts,
          "  Restored outerScript=(%s:%u:%u,%u) innerScript=(%s:%u:%u,%u) "
          "(bailoutKind=%u)",
          "(bailoutKind=%u)",
          outerScript->filename(), outerScript->lineno(), outerScript->column(),
          outerScript->getWarmUpCount(), innerScript->filename(),
          innerScript->lineno(), innerScript->column(),
          innerScript->getWarmUpCount(), (unsigned)bailoutKind);


  switch (bailoutKind) {
    // Normal bailouts.
    case Bailout_Inevitable:
    case Bailout_DuringVMCall:
    case Bailout_TooManyArguments:
    case Bailout_DynamicNameNotFound:
    case Bailout_StringArgumentsEval:
    case Bailout_StringArgumentsEval:
    case Bailout_Overflow:
    case Bailout_Round:
    case Bailout_NonPrimitiveInput:
    case Bailout_PrecisionLoss:
    case Bailout_TypeBarrierO:
    case Bailout_TypeBarrierO:
    case Bailout_TypeBarrierV:
    case Bailout_ValueGuard:
    case Bailout_NullOrUndefinedGuard:
    case Bailout_MonitorTypes:
    case Bailout_Hole:
    case Bailout_Hole:
    case Bailout_NoDenseElementsGuard:
    case Bailout_NegativeIndex:
    case Bailout_NonInt32Input:
    case Bailout_NonNumericInput:
    case Bailout_NonObjectInput:
    case Bailout_NonBooleanInput:
    case Bailout_NonObjectInput:
    case Bailout_NonStringInput:
    case Bailout_NonSymbolInput:
    case Bailout_NonBigIntInput:
    case Bailout_Debugger:
    case Bailout_Debugger:
    case Bailout_SpecificAtomGuard:
    case Bailout_SpecificSymbolGuard:
      // Do nothing.
      break;

    case Bailout_FirstExecution:
      // Do not return directly, as this was not frequent in the first place,
      // thus rely on the check for frequent bailouts to recompile the current
      // thus rely on the check for frequent bailouts to recompile the current
      // script.
      break;

    // Invalid assumption based on baseline code.
    case Bailout_OverflowInvalidate:
    case Bailout_OverflowInvalidate:
      [[fallthrough]];
      outerScript->setHadOverflowBailout();
      [[fallthrough]];
    case Bailout_DoubleOutput:
    case Bailout_ObjectIdentityOrTypeGuard:
      HandleBaselineInfoBailout(cx, outerScript, innerScript);
      break;


    case Bailout_ArgumentCheck:
      // Do nothing, bailout will resume before the argument monitor ICs.
      break;
    case Bailout_BoundsCheck:
      HandleBoundsCheckFailure(cx, outerScript, innerScript);
      HandleBoundsCheckFailure(cx, outerScript, innerScript);
      break;
    case Bailout_ShapeGuard:
      HandleShapeGuardFailure(cx, outerScript, innerScript);
      break;
    case Bailout_UninitializedLexical:
    case Bailout_UninitializedLexical:
      HandleLexicalCheckFailure(cx, outerScript, innerScript);
      break;
    case Bailout_IonExceptionDebugMode:
      // Return false to resume in HandleException with reconstructed
      // Return false to resume in HandleException with reconstructed
      // baseline frame.
      return false;
    default:
      MOZ_CRASH("Unknown bailout kind!");
  }
  }

  CheckFrequentBailouts(cx, outerScript, bailoutKind);
  return true;
}